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.
- package/CHANGELOG.md +14 -0
- package/README.md +43 -10
- package/dist/mason-audit.js +92 -26
- package/dist/mason-audit.js.map +1 -1
- package/dist/mason-auto.js +2752 -548
- package/dist/mason-auto.js.map +1 -1
- package/dist/mason-drift.js +1 -1
- package/dist/mason-drift.js.map +1 -1
- package/dist/mason-hook.js +1 -1
- package/dist/mason-hook.js.map +1 -1
- package/dist/mason-mcp.js +4355 -3371
- package/dist/mason-mcp.js.map +1 -1
- package/dist/mason-review.js +1 -1
- package/dist/mason-review.js.map +1 -1
- package/package.json +2 -1
package/dist/mason-mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/paths.ts","../src/context/trust.ts","../src/decisions/provenance.ts","../src/utils/files.ts","../src/utils/storage.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/checks/deps-changed.ts","../src/context/lexical.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/impact/impact.ts","../src/context/assemble.ts","../src/automation/evidence.ts","../src/automation/store.ts","../src/automation/runtime.ts","../src/automation/adapters.ts","../src/automation/install.ts","../src/confluence/client.ts","../src/llm/config.ts","../src/confluence/url.ts","../src/confluence/renderer.ts","../src/confluence/diff.ts","../src/llm/providers.ts","../src/confluence/rewrite.ts","../src/confluence/sync.ts","../src/mcp/server.ts","../src/mcp/tools.ts","../src/audit/cli.ts","../src/analyzers/git-history.ts","../src/analyzers/base.ts","../src/analyzers/index.ts","../src/utils/git.ts","../src/mcp/sampler.ts","../src/decisions/review.ts","../src/snapshot/prompt.ts","../src/snapshot/partials.ts","../src/mcp/init.ts","../src/mcp/onboarding.ts","../src/review/review.ts","../src/review/cochange.ts","../src/review/evidence.ts","../src/review/evidence/vitest.ts","../src/review/evidence/paths.ts","../src/review/evidence/types.ts","../src/review/evidence/sarif.ts","../bin/mason-mcp.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","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 { 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)}`);\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 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: 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 { 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\";\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 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 = 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 { 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 path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess, SOURCE_GLOB } from \"../utils/files.js\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\n\nconst exec = promisify(execFile);\n\nexport interface CochangeEntry {\n file: string;\n cochangeRate: number;\n sharedCommits: number;\n}\n\nexport interface ReferenceEntry {\n file: string;\n matches: string[];\n /**\n * \"import\" when the name appears on an import/include/use line — a\n * structural dependency; \"mention\" for any other textual hit (comments,\n * strings, same-name-different-concept collisions). Imports sort first:\n * a mention of \"context\" in a doc comment is not the same signal as\n * `import { Context }`.\n */\n kind: \"import\" | \"mention\";\n}\n\nexport interface TestEntry {\n file: string;\n confidence: \"exact\" | \"best-guess\";\n}\n\nexport interface ImpactResult {\n targetFiles: string[];\n cochange: CochangeEntry[];\n references: ReferenceEntry[];\n tests: TestEntry[];\n}\n\nexport async function analyzeImpact(\n rootDir: string,\n targetFiles: string[]\n): Promise<ImpactResult> {\n const resolvedRoot = path.resolve(rootDir);\n\n // Resolve target files to full relative paths if only basename given\n const resolvedTargets = await resolveTargetFiles(resolvedRoot, targetFiles);\n\n const [cochange, references, tests] = await Promise.all([\n getCochangeFiles(resolvedRoot, resolvedTargets),\n getReferences(resolvedRoot, resolvedTargets),\n getRelatedTests(resolvedRoot, resolvedTargets),\n ]);\n\n return {\n targetFiles: resolvedTargets,\n cochange,\n references,\n tests,\n };\n}\n\nasync function resolveTargetFiles(\n rootDir: string,\n targets: string[]\n): Promise<string[]> {\n const resolved: string[] = [];\n const access = await createFileAccess(rootDir);\n\n for (const target of targets) {\n // If it contains a path separator, use as-is\n if (target.includes(\"/\")) {\n const normalized = normalizeRepoPath(target);\n if (normalized) resolved.push(normalized);\n continue;\n }\n\n // Otherwise, search for the filename\n const matches = await access.list(`**/${target}`);\n\n if (matches.length > 0) {\n resolved.push(matches[0]);\n } else {\n // Try without extension\n const noExt = target.replace(/\\.[^.]+$/, \"\");\n const extMatches = await access.list(`**/${noExt}.*`);\n if (extMatches.length > 0) {\n resolved.push(extMatches[0]);\n } else {\n resolved.push(target); // Keep as-is, might still work for grep\n }\n }\n }\n\n return resolved;\n}\n\nasync function getCochangeFiles(\n rootDir: string,\n targetFiles: string[]\n): Promise<CochangeEntry[]> {\n const cochangeCounts = new Map<string, number>();\n let totalTargetCommits = 0;\n\n for (const targetFile of targetFiles) {\n try {\n // Get commits that touched this file (cap at 500)\n const { stdout: commitLog } = await exec(\n \"git\",\n [\"log\", \"--format=%H\", \"-n\", \"500\", \"--\", targetFile],\n { cwd: rootDir, maxBuffer: 5_000_000 }\n );\n\n const commits = commitLog.trim().split(\"\\n\").filter(Boolean);\n totalTargetCommits += commits.length;\n\n if (commits.length === 0) continue;\n\n // For each commit, get the other files that changed\n for (const commit of commits) {\n try {\n const { stdout: filesInCommit } = await exec(\n \"git\",\n [\"diff-tree\", \"--no-commit-id\", \"--name-only\", \"-r\", commit],\n { cwd: rootDir }\n );\n\n const files = filesInCommit.trim().split(\"\\n\").filter(Boolean);\n for (const file of files) {\n if (targetFiles.includes(file)) continue; // Skip the target itself\n cochangeCounts.set(file, (cochangeCounts.get(file) ?? 0) + 1);\n }\n } catch {\n // Skip this commit\n }\n }\n } catch {\n // No git or file not tracked\n }\n }\n\n if (totalTargetCommits === 0) return [];\n\n // Filter to files that co-change >30% of the time, sort by rate\n return [...cochangeCounts.entries()]\n .map(([file, count]) => ({\n file,\n cochangeRate: Math.round((count / totalTargetCommits) * 100) / 100,\n sharedCommits: count,\n }))\n .filter((e) => e.cochangeRate >= 0.3 || e.sharedCommits >= 3)\n .sort((a, b) => b.cochangeRate - a.cochangeRate)\n .slice(0, 20);\n}\n\nasync function getReferences(\n rootDir: string,\n targetFiles: string[]\n): Promise<ReferenceEntry[]> {\n // Extract searchable names from target files\n const searchNames = new Set<string>();\n for (const target of targetFiles) {\n const basename = path.basename(target).replace(/\\.[^.]+$/, \"\");\n searchNames.add(basename);\n }\n\n const access = await createFileAccess(rootDir);\n const allSourceFiles = await access.list(SOURCE_GLOB);\n\n // Exclude target files from search\n const targetSet = new Set(targetFiles);\n const filesToSearch = allSourceFiles.filter((f) => !targetSet.has(f));\n\n const results = new Map<string, { matches: Set<string>; isImport: boolean }>();\n\n // Language-agnostic import-line heuristic: covers JS/TS import/require,\n // Python import/from, Go/Rust/Swift/Kotlin/Java import/use, C include.\n const importLine = /^\\s*(import\\b|from\\b.*\\bimport\\b|const\\b.*=\\s*require\\(|use\\b|#include\\b|require\\s*\\()/;\n\n // Read files in batches to avoid too many open handles\n const batchSize = 50;\n for (let i = 0; i < filesToSearch.length; i += batchSize) {\n const batch = filesToSearch.slice(i, i + batchSize);\n\n await Promise.all(\n batch.map(async (file) => {\n try {\n const full = await access.read(file);\n if (!full) return;\n const content = full.content;\n const lines = content.split(\"\\n\");\n\n for (const name of searchNames) {\n // Match the name as a word boundary (not part of another word)\n const regex = new RegExp(`\\\\b${escapeRegex(name)}\\\\b`);\n if (!regex.test(content)) continue;\n if (!results.has(file)) {\n results.set(file, { matches: new Set(), isImport: false });\n }\n const entry = results.get(file)!;\n entry.matches.add(name);\n if (\n !entry.isImport &&\n lines.some((l) => regex.test(l) && importLine.test(l))\n ) {\n entry.isImport = true;\n }\n }\n } catch {\n // Skip unreadable files\n }\n })\n );\n }\n\n return [...results.entries()]\n .map(([file, { matches, isImport }]) => ({\n file,\n matches: [...matches],\n kind: (isImport ? \"import\" : \"mention\") as \"import\" | \"mention\",\n }))\n .sort((a, b) => {\n if (a.kind !== b.kind) return a.kind === \"import\" ? -1 : 1;\n return b.matches.length - a.matches.length;\n });\n}\n\nasync function getRelatedTests(\n rootDir: string,\n targetFiles: string[]\n): Promise<TestEntry[]> {\n const testPatterns = [\n \"**/*.test.*\",\n \"**/*.spec.*\",\n \"**/*Test.kt\",\n \"**/*Test.java\",\n \"**/*Tests.kt\",\n \"**/*Tests.java\",\n \"**/test_*.py\",\n \"**/*_test.py\",\n \"**/*_test.go\",\n \"**/*Tests.swift\",\n \"**/*Test.swift\",\n \"**/*_test.rs\",\n ];\n\n const testFiles = await (await createFileAccess(rootDir)).list(testPatterns);\n const results: TestEntry[] = [];\n\n for (const target of targetFiles) {\n const targetBaseName = path\n .basename(target)\n .replace(/\\.[^.]+$/, \"\");\n\n for (const testFile of testFiles) {\n const testBaseName = path\n .basename(testFile)\n .replace(/\\.[^.]+$/, \"\");\n\n // Strip test suffixes to get the source name\n const sourceName = testBaseName\n .replace(/Test$|Tests$|Spec$|\\.test$|\\.spec$/, \"\")\n .replace(/^test_|_test$/, \"\");\n\n if (sourceName === targetBaseName) {\n results.push({\n file: testFile,\n confidence: \"exact\",\n });\n }\n }\n }\n\n return results;\n}\n\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { inspectSnapshot, normalizeFeatureType } from \"../snapshot/snapshot.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport type { FeatureType, Snapshot } from \"../snapshot/snapshot.js\";\nimport { computeDrift, type DriftReport } from \"../drift/drift.js\";\nimport { analyzeImpact } from \"../impact/impact.js\";\nimport type { CochangeEntry, ReferenceEntry } from \"../impact/impact.js\";\nimport { scoreEntry, tokenSet } from \"./lexical.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { decisionKnowledge, effectiveDecision, DECISION_GUIDANCE } from \"../decisions/provenance.js\";\nimport { anchorMatches, sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { assessTrust, trustHint, type TrustState } from \"./trust.js\";\nimport type { StoreDiagnostic } from \"../utils/storage.js\";\nimport type { DecisionDriftReport } from \"../decisions/drift.js\";\nimport type { DecisionCategory, DecisionRecord } from \"../decisions/decisions.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\n\nconst MAX_FEATURES = 5;\nconst MAX_FLOWS = 3;\nconst MAX_IMPACT_TARGETS = 3;\nconst MAX_DECISIONS = 5;\nconst DECISION_FEATURE_OVERLAP_BOOST = 2;\n\nexport interface MatchedFeature {\n description: string;\n files: string[];\n tests?: string[];\n type: FeatureType;\n score: number;\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface MatchedFlow {\n description: string;\n chain: string[];\n score: number;\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface MatchedDecision extends ReturnType<typeof decisionKnowledge> {\n title: string;\n /** Full body — the payload the decisions store exists for. */\n body: string;\n category: DecisionCategory;\n files: string[];\n score: number;\n /** Anchor files changed since this record was last verified. */\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface ContextBundle {\n exists: true;\n map: { status: \"available\" };\n diagnostics?: StoreDiagnostic[];\n task: string;\n features: Record<string, MatchedFeature>;\n flows: Record<string, MatchedFlow>;\n /** Relevant knowledge; approval distinguishes constraints from proposals. */\n decisions: Record<string, MatchedDecision>;\n /** All tests paired with the matched files, deduped. */\n relatedTests: string[];\n impact: {\n targets: string[];\n cochange: CochangeEntry[];\n references: ReferenceEntry[];\n } | null;\n freshness: {\n stale: boolean;\n recommendation: string;\n /** Matched entries whose files changed since they were last verified. */\n staleMatches: string[];\n };\n hint: string;\n}\n\nexport interface NoMatchBundle {\n exists: true;\n map: { status: \"available\" };\n impact?: ContextBundle[\"impact\"];\n relatedTests?: string[];\n diagnostics?: StoreDiagnostic[];\n freshness?: DriftReport | null;\n trust?: { features: Record<string, TrustState>; flows: Record<string, TrustState> };\n task: string;\n features: Record<string, never>;\n flows: Record<string, never>;\n /** Decisions can match even when no feature does. */\n decisions: Record<string, MatchedDecision>;\n /** The full feature catalog, so the caller can still act without a second guess. */\n availableFeatures: Record<string, string>;\n availableFlows: Record<string, string>;\n hint: string;\n}\n\nexport interface UnmappedContextBundle extends Omit<ContextBundle, \"exists\" | \"map\" | \"freshness\"> {\n /** Legacy exists indicates map availability, not decision availability. */\n exists: false;\n map: { status: \"missing\" | \"invalid\" };\n freshness: { stale: null; recommendation: \"no-map\" | \"repair-map\"; staleMatches: string[] };\n}\n\nasync function collectImpact(root: string, candidates: string[]): Promise<{\n impact: ContextBundle[\"impact\"]; relatedTests: string[];\n}> {\n const targets = new Set<string>();\n let sourceFiles: string[] | undefined;\n for (const candidate of sanitizeRepoPaths(candidates)) {\n const stat = await fs.stat(path.join(root, candidate)).catch(() => null);\n if (stat?.isDirectory()) {\n sourceFiles ??= await (await createFileAccess(root)).list();\n for (const file of sourceFiles) {\n if (anchorMatches(candidate, file)) targets.add(file);\n if (targets.size >= MAX_IMPACT_TARGETS) break;\n }\n } else {\n targets.add(candidate);\n }\n if (targets.size >= MAX_IMPACT_TARGETS) break;\n }\n if (!targets.size) return { impact: null, relatedTests: [] };\n const result = await analyzeImpact(root, [...targets]);\n return {\n impact: { targets: result.targetFiles, cochange: result.cochange, references: result.references.slice(0, 10) },\n relatedTests: [...new Set(result.tests.map(t => t.file))],\n };\n}\n\n/**\n * Assemble everything needed to start a task in one call: matching map\n * entries, their files and tests, blast radius for the top files, and\n * per-entry freshness. Deterministic and LLM-free.\n *\n * `files` optionally anchors matching to an explicit file list (e.g. a diff):\n * entries containing those files are boosted above pure lexical matches.\n */\nexport async function assembleContext(\n rootDir: string,\n task: string,\n files?: string[]\n): Promise<ContextBundle | NoMatchBundle | UnmappedContextBundle> {\n const resolvedRoot = path.resolve(rootDir);\n const mapState = await inspectSnapshot(resolvedRoot);\n const snapshot = mapState.snapshot;\n const store = await loadDecisionStore(resolvedRoot);\n const allDecisions = store.records;\n const decisionDrift = await computeDecisionDrift(resolvedRoot, allDecisions);\n const taskTokens = tokenSet(task);\n const anchorFiles = new Set(sanitizeRepoPaths(files ?? []));\n\n const anchorBoost = (entryFiles: string[]): number => {\n let boost = 0;\n for (const f of entryFiles) if ([...anchorFiles].some(file => anchorMatches(f, file))) boost += 5;\n return boost;\n };\n\n if (!snapshot) {\n const decisions = matchDecisions(allDecisions, taskTokens, anchorBoost, new Set(), decisionDrift);\n const { impact, relatedTests } = await collectImpact(resolvedRoot, [...anchorFiles, ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])])]);\n const invalid = mapState.status === \"invalid\";\n return {\n exists: false, map: { status: invalid ? \"invalid\" : \"missing\" }, task,\n features: {}, flows: {}, decisions, impact, relatedTests,\n diagnostics: [...mapState.diagnostics, ...store.diagnostics],\n freshness: { stale: null, recommendation: invalid ? \"repair-map\" : \"no-map\", staleMatches: [] },\n hint: (invalid ? \"The concept map is invalid; consult diagnostics and repair it before relying on map entries. \" : \"No concept map is present. Maps are optional; decisions and file impact work now. \") +\n (Object.keys(decisions).length ? DECISION_GUIDANCE + \" \" + trustHint(Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])])) : \"No saved decision matched. Inspect the source and use save_decision for a learned constraint or incident rationale. \") +\n (store.diagnostics.length ? \" Some decision records are invalid; consult diagnostics before assuming all constraints were retrieved.\" : \"\"),\n };\n }\n\n const drift = await computeDrift(resolvedRoot);\n\n const featureScores = Object.entries(snapshot.features)\n .map(([name, feat]) => ({\n name,\n feat,\n score:\n scoreEntry(taskTokens, { name, description: feat.description, files: feat.files }) +\n anchorBoost([...feat.files, ...(feat.tests ?? [])]),\n }))\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_FEATURES);\n\n const flowScores = Object.entries(snapshot.flows)\n .map(([name, flow]) => ({\n name,\n flow,\n score:\n scoreEntry(taskTokens, { name, description: flow.description, files: flow.chain }) +\n anchorBoost(flow.chain),\n }))\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_FLOWS);\n\n const matchedEntryFiles = new Set<string>([\n ...featureScores.flatMap((e) => e.feat.files),\n ...flowScores.flatMap((e) => e.flow.chain),\n ]);\n const decisions = matchDecisions(\n allDecisions,\n taskTokens,\n anchorBoost,\n matchedEntryFiles,\n decisionDrift\n );\n\n if (featureScores.length === 0 && flowScores.length === 0) {\n const bundle = noMatchBundle(snapshot, task, decisions);\n Object.assign(bundle, await collectImpact(resolvedRoot, [...anchorFiles, ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])])]));\n bundle.diagnostics = store.diagnostics;\n bundle.freshness = drift;\n bundle.trust = {\n features: Object.fromEntries(Object.entries(snapshot.features).map(([name, entry]) =>\n [name, assessTrust(entry, drift?.featureFreshness?.[name] ?? \"unknown\")]\n )),\n flows: Object.fromEntries(Object.entries(snapshot.flows).map(([name, entry]) =>\n [name, assessTrust(entry, drift?.flowFreshness?.[name] ?? \"unknown\")]\n )),\n };\n bundle.hint += \" \" + trustHint([\n ...Object.values(bundle.trust.features),\n ...Object.values(bundle.trust.flows),\n ...Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])]),\n ]);\n if (Object.keys(decisions).length) bundle.hint += \" \" + DECISION_GUIDANCE;\n if (store.diagnostics.length) bundle.hint += \" Some decision records are invalid; consult diagnostics.\";\n return bundle;\n }\n\n const features: Record<string, MatchedFeature> = {};\n const staleMatches: string[] = [];\n for (const { name, feat, score } of featureScores) {\n const trust = assessTrust(feat, drift?.featureFreshness?.[name] ?? \"unknown\");\n const stale = trust.freshness !== \"current\";\n if (stale) staleMatches.push(name);\n features[name] = {\n description: feat.description,\n files: feat.files,\n ...(feat.tests && feat.tests.length > 0 ? { tests: feat.tests } : {}),\n type: normalizeFeatureType(feat.type),\n score,\n stale,\n trust,\n };\n }\n\n const flows: Record<string, MatchedFlow> = {};\n for (const { name, flow, score } of flowScores) {\n const trust = assessTrust(flow, drift?.flowFreshness?.[name] ?? \"unknown\");\n const stale = trust.freshness !== \"current\";\n if (stale) staleMatches.push(name);\n flows[name] = {\n description: flow.description,\n chain: flow.chain,\n score,\n stale,\n trust,\n };\n }\n\n const { impact, relatedTests: impactTests } = await collectImpact(resolvedRoot, [\n ...anchorFiles,\n ...featureScores.flatMap((e) => e.feat.files),\n ...flowScores.flatMap(e => e.flow.chain),\n ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])]),\n ]);\n\n const relatedTests = [\n ...new Set([\n ...featureScores.flatMap((e) => e.feat.tests ?? []),\n ...impactTests,\n ]),\n ];\n\n const stale = drift?.stale ?? false;\n return {\n exists: true,\n map: { status: \"available\" },\n diagnostics: store.diagnostics,\n task,\n features,\n flows,\n decisions,\n relatedTests,\n impact,\n freshness: {\n stale,\n recommendation: drift?.recommendation ?? \"up-to-date\",\n staleMatches,\n },\n hint: (Object.keys(decisions).length ? DECISION_GUIDANCE + \" \" : \"\") + trustHint([...Object.values(features).map(e => e.trust), ...Object.values(flows).map(e => e.trust), ...Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])])]) + (store.diagnostics.length ? \" Some decision records are invalid; consult diagnostics before assuming all constraints were retrieved.\" : \"\"),\n };\n}\n\n/**\n * Score active decisions against the task with the same lexical machinery\n * as map entries, plus a feature-overlap boost: a decision anchored to a\n * file of an already-matched feature is relevant even with zero lexical\n * overlap (\"auth is weird\" should surface on any auth task).\n */\nfunction matchDecisions(\n allDecisions: DecisionRecord[],\n taskTokens: Set<string>,\n anchorBoost: (files: string[]) => number,\n matchedEntryFiles: Set<string>,\n decisionDrift: DecisionDriftReport\n): Record<string, MatchedDecision> {\n const scored = allDecisions\n .filter((d) => d.status === \"active\")\n .map((d) => {\n const scoreRevision = (revision: DecisionRecord) =>\n scoreEntry(taskTokens, { name: revision.title, description: revision.body, files: revision.files }) + anchorBoost(revision.files) +\n (revision.files.some(f => [...matchedEntryFiles].some(file => anchorMatches(f, file))) ? DECISION_FEATURE_OVERLAP_BOOST : 0);\n const score = Math.max(scoreRevision(effectiveDecision(d)), scoreRevision(d));\n return { d, score };\n })\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_DECISIONS);\n\n const result: Record<string, MatchedDecision> = {};\n for (const { d, score } of scored) {\n result[d.id] = {\n ...decisionKnowledge(d, decisionDrift.freshness?.[d.id] ?? \"unknown\", decisionDrift.pendingProposals?.[d.id]?.freshness ?? \"unknown\"),\n score,\n stale: decisionDrift.freshness?.[d.id] !== \"current\",\n };\n }\n return result;\n}\n\nfunction noMatchBundle(\n snapshot: Snapshot,\n task: string,\n decisions: Record<string, MatchedDecision>\n): NoMatchBundle {\n const availableFeatures: Record<string, string> = {};\n for (const [name, feat] of Object.entries(snapshot.features)) {\n availableFeatures[name] = feat.description;\n }\n const availableFlows: Record<string, string> = {};\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n availableFlows[name] = flow.description;\n }\n return {\n exists: true,\n map: { status: \"available\" },\n task,\n features: {},\n flows: {},\n decisions,\n availableFeatures,\n availableFlows,\n hint: \"No map entry matched the task wording. The full catalog is listed — pick the relevant entries and call get_context again with their names in the task, or read their files directly via get_snapshot.\",\n };\n}\n","import fs from \"node:fs/promises\";\nimport 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 { 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 { 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 type { ConfluenceConfig } from \"../llm/config.js\";\n\nexport interface ConfluencePage {\n id: string;\n title: string;\n version: number;\n body: string;\n parentId?: string;\n}\n\nexport interface CreatePageInput {\n spaceId: string;\n title: string;\n body: string;\n parentId?: string;\n}\n\nexport interface UpdatePageInput {\n id: string;\n title: string;\n body: string;\n version: number;\n parentId?: string;\n}\n\nexport interface ConfluenceSpace {\n id: string;\n key: string;\n name: string;\n}\n\nexport interface ConfluenceRootPage {\n id: string;\n title: string;\n}\n\nexport interface ConfluenceClient {\n resolveSpaceId(spaceKey: string): Promise<string>;\n listSpaces(): Promise<ConfluenceSpace[]>;\n listRootPages(spaceId: string): Promise<ConfluenceRootPage[]>;\n findPageByTitle(spaceId: string, title: string): Promise<ConfluencePage | null>;\n createPage(input: CreatePageInput): Promise<ConfluencePage>;\n updatePage(input: UpdatePageInput): Promise<ConfluencePage>;\n}\n\ninterface PageApiResponse {\n id: string;\n title: string;\n parentId?: string;\n version?: { number: number };\n body?: { storage?: { value?: string } };\n}\n\nexport function createConfluenceClient(\n config: ConfluenceConfig,\n fetchFn: typeof fetch = fetch\n): ConfluenceClient {\n const baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n const auth =\n \"Basic \" +\n Buffer.from(`${config.email}:${config.apiToken}`).toString(\"base64\");\n\n async function call(\n method: string,\n path: string,\n body?: unknown\n ): Promise<unknown> {\n const res = await fetchFn(`${baseUrl}${path}`, {\n method,\n headers: {\n Authorization: auth,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new Error(\n `Confluence ${method} ${path} failed: ${res.status} ${res.statusText} — ${text}`\n );\n }\n\n if (res.status === 204) return null;\n return res.json();\n }\n\n function toPage(raw: PageApiResponse): ConfluencePage {\n return {\n id: raw.id,\n title: raw.title,\n version: raw.version?.number ?? 1,\n body: raw.body?.storage?.value ?? \"\",\n parentId: raw.parentId,\n };\n }\n\n return {\n async resolveSpaceId(spaceKey: string): Promise<string> {\n const res = (await call(\n \"GET\",\n `/wiki/api/v2/spaces?keys=${encodeURIComponent(spaceKey)}`\n )) as { results?: Array<{ id: string; key: string }> };\n const space = res.results?.find((s) => s.key === spaceKey);\n if (!space) {\n throw new Error(`Confluence space not found: ${spaceKey}`);\n }\n return space.id;\n },\n\n async listSpaces(): Promise<ConfluenceSpace[]> {\n const all: ConfluenceSpace[] = [];\n let cursor = \"/wiki/api/v2/spaces?limit=100\";\n while (cursor) {\n const res = (await call(\"GET\", cursor)) as {\n results?: Array<{ id: string; key: string; name?: string }>;\n _links?: { next?: string };\n };\n for (const s of res.results ?? []) {\n all.push({ id: s.id, key: s.key, name: s.name ?? s.key });\n }\n const next = res._links?.next;\n if (!next) break;\n // v2 returns relative paths beginning with \"/wiki/...\"\n cursor = next.startsWith(\"/\") ? next : `/${next}`;\n }\n return all;\n },\n\n async listRootPages(spaceId: string): Promise<ConfluenceRootPage[]> {\n const url =\n `/wiki/api/v2/spaces/${encodeURIComponent(spaceId)}/pages` +\n `?depth=root&limit=50`;\n const res = (await call(\"GET\", url)) as {\n results?: Array<{ id: string; title: string }>;\n };\n return (res.results ?? []).map((p) => ({ id: p.id, title: p.title }));\n },\n\n async findPageByTitle(\n spaceId: string,\n title: string\n ): Promise<ConfluencePage | null> {\n const url =\n `/wiki/api/v2/spaces/${encodeURIComponent(spaceId)}/pages` +\n `?title=${encodeURIComponent(title)}&body-format=storage&limit=1`;\n const res = (await call(\"GET\", url)) as {\n results?: PageApiResponse[];\n };\n const match = res.results?.find((p) => p.title === title);\n return match ? toPage(match) : null;\n },\n\n async createPage(input: CreatePageInput): Promise<ConfluencePage> {\n const res = (await call(\"POST\", \"/wiki/api/v2/pages\", {\n spaceId: input.spaceId,\n status: \"current\",\n title: input.title,\n parentId: input.parentId,\n body: {\n representation: \"storage\",\n value: input.body,\n },\n })) as PageApiResponse;\n return toPage(res);\n },\n\n async updatePage(input: UpdatePageInput): Promise<ConfluencePage> {\n const res = (await call(\"PUT\", `/wiki/api/v2/pages/${input.id}`, {\n id: input.id,\n status: \"current\",\n title: input.title,\n parentId: input.parentId,\n body: {\n representation: \"storage\",\n value: input.body,\n },\n version: {\n number: input.version + 1,\n },\n })) as PageApiResponse;\n return toPage(res);\n },\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\nexport type Provider = \"claude\" | \"gemini\" | \"openai\" | \"ollama\";\n\nexport interface ConfluenceConfig {\n baseUrl: string;\n email: string;\n apiToken: string;\n spaceKey: string;\n parentPageId?: string;\n}\n\nexport interface MasonConfig {\n provider: Provider;\n apiKey?: string;\n model?: string;\n ollamaHost?: string;\n confluence?: ConfluenceConfig;\n}\n\nfunction configDir(): string {\n return path.join(os.homedir(), \".mason\");\n}\n\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\nconst DEFAULT_MODELS: Record<Provider, string> = {\n claude: \"claude-sonnet-4-20250514\",\n gemini: \"gemini-2.5-flash\",\n openai: \"gpt-4o\",\n ollama: \"llama3\",\n};\n\nexport async function loadConfig(): Promise<MasonConfig | null> {\n try {\n const raw = await fs.readFile(configFile(), \"utf-8\");\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nexport async function saveConfig(config: MasonConfig): Promise<void> {\n await fs.mkdir(configDir(), { recursive: true });\n await fs.writeFile(configFile(), JSON.stringify(config, null, 2), \"utf-8\");\n}\n\nexport function getDefaultModel(provider: Provider): string {\n return DEFAULT_MODELS[provider];\n}\n\nexport function validateProvider(value: string): Provider {\n const valid: Provider[] = [\"claude\", \"gemini\", \"openai\", \"ollama\"];\n if (!valid.includes(value as Provider)) {\n throw new Error(\n `Invalid provider \"${value}\". Must be one of: ${valid.join(\", \")}`\n );\n }\n return value as Provider;\n}\n\nexport async function detectCLI(\n provider: Provider\n): Promise<{ available: boolean; version?: string }> {\n const cliName = provider === \"claude\" ? \"claude\"\n : provider === \"gemini\" ? \"gemini\"\n : provider === \"ollama\" ? \"ollama\"\n : null;\n\n if (!cliName) return { available: false };\n\n try {\n const { stdout } = await exec(cliName, [\"--version\"]);\n return { available: true, version: stdout.trim() };\n } catch {\n return { available: false };\n }\n}\n\nexport function needsApiKey(provider: Provider): boolean {\n return provider === \"openai\";\n}\n\nexport async function saveConfluenceConfig(\n confluence: ConfluenceConfig\n): Promise<void> {\n const existing = (await loadConfig()) ?? { provider: \"claude\" as Provider };\n await saveConfig({ ...existing, confluence });\n}\n\nexport async function loadConfluenceConfig(): Promise<ConfluenceConfig | null> {\n const config = await loadConfig();\n return config?.confluence ?? null;\n}\n","export function normalizeAtlassianBaseUrl(input: string): string {\n const trimmed = input.trim().replace(/\\/+$/, \"\");\n if (!trimmed) throw new Error(\"Confluence baseUrl is required.\");\n if (/^https?:\\/\\//i.test(trimmed)) return trimmed;\n if (trimmed.includes(\".\")) return `https://${trimmed}`;\n // Bare subdomain — assume Atlassian Cloud\n return `https://${trimmed}.atlassian.net`;\n}\n","import type { FeatureEntry, FlowEntry } from \"../snapshot/snapshot.js\";\n\n// Mason fully owns each page body and overwrites it on every sync. Confluence\n// strips HTML comments and re-serializes storage XHTML, so in-page region\n// markers can't survive a round-trip — no-op detection happens via a content\n// hash in the local sync state instead (see sync.ts / diff.ts).\n\nfunction escape(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction infoPanel(text: string): string {\n return (\n `<ac:structured-macro ac:name=\"info\"><ac:rich-text-body>` +\n `<p>${escape(text)}</p>` +\n `</ac:rich-text-body></ac:structured-macro>`\n );\n}\n\nexport function featurePageTitle(prefix: string, name: string): string {\n return `${prefix}${name}`;\n}\n\nexport interface RenderedFeaturePage {\n body: string;\n title: string;\n}\n\nexport interface RenderFeaturePageOptions {\n name: string;\n productDescription: string;\n flowDescriptions: Array<{ name: string; description: string }>;\n indexPageTitle: string;\n}\n\nexport function renderFeaturePage(\n options: RenderFeaturePageOptions\n): RenderedFeaturePage {\n const overviewBody =\n `<h2>What it does</h2>` + `<p>${escape(options.productDescription)}</p>`;\n\n // Only render \"How it fits in\" when there are flows — an empty section with a\n // \"nothing here\" placeholder reads as unfinished.\n const flowsBody = options.flowDescriptions.length\n ? `<h2>How it fits in</h2><ul>` +\n options.flowDescriptions\n .map(\n (f) =>\n `<li><strong>${escape(f.name)}</strong> — ${escape(f.description)}</li>`\n )\n .join(\"\") +\n `</ul>`\n : \"\";\n\n // Native Confluence page link, resolved by title.\n const navBody =\n `<p><ac:link><ri:page ri:content-title=\"${escape(options.indexPageTitle)}\"/>` +\n `<ac:plain-text-link-body><![CDATA[Back to ${options.indexPageTitle}]]></ac:plain-text-link-body>` +\n `</ac:link></p>`;\n\n // Provenance note as a footer, not wedged between the content sections.\n const footer = infoPanel(\n `Generated from code by Mason. This page is overwritten on each sync — ` +\n `edit the code, not the page.`\n );\n\n const body = overviewBody + flowsBody + navBody + footer;\n\n return {\n title: options.name,\n body,\n };\n}\n\nexport interface RenderIndexPageOptions {\n featureTitles: string[];\n featurePrefix: string;\n}\n\nexport function renderIndexPage(options: RenderIndexPageOptions): string {\n if (options.featureTitles.length === 0) {\n return infoPanel(\"No features in the snapshot yet.\");\n }\n\n const list =\n `<h2>Features</h2><ul>` +\n options.featureTitles\n .map((name) => {\n const pageTitle = featurePageTitle(options.featurePrefix, name);\n return (\n `<li><ac:link><ri:page ri:content-title=\"${escape(pageTitle)}\"/>` +\n `<ac:plain-text-link-body><![CDATA[${name}]]></ac:plain-text-link-body>` +\n `</ac:link></li>`\n );\n })\n .join(\"\") +\n `</ul>`;\n\n const banner = infoPanel(\n `Generated from code by Mason. Maintained automatically — edit the code, not this page.`\n );\n\n return banner + list;\n}\n\nexport interface DiffSection {\n syncedAt: string;\n addedFeatures: string[];\n removedFeatures: string[];\n changedFeatures: string[];\n addedFlows: string[];\n removedFlows: string[];\n}\n\nexport function renderChangelogSection(section: DiffSection): string {\n const segments: string[] = [];\n if (section.addedFeatures.length) {\n segments.push(\n `<p><strong>Added features:</strong> ${section.addedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.removedFeatures.length) {\n segments.push(\n `<p><strong>Removed features:</strong> ${section.removedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.changedFeatures.length) {\n segments.push(\n `<p><strong>Updated features:</strong> ${section.changedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.addedFlows.length) {\n segments.push(\n `<p><strong>Added flows:</strong> ${section.addedFlows.map(escape).join(\", \")}</p>`\n );\n }\n if (section.removedFlows.length) {\n segments.push(\n `<p><strong>Removed flows:</strong> ${section.removedFlows.map(escape).join(\", \")}</p>`\n );\n }\n if (segments.length === 0) {\n segments.push(`<p><em>No meaningful changes detected.</em></p>`);\n }\n\n return (\n `<h3>${escape(section.syncedAt)}</h3>` + segments.join(\"\")\n );\n}\n\nexport function renderChangelogPage(sections: string[]): string {\n if (sections.length === 0) {\n return `<p><em>No sync has run yet.</em></p>`;\n }\n // Newest first\n return sections.join(\"\\n<hr/>\\n\");\n}\n\nexport type FeatureMap = Record<string, FeatureEntry>;\nexport type FlowMap = Record<string, FlowEntry>;\n\nexport function flowsForFeature(\n featureFiles: string[],\n flows: FlowMap\n): Array<{ name: string; description: string }> {\n const fileSet = new Set(featureFiles);\n const result: Array<{ name: string; description: string }> = [];\n for (const [name, flow] of Object.entries(flows)) {\n if (flow.chain.some((file) => fileSet.has(file))) {\n result.push({ name, description: flow.description });\n }\n }\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport type { Snapshot } from \"../snapshot/snapshot.js\";\nimport type { DiffSection } from \"./renderer.js\";\n\nexport interface RewriteCacheEntry {\n /** sha256 of the engineering (source) description this prose was derived from */\n sourceHash: string;\n /** the cached product-language prose */\n product: string;\n /** true when produced by the no-LLM fallback, not the model — re-attempted next run */\n fallback?: boolean;\n}\n\nexport interface RewriteCache {\n features: Record<string, RewriteCacheEntry>;\n flows: Record<string, RewriteCacheEntry>;\n}\n\nexport interface SyncState {\n version: 2;\n syncedAt: string;\n pageIds: {\n index?: string;\n changelog?: string;\n features: Record<string, string>;\n };\n lastSnapshot: {\n features: Record<string, { description: string }>;\n flows: Record<string, { description: string }>;\n };\n changelogSections: string[];\n /** product-language prose cache, keyed by feature/flow name */\n rewriteCache: RewriteCache;\n /**\n * Hash of the body Mason last rendered for each page, keyed by page title.\n * Used to skip re-publishing unchanged pages — we compare our render hash to\n * this, never to Confluence's re-serialized body. Optional for forward\n * compatibility with state written before this field existed.\n */\n pageHashes?: Record<string, string>;\n}\n\n/** Stable content hash of a source description, for cache invalidation. */\nexport function hashDescription(description: string): string {\n return createHash(\"sha256\").update(description, \"utf8\").digest(\"hex\");\n}\n\nfunction syncStateDir(rootDir: string): string {\n return path.join(rootDir, \".mason\");\n}\n\nfunction syncStatePath(rootDir: string): string {\n return path.join(syncStateDir(rootDir), \"confluence-sync.json\");\n}\n\nexport async function loadSyncState(rootDir: string): Promise<SyncState | null> {\n try {\n const raw = await fs.readFile(syncStatePath(rootDir), \"utf-8\");\n const parsed = JSON.parse(raw);\n // Only v2 state is usable. Older state (v1) is treated as absent: the next\n // export re-finds pages by title and rebuilds the rewrite cache from scratch.\n if (parsed.version !== 2) return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nexport async function saveSyncState(\n rootDir: string,\n state: SyncState\n): Promise<void> {\n await fs.mkdir(syncStateDir(rootDir), { recursive: true });\n await fs.writeFile(\n syncStatePath(rootDir),\n JSON.stringify(state, null, 2),\n \"utf-8\"\n );\n}\n\nexport function computeDiff(\n previous: SyncState | null,\n current: Snapshot,\n syncedAt: string\n): DiffSection {\n const prevFeatures = previous?.lastSnapshot.features ?? {};\n const prevFlows = previous?.lastSnapshot.flows ?? {};\n\n const currentFeatureNames = Object.keys(current.features);\n const prevFeatureNames = Object.keys(prevFeatures);\n\n const addedFeatures = currentFeatureNames.filter(\n (n) => !(n in prevFeatures)\n );\n const removedFeatures = prevFeatureNames.filter(\n (n) => !(n in current.features)\n );\n const changedFeatures = currentFeatureNames.filter(\n (n) =>\n n in prevFeatures &&\n prevFeatures[n].description !== current.features[n].description\n );\n\n const currentFlowNames = Object.keys(current.flows);\n const prevFlowNames = Object.keys(prevFlows);\n const addedFlows = currentFlowNames.filter((n) => !(n in prevFlows));\n const removedFlows = prevFlowNames.filter((n) => !(n in current.flows));\n\n return {\n syncedAt,\n addedFeatures,\n removedFeatures,\n changedFeatures,\n addedFlows,\n removedFlows,\n };\n}\n\nexport function isMeaningfulDiff(diff: DiffSection): boolean {\n return (\n diff.addedFeatures.length > 0 ||\n diff.removedFeatures.length > 0 ||\n diff.changedFeatures.length > 0 ||\n diff.addedFlows.length > 0 ||\n diff.removedFlows.length > 0\n );\n}\n\nexport function snapshotMinimal(snapshot: Snapshot): SyncState[\"lastSnapshot\"] {\n const features: Record<string, { description: string }> = {};\n for (const [k, v] of Object.entries(snapshot.features)) {\n features[k] = { description: v.description };\n }\n const flows: Record<string, { description: string }> = {};\n for (const [k, v] of Object.entries(snapshot.flows)) {\n flows[k] = { description: v.description };\n }\n return { features, flows };\n}\n","import { execFile, spawn } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { MasonConfig } from \"./config.js\";\nimport { getDefaultModel } from \"./config.js\";\n\nconst exec = promisify(execFile);\n\nconst CLAUDE_MD_SYSTEM_PROMPT = `You are Mason, a context engineering tool. You've been given a comprehensive analysis of a codebase including:\n- Git history stats (commit patterns, frequently changed files, stale directories)\n- Project structure (directory layout, file counts by type)\n- Curated code samples (key architectural files with previews)\n- Test-to-source file mapping\n\nYour job: write a COMPLETE CLAUDE.md file from scratch based ONLY on the analysis data provided below. Do NOT read any existing files in the project. Do NOT reference or preserve any existing CLAUDE.md. Generate the entire document fresh.\n\nCRITICAL: Output ONLY the raw markdown content. No preamble, no summary, no \"Here's the CLAUDE.md:\", no explanation, no questions, no commentary. Start directly with \"# CLAUDE.md\" and end with the last line of content. Your entire response will be written directly to a file.\n\nThe CLAUDE.md should include:\n- Project overview (what it is, tech stack, architecture)\n- Module/package structure and boundaries\n- Code conventions and patterns you observe in the samples\n- Testing conventions and coverage\n- Build and development commands\n- Important files and hot spots\n- Any warnings or gotchas\n\nBe specific and actionable. Reference actual file paths. Don't be generic — every rule should be grounded in what you see in the data.`;\n\nexport type CallResult =\n | { type: \"response\"; text: string }\n | { type: \"prompt\"; text: string };\n\nexport async function callLLM(\n config: MasonConfig,\n userMessage: string,\n systemPrompt?: string\n): Promise<CallResult> {\n const model = config.model ?? getDefaultModel(config.provider);\n const system = systemPrompt ?? CLAUDE_MD_SYSTEM_PROMPT;\n\n switch (config.provider) {\n case \"claude\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callClaudeAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"response\",\n text: await callClaudeCLI(system, userMessage),\n };\n\n case \"ollama\":\n return {\n type: \"response\",\n text: await callOllamaCLI(\n config.ollamaHost ?? \"http://localhost:11434\",\n model,\n system,\n userMessage,\n ),\n };\n\n case \"gemini\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callGeminiAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"response\",\n text: await callGeminiCLI(system, userMessage),\n };\n\n case \"openai\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callOpenAIAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"prompt\",\n text: formatPromptForCopy(system, userMessage),\n };\n }\n}\n\nfunction formatPromptForCopy(system: string, userMessage: string): string {\n return `${system}\\n\\n---\\n\\n${userMessage}`;\n}\n\n// === CLI-based providers (no API key) ===\n\nasync function callViaTempFile(\n command: string,\n args: (promptPath: string) => string[],\n system: string,\n userMessage: string\n): Promise<string> {\n const fs = await import(\"node:fs/promises\");\n const os = await import(\"node:os\");\n const path = await import(\"node:path\");\n\n const prompt = `${system}\\n\\n${userMessage}`;\n const tmpFile = path.join(os.tmpdir(), `mason-prompt-${Date.now()}.txt`);\n\n try {\n await fs.writeFile(tmpFile, prompt, \"utf-8\");\n const { stdout } = await exec(command, args(tmpFile), {\n maxBuffer: 10_000_000,\n timeout: 300_000,\n });\n return stdout.trim();\n } finally {\n await fs.unlink(tmpFile).catch(() => {});\n }\n}\n\nfunction spawnWithStdin(\n command: string,\n args: string[],\n input: string\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n timeout: 300_000,\n });\n\n // ora puts stdin into raw mode, which means Ctrl+C is emitted as\n // process.emit(\"SIGINT\") rather than a real signal to the process\n // group. Forward it to the child so it can terminate.\n const onSigint = () => proc.kill(\"SIGINT\");\n process.on(\"SIGINT\", onSigint);\n\n let stdout = \"\";\n let stderr = \"\";\n\n proc.stdout.on(\"data\", (data: Buffer) => {\n stdout += data.toString();\n });\n proc.stderr.on(\"data\", (data: Buffer) => {\n stderr += data.toString();\n });\n\n proc.on(\"close\", (code: number | null) => {\n process.off(\"SIGINT\", onSigint);\n if (code === 0) {\n resolve(stdout.trim());\n } else {\n reject(new Error(`${command} exited with code ${code}: ${stderr}`));\n }\n });\n\n proc.on(\"error\", (err) => {\n process.off(\"SIGINT\", onSigint);\n reject(err);\n });\n\n proc.stdin.write(input);\n proc.stdin.end();\n });\n}\n\nasync function callClaudeCLI(\n system: string,\n userMessage: string\n): Promise<string> {\n return spawnWithStdin(\"claude\", [\"-p\", \"--system-prompt\", system], userMessage);\n}\n\nasync function callGeminiCLI(\n system: string,\n userMessage: string\n): Promise<string> {\n const prompt = `<system>\\n${system}\\n</system>\\n\\n${userMessage}`;\n return spawnWithStdin(\"gemini\", [\"-p\", \"\"], prompt);\n}\n\nasync function callOllamaCLI(\n host: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const response = await fetch(`${host}/api/chat`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model,\n stream: false,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n }),\n });\n\n const result = (await response.json()) as {\n message?: { content?: string };\n };\n return result.message?.content ?? \"\";\n}\n\n// === API-based providers ===\n\nasync function callClaudeAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: Anthropic } = await import(\"@anthropic-ai/sdk\");\n const client = new Anthropic({ apiKey });\n\n const response = await client.messages.create({\n model,\n max_tokens: 8192,\n system,\n messages: [{ role: \"user\", content: userMessage }],\n });\n\n const textBlock = response.content.find((b) => b.type === \"text\");\n return textBlock?.text ?? \"\";\n}\n\nasync function callGeminiAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: OpenAI } = await import(\"openai\");\n const client = new OpenAI({\n apiKey,\n baseURL: \"https://generativelanguage.googleapis.com/v1beta/openai/\",\n });\n\n const response = await client.chat.completions.create({\n model,\n max_tokens: 8192,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n });\n\n return response.choices[0]?.message?.content ?? \"\";\n}\n\nasync function callOpenAIAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: OpenAI } = await import(\"openai\");\n const client = new OpenAI({ apiKey });\n\n const response = await client.chat.completions.create({\n model,\n max_tokens: 8192,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n });\n\n return response.choices[0]?.message?.content ?? \"\";\n}\n","import { callLLM } from \"../llm/providers.js\";\nimport type { MasonConfig } from \"../llm/config.js\";\nimport type {\n FeatureEntry,\n FlowEntry,\n Snapshot,\n} from \"../snapshot/snapshot.js\";\nimport {\n hashDescription,\n type RewriteCache,\n type RewriteCacheEntry,\n} from \"./diff.js\";\n\nconst PM_REWRITE_SYSTEM_PROMPT = `You are Mason, rewriting an engineering-flavoured concept map into product-readable language for a company wiki.\n\nYou will receive a JSON object with two maps:\n- \"features\": each entry has a description and a list of source file paths.\n- \"flows\": each entry has a description and an ordered chain of file paths.\n\nYour job: rewrite EACH description so a Product Manager, designer, or non-engineering stakeholder can understand what the system does — without seeing any code. Treat the file paths as hints, not content. Do NOT include them in your output.\n\nHard rules:\n- NEVER mention file names, directory names, file extensions, class names, function names, repository names, framework names, or libraries.\n- NEVER use words like \"module\", \"service\", \"handler\", \"controller\", \"ViewModel\", \"repository\", \"endpoint\", \"API\", \"schema\", \"interface\", \"class\".\n- Use plain English. Focus on what users or the business can do, what data moves, what decisions get made, and why it matters.\n- 1–3 sentences per description. Concrete. No filler.\n- Preserve the original keys exactly; only the description values change.\n\nOutput ONLY raw JSON with the same shape as the input — same keys, rewritten descriptions. No markdown, no code fences, no preamble.`;\n\ntype Rewritten = {\n features: Record<string, string>;\n flows: Record<string, string>;\n};\n\ninterface RewriteInput {\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n}\n\nfunction buildPrompt(input: RewriteInput): string {\n return `Rewrite the descriptions below for a product audience. Return ONLY a JSON object of the form {\"features\": {\"name\": \"rewritten description\", ...}, \"flows\": {...}}.\\n\\n${JSON.stringify(input, null, 2)}`;\n}\n\nfunction parseRewriteResponse(raw: string): Rewritten {\n let cleaned = raw.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n try {\n const parsed = JSON.parse(cleaned);\n return {\n features: parsed.features ?? {},\n flows: parsed.flows ?? {},\n };\n } catch {\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (match) {\n try {\n const parsed = JSON.parse(match[0]);\n return {\n features: parsed.features ?? {},\n flows: parsed.flows ?? {},\n };\n } catch {\n return { features: {}, flows: {} };\n }\n }\n return { features: {}, flows: {} };\n }\n}\n\nexport interface RewriteResult {\n features: Record<string, string>;\n flows: Record<string, string>;\n /** Updated prose cache to persist into the sync state. */\n cache: RewriteCache;\n}\n\nexport interface RewriteContext {\n /** Prose cache from the previous sync; used to skip unchanged entries. */\n previousCache?: RewriteCache;\n /** LLM caller; injectable for tests. Defaults to the configured provider. */\n llm?: typeof callLLM;\n}\n\n/** Pick a subset of a record by key. */\nfunction pick<T>(source: Record<string, T>, keys: string[]): Record<string, T> {\n const out: Record<string, T> = {};\n for (const k of keys) out[k] = source[k];\n return out;\n}\n\n/**\n * Rewrite engineering descriptions into product-readable prose, incrementally.\n *\n * Entries whose source description is unchanged since the last sync (matched by\n * content hash) reuse their cached prose verbatim — no LLM call. Only new or\n * changed entries are sent to the model, batched into a single request. When\n * nothing changed, the LLM is not invoked at all.\n */\nexport async function rewriteForProduct(\n snapshot: Snapshot,\n config: MasonConfig,\n ctx: RewriteContext = {}\n): Promise<RewriteResult> {\n const featureHashes = hashEntries(snapshot.features);\n const flowHashes = hashEntries(snapshot.flows);\n\n const missFeatures = missingNames(\n snapshot.features,\n featureHashes,\n ctx.previousCache?.features\n );\n const missFlows = missingNames(\n snapshot.flows,\n flowHashes,\n ctx.previousCache?.flows\n );\n\n let parsed: Rewritten = { features: {}, flows: {} };\n if (missFeatures.length > 0 || missFlows.length > 0) {\n const input: RewriteInput = {\n features: pick(snapshot.features, missFeatures),\n flows: pick(snapshot.flows, missFlows),\n };\n const prompt = buildPrompt(input);\n const llm = ctx.llm ?? callLLM;\n const result = await llm(config, prompt, PM_REWRITE_SYSTEM_PROMPT);\n const text =\n typeof result === \"string\"\n ? result\n : result.type === \"response\"\n ? result.text\n : \"\";\n // Empty text means no API/CLI is available — leave `parsed` empty so every\n // miss falls back to its engineering description (cached as fallback).\n if (text) parsed = parseRewriteResponse(text);\n }\n\n const features = resolve(\n snapshot.features,\n featureHashes,\n parsed.features,\n ctx.previousCache?.features\n );\n const flows = resolve(\n snapshot.flows,\n flowHashes,\n parsed.flows,\n ctx.previousCache?.flows\n );\n\n return {\n features: features.descriptions,\n flows: flows.descriptions,\n cache: { features: features.cache, flows: flows.cache },\n };\n}\n\nfunction hashEntries(\n entries: Record<string, { description: string }>\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, entry] of Object.entries(entries)) {\n out[name] = hashDescription(entry.description);\n }\n return out;\n}\n\n/** A cache entry is a hit only if the source hash matches and it isn't a fallback. */\nfunction isHit(\n prev: RewriteCacheEntry | undefined,\n hash: string\n): prev is RewriteCacheEntry {\n return !!prev && prev.sourceHash === hash && !prev.fallback;\n}\n\nfunction missingNames(\n entries: Record<string, { description: string }>,\n hashes: Record<string, string>,\n prevCache: Record<string, RewriteCacheEntry> | undefined\n): string[] {\n return Object.keys(entries).filter(\n (name) => !isHit(prevCache?.[name], hashes[name])\n );\n}\n\n/**\n * Build the final prose map + next cache for one collection (features or flows):\n * reuse cached prose on a hit, take fresh model prose on a miss, or fall back to\n * the engineering description (marked `fallback`) when the model omitted it.\n */\nfunction resolve(\n entries: Record<string, { description: string }>,\n hashes: Record<string, string>,\n rewritten: Record<string, string>,\n prevCache: Record<string, RewriteCacheEntry> | undefined\n): { descriptions: Record<string, string>; cache: Record<string, RewriteCacheEntry> } {\n const descriptions: Record<string, string> = {};\n const cache: Record<string, RewriteCacheEntry> = {};\n\n for (const [name, entry] of Object.entries(entries)) {\n const hash = hashes[name];\n const prev = prevCache?.[name];\n\n if (isHit(prev, hash)) {\n descriptions[name] = prev.product;\n cache[name] = { sourceHash: hash, product: prev.product };\n continue;\n }\n\n const fresh = rewritten[name];\n if (typeof fresh === \"string\" && fresh.trim().length > 0) {\n descriptions[name] = fresh;\n cache[name] = { sourceHash: hash, product: fresh };\n } else {\n // No usable model output — keep the engineering description and mark it a\n // fallback so a later successful run re-attempts it.\n descriptions[name] = entry.description;\n cache[name] = { sourceHash: hash, product: entry.description, fallback: true };\n }\n }\n\n return { descriptions, cache };\n}\n","import { loadSnapshot } from \"../snapshot/snapshot.js\";\nimport type { MasonConfig, ConfluenceConfig } from \"../llm/config.js\";\nimport { createConfluenceClient, type ConfluenceClient } from \"./client.js\";\nimport {\n renderFeaturePage,\n renderIndexPage,\n renderChangelogPage,\n renderChangelogSection,\n flowsForFeature,\n featurePageTitle,\n} from \"./renderer.js\";\nimport {\n computeDiff,\n isMeaningfulDiff,\n loadSyncState,\n saveSyncState,\n snapshotMinimal,\n hashDescription,\n type SyncState,\n} from \"./diff.js\";\nimport {\n rewriteForProduct,\n type RewriteResult,\n type RewriteContext,\n} from \"./rewrite.js\";\nimport type { FeatureEntry, Snapshot } from \"../snapshot/snapshot.js\";\n\nexport interface SyncOptions {\n indexPageTitle?: string;\n changelogPageTitle?: string;\n featurePagePrefix?: string;\n}\n\nexport interface SyncSummary {\n created: string[];\n updated: string[];\n unchanged: string[];\n indexPageId: string;\n changelogPageId: string;\n hadChanges: boolean;\n}\n\nexport interface SyncDeps {\n client: ConfluenceClient;\n rewrite: (\n snapshot: Snapshot,\n config: MasonConfig,\n ctx: RewriteContext\n ) => Promise<RewriteResult>;\n}\n\nconst DEFAULT_INDEX_TITLE = \"Mason — System Map\";\nconst DEFAULT_CHANGELOG_TITLE = \"Mason — Changelog\";\nconst DEFAULT_FEATURE_PREFIX = \"Feature: \";\n\nexport async function exportToConfluence(\n rootDir: string,\n config: MasonConfig,\n options: SyncOptions = {},\n deps?: Partial<SyncDeps>\n): Promise<SyncSummary> {\n const confluence = config.confluence;\n if (!confluence) {\n throw new Error(\n \"No Confluence credentials configured. Ask your assistant to call mason_set_confluence first.\"\n );\n }\n\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n throw new Error(\n \"No snapshot found. Build the concept map first (ask your assistant to run mason_init and follow the playbook).\"\n );\n }\n\n const client = deps?.client ?? createConfluenceClient(confluence);\n const rewrite = deps?.rewrite ?? rewriteForProduct;\n\n // Only user-facing capabilities are published to the wiki. Infrastructure\n // features (DI wiring, config, logging, provider plumbing) stay in the AI\n // concept map but never become PM-facing pages. Filter once here; everything\n // downstream — rewrite, index, feature pages, changelog diff, persisted\n // state — operates on this published subset. Missing type defaults to\n // \"capability\" (see normalizeFeatureType), so older snapshots publish as before.\n const publishedFeatures: Record<string, FeatureEntry> = {};\n for (const [name, entry] of Object.entries(snapshot.features)) {\n if (entry.type !== \"infrastructure\") publishedFeatures[name] = entry;\n }\n const publishSnapshot: Snapshot = { ...snapshot, features: publishedFeatures };\n\n const indexTitle = options.indexPageTitle ?? DEFAULT_INDEX_TITLE;\n const changelogTitle = options.changelogPageTitle ?? DEFAULT_CHANGELOG_TITLE;\n const featurePrefix = options.featurePagePrefix ?? DEFAULT_FEATURE_PREFIX;\n\n const spaceId = await client.resolveSpaceId(confluence.spaceKey);\n // Wall-clock time is used ONLY for the append-only changelog heading. Page\n // bodies carry no timestamp/hash, so a page is re-published only when its own\n // content (description/flows) changes — not on every unrelated commit.\n const syncedAt = new Date().toISOString();\n const previousState = await loadSyncState(rootDir);\n const previousHashes = previousState?.pageHashes ?? {};\n const nextHashes: Record<string, string> = {};\n\n const productLanguage = await rewrite(publishSnapshot, config, {\n previousCache: previousState?.rewriteCache,\n });\n\n // 1. Upsert index page (so feature pages can hang under it)\n const indexBody = renderIndexPage({\n featureTitles: Object.keys(publishSnapshot.features),\n featurePrefix,\n });\n\n const indexPage = await upsertPage({\n client,\n spaceId,\n title: indexTitle,\n parentId: confluence.parentPageId,\n renderedBody: indexBody,\n previousHash: previousHashes[indexTitle],\n });\n nextHashes[indexTitle] = indexPage.hash;\n\n // 2. Upsert each feature page under the index\n const created: string[] = [];\n const updated: string[] = [];\n const unchanged: string[] = [];\n const featurePageIds: Record<string, string> = {};\n\n for (const [name, entry] of Object.entries(publishSnapshot.features)) {\n const title = featurePageTitle(featurePrefix, name);\n const productDescription =\n productLanguage.features[name] ?? entry.description;\n const relatedFlows = flowsForFeature(entry.files, publishSnapshot.flows).map(\n (f) => ({\n name: f.name,\n description: productLanguage.flows[f.name] ?? f.description,\n })\n );\n\n const rendered = renderFeaturePage({\n name,\n productDescription,\n flowDescriptions: relatedFlows,\n indexPageTitle: indexTitle,\n });\n\n const result = await upsertPage({\n client,\n spaceId,\n title,\n parentId: indexPage.id,\n renderedBody: rendered.body,\n previousHash: previousHashes[title],\n });\n nextHashes[title] = result.hash;\n\n featurePageIds[name] = result.id;\n if (result.outcome === \"created\") created.push(title);\n else if (result.outcome === \"updated\") updated.push(title);\n else unchanged.push(title);\n }\n\n // 3. Diff + changelog page\n const diff = computeDiff(previousState, publishSnapshot, syncedAt);\n const hadChanges = previousState === null || isMeaningfulDiff(diff);\n\n const previousSections = previousState?.changelogSections ?? [];\n let newSections = previousSections;\n if (hadChanges) {\n const section = renderChangelogSection(diff);\n newSections = [section, ...previousSections].slice(0, 50);\n }\n\n const changelogBody = renderChangelogPage(newSections);\n const changelogPage = await upsertPage({\n client,\n spaceId,\n title: changelogTitle,\n parentId: indexPage.id,\n renderedBody: changelogBody,\n previousHash: previousHashes[changelogTitle],\n });\n nextHashes[changelogTitle] = changelogPage.hash;\n\n // 4. Persist sync state\n const nextState: SyncState = {\n version: 2,\n syncedAt,\n pageIds: {\n index: indexPage.id,\n changelog: changelogPage.id,\n features: featurePageIds,\n },\n lastSnapshot: snapshotMinimal(publishSnapshot),\n changelogSections: newSections,\n rewriteCache: productLanguage.cache,\n pageHashes: nextHashes,\n };\n await saveSyncState(rootDir, nextState);\n\n return {\n created,\n updated,\n unchanged,\n indexPageId: indexPage.id,\n changelogPageId: changelogPage.id,\n hadChanges,\n };\n}\n\ninterface UpsertArgs {\n client: ConfluenceClient;\n spaceId: string;\n title: string;\n parentId?: string;\n renderedBody: string;\n /** Hash of the body we published for this page last sync, if any. */\n previousHash?: string;\n}\n\ninterface UpsertResult {\n id: string;\n outcome: \"created\" | \"updated\" | \"unchanged\";\n /** Hash of the body published this sync — persist for next-run comparison. */\n hash: string;\n}\n\nasync function upsertPage(args: UpsertArgs): Promise<UpsertResult> {\n const hash = hashDescription(args.renderedBody);\n const existing = await args.client.findPageByTitle(args.spaceId, args.title);\n\n if (!existing) {\n const page = await args.client.createPage({\n spaceId: args.spaceId,\n title: args.title,\n parentId: args.parentId,\n body: args.renderedBody,\n });\n return { id: page.id, outcome: \"created\", hash };\n }\n\n // Confluence re-serializes stored bodies (strips comments, re-encodes\n // entities, injects macro ids), so we can't compare against existing.body.\n // Compare our render hash to the hash we stored last sync instead. When it\n // matches, the page is already current — skip the write entirely.\n if (args.previousHash === hash) {\n return { id: existing.id, outcome: \"unchanged\", hash };\n }\n\n // Mason owns the whole page body: overwrite it wholesale.\n const updated = await args.client.updatePage({\n id: existing.id,\n title: args.title,\n parentId: args.parentId,\n body: args.renderedBody,\n version: existing.version,\n });\n return { id: updated.id, outcome: \"updated\", hash };\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { attributionSchema } from \"../decisions/provenance.js\";\nimport {\n analyzeProject,\n checkDrift,\n exportToConfluenceTool,\n fullAnalysis,\n generateSnapshotBatch,\n getCodeSamples,\n getContext,\n getImpact,\n getSnapshot,\n saveDecision,\n reviewDecision,\n saveVerification,\n verifySnapshot,\n masonCompleteInit,\n masonInit,\n masonRepair,\n masonAutomation,\n masonSetConfluence,\n reduceSnapshot,\n saveSnapshotData,\n saveSnapshotPartial,\n} from \"./tools.js\";\n\ndeclare const PKG_VERSION: string;\n\nexport function createMcpServer(): McpServer {\n const server = new McpServer(\n {\n name: \"mason\",\n version: PKG_VERSION,\n },\n {\n instructions:\n \"Mason retrieves recorded decisions, file impact, and optional feature/flow maps. Use get_context with the task and known files, and get_impact before editing. Save learned rationale and constraints with save_decision; review and commit the local records through the project workflow. These tools work without initialization or a concept map. Consult trust and diagnostics: changed or unknown freshness needs source inspection, failed verification needs correction, and proposals are suggestions and legacy records are unreviewed. Accepted decisions are recorded team constraints, still subject to freshness checks. Use review_decision to prepare code evidence and record only authorized acceptance, reaffirmation, or retirement. Never invent a reviewer or treat these recorded identities as authenticated approval. mason_init returns documentation audit and committed-diff review findings with a quickstart guide. Use mode: \\\"map\\\" only when a full architecture map is requested. A missing map is not a setup failure; use decisions and source evidence. get_snapshot provides architecture navigation when a map is available. The mason-audit and mason-review CLIs also work without setup.\",\n }\n );\n\n server.tool(\n \"mason_init\",\n \"Inspect this project now: returns documentation audit findings, committed-diff review findings, decision/map status, and a quickstart playbook. Read-only, deterministic, and usable without a map. Optional base selects the review comparison; evidence imports CI manifests with check outcomes, commit freshness, and links to changed files and accepted decisions. mode: map returns the full Map-Reduce build workflow. Repeat calls refresh findings even after setup.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n mode: z.enum([\"quickstart\", \"map\"]).optional().default(\"quickstart\")\n .describe(\"Quickstart returns checks and a short setup guide; map requests a full architecture build.\"),\n base: z.string().optional().describe(\"Git ref for committed-diff review. Defaults to the first available main branch ref.\"),\n evidence: z.array(z.string()).max(10).optional().describe(\"Repository-local CI evidence manifests to include in the review. Imports Vitest JSON and SARIF without executing check commands.\"),\n },\n async ({ dir, mode, base, evidence }) => {\n const result = await masonInit(dir, { mode, base, evidence });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_automation\",\n \"Inspect installed automation and observed host events, or resume/check retained documentation repair evidence across sessions. status is read-only; check saves local baselines and verification reports without editing source or approving advisories. Returns concise results with a full report path. Works without a map.\",\n {\n dir: z.string().describe(\"Absolute path to the project directory\"),\n action: z.enum([\"status\", \"check\"]).describe(\"Inspect configuration and receipts, or capture/resume and verify original audit evidence.\"),\n },\n async ({ dir, action }) => ({ content: [{ type: \"text\", text: await masonAutomation(dir, action) }] })\n );\n\n server.tool(\n \"mason_repair\",\n \"Track documentation repairs against original audit evidence. prepare saves a local baseline and returns a scoped work order; verify reads that baseline and reports resolved, unresolved, review-required, unverified, and new findings. Suppressed advisories remain unresolved. Does not edit documentation or approve decisions. No map required.\",\n {\n dir: z.string().describe(\"Absolute path to the project root directory\"),\n action: z.enum([\"prepare\", \"verify\"]),\n baselinePath: z.string().optional().describe(\"Original baseline path returned by prepare; required for verify.\"),\n checks: z.array(z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]))\n .min(1).optional().describe(\"Optional audit check subset for prepare. Verification always uses the original checks.\"),\n },\n async ({ dir, action, baselinePath, checks }) => {\n const result = await masonRepair(dir, { action, baselinePath, checks });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_complete_init\",\n \"Record completion of assistant instruction setup in .mason/project.json. Other tools work without this marker. Repeated calls preserve the original setup time and existing settings; pass confluenceConfigured only to change that setting.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n confluenceConfigured: z\n .boolean()\n .optional()\n .describe(\"Set the Confluence setup status; omit to preserve the existing value\"),\n },\n async ({ dir, confluenceConfigured }) => {\n const result = await masonCompleteInit(dir, { confluenceConfigured });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_set_confluence\",\n \"Configure Confluence credentials. Two-step flow: (1) call without `spaceKey` to validate the credentials and receive a list of available spaces — relay them to the user. (2) call again with the same `baseUrl`/`email`/`apiToken` plus the chosen `spaceKey` to persist. Credentials are stored in `~/.mason/config.json`. Warn the user that the API token will be visible in chat history before they paste it.\",\n {\n baseUrl: z\n .string()\n .describe(\"Confluence base URL. Accepts `acme`, `acme.atlassian.net`, or `https://acme.atlassian.net` (normalized automatically).\"),\n email: z.string().describe(\"User's Atlassian account email\"),\n apiToken: z\n .string()\n .describe(\"API token from id.atlassian.com/manage-profile/security/api-tokens\"),\n spaceKey: z\n .string()\n .optional()\n .describe(\"Confluence space key. Omit on the first call to list available spaces.\"),\n parentPageId: z\n .string()\n .optional()\n .describe(\"Optional parent page ID under which Mason's index page is created\"),\n },\n async ({ baseUrl, email, apiToken, spaceKey, parentPageId }) => {\n const result = await masonSetConfluence({\n baseUrl,\n email,\n apiToken,\n spaceKey,\n parentPageId,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"full_analysis\",\n \"One-shot orientation for a project WITHOUT a concept map (get_snapshot returned exists:false). Returns git history stats, project structure with file counts, curated code sample previews (~60 lines each), and test-to-source mapping. On a mapped project, prefer get_snapshot — it is cheaper and answers feature/architecture questions directly.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await fullAnalysis(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"analyze_project\",\n \"Run git history analysis on a codebase. Returns commit convention patterns, stale directories, and frequently changed files. These are aggregate stats across hundreds of commits that would be expensive to compute manually.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await analyzeProject(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_code_samples\",\n \"Get previews (first ~60 lines) of representative source files from the codebase. Includes entry points, config files, hot files (frequently changed), test examples, and one file per directory for breadth. Read files natively for full content.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n count: z\n .number()\n .optional()\n .default(15)\n .describe(\"Maximum number of files to sample (default: 15)\"),\n },\n async ({ dir, count }) => {\n const result = await getCodeSamples(dir, count);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_snapshot\",\n \"Return the optional feature-to-file architecture map with drift and trust evidence. If no map exists, returns exists:false plus project structure, Git signals, and test pairs. Decision capture, get_context, and get_impact still work. No initialization required.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await getSnapshot(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_context\",\n \"Assemble task context: matching decisions with rationale, approval, owner, sources, last review, and freshness, plus related tests, file impact, and any available map entries. Proposals are suggestions; legacy records are unreviewed; accepted decisions are constraints subject to freshness. No initialization or map required. Pass task and optional files. map.status and diagnostics preserve missing or invalid knowledge. Impact covers up to three unique files, expanding directory anchors.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n task: z\n .string()\n .describe(\"The task, bug, or change request in natural language — e.g. 'add rate limiting to the API client' or a ticket description\"),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Optional file paths already known to be involved (e.g. from a diff or stack trace). Entries containing them are boosted above pure text matches.\"),\n },\n async ({ dir, task, files }) => {\n const result = await getContext(dir, task, files);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"generate_snapshot_batch\",\n \"Map step of the concept-map build. Returns one batch of source files (skeletons of every file in the batch plus a few deeper-read bodies for grounding), along with a system prompt instructing you to derive features and flows for ONLY this batch. Call repeatedly with the returned `nextOffset` until it is null, calling `save_partial_snapshot` between each call. Use product-natural feature names so partials merge cleanly in the reduce step.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n offset: z\n .number()\n .int()\n .optional()\n .describe(\"0-indexed file offset to start the batch at. Omit on the first call; pass the `nextOffset` from the previous response for subsequent calls.\"),\n batchSize: z\n .number()\n .int()\n .optional()\n .describe(\"Files per batch. Defaults to 50.\"),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Scope the batch walk to this explicit file list — e.g. the drift set from mason_check_drift (changedFiles + unmappedFiles). Pass the SAME list on every batch call of one refresh run. Triggers refresh mode: reduce_snapshot will merge the partials into the existing map instead of rebuilding it.\"),\n },\n async ({ dir, offset, batchSize, files }) => {\n const result = await generateSnapshotBatch(dir, offset, batchSize, files);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_partial_snapshot\",\n \"Persist the partial concept map you derived for one batch. Call this once per batch, with the `batchId` from the `generate_snapshot_batch` response. Partials accumulate in `.mason/partial-snapshots/` and are merged in the reduce step.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n batchId: z\n .string()\n .describe(\"The `batchId` returned by `generate_snapshot_batch`.\"),\n offset: z\n .number()\n .int()\n .describe(\"The `offset` returned by `generate_snapshot_batch`. Used to order partials in the reduce step.\"),\n features: z\n .record(\n z.object({\n description: z.string(),\n files: z.array(z.string()),\n tests: z.array(z.string()).optional(),\n type: z\n .enum([\"capability\", \"infrastructure\"])\n .optional()\n .describe(\n '\"capability\" (user-facing functionality) or \"infrastructure\" (internal plumbing with no end user — DI/service wiring, config, logging, adapters). Defaults to \"capability\".'\n ),\n })\n )\n .describe(\"Partial features for this batch only — files outside the batch will be added by other partials.\"),\n flows: z\n .record(\n z.object({\n description: z.string(),\n chain: z.array(z.string()),\n })\n )\n .describe(\"Partial flows whose entire chain is in this batch. Cross-batch flows are reconstructed in reduce.\"),\n },\n async ({ dir, batchId, offset, features, flows }) => {\n const result = await saveSnapshotPartial(dir, batchId, offset, features, flows);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"reduce_snapshot\",\n \"Reduce step of the concept-map build. Returns every partial snapshot plus a system prompt asking you to merge them into one coherent project-wide map. Resolve platform variants into single product features, dedupe near-duplicates, and ensure no file is dropped. After producing the unified map, call `save_snapshot` to persist it (this also clears the partials).\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await reduceSnapshot(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_snapshot\",\n \"Save a concept-to-files map as a persistent project snapshot. Maps feature names and data flows to the files that implement them. Persists across conversations — future sessions can call get_snapshot to instantly find relevant files. No API key needed — you are the LLM generating the map.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n features: z\n .record(\n z.object({\n description: z.string().describe(\"One-line description of the feature\"),\n files: z.array(z.string()).describe(\"File paths that implement this feature\"),\n tests: z.array(z.string()).optional().describe(\"Test file paths for this feature\"),\n type: z\n .enum([\"capability\", \"infrastructure\"])\n .optional()\n .describe(\n 'Classification: \"capability\" for user-facing functionality, \"infrastructure\" for internal plumbing with no end user (DI/service wiring, config, logging, adapters). Capabilities are published to Confluence; infrastructure stays in the AI concept map only. Defaults to \"capability\".'\n ),\n })\n )\n .describe(\"Map of feature names to their implementing files\"),\n flows: z\n .record(\n z.object({\n description: z.string().describe(\"One-line description of the flow\"),\n chain: z.array(z.string()).describe(\"Ordered list of file paths showing data/call flow\"),\n })\n )\n .describe(\"Map of flow names to ordered file chains\"),\n removeFeatures: z\n .array(z.string())\n .optional()\n .describe(\"Feature names to delete from the existing map — for features that were renamed or no longer exist. Applied before merging; only meaningful on incremental saves.\"),\n removeFlows: z\n .array(z.string())\n .optional()\n .describe(\"Flow names to delete from the existing map. Applied before merging; only meaningful on incremental saves.\"),\n },\n async ({ dir, features, flows, removeFeatures, removeFlows }) => {\n const result = await saveSnapshotData(\n dir,\n features,\n flows,\n removeFeatures ?? [],\n removeFlows ?? []\n );\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_decision\",\n \"Capture or revise a decision proposal with rationale, anchors, optional owner, sources, and a known actor. No setup or map required. Writes a local record and preserves content history. Changes create a pending proposal while the last accepted revision remains operative; unchanged content does not re-verify or refresh it. Use review_decision for authorized acceptance or reaffirmation. A proposal cannot supersede a record with an operative accepted revision; review its replacement and retire the original separately.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n title: z\n .string()\n .max(80)\n .describe(\"Short, specific headline — becomes the stable record id\"),\n body: z\n .string()\n .max(1500)\n .describe(\"The knowledge itself: what was tried/decided, why, and what to avoid. Must contain information NOT derivable by reading the code.\"),\n category: z.enum([\"decision\", \"gotcha\", \"deprecation\", \"convention\"]),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Repo-relative files or directory prefixes this applies to. Matching is shared by retrieval, hooks, review, and drift checking; changes flag the decision for re-verification.\"),\n id: z\n .string()\n .optional()\n .describe(\"Existing id to revise. Changed content becomes a proposal; unchanged content leaves the review and freshness untouched.\"),\n supersedes: z\n .string()\n .optional()\n .describe(\"Id of an unreviewed record or proposal with no accepted revision to replace. Operative accepted decisions require separate review and retirement.\"),\n owner: attributionSchema.shape.owner.describe(\"Responsible person or team, when known. Null clears it. Required for acceptance.\"),\n sources: attributionSchema.shape.sources.describe(\"Known PR, issue, incident, discussion, or document references. Omit to preserve; [] clears. At least one is required for acceptance.\"),\n actor: attributionSchema.shape.actor.describe(\"Known person or agent recording this revision. Omit if unknown; do not infer from Git identity.\"),\n force: z\n .boolean()\n .optional()\n .describe(\"Save even when a near-duplicate was detected\"),\n },\n async ({ dir, title, body, category, files, id, supersedes, force, owner, sources, actor }) => {\n const result = await saveDecision(dir, {\n title,\n body,\n category,\n files,\n id,\n supersedes,\n force,\n owner,\n sources,\n actor,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"review_decision\",\n \"Prepare a decision review: returns the full record and history, any operative accepted revision, provenance, changes and previews for both sets of anchors, and a reviewToken. Then record accept, reaffirm, or retire with that token, the authorized reviewer, and a reason. Acceptance replaces the operative revision; retirement withdraws the entire record including its proposal. Acceptance requires owner, source, readable Git HEAD, and committed anchor changes. Changed records or code invalidate the token. Identities and approvals are recorded assertions for normal PR review, not authenticated proof.\",\n {\n dir: z.string().describe(\"Absolute path to the project root directory\"),\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/).describe(\"Decision id from get_context or save_decision\"),\n action: z.enum([\"prepare\", \"accept\", \"reaffirm\", \"retire\"]).optional().default(\"prepare\")\n .describe(\"Prepare is read-only. Other actions record an explicitly authorized review.\"),\n reviewer: z.string().trim().min(1).max(200).optional().describe(\"Identity of the actual reviewer; required for a verdict. Never invent one.\"),\n note: z.string().trim().min(1).max(1500).optional().describe(\"Review rationale; required for a verdict. Cite evidence for the decision.\"),\n reviewToken: z.string().regex(/^[a-f0-9]{64}$/).optional().describe(\"Token from the prepared review; rejects stale record or code revisions\"),\n },\n async ({ dir, ...input }) => {\n const result = await reviewDecision(dir, input);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_check_drift\",\n \"Check how far the concept map has drifted from HEAD. Deterministic (git + filesystem, no LLM). Returns which features/flows are stale and the changed files behind them, new source files not yet mapped, ghost files (mapped but deleted), renames, and a `recommendation`: `up-to-date` (nothing to do), `incremental` (update just the stale entries via save_snapshot), or `full-rebuild` (re-run the Map-Reduce build). Call this before trusting the map in a long session, or periodically to keep the map and any synced wikis fresh.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await checkDrift(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"verify_snapshot\",\n \"Spot-check the concept map's CORRECTNESS (drift checks freshness; this checks entries were right to begin with). Returns a sample of entries — always the never-verified and least-recently-verified first — with skeletons of their claimed files, for you to judge whether the files actually implement what the entry claims. Report verdicts back via save_verification. Run periodically, or after an automated refresh wrote entries no human reviewed.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n sample: z\n .number()\n .int()\n .optional()\n .describe(\"Entries to sample (default 5)\"),\n },\n async ({ dir, sample }) => {\n const result = await verifySnapshot(dir, sample);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"save_verification\",\n \"Record verify_snapshot verdicts. Entries judged ok are stamped verifiedAt; failures are flagged verificationFailed with your note and surface in get_context, get_snapshot, and mason_check_drift until corrected. Verdict notes are required for failures.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n verdicts: z\n .record(\n z.object({\n ok: z.boolean(),\n note: z\n .string()\n .optional()\n .describe(\"One line on what's wrong — required when ok is false\"),\n })\n )\n .describe(\"Entry name → verdict, exactly as returned by verify_snapshot\"),\n },\n async ({ dir, verdicts }) => {\n const result = await saveVerification(dir, verdicts);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"get_impact\",\n \"Trace the impact of changing files: historical co-change partners, references, and related tests. Deterministic, read-only, and usable without initialization, saved decisions, or a concept map.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n files: z\n .array(z.string())\n .describe(\"File paths or names to analyze (e.g., ['WeatherRepository.kt'] or ['src/services/auth.ts'])\"),\n },\n async ({ dir, files }) => {\n const result = await getImpact(dir, files);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"export_to_confluence\",\n \"Sync the project's concept map to Confluence as product-readable wiki pages: an index page, one page per feature (PM-language descriptions, no file paths), and a changelog page. Mason replaces managed page bodies; manual edits to those bodies are overwritten. Requires `mason_set_confluence` to have been called first.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n spaceKey: z\n .string()\n .optional()\n .describe(\"Override the configured space key\"),\n parentPageId: z\n .string()\n .optional()\n .describe(\"Override the configured parent page ID\"),\n indexPageTitle: z\n .string()\n .optional()\n .describe(\"Title of the index page (default: 'Mason — System Map')\"),\n changelogPageTitle: z\n .string()\n .optional()\n .describe(\"Title of the changelog page (default: 'Mason — Changelog')\"),\n featurePagePrefix: z\n .string()\n .optional()\n .describe(\"Prefix for each feature page title (default: 'Feature: ')\"),\n },\n async ({ dir, spaceKey, parentPageId, indexPageTitle, changelogPageTitle, featurePagePrefix }) => {\n const result = await exportToConfluenceTool(dir, {\n spaceKey,\n parentPageId,\n indexPageTitle,\n changelogPageTitle,\n featurePagePrefix,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n return server;\n}\n\nexport async function startMcpServer(): Promise<void> {\n const server = createMcpServer();\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { prepareRepair, verifyRepair } from \"../audit/repair.js\";\nimport { formatFixPrompt } from \"../audit/cli.js\";\nimport type { CheckName } from \"../audit/types.js\";\n\nconst exec = promisify(execFile);\nimport { runAll } from \"../analyzers/index.js\";\nimport { isGitRepo } from \"../utils/git.js\";\nimport { sampleFiles } from \"./sampler.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { assessTrust, trustHint, type TrustState } from \"../context/trust.js\";\nimport { compactDecisionKnowledge, effectiveDecision, decisionTrust, DECISION_GUIDANCE } from \"../decisions/provenance.js\";\nimport type { UpsertDecisionInput } from \"../decisions/decisions.js\";\nimport { reviewDecision as runDecisionReview, type ReviewDecisionInput } from \"../decisions/review.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\nimport {\n loadSnapshot,\n saveSnapshot,\n getCurrentGitHash,\n prepareSnapshotBatch,\n normalizeFeatureType,\n DEFAULT_BATCH_SIZE,\n type FeatureType,\n} from \"../snapshot/snapshot.js\";\nimport { computeDrift } from \"../drift/drift.js\";\nimport type { DriftReport } from \"../drift/drift.js\";\nimport {\n BATCH_SYSTEM_PROMPT,\n REDUCE_SYSTEM_PROMPT,\n REFRESH_REDUCE_SYSTEM_PROMPT,\n buildBatchPrompt,\n buildReducePrompt,\n buildRefreshReducePrompt,\n} from \"../snapshot/prompt.js\";\nimport {\n batchIdFor,\n clearAllPartials,\n clearScope,\n loadAllPartials,\n loadScope,\n savePartial,\n saveScope,\n} from \"../snapshot/partials.js\";\nimport type { Snapshot, FeatureEntry, FlowEntry } from \"../snapshot/snapshot.js\";\nimport type { AnalyzerContext } from \"../types.js\";\nimport {\n loadProjectMarker,\n saveProjectMarker,\n setupPlaybook,\n type ProjectMarker,\n type InitMode,\n} from \"./init.js\";\nimport { inspectOnboarding } from \"./onboarding.js\";\n\nasync function buildContext(dir: string): Promise<AnalyzerContext> {\n return {\n rootDir: dir,\n gitAvailable: await isGitRepo(dir),\n };\n}\n\nexport async function analyzeProject(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n const context = await buildContext(rootDir);\n const results = await runAll(context);\n\n // Lightweight project snapshot — pure file existence checks, no parsing\n const projectSnapshot = await detectProjectSnapshot(rootDir);\n\n const output = {\n project: projectSnapshot,\n analyzers: results.map((r) => ({\n name: r.analyzer,\n durationMs: r.durationMs,\n findings: r.findings.map((f) => ({\n category: f.category,\n confidence: f.confidence,\n summary: f.summary,\n evidence: f.evidence,\n suggestedRule: f.ruleCandidate,\n })),\n gaps: r.gaps.map((g) => ({\n question: g.question,\n context: g.context,\n })),\n })),\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nasync function detectProjectSnapshot(rootDir: string): Promise<Record<string, unknown>> {\n // Build config files present (what exists, not what's in them)\n const access = await createFileAccess(rootDir);\n const buildFiles = [\n \"package.json\", \"tsconfig.json\",\n \"build.gradle.kts\", \"build.gradle\", \"settings.gradle.kts\", \"settings.gradle\",\n \"gradle/libs.versions.toml\",\n \"Cargo.toml\", \"go.mod\", \"go.sum\",\n \"pyproject.toml\", \"setup.py\", \"requirements.txt\", \"Pipfile\",\n \"Gemfile\", \"Package.swift\",\n \"Makefile\", \"CMakeLists.txt\",\n \"Dockerfile\", \"docker-compose.yml\", \"docker-compose.yaml\",\n \".github/workflows\", \".gitlab-ci.yml\", \"Jenkinsfile\",\n ];\n\n const present: string[] = [];\n for (const file of buildFiles) {\n try {\n await fs.access(path.join(rootDir, file));\n present.push(file);\n } catch {\n // Not found\n }\n }\n\n // Test directories and file counts\n const testDirs = [\n \"test\", \"tests\", \"__tests__\", \"spec\",\n \"src/test\", \"src/tests\",\n \"**/src/test\", \"**/src/androidTest\", \"**/src/iosTest\",\n ];\n const testInfo: Record<string, number> = {};\n for (const pattern of testDirs) {\n const files = await access.list(`${pattern}/**/*`);\n if (files.length > 0) {\n testInfo[pattern] = files.length;\n }\n }\n\n // Also count test files by naming convention\n const testFilePatterns = [\n { pattern: \"**/*.test.*\", label: \"*.test.*\" },\n { pattern: \"**/*.spec.*\", label: \"*.spec.*\" },\n { pattern: \"**/*Test.kt\", label: \"*Test.kt\" },\n { pattern: \"**/*Test.java\", label: \"*Test.java\" },\n { pattern: \"**/test_*.py\", label: \"test_*.py\" },\n { pattern: \"**/*_test.go\", label: \"*_test.go\" },\n { pattern: \"**/*Tests.swift\", label: \"*Tests.swift\" },\n { pattern: \"**/*_test.rs\", label: \"*_test.rs\" },\n ];\n for (const { pattern, label } of testFilePatterns) {\n const files = await access.list(pattern);\n if (files.length > 0) {\n testInfo[label] = files.length;\n }\n }\n\n // Source file counts by extension\n const sourceFiles = await access.list();\n const fileCounts: Record<string, number> = {};\n for (const file of sourceFiles) {\n const ext = path.extname(file).slice(1);\n fileCounts[ext] = (fileCounts[ext] ?? 0) + 1;\n }\n\n return {\n configFilesPresent: present,\n sourceFileCounts: fileCounts,\n totalSourceFiles: sourceFiles.length,\n testInfo: Object.keys(testInfo).length > 0 ? testInfo : undefined,\n };\n}\n\nexport async function getCodeSamples(\n dir: string,\n count: number = 15\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const samples = await sampleFiles(rootDir, count);\n\n const output = {\n note: \"These are previews (first ~60 lines). Read the file directly with your own tools to see it in full.\",\n files: samples.map((s) => ({\n path: s.path,\n reason: s.reason,\n totalLines: s.totalLines,\n sizeBytes: s.sizeBytes,\n preview: s.preview,\n })),\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nconst UNINIT_MAX_DIRECTORIES = 40;\nconst UNINIT_MAX_TEST_PAIRS = 30;\n\n/** Keep architecture requests useful when the optional map is absent. */\nasync function unmappedContextResponse(rootDir: string): Promise<string> {\n const [structureRaw, analyzerResults, testMap] = await Promise.all([\n getProjectStructure(rootDir),\n runAll(await buildContext(rootDir)).catch(() => []),\n import(\"../test-map.js\")\n .then((m) => m.buildTestMap(rootDir))\n .catch(() => null),\n ]);\n\n const structure = JSON.parse(structureRaw);\n structure.directories = (structure.directories ?? [])\n .sort(\n (a: { fileCount: number }, b: { fileCount: number }) =>\n b.fileCount - a.fileCount\n )\n .slice(0, UNINIT_MAX_DIRECTORIES);\n\n const gitSignals = analyzerResults.flatMap((r) =>\n r.findings.map((f) => ({\n category: f.category,\n summary: f.summary,\n evidence: f.evidence.slice(0, 5),\n }))\n );\n\n return JSON.stringify({\n exists: false,\n map: { status: \"missing\" },\n hint:\n `No Mason concept map exists here yet. Use the context below plus your own reads to answer now — ` +\n `get_context, save_decision, and get_impact work without a map. For an optional map, mason_init with mode: \"map\" provides the generate_snapshot_batch workflow.`,\n structure,\n gitSignals,\n testPairs: testMap?.paired?.slice(0, UNINIT_MAX_TEST_PAIRS) ?? [],\n });\n}\n\nexport async function getProjectStructure(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n // Get all files\n const allFiles = await (await createFileAccess(rootDir)).list(\"**/*\");\n\n // Build directory summary with file counts and extension breakdown\n const dirInfo = new Map<\n string,\n { fileCount: number; extensions: Map<string, number> }\n >();\n\n for (const file of allFiles) {\n const parts = file.split(\"/\");\n // Track up to 2 levels deep\n for (let depth = 1; depth <= Math.min(parts.length, 2); depth++) {\n const dirPath = parts.slice(0, depth).join(\"/\");\n if (!dirInfo.has(dirPath)) {\n dirInfo.set(dirPath, { fileCount: 0, extensions: new Map() });\n }\n const info = dirInfo.get(dirPath)!;\n info.fileCount++;\n const ext = path.extname(file).slice(1);\n if (ext) {\n info.extensions.set(ext, (info.extensions.get(ext) ?? 0) + 1);\n }\n }\n }\n\n // Format directories sorted by path\n const directories = [...dirInfo.entries()]\n .sort((a, b) => a[0].localeCompare(b[0]))\n .map(([dirPath, info]) => {\n const extensions: Record<string, number> = {};\n for (const [ext, count] of info.extensions) {\n extensions[ext] = count;\n }\n return { path: dirPath, fileCount: info.fileCount, extensions };\n });\n\n // Top-level files\n const topLevelFiles = allFiles.filter((f) => !f.includes(\"/\"));\n\n const output = {\n totalFiles: allFiles.length,\n topLevelFiles,\n directories,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nexport async function getTestMap(dir: string): Promise<string> {\n const { buildTestMap } = await import(\"../test-map.js\");\n const result = await buildTestMap(dir);\n return JSON.stringify(result, null, 2);\n}\n\nconst STALE_DIFF_PREVIEW_LINES = 60;\nconst STALE_DIFF_MAX_FILES = 25;\n\nasync function buildChangedFilePreviews(\n rootDir: string,\n changedFiles: string[]\n): Promise<Array<{ path: string; totalLines: number; preview: string }>> {\n const access = await createFileAccess(rootDir);\n const capped = changedFiles.slice(0, STALE_DIFF_MAX_FILES);\n const previews: Array<{ path: string; totalLines: number; preview: string }> = [];\n for (const filePath of capped) {\n const full = await access.read(filePath);\n if (!full) continue;\n const lines = full.content.split(\"\\n\");\n previews.push({\n path: full.path,\n totalLines: full.totalLines,\n preview: lines.slice(0, STALE_DIFF_PREVIEW_LINES).join(\"\\n\"),\n });\n }\n return previews;\n}\n\nexport async function getSnapshot(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const snapshot = await loadSnapshot(rootDir);\n\n if (!snapshot) {\n return unmappedContextResponse(rootDir);\n }\n\n // Staleness is per entry, not just top-level — a partially refreshed map\n // can be pinned to HEAD while individual entries lag behind.\n const drift = await computeDrift(rootDir);\n const isStale = drift?.stale ?? false;\n\n // Return compact format: feature/flow names -> file lists only.\n // Descriptions and metadata stay in the full snapshot on disk.\n // Deduplicate files that appear in multiple features.\n const seenFiles = new Set<string>();\n const compactFeatures: Record<\n string,\n { files: string[]; tests?: string[]; type: FeatureType }\n > = {};\n for (const [name, feat] of Object.entries(snapshot.features)) {\n const unique = feat.files.filter((f) => !seenFiles.has(f));\n if (unique.length === 0) continue; // Skip fully duplicate features\n for (const f of unique) seenFiles.add(f);\n const entry: { files: string[]; tests?: string[]; type: FeatureType } = {\n files: unique,\n type: normalizeFeatureType(feat.type),\n };\n if (feat.tests && feat.tests.length > 0) {\n entry.tests = feat.tests;\n }\n compactFeatures[name] = entry;\n }\n\n const compactFlows: Record<string, string[]> = {};\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n compactFlows[name] = flow.chain; // Flows keep all files (order matters)\n }\n\n const output: Record<string, unknown> = {\n exists: true,\n map: { status: \"available\" },\n updatedAt: snapshot.updatedAt,\n features: compactFeatures,\n flows: compactFlows,\n stale: isStale,\n };\n\n // Compact decision index — titles only, no bodies (up to 150 × 1.5KB is\n // too heavy for the orientation call). Full text via get_context or the\n // record file itself.\n const { loadDecisionStore } = await import(\"../decisions/decisions.js\");\n const store = await loadDecisionStore(rootDir);\n const decisionRecords = store.records;\n const decisionDrift = await computeDecisionDrift(rootDir, decisionRecords);\n const trust: { features: Record<string, TrustState>; flows: Record<string, TrustState>; decisions: Record<string, TrustState> } = {\n features: Object.fromEntries(Object.entries(snapshot.features).map(([name, entry]) => [name, assessTrust(entry, drift?.featureFreshness?.[name] ?? \"unknown\")])),\n flows: Object.fromEntries(Object.entries(snapshot.flows).map(([name, entry]) => [name, assessTrust(entry, drift?.flowFreshness?.[name] ?? \"unknown\")])),\n decisions: Object.fromEntries(decisionRecords.filter(d => d.status === \"active\").map(d => [d.id, decisionTrust(effectiveDecision(d), decisionDrift.freshness?.[d.id] ?? \"unknown\")])),\n };\n output.trust = trust;\n output.workingTree = drift?.workingTree;\n output.diagnostics = store.diagnostics;\n if (decisionRecords.length > 0) {\n const compactDecisions: Record<\n string,\n ReturnType<typeof compactDecisionKnowledge>\n > = {};\n for (const d of decisionRecords) {\n if (d.status !== \"active\") continue;\n compactDecisions[d.id] = compactDecisionKnowledge(d, decisionDrift.freshness?.[d.id] ?? \"unknown\", decisionDrift.pendingProposals?.[d.id]?.freshness ?? \"unknown\");\n }\n output.decisions = compactDecisions;\n output.decisionsHint =\n DECISION_GUIDANCE + \" Full bodies via get_context; full history via review_decision.\";\n }\n\n if (isStale && drift) {\n output.hint = driftHint(drift);\n output.drift = {\n historyAvailable: drift.historyAvailable,\n staleFeatures: drift.staleFeatures,\n staleFlows: drift.staleFlows,\n unmappedFiles: drift.unmappedFiles,\n ghostFiles: drift.ghostFiles,\n renames: drift.renames,\n recommendation: drift.recommendation,\n };\n if (drift.historyAvailable && drift.changedFiles.length > 0) {\n const samples = await buildChangedFilePreviews(\n rootDir,\n drift.changedFiles\n );\n output.diff = {\n changedFiles: drift.changedFiles,\n samples,\n truncated: drift.changedFiles.length > STALE_DIFF_MAX_FILES,\n };\n }\n }\n\n output.hint = [output.hint, trustHint([...Object.values(trust.features), ...Object.values(trust.flows), ...Object.values(trust.decisions)]), store.diagnostics.length ? \"Some decision records are invalid; consult diagnostics.\" : \"\"].filter(Boolean).join(\" \");\n return JSON.stringify(output);\n}\n\nfunction driftHint(report: DriftReport): string {\n if (!report.stale) {\n return \"No committed changes affect the map. Consult verification and working-tree evidence before relying on it.\";\n }\n if (!report.historyAvailable) {\n return \"Snapshot is stale but its commit is unreachable (shallow clone or rewritten history), so per-feature drift cannot be computed. Re-run the Map-Reduce build: generate_snapshot_batch → save_partial_snapshot → reduce_snapshot → save_snapshot.\";\n }\n if (report.recommendation === \"full-rebuild\") {\n return \"Drift is too large for an incremental update. Re-run the Map-Reduce build: generate_snapshot_batch → save_partial_snapshot → reduce_snapshot → save_snapshot.\";\n }\n if (report.changedFiles.length + report.unmappedFiles.length > STALE_DIFF_MAX_FILES) {\n return \"Many files drifted — use a scoped refresh instead of reading them all inline: call generate_snapshot_batch(dir, files=[...changedFiles, ...unmappedFiles]) repeatedly (same list every call) with save_partial_snapshot per batch, then reduce_snapshot and save_snapshot. Entries untouched by the drift are preserved in the reduce step.\";\n }\n const nothingToRemap =\n Object.keys(report.staleFeatures).length === 0 &&\n Object.keys(report.staleFlows).length === 0 &&\n report.unmappedFiles.length === 0 &&\n report.ghostFiles.length === 0;\n if (nothingToRemap) {\n return \"Changes since the snapshot don't touch any mapped files. Call save_snapshot with empty features/flows to re-pin the snapshot to HEAD.\";\n }\n return \"Read the changed files under staleFeatures/staleFlows, update those entries (fold unmappedFiles into the right features), and call save_snapshot with only the affected entries — unchanged entries are preserved. Drop ghostFiles from any entries that reference them, and delete features/flows that no longer exist via save_snapshot's removeFeatures/removeFlows.\";\n}\n\nexport async function checkDrift(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n\n const report = await computeDrift(rootDir);\n if (!report) {\n return JSON.stringify({\n exists: false,\n hint: \"No concept map exists to check. Decisions and impact work without one; mason_init with mode: \\\"map\\\" provides the optional map workflow.\",\n });\n }\n\n // Report recorded correctness verdicts alongside freshness evidence.\n const snapshot = await loadSnapshot(rootDir);\n let verification: Record<string, unknown> | undefined;\n let hint = driftHint(report);\n if (snapshot) {\n const all = [\n ...Object.values(snapshot.features),\n ...Object.values(snapshot.flows),\n ];\n const failedNames = [\n ...Object.entries(snapshot.features)\n .filter(([, e]) => e.verificationFailed)\n .map(([n]) => n),\n ...Object.entries(snapshot.flows)\n .filter(([, e]) => e.verificationFailed)\n .map(([n]) => n),\n ];\n verification = {\n neverVerified: all.filter((e) => !e.verifiedAt).length,\n failed: failedNames,\n };\n if (failedNames.length > 0) {\n hint += ` Verification previously FAILED for [${failedNames.join(\", \")}] — re-map those entries before trusting them.`;\n }\n }\n\n return JSON.stringify({ exists: true, ...report, verification, hint });\n}\n\nexport async function generateSnapshotBatch(\n dir: string,\n offset: number = 0,\n batchSize: number = DEFAULT_BATCH_SIZE,\n files?: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const scoped = files !== undefined && files.length > 0;\n const scopeFiles = scoped ? sanitizePaths(rootDir, files) : undefined;\n const batch = await prepareSnapshotBatch(dir, offset, batchSize, scopeFiles);\n\n if (scoped && batch.totalFiles > 0) {\n // Mark this partial run as a scoped refresh so reduce_snapshot merges\n // into the existing map instead of rebuilding it from partials alone.\n await saveScope(rootDir, scopeFiles!);\n } else if (!scoped) {\n // A full build must never inherit a scope marker left behind by an\n // abandoned refresh run — its reduce step would wrongly merge instead\n // of rebuilding.\n await clearScope(rootDir);\n }\n\n const task = scoped\n ? \"Refresh the concept map for a scoped set of drifted files (batch step).\"\n : \"Build a concept-to-files map for this project (batch step).\";\n\n if (batch.totalFiles === 0) {\n return JSON.stringify(\n {\n task,\n offset: 0,\n nextOffset: null,\n totalFiles: 0,\n batchId: batchIdFor(0),\n instructions: BATCH_SYSTEM_PROMPT,\n prompt: scoped\n ? \"(None of the requested files exist as source files in this project.)\"\n : \"(No source files found to map.)\",\n next: scoped\n ? \"None of the requested files matched project source files. Check the paths passed in `files` — they must be repo-relative.\"\n : \"No source files were found. Skip the rest of the playbook and call mason_complete_init.\",\n },\n null,\n 2\n );\n }\n\n const batchId = batchIdFor(batch.offset);\n const continueCall = scoped\n ? `generate_snapshot_batch(dir, offset=${batch.nextOffset}, files=<the same list>)`\n : `generate_snapshot_batch(dir, offset=${batch.nextOffset})`;\n\n return JSON.stringify(\n {\n task,\n offset: batch.offset,\n nextOffset: batch.nextOffset,\n totalFiles: batch.totalFiles,\n batchId,\n batchSize: batch.batchSize,\n filesInBatch: batch.skeletons.length,\n scoped,\n instructions: BATCH_SYSTEM_PROMPT,\n prompt: buildBatchPrompt(batch),\n next:\n batch.nextOffset === null\n ? `Derive partial features/flows for this batch and call save_partial_snapshot(dir, batchId=\"${batchId}\", features, flows). This is the last batch — after saving, proceed to reduce_snapshot.`\n : `Derive partial features/flows for this batch and call save_partial_snapshot(dir, batchId=\"${batchId}\", features, flows). Then call ${continueCall} to continue.`,\n },\n null,\n 2\n );\n}\n\nexport async function saveSnapshotPartial(\n dir: string,\n batchId: string,\n offset: number,\n features: Record<\n string,\n { description: string; files: string[]; tests?: string[]; type?: FeatureType }\n >,\n flows: Record<string, { description: string; chain: string[] }>\n): Promise<string> {\n const rootDir = path.resolve(dir);\n\n // Sanitize all file paths to prevent path traversal in stored partials, and\n // normalize the capability/infrastructure classification so it survives reduce.\n for (const feat of Object.values(features)) {\n feat.files = sanitizePaths(rootDir, feat.files);\n if (feat.tests) feat.tests = sanitizePaths(rootDir, feat.tests);\n feat.type = normalizeFeatureType(feat.type);\n }\n for (const flow of Object.values(flows)) {\n flow.chain = sanitizePaths(rootDir, flow.chain);\n }\n\n await savePartial(rootDir, {\n batchId,\n offset,\n features,\n flows,\n savedAt: new Date().toISOString(),\n });\n\n const all = await loadAllPartials(rootDir);\n return JSON.stringify(\n {\n status: \"stored\",\n batchId,\n partialsStored: all.length,\n hint:\n \"Partial saved. Continue with the next generate_snapshot_batch call, or proceed to reduce_snapshot when nextOffset is null.\",\n },\n null,\n 2\n );\n}\n\nexport async function reduceSnapshot(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n const partials = await loadAllPartials(rootDir);\n\n if (partials.length === 0) {\n return JSON.stringify(\n {\n status: \"error\",\n error:\n \"No partial snapshots found. Run generate_snapshot_batch and save_partial_snapshot at least once before calling reduce_snapshot.\",\n },\n null,\n 2\n );\n }\n\n // A scope marker means these partials re-analyzed only a drifted subset —\n // merge them into the existing map instead of rebuilding from scratch.\n const scope = await loadScope(rootDir);\n const existing =\n scope && scope.length > 0 ? await loadSnapshot(rootDir) : null;\n\n if (scope && existing) {\n // Strip bookkeeping fields — the assistant shouldn't echo them back.\n const cleanFeatures = Object.fromEntries(\n Object.entries(existing.features).map(([name, feat]) => [\n name,\n {\n description: feat.description,\n files: feat.files,\n ...(feat.tests && feat.tests.length > 0 ? { tests: feat.tests } : {}),\n type: normalizeFeatureType(feat.type),\n },\n ])\n );\n const cleanFlows = Object.fromEntries(\n Object.entries(existing.flows).map(([name, flow]) => [\n name,\n { description: flow.description, chain: flow.chain },\n ])\n );\n\n return JSON.stringify(\n {\n task: \"Merge a scoped refresh into the existing concept map.\",\n partialsCount: partials.length,\n refreshedFiles: scope.length,\n instructions: REFRESH_REDUCE_SYSTEM_PROMPT,\n prompt: buildRefreshReducePrompt(\n { features: cleanFeatures, flows: cleanFlows },\n scope,\n partials\n ),\n next: \"Follow `instructions` to produce the COMPLETE updated features/flows (entries untouched by the refresh copied through unchanged), then call save_snapshot(dir, features, flows). Partials and the scope marker are cleaned up automatically after save_snapshot succeeds.\",\n },\n null,\n 2\n );\n }\n\n return JSON.stringify(\n {\n task: \"Merge partial concept maps into one unified map.\",\n partialsCount: partials.length,\n instructions: REDUCE_SYSTEM_PROMPT,\n prompt: buildReducePrompt(partials),\n next: \"Follow `instructions` to produce the unified features/flows, then call save_snapshot(dir, features, flows). Partial files will be cleaned up automatically after save_snapshot succeeds. Finish with mason_complete_init(dir).\",\n },\n null,\n 2\n );\n}\n\nexport async function fullAnalysis(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const [analysis, structure, samples, testMap, snapshot] = await Promise.all([\n analyzeProject(dir),\n getProjectStructure(dir),\n getCodeSamples(dir, 25),\n getTestMap(dir),\n loadSnapshot(rootDir),\n ]);\n\n const output: Record<string, unknown> = {\n note: \"Full project analysis. Code samples are previews (~60 lines). Read files directly with your own tools to see them in full.\",\n analysis: JSON.parse(analysis),\n structure: JSON.parse(structure),\n codeSamples: JSON.parse(samples),\n testMap: JSON.parse(testMap),\n };\n\n if (snapshot) {\n output.conceptMap = {\n updatedAt: snapshot.updatedAt,\n features: snapshot.features,\n flows: snapshot.flows,\n };\n output.note =\n \"Full project analysis with concept map. The concept map shows which files implement each feature and how data flows through them. Use it to jump straight to relevant files instead of exploring, then read them directly with your own tools.\";\n }\n\n return JSON.stringify(output, null, 2);\n}\n\nfunction sanitizePaths(\n rootDir: string,\n files: string[]\n): string[] {\n return sanitizeRepoPaths(files);\n}\n\nexport async function saveSnapshotData(\n dir: string,\n features: Record<\n string,\n {\n description: string;\n files: string[];\n tests?: string[];\n refreshedHash?: string;\n type?: FeatureType;\n }\n >,\n flows: Record<\n string,\n { description: string; chain: string[]; refreshedHash?: string }\n >,\n removeFeatures: string[] = [],\n removeFlows: string[] = []\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const gitHash = await getCurrentGitHash(rootDir);\n const now = new Date().toISOString();\n\n // Sanitize all file paths to prevent path traversal, and normalize the\n // capability/infrastructure classification (defaults to \"capability\").\n for (const feat of Object.values(features)) {\n feat.files = sanitizePaths(rootDir, feat.files);\n if (feat.tests) feat.tests = sanitizePaths(rootDir, feat.tests);\n feat.type = normalizeFeatureType(feat.type);\n }\n for (const flow of Object.values(flows)) {\n flow.chain = sanitizePaths(rootDir, flow.chain);\n }\n\n // If partials exist we're consolidating a Map-Reduce run: replace the\n // snapshot wholesale. Merging here would pollute the unified map with any\n // earlier (possibly hallucinated) call to save_snapshot. Outside of\n // Map-Reduce — incremental refresh of one feature — fall back to merge.\n const partials = await loadAllPartials(rootDir);\n const replaceMode = partials.length > 0;\n const previous = await loadSnapshot(rootDir);\n const existing = replaceMode ? null : previous;\n // Copy-through entries must not silently lose a failed verification during\n // a scoped rebuild. A changed description/path set requires a new verdict.\n const preserveVerification = (next: FeatureEntry | FlowEntry, old?: FeatureEntry | FlowEntry) => {\n if (!old) return;\n const semantic = (entry: FeatureEntry | FlowEntry) => JSON.stringify({\n description: entry.description,\n files: \"files\" in entry ? entry.files : undefined,\n chain: \"chain\" in entry ? entry.chain : undefined,\n tests: \"files\" in entry ? entry.tests : undefined,\n type: \"files\" in entry ? normalizeFeatureType(entry.type) : undefined,\n });\n if (semantic(next) !== semantic(old)) return;\n next.verifiedAt = old.verifiedAt;\n next.verifiedHash = old.verifiedHash;\n next.verificationFailed = old.verificationFailed;\n next.verificationNote = old.verificationNote;\n };\n for (const [name, entry] of Object.entries(features)) preserveVerification(entry, previous?.features[name]);\n for (const [name, entry] of Object.entries(flows)) preserveVerification(entry, previous?.flows[name]);\n\n if (existing) {\n // Entries not re-sent in this call are only verified as of the previous\n // hash — record that before the top-level gitHash moves to HEAD, so\n // drift detection can still see which entries were skipped.\n if (existing.gitHash !== \"unknown\") {\n for (const feat of Object.values(existing.features)) {\n feat.refreshedHash ??= existing.gitHash;\n }\n for (const flow of Object.values(existing.flows)) {\n flow.refreshedHash ??= existing.gitHash;\n }\n }\n\n const removedFeatures = removeFeatures.filter(\n (name) => name in existing.features\n );\n const removedFlows = removeFlows.filter((name) => name in existing.flows);\n for (const name of removedFeatures) delete existing.features[name];\n for (const name of removedFlows) delete existing.flows[name];\n\n if (gitHash !== \"unknown\") {\n for (const feat of Object.values(features)) feat.refreshedHash = gitHash;\n for (const flow of Object.values(flows)) flow.refreshedHash = gitHash;\n }\n\n existing.features = { ...existing.features, ...features };\n existing.flows = { ...existing.flows, ...flows };\n existing.updatedAt = now;\n existing.gitHash = gitHash;\n await saveSnapshot(rootDir, existing);\n await clearAllPartials(rootDir);\n return JSON.stringify({\n status: \"updated\",\n mode: \"merged\",\n features: Object.keys(existing.features).length,\n flows: Object.keys(existing.flows).length,\n removedFeatures: removedFeatures.length,\n removedFlows: removedFlows.length,\n });\n }\n\n const snapshot: Snapshot = {\n version: 2,\n createdAt: now,\n updatedAt: now,\n gitHash,\n features,\n flows,\n };\n\n await saveSnapshot(rootDir, snapshot);\n await clearAllPartials(rootDir);\n return JSON.stringify({\n status: replaceMode ? \"replaced\" : \"created\",\n mode: replaceMode ? \"replaced-from-partials\" : \"fresh\",\n features: Object.keys(features).length,\n flows: Object.keys(flows).length,\n });\n}\n\nexport async function configureProject(\n dir: string,\n config: {\n patterns?: string[];\n alwaysInclude?: string[];\n ignore?: string[];\n }\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const existing = (await readStoreJson(rootDir, \".mason/config.json\") ?? {}) as Record<string, unknown>;\n\n if (config.patterns) existing.patterns = config.patterns;\n if (config.alwaysInclude) existing.alwaysInclude = config.alwaysInclude;\n if (config.ignore) existing.ignore = config.ignore;\n\n await writeStoreJson(rootDir, \".mason/config.json\", existing);\n\n return JSON.stringify({\n status: \"saved\",\n path: path.join(rootDir, \".mason/config.json\"),\n config: existing,\n });\n}\n\nexport async function getImpact(\n dir: string,\n files: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { analyzeImpact } = await import(\"../impact/impact.js\");\n const result = await analyzeImpact(rootDir, files);\n return JSON.stringify(result, null, 2);\n}\n\nconst VERIFY_DEFAULT_SAMPLE = 5;\nconst VERIFY_MAX_FILES_PER_ENTRY = 8;\nconst VERIFY_SKELETON_CHARS = 500;\n\n/**\n * Verification closes the day-one hole drift can't: drift proves the map is\n * current against git, but nothing proves an entry was CORRECT when written.\n * Sample entries weighted toward never-verified, then oldest-verified.\n */\nexport async function verifySnapshot(\n dir: string,\n sample: number = VERIFY_DEFAULT_SAMPLE\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n return JSON.stringify({\n exists: false,\n hint: \"No concept map exists yet — nothing to verify.\",\n });\n }\n\n const entries = [\n ...Object.entries(snapshot.features).map(([name, e]) => ({\n name,\n kind: \"feature\" as const,\n description: e.description,\n files: e.files,\n verifiedAt: e.verifiedAt,\n })),\n ...Object.entries(snapshot.flows).map(([name, e]) => ({\n name,\n kind: \"flow\" as const,\n description: e.description,\n files: e.chain,\n verifiedAt: e.verifiedAt,\n })),\n ];\n\n entries.sort((a, b) => {\n if (!a.verifiedAt && !b.verifiedAt) return a.name.localeCompare(b.name);\n if (!a.verifiedAt) return -1;\n if (!b.verifiedAt) return 1;\n return a.verifiedAt.localeCompare(b.verifiedAt);\n });\n\n const access = await createFileAccess(rootDir);\n const picked = entries.slice(0, Math.max(1, sample));\n const toVerify = [];\n for (const entry of picked) {\n const skeletons: Array<{ path: string; content: string } | { path: string; missing: true }> = [];\n for (const filePath of entry.files.slice(0, VERIFY_MAX_FILES_PER_ENTRY)) {\n const full = await access.read(filePath);\n if (full) {\n skeletons.push({\n path: full.path,\n content: full.content.slice(0, VERIFY_SKELETON_CHARS),\n });\n } else {\n skeletons.push({ path: filePath, missing: true });\n }\n }\n toVerify.push({\n name: entry.name,\n kind: entry.kind,\n description: entry.description,\n lastVerified: entry.verifiedAt ?? \"never\",\n skeletons,\n truncated: entry.files.length > VERIFY_MAX_FILES_PER_ENTRY,\n });\n }\n\n const neverVerified = entries.filter((e) => !e.verifiedAt).length;\n\n return JSON.stringify({\n exists: true,\n totalEntries: entries.length,\n neverVerified,\n entries: toVerify,\n instructions:\n \"For each entry, judge from the skeletons whether the listed files actually implement the claimed feature/flow (missing files count against it). Then call save_verification with verdicts: {\\\"<entry name>\\\": {\\\"ok\\\": true|false, \\\"note\\\": \\\"<one line, required when ok is false>\\\"}}. Be skeptical — a plausible description is not evidence; the files must show it.\",\n });\n}\n\nexport async function saveVerification(\n dir: string,\n verdicts: Record<string, { ok: boolean; note?: string }>\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n return JSON.stringify({ exists: false, hint: \"No concept map exists.\" });\n }\n\n const now = new Date().toISOString();\n const verifiedHash = await getCurrentGitHash(rootDir);\n const stamped: string[] = [];\n const unknown: string[] = [];\n const failed: string[] = [];\n\n for (const [name, verdict] of Object.entries(verdicts)) {\n const entry = snapshot.features[name] ?? snapshot.flows[name];\n if (!entry) {\n unknown.push(name);\n continue;\n }\n entry.verifiedAt = now;\n entry.verifiedHash = verifiedHash;\n if (verdict.ok) {\n delete entry.verificationFailed;\n delete entry.verificationNote;\n } else {\n entry.verificationFailed = true;\n entry.verificationNote = verdict.note ?? \"verification failed\";\n failed.push(name);\n }\n stamped.push(name);\n }\n\n snapshot.updatedAt = now;\n await saveSnapshot(rootDir, snapshot);\n\n return JSON.stringify({\n stamped,\n unknown,\n failed,\n hint:\n failed.length > 0\n ? `Entries [${failed.join(\", \")}] are mis-mapped. Re-map them: read their actual files, correct the entries, and call save_snapshot with only those entries (plus removeFeatures/removeFlows if a concept no longer exists).`\n : \"All sampled entries verified. Re-run verify_snapshot periodically — it always picks the least-recently-verified entries next.\",\n });\n}\n\nexport async function saveDecision(\n dir: string,\n input: UpsertDecisionInput\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { upsertDecision } = await import(\"../decisions/decisions.js\");\n const result = await upsertDecision(rootDir, input);\n return JSON.stringify(result);\n}\n\nexport async function reviewDecision(dir: string, input: ReviewDecisionInput): Promise<string> {\n return JSON.stringify(await runDecisionReview(path.resolve(dir), input));\n}\n\nexport async function getContext(\n dir: string,\n task: string,\n files?: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { assembleContext } = await import(\"../context/assemble.js\");\n const bundle = await assembleContext(rootDir, task, files);\n return JSON.stringify(bundle);\n}\n\n// ===== Init MCP tools =====\n\nexport async function masonAutomation(dir: string, action: \"status\" | \"check\"): Promise<string> {\n try {\n const { automate, automationStatus, summarize } = await import(\"../automation/runtime.js\");\n const { installedAutomation } = await import(\"../automation/install.js\");\n if (action === \"status\") return JSON.stringify({ ...await automationStatus(dir), configured: await installedAutomation(dir) });\n if (action !== \"check\") throw new Error(\"Expected status or check.\");\n const { report } = await automate(dir, { event: \"task_end\" });\n const { findings, ...summary } = report;\n return JSON.stringify({ ...summary, findings: findings.slice(0, 5), truncated: findings.length > 5, summary: summarize(report) });\n } catch (error) {\n return JSON.stringify({ status: \"unavailable\", error: error instanceof Error ? error.message : String(error) });\n }\n}\n\nexport async function masonRepair(dir: string, options: { action: \"prepare\" | \"verify\"; baselinePath?: string; checks?: CheckName[] }): Promise<string> {\n try {\n if (options.action === \"verify\") {\n if (!options.baselinePath || options.checks) throw new Error(\"Verification requires baselinePath and uses the original checks; do not pass checks.\");\n return JSON.stringify(await verifyRepair(dir, options.baselinePath), null, 2);\n }\n if (options.action !== \"prepare\" || options.baselinePath) throw new Error(\"Preparation accepts checks, not an existing baselinePath.\");\n const result = await prepareRepair(dir, options.checks);\n return JSON.stringify({ ...result, workOrder: formatFixPrompt(result.report, result.baselinePath) }, null, 2);\n } catch (error) {\n return JSON.stringify({ status: \"unavailable\", error: error instanceof Error ? error.message : String(error) });\n }\n}\n\nexport async function masonInit(dir: string, options: { mode?: InitMode; base?: string; evidence?: string[] } = {}): Promise<string> {\n const rootDir = path.resolve(dir);\n const marker = await loadProjectMarker(rootDir);\n const mode = options.mode ?? \"quickstart\";\n const findings = await inspectOnboarding(rootDir, options.base, options.evidence);\n return JSON.stringify(\n {\n initialized: marker !== null,\n ...(marker ? { initializedAt: marker.initializedAt } : {}),\n confluenceConfigured: marker?.features?.confluence === true,\n mode,\n ...findings,\n playbook: setupPlaybook(mode),\n },\n null,\n 2\n );\n}\n\nexport async function masonCompleteInit(\n dir: string,\n options: { confluenceConfigured?: boolean } = {}\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const existing = await loadProjectMarker(rootDir);\n const marker: ProjectMarker = {\n version: 1,\n initializedAt: existing?.initializedAt ?? new Date().toISOString(),\n features: {\n ...existing?.features,\n confluence: options.confluenceConfigured ?? existing?.features?.confluence ?? false,\n },\n };\n await saveProjectMarker(rootDir, marker);\n return JSON.stringify(\n {\n status: \"initialized\",\n marker,\n hint: \"Assistant setup recorded. Save decisions as you learn, review and commit them, and retrieve them with get_context. A concept map is optional.\",\n },\n null,\n 2\n );\n}\n\n// ===== Confluence MCP tools =====\n\nexport async function masonSetConfluence(input: {\n baseUrl: string;\n email: string;\n apiToken: string;\n spaceKey?: string;\n parentPageId?: string;\n}): Promise<string> {\n const { createConfluenceClient } = await import(\"../confluence/client.js\");\n const { saveConfluenceConfig } = await import(\"../llm/config.js\");\n const { normalizeAtlassianBaseUrl } = await import(\"../confluence/url.js\");\n\n let baseUrl: string;\n try {\n baseUrl = normalizeAtlassianBaseUrl(input.baseUrl);\n } catch (err) {\n return JSON.stringify({\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n if (!input.email.includes(\"@\")) {\n return JSON.stringify({\n status: \"error\",\n error: `Email looks invalid: \"${input.email}\".`,\n });\n }\n if (!input.apiToken.trim()) {\n return JSON.stringify({\n status: \"error\",\n error: \"API token is required.\",\n });\n }\n\n const probeConfig = {\n baseUrl,\n email: input.email,\n apiToken: input.apiToken,\n spaceKey: input.spaceKey ?? \"\",\n parentPageId: input.parentPageId,\n };\n const client = createConfluenceClient(probeConfig);\n\n let spaces;\n try {\n spaces = await client.listSpaces();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(\"401\") || msg.includes(\"403\")) {\n return JSON.stringify({\n status: \"error\",\n error:\n \"Credentials rejected by Confluence. Re-check the email and that the API token hasn't expired or been revoked.\",\n });\n }\n return JSON.stringify({\n status: \"error\",\n error: `Confluence validation failed: ${msg}`,\n });\n }\n\n if (!input.spaceKey) {\n // Step 1 — return spaces for the assistant to relay to the user.\n return JSON.stringify(\n {\n status: \"spaces_listed\",\n baseUrl,\n spaces: spaces.map((s) => ({ key: s.key, name: s.name })),\n hint:\n spaces.length === 0\n ? \"Authenticated, but no spaces are visible to this account. Create one in Confluence first, then re-run mason_set_confluence.\"\n : \"Ask the user which space to use, then call mason_set_confluence again with the same baseUrl/email/apiToken plus the chosen spaceKey.\",\n },\n null,\n 2\n );\n }\n\n const match = spaces.find((s) => s.key === input.spaceKey);\n if (!match) {\n return JSON.stringify({\n status: \"error\",\n error: `Space key \"${input.spaceKey}\" was not found among the spaces visible to this account. Available keys: ${spaces.map((s) => s.key).join(\", \") || \"(none)\"}.`,\n });\n }\n\n await saveConfluenceConfig({\n baseUrl,\n email: input.email,\n apiToken: input.apiToken,\n spaceKey: input.spaceKey,\n parentPageId: input.parentPageId,\n });\n\n return JSON.stringify(\n {\n status: \"saved\",\n spaceKey: input.spaceKey,\n spaceName: match.name,\n hint:\n \"Confluence is configured. The credentials are stored in ~/.mason/config.json. Call export_to_confluence to sync the concept map.\",\n },\n null,\n 2\n );\n}\n\nexport async function exportToConfluenceTool(\n dir: string,\n overrides?: {\n spaceKey?: string;\n parentPageId?: string;\n indexPageTitle?: string;\n changelogPageTitle?: string;\n featurePagePrefix?: string;\n }\n): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const { loadConfig } = await import(\"../llm/config.js\");\n const { exportToConfluence } = await import(\"../confluence/sync.js\");\n\n const config = await loadConfig();\n if (!config?.confluence) {\n return JSON.stringify({\n status: \"error\",\n error:\n 'No Confluence credentials configured. Call mason_set_confluence first.',\n });\n }\n\n const merged = {\n ...config,\n confluence: {\n ...config.confluence,\n spaceKey: overrides?.spaceKey ?? config.confluence.spaceKey,\n parentPageId: overrides?.parentPageId ?? config.confluence.parentPageId,\n },\n };\n\n try {\n const summary = await exportToConfluence(rootDir, merged, {\n indexPageTitle: overrides?.indexPageTitle,\n changelogPageTitle: overrides?.changelogPageTitle,\n featurePagePrefix: overrides?.featurePagePrefix,\n });\n return JSON.stringify({ status: \"ok\", ...summary }, null, 2);\n } catch (err) {\n return JSON.stringify({\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n","import path from \"node:path\";\nimport { computeAudit } from \"./audit.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport { prepareRepair, verifyRepair, formatRepairSummary, repairExitCode } from \"./repair.js\";\nimport type { AuditIssue, AuditReport, CheckName } from \"./types.js\";\n\nexport const USAGE = `Usage: mason-audit [--dir <path>] [--json | --fix-prompt] [--checks <list>]\n\nAudits the repo's AI context files (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md)\nagainst repo reality: referenced paths that no longer exist, undocumented\nmodules, stale counts, dead npm scripts, and manifests newer than the doc.\nDeterministic: no LLM call, no network – safe for CI. Works on any repo with\na context file; no Mason setup required.\n\nOptions:\n --dir <path> Project root to audit (default: current directory)\n --json Print the full audit report as JSON (additive-only schema)\n --fix-prompt When issues exist, print a work order for ANY coding agent\n (Claude, Codex, Gemini, ...) – pipe it to your agent CLI to\n repair the findings. Includes advisories that require review.\n --prepare-repair Save the original audit under .mason/reports/repairs/ before edits\n --verify-repair <path>\n Compare against that saved baseline, using its original checks\n --checks <list> Comma-separated subset of checks to run (default: all):\n ${ALL_CHECKS.join(\", \")}\n --help Show this help\n\nExit codes:\n 0 no issues (advisories may still be present)\n 1 provable issues found\n 2 error (no context file, not a git repository, bad arguments)\n\nWith --verify-repair: 0 verified by the original checks; 1 issues remain;\n2 incomplete (unverified findings, skipped checks, or advisories needing review).\nPreparation writes only a baseline; verification and ordinary audits are read-only.`;\n\nexport interface AuditCliIo {\n out: (line: string) => void;\n err: (line: string) => void;\n}\n\ninterface ParsedArgs {\n dir: string;\n json: boolean;\n fixPrompt: boolean;\n help: boolean;\n checks: CheckName[] | undefined;\n prepareRepair: boolean;\n baseline?: string;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const parsed: ParsedArgs = {\n dir: process.cwd(),\n json: false,\n fixPrompt: false,\n help: false,\n checks: undefined,\n prepareRepair: false,\n };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--json\") {\n parsed.json = true;\n } else if (arg === \"--fix-prompt\") {\n parsed.fixPrompt = true;\n } else if (arg === \"--prepare-repair\") {\n parsed.prepareRepair = true;\n } else if (arg === \"--verify-repair\") {\n const value = argv[++i];\n if (!value || value.startsWith(\"--\")) throw new Error(\"--verify-repair requires a baseline path\");\n parsed.baseline = value;\n } else if (arg === \"--help\" || arg === \"-h\") {\n parsed.help = true;\n } else if (arg === \"--dir\") {\n const value = argv[++i];\n if (!value) throw new Error(\"--dir requires a path argument\");\n parsed.dir = value;\n } else if (arg === \"--checks\") {\n const value = argv[++i];\n if (!value) throw new Error(\"--checks requires a comma-separated list\");\n const names = value.split(\",\").map((n) => n.trim()).filter(Boolean);\n if (!names.length) throw new Error(\"--checks requires at least one check\");\n for (const name of names) {\n if (!ALL_CHECKS.includes(name as CheckName)) {\n throw new Error(\n `Unknown check: ${name} (valid: ${ALL_CHECKS.join(\", \")})`\n );\n }\n }\n parsed.checks = names as CheckName[];\n } else if (!arg.startsWith(\"-\") && parsed.dir === process.cwd()) {\n parsed.dir = arg;\n } else {\n throw new Error(`Unknown argument: ${arg}`);\n }\n }\n return parsed;\n}\n\nfunction issueLine(issue: AuditIssue): string {\n const where =\n issue.anchor.line !== null ? `line ${issue.anchor.line}` : \"doc-level\";\n const likely = issue.confidence === \"likely\" ? \" (likely)\" : \"\";\n return ` [${issue.type}]${likely} ${where}: ${issue.message}`;\n}\n\nexport function formatAuditSummary(report: AuditReport): string {\n const lines: string[] = [];\n const reviewCount = report.advisories.length + (report.suppressedAdvisories?.length ?? 0);\n\n for (const doc of report.docs) {\n const docIssues = report.issues.filter((i) => i.anchor.doc === doc.path);\n const committed = doc.lastCommit\n ? `last committed ${doc.lastCommit.date.slice(0, 10)}, ${doc.lastCommit.hash.slice(0, 7)}`\n : \"untracked\";\n if (docIssues.length === 0) {\n lines.push(`${doc.path} – clean (${committed})`);\n continue;\n }\n lines.push(\n `${doc.path} – ${docIssues.length} issue${docIssues.length === 1 ? \"\" : \"s\"} (${committed})`\n );\n for (const issue of docIssues) lines.push(issueLine(issue));\n }\n\n // Issues anchored outside the docs list (defensive; new-module anchors to\n // the primary doc, so this should stay empty).\n const docPaths = new Set(report.docs.map((d) => d.path));\n for (const issue of report.issues) {\n if (!docPaths.has(issue.anchor.doc)) lines.push(issueLine(issue));\n }\n\n if (report.advisories.length > 0) {\n lines.push(\"Advisories (do not affect the exit code):\");\n for (const advisory of report.advisories) {\n lines.push(` [${advisory.type}] ${advisory.anchor.doc}: ${advisory.message}`);\n }\n }\n if (report.skippedChecks.length > 0) {\n for (const skip of report.skippedChecks) {\n lines.push(` [skipped] ${skip.check}: ${skip.reason}`);\n }\n }\n\n for (const advisory of report.suppressedAdvisories ?? []) {\n lines.push(` [suppressed; unresolved] ${advisory.type} ${advisory.anchor.doc}: ${advisory.message}`);\n }\n\n lines.push(\n report.clean\n ? reviewCount || report.skippedChecks.length\n ? `No audit issues detected (${report.docs.length} docs audited); ${reviewCount} advisories remain for review, ${report.skippedChecks.length} checks skipped.`\n : `Context files are clean (${report.docs.length} doc${report.docs.length === 1 ? \"\" : \"s\"} audited).`\n : `${report.issues.length} issue${report.issues.length === 1 ? \"\" : \"s\"} across ${report.docs.length} doc${report.docs.length === 1 ? \"\" : \"s\"}.`\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Provider-neutral work order: any coding agent can execute it. The evidence\n * is deterministic; the agent's job is judgment scoped to exactly these\n * claims – never a free-form doc rewrite.\n */\nexport function formatFixPrompt(report: AuditReport, baselinePath?: string): string {\n const flaggedDocs = [...new Set(report.issues.map((i) => i.anchor.doc))];\n const lines: string[] = [];\n lines.push(\n \"Review the flagged context claims using the evidence below. Make minimal repairs within the user's authorized scope. A setup-only or audit-only request does not authorize rewriting existing documentation.\"\n );\n lines.push(\"\");\n lines.push(\"RULES:\");\n lines.push(baselinePath\n ? `- Preserve the original repair baseline: ${JSON.stringify(baselinePath)}. Do not replace it after editing.`\n : \"- Before the first edit, call mason_repair with action: prepare, or run mason-audit --prepare-repair --json with the same --dir and --checks. Keep the returned baselinePath through verification.\");\n lines.push(\n `- Edit ONLY these files: ${flaggedDocs.join(\", \") || \"none (advisory review only)\"}. Bring the docs into agreement with verified source evidence; do not change source code or configs to silence findings.`\n );\n lines.push(\n \"- Keep diffs minimal: change the smallest span that makes each claim true.\"\n );\n lines.push(\n \"- Never invent content. Every replacement must be grounded in the evidence below or in files you read from this repository.\"\n );\n lines.push(\"- Inspect likely findings before editing: heuristic evidence may describe an intentional omission or an example.\");\n lines.push(\n \"- deleted-reference: if evidence shows renamedTo, update the path; otherwise remove the reference, or rephrase to past tense if the sentence is about history. Deleted paths inside directory trees: delete the tree line.\"\n );\n lines.push(\n \"- stale-count: replace the number with the actual count from the evidence.\"\n );\n lines.push(\n \"- dead-command: replace with the correct script from availableScripts if an obvious rename exists; otherwise remove the command mention.\"\n );\n lines.push(\n \"- new-module: add a one-line factual mention of the directory where sibling modules are described; read the directory's files first and describe only what you verified.\"\n );\n lines.push(\n \"- ADVISORIES require a separate assessment of the cited commits or decision evidence. Report any review you perform and what remains unknown. Their disappearance after edits or a commit does not establish review or approval.\"\n );\n lines.push(\"\");\n lines.push(\"AUDIT REPORT (current context files and repository evidence, including local edits):\");\n lines.push(\n JSON.stringify(\n { root: report.root, checks: report.checksRun, issues: report.issues, advisories: report.advisories,\n suppressedAdvisories: report.suppressedAdvisories, skippedChecks: report.skippedChecks },\n null,\n 2\n )\n );\n lines.push(\"\");\n lines.push(\n \"After edits, call mason_repair with action: verify and the original baselinePath, or mason-audit --verify-repair <baselinePath> --dir <project>. Repeat against the same baseline after any final documentation commit. Summarize resolved, unresolved, review-required, unverified, and new findings with their evidence. Do not report a suppressed or unavailable check as fixed. This audit covers the listed context files; independently discovered README or application issues need their own validation.\"\n );\n return lines.join(\"\\n\");\n}\n\nexport async function runAuditCli(\n argv: string[],\n io: AuditCliIo = {\n out: (line) => process.stdout.write(`${line}\\n`),\n err: (line) => process.stderr.write(`${line}\\n`),\n }\n): Promise<number> {\n let args: ParsedArgs;\n try {\n args = parseArgs(argv);\n if (args.json && args.fixPrompt) {\n throw new Error(\"--json and --fix-prompt are mutually exclusive\");\n }\n if (args.baseline && (args.prepareRepair || args.checks || args.fixPrompt)) {\n throw new Error(\"--verify-repair cannot be combined with --prepare-repair, --checks, or --fix-prompt; verification uses the original scope\");\n }\n } catch (error) {\n io.err(error instanceof Error ? error.message : String(error));\n io.err(USAGE);\n return 2;\n }\n\n if (args.help) {\n io.out(USAGE);\n return 0;\n }\n\n const rootDir = path.resolve(args.dir);\n if (args.baseline || args.prepareRepair) {\n try {\n if (args.baseline) {\n const verification = await verifyRepair(rootDir, args.baseline);\n io.out(args.json ? JSON.stringify(verification, null, 2) : formatRepairSummary(verification));\n return repairExitCode(verification);\n }\n const prepared = await prepareRepair(rootDir, args.checks);\n io.out(args.json ? JSON.stringify({ ...prepared, workOrder: formatFixPrompt(prepared.report, prepared.baselinePath) }, null, 2)\n : args.fixPrompt ? formatFixPrompt(prepared.report, prepared.baselinePath)\n : `Repair baseline: ${prepared.baselinePath}\\n${formatAuditSummary(prepared.report)}`);\n return prepared.report.clean ? 0 : 1;\n } catch (error) {\n io.err(error instanceof Error ? error.message : String(error));\n return 2;\n }\n }\n const report = await computeAudit(rootDir, { checks: args.checks });\n\n if (!report) {\n io.err(\n `No CLAUDE.md, .claude/CLAUDE.md, or AGENTS.md found in ${rootDir}.`\n );\n return 2;\n }\n\n if (!report.gitAvailable) {\n io.err(\n `Could not determine git HEAD in ${rootDir} – not a git repository, or git is unavailable.`\n );\n return 2;\n }\n\n if (args.fixPrompt) {\n io.out(\n report.clean && !report.advisories.length && !report.suppressedAdvisories?.length\n ? formatAuditSummary(report) : formatFixPrompt(report)\n );\n return report.clean ? 0 : 1;\n }\n\n if (args.json) {\n io.out(JSON.stringify(report, null, 2));\n } else {\n io.out(formatAuditSummary(report));\n }\n return report.clean ? 0 : 1;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { BaseAnalyzer } from \"./base.js\";\nimport type { AnalyzerContext, AnalyzerResult, Finding, Gap } from \"../types.js\";\n\nconst exec = promisify(execFile);\n\nexport class GitHistoryAnalyzer extends BaseAnalyzer {\n name = \"git-history\";\n\n async analyze(context: AnalyzerContext): Promise<AnalyzerResult> {\n const startTime = Date.now();\n const findings: Finding[] = [];\n const gaps: Gap[] = [];\n\n if (!context.gitAvailable) {\n return this.createResult([], [], startTime);\n }\n\n const [staleFindings, staleGaps] = await this.findStaleDirectories(context);\n findings.push(...staleFindings);\n gaps.push(...staleGaps);\n\n const hotFindings = await this.findHotFiles(context);\n findings.push(...hotFindings);\n\n const commitFindings = await this.analyzeCommitPatterns(context);\n findings.push(...commitFindings);\n\n return this.createResult(findings, gaps, startTime);\n }\n\n private async git(\n args: string[],\n cwd: string\n ): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", args, { cwd, maxBuffer: 10_000_000 });\n return stdout.trim();\n } catch {\n return \"\";\n }\n }\n\n private async findStaleDirectories(\n context: AnalyzerContext\n ): Promise<[Finding[], Gap[]]> {\n const findings: Finding[] = [];\n const gaps: Gap[] = [];\n\n // Get top-level directories with their last commit date\n const output = await this.git(\n [\"log\", \"--all\", \"--format=%ci\", \"--name-only\", \"--diff-filter=AMCR\", \"-n\", \"500\"],\n context.rootDir\n );\n\n if (!output) return [findings, gaps];\n\n const dirLastTouch = new Map<string, Date>();\n let currentDate: Date | null = null;\n\n for (const line of output.split(\"\\n\")) {\n if (!line) continue;\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(line)) {\n currentDate = new Date(line);\n } else if (currentDate) {\n const topDir = line.split(\"/\")[0];\n if (\n topDir &&\n !topDir.startsWith(\".\") &&\n !topDir.includes(\"node_modules\")\n ) {\n const existing = dirLastTouch.get(topDir);\n if (!existing || currentDate > existing) {\n dirLastTouch.set(topDir, currentDate);\n }\n }\n }\n }\n\n const sixMonthsAgo = new Date();\n sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);\n\n for (const [dir, lastTouch] of dirLastTouch) {\n if (lastTouch < sixMonthsAgo) {\n const monthsStale = Math.floor(\n (Date.now() - lastTouch.getTime()) / (1000 * 60 * 60 * 24 * 30)\n );\n findings.push(\n this.createFinding({\n category: \"risk\",\n confidence: 0.7,\n summary: `Directory \"${dir}\" hasn't been modified in ${monthsStale} months`,\n evidence: [\n { filePath: dir, detail: `Last commit: ${lastTouch.toISOString().split(\"T\")[0]}` },\n ],\n ruleCandidate: `Do not refactor or modify files in \"${dir}/\" unless explicitly asked — this area has been stable for ${monthsStale} months and may be legacy code.`,\n })\n );\n gaps.push({\n analyzer: this.name,\n question: `Directory \"${dir}\" hasn't been touched in ${monthsStale} months. Is it deprecated, stable, or legacy?`,\n context: `Last modified: ${lastTouch.toISOString().split(\"T\")[0]}`,\n answerKey: `stale-dir-${dir}`,\n });\n }\n }\n\n return [findings, gaps];\n }\n\n private async findHotFiles(context: AnalyzerContext): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n // Most frequently changed files in the last 3 months\n const output = await this.git(\n [\"log\", \"--since=3 months ago\", \"--format=\", \"--name-only\"],\n context.rootDir\n );\n\n if (!output) return findings;\n\n const fileCounts = new Map<string, number>();\n for (const line of output.split(\"\\n\")) {\n if (!line || line.startsWith(\".\") || line.includes(\"node_modules\")) continue;\n fileCounts.set(line, (fileCounts.get(line) ?? 0) + 1);\n }\n\n const sorted = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10);\n\n if (sorted.length > 0 && sorted[0][1] >= 5) {\n const hotFiles = sorted.filter(([, count]) => count >= 5);\n if (hotFiles.length > 0) {\n findings.push(\n this.createFinding({\n category: \"risk\",\n confidence: 0.8,\n summary: `${hotFiles.length} files changed frequently in the last 3 months`,\n evidence: hotFiles.map(([file, count]) => ({\n filePath: file,\n detail: `${count} commits`,\n })),\n ruleCandidate: `These files change frequently and are high-risk for conflicts: ${hotFiles.map(([f]) => f).join(\", \")}. Take extra care when modifying them.`,\n })\n );\n }\n }\n\n return findings;\n }\n\n private async analyzeCommitPatterns(\n context: AnalyzerContext\n ): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n const output = await this.git(\n [\"log\", \"--format=%s\", \"-n\", \"100\"],\n context.rootDir\n );\n\n if (!output) return findings;\n\n const messages = output.split(\"\\n\").filter(Boolean);\n\n // Check for conventional commits\n const conventionalPattern = /^(feat|fix|chore|docs|style|refactor|test|perf|ci|build|revert)(\\(.+\\))?:/;\n const conventionalCount = messages.filter((m) =>\n conventionalPattern.test(m)\n ).length;\n const conventionalRatio = conventionalCount / messages.length;\n\n if (conventionalRatio > 0.5) {\n findings.push(\n this.createFinding({\n category: \"convention\",\n confidence: Math.min(conventionalRatio + 0.1, 1),\n summary: `${Math.round(conventionalRatio * 100)}% of recent commits use conventional commit format`,\n evidence: [\n {\n filePath: \".git\",\n detail: `${conventionalCount} of ${messages.length} commits match`,\n },\n ],\n ruleCandidate:\n \"Use conventional commit format: type(scope): description (e.g., feat(auth): add login endpoint)\",\n })\n );\n }\n\n // Check for ticket/issue references\n const ticketPattern = /[A-Z]+-\\d+|#\\d+/;\n const ticketCount = messages.filter((m) => ticketPattern.test(m)).length;\n const ticketRatio = ticketCount / messages.length;\n\n if (ticketRatio > 0.3) {\n findings.push(\n this.createFinding({\n category: \"convention\",\n confidence: ticketRatio,\n summary: `${Math.round(ticketRatio * 100)}% of commits reference issue/ticket IDs`,\n evidence: [\n {\n filePath: \".git\",\n detail: `${ticketCount} of ${messages.length} commits have ticket refs`,\n },\n ],\n ruleCandidate:\n \"Include issue/ticket references in commit messages when applicable.\",\n })\n );\n }\n\n return findings;\n }\n}\n","import fs from \"node:fs/promises\";\nimport fg from \"fast-glob\";\nimport type {\n AnalyzerContext,\n AnalyzerResult,\n Finding,\n FindingCategory,\n} from \"../types.js\";\n\nexport abstract class BaseAnalyzer {\n abstract name: string;\n abstract analyze(context: AnalyzerContext): Promise<AnalyzerResult>;\n\n protected async findFiles(\n patterns: string[],\n root: string\n ): Promise<string[]> {\n return fg(patterns, {\n cwd: root,\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/.git/**\"],\n absolute: true,\n });\n }\n\n protected async readFile(filePath: string): Promise<string> {\n return fs.readFile(filePath, \"utf-8\");\n }\n\n protected createFinding(partial: {\n category: FindingCategory;\n confidence: number;\n summary: string;\n evidence?: Finding[\"evidence\"];\n ruleCandidate?: string | null;\n }): Finding {\n return {\n analyzer: this.name,\n category: partial.category,\n confidence: partial.confidence,\n summary: partial.summary,\n evidence: partial.evidence ?? [],\n ruleCandidate: partial.ruleCandidate ?? null,\n };\n }\n\n protected createResult(\n findings: Finding[],\n gaps: AnalyzerResult[\"gaps\"],\n startTime: number\n ): AnalyzerResult {\n return {\n analyzer: this.name,\n findings,\n gaps,\n durationMs: Date.now() - startTime,\n };\n }\n}\n","import type { AnalyzerContext, AnalyzerResult } from \"../types.js\";\nimport type { BaseAnalyzer } from \"./base.js\";\nimport { GitHistoryAnalyzer } from \"./git-history.js\";\n\nconst analyzers: BaseAnalyzer[] = [new GitHistoryAnalyzer()];\n\nexport async function runAll(\n context: AnalyzerContext\n): Promise<AnalyzerResult[]> {\n return Promise.all(analyzers.map((a) => a.analyze(context)));\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\nexport async function isGitRepo(dir: string): Promise<boolean> {\n try {\n await exec(\"git\", [\"rev-parse\", \"--git-dir\"], { cwd: dir });\n return true;\n } catch {\n return false;\n }\n}\n","import path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess, SOURCE_EXTENSIONS } from \"../utils/files.js\";\nexport type { ProjectConfig } from \"../utils/files.js\";\n\nconst exec = promisify(execFile);\n\nconst CONFIG_FILES = [\n // Build & project config\n \"package.json\",\n \"tsconfig.json\",\n \"build.gradle.kts\",\n \"build.gradle\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"Gemfile\",\n \"*.csproj\",\n // Version catalogs & dependency locks\n \"gradle/libs.versions.toml\",\n // Code quality & formatting\n \".editorconfig\",\n \".eslintrc.*\",\n \"eslint.config.*\",\n \".prettierrc\",\n \"rustfmt.toml\",\n \".swiftlint.yml\",\n // CI/CD\n \".github/workflows/*.yml\",\n \".gitlab-ci.yml\",\n \"Jenkinsfile\",\n // Containerization\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"docker-compose.yaml\",\n];\n\nconst ENTRY_POINT_PATTERNS = [\n \"src/main.*\",\n \"src/index.*\",\n \"src/app.*\",\n \"main.*\",\n \"index.*\",\n \"app.*\",\n \"App.*\",\n \"**/Main.kt\",\n \"**/Application.kt\",\n \"**/main.py\",\n \"**/main.go\",\n \"**/main.rs\",\n \"**/lib.rs\",\n \"**/Program.cs\",\n];\n\n// Filename patterns that reveal architectural patterns and conventions.\n// These are language-agnostic — the suffixes appear across ecosystems.\n// Ordered by architectural importance — most distinctive patterns first.\nconst ARCHITECTURAL_PATTERNS = [\n // State/data flow\n { glob: \"**/*ViewModel.*\", category: \"state\", reason: \"viewmodel (state management)\" },\n { glob: \"**/*Store.*\", category: \"state\", reason: \"store (state management)\" },\n { glob: \"**/*Reducer.*\", category: \"state\", reason: \"reducer (state management)\" },\n // Data layer — interface\n { glob: \"**/*Repository.*\", category: \"data-interface\", reason: \"repository interface (data layer contract)\" },\n { glob: \"**/*Dao.*\", category: \"data-interface\", reason: \"DAO (data access)\" },\n { glob: \"**/*DataSource.*\", category: \"data-interface\", reason: \"data source\" },\n // Data layer — implementation (where actual patterns live: mappers, retry, IO dispatchers)\n { glob: \"**/*RepositoryImpl.*\", category: \"data-impl\", reason: \"repository implementation (data layer patterns)\" },\n { glob: \"**/*ServiceImpl.*\", category: \"data-impl\", reason: \"service implementation\" },\n { glob: \"**/*Impl.*\", category: \"data-impl\", reason: \"implementation (concrete patterns)\" },\n // Data transformation\n { glob: \"**/*Mapper.*\", category: \"transform\", reason: \"mapper (data transformation)\" },\n { glob: \"**/*Converter.*\", category: \"transform\", reason: \"converter (data transformation)\" },\n { glob: \"**/*Adapter.*\", category: \"transform\", reason: \"adapter (interface adaptation)\" },\n // Dependency injection / wiring\n { glob: \"**/*Module.*\", category: \"di\", reason: \"module (DI/wiring)\" },\n { glob: \"**/*Provider.*\", category: \"di\", reason: \"provider (DI/wiring)\" },\n { glob: \"**/*Container.*\", category: \"di\", reason: \"container (DI/wiring)\" },\n { glob: \"**/*Factory.*\", category: \"di\", reason: \"factory (object creation)\" },\n // API / network\n { glob: \"**/*Service.*\", category: \"api\", reason: \"service (business/API layer)\" },\n { glob: \"**/*Client.*\", category: \"api\", reason: \"client (API/network layer)\" },\n { glob: \"**/*Api.*\", category: \"api\", reason: \"API interface definition\" },\n // Interface contracts / protocols\n { glob: \"**/*Interface.*\", category: \"contract\", reason: \"interface definition\" },\n { glob: \"**/*Protocol.*\", category: \"contract\", reason: \"protocol definition\" },\n { glob: \"**/*Trait.*\", category: \"contract\", reason: \"trait definition\" },\n // Routing / navigation\n { glob: \"**/*Router.*\", category: \"routing\", reason: \"router (navigation/routing)\" },\n { glob: \"**/*Route.*\", category: \"routing\", reason: \"route definition\" },\n { glob: \"**/*NavHost.*\", category: \"routing\", reason: \"navigation host\" },\n { glob: \"**/*Controller.*\", category: \"routing\", reason: \"controller (request handling)\" },\n { glob: \"**/*Handler.*\", category: \"routing\", reason: \"handler (request handling)\" },\n // Middleware / interceptors\n { glob: \"**/*Middleware.*\", category: \"middleware\", reason: \"middleware (request pipeline)\" },\n { glob: \"**/*Interceptor.*\", category: \"middleware\", reason: \"interceptor (cross-cutting)\" },\n { glob: \"**/*Plugin.*\", category: \"middleware\", reason: \"plugin (extensibility)\" },\n // Models / types\n { glob: \"**/*Model.*\", category: \"model\", reason: \"model (domain types)\" },\n { glob: \"**/*Entity.*\", category: \"model\", reason: \"entity (persistence types)\" },\n { glob: \"**/*Dto.*\", category: \"model\", reason: \"DTO (data transfer types)\" },\n { glob: \"**/*Schema.*\", category: \"model\", reason: \"schema (data validation)\" },\n // Use cases / commands\n { glob: \"**/*UseCase.*\", category: \"usecase\", reason: \"use case (business logic)\" },\n { glob: \"**/*Interactor.*\", category: \"usecase\", reason: \"interactor (business logic)\" },\n { glob: \"**/*Command.*\", category: \"usecase\", reason: \"command (CQRS pattern)\" },\n];\n\nconst PREVIEW_LINES = 60;\n\nexport interface SampledFile {\n path: string;\n preview: string;\n totalLines: number;\n sizeBytes: number;\n reason: string;\n}\n\nexport async function sampleFiles(\n rootDir: string,\n maxFiles: number = 25\n): Promise<SampledFile[]> {\n const selected = new Map<string, string>(); // path -> reason\n const access = await createFileAccess(rootDir);\n const projectConfig = access.config;\n\n // 0. Always-include files from project config (highest priority)\n for (const filePath of projectConfig.alwaysInclude ?? []) {\n if (selected.size >= maxFiles) break;\n // Validate path stays within project root\n const resolvedPath = path.resolve(rootDir, filePath);\n if (!resolvedPath.startsWith(path.resolve(rootDir))) continue;\n selected.set(filePath, \"always-include (project config)\");\n }\n\n // 1. Config files (cap at 5)\n let configCount = 0;\n for (const pattern of CONFIG_FILES) {\n if (configCount >= 5) break;\n const matches = await access.list(pattern, {\n deep: 3,\n });\n for (const match of matches) {\n if (configCount >= 5 || selected.size >= maxFiles) break;\n selected.set(match, \"config file\");\n configCount++;\n }\n }\n\n // 2. Module build/config files — build files from subdirectories reveal dependency graph\n const moduleBuildPatterns = [\n // Gradle\n \"**/build.gradle.kts\",\n \"**/build.gradle\",\n // Cargo workspace members\n \"**/Cargo.toml\",\n // Node workspaces\n \"**/package.json\",\n // Go sub-modules\n \"**/go.mod\",\n ];\n let moduleBuildCount = 0;\n for (const pattern of moduleBuildPatterns) {\n const matches = await access.list(pattern, {\n deep: 4,\n });\n // Skip root-level files (already captured as config)\n const subMatches = matches.filter((m) => m.includes(\"/\"));\n for (const match of subMatches) {\n if (moduleBuildCount >= 4 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"module build file (reveals dependency graph)\");\n moduleBuildCount++;\n }\n }\n if (moduleBuildCount >= 4) break;\n }\n\n // 3. Entry points (cap at 2)\n let entryCount = 0;\n for (const pattern of ENTRY_POINT_PATTERNS) {\n if (entryCount >= 2) break;\n const matches = await access.list(pattern, {\n deep: 5,\n });\n for (const match of matches) {\n if (entryCount >= 2 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"entry point\");\n entryCount++;\n }\n }\n }\n\n // 4. Hot files from git (up to 5)\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"--since=3 months ago\", \"--format=\", \"--name-only\"],\n { cwd: rootDir, maxBuffer: 5_000_000 }\n );\n\n const fileCounts = new Map<string, number>();\n for (const line of stdout.split(\"\\n\")) {\n if (!line) continue;\n if (\n line.includes(\"node_modules\") ||\n line.includes(\"/build/\") ||\n line.includes(\".gradle\") ||\n line.includes(\"/generated/\")\n )\n continue;\n const ext = path.extname(line).slice(1);\n if (!SOURCE_EXTENSIONS.includes(ext)) continue;\n fileCounts.set(line, (fileCounts.get(line) ?? 0) + 1);\n }\n\n const hotFiles = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5);\n\n for (const [file, count] of hotFiles) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, `frequently changed (${count} commits in 3 months)`);\n }\n }\n } catch {\n // No git\n }\n\n // 5. Architectural pattern files — one per category (cap at 8)\n const seenCategories = new Set<string>();\n let patternCount = 0;\n for (const pattern of ARCHITECTURAL_PATTERNS) {\n if (patternCount >= 8 || selected.size >= maxFiles) break;\n if (seenCategories.has(pattern.category)) continue;\n\n const matches = await access.list(pattern.glob, {\n });\n\n if (matches.length > 0) {\n for (const match of matches) {\n if (!selected.has(match)) {\n selected.set(match, pattern.reason);\n seenCategories.add(pattern.category);\n patternCount++;\n break;\n }\n }\n }\n }\n\n // 5b. Custom patterns from project config\n for (const customGlob of projectConfig.patterns ?? []) {\n if (selected.size >= maxFiles) break;\n const matches = await access.list(customGlob, {\n });\n for (const match of matches) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"custom pattern (project config)\");\n break; // one per pattern\n }\n }\n }\n\n // 6. Test examples — diverse across file types (cap at 3)\n const testPatternGroups = [\n // JS/TS tests\n { patterns: [\"**/*.test.*\", \"**/*.spec.*\"], label: \"JS/TS test\" },\n // JVM tests\n { patterns: [\"**/*Test.kt\", \"**/*Test.java\"], label: \"JVM test\" },\n // Python tests\n { patterns: [\"**/test_*.py\", \"**/*_test.py\"], label: \"Python test\" },\n // Go tests\n { patterns: [\"**/*_test.go\"], label: \"Go test\" },\n // Swift tests\n { patterns: [\"**/*Tests.swift\", \"**/*Test.swift\"], label: \"Swift test\" },\n // Rust tests\n { patterns: [\"**/*_test.rs\"], label: \"Rust test\" },\n ];\n let testCount = 0;\n for (const group of testPatternGroups) {\n if (testCount >= 3 || selected.size >= maxFiles) break;\n const testFiles = await access.list(group.patterns, {\n });\n if (testFiles.length > 0) {\n for (const file of testFiles) {\n if (!selected.has(file)) {\n selected.set(file, `test example (${group.label})`);\n testCount++;\n break;\n }\n }\n }\n }\n\n // 7. Directory breadth — fill remaining slots with one file per top-level dir\n const sourceGlobs = SOURCE_EXTENSIONS.map((ext) => `**/*.${ext}`);\n const allSourceFiles = await access.list(sourceGlobs, {\n });\n\n const dirRepresentatives = new Map<string, string>();\n const boringFiles = /\\.(gradle|gradle\\.kts|json|toml|yaml|yml|xml|properties)$/;\n for (const file of allSourceFiles) {\n const topDir = file.split(\"/\")[0];\n if (!dirRepresentatives.has(topDir) && !boringFiles.test(file)) {\n dirRepresentatives.set(topDir, file);\n }\n }\n\n for (const [, file] of dirRepresentatives) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, \"directory representative\");\n }\n }\n\n // Read file previews\n const results: SampledFile[] = [];\n for (const [filePath, reason] of selected) {\n try {\n const full = await access.read(filePath);\n if (!full || Buffer.byteLength(full.content) > 100_000) continue;\n const lines = full.content.split(\"\\n\");\n const preview = lines.slice(0, PREVIEW_LINES).join(\"\\n\");\n\n results.push({\n path: filePath,\n preview,\n totalLines: lines.length,\n sizeBytes: Buffer.byteLength(full.content),\n reason,\n });\n } catch {\n // Skip\n }\n }\n\n return results;\n}\n\nexport async function readFullFile(\n rootDir: string,\n filePath: string\n): Promise<{ path: string; content: string; totalLines: number } | null> {\n return (await createFileAccess(rootDir)).read(filePath);\n}\n","import { createHash } from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { z } from \"zod\";\nimport { loadDecisionStore, saveDecisionRecord, withDecisionWrite } from \"./decisions.js\";\nimport { decisionApproval, decisionAnchors, decisionContent, decisionProvenance, effectiveDecision, importLegacy, type DecisionRecord, type ReviewedDecisionRecord } from \"./provenance.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getChangesWithStatus, getWorkingTree, touchedPaths } from \"../drift/drift.js\";\nimport { anchorMatches, matchingPaths } from \"../utils/paths.js\";\nimport { createFileAccess } from \"../utils/files.js\";\n\nconst exec = promisify(execFile);\nconst requestSchema = z.object({\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/),\n action: z.enum([\"prepare\", \"accept\", \"reaffirm\", \"retire\"]).default(\"prepare\"),\n reviewer: z.string().trim().min(1).max(200).optional(),\n note: z.string().trim().min(1).max(1500).optional(),\n reviewToken: z.string().regex(/^[a-f0-9]{64}$/).optional(),\n});\nexport type ReviewDecisionInput = z.input<typeof requestSchema>;\n\nasync function reviewState(root: string, record: DecisionRecord) {\n const [headHash, workingTree, changes] = await Promise.all([\n getCurrentGitHash(root), getWorkingTree(root), getChangesWithStatus(root, record.refreshedHash),\n ]);\n const anchors = decisionAnchors(record);\n const committed = (changes ?? []).filter(c => [c.path, ...(c.previousPath ? [c.previousPath] : [])].some(file => anchors.some(anchor => anchorMatches(anchor, file))));\n const evidence = {\n baseHash: record.refreshedHash, headHash, historyAvailable: changes !== null,\n changedFiles: touchedPaths(committed), localChanges: matchingPaths(anchors, workingTree.changedFiles),\n };\n const reviewToken = createHash(\"sha256\").update(JSON.stringify({ record, evidence, workingTreeAvailable: workingTree.available })).digest(\"hex\");\n return { reviewToken, evidence, committed, workingTreeAvailable: workingTree.available };\n}\n\nasync function previews(root: string, record: DecisionRecord, state: Awaited<ReturnType<typeof reviewState>>) {\n const access = await createFileAccess(root);\n const anchors = decisionAnchors(record);\n const candidates = [...new Set([...state.evidence.changedFiles, ...state.evidence.localChanges, ...anchors,\n ...(await access.list()).filter(file => anchors.some(anchor => anchorMatches(anchor, file))),\n ])];\n const files: Array<{ path: string; preview: string; totalLines: number }> = [];\n const omittedFiles: string[] = [];\n const diffPaths: string[] = [];\n for (const file of candidates) {\n if (files.length >= 6) { omittedFiles.push(file); continue; }\n const source = await access.read(file);\n if (!source) { omittedFiles.push(file); continue; }\n files.push({ path: source.path, preview: source.content.slice(0, 2000), totalLines: source.totalLines });\n if (state.evidence.changedFiles.includes(file)) diffPaths.push(file);\n }\n let diff: string | null = null;\n let diffUnavailable: string | undefined;\n if (state.evidence.historyAvailable && diffPaths.length) {\n try {\n const { stdout } = await exec(\"git\", [\"--literal-pathspecs\", \"diff\", \"--no-ext-diff\", \"--no-textconv\", \"--no-color\", \"--no-renames\", \"-U3\", record.refreshedHash, state.evidence.headHash, \"--\", ...diffPaths], { cwd: root, maxBuffer: 1024 * 1024 });\n diff = stdout.slice(0, 16000);\n if (stdout.length > diff.length) diffUnavailable = \"Diff preview was truncated; inspect the full diff before reviewing.\";\n } catch { diffUnavailable = \"Diff preview could not be read within its size bound; inspect the diff separately.\"; }\n }\n return { files, diff, diffUnavailable, omittedFiles, hint: \"Bounded source and diff previews only. Deleted, excluded, sensitive, oversized, or additional files may be omitted. Inspect relevant evidence beyond these previews before recording a verdict.\" };\n}\n\n/** Prepare first, then attest to that exact record and committed code revision. */\nexport async function reviewDecision(root: string, input: ReviewDecisionInput) {\n const parsed = requestSchema.safeParse(input);\n if (!parsed.success) return { status: \"error\", error: parsed.error.message };\n const request = parsed.data;\n const read = async () => {\n const store = await loadDecisionStore(root);\n return { ...store, record: store.records.find(record => record.id === request.id) };\n };\n if (request.action === \"prepare\") {\n const { record, diagnostics } = await read();\n if (!record) return { status: \"error\", error: `No readable decision with id \"${request.id}\"`, diagnostics };\n const state = await reviewState(root, record);\n const operativeDecision = effectiveDecision(record);\n return {\n status: \"prepared\", record, ...(operativeDecision !== record ? { operativeDecision } : {}), provenance: decisionProvenance(record), ...state, diagnostics,\n previews: await previews(root, record, state),\n hint: \"Inspect the proposed content, operativeDecision, sources, history, and code changes. A pending proposal leaves the prior accepted revision operative; accepting it replaces that revision, and retirement withdraws the entire decision including its proposal. Evidence covers both revisions' anchors. Only record acceptance or reaffirmation when the user or cited team review has authorized it. Supply that reviewer's identity, a reason, and this reviewToken. Do not invent identities or infer agreement from unchanged code. Acceptance and reaffirmation require committed anchor changes; retirement is available independently. Missing old history remains visible in the event even if a reviewer establishes a new baseline at HEAD. Saved reviews are local assertions for normal PR review, not authenticated approvals.\",\n };\n }\n if (!request.reviewer || !request.note || !request.reviewToken) return { status: \"error\", error: \"Prepare the review first, then provide reviewToken, reviewer, and note.\" };\n return withDecisionWrite(root, async () => {\n const { record: original, diagnostics } = await read();\n if (diagnostics.length) return { status: \"error\", error: \"Repair malformed decision records before recording a review.\", diagnostics };\n if (!original) return { status: \"error\", error: `No decision with id \"${request.id}\"` };\n const state = await reviewState(root, original);\n if (state.reviewToken !== request.reviewToken) return { status: \"conflict\", error: \"The decision or code revision changed after preparation. Prepare and inspect a new review.\" };\n if (original.status !== \"active\") return { status: \"error\", error: \"Archived decisions cannot be reviewed again; create a new proposal.\" };\n const approval = decisionApproval(original);\n if (request.action === \"accept\" && approval === \"accepted\") return { status: \"error\", error: \"This decision is already accepted. Use reaffirm to record a new review.\" };\n if (request.action === \"reaffirm\" && approval !== \"accepted\") return { status: \"error\", error: \"Only accepted decisions can be reaffirmed. Review and accept this proposal or legacy record first.\" };\n const now = new Date().toISOString();\n const record = importLegacy(original, now);\n if (request.action !== \"retire\") {\n if (!record.owner || !record.sources.length) return { status: \"error\", error: \"Acceptance requires an owner and at least one source. Add them with save_decision, then prepare a new review.\" };\n if (state.evidence.headHash === \"unknown\" || !state.workingTreeAvailable || state.evidence.localChanges.length) return { status: \"error\", error: \"Acceptance requires readable Git HEAD and working-tree evidence with no uncommitted anchor changes. Commit the anchor changes and prepare a new review.\", evidence: state.evidence };\n }\n const status = request.action === \"retire\" ? \"retired\" : \"active\";\n const nextApproval = request.action === \"retire\" ? record.approval : \"accepted\";\n const refreshedHash = request.action === \"retire\" ? record.refreshedHash : state.evidence.headHash;\n const event = { kind: request.action === \"accept\" ? \"accepted\" : request.action === \"reaffirm\" ? \"reaffirmed\" : \"retired\",\n at: now, actor: request.reviewer, note: request.note, revision: record.revision, content: decisionContent(record),\n approval: nextApproval, status, refreshedHash, evidence: state.evidence,\n } as const;\n const updated: ReviewedDecisionRecord = { ...record, status, approval: nextApproval, refreshedHash, updatedAt: now, history: [...record.history, event] };\n // Detect an external Git operation during review preparation, too.\n if ((await reviewState(root, original)).reviewToken !== state.reviewToken) return { status: \"conflict\", error: \"Code changed while the review was being recorded. Prepare a new review.\" };\n await saveDecisionRecord(root, updated);\n return { status: event.kind, id: record.id, event, hint: \"Review recorded locally. Review and commit the decision file through the normal project workflow.\" };\n });\n}\n","export const BATCH_SYSTEM_PROMPT = `You are Mason, building one piece of a larger concept-to-files map via a Map-Reduce pattern.\n\nYou are seeing ONE batch of files from this project — not the whole codebase. Other batches will be processed separately and merged with yours in a final reduce step.\n\nYour job for this batch: identify the features and flows that involve the files in this batch, and return a partial concept map.\n\nRespond with ONLY a JSON object. No markdown, no explanation, no code fences. Just the raw JSON. Same shape as the full map (\\`{\"features\": {...}, \"flows\": {...}}\\`).\n\nCRITICAL: name features in PRODUCT-NATURAL language (e.g., \"home screen\", \"authentication\", \"checkout\"). Do NOT add platform or layer suffixes — call both the Android and iOS home-screen files part of a feature named \"home screen\". This is what lets the reduce step merge platform variants from other batches into a single product feature.\n\nOther rules:\n- Only include files that you see in this batch. Don't predict files in other batches.\n- Use the FULL relative file paths exactly as given.\n- Classify each feature with a \"type\": \"capability\" (user-facing functionality) or \"infrastructure\" (internal plumbing with no end user — DI/service wiring, configuration, logging, adapters, build tooling). When unsure, use \"capability\".\n- Each feature should have 1–8 files from this batch — partials can be narrow.\n- Flows in a partial only make sense if all their chain steps are in this batch. Skip flows that span batches; the reduce step will assemble them.\n- Include test files in \"tests\" when present in this batch.\n- Two views of the batch: FILE HEADERS (every file in the batch, skeleton-level) and REPRESENTATIVE BODIES (deeper read of a few for grounding). Use the bodies to learn the codebase's domain vocabulary; use the headers to know which files exist.`;\n\nexport const REDUCE_SYSTEM_PROMPT = `You are Mason, merging partial concept maps from a Map-Reduce pass into a single unified map.\n\nYou will receive an array of \\`partials\\`, each produced from one batch of files. Your job: merge them into one coherent concept-to-files map for the whole project.\n\nRespond with ONLY a JSON object: \\`{\"features\": {...}, \"flows\": {...}}\\`. No markdown, no preamble.\n\nMerge rules:\n- If two partials use the same feature name (e.g., both have \"home screen\"), MERGE them — combine their \\`files\\` and \\`tests\\` arrays (dedupe), and reconcile descriptions by picking the more product-natural wording or merging the two.\n- If two partials use *near-duplicate* feature names that clearly refer to the same product concept (\"home screen\" vs \"home view\", \"auth\" vs \"authentication\"), merge them under the more product-natural name.\n- If a partial split what should be one feature by platform (\"home Android\" + \"home iOS\"), merge into a single platform-agnostic feature (\"home screen\").\n- Preserve each feature's \"type\" (\"capability\" or \"infrastructure\"). When merged partials disagree on a feature's type, prefer \"capability\". If a partial omitted the type, infer it: user-facing functionality is \"capability\"; internal plumbing with no end user (DI/service wiring, config, logging, adapters) is \"infrastructure\".\n- For flows that were skipped by partials because they span batches, reconstruct them when you can see the full chain across multiple partials.\n- Every file that appears in any partial MUST end up in some feature in the unified map. Don't silently drop files.\n- Feature descriptions in the final map should be 1–2 sentences, written for a product/PM audience — concrete and specific, but free of code-level detail.\n- Each feature should have 2–8 files. If merging produces a feature with 20+ files, consider whether it should be split into sub-features.`;\n\nexport function buildBatchPrompt(\n batch: {\n offset: number;\n batchSize: number;\n nextOffset: number | null;\n totalFiles: number;\n skeletons: Array<{ path: string; content: string }>;\n samples: Array<{ path: string; content: string }>;\n testPairs?: Array<{ test: string; source: string; confidence: string }>;\n }\n): string {\n const skeletonBlocks = batch.skeletons\n .map(\n (f) =>\n `--- ${f.path} ---\\n${f.content}${f.content.length >= 500 ? \"\\n... (truncated)\" : \"\"}`\n )\n .join(\"\\n\\n\");\n\n const sampleBlocks = batch.samples\n .map(\n (f) =>\n `=== ${f.path} (deeper read) ===\\n${f.content}${f.content.length >= 1500 ? \"\\n... (truncated)\" : \"\"}`\n )\n .join(\"\\n\\n\");\n\n const batchInfo = `Batch ${Math.floor(batch.offset / batch.batchSize) + 1}: files ${batch.offset + 1}–${batch.offset + batch.skeletons.length} of ${batch.totalFiles}.`;\n\n let prompt = `${batchInfo}\n\n=== FILE HEADERS (every file in this batch) ===\n\n${skeletonBlocks}\n\n=== REPRESENTATIVE BODIES (for grounding) ===\n\n${sampleBlocks}`;\n\n if (batch.testPairs && batch.testPairs.length > 0) {\n const testBlock = batch.testPairs\n .map((p) => `${p.test} → ${p.source}`)\n .join(\"\\n\");\n prompt += `\\n\\n=== TEST → SOURCE MAPPINGS (for this batch) ===\\n\\n${testBlock}`;\n }\n\n return prompt;\n}\n\nexport function buildReducePrompt(\n partials: Array<{\n batchId: string;\n offset: number;\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n }>\n): string {\n return `Merge the following ${partials.length} partial concept maps into a single unified map.\n\n${JSON.stringify({ partials }, null, 2)}`;\n}\n\nexport const REFRESH_REDUCE_SYSTEM_PROMPT = `You are Mason, merging a scoped refresh into an existing concept-to-files map.\n\nOnly a subset of the project's files was re-analyzed (they changed since the map was built). You receive the existing full map, the list of re-analyzed file paths, and partial concept maps derived from ONLY those files.\n\nRespond with ONLY a JSON object: \\`{\"features\": {...}, \"flows\": {...}}\\` — the COMPLETE updated map. No markdown, no preamble.\n\nMerge rules:\n- Entries in the existing map that reference none of the re-analyzed files: copy them through UNCHANGED.\n- Entries that reference re-analyzed files: update them using the partials — adjust descriptions, add new files, drop files that moved elsewhere.\n- Merge partial features into existing features when they're the same product concept, even if named slightly differently (\"auth\" vs \"authentication\") — keep the existing name unless the new one is clearly more product-natural.\n- Features whose files were all deleted or renamed away: remove them by omitting them from your output.\n- Every file that appears in any partial MUST end up in some feature. Don't silently drop files.\n- Do not invent or alter entries for files you haven't seen.`;\n\nexport function buildRefreshReducePrompt(\n existingMap: {\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n },\n refreshedFiles: string[],\n partials: Array<{\n batchId: string;\n offset: number;\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n }>\n): string {\n return `Merge this scoped refresh into the existing concept map.\n\n=== EXISTING MAP ===\n${JSON.stringify(existingMap, null, 2)}\n\n=== RE-ANALYZED FILES ===\n${refreshedFiles.join(\"\\n\")}\n\n=== PARTIALS (derived from the re-analyzed files only) ===\n${JSON.stringify({ partials }, null, 2)}`;\n}\n\n","import fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { readStoreJson, writeStoreJson, storePath } from \"../utils/storage.js\";\nimport { featureSchema, flowSchema } from \"./snapshot.js\";\nimport type { FeatureEntry, FlowEntry } from \"./snapshot.js\";\n\nexport interface Partial {\n batchId: string;\n offset: number;\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n savedAt: string;\n}\n\nconst DIRECTORY = \".mason/partial-snapshots\";\nconst partialSchema = z.object({\n batchId: z.string().regex(/^[a-zA-Z0-9_-]+$/), offset: z.number().int().nonnegative(),\n features: z.record(featureSchema), flows: z.record(flowSchema), savedAt: z.string(),\n});\nconst scopeSchema = z.object({ files: z.array(z.string()), savedAt: z.string() });\n\nexport async function savePartial(rootDir: string, partial: Partial): Promise<void> {\n if (!/^[a-zA-Z0-9_-]+$/.test(partial.batchId)) throw new Error(`Invalid batchId: ${partial.batchId}`);\n await writeStoreJson(rootDir, `${DIRECTORY}/${partial.batchId}.json`, partialSchema.parse(partial));\n}\n\nexport async function loadAllPartials(rootDir: string): Promise<Partial[]> {\n let entries: string[];\n try { entries = await fs.readdir(await storePath(rootDir, DIRECTORY)); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw error;\n }\n const partials: Partial[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry === \"scope.json\") continue;\n const partial = partialSchema.parse(await readStoreJson(rootDir, `${DIRECTORY}/${entry}`));\n if (entry !== `${partial.batchId}.json`) throw new Error(`Invalid partial filename: ${entry}`);\n partials.push(partial);\n }\n return partials.sort((a, b) => a.offset - b.offset);\n}\n\nexport async function saveScope(rootDir: string, files: string[]): Promise<void> {\n await writeStoreJson(rootDir, `${DIRECTORY}/scope.json`, { files, savedAt: new Date().toISOString() });\n}\n\nexport async function loadScope(rootDir: string): Promise<string[] | null> {\n const raw = await readStoreJson(rootDir, `${DIRECTORY}/scope.json`);\n return raw === null ? null : scopeSchema.parse(raw).files;\n}\n\nexport async function clearScope(rootDir: string): Promise<void> {\n await fs.rm(await storePath(rootDir, `${DIRECTORY}/scope.json`), { force: true });\n}\n\nexport async function clearAllPartials(rootDir: string): Promise<void> {\n await fs.rm(await storePath(rootDir, DIRECTORY), { recursive: true, force: true });\n}\n\nexport function batchIdFor(offset: number): string {\n return `batch-${String(offset).padStart(6, \"0\")}`;\n}\n","import { 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\";\n\nconst ASSISTANT_SETUP = `ASSISTANT INSTRUCTIONS\nIf the user requested Mason setup, add the section below to the project's instruction file. If they only requested inspection or a review, return the findings and leave files unchanged.\nUse the file the project already follows:\n - \\`AGENTS.md\\` exists → put the section there. If a \\`CLAUDE.md\\` also exists and does not reference AGENTS.md, add a one-line pointer to it.\n - only \\`CLAUDE.md\\` (or \\`.claude/CLAUDE.md\\`) exists → put the section there.\n - neither exists → create \\`AGENTS.md\\` with the section.\nIf the \\`<!-- mason:start -->\\` marker already exists, replace the marked block instead of appending.\n\n${CLAUDE_MD_SECTION}\n\nFINALIZE\nAfter installing assistant instructions, call \\`mason_complete_init(dir)\\` to record setup. The marker records onboarding; decision capture, context, and impact already work without it. Summarize the findings, any edits, and any checks that could not run.`;\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 installing the assistant instructions, not rewriting existing claims. 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 { 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 { 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 { 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 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 { 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 { 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, 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 { startMcpServer } from \"../src/mcp/server.js\";\n\nstartMcpServer().catch((err) => {\n process.stderr.write(`Mason MCP server error: ${err}\\n`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;AAAA,OAAO,UAAU;AAGV,SAAS,kBAAkB,OAA8B;AAC9D,QAAM,QAAQ,MAAM,QA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AAK,KAAK;AACzC,aAAO;AAAA,QACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,OAAO,CAAC;AAAA,MAC1C;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,MACE,KAAKA,IACF,OAAO,EACP,SAAS,6CAA6C;AAAA,MACzD,UAAUA,IACP,OAAO,EACP,SAAS,EACT,SAAS,mCAAmC;AAAA,MAC/C,cAAcA,IACX,OAAO,EACP,SAAS,EACT,SAAS,wCAAwC;AAAA,MACpD,gBAAgBA,IACb,OAAO,EACP,SAAS,EACT,SAAS,8DAAyD;AAAA,MACrE,oBAAoBA,IACjB,OAAO,EACP,SAAS,EACT,SAAS,iEAA4D;AAAA,MACxE,mBAAmBA,IAChB,OAAO,EACP,SAAS,EACT,SAAS,2DAA2D;AAAA,IACzE;AAAA,IACA,OAAO,EAAE,KAAK,UAAU,cAAc,gBAAgB,oBAAoB,kBAAkB,MAAM;AAChG,YAAM,SAAS,MAAM,uBAAuB,KAAK;AAAA,QAC/C;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AACD,aAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,OAAO,CAAC,EAAE;AAAA,IACrD;AAAA,EACF;AAEA,SAAO;AACT;AAEA,eAAsB,iBAAgC;AACpD,QAAM,SAAS,gBAAgB;AAC/B,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;;;AoBxjBA,eAAe,EAAE,MAAM,CAAC,QAAQ;AAC9B,UAAQ,OAAO,MAAM,2BAA2B,GAAG;AAAA,CAAI;AACvD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["index","content","message","path","configPath","resolve","content","fs","path","path","count","path","execFile","promisify","z","exec","fs","path","execFile","promisify","exec","count","hash","hash","content","execFile","promisify","exec","fs","path","execFile","promisify","exec","content","fs","path","fg","path","text","count","fs","path","fg","content","fs","path","fg","manifest","path","text","fs","path","record","content","path","init_drift","init_drift","fs","path","fs","path","createHash","randomUUID","z","content","path","execFile","promisify","exec","count","content","path","fs","decisions","impact","relatedTests","stale","init_drift","fs","path","createHash","execFile","promisify","fg","z","exec","index","text","exists","fs","z","resolve","randomUUID","report","notify","text","z","z","path","text","fs","path","os","execFile","promisify","exec","text","fs","path","createHash","execFile","promisify","resolve","exec","text","hash","hash","z","fs","path","execFile","promisify","path","execFile","promisify","fs","fg","exec","promisify","execFile","count","execFile","promisify","exec","path","execFile","promisify","exec","count","reason","createHash","execFile","promisify","z","exec","init_drift","fs","z","z","init_drift","fs","path","execFile","promisify","execFile","promisify","exec","index","path","z","z","message","count","z","index","z","z","schema","resolve","rule","checkSchema","z","path","manifest","index","previews","exec","promisify","execFile","path","fs","MAX_FINDINGS","exec","promisify","execFile","path","fs","count","buildTestMap","previews","loadDecisionStore","path","analyzeImpact","upsertDecision","reviewDecision","assembleContext","automate","automationStatus","summarize","installedAutomation","createConfluenceClient","saveConfluenceConfig","normalizeAtlassianBaseUrl","loadConfig","exportToConfluence","z","count","reviewDecision"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/paths.ts","../src/context/trust.ts","../src/decisions/provenance.ts","../src/utils/files.ts","../src/utils/storage.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/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/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/impact/impact.ts","../src/context/assemble.ts","../src/automation/execution.ts","../src/automation/evidence.ts","../src/automation/store.ts","../src/automation/runtime.ts","../src/automation/adapters.ts","../src/automation/install.ts","../src/setup/model.ts","../src/setup/runtime.ts","../src/setup/files.ts","../src/setup/launcher.ts","../src/setup/config.ts","../src/setup/observations.ts","../src/setup/status.ts","../src/setup/setup.ts","../src/confluence/client.ts","../src/llm/config.ts","../src/confluence/url.ts","../src/confluence/renderer.ts","../src/confluence/diff.ts","../src/llm/providers.ts","../src/confluence/rewrite.ts","../src/confluence/sync.ts","../src/mcp/server.ts","../src/mcp/tools.ts","../src/audit/cli.ts","../src/analyzers/git-history.ts","../src/analyzers/base.ts","../src/analyzers/index.ts","../src/utils/git.ts","../src/mcp/sampler.ts","../src/decisions/review.ts","../src/snapshot/prompt.ts","../src/snapshot/partials.ts","../bin/mason-mcp.ts"],"sourcesContent":["import 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","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 { 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 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","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 { 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 path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess, SOURCE_GLOB } from \"../utils/files.js\";\nimport { normalizeRepoPath } from \"../utils/paths.js\";\n\nconst exec = promisify(execFile);\n\nexport interface CochangeEntry {\n file: string;\n cochangeRate: number;\n sharedCommits: number;\n}\n\nexport interface ReferenceEntry {\n file: string;\n matches: string[];\n /**\n * \"import\" when the name appears on an import/include/use line — a\n * structural dependency; \"mention\" for any other textual hit (comments,\n * strings, same-name-different-concept collisions). Imports sort first:\n * a mention of \"context\" in a doc comment is not the same signal as\n * `import { Context }`.\n */\n kind: \"import\" | \"mention\";\n}\n\nexport interface TestEntry {\n file: string;\n confidence: \"exact\" | \"best-guess\";\n}\n\nexport interface ImpactResult {\n targetFiles: string[];\n cochange: CochangeEntry[];\n references: ReferenceEntry[];\n tests: TestEntry[];\n}\n\nexport async function analyzeImpact(\n rootDir: string,\n targetFiles: string[]\n): Promise<ImpactResult> {\n const resolvedRoot = path.resolve(rootDir);\n\n // Resolve target files to full relative paths if only basename given\n const resolvedTargets = await resolveTargetFiles(resolvedRoot, targetFiles);\n\n const [cochange, references, tests] = await Promise.all([\n getCochangeFiles(resolvedRoot, resolvedTargets),\n getReferences(resolvedRoot, resolvedTargets),\n getRelatedTests(resolvedRoot, resolvedTargets),\n ]);\n\n return {\n targetFiles: resolvedTargets,\n cochange,\n references,\n tests,\n };\n}\n\nasync function resolveTargetFiles(\n rootDir: string,\n targets: string[]\n): Promise<string[]> {\n const resolved: string[] = [];\n const access = await createFileAccess(rootDir);\n\n for (const target of targets) {\n // If it contains a path separator, use as-is\n if (target.includes(\"/\")) {\n const normalized = normalizeRepoPath(target);\n if (normalized) resolved.push(normalized);\n continue;\n }\n\n // Otherwise, search for the filename\n const matches = await access.list(`**/${target}`);\n\n if (matches.length > 0) {\n resolved.push(matches[0]);\n } else {\n // Try without extension\n const noExt = target.replace(/\\.[^.]+$/, \"\");\n const extMatches = await access.list(`**/${noExt}.*`);\n if (extMatches.length > 0) {\n resolved.push(extMatches[0]);\n } else {\n resolved.push(target); // Keep as-is, might still work for grep\n }\n }\n }\n\n return resolved;\n}\n\nasync function getCochangeFiles(\n rootDir: string,\n targetFiles: string[]\n): Promise<CochangeEntry[]> {\n const cochangeCounts = new Map<string, number>();\n let totalTargetCommits = 0;\n\n for (const targetFile of targetFiles) {\n try {\n // Get commits that touched this file (cap at 500)\n const { stdout: commitLog } = await exec(\n \"git\",\n [\"log\", \"--format=%H\", \"-n\", \"500\", \"--\", targetFile],\n { cwd: rootDir, maxBuffer: 5_000_000 }\n );\n\n const commits = commitLog.trim().split(\"\\n\").filter(Boolean);\n totalTargetCommits += commits.length;\n\n if (commits.length === 0) continue;\n\n // For each commit, get the other files that changed\n for (const commit of commits) {\n try {\n const { stdout: filesInCommit } = await exec(\n \"git\",\n [\"diff-tree\", \"--no-commit-id\", \"--name-only\", \"-r\", commit],\n { cwd: rootDir }\n );\n\n const files = filesInCommit.trim().split(\"\\n\").filter(Boolean);\n for (const file of files) {\n if (targetFiles.includes(file)) continue; // Skip the target itself\n cochangeCounts.set(file, (cochangeCounts.get(file) ?? 0) + 1);\n }\n } catch {\n // Skip this commit\n }\n }\n } catch {\n // No git or file not tracked\n }\n }\n\n if (totalTargetCommits === 0) return [];\n\n // Filter to files that co-change >30% of the time, sort by rate\n return [...cochangeCounts.entries()]\n .map(([file, count]) => ({\n file,\n cochangeRate: Math.round((count / totalTargetCommits) * 100) / 100,\n sharedCommits: count,\n }))\n .filter((e) => e.cochangeRate >= 0.3 || e.sharedCommits >= 3)\n .sort((a, b) => b.cochangeRate - a.cochangeRate)\n .slice(0, 20);\n}\n\nasync function getReferences(\n rootDir: string,\n targetFiles: string[]\n): Promise<ReferenceEntry[]> {\n // Extract searchable names from target files\n const searchNames = new Set<string>();\n for (const target of targetFiles) {\n const basename = path.basename(target).replace(/\\.[^.]+$/, \"\");\n searchNames.add(basename);\n }\n\n const access = await createFileAccess(rootDir);\n const allSourceFiles = await access.list(SOURCE_GLOB);\n\n // Exclude target files from search\n const targetSet = new Set(targetFiles);\n const filesToSearch = allSourceFiles.filter((f) => !targetSet.has(f));\n\n const results = new Map<string, { matches: Set<string>; isImport: boolean }>();\n\n // Language-agnostic import-line heuristic: covers JS/TS import/require,\n // Python import/from, Go/Rust/Swift/Kotlin/Java import/use, C include.\n const importLine = /^\\s*(import\\b|from\\b.*\\bimport\\b|const\\b.*=\\s*require\\(|use\\b|#include\\b|require\\s*\\()/;\n\n // Read files in batches to avoid too many open handles\n const batchSize = 50;\n for (let i = 0; i < filesToSearch.length; i += batchSize) {\n const batch = filesToSearch.slice(i, i + batchSize);\n\n await Promise.all(\n batch.map(async (file) => {\n try {\n const full = await access.read(file);\n if (!full) return;\n const content = full.content;\n const lines = content.split(\"\\n\");\n\n for (const name of searchNames) {\n // Match the name as a word boundary (not part of another word)\n const regex = new RegExp(`\\\\b${escapeRegex(name)}\\\\b`);\n if (!regex.test(content)) continue;\n if (!results.has(file)) {\n results.set(file, { matches: new Set(), isImport: false });\n }\n const entry = results.get(file)!;\n entry.matches.add(name);\n if (\n !entry.isImport &&\n lines.some((l) => regex.test(l) && importLine.test(l))\n ) {\n entry.isImport = true;\n }\n }\n } catch {\n // Skip unreadable files\n }\n })\n );\n }\n\n return [...results.entries()]\n .map(([file, { matches, isImport }]) => ({\n file,\n matches: [...matches],\n kind: (isImport ? \"import\" : \"mention\") as \"import\" | \"mention\",\n }))\n .sort((a, b) => {\n if (a.kind !== b.kind) return a.kind === \"import\" ? -1 : 1;\n return b.matches.length - a.matches.length;\n });\n}\n\nasync function getRelatedTests(\n rootDir: string,\n targetFiles: string[]\n): Promise<TestEntry[]> {\n const testPatterns = [\n \"**/*.test.*\",\n \"**/*.spec.*\",\n \"**/*Test.kt\",\n \"**/*Test.java\",\n \"**/*Tests.kt\",\n \"**/*Tests.java\",\n \"**/test_*.py\",\n \"**/*_test.py\",\n \"**/*_test.go\",\n \"**/*Tests.swift\",\n \"**/*Test.swift\",\n \"**/*_test.rs\",\n ];\n\n const testFiles = await (await createFileAccess(rootDir)).list(testPatterns);\n const results: TestEntry[] = [];\n\n for (const target of targetFiles) {\n const targetBaseName = path\n .basename(target)\n .replace(/\\.[^.]+$/, \"\");\n\n for (const testFile of testFiles) {\n const testBaseName = path\n .basename(testFile)\n .replace(/\\.[^.]+$/, \"\");\n\n // Strip test suffixes to get the source name\n const sourceName = testBaseName\n .replace(/Test$|Tests$|Spec$|\\.test$|\\.spec$/, \"\")\n .replace(/^test_|_test$/, \"\");\n\n if (sourceName === targetBaseName) {\n results.push({\n file: testFile,\n confidence: \"exact\",\n });\n }\n }\n }\n\n return results;\n}\n\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","import path from \"node:path\";\nimport fs from \"node:fs/promises\";\nimport { inspectSnapshot, normalizeFeatureType } from \"../snapshot/snapshot.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport type { FeatureType, Snapshot } from \"../snapshot/snapshot.js\";\nimport { computeDrift, type DriftReport } from \"../drift/drift.js\";\nimport { analyzeImpact } from \"../impact/impact.js\";\nimport type { CochangeEntry, ReferenceEntry } from \"../impact/impact.js\";\nimport { scoreEntry, tokenSet } from \"./lexical.js\";\nimport { loadDecisionStore } from \"../decisions/decisions.js\";\nimport { decisionKnowledge, effectiveDecision, DECISION_GUIDANCE } from \"../decisions/provenance.js\";\nimport { anchorMatches, sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { assessTrust, trustHint, type TrustState } from \"./trust.js\";\nimport type { StoreDiagnostic } from \"../utils/storage.js\";\nimport type { DecisionDriftReport } from \"../decisions/drift.js\";\nimport type { DecisionCategory, DecisionRecord } from \"../decisions/decisions.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\n\nconst MAX_FEATURES = 5;\nconst MAX_FLOWS = 3;\nconst MAX_IMPACT_TARGETS = 3;\nconst MAX_DECISIONS = 5;\nconst DECISION_FEATURE_OVERLAP_BOOST = 2;\n\nexport interface MatchedFeature {\n description: string;\n files: string[];\n tests?: string[];\n type: FeatureType;\n score: number;\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface MatchedFlow {\n description: string;\n chain: string[];\n score: number;\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface MatchedDecision extends ReturnType<typeof decisionKnowledge> {\n title: string;\n /** Full body — the payload the decisions store exists for. */\n body: string;\n category: DecisionCategory;\n files: string[];\n score: number;\n /** Anchor files changed since this record was last verified. */\n stale: boolean;\n trust: TrustState;\n}\n\nexport interface ContextBundle {\n exists: true;\n map: { status: \"available\" };\n diagnostics?: StoreDiagnostic[];\n task: string;\n features: Record<string, MatchedFeature>;\n flows: Record<string, MatchedFlow>;\n /** Relevant knowledge; approval distinguishes constraints from proposals. */\n decisions: Record<string, MatchedDecision>;\n /** All tests paired with the matched files, deduped. */\n relatedTests: string[];\n impact: {\n targets: string[];\n cochange: CochangeEntry[];\n references: ReferenceEntry[];\n } | null;\n freshness: {\n stale: boolean;\n recommendation: string;\n /** Matched entries whose files changed since they were last verified. */\n staleMatches: string[];\n };\n hint: string;\n}\n\nexport interface NoMatchBundle {\n exists: true;\n map: { status: \"available\" };\n impact?: ContextBundle[\"impact\"];\n relatedTests?: string[];\n diagnostics?: StoreDiagnostic[];\n freshness?: DriftReport | null;\n trust?: { features: Record<string, TrustState>; flows: Record<string, TrustState> };\n task: string;\n features: Record<string, never>;\n flows: Record<string, never>;\n /** Decisions can match even when no feature does. */\n decisions: Record<string, MatchedDecision>;\n /** The full feature catalog, so the caller can still act without a second guess. */\n availableFeatures: Record<string, string>;\n availableFlows: Record<string, string>;\n hint: string;\n}\n\nexport interface UnmappedContextBundle extends Omit<ContextBundle, \"exists\" | \"map\" | \"freshness\"> {\n /** Legacy exists indicates map availability, not decision availability. */\n exists: false;\n map: { status: \"missing\" | \"invalid\" };\n freshness: { stale: null; recommendation: \"no-map\" | \"repair-map\"; staleMatches: string[] };\n}\n\nasync function collectImpact(root: string, candidates: string[]): Promise<{\n impact: ContextBundle[\"impact\"]; relatedTests: string[];\n}> {\n const targets = new Set<string>();\n let sourceFiles: string[] | undefined;\n for (const candidate of sanitizeRepoPaths(candidates)) {\n const stat = await fs.stat(path.join(root, candidate)).catch(() => null);\n if (stat?.isDirectory()) {\n sourceFiles ??= await (await createFileAccess(root)).list();\n for (const file of sourceFiles) {\n if (anchorMatches(candidate, file)) targets.add(file);\n if (targets.size >= MAX_IMPACT_TARGETS) break;\n }\n } else {\n targets.add(candidate);\n }\n if (targets.size >= MAX_IMPACT_TARGETS) break;\n }\n if (!targets.size) return { impact: null, relatedTests: [] };\n const result = await analyzeImpact(root, [...targets]);\n return {\n impact: { targets: result.targetFiles, cochange: result.cochange, references: result.references.slice(0, 10) },\n relatedTests: [...new Set(result.tests.map(t => t.file))],\n };\n}\n\n/**\n * Assemble everything needed to start a task in one call: matching map\n * entries, their files and tests, blast radius for the top files, and\n * per-entry freshness. Deterministic and LLM-free.\n *\n * `files` optionally anchors matching to an explicit file list (e.g. a diff):\n * entries containing those files are boosted above pure lexical matches.\n */\nexport async function assembleContext(\n rootDir: string,\n task: string,\n files?: string[]\n): Promise<ContextBundle | NoMatchBundle | UnmappedContextBundle> {\n const resolvedRoot = path.resolve(rootDir);\n const mapState = await inspectSnapshot(resolvedRoot);\n const snapshot = mapState.snapshot;\n const store = await loadDecisionStore(resolvedRoot);\n const allDecisions = store.records;\n const decisionDrift = await computeDecisionDrift(resolvedRoot, allDecisions);\n const taskTokens = tokenSet(task);\n const anchorFiles = new Set(sanitizeRepoPaths(files ?? []));\n\n const anchorBoost = (entryFiles: string[]): number => {\n let boost = 0;\n for (const f of entryFiles) if ([...anchorFiles].some(file => anchorMatches(f, file))) boost += 5;\n return boost;\n };\n\n if (!snapshot) {\n const decisions = matchDecisions(allDecisions, taskTokens, anchorBoost, new Set(), decisionDrift);\n const { impact, relatedTests } = await collectImpact(resolvedRoot, [...anchorFiles, ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])])]);\n const invalid = mapState.status === \"invalid\";\n return {\n exists: false, map: { status: invalid ? \"invalid\" : \"missing\" }, task,\n features: {}, flows: {}, decisions, impact, relatedTests,\n diagnostics: [...mapState.diagnostics, ...store.diagnostics],\n freshness: { stale: null, recommendation: invalid ? \"repair-map\" : \"no-map\", staleMatches: [] },\n hint: (invalid ? \"The concept map is invalid; consult diagnostics and repair it before relying on map entries. \" : \"No concept map is present. Maps are optional; decisions and file impact work now. \") +\n (Object.keys(decisions).length ? DECISION_GUIDANCE + \" \" + trustHint(Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])])) : \"No saved decision matched. Inspect the source and use save_decision for a learned constraint or incident rationale. \") +\n (store.diagnostics.length ? \" Some decision records are invalid; consult diagnostics before assuming all constraints were retrieved.\" : \"\"),\n };\n }\n\n const drift = await computeDrift(resolvedRoot);\n\n const featureScores = Object.entries(snapshot.features)\n .map(([name, feat]) => ({\n name,\n feat,\n score:\n scoreEntry(taskTokens, { name, description: feat.description, files: feat.files }) +\n anchorBoost([...feat.files, ...(feat.tests ?? [])]),\n }))\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_FEATURES);\n\n const flowScores = Object.entries(snapshot.flows)\n .map(([name, flow]) => ({\n name,\n flow,\n score:\n scoreEntry(taskTokens, { name, description: flow.description, files: flow.chain }) +\n anchorBoost(flow.chain),\n }))\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_FLOWS);\n\n const matchedEntryFiles = new Set<string>([\n ...featureScores.flatMap((e) => e.feat.files),\n ...flowScores.flatMap((e) => e.flow.chain),\n ]);\n const decisions = matchDecisions(\n allDecisions,\n taskTokens,\n anchorBoost,\n matchedEntryFiles,\n decisionDrift\n );\n\n if (featureScores.length === 0 && flowScores.length === 0) {\n const bundle = noMatchBundle(snapshot, task, decisions);\n Object.assign(bundle, await collectImpact(resolvedRoot, [...anchorFiles, ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])])]));\n bundle.diagnostics = store.diagnostics;\n bundle.freshness = drift;\n bundle.trust = {\n features: Object.fromEntries(Object.entries(snapshot.features).map(([name, entry]) =>\n [name, assessTrust(entry, drift?.featureFreshness?.[name] ?? \"unknown\")]\n )),\n flows: Object.fromEntries(Object.entries(snapshot.flows).map(([name, entry]) =>\n [name, assessTrust(entry, drift?.flowFreshness?.[name] ?? \"unknown\")]\n )),\n };\n bundle.hint += \" \" + trustHint([\n ...Object.values(bundle.trust.features),\n ...Object.values(bundle.trust.flows),\n ...Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])]),\n ]);\n if (Object.keys(decisions).length) bundle.hint += \" \" + DECISION_GUIDANCE;\n if (store.diagnostics.length) bundle.hint += \" Some decision records are invalid; consult diagnostics.\";\n return bundle;\n }\n\n const features: Record<string, MatchedFeature> = {};\n const staleMatches: string[] = [];\n for (const { name, feat, score } of featureScores) {\n const trust = assessTrust(feat, drift?.featureFreshness?.[name] ?? \"unknown\");\n const stale = trust.freshness !== \"current\";\n if (stale) staleMatches.push(name);\n features[name] = {\n description: feat.description,\n files: feat.files,\n ...(feat.tests && feat.tests.length > 0 ? { tests: feat.tests } : {}),\n type: normalizeFeatureType(feat.type),\n score,\n stale,\n trust,\n };\n }\n\n const flows: Record<string, MatchedFlow> = {};\n for (const { name, flow, score } of flowScores) {\n const trust = assessTrust(flow, drift?.flowFreshness?.[name] ?? \"unknown\");\n const stale = trust.freshness !== \"current\";\n if (stale) staleMatches.push(name);\n flows[name] = {\n description: flow.description,\n chain: flow.chain,\n score,\n stale,\n trust,\n };\n }\n\n const { impact, relatedTests: impactTests } = await collectImpact(resolvedRoot, [\n ...anchorFiles,\n ...featureScores.flatMap((e) => e.feat.files),\n ...flowScores.flatMap(e => e.flow.chain),\n ...Object.values(decisions).flatMap(d => [...d.files, ...(d.pendingProposal?.files ?? [])]),\n ]);\n\n const relatedTests = [\n ...new Set([\n ...featureScores.flatMap((e) => e.feat.tests ?? []),\n ...impactTests,\n ]),\n ];\n\n const stale = drift?.stale ?? false;\n return {\n exists: true,\n map: { status: \"available\" },\n diagnostics: store.diagnostics,\n task,\n features,\n flows,\n decisions,\n relatedTests,\n impact,\n freshness: {\n stale,\n recommendation: drift?.recommendation ?? \"up-to-date\",\n staleMatches,\n },\n hint: (Object.keys(decisions).length ? DECISION_GUIDANCE + \" \" : \"\") + trustHint([...Object.values(features).map(e => e.trust), ...Object.values(flows).map(e => e.trust), ...Object.values(decisions).flatMap(d => [d.trust, ...(d.pendingProposal ? [d.pendingProposal.trust] : [])])]) + (store.diagnostics.length ? \" Some decision records are invalid; consult diagnostics before assuming all constraints were retrieved.\" : \"\"),\n };\n}\n\n/**\n * Score active decisions against the task with the same lexical machinery\n * as map entries, plus a feature-overlap boost: a decision anchored to a\n * file of an already-matched feature is relevant even with zero lexical\n * overlap (\"auth is weird\" should surface on any auth task).\n */\nfunction matchDecisions(\n allDecisions: DecisionRecord[],\n taskTokens: Set<string>,\n anchorBoost: (files: string[]) => number,\n matchedEntryFiles: Set<string>,\n decisionDrift: DecisionDriftReport\n): Record<string, MatchedDecision> {\n const scored = allDecisions\n .filter((d) => d.status === \"active\")\n .map((d) => {\n const scoreRevision = (revision: DecisionRecord) =>\n scoreEntry(taskTokens, { name: revision.title, description: revision.body, files: revision.files }) + anchorBoost(revision.files) +\n (revision.files.some(f => [...matchedEntryFiles].some(file => anchorMatches(f, file))) ? DECISION_FEATURE_OVERLAP_BOOST : 0);\n const score = Math.max(scoreRevision(effectiveDecision(d)), scoreRevision(d));\n return { d, score };\n })\n .filter((e) => e.score > 0)\n .sort((a, b) => b.score - a.score)\n .slice(0, MAX_DECISIONS);\n\n const result: Record<string, MatchedDecision> = {};\n for (const { d, score } of scored) {\n result[d.id] = {\n ...decisionKnowledge(d, decisionDrift.freshness?.[d.id] ?? \"unknown\", decisionDrift.pendingProposals?.[d.id]?.freshness ?? \"unknown\"),\n score,\n stale: decisionDrift.freshness?.[d.id] !== \"current\",\n };\n }\n return result;\n}\n\nfunction noMatchBundle(\n snapshot: Snapshot,\n task: string,\n decisions: Record<string, MatchedDecision>\n): NoMatchBundle {\n const availableFeatures: Record<string, string> = {};\n for (const [name, feat] of Object.entries(snapshot.features)) {\n availableFeatures[name] = feat.description;\n }\n const availableFlows: Record<string, string> = {};\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n availableFlows[name] = flow.description;\n }\n return {\n exists: true,\n map: { status: \"available\" },\n task,\n features: {},\n flows: {},\n decisions,\n availableFeatures,\n availableFlows,\n hint: \"No map entry matched the task wording. The full catalog is listed — pick the relevant entries and call get_context again with their names in the task, or read their files directly via get_snapshot.\",\n };\n}\n","import 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 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 { 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 } 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 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 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 { 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 { 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 type { ConfluenceConfig } from \"../llm/config.js\";\n\nexport interface ConfluencePage {\n id: string;\n title: string;\n version: number;\n body: string;\n parentId?: string;\n}\n\nexport interface CreatePageInput {\n spaceId: string;\n title: string;\n body: string;\n parentId?: string;\n}\n\nexport interface UpdatePageInput {\n id: string;\n title: string;\n body: string;\n version: number;\n parentId?: string;\n}\n\nexport interface ConfluenceSpace {\n id: string;\n key: string;\n name: string;\n}\n\nexport interface ConfluenceRootPage {\n id: string;\n title: string;\n}\n\nexport interface ConfluenceClient {\n resolveSpaceId(spaceKey: string): Promise<string>;\n listSpaces(): Promise<ConfluenceSpace[]>;\n listRootPages(spaceId: string): Promise<ConfluenceRootPage[]>;\n findPageByTitle(spaceId: string, title: string): Promise<ConfluencePage | null>;\n createPage(input: CreatePageInput): Promise<ConfluencePage>;\n updatePage(input: UpdatePageInput): Promise<ConfluencePage>;\n}\n\ninterface PageApiResponse {\n id: string;\n title: string;\n parentId?: string;\n version?: { number: number };\n body?: { storage?: { value?: string } };\n}\n\nexport function createConfluenceClient(\n config: ConfluenceConfig,\n fetchFn: typeof fetch = fetch\n): ConfluenceClient {\n const baseUrl = config.baseUrl.replace(/\\/+$/, \"\");\n const auth =\n \"Basic \" +\n Buffer.from(`${config.email}:${config.apiToken}`).toString(\"base64\");\n\n async function call(\n method: string,\n path: string,\n body?: unknown\n ): Promise<unknown> {\n const res = await fetchFn(`${baseUrl}${path}`, {\n method,\n headers: {\n Authorization: auth,\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new Error(\n `Confluence ${method} ${path} failed: ${res.status} ${res.statusText} — ${text}`\n );\n }\n\n if (res.status === 204) return null;\n return res.json();\n }\n\n function toPage(raw: PageApiResponse): ConfluencePage {\n return {\n id: raw.id,\n title: raw.title,\n version: raw.version?.number ?? 1,\n body: raw.body?.storage?.value ?? \"\",\n parentId: raw.parentId,\n };\n }\n\n return {\n async resolveSpaceId(spaceKey: string): Promise<string> {\n const res = (await call(\n \"GET\",\n `/wiki/api/v2/spaces?keys=${encodeURIComponent(spaceKey)}`\n )) as { results?: Array<{ id: string; key: string }> };\n const space = res.results?.find((s) => s.key === spaceKey);\n if (!space) {\n throw new Error(`Confluence space not found: ${spaceKey}`);\n }\n return space.id;\n },\n\n async listSpaces(): Promise<ConfluenceSpace[]> {\n const all: ConfluenceSpace[] = [];\n let cursor = \"/wiki/api/v2/spaces?limit=100\";\n while (cursor) {\n const res = (await call(\"GET\", cursor)) as {\n results?: Array<{ id: string; key: string; name?: string }>;\n _links?: { next?: string };\n };\n for (const s of res.results ?? []) {\n all.push({ id: s.id, key: s.key, name: s.name ?? s.key });\n }\n const next = res._links?.next;\n if (!next) break;\n // v2 returns relative paths beginning with \"/wiki/...\"\n cursor = next.startsWith(\"/\") ? next : `/${next}`;\n }\n return all;\n },\n\n async listRootPages(spaceId: string): Promise<ConfluenceRootPage[]> {\n const url =\n `/wiki/api/v2/spaces/${encodeURIComponent(spaceId)}/pages` +\n `?depth=root&limit=50`;\n const res = (await call(\"GET\", url)) as {\n results?: Array<{ id: string; title: string }>;\n };\n return (res.results ?? []).map((p) => ({ id: p.id, title: p.title }));\n },\n\n async findPageByTitle(\n spaceId: string,\n title: string\n ): Promise<ConfluencePage | null> {\n const url =\n `/wiki/api/v2/spaces/${encodeURIComponent(spaceId)}/pages` +\n `?title=${encodeURIComponent(title)}&body-format=storage&limit=1`;\n const res = (await call(\"GET\", url)) as {\n results?: PageApiResponse[];\n };\n const match = res.results?.find((p) => p.title === title);\n return match ? toPage(match) : null;\n },\n\n async createPage(input: CreatePageInput): Promise<ConfluencePage> {\n const res = (await call(\"POST\", \"/wiki/api/v2/pages\", {\n spaceId: input.spaceId,\n status: \"current\",\n title: input.title,\n parentId: input.parentId,\n body: {\n representation: \"storage\",\n value: input.body,\n },\n })) as PageApiResponse;\n return toPage(res);\n },\n\n async updatePage(input: UpdatePageInput): Promise<ConfluencePage> {\n const res = (await call(\"PUT\", `/wiki/api/v2/pages/${input.id}`, {\n id: input.id,\n status: \"current\",\n title: input.title,\n parentId: input.parentId,\n body: {\n representation: \"storage\",\n value: input.body,\n },\n version: {\n number: input.version + 1,\n },\n })) as PageApiResponse;\n return toPage(res);\n },\n };\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport os from \"node:os\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\nexport type Provider = \"claude\" | \"gemini\" | \"openai\" | \"ollama\";\n\nexport interface ConfluenceConfig {\n baseUrl: string;\n email: string;\n apiToken: string;\n spaceKey: string;\n parentPageId?: string;\n}\n\nexport interface MasonConfig {\n provider: Provider;\n apiKey?: string;\n model?: string;\n ollamaHost?: string;\n confluence?: ConfluenceConfig;\n}\n\nfunction configDir(): string {\n return path.join(os.homedir(), \".mason\");\n}\n\nfunction configFile(): string {\n return path.join(configDir(), \"config.json\");\n}\n\nconst DEFAULT_MODELS: Record<Provider, string> = {\n claude: \"claude-sonnet-4-20250514\",\n gemini: \"gemini-2.5-flash\",\n openai: \"gpt-4o\",\n ollama: \"llama3\",\n};\n\nexport async function loadConfig(): Promise<MasonConfig | null> {\n try {\n const raw = await fs.readFile(configFile(), \"utf-8\");\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nexport async function saveConfig(config: MasonConfig): Promise<void> {\n await fs.mkdir(configDir(), { recursive: true });\n await fs.writeFile(configFile(), JSON.stringify(config, null, 2), \"utf-8\");\n}\n\nexport function getDefaultModel(provider: Provider): string {\n return DEFAULT_MODELS[provider];\n}\n\nexport function validateProvider(value: string): Provider {\n const valid: Provider[] = [\"claude\", \"gemini\", \"openai\", \"ollama\"];\n if (!valid.includes(value as Provider)) {\n throw new Error(\n `Invalid provider \"${value}\". Must be one of: ${valid.join(\", \")}`\n );\n }\n return value as Provider;\n}\n\nexport async function detectCLI(\n provider: Provider\n): Promise<{ available: boolean; version?: string }> {\n const cliName = provider === \"claude\" ? \"claude\"\n : provider === \"gemini\" ? \"gemini\"\n : provider === \"ollama\" ? \"ollama\"\n : null;\n\n if (!cliName) return { available: false };\n\n try {\n const { stdout } = await exec(cliName, [\"--version\"]);\n return { available: true, version: stdout.trim() };\n } catch {\n return { available: false };\n }\n}\n\nexport function needsApiKey(provider: Provider): boolean {\n return provider === \"openai\";\n}\n\nexport async function saveConfluenceConfig(\n confluence: ConfluenceConfig\n): Promise<void> {\n const existing = (await loadConfig()) ?? { provider: \"claude\" as Provider };\n await saveConfig({ ...existing, confluence });\n}\n\nexport async function loadConfluenceConfig(): Promise<ConfluenceConfig | null> {\n const config = await loadConfig();\n return config?.confluence ?? null;\n}\n","export function normalizeAtlassianBaseUrl(input: string): string {\n const trimmed = input.trim().replace(/\\/+$/, \"\");\n if (!trimmed) throw new Error(\"Confluence baseUrl is required.\");\n if (/^https?:\\/\\//i.test(trimmed)) return trimmed;\n if (trimmed.includes(\".\")) return `https://${trimmed}`;\n // Bare subdomain — assume Atlassian Cloud\n return `https://${trimmed}.atlassian.net`;\n}\n","import type { FeatureEntry, FlowEntry } from \"../snapshot/snapshot.js\";\n\n// Mason fully owns each page body and overwrites it on every sync. Confluence\n// strips HTML comments and re-serializes storage XHTML, so in-page region\n// markers can't survive a round-trip — no-op detection happens via a content\n// hash in the local sync state instead (see sync.ts / diff.ts).\n\nfunction escape(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\");\n}\n\nfunction infoPanel(text: string): string {\n return (\n `<ac:structured-macro ac:name=\"info\"><ac:rich-text-body>` +\n `<p>${escape(text)}</p>` +\n `</ac:rich-text-body></ac:structured-macro>`\n );\n}\n\nexport function featurePageTitle(prefix: string, name: string): string {\n return `${prefix}${name}`;\n}\n\nexport interface RenderedFeaturePage {\n body: string;\n title: string;\n}\n\nexport interface RenderFeaturePageOptions {\n name: string;\n productDescription: string;\n flowDescriptions: Array<{ name: string; description: string }>;\n indexPageTitle: string;\n}\n\nexport function renderFeaturePage(\n options: RenderFeaturePageOptions\n): RenderedFeaturePage {\n const overviewBody =\n `<h2>What it does</h2>` + `<p>${escape(options.productDescription)}</p>`;\n\n // Only render \"How it fits in\" when there are flows — an empty section with a\n // \"nothing here\" placeholder reads as unfinished.\n const flowsBody = options.flowDescriptions.length\n ? `<h2>How it fits in</h2><ul>` +\n options.flowDescriptions\n .map(\n (f) =>\n `<li><strong>${escape(f.name)}</strong> — ${escape(f.description)}</li>`\n )\n .join(\"\") +\n `</ul>`\n : \"\";\n\n // Native Confluence page link, resolved by title.\n const navBody =\n `<p><ac:link><ri:page ri:content-title=\"${escape(options.indexPageTitle)}\"/>` +\n `<ac:plain-text-link-body><![CDATA[Back to ${options.indexPageTitle}]]></ac:plain-text-link-body>` +\n `</ac:link></p>`;\n\n // Provenance note as a footer, not wedged between the content sections.\n const footer = infoPanel(\n `Generated from code by Mason. This page is overwritten on each sync — ` +\n `edit the code, not the page.`\n );\n\n const body = overviewBody + flowsBody + navBody + footer;\n\n return {\n title: options.name,\n body,\n };\n}\n\nexport interface RenderIndexPageOptions {\n featureTitles: string[];\n featurePrefix: string;\n}\n\nexport function renderIndexPage(options: RenderIndexPageOptions): string {\n if (options.featureTitles.length === 0) {\n return infoPanel(\"No features in the snapshot yet.\");\n }\n\n const list =\n `<h2>Features</h2><ul>` +\n options.featureTitles\n .map((name) => {\n const pageTitle = featurePageTitle(options.featurePrefix, name);\n return (\n `<li><ac:link><ri:page ri:content-title=\"${escape(pageTitle)}\"/>` +\n `<ac:plain-text-link-body><![CDATA[${name}]]></ac:plain-text-link-body>` +\n `</ac:link></li>`\n );\n })\n .join(\"\") +\n `</ul>`;\n\n const banner = infoPanel(\n `Generated from code by Mason. Maintained automatically — edit the code, not this page.`\n );\n\n return banner + list;\n}\n\nexport interface DiffSection {\n syncedAt: string;\n addedFeatures: string[];\n removedFeatures: string[];\n changedFeatures: string[];\n addedFlows: string[];\n removedFlows: string[];\n}\n\nexport function renderChangelogSection(section: DiffSection): string {\n const segments: string[] = [];\n if (section.addedFeatures.length) {\n segments.push(\n `<p><strong>Added features:</strong> ${section.addedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.removedFeatures.length) {\n segments.push(\n `<p><strong>Removed features:</strong> ${section.removedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.changedFeatures.length) {\n segments.push(\n `<p><strong>Updated features:</strong> ${section.changedFeatures.map(escape).join(\", \")}</p>`\n );\n }\n if (section.addedFlows.length) {\n segments.push(\n `<p><strong>Added flows:</strong> ${section.addedFlows.map(escape).join(\", \")}</p>`\n );\n }\n if (section.removedFlows.length) {\n segments.push(\n `<p><strong>Removed flows:</strong> ${section.removedFlows.map(escape).join(\", \")}</p>`\n );\n }\n if (segments.length === 0) {\n segments.push(`<p><em>No meaningful changes detected.</em></p>`);\n }\n\n return (\n `<h3>${escape(section.syncedAt)}</h3>` + segments.join(\"\")\n );\n}\n\nexport function renderChangelogPage(sections: string[]): string {\n if (sections.length === 0) {\n return `<p><em>No sync has run yet.</em></p>`;\n }\n // Newest first\n return sections.join(\"\\n<hr/>\\n\");\n}\n\nexport type FeatureMap = Record<string, FeatureEntry>;\nexport type FlowMap = Record<string, FlowEntry>;\n\nexport function flowsForFeature(\n featureFiles: string[],\n flows: FlowMap\n): Array<{ name: string; description: string }> {\n const fileSet = new Set(featureFiles);\n const result: Array<{ name: string; description: string }> = [];\n for (const [name, flow] of Object.entries(flows)) {\n if (flow.chain.some((file) => fileSet.has(file))) {\n result.push({ name, description: flow.description });\n }\n }\n return result;\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createHash } from \"node:crypto\";\nimport type { Snapshot } from \"../snapshot/snapshot.js\";\nimport type { DiffSection } from \"./renderer.js\";\n\nexport interface RewriteCacheEntry {\n /** sha256 of the engineering (source) description this prose was derived from */\n sourceHash: string;\n /** the cached product-language prose */\n product: string;\n /** true when produced by the no-LLM fallback, not the model — re-attempted next run */\n fallback?: boolean;\n}\n\nexport interface RewriteCache {\n features: Record<string, RewriteCacheEntry>;\n flows: Record<string, RewriteCacheEntry>;\n}\n\nexport interface SyncState {\n version: 2;\n syncedAt: string;\n pageIds: {\n index?: string;\n changelog?: string;\n features: Record<string, string>;\n };\n lastSnapshot: {\n features: Record<string, { description: string }>;\n flows: Record<string, { description: string }>;\n };\n changelogSections: string[];\n /** product-language prose cache, keyed by feature/flow name */\n rewriteCache: RewriteCache;\n /**\n * Hash of the body Mason last rendered for each page, keyed by page title.\n * Used to skip re-publishing unchanged pages — we compare our render hash to\n * this, never to Confluence's re-serialized body. Optional for forward\n * compatibility with state written before this field existed.\n */\n pageHashes?: Record<string, string>;\n}\n\n/** Stable content hash of a source description, for cache invalidation. */\nexport function hashDescription(description: string): string {\n return createHash(\"sha256\").update(description, \"utf8\").digest(\"hex\");\n}\n\nfunction syncStateDir(rootDir: string): string {\n return path.join(rootDir, \".mason\");\n}\n\nfunction syncStatePath(rootDir: string): string {\n return path.join(syncStateDir(rootDir), \"confluence-sync.json\");\n}\n\nexport async function loadSyncState(rootDir: string): Promise<SyncState | null> {\n try {\n const raw = await fs.readFile(syncStatePath(rootDir), \"utf-8\");\n const parsed = JSON.parse(raw);\n // Only v2 state is usable. Older state (v1) is treated as absent: the next\n // export re-finds pages by title and rebuilds the rewrite cache from scratch.\n if (parsed.version !== 2) return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\nexport async function saveSyncState(\n rootDir: string,\n state: SyncState\n): Promise<void> {\n await fs.mkdir(syncStateDir(rootDir), { recursive: true });\n await fs.writeFile(\n syncStatePath(rootDir),\n JSON.stringify(state, null, 2),\n \"utf-8\"\n );\n}\n\nexport function computeDiff(\n previous: SyncState | null,\n current: Snapshot,\n syncedAt: string\n): DiffSection {\n const prevFeatures = previous?.lastSnapshot.features ?? {};\n const prevFlows = previous?.lastSnapshot.flows ?? {};\n\n const currentFeatureNames = Object.keys(current.features);\n const prevFeatureNames = Object.keys(prevFeatures);\n\n const addedFeatures = currentFeatureNames.filter(\n (n) => !(n in prevFeatures)\n );\n const removedFeatures = prevFeatureNames.filter(\n (n) => !(n in current.features)\n );\n const changedFeatures = currentFeatureNames.filter(\n (n) =>\n n in prevFeatures &&\n prevFeatures[n].description !== current.features[n].description\n );\n\n const currentFlowNames = Object.keys(current.flows);\n const prevFlowNames = Object.keys(prevFlows);\n const addedFlows = currentFlowNames.filter((n) => !(n in prevFlows));\n const removedFlows = prevFlowNames.filter((n) => !(n in current.flows));\n\n return {\n syncedAt,\n addedFeatures,\n removedFeatures,\n changedFeatures,\n addedFlows,\n removedFlows,\n };\n}\n\nexport function isMeaningfulDiff(diff: DiffSection): boolean {\n return (\n diff.addedFeatures.length > 0 ||\n diff.removedFeatures.length > 0 ||\n diff.changedFeatures.length > 0 ||\n diff.addedFlows.length > 0 ||\n diff.removedFlows.length > 0\n );\n}\n\nexport function snapshotMinimal(snapshot: Snapshot): SyncState[\"lastSnapshot\"] {\n const features: Record<string, { description: string }> = {};\n for (const [k, v] of Object.entries(snapshot.features)) {\n features[k] = { description: v.description };\n }\n const flows: Record<string, { description: string }> = {};\n for (const [k, v] of Object.entries(snapshot.flows)) {\n flows[k] = { description: v.description };\n }\n return { features, flows };\n}\n","import { execFile, spawn } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { MasonConfig } from \"./config.js\";\nimport { getDefaultModel } from \"./config.js\";\n\nconst exec = promisify(execFile);\n\nconst CLAUDE_MD_SYSTEM_PROMPT = `You are Mason, a context engineering tool. You've been given a comprehensive analysis of a codebase including:\n- Git history stats (commit patterns, frequently changed files, stale directories)\n- Project structure (directory layout, file counts by type)\n- Curated code samples (key architectural files with previews)\n- Test-to-source file mapping\n\nYour job: write a COMPLETE CLAUDE.md file from scratch based ONLY on the analysis data provided below. Do NOT read any existing files in the project. Do NOT reference or preserve any existing CLAUDE.md. Generate the entire document fresh.\n\nCRITICAL: Output ONLY the raw markdown content. No preamble, no summary, no \"Here's the CLAUDE.md:\", no explanation, no questions, no commentary. Start directly with \"# CLAUDE.md\" and end with the last line of content. Your entire response will be written directly to a file.\n\nThe CLAUDE.md should include:\n- Project overview (what it is, tech stack, architecture)\n- Module/package structure and boundaries\n- Code conventions and patterns you observe in the samples\n- Testing conventions and coverage\n- Build and development commands\n- Important files and hot spots\n- Any warnings or gotchas\n\nBe specific and actionable. Reference actual file paths. Don't be generic — every rule should be grounded in what you see in the data.`;\n\nexport type CallResult =\n | { type: \"response\"; text: string }\n | { type: \"prompt\"; text: string };\n\nexport async function callLLM(\n config: MasonConfig,\n userMessage: string,\n systemPrompt?: string\n): Promise<CallResult> {\n const model = config.model ?? getDefaultModel(config.provider);\n const system = systemPrompt ?? CLAUDE_MD_SYSTEM_PROMPT;\n\n switch (config.provider) {\n case \"claude\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callClaudeAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"response\",\n text: await callClaudeCLI(system, userMessage),\n };\n\n case \"ollama\":\n return {\n type: \"response\",\n text: await callOllamaCLI(\n config.ollamaHost ?? \"http://localhost:11434\",\n model,\n system,\n userMessage,\n ),\n };\n\n case \"gemini\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callGeminiAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"response\",\n text: await callGeminiCLI(system, userMessage),\n };\n\n case \"openai\":\n if (config.apiKey) {\n return {\n type: \"response\",\n text: await callOpenAIAPI(config.apiKey, model, system, userMessage),\n };\n }\n return {\n type: \"prompt\",\n text: formatPromptForCopy(system, userMessage),\n };\n }\n}\n\nfunction formatPromptForCopy(system: string, userMessage: string): string {\n return `${system}\\n\\n---\\n\\n${userMessage}`;\n}\n\n// === CLI-based providers (no API key) ===\n\nasync function callViaTempFile(\n command: string,\n args: (promptPath: string) => string[],\n system: string,\n userMessage: string\n): Promise<string> {\n const fs = await import(\"node:fs/promises\");\n const os = await import(\"node:os\");\n const path = await import(\"node:path\");\n\n const prompt = `${system}\\n\\n${userMessage}`;\n const tmpFile = path.join(os.tmpdir(), `mason-prompt-${Date.now()}.txt`);\n\n try {\n await fs.writeFile(tmpFile, prompt, \"utf-8\");\n const { stdout } = await exec(command, args(tmpFile), {\n maxBuffer: 10_000_000,\n timeout: 300_000,\n });\n return stdout.trim();\n } finally {\n await fs.unlink(tmpFile).catch(() => {});\n }\n}\n\nfunction spawnWithStdin(\n command: string,\n args: string[],\n input: string\n): Promise<string> {\n return new Promise((resolve, reject) => {\n const proc = spawn(command, args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n timeout: 300_000,\n });\n\n // ora puts stdin into raw mode, which means Ctrl+C is emitted as\n // process.emit(\"SIGINT\") rather than a real signal to the process\n // group. Forward it to the child so it can terminate.\n const onSigint = () => proc.kill(\"SIGINT\");\n process.on(\"SIGINT\", onSigint);\n\n let stdout = \"\";\n let stderr = \"\";\n\n proc.stdout.on(\"data\", (data: Buffer) => {\n stdout += data.toString();\n });\n proc.stderr.on(\"data\", (data: Buffer) => {\n stderr += data.toString();\n });\n\n proc.on(\"close\", (code: number | null) => {\n process.off(\"SIGINT\", onSigint);\n if (code === 0) {\n resolve(stdout.trim());\n } else {\n reject(new Error(`${command} exited with code ${code}: ${stderr}`));\n }\n });\n\n proc.on(\"error\", (err) => {\n process.off(\"SIGINT\", onSigint);\n reject(err);\n });\n\n proc.stdin.write(input);\n proc.stdin.end();\n });\n}\n\nasync function callClaudeCLI(\n system: string,\n userMessage: string\n): Promise<string> {\n return spawnWithStdin(\"claude\", [\"-p\", \"--system-prompt\", system], userMessage);\n}\n\nasync function callGeminiCLI(\n system: string,\n userMessage: string\n): Promise<string> {\n const prompt = `<system>\\n${system}\\n</system>\\n\\n${userMessage}`;\n return spawnWithStdin(\"gemini\", [\"-p\", \"\"], prompt);\n}\n\nasync function callOllamaCLI(\n host: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const response = await fetch(`${host}/api/chat`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n model,\n stream: false,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n }),\n });\n\n const result = (await response.json()) as {\n message?: { content?: string };\n };\n return result.message?.content ?? \"\";\n}\n\n// === API-based providers ===\n\nasync function callClaudeAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: Anthropic } = await import(\"@anthropic-ai/sdk\");\n const client = new Anthropic({ apiKey });\n\n const response = await client.messages.create({\n model,\n max_tokens: 8192,\n system,\n messages: [{ role: \"user\", content: userMessage }],\n });\n\n const textBlock = response.content.find((b) => b.type === \"text\");\n return textBlock?.text ?? \"\";\n}\n\nasync function callGeminiAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: OpenAI } = await import(\"openai\");\n const client = new OpenAI({\n apiKey,\n baseURL: \"https://generativelanguage.googleapis.com/v1beta/openai/\",\n });\n\n const response = await client.chat.completions.create({\n model,\n max_tokens: 8192,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n });\n\n return response.choices[0]?.message?.content ?? \"\";\n}\n\nasync function callOpenAIAPI(\n apiKey: string,\n model: string,\n system: string,\n userMessage: string\n): Promise<string> {\n const { default: OpenAI } = await import(\"openai\");\n const client = new OpenAI({ apiKey });\n\n const response = await client.chat.completions.create({\n model,\n max_tokens: 8192,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: userMessage },\n ],\n });\n\n return response.choices[0]?.message?.content ?? \"\";\n}\n","import { callLLM } from \"../llm/providers.js\";\nimport type { MasonConfig } from \"../llm/config.js\";\nimport type {\n FeatureEntry,\n FlowEntry,\n Snapshot,\n} from \"../snapshot/snapshot.js\";\nimport {\n hashDescription,\n type RewriteCache,\n type RewriteCacheEntry,\n} from \"./diff.js\";\n\nconst PM_REWRITE_SYSTEM_PROMPT = `You are Mason, rewriting an engineering-flavoured concept map into product-readable language for a company wiki.\n\nYou will receive a JSON object with two maps:\n- \"features\": each entry has a description and a list of source file paths.\n- \"flows\": each entry has a description and an ordered chain of file paths.\n\nYour job: rewrite EACH description so a Product Manager, designer, or non-engineering stakeholder can understand what the system does — without seeing any code. Treat the file paths as hints, not content. Do NOT include them in your output.\n\nHard rules:\n- NEVER mention file names, directory names, file extensions, class names, function names, repository names, framework names, or libraries.\n- NEVER use words like \"module\", \"service\", \"handler\", \"controller\", \"ViewModel\", \"repository\", \"endpoint\", \"API\", \"schema\", \"interface\", \"class\".\n- Use plain English. Focus on what users or the business can do, what data moves, what decisions get made, and why it matters.\n- 1–3 sentences per description. Concrete. No filler.\n- Preserve the original keys exactly; only the description values change.\n\nOutput ONLY raw JSON with the same shape as the input — same keys, rewritten descriptions. No markdown, no code fences, no preamble.`;\n\ntype Rewritten = {\n features: Record<string, string>;\n flows: Record<string, string>;\n};\n\ninterface RewriteInput {\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n}\n\nfunction buildPrompt(input: RewriteInput): string {\n return `Rewrite the descriptions below for a product audience. Return ONLY a JSON object of the form {\"features\": {\"name\": \"rewritten description\", ...}, \"flows\": {...}}.\\n\\n${JSON.stringify(input, null, 2)}`;\n}\n\nfunction parseRewriteResponse(raw: string): Rewritten {\n let cleaned = raw.trim();\n if (cleaned.startsWith(\"```\")) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, \"\").replace(/\\n?```$/, \"\");\n }\n try {\n const parsed = JSON.parse(cleaned);\n return {\n features: parsed.features ?? {},\n flows: parsed.flows ?? {},\n };\n } catch {\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (match) {\n try {\n const parsed = JSON.parse(match[0]);\n return {\n features: parsed.features ?? {},\n flows: parsed.flows ?? {},\n };\n } catch {\n return { features: {}, flows: {} };\n }\n }\n return { features: {}, flows: {} };\n }\n}\n\nexport interface RewriteResult {\n features: Record<string, string>;\n flows: Record<string, string>;\n /** Updated prose cache to persist into the sync state. */\n cache: RewriteCache;\n}\n\nexport interface RewriteContext {\n /** Prose cache from the previous sync; used to skip unchanged entries. */\n previousCache?: RewriteCache;\n /** LLM caller; injectable for tests. Defaults to the configured provider. */\n llm?: typeof callLLM;\n}\n\n/** Pick a subset of a record by key. */\nfunction pick<T>(source: Record<string, T>, keys: string[]): Record<string, T> {\n const out: Record<string, T> = {};\n for (const k of keys) out[k] = source[k];\n return out;\n}\n\n/**\n * Rewrite engineering descriptions into product-readable prose, incrementally.\n *\n * Entries whose source description is unchanged since the last sync (matched by\n * content hash) reuse their cached prose verbatim — no LLM call. Only new or\n * changed entries are sent to the model, batched into a single request. When\n * nothing changed, the LLM is not invoked at all.\n */\nexport async function rewriteForProduct(\n snapshot: Snapshot,\n config: MasonConfig,\n ctx: RewriteContext = {}\n): Promise<RewriteResult> {\n const featureHashes = hashEntries(snapshot.features);\n const flowHashes = hashEntries(snapshot.flows);\n\n const missFeatures = missingNames(\n snapshot.features,\n featureHashes,\n ctx.previousCache?.features\n );\n const missFlows = missingNames(\n snapshot.flows,\n flowHashes,\n ctx.previousCache?.flows\n );\n\n let parsed: Rewritten = { features: {}, flows: {} };\n if (missFeatures.length > 0 || missFlows.length > 0) {\n const input: RewriteInput = {\n features: pick(snapshot.features, missFeatures),\n flows: pick(snapshot.flows, missFlows),\n };\n const prompt = buildPrompt(input);\n const llm = ctx.llm ?? callLLM;\n const result = await llm(config, prompt, PM_REWRITE_SYSTEM_PROMPT);\n const text =\n typeof result === \"string\"\n ? result\n : result.type === \"response\"\n ? result.text\n : \"\";\n // Empty text means no API/CLI is available — leave `parsed` empty so every\n // miss falls back to its engineering description (cached as fallback).\n if (text) parsed = parseRewriteResponse(text);\n }\n\n const features = resolve(\n snapshot.features,\n featureHashes,\n parsed.features,\n ctx.previousCache?.features\n );\n const flows = resolve(\n snapshot.flows,\n flowHashes,\n parsed.flows,\n ctx.previousCache?.flows\n );\n\n return {\n features: features.descriptions,\n flows: flows.descriptions,\n cache: { features: features.cache, flows: flows.cache },\n };\n}\n\nfunction hashEntries(\n entries: Record<string, { description: string }>\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [name, entry] of Object.entries(entries)) {\n out[name] = hashDescription(entry.description);\n }\n return out;\n}\n\n/** A cache entry is a hit only if the source hash matches and it isn't a fallback. */\nfunction isHit(\n prev: RewriteCacheEntry | undefined,\n hash: string\n): prev is RewriteCacheEntry {\n return !!prev && prev.sourceHash === hash && !prev.fallback;\n}\n\nfunction missingNames(\n entries: Record<string, { description: string }>,\n hashes: Record<string, string>,\n prevCache: Record<string, RewriteCacheEntry> | undefined\n): string[] {\n return Object.keys(entries).filter(\n (name) => !isHit(prevCache?.[name], hashes[name])\n );\n}\n\n/**\n * Build the final prose map + next cache for one collection (features or flows):\n * reuse cached prose on a hit, take fresh model prose on a miss, or fall back to\n * the engineering description (marked `fallback`) when the model omitted it.\n */\nfunction resolve(\n entries: Record<string, { description: string }>,\n hashes: Record<string, string>,\n rewritten: Record<string, string>,\n prevCache: Record<string, RewriteCacheEntry> | undefined\n): { descriptions: Record<string, string>; cache: Record<string, RewriteCacheEntry> } {\n const descriptions: Record<string, string> = {};\n const cache: Record<string, RewriteCacheEntry> = {};\n\n for (const [name, entry] of Object.entries(entries)) {\n const hash = hashes[name];\n const prev = prevCache?.[name];\n\n if (isHit(prev, hash)) {\n descriptions[name] = prev.product;\n cache[name] = { sourceHash: hash, product: prev.product };\n continue;\n }\n\n const fresh = rewritten[name];\n if (typeof fresh === \"string\" && fresh.trim().length > 0) {\n descriptions[name] = fresh;\n cache[name] = { sourceHash: hash, product: fresh };\n } else {\n // No usable model output — keep the engineering description and mark it a\n // fallback so a later successful run re-attempts it.\n descriptions[name] = entry.description;\n cache[name] = { sourceHash: hash, product: entry.description, fallback: true };\n }\n }\n\n return { descriptions, cache };\n}\n","import { loadSnapshot } from \"../snapshot/snapshot.js\";\nimport type { MasonConfig, ConfluenceConfig } from \"../llm/config.js\";\nimport { createConfluenceClient, type ConfluenceClient } from \"./client.js\";\nimport {\n renderFeaturePage,\n renderIndexPage,\n renderChangelogPage,\n renderChangelogSection,\n flowsForFeature,\n featurePageTitle,\n} from \"./renderer.js\";\nimport {\n computeDiff,\n isMeaningfulDiff,\n loadSyncState,\n saveSyncState,\n snapshotMinimal,\n hashDescription,\n type SyncState,\n} from \"./diff.js\";\nimport {\n rewriteForProduct,\n type RewriteResult,\n type RewriteContext,\n} from \"./rewrite.js\";\nimport type { FeatureEntry, Snapshot } from \"../snapshot/snapshot.js\";\n\nexport interface SyncOptions {\n indexPageTitle?: string;\n changelogPageTitle?: string;\n featurePagePrefix?: string;\n}\n\nexport interface SyncSummary {\n created: string[];\n updated: string[];\n unchanged: string[];\n indexPageId: string;\n changelogPageId: string;\n hadChanges: boolean;\n}\n\nexport interface SyncDeps {\n client: ConfluenceClient;\n rewrite: (\n snapshot: Snapshot,\n config: MasonConfig,\n ctx: RewriteContext\n ) => Promise<RewriteResult>;\n}\n\nconst DEFAULT_INDEX_TITLE = \"Mason — System Map\";\nconst DEFAULT_CHANGELOG_TITLE = \"Mason — Changelog\";\nconst DEFAULT_FEATURE_PREFIX = \"Feature: \";\n\nexport async function exportToConfluence(\n rootDir: string,\n config: MasonConfig,\n options: SyncOptions = {},\n deps?: Partial<SyncDeps>\n): Promise<SyncSummary> {\n const confluence = config.confluence;\n if (!confluence) {\n throw new Error(\n \"No Confluence credentials configured. Ask your assistant to call mason_set_confluence first.\"\n );\n }\n\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n throw new Error(\n \"No snapshot found. Build the concept map first (ask your assistant to run mason_init and follow the playbook).\"\n );\n }\n\n const client = deps?.client ?? createConfluenceClient(confluence);\n const rewrite = deps?.rewrite ?? rewriteForProduct;\n\n // Only user-facing capabilities are published to the wiki. Infrastructure\n // features (DI wiring, config, logging, provider plumbing) stay in the AI\n // concept map but never become PM-facing pages. Filter once here; everything\n // downstream — rewrite, index, feature pages, changelog diff, persisted\n // state — operates on this published subset. Missing type defaults to\n // \"capability\" (see normalizeFeatureType), so older snapshots publish as before.\n const publishedFeatures: Record<string, FeatureEntry> = {};\n for (const [name, entry] of Object.entries(snapshot.features)) {\n if (entry.type !== \"infrastructure\") publishedFeatures[name] = entry;\n }\n const publishSnapshot: Snapshot = { ...snapshot, features: publishedFeatures };\n\n const indexTitle = options.indexPageTitle ?? DEFAULT_INDEX_TITLE;\n const changelogTitle = options.changelogPageTitle ?? DEFAULT_CHANGELOG_TITLE;\n const featurePrefix = options.featurePagePrefix ?? DEFAULT_FEATURE_PREFIX;\n\n const spaceId = await client.resolveSpaceId(confluence.spaceKey);\n // Wall-clock time is used ONLY for the append-only changelog heading. Page\n // bodies carry no timestamp/hash, so a page is re-published only when its own\n // content (description/flows) changes — not on every unrelated commit.\n const syncedAt = new Date().toISOString();\n const previousState = await loadSyncState(rootDir);\n const previousHashes = previousState?.pageHashes ?? {};\n const nextHashes: Record<string, string> = {};\n\n const productLanguage = await rewrite(publishSnapshot, config, {\n previousCache: previousState?.rewriteCache,\n });\n\n // 1. Upsert index page (so feature pages can hang under it)\n const indexBody = renderIndexPage({\n featureTitles: Object.keys(publishSnapshot.features),\n featurePrefix,\n });\n\n const indexPage = await upsertPage({\n client,\n spaceId,\n title: indexTitle,\n parentId: confluence.parentPageId,\n renderedBody: indexBody,\n previousHash: previousHashes[indexTitle],\n });\n nextHashes[indexTitle] = indexPage.hash;\n\n // 2. Upsert each feature page under the index\n const created: string[] = [];\n const updated: string[] = [];\n const unchanged: string[] = [];\n const featurePageIds: Record<string, string> = {};\n\n for (const [name, entry] of Object.entries(publishSnapshot.features)) {\n const title = featurePageTitle(featurePrefix, name);\n const productDescription =\n productLanguage.features[name] ?? entry.description;\n const relatedFlows = flowsForFeature(entry.files, publishSnapshot.flows).map(\n (f) => ({\n name: f.name,\n description: productLanguage.flows[f.name] ?? f.description,\n })\n );\n\n const rendered = renderFeaturePage({\n name,\n productDescription,\n flowDescriptions: relatedFlows,\n indexPageTitle: indexTitle,\n });\n\n const result = await upsertPage({\n client,\n spaceId,\n title,\n parentId: indexPage.id,\n renderedBody: rendered.body,\n previousHash: previousHashes[title],\n });\n nextHashes[title] = result.hash;\n\n featurePageIds[name] = result.id;\n if (result.outcome === \"created\") created.push(title);\n else if (result.outcome === \"updated\") updated.push(title);\n else unchanged.push(title);\n }\n\n // 3. Diff + changelog page\n const diff = computeDiff(previousState, publishSnapshot, syncedAt);\n const hadChanges = previousState === null || isMeaningfulDiff(diff);\n\n const previousSections = previousState?.changelogSections ?? [];\n let newSections = previousSections;\n if (hadChanges) {\n const section = renderChangelogSection(diff);\n newSections = [section, ...previousSections].slice(0, 50);\n }\n\n const changelogBody = renderChangelogPage(newSections);\n const changelogPage = await upsertPage({\n client,\n spaceId,\n title: changelogTitle,\n parentId: indexPage.id,\n renderedBody: changelogBody,\n previousHash: previousHashes[changelogTitle],\n });\n nextHashes[changelogTitle] = changelogPage.hash;\n\n // 4. Persist sync state\n const nextState: SyncState = {\n version: 2,\n syncedAt,\n pageIds: {\n index: indexPage.id,\n changelog: changelogPage.id,\n features: featurePageIds,\n },\n lastSnapshot: snapshotMinimal(publishSnapshot),\n changelogSections: newSections,\n rewriteCache: productLanguage.cache,\n pageHashes: nextHashes,\n };\n await saveSyncState(rootDir, nextState);\n\n return {\n created,\n updated,\n unchanged,\n indexPageId: indexPage.id,\n changelogPageId: changelogPage.id,\n hadChanges,\n };\n}\n\ninterface UpsertArgs {\n client: ConfluenceClient;\n spaceId: string;\n title: string;\n parentId?: string;\n renderedBody: string;\n /** Hash of the body we published for this page last sync, if any. */\n previousHash?: string;\n}\n\ninterface UpsertResult {\n id: string;\n outcome: \"created\" | \"updated\" | \"unchanged\";\n /** Hash of the body published this sync — persist for next-run comparison. */\n hash: string;\n}\n\nasync function upsertPage(args: UpsertArgs): Promise<UpsertResult> {\n const hash = hashDescription(args.renderedBody);\n const existing = await args.client.findPageByTitle(args.spaceId, args.title);\n\n if (!existing) {\n const page = await args.client.createPage({\n spaceId: args.spaceId,\n title: args.title,\n parentId: args.parentId,\n body: args.renderedBody,\n });\n return { id: page.id, outcome: \"created\", hash };\n }\n\n // Confluence re-serializes stored bodies (strips comments, re-encodes\n // entities, injects macro ids), so we can't compare against existing.body.\n // Compare our render hash to the hash we stored last sync instead. When it\n // matches, the page is already current — skip the write entirely.\n if (args.previousHash === hash) {\n return { id: existing.id, outcome: \"unchanged\", hash };\n }\n\n // Mason owns the whole page body: overwrite it wholesale.\n const updated = await args.client.updatePage({\n id: existing.id,\n title: args.title,\n parentId: args.parentId,\n body: args.renderedBody,\n version: existing.version,\n });\n return { id: updated.id, outcome: \"updated\", hash };\n}\n","import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\";\nimport { z } from \"zod\";\nimport { attributionSchema } from \"../decisions/provenance.js\";\nimport {\n analyzeProject,\n checkDrift,\n exportToConfluenceTool,\n fullAnalysis,\n generateSnapshotBatch,\n getCodeSamples,\n getContext,\n getImpact,\n getSnapshot,\n saveDecision,\n reviewDecision,\n saveVerification,\n verifySnapshot,\n masonCompleteInit,\n masonInit,\n masonRepair,\n masonAutomation,\n masonSetConfluence,\n reduceSnapshot,\n saveSnapshotData,\n saveSnapshotPartial,\n} from \"./tools.js\";\n\ndeclare const PKG_VERSION: string;\n\nexport function createMcpServer(): McpServer {\n const server = new McpServer(\n {\n name: \"mason\",\n version: PKG_VERSION,\n },\n {\n instructions:\n \"Mason retrieves recorded decisions, file impact, and optional feature/flow maps. Use get_context with the task and known files, and get_impact before editing. Save learned rationale and constraints with save_decision; review and commit the local records through the project workflow. These tools work without initialization or a concept map. Consult trust and diagnostics: changed or unknown freshness needs source inspection, failed verification needs correction, and proposals are suggestions and legacy records are unreviewed. Accepted decisions are recorded team constraints, still subject to freshness checks. Use review_decision to prepare code evidence and record only authorized acceptance, reaffirmation, or retirement. Never invent a reviewer or treat these recorded identities as authenticated approval. mason_init returns documentation audit and committed-diff review findings with a quickstart guide. Use mode: \\\"map\\\" only when a full architecture map is requested. A missing map is not a setup failure; use decisions and source evidence. get_snapshot provides architecture navigation when a map is available. The mason-audit and mason-review CLIs also work without setup.\",\n }\n );\n\n server.tool(\n \"mason_init\",\n \"Inspect this project now: returns documentation audit findings, committed-diff review findings, decision/map status, and a quickstart playbook. Quickstart and map modes are read-only and deterministic. Explicit mode: setup installs a pinned project runtime, MCP configuration, instructions and lifecycle hooks while retaining original audit evidence; use it only when the user requests setup. Optional host selects codex or claude. Optional base selects the review comparison; evidence imports CI manifests with check outcomes, commit freshness, and links to changed files and accepted decisions. mode: map returns the full Map-Reduce build workflow. Repeat calls refresh findings even after setup.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n mode: z.enum([\"quickstart\", \"map\", \"setup\"]).optional().default(\"quickstart\")\n .describe(\"Quickstart inspects without edits; map requests an architecture build; setup installs the shared onboarding flow.\"),\n host: z.enum([\"codex\", \"claude\"]).optional().describe(\"Assistant to configure in setup mode; inferred only when unambiguous.\"),\n base: z.string().optional().describe(\"Git ref for committed-diff review. Defaults to the first available main branch ref.\"),\n evidence: z.array(z.string()).max(10).optional().describe(\"Repository-local CI evidence manifests to include in the review. Imports Vitest JSON and SARIF without executing check commands.\"),\n },\n async ({ dir, mode, host, base, evidence }) => {\n const result = await masonInit(dir, { mode, host, base, evidence });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_automation\",\n \"Inspect installed automation and observed host events, or resume/check retained documentation repair evidence across sessions. status is read-only; check saves local baselines and verification reports without editing source or approving advisories. Returns concise results with a full report path. Works without a map.\",\n {\n dir: z.string().describe(\"Absolute path to the project directory\"),\n action: z.enum([\"status\", \"check\"]).describe(\"Inspect configuration and receipts, or capture/resume and verify original audit evidence.\"),\n },\n async ({ dir, action }) => ({ content: [{ type: \"text\", text: await masonAutomation(dir, action) }] })\n );\n\n server.tool(\n \"mason_repair\",\n \"Track documentation repairs against original audit evidence. prepare saves a local baseline and returns a scoped work order; verify reads that baseline and reports resolved, unresolved, review-required, unverified, and new findings. Suppressed advisories remain unresolved. Does not edit documentation or approve decisions. No map required.\",\n {\n dir: z.string().describe(\"Absolute path to the project root directory\"),\n action: z.enum([\"prepare\", \"verify\"]),\n baselinePath: z.string().optional().describe(\"Original baseline path returned by prepare; required for verify.\"),\n checks: z.array(z.enum([\"deleted-reference\", \"new-module\", \"stale-count\", \"dead-command\", \"deps-changed\", \"decision-anchor-drift\"]))\n .min(1).optional().describe(\"Optional audit check subset for prepare. Verification always uses the original checks.\"),\n },\n async ({ dir, action, baselinePath, checks }) => {\n const result = await masonRepair(dir, { action, baselinePath, checks });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_complete_init\",\n \"Record completion of assistant instruction setup in .mason/project.json. Other tools work without this marker. Repeated calls preserve the original setup time and existing settings; pass confluenceConfigured only to change that setting.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n confluenceConfigured: z\n .boolean()\n .optional()\n .describe(\"Set the Confluence setup status; omit to preserve the existing value\"),\n },\n async ({ dir, confluenceConfigured }) => {\n const result = await masonCompleteInit(dir, { confluenceConfigured });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_set_confluence\",\n \"Configure Confluence credentials. Two-step flow: (1) call without `spaceKey` to validate the credentials and receive a list of available spaces — relay them to the user. (2) call again with the same `baseUrl`/`email`/`apiToken` plus the chosen `spaceKey` to persist. Credentials are stored in `~/.mason/config.json`. Warn the user that the API token will be visible in chat history before they paste it.\",\n {\n baseUrl: z\n .string()\n .describe(\"Confluence base URL. Accepts `acme`, `acme.atlassian.net`, or `https://acme.atlassian.net` (normalized automatically).\"),\n email: z.string().describe(\"User's Atlassian account email\"),\n apiToken: z\n .string()\n .describe(\"API token from id.atlassian.com/manage-profile/security/api-tokens\"),\n spaceKey: z\n .string()\n .optional()\n .describe(\"Confluence space key. Omit on the first call to list available spaces.\"),\n parentPageId: z\n .string()\n .optional()\n .describe(\"Optional parent page ID under which Mason's index page is created\"),\n },\n async ({ baseUrl, email, apiToken, spaceKey, parentPageId }) => {\n const result = await masonSetConfluence({\n baseUrl,\n email,\n apiToken,\n spaceKey,\n parentPageId,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"full_analysis\",\n \"One-shot orientation for a project WITHOUT a concept map (get_snapshot returned exists:false). Returns git history stats, project structure with file counts, curated code sample previews (~60 lines each), and test-to-source mapping. On a mapped project, prefer get_snapshot — it is cheaper and answers feature/architecture questions directly.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await fullAnalysis(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"analyze_project\",\n \"Run git history analysis on a codebase. Returns commit convention patterns, stale directories, and frequently changed files. These are aggregate stats across hundreds of commits that would be expensive to compute manually.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await analyzeProject(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_code_samples\",\n \"Get previews (first ~60 lines) of representative source files from the codebase. Includes entry points, config files, hot files (frequently changed), test examples, and one file per directory for breadth. Read files natively for full content.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n count: z\n .number()\n .optional()\n .default(15)\n .describe(\"Maximum number of files to sample (default: 15)\"),\n },\n async ({ dir, count }) => {\n const result = await getCodeSamples(dir, count);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_snapshot\",\n \"Return the optional feature-to-file architecture map with drift and trust evidence. If no map exists, returns exists:false plus project structure, Git signals, and test pairs. Decision capture, get_context, and get_impact still work. No initialization required.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await getSnapshot(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"get_context\",\n \"Assemble task context: matching decisions with rationale, approval, owner, sources, last review, and freshness, plus related tests, file impact, and any available map entries. Proposals are suggestions; legacy records are unreviewed; accepted decisions are constraints subject to freshness. No initialization or map required. Pass task and optional files. map.status and diagnostics preserve missing or invalid knowledge. Impact covers up to three unique files, expanding directory anchors.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n task: z\n .string()\n .describe(\"The task, bug, or change request in natural language — e.g. 'add rate limiting to the API client' or a ticket description\"),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Optional file paths already known to be involved (e.g. from a diff or stack trace). Entries containing them are boosted above pure text matches.\"),\n },\n async ({ dir, task, files }) => {\n const result = await getContext(dir, task, files);\n const { observeActivation } = await import(\"../setup/observations.js\");\n const warning = await observeActivation(dir, \"context\");\n if (warning) return { content: [{ type: \"text\", text: result }, { type: \"text\", text: warning }] };\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"generate_snapshot_batch\",\n \"Map step of the concept-map build. Returns one batch of source files (skeletons of every file in the batch plus a few deeper-read bodies for grounding), along with a system prompt instructing you to derive features and flows for ONLY this batch. Call repeatedly with the returned `nextOffset` until it is null, calling `save_partial_snapshot` between each call. Use product-natural feature names so partials merge cleanly in the reduce step.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n offset: z\n .number()\n .int()\n .optional()\n .describe(\"0-indexed file offset to start the batch at. Omit on the first call; pass the `nextOffset` from the previous response for subsequent calls.\"),\n batchSize: z\n .number()\n .int()\n .optional()\n .describe(\"Files per batch. Defaults to 50.\"),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Scope the batch walk to this explicit file list — e.g. the drift set from mason_check_drift (changedFiles + unmappedFiles). Pass the SAME list on every batch call of one refresh run. Triggers refresh mode: reduce_snapshot will merge the partials into the existing map instead of rebuilding it.\"),\n },\n async ({ dir, offset, batchSize, files }) => {\n const result = await generateSnapshotBatch(dir, offset, batchSize, files);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_partial_snapshot\",\n \"Persist the partial concept map you derived for one batch. Call this once per batch, with the `batchId` from the `generate_snapshot_batch` response. Partials accumulate in `.mason/partial-snapshots/` and are merged in the reduce step.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n batchId: z\n .string()\n .describe(\"The `batchId` returned by `generate_snapshot_batch`.\"),\n offset: z\n .number()\n .int()\n .describe(\"The `offset` returned by `generate_snapshot_batch`. Used to order partials in the reduce step.\"),\n features: z\n .record(\n z.object({\n description: z.string(),\n files: z.array(z.string()),\n tests: z.array(z.string()).optional(),\n type: z\n .enum([\"capability\", \"infrastructure\"])\n .optional()\n .describe(\n '\"capability\" (user-facing functionality) or \"infrastructure\" (internal plumbing with no end user — DI/service wiring, config, logging, adapters). Defaults to \"capability\".'\n ),\n })\n )\n .describe(\"Partial features for this batch only — files outside the batch will be added by other partials.\"),\n flows: z\n .record(\n z.object({\n description: z.string(),\n chain: z.array(z.string()),\n })\n )\n .describe(\"Partial flows whose entire chain is in this batch. Cross-batch flows are reconstructed in reduce.\"),\n },\n async ({ dir, batchId, offset, features, flows }) => {\n const result = await saveSnapshotPartial(dir, batchId, offset, features, flows);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"reduce_snapshot\",\n \"Reduce step of the concept-map build. Returns every partial snapshot plus a system prompt asking you to merge them into one coherent project-wide map. Resolve platform variants into single product features, dedupe near-duplicates, and ensure no file is dropped. After producing the unified map, call `save_snapshot` to persist it (this also clears the partials).\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await reduceSnapshot(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_snapshot\",\n \"Save a concept-to-files map as a persistent project snapshot. Maps feature names and data flows to the files that implement them. Persists across conversations — future sessions can call get_snapshot to instantly find relevant files. No API key needed — you are the LLM generating the map.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n features: z\n .record(\n z.object({\n description: z.string().describe(\"One-line description of the feature\"),\n files: z.array(z.string()).describe(\"File paths that implement this feature\"),\n tests: z.array(z.string()).optional().describe(\"Test file paths for this feature\"),\n type: z\n .enum([\"capability\", \"infrastructure\"])\n .optional()\n .describe(\n 'Classification: \"capability\" for user-facing functionality, \"infrastructure\" for internal plumbing with no end user (DI/service wiring, config, logging, adapters). Capabilities are published to Confluence; infrastructure stays in the AI concept map only. Defaults to \"capability\".'\n ),\n })\n )\n .describe(\"Map of feature names to their implementing files\"),\n flows: z\n .record(\n z.object({\n description: z.string().describe(\"One-line description of the flow\"),\n chain: z.array(z.string()).describe(\"Ordered list of file paths showing data/call flow\"),\n })\n )\n .describe(\"Map of flow names to ordered file chains\"),\n removeFeatures: z\n .array(z.string())\n .optional()\n .describe(\"Feature names to delete from the existing map — for features that were renamed or no longer exist. Applied before merging; only meaningful on incremental saves.\"),\n removeFlows: z\n .array(z.string())\n .optional()\n .describe(\"Flow names to delete from the existing map. Applied before merging; only meaningful on incremental saves.\"),\n },\n async ({ dir, features, flows, removeFeatures, removeFlows }) => {\n const result = await saveSnapshotData(\n dir,\n features,\n flows,\n removeFeatures ?? [],\n removeFlows ?? []\n );\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"save_decision\",\n \"Capture or revise a decision proposal with rationale, anchors, optional owner, sources, and a known actor. No setup or map required. Writes a local record and preserves content history. Changes create a pending proposal while the last accepted revision remains operative; unchanged content does not re-verify or refresh it. Use review_decision for authorized acceptance or reaffirmation. A proposal cannot supersede a record with an operative accepted revision; review its replacement and retire the original separately.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n title: z\n .string()\n .max(80)\n .describe(\"Short, specific headline — becomes the stable record id\"),\n body: z\n .string()\n .max(1500)\n .describe(\"The knowledge itself: what was tried/decided, why, and what to avoid. Must contain information NOT derivable by reading the code.\"),\n category: z.enum([\"decision\", \"gotcha\", \"deprecation\", \"convention\"]),\n files: z\n .array(z.string())\n .optional()\n .describe(\"Repo-relative files or directory prefixes this applies to. Matching is shared by retrieval, hooks, review, and drift checking; changes flag the decision for re-verification.\"),\n id: z\n .string()\n .optional()\n .describe(\"Existing id to revise. Changed content becomes a proposal; unchanged content leaves the review and freshness untouched.\"),\n supersedes: z\n .string()\n .optional()\n .describe(\"Id of an unreviewed record or proposal with no accepted revision to replace. Operative accepted decisions require separate review and retirement.\"),\n owner: attributionSchema.shape.owner.describe(\"Responsible person or team, when known. Null clears it. Required for acceptance.\"),\n sources: attributionSchema.shape.sources.describe(\"Known PR, issue, incident, discussion, or document references. Omit to preserve; [] clears. At least one is required for acceptance.\"),\n actor: attributionSchema.shape.actor.describe(\"Known person or agent recording this revision. Omit if unknown; do not infer from Git identity.\"),\n force: z\n .boolean()\n .optional()\n .describe(\"Save even when a near-duplicate was detected\"),\n },\n async ({ dir, title, body, category, files, id, supersedes, force, owner, sources, actor }) => {\n const result = await saveDecision(dir, {\n title,\n body,\n category,\n files,\n id,\n supersedes,\n force,\n owner,\n sources,\n actor,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"review_decision\",\n \"Prepare a decision review: returns the full record and history, any operative accepted revision, provenance, changes and previews for both sets of anchors, and a reviewToken. Then record accept, reaffirm, or retire with that token, the authorized reviewer, and a reason. Acceptance replaces the operative revision; retirement withdraws the entire record including its proposal. Acceptance requires owner, source, readable Git HEAD, and committed anchor changes. Changed records or code invalidate the token. Identities and approvals are recorded assertions for normal PR review, not authenticated proof.\",\n {\n dir: z.string().describe(\"Absolute path to the project root directory\"),\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/).describe(\"Decision id from get_context or save_decision\"),\n action: z.enum([\"prepare\", \"accept\", \"reaffirm\", \"retire\"]).optional().default(\"prepare\")\n .describe(\"Prepare is read-only. Other actions record an explicitly authorized review.\"),\n reviewer: z.string().trim().min(1).max(200).optional().describe(\"Identity of the actual reviewer; required for a verdict. Never invent one.\"),\n note: z.string().trim().min(1).max(1500).optional().describe(\"Review rationale; required for a verdict. Cite evidence for the decision.\"),\n reviewToken: z.string().regex(/^[a-f0-9]{64}$/).optional().describe(\"Token from the prepared review; rejects stale record or code revisions\"),\n },\n async ({ dir, ...input }) => {\n const result = await reviewDecision(dir, input);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"mason_check_drift\",\n \"Check how far the concept map has drifted from HEAD. Deterministic (git + filesystem, no LLM). Returns which features/flows are stale and the changed files behind them, new source files not yet mapped, ghost files (mapped but deleted), renames, and a `recommendation`: `up-to-date` (nothing to do), `incremental` (update just the stale entries via save_snapshot), or `full-rebuild` (re-run the Map-Reduce build). Call this before trusting the map in a long session, or periodically to keep the map and any synced wikis fresh.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n },\n async ({ dir }) => {\n const result = await checkDrift(dir);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"verify_snapshot\",\n \"Spot-check the concept map's CORRECTNESS (drift checks freshness; this checks entries were right to begin with). Returns a sample of entries — always the never-verified and least-recently-verified first — with skeletons of their claimed files, for you to judge whether the files actually implement what the entry claims. Report verdicts back via save_verification. Run periodically, or after an automated refresh wrote entries no human reviewed.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n sample: z\n .number()\n .int()\n .optional()\n .describe(\"Entries to sample (default 5)\"),\n },\n async ({ dir, sample }) => {\n const result = await verifySnapshot(dir, sample);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"save_verification\",\n \"Record verify_snapshot verdicts. Entries judged ok are stamped verifiedAt; failures are flagged verificationFailed with your note and surface in get_context, get_snapshot, and mason_check_drift until corrected. Verdict notes are required for failures.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n verdicts: z\n .record(\n z.object({\n ok: z.boolean(),\n note: z\n .string()\n .optional()\n .describe(\"One line on what's wrong — required when ok is false\"),\n })\n )\n .describe(\"Entry name → verdict, exactly as returned by verify_snapshot\"),\n },\n async ({ dir, verdicts }) => {\n const result = await saveVerification(dir, verdicts);\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n server.tool(\n \"get_impact\",\n \"Trace the impact of changing files: historical co-change partners, references, and related tests. Deterministic, read-only, and usable without initialization, saved decisions, or a concept map.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n files: z\n .array(z.string())\n .describe(\"File paths or names to analyze (e.g., ['WeatherRepository.kt'] or ['src/services/auth.ts'])\"),\n },\n async ({ dir, files }) => {\n const result = await getImpact(dir, files);\n return {\n content: [{ type: \"text\", text: result }],\n };\n }\n );\n\n server.tool(\n \"export_to_confluence\",\n \"Sync the project's concept map to Confluence as product-readable wiki pages: an index page, one page per feature (PM-language descriptions, no file paths), and a changelog page. Mason replaces managed page bodies; manual edits to those bodies are overwritten. Requires `mason_set_confluence` to have been called first.\",\n {\n dir: z\n .string()\n .describe(\"Absolute path to the project root directory\"),\n spaceKey: z\n .string()\n .optional()\n .describe(\"Override the configured space key\"),\n parentPageId: z\n .string()\n .optional()\n .describe(\"Override the configured parent page ID\"),\n indexPageTitle: z\n .string()\n .optional()\n .describe(\"Title of the index page (default: 'Mason — System Map')\"),\n changelogPageTitle: z\n .string()\n .optional()\n .describe(\"Title of the changelog page (default: 'Mason — Changelog')\"),\n featurePagePrefix: z\n .string()\n .optional()\n .describe(\"Prefix for each feature page title (default: 'Feature: ')\"),\n },\n async ({ dir, spaceKey, parentPageId, indexPageTitle, changelogPageTitle, featurePagePrefix }) => {\n const result = await exportToConfluenceTool(dir, {\n spaceKey,\n parentPageId,\n indexPageTitle,\n changelogPageTitle,\n featurePagePrefix,\n });\n return { content: [{ type: \"text\", text: result }] };\n }\n );\n\n return server;\n}\n\nexport async function startMcpServer(): Promise<void> {\n const server = createMcpServer();\n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { prepareRepair, verifyRepair } from \"../audit/repair.js\";\nimport { formatFixPrompt } from \"../audit/cli.js\";\nimport type { CheckName } from \"../audit/types.js\";\n\nconst exec = promisify(execFile);\nimport { runAll } from \"../analyzers/index.js\";\nimport { isGitRepo } from \"../utils/git.js\";\nimport { sampleFiles } from \"./sampler.js\";\nimport { createFileAccess } from \"../utils/files.js\";\nimport { readStoreJson, writeStoreJson } from \"../utils/storage.js\";\nimport { sanitizeRepoPaths } from \"../utils/paths.js\";\nimport { assessTrust, trustHint, type TrustState } from \"../context/trust.js\";\nimport { compactDecisionKnowledge, effectiveDecision, decisionTrust, DECISION_GUIDANCE } from \"../decisions/provenance.js\";\nimport type { UpsertDecisionInput } from \"../decisions/decisions.js\";\nimport { reviewDecision as runDecisionReview, type ReviewDecisionInput } from \"../decisions/review.js\";\nimport { computeDecisionDrift } from \"../decisions/drift.js\";\nimport {\n loadSnapshot,\n saveSnapshot,\n getCurrentGitHash,\n prepareSnapshotBatch,\n normalizeFeatureType,\n DEFAULT_BATCH_SIZE,\n type FeatureType,\n} from \"../snapshot/snapshot.js\";\nimport { computeDrift } from \"../drift/drift.js\";\nimport type { DriftReport } from \"../drift/drift.js\";\nimport {\n BATCH_SYSTEM_PROMPT,\n REDUCE_SYSTEM_PROMPT,\n REFRESH_REDUCE_SYSTEM_PROMPT,\n buildBatchPrompt,\n buildReducePrompt,\n buildRefreshReducePrompt,\n} from \"../snapshot/prompt.js\";\nimport {\n batchIdFor,\n clearAllPartials,\n clearScope,\n loadAllPartials,\n loadScope,\n savePartial,\n saveScope,\n} from \"../snapshot/partials.js\";\nimport type { Snapshot, FeatureEntry, FlowEntry } from \"../snapshot/snapshot.js\";\nimport type { AnalyzerContext } from \"../types.js\";\nimport {\n loadProjectMarker,\n saveProjectMarker,\n setupPlaybook,\n type ProjectMarker,\n type InitMode,\n} from \"./init.js\";\nimport { inspectOnboarding } from \"./onboarding.js\";\n\nasync function buildContext(dir: string): Promise<AnalyzerContext> {\n return {\n rootDir: dir,\n gitAvailable: await isGitRepo(dir),\n };\n}\n\nexport async function analyzeProject(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n const context = await buildContext(rootDir);\n const results = await runAll(context);\n\n // Lightweight project snapshot — pure file existence checks, no parsing\n const projectSnapshot = await detectProjectSnapshot(rootDir);\n\n const output = {\n project: projectSnapshot,\n analyzers: results.map((r) => ({\n name: r.analyzer,\n durationMs: r.durationMs,\n findings: r.findings.map((f) => ({\n category: f.category,\n confidence: f.confidence,\n summary: f.summary,\n evidence: f.evidence,\n suggestedRule: f.ruleCandidate,\n })),\n gaps: r.gaps.map((g) => ({\n question: g.question,\n context: g.context,\n })),\n })),\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nasync function detectProjectSnapshot(rootDir: string): Promise<Record<string, unknown>> {\n // Build config files present (what exists, not what's in them)\n const access = await createFileAccess(rootDir);\n const buildFiles = [\n \"package.json\", \"tsconfig.json\",\n \"build.gradle.kts\", \"build.gradle\", \"settings.gradle.kts\", \"settings.gradle\",\n \"gradle/libs.versions.toml\",\n \"Cargo.toml\", \"go.mod\", \"go.sum\",\n \"pyproject.toml\", \"setup.py\", \"requirements.txt\", \"Pipfile\",\n \"Gemfile\", \"Package.swift\",\n \"Makefile\", \"CMakeLists.txt\",\n \"Dockerfile\", \"docker-compose.yml\", \"docker-compose.yaml\",\n \".github/workflows\", \".gitlab-ci.yml\", \"Jenkinsfile\",\n ];\n\n const present: string[] = [];\n for (const file of buildFiles) {\n try {\n await fs.access(path.join(rootDir, file));\n present.push(file);\n } catch {\n // Not found\n }\n }\n\n // Test directories and file counts\n const testDirs = [\n \"test\", \"tests\", \"__tests__\", \"spec\",\n \"src/test\", \"src/tests\",\n \"**/src/test\", \"**/src/androidTest\", \"**/src/iosTest\",\n ];\n const testInfo: Record<string, number> = {};\n for (const pattern of testDirs) {\n const files = await access.list(`${pattern}/**/*`);\n if (files.length > 0) {\n testInfo[pattern] = files.length;\n }\n }\n\n // Also count test files by naming convention\n const testFilePatterns = [\n { pattern: \"**/*.test.*\", label: \"*.test.*\" },\n { pattern: \"**/*.spec.*\", label: \"*.spec.*\" },\n { pattern: \"**/*Test.kt\", label: \"*Test.kt\" },\n { pattern: \"**/*Test.java\", label: \"*Test.java\" },\n { pattern: \"**/test_*.py\", label: \"test_*.py\" },\n { pattern: \"**/*_test.go\", label: \"*_test.go\" },\n { pattern: \"**/*Tests.swift\", label: \"*Tests.swift\" },\n { pattern: \"**/*_test.rs\", label: \"*_test.rs\" },\n ];\n for (const { pattern, label } of testFilePatterns) {\n const files = await access.list(pattern);\n if (files.length > 0) {\n testInfo[label] = files.length;\n }\n }\n\n // Source file counts by extension\n const sourceFiles = await access.list();\n const fileCounts: Record<string, number> = {};\n for (const file of sourceFiles) {\n const ext = path.extname(file).slice(1);\n fileCounts[ext] = (fileCounts[ext] ?? 0) + 1;\n }\n\n return {\n configFilesPresent: present,\n sourceFileCounts: fileCounts,\n totalSourceFiles: sourceFiles.length,\n testInfo: Object.keys(testInfo).length > 0 ? testInfo : undefined,\n };\n}\n\nexport async function getCodeSamples(\n dir: string,\n count: number = 15\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const samples = await sampleFiles(rootDir, count);\n\n const output = {\n note: \"These are previews (first ~60 lines). Read the file directly with your own tools to see it in full.\",\n files: samples.map((s) => ({\n path: s.path,\n reason: s.reason,\n totalLines: s.totalLines,\n sizeBytes: s.sizeBytes,\n preview: s.preview,\n })),\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nconst UNINIT_MAX_DIRECTORIES = 40;\nconst UNINIT_MAX_TEST_PAIRS = 30;\n\n/** Keep architecture requests useful when the optional map is absent. */\nasync function unmappedContextResponse(rootDir: string): Promise<string> {\n const [structureRaw, analyzerResults, testMap] = await Promise.all([\n getProjectStructure(rootDir),\n runAll(await buildContext(rootDir)).catch(() => []),\n import(\"../test-map.js\")\n .then((m) => m.buildTestMap(rootDir))\n .catch(() => null),\n ]);\n\n const structure = JSON.parse(structureRaw);\n structure.directories = (structure.directories ?? [])\n .sort(\n (a: { fileCount: number }, b: { fileCount: number }) =>\n b.fileCount - a.fileCount\n )\n .slice(0, UNINIT_MAX_DIRECTORIES);\n\n const gitSignals = analyzerResults.flatMap((r) =>\n r.findings.map((f) => ({\n category: f.category,\n summary: f.summary,\n evidence: f.evidence.slice(0, 5),\n }))\n );\n\n return JSON.stringify({\n exists: false,\n map: { status: \"missing\" },\n hint:\n `No Mason concept map exists here yet. Use the context below plus your own reads to answer now — ` +\n `get_context, save_decision, and get_impact work without a map. For an optional map, mason_init with mode: \"map\" provides the generate_snapshot_batch workflow.`,\n structure,\n gitSignals,\n testPairs: testMap?.paired?.slice(0, UNINIT_MAX_TEST_PAIRS) ?? [],\n });\n}\n\nexport async function getProjectStructure(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n // Get all files\n const allFiles = await (await createFileAccess(rootDir)).list(\"**/*\");\n\n // Build directory summary with file counts and extension breakdown\n const dirInfo = new Map<\n string,\n { fileCount: number; extensions: Map<string, number> }\n >();\n\n for (const file of allFiles) {\n const parts = file.split(\"/\");\n // Track up to 2 levels deep\n for (let depth = 1; depth <= Math.min(parts.length, 2); depth++) {\n const dirPath = parts.slice(0, depth).join(\"/\");\n if (!dirInfo.has(dirPath)) {\n dirInfo.set(dirPath, { fileCount: 0, extensions: new Map() });\n }\n const info = dirInfo.get(dirPath)!;\n info.fileCount++;\n const ext = path.extname(file).slice(1);\n if (ext) {\n info.extensions.set(ext, (info.extensions.get(ext) ?? 0) + 1);\n }\n }\n }\n\n // Format directories sorted by path\n const directories = [...dirInfo.entries()]\n .sort((a, b) => a[0].localeCompare(b[0]))\n .map(([dirPath, info]) => {\n const extensions: Record<string, number> = {};\n for (const [ext, count] of info.extensions) {\n extensions[ext] = count;\n }\n return { path: dirPath, fileCount: info.fileCount, extensions };\n });\n\n // Top-level files\n const topLevelFiles = allFiles.filter((f) => !f.includes(\"/\"));\n\n const output = {\n totalFiles: allFiles.length,\n topLevelFiles,\n directories,\n };\n\n return JSON.stringify(output, null, 2);\n}\n\nexport async function getTestMap(dir: string): Promise<string> {\n const { buildTestMap } = await import(\"../test-map.js\");\n const result = await buildTestMap(dir);\n return JSON.stringify(result, null, 2);\n}\n\nconst STALE_DIFF_PREVIEW_LINES = 60;\nconst STALE_DIFF_MAX_FILES = 25;\n\nasync function buildChangedFilePreviews(\n rootDir: string,\n changedFiles: string[]\n): Promise<Array<{ path: string; totalLines: number; preview: string }>> {\n const access = await createFileAccess(rootDir);\n const capped = changedFiles.slice(0, STALE_DIFF_MAX_FILES);\n const previews: Array<{ path: string; totalLines: number; preview: string }> = [];\n for (const filePath of capped) {\n const full = await access.read(filePath);\n if (!full) continue;\n const lines = full.content.split(\"\\n\");\n previews.push({\n path: full.path,\n totalLines: full.totalLines,\n preview: lines.slice(0, STALE_DIFF_PREVIEW_LINES).join(\"\\n\"),\n });\n }\n return previews;\n}\n\nexport async function getSnapshot(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const snapshot = await loadSnapshot(rootDir);\n\n if (!snapshot) {\n return unmappedContextResponse(rootDir);\n }\n\n // Staleness is per entry, not just top-level — a partially refreshed map\n // can be pinned to HEAD while individual entries lag behind.\n const drift = await computeDrift(rootDir);\n const isStale = drift?.stale ?? false;\n\n // Return compact format: feature/flow names -> file lists only.\n // Descriptions and metadata stay in the full snapshot on disk.\n // Deduplicate files that appear in multiple features.\n const seenFiles = new Set<string>();\n const compactFeatures: Record<\n string,\n { files: string[]; tests?: string[]; type: FeatureType }\n > = {};\n for (const [name, feat] of Object.entries(snapshot.features)) {\n const unique = feat.files.filter((f) => !seenFiles.has(f));\n if (unique.length === 0) continue; // Skip fully duplicate features\n for (const f of unique) seenFiles.add(f);\n const entry: { files: string[]; tests?: string[]; type: FeatureType } = {\n files: unique,\n type: normalizeFeatureType(feat.type),\n };\n if (feat.tests && feat.tests.length > 0) {\n entry.tests = feat.tests;\n }\n compactFeatures[name] = entry;\n }\n\n const compactFlows: Record<string, string[]> = {};\n for (const [name, flow] of Object.entries(snapshot.flows)) {\n compactFlows[name] = flow.chain; // Flows keep all files (order matters)\n }\n\n const output: Record<string, unknown> = {\n exists: true,\n map: { status: \"available\" },\n updatedAt: snapshot.updatedAt,\n features: compactFeatures,\n flows: compactFlows,\n stale: isStale,\n };\n\n // Compact decision index — titles only, no bodies (up to 150 × 1.5KB is\n // too heavy for the orientation call). Full text via get_context or the\n // record file itself.\n const { loadDecisionStore } = await import(\"../decisions/decisions.js\");\n const store = await loadDecisionStore(rootDir);\n const decisionRecords = store.records;\n const decisionDrift = await computeDecisionDrift(rootDir, decisionRecords);\n const trust: { features: Record<string, TrustState>; flows: Record<string, TrustState>; decisions: Record<string, TrustState> } = {\n features: Object.fromEntries(Object.entries(snapshot.features).map(([name, entry]) => [name, assessTrust(entry, drift?.featureFreshness?.[name] ?? \"unknown\")])),\n flows: Object.fromEntries(Object.entries(snapshot.flows).map(([name, entry]) => [name, assessTrust(entry, drift?.flowFreshness?.[name] ?? \"unknown\")])),\n decisions: Object.fromEntries(decisionRecords.filter(d => d.status === \"active\").map(d => [d.id, decisionTrust(effectiveDecision(d), decisionDrift.freshness?.[d.id] ?? \"unknown\")])),\n };\n output.trust = trust;\n output.workingTree = drift?.workingTree;\n output.diagnostics = store.diagnostics;\n if (decisionRecords.length > 0) {\n const compactDecisions: Record<\n string,\n ReturnType<typeof compactDecisionKnowledge>\n > = {};\n for (const d of decisionRecords) {\n if (d.status !== \"active\") continue;\n compactDecisions[d.id] = compactDecisionKnowledge(d, decisionDrift.freshness?.[d.id] ?? \"unknown\", decisionDrift.pendingProposals?.[d.id]?.freshness ?? \"unknown\");\n }\n output.decisions = compactDecisions;\n output.decisionsHint =\n DECISION_GUIDANCE + \" Full bodies via get_context; full history via review_decision.\";\n }\n\n if (isStale && drift) {\n output.hint = driftHint(drift);\n output.drift = {\n historyAvailable: drift.historyAvailable,\n staleFeatures: drift.staleFeatures,\n staleFlows: drift.staleFlows,\n unmappedFiles: drift.unmappedFiles,\n ghostFiles: drift.ghostFiles,\n renames: drift.renames,\n recommendation: drift.recommendation,\n };\n if (drift.historyAvailable && drift.changedFiles.length > 0) {\n const samples = await buildChangedFilePreviews(\n rootDir,\n drift.changedFiles\n );\n output.diff = {\n changedFiles: drift.changedFiles,\n samples,\n truncated: drift.changedFiles.length > STALE_DIFF_MAX_FILES,\n };\n }\n }\n\n output.hint = [output.hint, trustHint([...Object.values(trust.features), ...Object.values(trust.flows), ...Object.values(trust.decisions)]), store.diagnostics.length ? \"Some decision records are invalid; consult diagnostics.\" : \"\"].filter(Boolean).join(\" \");\n return JSON.stringify(output);\n}\n\nfunction driftHint(report: DriftReport): string {\n if (!report.stale) {\n return \"No committed changes affect the map. Consult verification and working-tree evidence before relying on it.\";\n }\n if (!report.historyAvailable) {\n return \"Snapshot is stale but its commit is unreachable (shallow clone or rewritten history), so per-feature drift cannot be computed. Re-run the Map-Reduce build: generate_snapshot_batch → save_partial_snapshot → reduce_snapshot → save_snapshot.\";\n }\n if (report.recommendation === \"full-rebuild\") {\n return \"Drift is too large for an incremental update. Re-run the Map-Reduce build: generate_snapshot_batch → save_partial_snapshot → reduce_snapshot → save_snapshot.\";\n }\n if (report.changedFiles.length + report.unmappedFiles.length > STALE_DIFF_MAX_FILES) {\n return \"Many files drifted — use a scoped refresh instead of reading them all inline: call generate_snapshot_batch(dir, files=[...changedFiles, ...unmappedFiles]) repeatedly (same list every call) with save_partial_snapshot per batch, then reduce_snapshot and save_snapshot. Entries untouched by the drift are preserved in the reduce step.\";\n }\n const nothingToRemap =\n Object.keys(report.staleFeatures).length === 0 &&\n Object.keys(report.staleFlows).length === 0 &&\n report.unmappedFiles.length === 0 &&\n report.ghostFiles.length === 0;\n if (nothingToRemap) {\n return \"Changes since the snapshot don't touch any mapped files. Call save_snapshot with empty features/flows to re-pin the snapshot to HEAD.\";\n }\n return \"Read the changed files under staleFeatures/staleFlows, update those entries (fold unmappedFiles into the right features), and call save_snapshot with only the affected entries — unchanged entries are preserved. Drop ghostFiles from any entries that reference them, and delete features/flows that no longer exist via save_snapshot's removeFeatures/removeFlows.\";\n}\n\nexport async function checkDrift(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n\n const report = await computeDrift(rootDir);\n if (!report) {\n return JSON.stringify({\n exists: false,\n hint: \"No concept map exists to check. Decisions and impact work without one; mason_init with mode: \\\"map\\\" provides the optional map workflow.\",\n });\n }\n\n // Report recorded correctness verdicts alongside freshness evidence.\n const snapshot = await loadSnapshot(rootDir);\n let verification: Record<string, unknown> | undefined;\n let hint = driftHint(report);\n if (snapshot) {\n const all = [\n ...Object.values(snapshot.features),\n ...Object.values(snapshot.flows),\n ];\n const failedNames = [\n ...Object.entries(snapshot.features)\n .filter(([, e]) => e.verificationFailed)\n .map(([n]) => n),\n ...Object.entries(snapshot.flows)\n .filter(([, e]) => e.verificationFailed)\n .map(([n]) => n),\n ];\n verification = {\n neverVerified: all.filter((e) => !e.verifiedAt).length,\n failed: failedNames,\n };\n if (failedNames.length > 0) {\n hint += ` Verification previously FAILED for [${failedNames.join(\", \")}] — re-map those entries before trusting them.`;\n }\n }\n\n return JSON.stringify({ exists: true, ...report, verification, hint });\n}\n\nexport async function generateSnapshotBatch(\n dir: string,\n offset: number = 0,\n batchSize: number = DEFAULT_BATCH_SIZE,\n files?: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const scoped = files !== undefined && files.length > 0;\n const scopeFiles = scoped ? sanitizePaths(rootDir, files) : undefined;\n const batch = await prepareSnapshotBatch(dir, offset, batchSize, scopeFiles);\n\n if (scoped && batch.totalFiles > 0) {\n // Mark this partial run as a scoped refresh so reduce_snapshot merges\n // into the existing map instead of rebuilding it from partials alone.\n await saveScope(rootDir, scopeFiles!);\n } else if (!scoped) {\n // A full build must never inherit a scope marker left behind by an\n // abandoned refresh run — its reduce step would wrongly merge instead\n // of rebuilding.\n await clearScope(rootDir);\n }\n\n const task = scoped\n ? \"Refresh the concept map for a scoped set of drifted files (batch step).\"\n : \"Build a concept-to-files map for this project (batch step).\";\n\n if (batch.totalFiles === 0) {\n return JSON.stringify(\n {\n task,\n offset: 0,\n nextOffset: null,\n totalFiles: 0,\n batchId: batchIdFor(0),\n instructions: BATCH_SYSTEM_PROMPT,\n prompt: scoped\n ? \"(None of the requested files exist as source files in this project.)\"\n : \"(No source files found to map.)\",\n next: scoped\n ? \"None of the requested files matched project source files. Check the paths passed in `files` — they must be repo-relative.\"\n : \"No source files were found. Skip the rest of the playbook and call mason_complete_init.\",\n },\n null,\n 2\n );\n }\n\n const batchId = batchIdFor(batch.offset);\n const continueCall = scoped\n ? `generate_snapshot_batch(dir, offset=${batch.nextOffset}, files=<the same list>)`\n : `generate_snapshot_batch(dir, offset=${batch.nextOffset})`;\n\n return JSON.stringify(\n {\n task,\n offset: batch.offset,\n nextOffset: batch.nextOffset,\n totalFiles: batch.totalFiles,\n batchId,\n batchSize: batch.batchSize,\n filesInBatch: batch.skeletons.length,\n scoped,\n instructions: BATCH_SYSTEM_PROMPT,\n prompt: buildBatchPrompt(batch),\n next:\n batch.nextOffset === null\n ? `Derive partial features/flows for this batch and call save_partial_snapshot(dir, batchId=\"${batchId}\", features, flows). This is the last batch — after saving, proceed to reduce_snapshot.`\n : `Derive partial features/flows for this batch and call save_partial_snapshot(dir, batchId=\"${batchId}\", features, flows). Then call ${continueCall} to continue.`,\n },\n null,\n 2\n );\n}\n\nexport async function saveSnapshotPartial(\n dir: string,\n batchId: string,\n offset: number,\n features: Record<\n string,\n { description: string; files: string[]; tests?: string[]; type?: FeatureType }\n >,\n flows: Record<string, { description: string; chain: string[] }>\n): Promise<string> {\n const rootDir = path.resolve(dir);\n\n // Sanitize all file paths to prevent path traversal in stored partials, and\n // normalize the capability/infrastructure classification so it survives reduce.\n for (const feat of Object.values(features)) {\n feat.files = sanitizePaths(rootDir, feat.files);\n if (feat.tests) feat.tests = sanitizePaths(rootDir, feat.tests);\n feat.type = normalizeFeatureType(feat.type);\n }\n for (const flow of Object.values(flows)) {\n flow.chain = sanitizePaths(rootDir, flow.chain);\n }\n\n await savePartial(rootDir, {\n batchId,\n offset,\n features,\n flows,\n savedAt: new Date().toISOString(),\n });\n\n const all = await loadAllPartials(rootDir);\n return JSON.stringify(\n {\n status: \"stored\",\n batchId,\n partialsStored: all.length,\n hint:\n \"Partial saved. Continue with the next generate_snapshot_batch call, or proceed to reduce_snapshot when nextOffset is null.\",\n },\n null,\n 2\n );\n}\n\nexport async function reduceSnapshot(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n const partials = await loadAllPartials(rootDir);\n\n if (partials.length === 0) {\n return JSON.stringify(\n {\n status: \"error\",\n error:\n \"No partial snapshots found. Run generate_snapshot_batch and save_partial_snapshot at least once before calling reduce_snapshot.\",\n },\n null,\n 2\n );\n }\n\n // A scope marker means these partials re-analyzed only a drifted subset —\n // merge them into the existing map instead of rebuilding from scratch.\n const scope = await loadScope(rootDir);\n const existing =\n scope && scope.length > 0 ? await loadSnapshot(rootDir) : null;\n\n if (scope && existing) {\n // Strip bookkeeping fields — the assistant shouldn't echo them back.\n const cleanFeatures = Object.fromEntries(\n Object.entries(existing.features).map(([name, feat]) => [\n name,\n {\n description: feat.description,\n files: feat.files,\n ...(feat.tests && feat.tests.length > 0 ? { tests: feat.tests } : {}),\n type: normalizeFeatureType(feat.type),\n },\n ])\n );\n const cleanFlows = Object.fromEntries(\n Object.entries(existing.flows).map(([name, flow]) => [\n name,\n { description: flow.description, chain: flow.chain },\n ])\n );\n\n return JSON.stringify(\n {\n task: \"Merge a scoped refresh into the existing concept map.\",\n partialsCount: partials.length,\n refreshedFiles: scope.length,\n instructions: REFRESH_REDUCE_SYSTEM_PROMPT,\n prompt: buildRefreshReducePrompt(\n { features: cleanFeatures, flows: cleanFlows },\n scope,\n partials\n ),\n next: \"Follow `instructions` to produce the COMPLETE updated features/flows (entries untouched by the refresh copied through unchanged), then call save_snapshot(dir, features, flows). Partials and the scope marker are cleaned up automatically after save_snapshot succeeds.\",\n },\n null,\n 2\n );\n }\n\n return JSON.stringify(\n {\n task: \"Merge partial concept maps into one unified map.\",\n partialsCount: partials.length,\n instructions: REDUCE_SYSTEM_PROMPT,\n prompt: buildReducePrompt(partials),\n next: \"Follow `instructions` to produce the unified features/flows, then call save_snapshot(dir, features, flows). Partial files will be cleaned up automatically after save_snapshot succeeds. Finish with mason_complete_init(dir).\",\n },\n null,\n 2\n );\n}\n\nexport async function fullAnalysis(dir: string): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const [analysis, structure, samples, testMap, snapshot] = await Promise.all([\n analyzeProject(dir),\n getProjectStructure(dir),\n getCodeSamples(dir, 25),\n getTestMap(dir),\n loadSnapshot(rootDir),\n ]);\n\n const output: Record<string, unknown> = {\n note: \"Full project analysis. Code samples are previews (~60 lines). Read files directly with your own tools to see them in full.\",\n analysis: JSON.parse(analysis),\n structure: JSON.parse(structure),\n codeSamples: JSON.parse(samples),\n testMap: JSON.parse(testMap),\n };\n\n if (snapshot) {\n output.conceptMap = {\n updatedAt: snapshot.updatedAt,\n features: snapshot.features,\n flows: snapshot.flows,\n };\n output.note =\n \"Full project analysis with concept map. The concept map shows which files implement each feature and how data flows through them. Use it to jump straight to relevant files instead of exploring, then read them directly with your own tools.\";\n }\n\n return JSON.stringify(output, null, 2);\n}\n\nfunction sanitizePaths(\n rootDir: string,\n files: string[]\n): string[] {\n return sanitizeRepoPaths(files);\n}\n\nexport async function saveSnapshotData(\n dir: string,\n features: Record<\n string,\n {\n description: string;\n files: string[];\n tests?: string[];\n refreshedHash?: string;\n type?: FeatureType;\n }\n >,\n flows: Record<\n string,\n { description: string; chain: string[]; refreshedHash?: string }\n >,\n removeFeatures: string[] = [],\n removeFlows: string[] = []\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const gitHash = await getCurrentGitHash(rootDir);\n const now = new Date().toISOString();\n\n // Sanitize all file paths to prevent path traversal, and normalize the\n // capability/infrastructure classification (defaults to \"capability\").\n for (const feat of Object.values(features)) {\n feat.files = sanitizePaths(rootDir, feat.files);\n if (feat.tests) feat.tests = sanitizePaths(rootDir, feat.tests);\n feat.type = normalizeFeatureType(feat.type);\n }\n for (const flow of Object.values(flows)) {\n flow.chain = sanitizePaths(rootDir, flow.chain);\n }\n\n // If partials exist we're consolidating a Map-Reduce run: replace the\n // snapshot wholesale. Merging here would pollute the unified map with any\n // earlier (possibly hallucinated) call to save_snapshot. Outside of\n // Map-Reduce — incremental refresh of one feature — fall back to merge.\n const partials = await loadAllPartials(rootDir);\n const replaceMode = partials.length > 0;\n const previous = await loadSnapshot(rootDir);\n const existing = replaceMode ? null : previous;\n // Copy-through entries must not silently lose a failed verification during\n // a scoped rebuild. A changed description/path set requires a new verdict.\n const preserveVerification = (next: FeatureEntry | FlowEntry, old?: FeatureEntry | FlowEntry) => {\n if (!old) return;\n const semantic = (entry: FeatureEntry | FlowEntry) => JSON.stringify({\n description: entry.description,\n files: \"files\" in entry ? entry.files : undefined,\n chain: \"chain\" in entry ? entry.chain : undefined,\n tests: \"files\" in entry ? entry.tests : undefined,\n type: \"files\" in entry ? normalizeFeatureType(entry.type) : undefined,\n });\n if (semantic(next) !== semantic(old)) return;\n next.verifiedAt = old.verifiedAt;\n next.verifiedHash = old.verifiedHash;\n next.verificationFailed = old.verificationFailed;\n next.verificationNote = old.verificationNote;\n };\n for (const [name, entry] of Object.entries(features)) preserveVerification(entry, previous?.features[name]);\n for (const [name, entry] of Object.entries(flows)) preserveVerification(entry, previous?.flows[name]);\n\n if (existing) {\n // Entries not re-sent in this call are only verified as of the previous\n // hash — record that before the top-level gitHash moves to HEAD, so\n // drift detection can still see which entries were skipped.\n if (existing.gitHash !== \"unknown\") {\n for (const feat of Object.values(existing.features)) {\n feat.refreshedHash ??= existing.gitHash;\n }\n for (const flow of Object.values(existing.flows)) {\n flow.refreshedHash ??= existing.gitHash;\n }\n }\n\n const removedFeatures = removeFeatures.filter(\n (name) => name in existing.features\n );\n const removedFlows = removeFlows.filter((name) => name in existing.flows);\n for (const name of removedFeatures) delete existing.features[name];\n for (const name of removedFlows) delete existing.flows[name];\n\n if (gitHash !== \"unknown\") {\n for (const feat of Object.values(features)) feat.refreshedHash = gitHash;\n for (const flow of Object.values(flows)) flow.refreshedHash = gitHash;\n }\n\n existing.features = { ...existing.features, ...features };\n existing.flows = { ...existing.flows, ...flows };\n existing.updatedAt = now;\n existing.gitHash = gitHash;\n await saveSnapshot(rootDir, existing);\n await clearAllPartials(rootDir);\n return JSON.stringify({\n status: \"updated\",\n mode: \"merged\",\n features: Object.keys(existing.features).length,\n flows: Object.keys(existing.flows).length,\n removedFeatures: removedFeatures.length,\n removedFlows: removedFlows.length,\n });\n }\n\n const snapshot: Snapshot = {\n version: 2,\n createdAt: now,\n updatedAt: now,\n gitHash,\n features,\n flows,\n };\n\n await saveSnapshot(rootDir, snapshot);\n await clearAllPartials(rootDir);\n return JSON.stringify({\n status: replaceMode ? \"replaced\" : \"created\",\n mode: replaceMode ? \"replaced-from-partials\" : \"fresh\",\n features: Object.keys(features).length,\n flows: Object.keys(flows).length,\n });\n}\n\nexport async function configureProject(\n dir: string,\n config: {\n patterns?: string[];\n alwaysInclude?: string[];\n ignore?: string[];\n }\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const existing = (await readStoreJson(rootDir, \".mason/config.json\") ?? {}) as Record<string, unknown>;\n\n if (config.patterns) existing.patterns = config.patterns;\n if (config.alwaysInclude) existing.alwaysInclude = config.alwaysInclude;\n if (config.ignore) existing.ignore = config.ignore;\n\n await writeStoreJson(rootDir, \".mason/config.json\", existing);\n\n return JSON.stringify({\n status: \"saved\",\n path: path.join(rootDir, \".mason/config.json\"),\n config: existing,\n });\n}\n\nexport async function getImpact(\n dir: string,\n files: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { analyzeImpact } = await import(\"../impact/impact.js\");\n const result = await analyzeImpact(rootDir, files);\n return JSON.stringify(result, null, 2);\n}\n\nconst VERIFY_DEFAULT_SAMPLE = 5;\nconst VERIFY_MAX_FILES_PER_ENTRY = 8;\nconst VERIFY_SKELETON_CHARS = 500;\n\n/**\n * Verification closes the day-one hole drift can't: drift proves the map is\n * current against git, but nothing proves an entry was CORRECT when written.\n * Sample entries weighted toward never-verified, then oldest-verified.\n */\nexport async function verifySnapshot(\n dir: string,\n sample: number = VERIFY_DEFAULT_SAMPLE\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n return JSON.stringify({\n exists: false,\n hint: \"No concept map exists yet — nothing to verify.\",\n });\n }\n\n const entries = [\n ...Object.entries(snapshot.features).map(([name, e]) => ({\n name,\n kind: \"feature\" as const,\n description: e.description,\n files: e.files,\n verifiedAt: e.verifiedAt,\n })),\n ...Object.entries(snapshot.flows).map(([name, e]) => ({\n name,\n kind: \"flow\" as const,\n description: e.description,\n files: e.chain,\n verifiedAt: e.verifiedAt,\n })),\n ];\n\n entries.sort((a, b) => {\n if (!a.verifiedAt && !b.verifiedAt) return a.name.localeCompare(b.name);\n if (!a.verifiedAt) return -1;\n if (!b.verifiedAt) return 1;\n return a.verifiedAt.localeCompare(b.verifiedAt);\n });\n\n const access = await createFileAccess(rootDir);\n const picked = entries.slice(0, Math.max(1, sample));\n const toVerify = [];\n for (const entry of picked) {\n const skeletons: Array<{ path: string; content: string } | { path: string; missing: true }> = [];\n for (const filePath of entry.files.slice(0, VERIFY_MAX_FILES_PER_ENTRY)) {\n const full = await access.read(filePath);\n if (full) {\n skeletons.push({\n path: full.path,\n content: full.content.slice(0, VERIFY_SKELETON_CHARS),\n });\n } else {\n skeletons.push({ path: filePath, missing: true });\n }\n }\n toVerify.push({\n name: entry.name,\n kind: entry.kind,\n description: entry.description,\n lastVerified: entry.verifiedAt ?? \"never\",\n skeletons,\n truncated: entry.files.length > VERIFY_MAX_FILES_PER_ENTRY,\n });\n }\n\n const neverVerified = entries.filter((e) => !e.verifiedAt).length;\n\n return JSON.stringify({\n exists: true,\n totalEntries: entries.length,\n neverVerified,\n entries: toVerify,\n instructions:\n \"For each entry, judge from the skeletons whether the listed files actually implement the claimed feature/flow (missing files count against it). Then call save_verification with verdicts: {\\\"<entry name>\\\": {\\\"ok\\\": true|false, \\\"note\\\": \\\"<one line, required when ok is false>\\\"}}. Be skeptical — a plausible description is not evidence; the files must show it.\",\n });\n}\n\nexport async function saveVerification(\n dir: string,\n verdicts: Record<string, { ok: boolean; note?: string }>\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const snapshot = await loadSnapshot(rootDir);\n if (!snapshot) {\n return JSON.stringify({ exists: false, hint: \"No concept map exists.\" });\n }\n\n const now = new Date().toISOString();\n const verifiedHash = await getCurrentGitHash(rootDir);\n const stamped: string[] = [];\n const unknown: string[] = [];\n const failed: string[] = [];\n\n for (const [name, verdict] of Object.entries(verdicts)) {\n const entry = snapshot.features[name] ?? snapshot.flows[name];\n if (!entry) {\n unknown.push(name);\n continue;\n }\n entry.verifiedAt = now;\n entry.verifiedHash = verifiedHash;\n if (verdict.ok) {\n delete entry.verificationFailed;\n delete entry.verificationNote;\n } else {\n entry.verificationFailed = true;\n entry.verificationNote = verdict.note ?? \"verification failed\";\n failed.push(name);\n }\n stamped.push(name);\n }\n\n snapshot.updatedAt = now;\n await saveSnapshot(rootDir, snapshot);\n\n return JSON.stringify({\n stamped,\n unknown,\n failed,\n hint:\n failed.length > 0\n ? `Entries [${failed.join(\", \")}] are mis-mapped. Re-map them: read their actual files, correct the entries, and call save_snapshot with only those entries (plus removeFeatures/removeFlows if a concept no longer exists).`\n : \"All sampled entries verified. Re-run verify_snapshot periodically — it always picks the least-recently-verified entries next.\",\n });\n}\n\nexport async function saveDecision(\n dir: string,\n input: UpsertDecisionInput\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { upsertDecision } = await import(\"../decisions/decisions.js\");\n const result = await upsertDecision(rootDir, input);\n return JSON.stringify(result);\n}\n\nexport async function reviewDecision(dir: string, input: ReviewDecisionInput): Promise<string> {\n return JSON.stringify(await runDecisionReview(path.resolve(dir), input));\n}\n\nexport async function getContext(\n dir: string,\n task: string,\n files?: string[]\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const { assembleContext } = await import(\"../context/assemble.js\");\n const bundle = await assembleContext(rootDir, task, files);\n return JSON.stringify(bundle);\n}\n\n// ===== Init MCP tools =====\n\nexport async function masonAutomation(dir: string, action: \"status\" | \"check\"): Promise<string> {\n try {\n const { automate, automationStatus, summarize } = await import(\"../automation/runtime.js\");\n const { installedAutomation } = await import(\"../automation/install.js\");\n if (action === \"status\") {\n const { setupStatus } = await import(\"../setup/status.js\");\n return JSON.stringify({ ...await automationStatus(dir), configured: await installedAutomation(dir), setup: await setupStatus(dir) });\n }\n if (action !== \"check\") throw new Error(\"Expected status or check.\");\n const { report } = await automate(dir, { event: \"task_end\" });\n const { findings, ...summary } = report;\n return JSON.stringify({ ...summary, findings: findings.slice(0, 5), truncated: findings.length > 5, summary: summarize(report) });\n } catch (error) {\n const { automationFailure } = await import(\"../automation/execution.js\");\n const failure = automationFailure(error);\n return JSON.stringify({ version: 1, status: \"unavailable\", error: failure.message, failure });\n }\n}\n\nexport async function masonRepair(dir: string, options: { action: \"prepare\" | \"verify\"; baselinePath?: string; checks?: CheckName[] }): Promise<string> {\n try {\n if (options.action === \"verify\") {\n if (!options.baselinePath || options.checks) throw new Error(\"Verification requires baselinePath and uses the original checks; do not pass checks.\");\n return JSON.stringify(await verifyRepair(dir, options.baselinePath), null, 2);\n }\n if (options.action !== \"prepare\" || options.baselinePath) throw new Error(\"Preparation accepts checks, not an existing baselinePath.\");\n const result = await prepareRepair(dir, options.checks);\n return JSON.stringify({ ...result, workOrder: formatFixPrompt(result.report, result.baselinePath) }, null, 2);\n } catch (error) {\n return JSON.stringify({ status: \"unavailable\", error: error instanceof Error ? error.message : String(error) });\n }\n}\n\nexport async function masonInit(dir: string, options: { mode?: InitMode; host?: \"codex\" | \"claude\"; base?: string; evidence?: string[] } = {}): Promise<string> {\n if (options.mode === \"setup\") {\n const { setupProject } = await import(\"../setup/setup.js\");\n return JSON.stringify(await setupProject(dir, options), null, 2);\n }\n if (options.host) throw new Error(\"host applies only to mode: setup.\");\n const rootDir = path.resolve(dir);\n const marker = await loadProjectMarker(rootDir);\n const mode = options.mode ?? \"quickstart\";\n const findings = await inspectOnboarding(rootDir, options.base, options.evidence);\n return JSON.stringify(\n {\n initialized: marker !== null,\n ...(marker ? { initializedAt: marker.initializedAt } : {}),\n confluenceConfigured: marker?.features?.confluence === true,\n mode,\n ...findings,\n playbook: setupPlaybook(mode),\n },\n null,\n 2\n );\n}\n\nexport async function masonCompleteInit(\n dir: string,\n options: { confluenceConfigured?: boolean } = {}\n): Promise<string> {\n const rootDir = path.resolve(dir);\n const existing = await loadProjectMarker(rootDir);\n const marker: ProjectMarker = {\n version: 1,\n initializedAt: existing?.initializedAt ?? new Date().toISOString(),\n features: {\n ...existing?.features,\n confluence: options.confluenceConfigured ?? existing?.features?.confluence ?? false,\n },\n };\n await saveProjectMarker(rootDir, marker);\n return JSON.stringify(\n {\n status: \"initialized\",\n marker,\n hint: \"Assistant setup recorded. Save decisions as you learn, review and commit them, and retrieve them with get_context. A concept map is optional.\",\n },\n null,\n 2\n );\n}\n\n// ===== Confluence MCP tools =====\n\nexport async function masonSetConfluence(input: {\n baseUrl: string;\n email: string;\n apiToken: string;\n spaceKey?: string;\n parentPageId?: string;\n}): Promise<string> {\n const { createConfluenceClient } = await import(\"../confluence/client.js\");\n const { saveConfluenceConfig } = await import(\"../llm/config.js\");\n const { normalizeAtlassianBaseUrl } = await import(\"../confluence/url.js\");\n\n let baseUrl: string;\n try {\n baseUrl = normalizeAtlassianBaseUrl(input.baseUrl);\n } catch (err) {\n return JSON.stringify({\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n if (!input.email.includes(\"@\")) {\n return JSON.stringify({\n status: \"error\",\n error: `Email looks invalid: \"${input.email}\".`,\n });\n }\n if (!input.apiToken.trim()) {\n return JSON.stringify({\n status: \"error\",\n error: \"API token is required.\",\n });\n }\n\n const probeConfig = {\n baseUrl,\n email: input.email,\n apiToken: input.apiToken,\n spaceKey: input.spaceKey ?? \"\",\n parentPageId: input.parentPageId,\n };\n const client = createConfluenceClient(probeConfig);\n\n let spaces;\n try {\n spaces = await client.listSpaces();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (msg.includes(\"401\") || msg.includes(\"403\")) {\n return JSON.stringify({\n status: \"error\",\n error:\n \"Credentials rejected by Confluence. Re-check the email and that the API token hasn't expired or been revoked.\",\n });\n }\n return JSON.stringify({\n status: \"error\",\n error: `Confluence validation failed: ${msg}`,\n });\n }\n\n if (!input.spaceKey) {\n // Step 1 — return spaces for the assistant to relay to the user.\n return JSON.stringify(\n {\n status: \"spaces_listed\",\n baseUrl,\n spaces: spaces.map((s) => ({ key: s.key, name: s.name })),\n hint:\n spaces.length === 0\n ? \"Authenticated, but no spaces are visible to this account. Create one in Confluence first, then re-run mason_set_confluence.\"\n : \"Ask the user which space to use, then call mason_set_confluence again with the same baseUrl/email/apiToken plus the chosen spaceKey.\",\n },\n null,\n 2\n );\n }\n\n const match = spaces.find((s) => s.key === input.spaceKey);\n if (!match) {\n return JSON.stringify({\n status: \"error\",\n error: `Space key \"${input.spaceKey}\" was not found among the spaces visible to this account. Available keys: ${spaces.map((s) => s.key).join(\", \") || \"(none)\"}.`,\n });\n }\n\n await saveConfluenceConfig({\n baseUrl,\n email: input.email,\n apiToken: input.apiToken,\n spaceKey: input.spaceKey,\n parentPageId: input.parentPageId,\n });\n\n return JSON.stringify(\n {\n status: \"saved\",\n spaceKey: input.spaceKey,\n spaceName: match.name,\n hint:\n \"Confluence is configured. The credentials are stored in ~/.mason/config.json. Call export_to_confluence to sync the concept map.\",\n },\n null,\n 2\n );\n}\n\nexport async function exportToConfluenceTool(\n dir: string,\n overrides?: {\n spaceKey?: string;\n parentPageId?: string;\n indexPageTitle?: string;\n changelogPageTitle?: string;\n featurePagePrefix?: string;\n }\n): Promise<string> {\n const rootDir = path.resolve(dir);\n\n const { loadConfig } = await import(\"../llm/config.js\");\n const { exportToConfluence } = await import(\"../confluence/sync.js\");\n\n const config = await loadConfig();\n if (!config?.confluence) {\n return JSON.stringify({\n status: \"error\",\n error:\n 'No Confluence credentials configured. Call mason_set_confluence first.',\n });\n }\n\n const merged = {\n ...config,\n confluence: {\n ...config.confluence,\n spaceKey: overrides?.spaceKey ?? config.confluence.spaceKey,\n parentPageId: overrides?.parentPageId ?? config.confluence.parentPageId,\n },\n };\n\n try {\n const summary = await exportToConfluence(rootDir, merged, {\n indexPageTitle: overrides?.indexPageTitle,\n changelogPageTitle: overrides?.changelogPageTitle,\n featurePagePrefix: overrides?.featurePagePrefix,\n });\n return JSON.stringify({ status: \"ok\", ...summary }, null, 2);\n } catch (err) {\n return JSON.stringify({\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n","import path from \"node:path\";\nimport { computeAudit } from \"./audit.js\";\nimport { ALL_CHECKS } from \"./types.js\";\nimport { prepareRepair, verifyRepair, formatRepairSummary, repairExitCode } from \"./repair.js\";\nimport type { AuditIssue, AuditReport, CheckName } from \"./types.js\";\n\nexport const USAGE = `Usage: mason-audit [--dir <path>] [--json | --fix-prompt] [--checks <list>]\n\nAudits the repo's AI context files (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md)\nagainst repo reality: referenced paths that no longer exist, undocumented\nmodules, stale counts, dead npm scripts, and manifests newer than the doc.\nDeterministic: no LLM call, no network – safe for CI. Works on any repo with\na context file; no Mason setup required.\n\nOptions:\n --dir <path> Project root to audit (default: current directory)\n --json Print the full audit report as JSON (additive-only schema)\n --fix-prompt When issues exist, print a work order for ANY coding agent\n (Claude, Codex, Gemini, ...) – pipe it to your agent CLI to\n repair the findings. Includes advisories that require review.\n --prepare-repair Save the original audit under .mason/reports/repairs/ before edits\n --verify-repair <path>\n Compare against that saved baseline, using its original checks\n --checks <list> Comma-separated subset of checks to run (default: all):\n ${ALL_CHECKS.join(\", \")}\n --help Show this help\n\nExit codes:\n 0 no issues (advisories may still be present)\n 1 provable issues found\n 2 error (no context file, not a git repository, bad arguments)\n\nWith --verify-repair: 0 verified by the original checks; 1 issues remain;\n2 incomplete (unverified findings, skipped checks, or advisories needing review).\nPreparation writes only a baseline; verification and ordinary audits are read-only.`;\n\nexport interface AuditCliIo {\n out: (line: string) => void;\n err: (line: string) => void;\n}\n\ninterface ParsedArgs {\n dir: string;\n json: boolean;\n fixPrompt: boolean;\n help: boolean;\n checks: CheckName[] | undefined;\n prepareRepair: boolean;\n baseline?: string;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const parsed: ParsedArgs = {\n dir: process.cwd(),\n json: false,\n fixPrompt: false,\n help: false,\n checks: undefined,\n prepareRepair: false,\n };\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg === \"--json\") {\n parsed.json = true;\n } else if (arg === \"--fix-prompt\") {\n parsed.fixPrompt = true;\n } else if (arg === \"--prepare-repair\") {\n parsed.prepareRepair = true;\n } else if (arg === \"--verify-repair\") {\n const value = argv[++i];\n if (!value || value.startsWith(\"--\")) throw new Error(\"--verify-repair requires a baseline path\");\n parsed.baseline = value;\n } else if (arg === \"--help\" || arg === \"-h\") {\n parsed.help = true;\n } else if (arg === \"--dir\") {\n const value = argv[++i];\n if (!value) throw new Error(\"--dir requires a path argument\");\n parsed.dir = value;\n } else if (arg === \"--checks\") {\n const value = argv[++i];\n if (!value) throw new Error(\"--checks requires a comma-separated list\");\n const names = value.split(\",\").map((n) => n.trim()).filter(Boolean);\n if (!names.length) throw new Error(\"--checks requires at least one check\");\n for (const name of names) {\n if (!ALL_CHECKS.includes(name as CheckName)) {\n throw new Error(\n `Unknown check: ${name} (valid: ${ALL_CHECKS.join(\", \")})`\n );\n }\n }\n parsed.checks = names as CheckName[];\n } else if (!arg.startsWith(\"-\") && parsed.dir === process.cwd()) {\n parsed.dir = arg;\n } else {\n throw new Error(`Unknown argument: ${arg}`);\n }\n }\n return parsed;\n}\n\nfunction issueLine(issue: AuditIssue): string {\n const where =\n issue.anchor.line !== null ? `line ${issue.anchor.line}` : \"doc-level\";\n const likely = issue.confidence === \"likely\" ? \" (likely)\" : \"\";\n return ` [${issue.type}]${likely} ${where}: ${issue.message}`;\n}\n\nexport function formatAuditSummary(report: AuditReport): string {\n const lines: string[] = [];\n const reviewCount = report.advisories.length + (report.suppressedAdvisories?.length ?? 0);\n\n for (const doc of report.docs) {\n const docIssues = report.issues.filter((i) => i.anchor.doc === doc.path);\n const committed = doc.lastCommit\n ? `last committed ${doc.lastCommit.date.slice(0, 10)}, ${doc.lastCommit.hash.slice(0, 7)}`\n : \"untracked\";\n if (docIssues.length === 0) {\n lines.push(`${doc.path} – clean (${committed})`);\n continue;\n }\n lines.push(\n `${doc.path} – ${docIssues.length} issue${docIssues.length === 1 ? \"\" : \"s\"} (${committed})`\n );\n for (const issue of docIssues) lines.push(issueLine(issue));\n }\n\n // Issues anchored outside the docs list (defensive; new-module anchors to\n // the primary doc, so this should stay empty).\n const docPaths = new Set(report.docs.map((d) => d.path));\n for (const issue of report.issues) {\n if (!docPaths.has(issue.anchor.doc)) lines.push(issueLine(issue));\n }\n\n if (report.advisories.length > 0) {\n lines.push(\"Advisories (do not affect the exit code):\");\n for (const advisory of report.advisories) {\n lines.push(` [${advisory.type}] ${advisory.anchor.doc}: ${advisory.message}`);\n }\n }\n if (report.skippedChecks.length > 0) {\n for (const skip of report.skippedChecks) {\n lines.push(` [skipped] ${skip.check}: ${skip.reason}`);\n }\n }\n\n for (const advisory of report.suppressedAdvisories ?? []) {\n lines.push(` [suppressed; unresolved] ${advisory.type} ${advisory.anchor.doc}: ${advisory.message}`);\n }\n\n lines.push(\n report.clean\n ? reviewCount || report.skippedChecks.length\n ? `No audit issues detected (${report.docs.length} docs audited); ${reviewCount} advisories remain for review, ${report.skippedChecks.length} checks skipped.`\n : `Context files are clean (${report.docs.length} doc${report.docs.length === 1 ? \"\" : \"s\"} audited).`\n : `${report.issues.length} issue${report.issues.length === 1 ? \"\" : \"s\"} across ${report.docs.length} doc${report.docs.length === 1 ? \"\" : \"s\"}.`\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * Provider-neutral work order: any coding agent can execute it. The evidence\n * is deterministic; the agent's job is judgment scoped to exactly these\n * claims – never a free-form doc rewrite.\n */\nexport function formatFixPrompt(report: AuditReport, baselinePath?: string): string {\n const flaggedDocs = [...new Set(report.issues.map((i) => i.anchor.doc))];\n const lines: string[] = [];\n lines.push(\n \"Review the flagged context claims using the evidence below. Make minimal repairs within the user's authorized scope. A setup-only or audit-only request does not authorize rewriting existing documentation.\"\n );\n lines.push(\"\");\n lines.push(\"RULES:\");\n lines.push(baselinePath\n ? `- Preserve the original repair baseline: ${JSON.stringify(baselinePath)}. Do not replace it after editing.`\n : \"- Before the first edit, call mason_repair with action: prepare, or run mason-audit --prepare-repair --json with the same --dir and --checks. Keep the returned baselinePath through verification.\");\n lines.push(\n `- Edit ONLY these files: ${flaggedDocs.join(\", \") || \"none (advisory review only)\"}. Bring the docs into agreement with verified source evidence; do not change source code or configs to silence findings.`\n );\n lines.push(\n \"- Keep diffs minimal: change the smallest span that makes each claim true.\"\n );\n lines.push(\n \"- Never invent content. Every replacement must be grounded in the evidence below or in files you read from this repository.\"\n );\n lines.push(\"- Inspect likely findings before editing: heuristic evidence may describe an intentional omission or an example.\");\n lines.push(\n \"- deleted-reference: if evidence shows renamedTo, update the path; otherwise remove the reference, or rephrase to past tense if the sentence is about history. Deleted paths inside directory trees: delete the tree line.\"\n );\n lines.push(\n \"- stale-count: replace the number with the actual count from the evidence.\"\n );\n lines.push(\n \"- dead-command: replace with the correct script from availableScripts if an obvious rename exists; otherwise remove the command mention.\"\n );\n lines.push(\n \"- new-module: add a one-line factual mention of the directory where sibling modules are described; read the directory's files first and describe only what you verified.\"\n );\n lines.push(\n \"- ADVISORIES require a separate assessment of the cited commits or decision evidence. Report any review you perform and what remains unknown. Their disappearance after edits or a commit does not establish review or approval.\"\n );\n lines.push(\"\");\n lines.push(\"AUDIT REPORT (current context files and repository evidence, including local edits):\");\n lines.push(\n JSON.stringify(\n { root: report.root, checks: report.checksRun, issues: report.issues, advisories: report.advisories,\n suppressedAdvisories: report.suppressedAdvisories, skippedChecks: report.skippedChecks },\n null,\n 2\n )\n );\n lines.push(\"\");\n lines.push(\n \"After edits, call mason_repair with action: verify and the original baselinePath, or mason-audit --verify-repair <baselinePath> --dir <project>. Repeat against the same baseline after any final documentation commit. Summarize resolved, unresolved, review-required, unverified, and new findings with their evidence. Do not report a suppressed or unavailable check as fixed. This audit covers the listed context files; independently discovered README or application issues need their own validation.\"\n );\n return lines.join(\"\\n\");\n}\n\nexport async function runAuditCli(\n argv: string[],\n io: AuditCliIo = {\n out: (line) => process.stdout.write(`${line}\\n`),\n err: (line) => process.stderr.write(`${line}\\n`),\n }\n): Promise<number> {\n let args: ParsedArgs;\n try {\n args = parseArgs(argv);\n if (args.json && args.fixPrompt) {\n throw new Error(\"--json and --fix-prompt are mutually exclusive\");\n }\n if (args.baseline && (args.prepareRepair || args.checks || args.fixPrompt)) {\n throw new Error(\"--verify-repair cannot be combined with --prepare-repair, --checks, or --fix-prompt; verification uses the original scope\");\n }\n } catch (error) {\n io.err(error instanceof Error ? error.message : String(error));\n io.err(USAGE);\n return 2;\n }\n\n if (args.help) {\n io.out(USAGE);\n return 0;\n }\n\n const rootDir = path.resolve(args.dir);\n if (args.baseline || args.prepareRepair) {\n try {\n if (args.baseline) {\n const verification = await verifyRepair(rootDir, args.baseline);\n io.out(args.json ? JSON.stringify(verification, null, 2) : formatRepairSummary(verification));\n return repairExitCode(verification);\n }\n const prepared = await prepareRepair(rootDir, args.checks);\n io.out(args.json ? JSON.stringify({ ...prepared, workOrder: formatFixPrompt(prepared.report, prepared.baselinePath) }, null, 2)\n : args.fixPrompt ? formatFixPrompt(prepared.report, prepared.baselinePath)\n : `Repair baseline: ${prepared.baselinePath}\\n${formatAuditSummary(prepared.report)}`);\n return prepared.report.clean ? 0 : 1;\n } catch (error) {\n io.err(error instanceof Error ? error.message : String(error));\n return 2;\n }\n }\n const report = await computeAudit(rootDir, { checks: args.checks });\n\n if (!report) {\n io.err(\n `No CLAUDE.md, .claude/CLAUDE.md, or AGENTS.md found in ${rootDir}.`\n );\n return 2;\n }\n\n if (!report.gitAvailable) {\n io.err(\n `Could not determine git HEAD in ${rootDir} – not a git repository, or git is unavailable.`\n );\n return 2;\n }\n\n if (args.fixPrompt) {\n io.out(\n report.clean && !report.advisories.length && !report.suppressedAdvisories?.length\n ? formatAuditSummary(report) : formatFixPrompt(report)\n );\n return report.clean ? 0 : 1;\n }\n\n if (args.json) {\n io.out(JSON.stringify(report, null, 2));\n } else {\n io.out(formatAuditSummary(report));\n }\n return report.clean ? 0 : 1;\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { BaseAnalyzer } from \"./base.js\";\nimport type { AnalyzerContext, AnalyzerResult, Finding, Gap } from \"../types.js\";\n\nconst exec = promisify(execFile);\n\nexport class GitHistoryAnalyzer extends BaseAnalyzer {\n name = \"git-history\";\n\n async analyze(context: AnalyzerContext): Promise<AnalyzerResult> {\n const startTime = Date.now();\n const findings: Finding[] = [];\n const gaps: Gap[] = [];\n\n if (!context.gitAvailable) {\n return this.createResult([], [], startTime);\n }\n\n const [staleFindings, staleGaps] = await this.findStaleDirectories(context);\n findings.push(...staleFindings);\n gaps.push(...staleGaps);\n\n const hotFindings = await this.findHotFiles(context);\n findings.push(...hotFindings);\n\n const commitFindings = await this.analyzeCommitPatterns(context);\n findings.push(...commitFindings);\n\n return this.createResult(findings, gaps, startTime);\n }\n\n private async git(\n args: string[],\n cwd: string\n ): Promise<string> {\n try {\n const { stdout } = await exec(\"git\", args, { cwd, maxBuffer: 10_000_000 });\n return stdout.trim();\n } catch {\n return \"\";\n }\n }\n\n private async findStaleDirectories(\n context: AnalyzerContext\n ): Promise<[Finding[], Gap[]]> {\n const findings: Finding[] = [];\n const gaps: Gap[] = [];\n\n // Get top-level directories with their last commit date\n const output = await this.git(\n [\"log\", \"--all\", \"--format=%ci\", \"--name-only\", \"--diff-filter=AMCR\", \"-n\", \"500\"],\n context.rootDir\n );\n\n if (!output) return [findings, gaps];\n\n const dirLastTouch = new Map<string, Date>();\n let currentDate: Date | null = null;\n\n for (const line of output.split(\"\\n\")) {\n if (!line) continue;\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(line)) {\n currentDate = new Date(line);\n } else if (currentDate) {\n const topDir = line.split(\"/\")[0];\n if (\n topDir &&\n !topDir.startsWith(\".\") &&\n !topDir.includes(\"node_modules\")\n ) {\n const existing = dirLastTouch.get(topDir);\n if (!existing || currentDate > existing) {\n dirLastTouch.set(topDir, currentDate);\n }\n }\n }\n }\n\n const sixMonthsAgo = new Date();\n sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6);\n\n for (const [dir, lastTouch] of dirLastTouch) {\n if (lastTouch < sixMonthsAgo) {\n const monthsStale = Math.floor(\n (Date.now() - lastTouch.getTime()) / (1000 * 60 * 60 * 24 * 30)\n );\n findings.push(\n this.createFinding({\n category: \"risk\",\n confidence: 0.7,\n summary: `Directory \"${dir}\" hasn't been modified in ${monthsStale} months`,\n evidence: [\n { filePath: dir, detail: `Last commit: ${lastTouch.toISOString().split(\"T\")[0]}` },\n ],\n ruleCandidate: `Do not refactor or modify files in \"${dir}/\" unless explicitly asked — this area has been stable for ${monthsStale} months and may be legacy code.`,\n })\n );\n gaps.push({\n analyzer: this.name,\n question: `Directory \"${dir}\" hasn't been touched in ${monthsStale} months. Is it deprecated, stable, or legacy?`,\n context: `Last modified: ${lastTouch.toISOString().split(\"T\")[0]}`,\n answerKey: `stale-dir-${dir}`,\n });\n }\n }\n\n return [findings, gaps];\n }\n\n private async findHotFiles(context: AnalyzerContext): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n // Most frequently changed files in the last 3 months\n const output = await this.git(\n [\"log\", \"--since=3 months ago\", \"--format=\", \"--name-only\"],\n context.rootDir\n );\n\n if (!output) return findings;\n\n const fileCounts = new Map<string, number>();\n for (const line of output.split(\"\\n\")) {\n if (!line || line.startsWith(\".\") || line.includes(\"node_modules\")) continue;\n fileCounts.set(line, (fileCounts.get(line) ?? 0) + 1);\n }\n\n const sorted = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10);\n\n if (sorted.length > 0 && sorted[0][1] >= 5) {\n const hotFiles = sorted.filter(([, count]) => count >= 5);\n if (hotFiles.length > 0) {\n findings.push(\n this.createFinding({\n category: \"risk\",\n confidence: 0.8,\n summary: `${hotFiles.length} files changed frequently in the last 3 months`,\n evidence: hotFiles.map(([file, count]) => ({\n filePath: file,\n detail: `${count} commits`,\n })),\n ruleCandidate: `These files change frequently and are high-risk for conflicts: ${hotFiles.map(([f]) => f).join(\", \")}. Take extra care when modifying them.`,\n })\n );\n }\n }\n\n return findings;\n }\n\n private async analyzeCommitPatterns(\n context: AnalyzerContext\n ): Promise<Finding[]> {\n const findings: Finding[] = [];\n\n const output = await this.git(\n [\"log\", \"--format=%s\", \"-n\", \"100\"],\n context.rootDir\n );\n\n if (!output) return findings;\n\n const messages = output.split(\"\\n\").filter(Boolean);\n\n // Check for conventional commits\n const conventionalPattern = /^(feat|fix|chore|docs|style|refactor|test|perf|ci|build|revert)(\\(.+\\))?:/;\n const conventionalCount = messages.filter((m) =>\n conventionalPattern.test(m)\n ).length;\n const conventionalRatio = conventionalCount / messages.length;\n\n if (conventionalRatio > 0.5) {\n findings.push(\n this.createFinding({\n category: \"convention\",\n confidence: Math.min(conventionalRatio + 0.1, 1),\n summary: `${Math.round(conventionalRatio * 100)}% of recent commits use conventional commit format`,\n evidence: [\n {\n filePath: \".git\",\n detail: `${conventionalCount} of ${messages.length} commits match`,\n },\n ],\n ruleCandidate:\n \"Use conventional commit format: type(scope): description (e.g., feat(auth): add login endpoint)\",\n })\n );\n }\n\n // Check for ticket/issue references\n const ticketPattern = /[A-Z]+-\\d+|#\\d+/;\n const ticketCount = messages.filter((m) => ticketPattern.test(m)).length;\n const ticketRatio = ticketCount / messages.length;\n\n if (ticketRatio > 0.3) {\n findings.push(\n this.createFinding({\n category: \"convention\",\n confidence: ticketRatio,\n summary: `${Math.round(ticketRatio * 100)}% of commits reference issue/ticket IDs`,\n evidence: [\n {\n filePath: \".git\",\n detail: `${ticketCount} of ${messages.length} commits have ticket refs`,\n },\n ],\n ruleCandidate:\n \"Include issue/ticket references in commit messages when applicable.\",\n })\n );\n }\n\n return findings;\n }\n}\n","import fs from \"node:fs/promises\";\nimport fg from \"fast-glob\";\nimport type {\n AnalyzerContext,\n AnalyzerResult,\n Finding,\n FindingCategory,\n} from \"../types.js\";\n\nexport abstract class BaseAnalyzer {\n abstract name: string;\n abstract analyze(context: AnalyzerContext): Promise<AnalyzerResult>;\n\n protected async findFiles(\n patterns: string[],\n root: string\n ): Promise<string[]> {\n return fg(patterns, {\n cwd: root,\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/.git/**\"],\n absolute: true,\n });\n }\n\n protected async readFile(filePath: string): Promise<string> {\n return fs.readFile(filePath, \"utf-8\");\n }\n\n protected createFinding(partial: {\n category: FindingCategory;\n confidence: number;\n summary: string;\n evidence?: Finding[\"evidence\"];\n ruleCandidate?: string | null;\n }): Finding {\n return {\n analyzer: this.name,\n category: partial.category,\n confidence: partial.confidence,\n summary: partial.summary,\n evidence: partial.evidence ?? [],\n ruleCandidate: partial.ruleCandidate ?? null,\n };\n }\n\n protected createResult(\n findings: Finding[],\n gaps: AnalyzerResult[\"gaps\"],\n startTime: number\n ): AnalyzerResult {\n return {\n analyzer: this.name,\n findings,\n gaps,\n durationMs: Date.now() - startTime,\n };\n }\n}\n","import type { AnalyzerContext, AnalyzerResult } from \"../types.js\";\nimport type { BaseAnalyzer } from \"./base.js\";\nimport { GitHistoryAnalyzer } from \"./git-history.js\";\n\nconst analyzers: BaseAnalyzer[] = [new GitHistoryAnalyzer()];\n\nexport async function runAll(\n context: AnalyzerContext\n): Promise<AnalyzerResult[]> {\n return Promise.all(analyzers.map((a) => a.analyze(context)));\n}\n","import { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst exec = promisify(execFile);\n\nexport async function isGitRepo(dir: string): Promise<boolean> {\n try {\n await exec(\"git\", [\"rev-parse\", \"--git-dir\"], { cwd: dir });\n return true;\n } catch {\n return false;\n }\n}\n","import path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { createFileAccess, SOURCE_EXTENSIONS } from \"../utils/files.js\";\nexport type { ProjectConfig } from \"../utils/files.js\";\n\nconst exec = promisify(execFile);\n\nconst CONFIG_FILES = [\n // Build & project config\n \"package.json\",\n \"tsconfig.json\",\n \"build.gradle.kts\",\n \"build.gradle\",\n \"settings.gradle.kts\",\n \"settings.gradle\",\n \"Cargo.toml\",\n \"go.mod\",\n \"pyproject.toml\",\n \"Gemfile\",\n \"*.csproj\",\n // Version catalogs & dependency locks\n \"gradle/libs.versions.toml\",\n // Code quality & formatting\n \".editorconfig\",\n \".eslintrc.*\",\n \"eslint.config.*\",\n \".prettierrc\",\n \"rustfmt.toml\",\n \".swiftlint.yml\",\n // CI/CD\n \".github/workflows/*.yml\",\n \".gitlab-ci.yml\",\n \"Jenkinsfile\",\n // Containerization\n \"Dockerfile\",\n \"docker-compose.yml\",\n \"docker-compose.yaml\",\n];\n\nconst ENTRY_POINT_PATTERNS = [\n \"src/main.*\",\n \"src/index.*\",\n \"src/app.*\",\n \"main.*\",\n \"index.*\",\n \"app.*\",\n \"App.*\",\n \"**/Main.kt\",\n \"**/Application.kt\",\n \"**/main.py\",\n \"**/main.go\",\n \"**/main.rs\",\n \"**/lib.rs\",\n \"**/Program.cs\",\n];\n\n// Filename patterns that reveal architectural patterns and conventions.\n// These are language-agnostic — the suffixes appear across ecosystems.\n// Ordered by architectural importance — most distinctive patterns first.\nconst ARCHITECTURAL_PATTERNS = [\n // State/data flow\n { glob: \"**/*ViewModel.*\", category: \"state\", reason: \"viewmodel (state management)\" },\n { glob: \"**/*Store.*\", category: \"state\", reason: \"store (state management)\" },\n { glob: \"**/*Reducer.*\", category: \"state\", reason: \"reducer (state management)\" },\n // Data layer — interface\n { glob: \"**/*Repository.*\", category: \"data-interface\", reason: \"repository interface (data layer contract)\" },\n { glob: \"**/*Dao.*\", category: \"data-interface\", reason: \"DAO (data access)\" },\n { glob: \"**/*DataSource.*\", category: \"data-interface\", reason: \"data source\" },\n // Data layer — implementation (where actual patterns live: mappers, retry, IO dispatchers)\n { glob: \"**/*RepositoryImpl.*\", category: \"data-impl\", reason: \"repository implementation (data layer patterns)\" },\n { glob: \"**/*ServiceImpl.*\", category: \"data-impl\", reason: \"service implementation\" },\n { glob: \"**/*Impl.*\", category: \"data-impl\", reason: \"implementation (concrete patterns)\" },\n // Data transformation\n { glob: \"**/*Mapper.*\", category: \"transform\", reason: \"mapper (data transformation)\" },\n { glob: \"**/*Converter.*\", category: \"transform\", reason: \"converter (data transformation)\" },\n { glob: \"**/*Adapter.*\", category: \"transform\", reason: \"adapter (interface adaptation)\" },\n // Dependency injection / wiring\n { glob: \"**/*Module.*\", category: \"di\", reason: \"module (DI/wiring)\" },\n { glob: \"**/*Provider.*\", category: \"di\", reason: \"provider (DI/wiring)\" },\n { glob: \"**/*Container.*\", category: \"di\", reason: \"container (DI/wiring)\" },\n { glob: \"**/*Factory.*\", category: \"di\", reason: \"factory (object creation)\" },\n // API / network\n { glob: \"**/*Service.*\", category: \"api\", reason: \"service (business/API layer)\" },\n { glob: \"**/*Client.*\", category: \"api\", reason: \"client (API/network layer)\" },\n { glob: \"**/*Api.*\", category: \"api\", reason: \"API interface definition\" },\n // Interface contracts / protocols\n { glob: \"**/*Interface.*\", category: \"contract\", reason: \"interface definition\" },\n { glob: \"**/*Protocol.*\", category: \"contract\", reason: \"protocol definition\" },\n { glob: \"**/*Trait.*\", category: \"contract\", reason: \"trait definition\" },\n // Routing / navigation\n { glob: \"**/*Router.*\", category: \"routing\", reason: \"router (navigation/routing)\" },\n { glob: \"**/*Route.*\", category: \"routing\", reason: \"route definition\" },\n { glob: \"**/*NavHost.*\", category: \"routing\", reason: \"navigation host\" },\n { glob: \"**/*Controller.*\", category: \"routing\", reason: \"controller (request handling)\" },\n { glob: \"**/*Handler.*\", category: \"routing\", reason: \"handler (request handling)\" },\n // Middleware / interceptors\n { glob: \"**/*Middleware.*\", category: \"middleware\", reason: \"middleware (request pipeline)\" },\n { glob: \"**/*Interceptor.*\", category: \"middleware\", reason: \"interceptor (cross-cutting)\" },\n { glob: \"**/*Plugin.*\", category: \"middleware\", reason: \"plugin (extensibility)\" },\n // Models / types\n { glob: \"**/*Model.*\", category: \"model\", reason: \"model (domain types)\" },\n { glob: \"**/*Entity.*\", category: \"model\", reason: \"entity (persistence types)\" },\n { glob: \"**/*Dto.*\", category: \"model\", reason: \"DTO (data transfer types)\" },\n { glob: \"**/*Schema.*\", category: \"model\", reason: \"schema (data validation)\" },\n // Use cases / commands\n { glob: \"**/*UseCase.*\", category: \"usecase\", reason: \"use case (business logic)\" },\n { glob: \"**/*Interactor.*\", category: \"usecase\", reason: \"interactor (business logic)\" },\n { glob: \"**/*Command.*\", category: \"usecase\", reason: \"command (CQRS pattern)\" },\n];\n\nconst PREVIEW_LINES = 60;\n\nexport interface SampledFile {\n path: string;\n preview: string;\n totalLines: number;\n sizeBytes: number;\n reason: string;\n}\n\nexport async function sampleFiles(\n rootDir: string,\n maxFiles: number = 25\n): Promise<SampledFile[]> {\n const selected = new Map<string, string>(); // path -> reason\n const access = await createFileAccess(rootDir);\n const projectConfig = access.config;\n\n // 0. Always-include files from project config (highest priority)\n for (const filePath of projectConfig.alwaysInclude ?? []) {\n if (selected.size >= maxFiles) break;\n // Validate path stays within project root\n const resolvedPath = path.resolve(rootDir, filePath);\n if (!resolvedPath.startsWith(path.resolve(rootDir))) continue;\n selected.set(filePath, \"always-include (project config)\");\n }\n\n // 1. Config files (cap at 5)\n let configCount = 0;\n for (const pattern of CONFIG_FILES) {\n if (configCount >= 5) break;\n const matches = await access.list(pattern, {\n deep: 3,\n });\n for (const match of matches) {\n if (configCount >= 5 || selected.size >= maxFiles) break;\n selected.set(match, \"config file\");\n configCount++;\n }\n }\n\n // 2. Module build/config files — build files from subdirectories reveal dependency graph\n const moduleBuildPatterns = [\n // Gradle\n \"**/build.gradle.kts\",\n \"**/build.gradle\",\n // Cargo workspace members\n \"**/Cargo.toml\",\n // Node workspaces\n \"**/package.json\",\n // Go sub-modules\n \"**/go.mod\",\n ];\n let moduleBuildCount = 0;\n for (const pattern of moduleBuildPatterns) {\n const matches = await access.list(pattern, {\n deep: 4,\n });\n // Skip root-level files (already captured as config)\n const subMatches = matches.filter((m) => m.includes(\"/\"));\n for (const match of subMatches) {\n if (moduleBuildCount >= 4 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"module build file (reveals dependency graph)\");\n moduleBuildCount++;\n }\n }\n if (moduleBuildCount >= 4) break;\n }\n\n // 3. Entry points (cap at 2)\n let entryCount = 0;\n for (const pattern of ENTRY_POINT_PATTERNS) {\n if (entryCount >= 2) break;\n const matches = await access.list(pattern, {\n deep: 5,\n });\n for (const match of matches) {\n if (entryCount >= 2 || selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"entry point\");\n entryCount++;\n }\n }\n }\n\n // 4. Hot files from git (up to 5)\n try {\n const { stdout } = await exec(\n \"git\",\n [\"log\", \"--since=3 months ago\", \"--format=\", \"--name-only\"],\n { cwd: rootDir, maxBuffer: 5_000_000 }\n );\n\n const fileCounts = new Map<string, number>();\n for (const line of stdout.split(\"\\n\")) {\n if (!line) continue;\n if (\n line.includes(\"node_modules\") ||\n line.includes(\"/build/\") ||\n line.includes(\".gradle\") ||\n line.includes(\"/generated/\")\n )\n continue;\n const ext = path.extname(line).slice(1);\n if (!SOURCE_EXTENSIONS.includes(ext)) continue;\n fileCounts.set(line, (fileCounts.get(line) ?? 0) + 1);\n }\n\n const hotFiles = [...fileCounts.entries()]\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5);\n\n for (const [file, count] of hotFiles) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, `frequently changed (${count} commits in 3 months)`);\n }\n }\n } catch {\n // No git\n }\n\n // 5. Architectural pattern files — one per category (cap at 8)\n const seenCategories = new Set<string>();\n let patternCount = 0;\n for (const pattern of ARCHITECTURAL_PATTERNS) {\n if (patternCount >= 8 || selected.size >= maxFiles) break;\n if (seenCategories.has(pattern.category)) continue;\n\n const matches = await access.list(pattern.glob, {\n });\n\n if (matches.length > 0) {\n for (const match of matches) {\n if (!selected.has(match)) {\n selected.set(match, pattern.reason);\n seenCategories.add(pattern.category);\n patternCount++;\n break;\n }\n }\n }\n }\n\n // 5b. Custom patterns from project config\n for (const customGlob of projectConfig.patterns ?? []) {\n if (selected.size >= maxFiles) break;\n const matches = await access.list(customGlob, {\n });\n for (const match of matches) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(match)) {\n selected.set(match, \"custom pattern (project config)\");\n break; // one per pattern\n }\n }\n }\n\n // 6. Test examples — diverse across file types (cap at 3)\n const testPatternGroups = [\n // JS/TS tests\n { patterns: [\"**/*.test.*\", \"**/*.spec.*\"], label: \"JS/TS test\" },\n // JVM tests\n { patterns: [\"**/*Test.kt\", \"**/*Test.java\"], label: \"JVM test\" },\n // Python tests\n { patterns: [\"**/test_*.py\", \"**/*_test.py\"], label: \"Python test\" },\n // Go tests\n { patterns: [\"**/*_test.go\"], label: \"Go test\" },\n // Swift tests\n { patterns: [\"**/*Tests.swift\", \"**/*Test.swift\"], label: \"Swift test\" },\n // Rust tests\n { patterns: [\"**/*_test.rs\"], label: \"Rust test\" },\n ];\n let testCount = 0;\n for (const group of testPatternGroups) {\n if (testCount >= 3 || selected.size >= maxFiles) break;\n const testFiles = await access.list(group.patterns, {\n });\n if (testFiles.length > 0) {\n for (const file of testFiles) {\n if (!selected.has(file)) {\n selected.set(file, `test example (${group.label})`);\n testCount++;\n break;\n }\n }\n }\n }\n\n // 7. Directory breadth — fill remaining slots with one file per top-level dir\n const sourceGlobs = SOURCE_EXTENSIONS.map((ext) => `**/*.${ext}`);\n const allSourceFiles = await access.list(sourceGlobs, {\n });\n\n const dirRepresentatives = new Map<string, string>();\n const boringFiles = /\\.(gradle|gradle\\.kts|json|toml|yaml|yml|xml|properties)$/;\n for (const file of allSourceFiles) {\n const topDir = file.split(\"/\")[0];\n if (!dirRepresentatives.has(topDir) && !boringFiles.test(file)) {\n dirRepresentatives.set(topDir, file);\n }\n }\n\n for (const [, file] of dirRepresentatives) {\n if (selected.size >= maxFiles) break;\n if (!selected.has(file)) {\n selected.set(file, \"directory representative\");\n }\n }\n\n // Read file previews\n const results: SampledFile[] = [];\n for (const [filePath, reason] of selected) {\n try {\n const full = await access.read(filePath);\n if (!full || Buffer.byteLength(full.content) > 100_000) continue;\n const lines = full.content.split(\"\\n\");\n const preview = lines.slice(0, PREVIEW_LINES).join(\"\\n\");\n\n results.push({\n path: filePath,\n preview,\n totalLines: lines.length,\n sizeBytes: Buffer.byteLength(full.content),\n reason,\n });\n } catch {\n // Skip\n }\n }\n\n return results;\n}\n\nexport async function readFullFile(\n rootDir: string,\n filePath: string\n): Promise<{ path: string; content: string; totalLines: number } | null> {\n return (await createFileAccess(rootDir)).read(filePath);\n}\n","import { createHash } from \"node:crypto\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { z } from \"zod\";\nimport { loadDecisionStore, saveDecisionRecord, withDecisionWrite } from \"./decisions.js\";\nimport { decisionApproval, decisionAnchors, decisionContent, decisionProvenance, effectiveDecision, importLegacy, type DecisionRecord, type ReviewedDecisionRecord } from \"./provenance.js\";\nimport { getCurrentGitHash } from \"../snapshot/snapshot.js\";\nimport { getChangesWithStatus, getWorkingTree, touchedPaths } from \"../drift/drift.js\";\nimport { anchorMatches, matchingPaths } from \"../utils/paths.js\";\nimport { createFileAccess } from \"../utils/files.js\";\n\nconst exec = promisify(execFile);\nconst requestSchema = z.object({\n id: z.string().regex(/^[a-zA-Z0-9_-]+$/),\n action: z.enum([\"prepare\", \"accept\", \"reaffirm\", \"retire\"]).default(\"prepare\"),\n reviewer: z.string().trim().min(1).max(200).optional(),\n note: z.string().trim().min(1).max(1500).optional(),\n reviewToken: z.string().regex(/^[a-f0-9]{64}$/).optional(),\n});\nexport type ReviewDecisionInput = z.input<typeof requestSchema>;\n\nasync function reviewState(root: string, record: DecisionRecord) {\n const [headHash, workingTree, changes] = await Promise.all([\n getCurrentGitHash(root), getWorkingTree(root), getChangesWithStatus(root, record.refreshedHash),\n ]);\n const anchors = decisionAnchors(record);\n const committed = (changes ?? []).filter(c => [c.path, ...(c.previousPath ? [c.previousPath] : [])].some(file => anchors.some(anchor => anchorMatches(anchor, file))));\n const evidence = {\n baseHash: record.refreshedHash, headHash, historyAvailable: changes !== null,\n changedFiles: touchedPaths(committed), localChanges: matchingPaths(anchors, workingTree.changedFiles),\n };\n const reviewToken = createHash(\"sha256\").update(JSON.stringify({ record, evidence, workingTreeAvailable: workingTree.available })).digest(\"hex\");\n return { reviewToken, evidence, committed, workingTreeAvailable: workingTree.available };\n}\n\nasync function previews(root: string, record: DecisionRecord, state: Awaited<ReturnType<typeof reviewState>>) {\n const access = await createFileAccess(root);\n const anchors = decisionAnchors(record);\n const candidates = [...new Set([...state.evidence.changedFiles, ...state.evidence.localChanges, ...anchors,\n ...(await access.list()).filter(file => anchors.some(anchor => anchorMatches(anchor, file))),\n ])];\n const files: Array<{ path: string; preview: string; totalLines: number }> = [];\n const omittedFiles: string[] = [];\n const diffPaths: string[] = [];\n for (const file of candidates) {\n if (files.length >= 6) { omittedFiles.push(file); continue; }\n const source = await access.read(file);\n if (!source) { omittedFiles.push(file); continue; }\n files.push({ path: source.path, preview: source.content.slice(0, 2000), totalLines: source.totalLines });\n if (state.evidence.changedFiles.includes(file)) diffPaths.push(file);\n }\n let diff: string | null = null;\n let diffUnavailable: string | undefined;\n if (state.evidence.historyAvailable && diffPaths.length) {\n try {\n const { stdout } = await exec(\"git\", [\"--literal-pathspecs\", \"diff\", \"--no-ext-diff\", \"--no-textconv\", \"--no-color\", \"--no-renames\", \"-U3\", record.refreshedHash, state.evidence.headHash, \"--\", ...diffPaths], { cwd: root, maxBuffer: 1024 * 1024 });\n diff = stdout.slice(0, 16000);\n if (stdout.length > diff.length) diffUnavailable = \"Diff preview was truncated; inspect the full diff before reviewing.\";\n } catch { diffUnavailable = \"Diff preview could not be read within its size bound; inspect the diff separately.\"; }\n }\n return { files, diff, diffUnavailable, omittedFiles, hint: \"Bounded source and diff previews only. Deleted, excluded, sensitive, oversized, or additional files may be omitted. Inspect relevant evidence beyond these previews before recording a verdict.\" };\n}\n\n/** Prepare first, then attest to that exact record and committed code revision. */\nexport async function reviewDecision(root: string, input: ReviewDecisionInput) {\n const parsed = requestSchema.safeParse(input);\n if (!parsed.success) return { status: \"error\", error: parsed.error.message };\n const request = parsed.data;\n const read = async () => {\n const store = await loadDecisionStore(root);\n return { ...store, record: store.records.find(record => record.id === request.id) };\n };\n if (request.action === \"prepare\") {\n const { record, diagnostics } = await read();\n if (!record) return { status: \"error\", error: `No readable decision with id \"${request.id}\"`, diagnostics };\n const state = await reviewState(root, record);\n const operativeDecision = effectiveDecision(record);\n return {\n status: \"prepared\", record, ...(operativeDecision !== record ? { operativeDecision } : {}), provenance: decisionProvenance(record), ...state, diagnostics,\n previews: await previews(root, record, state),\n hint: \"Inspect the proposed content, operativeDecision, sources, history, and code changes. A pending proposal leaves the prior accepted revision operative; accepting it replaces that revision, and retirement withdraws the entire decision including its proposal. Evidence covers both revisions' anchors. Only record acceptance or reaffirmation when the user or cited team review has authorized it. Supply that reviewer's identity, a reason, and this reviewToken. Do not invent identities or infer agreement from unchanged code. Acceptance and reaffirmation require committed anchor changes; retirement is available independently. Missing old history remains visible in the event even if a reviewer establishes a new baseline at HEAD. Saved reviews are local assertions for normal PR review, not authenticated approvals.\",\n };\n }\n if (!request.reviewer || !request.note || !request.reviewToken) return { status: \"error\", error: \"Prepare the review first, then provide reviewToken, reviewer, and note.\" };\n return withDecisionWrite(root, async () => {\n const { record: original, diagnostics } = await read();\n if (diagnostics.length) return { status: \"error\", error: \"Repair malformed decision records before recording a review.\", diagnostics };\n if (!original) return { status: \"error\", error: `No decision with id \"${request.id}\"` };\n const state = await reviewState(root, original);\n if (state.reviewToken !== request.reviewToken) return { status: \"conflict\", error: \"The decision or code revision changed after preparation. Prepare and inspect a new review.\" };\n if (original.status !== \"active\") return { status: \"error\", error: \"Archived decisions cannot be reviewed again; create a new proposal.\" };\n const approval = decisionApproval(original);\n if (request.action === \"accept\" && approval === \"accepted\") return { status: \"error\", error: \"This decision is already accepted. Use reaffirm to record a new review.\" };\n if (request.action === \"reaffirm\" && approval !== \"accepted\") return { status: \"error\", error: \"Only accepted decisions can be reaffirmed. Review and accept this proposal or legacy record first.\" };\n const now = new Date().toISOString();\n const record = importLegacy(original, now);\n if (request.action !== \"retire\") {\n if (!record.owner || !record.sources.length) return { status: \"error\", error: \"Acceptance requires an owner and at least one source. Add them with save_decision, then prepare a new review.\" };\n if (state.evidence.headHash === \"unknown\" || !state.workingTreeAvailable || state.evidence.localChanges.length) return { status: \"error\", error: \"Acceptance requires readable Git HEAD and working-tree evidence with no uncommitted anchor changes. Commit the anchor changes and prepare a new review.\", evidence: state.evidence };\n }\n const status = request.action === \"retire\" ? \"retired\" : \"active\";\n const nextApproval = request.action === \"retire\" ? record.approval : \"accepted\";\n const refreshedHash = request.action === \"retire\" ? record.refreshedHash : state.evidence.headHash;\n const event = { kind: request.action === \"accept\" ? \"accepted\" : request.action === \"reaffirm\" ? \"reaffirmed\" : \"retired\",\n at: now, actor: request.reviewer, note: request.note, revision: record.revision, content: decisionContent(record),\n approval: nextApproval, status, refreshedHash, evidence: state.evidence,\n } as const;\n const updated: ReviewedDecisionRecord = { ...record, status, approval: nextApproval, refreshedHash, updatedAt: now, history: [...record.history, event] };\n // Detect an external Git operation during review preparation, too.\n if ((await reviewState(root, original)).reviewToken !== state.reviewToken) return { status: \"conflict\", error: \"Code changed while the review was being recorded. Prepare a new review.\" };\n await saveDecisionRecord(root, updated);\n return { status: event.kind, id: record.id, event, hint: \"Review recorded locally. Review and commit the decision file through the normal project workflow.\" };\n });\n}\n","export const BATCH_SYSTEM_PROMPT = `You are Mason, building one piece of a larger concept-to-files map via a Map-Reduce pattern.\n\nYou are seeing ONE batch of files from this project — not the whole codebase. Other batches will be processed separately and merged with yours in a final reduce step.\n\nYour job for this batch: identify the features and flows that involve the files in this batch, and return a partial concept map.\n\nRespond with ONLY a JSON object. No markdown, no explanation, no code fences. Just the raw JSON. Same shape as the full map (\\`{\"features\": {...}, \"flows\": {...}}\\`).\n\nCRITICAL: name features in PRODUCT-NATURAL language (e.g., \"home screen\", \"authentication\", \"checkout\"). Do NOT add platform or layer suffixes — call both the Android and iOS home-screen files part of a feature named \"home screen\". This is what lets the reduce step merge platform variants from other batches into a single product feature.\n\nOther rules:\n- Only include files that you see in this batch. Don't predict files in other batches.\n- Use the FULL relative file paths exactly as given.\n- Classify each feature with a \"type\": \"capability\" (user-facing functionality) or \"infrastructure\" (internal plumbing with no end user — DI/service wiring, configuration, logging, adapters, build tooling). When unsure, use \"capability\".\n- Each feature should have 1–8 files from this batch — partials can be narrow.\n- Flows in a partial only make sense if all their chain steps are in this batch. Skip flows that span batches; the reduce step will assemble them.\n- Include test files in \"tests\" when present in this batch.\n- Two views of the batch: FILE HEADERS (every file in the batch, skeleton-level) and REPRESENTATIVE BODIES (deeper read of a few for grounding). Use the bodies to learn the codebase's domain vocabulary; use the headers to know which files exist.`;\n\nexport const REDUCE_SYSTEM_PROMPT = `You are Mason, merging partial concept maps from a Map-Reduce pass into a single unified map.\n\nYou will receive an array of \\`partials\\`, each produced from one batch of files. Your job: merge them into one coherent concept-to-files map for the whole project.\n\nRespond with ONLY a JSON object: \\`{\"features\": {...}, \"flows\": {...}}\\`. No markdown, no preamble.\n\nMerge rules:\n- If two partials use the same feature name (e.g., both have \"home screen\"), MERGE them — combine their \\`files\\` and \\`tests\\` arrays (dedupe), and reconcile descriptions by picking the more product-natural wording or merging the two.\n- If two partials use *near-duplicate* feature names that clearly refer to the same product concept (\"home screen\" vs \"home view\", \"auth\" vs \"authentication\"), merge them under the more product-natural name.\n- If a partial split what should be one feature by platform (\"home Android\" + \"home iOS\"), merge into a single platform-agnostic feature (\"home screen\").\n- Preserve each feature's \"type\" (\"capability\" or \"infrastructure\"). When merged partials disagree on a feature's type, prefer \"capability\". If a partial omitted the type, infer it: user-facing functionality is \"capability\"; internal plumbing with no end user (DI/service wiring, config, logging, adapters) is \"infrastructure\".\n- For flows that were skipped by partials because they span batches, reconstruct them when you can see the full chain across multiple partials.\n- Every file that appears in any partial MUST end up in some feature in the unified map. Don't silently drop files.\n- Feature descriptions in the final map should be 1–2 sentences, written for a product/PM audience — concrete and specific, but free of code-level detail.\n- Each feature should have 2–8 files. If merging produces a feature with 20+ files, consider whether it should be split into sub-features.`;\n\nexport function buildBatchPrompt(\n batch: {\n offset: number;\n batchSize: number;\n nextOffset: number | null;\n totalFiles: number;\n skeletons: Array<{ path: string; content: string }>;\n samples: Array<{ path: string; content: string }>;\n testPairs?: Array<{ test: string; source: string; confidence: string }>;\n }\n): string {\n const skeletonBlocks = batch.skeletons\n .map(\n (f) =>\n `--- ${f.path} ---\\n${f.content}${f.content.length >= 500 ? \"\\n... (truncated)\" : \"\"}`\n )\n .join(\"\\n\\n\");\n\n const sampleBlocks = batch.samples\n .map(\n (f) =>\n `=== ${f.path} (deeper read) ===\\n${f.content}${f.content.length >= 1500 ? \"\\n... (truncated)\" : \"\"}`\n )\n .join(\"\\n\\n\");\n\n const batchInfo = `Batch ${Math.floor(batch.offset / batch.batchSize) + 1}: files ${batch.offset + 1}–${batch.offset + batch.skeletons.length} of ${batch.totalFiles}.`;\n\n let prompt = `${batchInfo}\n\n=== FILE HEADERS (every file in this batch) ===\n\n${skeletonBlocks}\n\n=== REPRESENTATIVE BODIES (for grounding) ===\n\n${sampleBlocks}`;\n\n if (batch.testPairs && batch.testPairs.length > 0) {\n const testBlock = batch.testPairs\n .map((p) => `${p.test} → ${p.source}`)\n .join(\"\\n\");\n prompt += `\\n\\n=== TEST → SOURCE MAPPINGS (for this batch) ===\\n\\n${testBlock}`;\n }\n\n return prompt;\n}\n\nexport function buildReducePrompt(\n partials: Array<{\n batchId: string;\n offset: number;\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n }>\n): string {\n return `Merge the following ${partials.length} partial concept maps into a single unified map.\n\n${JSON.stringify({ partials }, null, 2)}`;\n}\n\nexport const REFRESH_REDUCE_SYSTEM_PROMPT = `You are Mason, merging a scoped refresh into an existing concept-to-files map.\n\nOnly a subset of the project's files was re-analyzed (they changed since the map was built). You receive the existing full map, the list of re-analyzed file paths, and partial concept maps derived from ONLY those files.\n\nRespond with ONLY a JSON object: \\`{\"features\": {...}, \"flows\": {...}}\\` — the COMPLETE updated map. No markdown, no preamble.\n\nMerge rules:\n- Entries in the existing map that reference none of the re-analyzed files: copy them through UNCHANGED.\n- Entries that reference re-analyzed files: update them using the partials — adjust descriptions, add new files, drop files that moved elsewhere.\n- Merge partial features into existing features when they're the same product concept, even if named slightly differently (\"auth\" vs \"authentication\") — keep the existing name unless the new one is clearly more product-natural.\n- Features whose files were all deleted or renamed away: remove them by omitting them from your output.\n- Every file that appears in any partial MUST end up in some feature. Don't silently drop files.\n- Do not invent or alter entries for files you haven't seen.`;\n\nexport function buildRefreshReducePrompt(\n existingMap: {\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n },\n refreshedFiles: string[],\n partials: Array<{\n batchId: string;\n offset: number;\n features: Record<string, { description: string; files: string[]; tests?: string[] }>;\n flows: Record<string, { description: string; chain: string[] }>;\n }>\n): string {\n return `Merge this scoped refresh into the existing concept map.\n\n=== EXISTING MAP ===\n${JSON.stringify(existingMap, null, 2)}\n\n=== RE-ANALYZED FILES ===\n${refreshedFiles.join(\"\\n\")}\n\n=== PARTIALS (derived from the re-analyzed files only) ===\n${JSON.stringify({ partials }, null, 2)}`;\n}\n\n","import fs from \"node:fs/promises\";\nimport { z } from \"zod\";\nimport { readStoreJson, writeStoreJson, storePath } from \"../utils/storage.js\";\nimport { featureSchema, flowSchema } from \"./snapshot.js\";\nimport type { FeatureEntry, FlowEntry } from \"./snapshot.js\";\n\nexport interface Partial {\n batchId: string;\n offset: number;\n features: Record<string, FeatureEntry>;\n flows: Record<string, FlowEntry>;\n savedAt: string;\n}\n\nconst DIRECTORY = \".mason/partial-snapshots\";\nconst partialSchema = z.object({\n batchId: z.string().regex(/^[a-zA-Z0-9_-]+$/), offset: z.number().int().nonnegative(),\n features: z.record(featureSchema), flows: z.record(flowSchema), savedAt: z.string(),\n});\nconst scopeSchema = z.object({ files: z.array(z.string()), savedAt: z.string() });\n\nexport async function savePartial(rootDir: string, partial: Partial): Promise<void> {\n if (!/^[a-zA-Z0-9_-]+$/.test(partial.batchId)) throw new Error(`Invalid batchId: ${partial.batchId}`);\n await writeStoreJson(rootDir, `${DIRECTORY}/${partial.batchId}.json`, partialSchema.parse(partial));\n}\n\nexport async function loadAllPartials(rootDir: string): Promise<Partial[]> {\n let entries: string[];\n try { entries = await fs.readdir(await storePath(rootDir, DIRECTORY)); }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw error;\n }\n const partials: Partial[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry === \"scope.json\") continue;\n const partial = partialSchema.parse(await readStoreJson(rootDir, `${DIRECTORY}/${entry}`));\n if (entry !== `${partial.batchId}.json`) throw new Error(`Invalid partial filename: ${entry}`);\n partials.push(partial);\n }\n return partials.sort((a, b) => a.offset - b.offset);\n}\n\nexport async function saveScope(rootDir: string, files: string[]): Promise<void> {\n await writeStoreJson(rootDir, `${DIRECTORY}/scope.json`, { files, savedAt: new Date().toISOString() });\n}\n\nexport async function loadScope(rootDir: string): Promise<string[] | null> {\n const raw = await readStoreJson(rootDir, `${DIRECTORY}/scope.json`);\n return raw === null ? null : scopeSchema.parse(raw).files;\n}\n\nexport async function clearScope(rootDir: string): Promise<void> {\n await fs.rm(await storePath(rootDir, `${DIRECTORY}/scope.json`), { force: true });\n}\n\nexport async function clearAllPartials(rootDir: string): Promise<void> {\n await fs.rm(await storePath(rootDir, DIRECTORY), { recursive: true, force: true });\n}\n\nexport function batchIdFor(offset: number): string {\n return `batch-${String(offset).padStart(6, \"0\")}`;\n}\n","import { startMcpServer } from \"../src/mcp/server.js\";\n\nstartMcpServer().catch((err) => {\n process.stderr.write(`Mason MCP server error: ${err}\\n`);\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;AAAA,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;AAEO,SAAS,kBAAkB,OAA2B;AAC3D,SAAO,CAAC,GAAG,IAAI,IAAI,MAAM,IAAI,iBAAiB,EAAE,OAAO,CAAC,MAAmB,M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,IACX,OAAO,EACP,SAAS,EACT,SAAS,wCAAwC;AAAA,MACpD,gBAAgBA,IACb,OAAO,EACP,SAAS,EACT,SAAS,8DAAyD;AAAA,MACrE,oBAAoBA,IACjB,OAAO,EACP,SAAS,EACT,SAAS,iEAA4D;AAAA,MACxE,mBAAmBA,IAChB,OAAO,EACP,SAAS,EACT,SAAS,2DAA2D;AAAA,IACzE;AAAA,IACA,OAAO,EAAE,KAAK,UAAU,cAAc,gBAAgB,oBAAoB,kBAAkB,MAAM;AAChG,YAAM,SAAS,MAAM,uBAAuB,KAAK;AAAA,QAC/C;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AACD,aAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,OAAO,CAAC,EAAE;AAAA,IACrD;AAAA,EACF;AAEA,SAAO;AACT;AAEA,eAAsB,iBAAgC;AACpD,QAAM,SAAS,gBAAgB;AAC/B,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;;;AW5jBA,eAAe,EAAE,MAAM,CAAC,QAAQ;AAC9B,UAAQ,OAAO,MAAM,2BAA2B,GAAG;AAAA,CAAI;AACvD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["index","content","message","path","configPath","resolve","content","fs","path","path","count","path","execFile","promisify","z","exec","fs","path","execFile","promisify","exec","count","hash","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","text","fs","path","record","content","path","init_drift","init_drift","fs","path","fs","path","createHash","randomUUID","z","content","z","execFile","promisify","exec","index","init_paths","message","init_types","z","index","count","init_paths","init_types","z","schema","resolve","rule","init_paths","init_types","path","z","index","checkSchema","previews","init_types","fs","path","execFile","promisify","exec","init_drift","MAX_FINDINGS","path","execFile","promisify","exec","count","content","path","fs","decisions","impact","relatedTests","stale","init_drift","randomUUID","z","message","attempt","git","fs","path","createHash","execFile","promisify","fg","z","exec","text","exists","index","init_evidence","fs","os","z","resolve","randomUUID","git","report","notify","init_evidence","text","z","z","init_evidence","z","fs","path","randomUUID","createHash","execFile","promisify","exec","init_runtime","init_evidence","fs","path","randomUUID","text","init_files","z","text","config","servers","index","planAutomationInstall","git","init_files","fs","z","init_evidence","isDeepStrictEqual","message","init_evidence","init_runtime","init_files","randomUUID","init_evidence","init_files","init_runtime","path","text","fs","path","os","execFile","promisify","exec","init_config","text","fs","path","createHash","execFile","promisify","resolve","exec","init_config","text","hash","hash","z","fs","path","execFile","promisify","path","execFile","promisify","fs","fg","exec","promisify","execFile","count","execFile","promisify","exec","path","execFile","promisify","exec","count","reason","createHash","execFile","promisify","z","exec","init_drift","fs","z","exec","promisify","execFile","path","fs","count","buildTestMap","previews","loadDecisionStore","path","analyzeImpact","upsertDecision","reviewDecision","assembleContext","automate","automationStatus","summarize","installedAutomation","setupStatus","automationFailure","setupProject","createConfluenceClient","saveConfluenceConfig","normalizeAtlassianBaseUrl","loadConfig","exportToConfluence","z","count","observeActivation","reviewDecision"]}
|