truthmark 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.de.md +623 -193
- package/README.es.md +624 -194
- package/README.md +614 -191
- package/README.ru.md +631 -201
- package/README.zh.md +630 -198
- package/dist/main.js +846 -39
- package/dist/main.js.map +1 -1
- package/package.json +1 -1
package/dist/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli/program.ts","../src/output/render.ts","../src/config/command.ts","../src/fs/paths.ts","../src/git/repository.ts","../src/templates/init-files.ts","../src/config/schema.ts","../src/config/defaults.ts","../src/routing/areas.ts","../src/truth/docs.ts","../src/init/init.ts","../src/config/load.ts","../src/init/hierarchy.ts","../src/truth/evidence.ts","../src/agents/shared.ts","../src/version.ts","../src/templates/agents-block.ts","../src/templates/default-standards.ts","../src/agents/workflow-manifest.ts","../src/agents/truth-check.ts","../src/agents/truth-document.ts","../src/agents/truth-preview.ts","../src/agents/truth-structure.ts","../src/sync/report.ts","../src/agents/truth-sync.ts","../src/agents/write-lease.ts","../src/templates/workflow-surfaces.ts","../src/templates/generated-surfaces.ts","../src/checks/branch-scope.ts","../src/markdown/hash.ts","../src/checks/authority.ts","../src/checks/frontmatter.ts","../src/markdown/parse.ts","../src/checks/links.ts","../src/checks/areas.ts","../src/routing/area-resolver.ts","../src/sync/classify.ts","../src/checks/decisions.ts","../src/checks/generated-surfaces.ts","../src/impact/build.ts","../src/repo-index/build.ts","../src/repo-index/file-tree.ts","../src/repo-index/package-metadata.ts","../src/repo-index/route-map.ts","../src/repo-index/typescript-symbols.ts","../src/impact/git-diff.ts","../src/git/changes.ts","../src/evidence/validate.ts","../src/evidence/parse.ts","../src/freshness/check.ts","../src/checks/check.ts","../src/context-pack/build.ts","../src/context-pack/render.ts","../src/cli/handlers.ts","../src/cli/main.ts"],"sourcesContent":["import { Command } from \"commander\";\n\nimport type { CommandResult } from \"../output/diagnostic.js\";\nimport { renderHuman, renderJson } from \"../output/render.js\";\nimport { runCheck, runConfig, runContext, runImpact, runIndex, runInit } from \"./handlers.js\";\n\ntype OutputOptions = {\n json?: boolean;\n};\n\ntype ConfigOptions = OutputOptions & {\n stdout?: boolean;\n force?: boolean;\n};\n\ntype CheckCliOptions = OutputOptions & {\n base?: string;\n};\n\ntype ImpactOptions = OutputOptions & {\n base?: string;\n};\n\ntype ContextOptions = OutputOptions & {\n workflow?: string;\n base?: string;\n format?: string;\n};\n\nconst writeResult = (result: CommandResult, options: OutputOptions): void => {\n const output = options.json ? renderJson(result) : renderHuman(result);\n process.stdout.write(`${output}\\n`);\n};\nconst writeContextResult = (result: CommandResult, options: ContextOptions): void => {\n if (!options.json && options.format === \"markdown\" && typeof result.data?.markdown === \"string\") {\n process.stdout.write(result.data.markdown);\n return;\n }\n writeResult(result, options);\n};\n\nconst addJsonOption = (command: Command): Command => {\n return command.option(\"--json\", \"Render command output as JSON\");\n};\n\nexport const buildProgram = (): Command => {\n const program = new Command();\n\n program\n .name(\"truthmark\")\n .description(\"Git-native, branch-scoped truth workflow installer for local AI coding agents.\")\n .showHelpAfterError();\n\n addJsonOption(\n program\n .command(\"config\")\n .description(\"Create or render the Truthmark repository config before initialization.\")\n .option(\"--stdout\", \"Render default config in the JSON data payload without writing\")\n .option(\"--force\", \"Overwrite an existing .truthmark/config.yml\"),\n ).action(async (options: ConfigOptions) => {\n writeResult(await runConfig(options), options);\n });\n\n addJsonOption(\n program\n .command(\"init\")\n .description(\"Initialize Truthmark workflow files in the current repository.\"),\n ).action(async (options: OutputOptions) => {\n writeResult(await runInit(), options);\n });\n\n addJsonOption(\n program\n .command(\"check\")\n .description(\"Run local Truthmark diagnostics.\")\n .option(\"--base <ref>\", \"Base Git ref for freshness diagnostics\"),\n ).action(async (options: CheckCliOptions) => {\n writeResult(await runCheck({ base: options.base }), options);\n });\n\n addJsonOption(\n program.command(\"index\").description(\"Build the deterministic Truthmark repository index.\"),\n ).action(async (options: OutputOptions) => {\n writeResult(await runIndex(), options);\n });\n\n addJsonOption(\n program\n .command(\"impact\")\n .description(\"Map changed files to truth routes, docs, owners, and tests.\")\n .requiredOption(\"--base <ref>\", \"Base Git ref to compare against\"),\n ).action(async (options: ImpactOptions) => {\n writeResult(await runImpact({ base: options.base }), options);\n });\n\n addJsonOption(\n program\n .command(\"context\")\n .description(\"Generate a bounded workflow context pack.\")\n .requiredOption(\"--workflow <workflow>\", \"Workflow name: truth-sync, truth-document, or truth-realize\")\n .option(\"--base <ref>\", \"Base Git ref for impact-backed packs\")\n .option(\"--format <format>\", \"Output format: json or markdown\", \"json\"),\n ).action(async (options: ContextOptions) => {\n writeContextResult(\n await runContext({\n workflow: options.workflow,\n base: options.base,\n format: options.format,\n }),\n options,\n );\n });\n\n return program;\n};\n","import type { CommandResult, Diagnostic } from \"./diagnostic.js\";\n\nconst formatContext = (diagnostic: Diagnostic): string => {\n const parts: string[] = [];\n\n if (diagnostic.file) {\n parts.push(`file: ${diagnostic.file}`);\n }\n\n if (diagnostic.area) {\n parts.push(`area: ${diagnostic.area}`);\n }\n\n return parts.length > 0 ? ` (${parts.join(\", \")})` : \"\";\n};\n\nconst toStableValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => toStableValue(entry));\n }\n\n if (value && typeof value === \"object\") {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((stable, key) => {\n stable[key] = toStableValue((value as Record<string, unknown>)[key]);\n return stable;\n }, {});\n }\n\n return value;\n};\n\nexport const renderHuman = (result: CommandResult): string => {\n const lines = [`truthmark ${result.command}`, result.summary];\n\n if (result.diagnostics.length > 0) {\n lines.push(\"\");\n }\n\n for (const diagnostic of result.diagnostics) {\n lines.push(\n `[${diagnostic.severity.toUpperCase()}] ${diagnostic.category}: ${diagnostic.message}${formatContext(diagnostic)}`,\n );\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const renderJson = (result: CommandResult): string => {\n return JSON.stringify(toStableValue(result), null, 2);\n};","import fs from \"node:fs/promises\";\n\nimport type { CommandResult } from \"../output/diagnostic.js\";\nimport { ensureRepoFile, resolveRepoPath, writeRepoFile } from \"../fs/paths.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport { renderConfigTemplate } from \"../templates/init-files.js\";\n\nexport type ConfigCommandOptions = {\n stdout?: boolean;\n force?: boolean;\n};\n\nconst CONFIG_PATH = \".truthmark/config.yml\";\n\nconst configExists = async (rootDir: string): Promise<boolean> => {\n try {\n await fs.stat(resolveRepoPath(rootDir, CONFIG_PATH));\n return true;\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n\n throw error;\n }\n};\n\nexport const runConfig = async (\n cwd: string,\n options: ConfigCommandOptions = {},\n): Promise<CommandResult> => {\n const repository = await getGitRepository(cwd);\n const content = renderConfigTemplate();\n\n if (options.stdout) {\n return {\n command: \"config\",\n summary: \"Rendered default Truthmark config.\",\n diagnostics: [],\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n path: CONFIG_PATH,\n content,\n },\n };\n }\n\n const exists = await configExists(repository.worktreePath);\n\n if (exists && !options.force) {\n return {\n command: \"config\",\n summary: \"Truthmark config already exists. Use --force to overwrite it.\",\n diagnostics: [\n {\n category: \"config\",\n severity: \"review\",\n message: \"Existing .truthmark/config.yml was left unchanged.\",\n file: CONFIG_PATH,\n },\n ],\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n },\n };\n }\n\n const result = options.force\n ? await writeRepoFile(repository.worktreePath, CONFIG_PATH, content)\n : await ensureRepoFile(repository.worktreePath, CONFIG_PATH, content);\n\n return {\n command: \"config\",\n summary: `Wrote Truthmark config to ${CONFIG_PATH}. Review it before running truthmark init.`,\n diagnostics: [\n {\n category: \"config\",\n severity: \"action\",\n message: result.status === \"updated\" ? `Updated ${CONFIG_PATH}.` : `Created ${CONFIG_PATH}.`,\n file: CONFIG_PATH,\n },\n ],\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n },\n };\n};\n","import path from \"node:path\";\n\nimport fs from \"node:fs/promises\";\n\nexport type FileWriteStatus = \"created\" | \"updated\" | \"unchanged\";\n\nexport type FileWriteResult = {\n path: string;\n status: FileWriteStatus;\n};\n\nconst isPathInsideRoot = (rootDir: string, targetPath: string): boolean => {\n return targetPath === rootDir || targetPath.startsWith(`${rootDir}${path.sep}`);\n};\n\nconst isNodeErrorWithCode = (error: unknown, code: string): boolean => {\n return error instanceof Error && \"code\" in error && error.code === code;\n};\n\nconst joinMissingSegments = (resolvedPath: string, missingSegments: string[]): string => {\n return missingSegments.reduce<string>((currentResolvedPath, segment) => {\n return path.join(currentResolvedPath, segment);\n }, resolvedPath);\n};\n\nconst resolveThroughExistingAncestor = async (targetPath: string): Promise<string> => {\n let currentPath = path.resolve(targetPath);\n const missingSegments: string[] = [];\n\n while (true) {\n try {\n const resolvedExistingPath = await fs.realpath(currentPath);\n\n return joinMissingSegments(resolvedExistingPath, missingSegments);\n } catch (error: unknown) {\n if (!isNodeErrorWithCode(error, \"ENOENT\")) {\n throw error;\n }\n\n try {\n const currentStat = await fs.lstat(currentPath);\n\n if (currentStat.isSymbolicLink()) {\n const linkTarget = await fs.readlink(currentPath);\n const resolvedLinkTarget = path.resolve(path.dirname(currentPath), linkTarget);\n\n return joinMissingSegments(resolvedLinkTarget, missingSegments);\n }\n } catch (lstatError: unknown) {\n if (!isNodeErrorWithCode(lstatError, \"ENOENT\")) {\n throw lstatError;\n }\n }\n\n const parentPath = path.dirname(currentPath);\n\n if (parentPath === currentPath) {\n return path.resolve(targetPath);\n }\n\n missingSegments.unshift(path.basename(currentPath));\n currentPath = parentPath;\n }\n }\n};\n\nexport const resolveRepoPath = (rootDir: string, relativePath: string): string => {\n const resolvedPath = path.resolve(rootDir, relativePath);\n\n if (!isPathInsideRoot(rootDir, resolvedPath)) {\n throw new Error(\"resolved path must stay inside the repository root\");\n }\n\n return resolvedPath;\n};\n\nexport const assertRepoContainment = async (\n rootDir: string,\n targetPath: string,\n): Promise<void> => {\n const [resolvedRootDir, resolvedTargetPath] = await Promise.all([\n resolveThroughExistingAncestor(rootDir),\n resolveThroughExistingAncestor(targetPath),\n ]);\n\n if (!isPathInsideRoot(resolvedRootDir, resolvedTargetPath)) {\n throw new Error(\"resolved path must stay inside the repository root\");\n }\n};\n\nexport const toRepoRelativePath = (rootDir: string, targetPath: string): string => {\n return path.relative(rootDir, targetPath).split(path.sep).join(\"/\");\n};\n\nconst normalizeContent = (content: string): string => {\n return content.endsWith(\"\\n\") ? content : `${content}\\n`;\n};\n\nexport const writeRepoFile = async (\n rootDir: string,\n relativePath: string,\n content: string,\n): Promise<FileWriteResult> => {\n const absolutePath = resolveRepoPath(rootDir, relativePath);\n await assertRepoContainment(rootDir, absolutePath);\n const normalizedContent = normalizeContent(content);\n\n let existingContent: string | null = null;\n\n try {\n existingContent = await fs.readFile(absolutePath, \"utf8\");\n } catch (error: unknown) {\n if (!(error instanceof Error) || !(\"code\" in error) || error.code !== \"ENOENT\") {\n throw error;\n }\n }\n\n if (existingContent === normalizedContent) {\n return {\n path: relativePath,\n status: \"unchanged\",\n };\n }\n\n await fs.mkdir(path.dirname(absolutePath), { recursive: true });\n await fs.writeFile(absolutePath, normalizedContent, \"utf8\");\n\n return {\n path: relativePath,\n status: existingContent === null ? \"created\" : \"updated\",\n };\n};\n\nexport const ensureRepoFile = async (\n rootDir: string,\n relativePath: string,\n content: string,\n): Promise<FileWriteResult> => {\n const absolutePath = resolveRepoPath(rootDir, relativePath);\n await assertRepoContainment(rootDir, absolutePath);\n const normalizedContent = normalizeContent(content);\n\n let existingContent: string | null = null;\n\n try {\n existingContent = await fs.readFile(absolutePath, \"utf8\");\n } catch (error: unknown) {\n if (!(error instanceof Error) || !(\"code\" in error) || error.code !== \"ENOENT\") {\n throw error;\n }\n }\n\n if (existingContent === null) {\n await fs.mkdir(path.dirname(absolutePath), { recursive: true });\n await fs.writeFile(absolutePath, normalizedContent, \"utf8\");\n\n return {\n path: relativePath,\n status: \"created\",\n };\n }\n\n if (existingContent.trim().length === 0) {\n await fs.mkdir(path.dirname(absolutePath), { recursive: true });\n await fs.writeFile(absolutePath, normalizedContent, \"utf8\");\n\n return {\n path: relativePath,\n status: \"updated\",\n };\n }\n\n return {\n path: relativePath,\n status: \"unchanged\",\n };\n};\n","import fs from \"node:fs/promises\";\nimport { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { execa } from \"execa\";\n\nexport type GitRepository = {\n repositoryRoot: string;\n worktreePath: string;\n branchName: string | null;\n headSha: string | null;\n isDetached: boolean;\n isUnborn: boolean;\n};\n\nconst realpathOrResolved = async (targetPath: string): Promise<string> => {\n try {\n return await fs.realpath(targetPath);\n } catch {\n return path.resolve(targetPath);\n }\n};\n\nconst runGit = async (\n cwd: string,\n args: string[],\n reject = true,\n): Promise<{ stdout: string; exitCode: number }> => {\n const result = await execa(\"git\", args, { cwd, reject });\n\n return {\n stdout: result.stdout,\n exitCode: result.exitCode ?? 1,\n };\n};\n\nexport const getGitRepository = async (cwd: string): Promise<GitRepository> => {\n const worktreePath = await realpathOrResolved(\n (await runGit(cwd, [\"rev-parse\", \"--show-toplevel\"])).stdout.trim(),\n );\n const commonDirOutput = (await runGit(cwd, [\"rev-parse\", \"--git-common-dir\"])).stdout.trim();\n const commonDir = await realpathOrResolved(path.resolve(worktreePath, commonDirOutput));\n const repositoryRoot = path.basename(commonDir) === \".git\" ? path.dirname(commonDir) : worktreePath;\n\n const branchResult = await runGit(cwd, [\"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"], false);\n const headResult = await runGit(cwd, [\"rev-parse\", \"--verify\", \"HEAD\"], false);\n\n const branchName = branchResult.exitCode === 0 ? branchResult.stdout.trim() : null;\n const headSha = headResult.exitCode === 0 ? headResult.stdout.trim() : null;\n const isDetached = branchName === null;\n const isUnborn = !isDetached && headSha === null;\n\n return {\n repositoryRoot,\n worktreePath,\n branchName,\n headSha,\n isDetached,\n isUnborn,\n };\n};\n\nexport const resolveWorktreePath = (\n repository: Pick<GitRepository, \"worktreePath\">,\n relativePath: string,\n): string => {\n const resolvedPath = path.resolve(repository.worktreePath, relativePath);\n let currentPath = resolvedPath;\n const missingSegments: string[] = [];\n\n const resolveContainedPath = (): string => {\n while (true) {\n try {\n return missingSegments.reduceRight<string>((resolvedExistingPath, segment) => {\n return path.join(resolvedExistingPath, segment);\n }, realpathSync(currentPath));\n } catch (error: unknown) {\n if (!(error instanceof Error) || !(\"code\" in error) || error.code !== \"ENOENT\") {\n throw error;\n }\n\n const parentPath = path.dirname(currentPath);\n\n if (parentPath === currentPath) {\n return resolvedPath;\n }\n\n missingSegments.unshift(path.basename(currentPath));\n currentPath = parentPath;\n }\n }\n };\n const containedPath = resolveContainedPath();\n\n if (\n containedPath !== repository.worktreePath &&\n !containedPath.startsWith(`${repository.worktreePath}${path.sep}`)\n ) {\n throw new Error(\"resolved path must stay inside the active worktree\");\n }\n\n return resolvedPath;\n};\n","import path from \"node:path\";\nimport { stringify } from \"yaml\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { DiscoveredMarkdownDocument } from \"../markdown/discovery.js\";\nimport {\n createDefaultConfig,\n createDefaultRawConfig,\n} from \"../config/defaults.js\";\nimport { inferTruthDocumentKindFromPath } from \"../routing/areas.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\n\nconst asRelativePath = (value: string): string => {\n return value.split(path.sep).join(\"/\");\n};\n\nconst currentDate = (): string => new Date().toISOString().slice(0, 10);\n\nconst resolveRelativePath = (fromPath: string, toPath: string): string => {\n return asRelativePath(path.relative(path.dirname(fromPath), toPath));\n};\n\nconst truthRoot = resolveTruthDocsRoot;\n\nconst renderTruthDocumentsMetadata = (\n documents: Array<{ path: string; kind: string }>,\n): string[] => {\n return [\n \"```yaml\",\n stringify({ truth_documents: documents }).trimEnd(),\n \"```\",\n ];\n};\n\nexport const renderConfigTemplate = (): string => {\n return stringify(createDefaultRawConfig());\n};\n\nexport const renderAreasTemplate = (\n documents: DiscoveredMarkdownDocument[],\n): string => {\n const truthDocuments =\n documents.length > 0\n ? documents.map((document) => ({\n path: document.path,\n kind: inferTruthDocumentKindFromPath(document.path) ?? \"behavior\",\n }))\n : [{ path: \"docs/truth/**/*.md\", kind: \"behavior\" }];\n\n return [\n \"# Truthmark Areas\",\n \"\",\n \"## Repository Truth Surface\",\n \"\",\n \"Truth documents:\",\n ...renderTruthDocumentsMetadata(truthDocuments),\n \"\",\n \"Code surface:\",\n \"- src/**\",\n \"\",\n \"Update truth when:\",\n \"- behavior changes affect the routed truth documents\",\n \"- API contracts or current feature behavior changes\",\n \"\",\n ].join(\"\\n\");\n};\n\nconst titleCase = (value: string): string => {\n return value\n .split(/[-_\\s]+/u)\n .filter(Boolean)\n .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))\n .join(\" \");\n};\n\nexport const renderHierarchicalAreasIndexTemplate = (\n config: TruthmarkConfig,\n): string => {\n const defaultArea = config.docs.routing.defaultArea;\n const childPath = `${config.docs.routing.areaFilesRoot}/${defaultArea}.md`;\n const title = titleCase(defaultArea);\n const sourceOfTruth = resolveRelativePath(\n config.docs.routing.rootIndex,\n \".truthmark/config.yml\",\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: route-index\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n ` - ${sourceOfTruth}`,\n \"---\",\n \"\",\n \"# Truthmark Areas\",\n \"\",\n `## ${title}`,\n \"\",\n \"Area files:\",\n `- ${childPath}`,\n \"\",\n \"Code surface:\",\n \"- src/**\",\n \"\",\n \"Update truth when:\",\n \"- behavior changes affect the routed truth documents\",\n \"- API contracts or current feature behavior changes\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderChildAreaTemplate = (config: TruthmarkConfig): string => {\n const defaultArea = config.docs.routing.defaultArea;\n const title = titleCase(defaultArea);\n const truthDocsRoot = truthRoot(config);\n const leafTruthDoc = `${truthDocsRoot}/${defaultArea}/overview.md`;\n const templatePath = `${config.docs.routing.areaFilesRoot}/${defaultArea}.md`;\n const sourceOfTruth = resolveRelativePath(templatePath, \".truthmark/config.yml\");\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: area-route\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n ` - ${sourceOfTruth}`,\n \"---\",\n \"\",\n `# ${title} Areas`,\n \"\",\n `## ${title}`,\n \"\",\n \"Truth documents:\",\n \"```yaml\",\n \"truth_documents:\",\n ` - path: ${leafTruthDoc}`,\n \" kind: behavior\",\n \"```\",\n \"\",\n \"Code surface:\",\n \"- src/**\",\n \"\",\n \"Update truth when:\",\n \"- behavior changes affect repository truth\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderTruthRootReadmeTemplate = (\n config: TruthmarkConfig = createDefaultConfig(),\n): string => {\n const templatePath = `${truthRoot(config)}/README.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n config.docs.routing.rootIndex,\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: index\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n ` - ${sourceOfTruth}`,\n \"---\",\n \"\",\n \"# Truth Docs\",\n \"\",\n \"This directory is an index for current truth docs organized by the configured Truthmark hierarchy.\",\n \"\",\n \"README.md files are indexes, not Truth Sync targets. Keep bounded truth in leaf docs under `<domain>/<behavior>.md`.\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderTruthDomainReadmeTemplate = (config: TruthmarkConfig): string => {\n const defaultArea = config.docs.routing.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/README.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n `${config.docs.routing.areaFilesRoot}/${defaultArea}.md`,\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: index\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n ` - ${sourceOfTruth}`,\n \"---\",\n \"\",\n `# ${title} Truth Docs`,\n \"\",\n `This directory indexes bounded ${title.toLowerCase()} truth docs.`,\n \"\",\n \"README.md files are indexes, not Truth Sync targets. Keep bounded truth in leaf docs in this directory.\",\n \"\",\n \"Current leaf docs:\",\n \"\",\n \"- [Overview](overview.md)\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const BEHAVIOR_DOC_TEMPLATE_PATH = \"docs/templates/behavior-doc.md\";\nexport const CONTRACT_DOC_TEMPLATE_PATH = \"docs/templates/contract-doc.md\";\nexport const ARCHITECTURE_DOC_TEMPLATE_PATH = \"docs/templates/architecture-doc.md\";\nexport const WORKFLOW_DOC_TEMPLATE_PATH = \"docs/templates/workflow-doc.md\";\nexport const OPERATIONS_DOC_TEMPLATE_PATH = \"docs/templates/operations-doc.md\";\nexport const TEST_BEHAVIOR_DOC_TEMPLATE_PATH = \"docs/templates/test-behavior-doc.md\";\n\nexport const renderBehaviorDocTemplateFile = (): string => {\n return [\n \"---\",\n \"status: active\",\n \"doc_type: behavior\",\n \"truth_kind: behavior\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n \" - {{source_of_truth}}\",\n \"---\",\n \"\",\n \"# {{title}}\",\n \"\",\n \"## Purpose\",\n \"\",\n \"<!-- State why this feature exists, the user or system outcome it protects, and the problem it solves. Keep roadmap or implementation plans out of this section. -->\",\n \"\",\n \"{{purpose}}\",\n \"\",\n \"## Scope\",\n \"\",\n \"{{scope}}\",\n \"\",\n \"<!--\",\n \"This doc must own one coherent behavior surface.\",\n \"Split into another leaf doc when content introduces:\",\n \"- a distinct user or system outcome\",\n \"- a separate lifecycle or state machine\",\n \"- an unrelated rule family\",\n \"- a different external contract\",\n \"- code that should route through a different owner\",\n \"Keep README.md files as indexes only.\",\n \"-->\",\n \"\",\n \"This doc was created from the editable behavior-doc template at {{template_path}}.\",\n \"\",\n \"## Current Behavior\",\n \"\",\n \"<!-- Describe implemented behavior in present tense. Do not include desired future behavior. -->\",\n \"\",\n \"{{current_behavior}}\",\n \"\",\n \"## Core Rules\",\n \"\",\n \"<!-- Capture stable business rules, invariants, precedence rules, validation rules, and must-never constraints. Omit incidental implementation details. -->\",\n \"\",\n \"{{core_rules}}\",\n \"\",\n \"## Flows And States\",\n \"\",\n \"<!-- Use for route switches, state transitions, lifecycle stages, retries, fallbacks, and important error paths. Write 'None beyond current behavior.' when no distinct flow or state model exists. -->\",\n \"\",\n \"{{flows_and_states}}\",\n \"\",\n \"## Contracts\",\n \"\",\n \"<!-- Capture user-visible or integration contracts: CLI/API shape, inputs, outputs, diagnostics, files, events, permissions, or links to canonical contract docs. Avoid duplicating a separate canonical contract doc. -->\",\n \"\",\n \"{{contracts}}\",\n \"\",\n \"## Product Decisions\",\n \"\",\n \"<!-- Keep active decisions only. Replace stale decisions instead of appending historical logs. -->\",\n \"\",\n \"{{decision}}\",\n \"\",\n \"## Rationale\",\n \"\",\n \"<!-- Explain why the current behavior and active decisions are this way, including tradeoffs. -->\",\n \"\",\n \"{{rationale}}\",\n \"\",\n \"## Non-Goals\",\n \"\",\n \"<!-- Name adjacent behavior this doc intentionally does not own, especially tempting future expansions. -->\",\n \"\",\n \"{{non_goals}}\",\n \"\",\n \"## Maintenance Notes\",\n \"\",\n \"<!-- List related tests, routing cautions, migration notes, and common drift risks for future agents. Keep this operational, not historical. -->\",\n \"\",\n \"{{maintenance_notes}}\",\n \"\",\n ].join(\"\\n\");\n};\n\nconst renderTypedTruthDocTemplate = (\n truthKind: string,\n docType: string,\n title: string,\n sections: string[],\n): string => {\n const placeholderNameForSection = (section: string): string => {\n return section\n .replace(/^#+\\s+/u, \"\")\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n };\n\n return [\n \"---\",\n \"status: active\",\n `doc_type: ${docType}`,\n `truth_kind: ${truthKind}`,\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n \" - {{source_of_truth}}\",\n \"---\",\n \"\",\n `# ${title}`,\n \"\",\n \"## Purpose\",\n \"\",\n \"{{purpose}}\",\n \"\",\n \"## Scope\",\n \"\",\n \"{{scope}}\",\n \"\",\n ...sections.flatMap((section) => [\n section,\n \"\",\n `{{${placeholderNameForSection(section)}}}`,\n \"\",\n ]),\n \"## Product Decisions\",\n \"\",\n \"{{decision}}\",\n \"\",\n \"## Rationale\",\n \"\",\n \"{{rationale}}\",\n \"\",\n \"## Non-Goals\",\n \"\",\n \"{{non_goals}}\",\n \"\",\n \"## Maintenance Notes\",\n \"\",\n \"{{maintenance_notes}}\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderContractDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"contract\", \"contract\", \"{{title}}\", [\n \"## Contract Surface\",\n \"## Inputs\",\n \"## Outputs\",\n \"## Errors And Diagnostics\",\n \"## Compatibility Rules\",\n \"## Versioning And Migration\",\n ]);\n};\n\nexport const renderArchitectureDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"architecture\", \"architecture\", \"{{title}}\", [\n \"## System Role\",\n \"## Boundaries\",\n \"## Components\",\n \"## Data And Control Flow\",\n \"## Ownership\",\n \"## Cross-Cutting Constraints\",\n ]);\n};\n\nexport const renderWorkflowDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"workflow\", \"behavior\", \"{{title}}\", [\n \"## Triggers\",\n \"## Inputs\",\n \"## Execution Model\",\n \"## Steps\",\n \"## State, Retry, And Failure Behavior\",\n \"## Outputs\",\n ]);\n};\n\nexport const renderOperationsDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"operations\", \"behavior\", \"{{title}}\", [\n \"## Operational Surface\",\n \"## Runtime Topology\",\n \"## Configuration\",\n \"## Permissions\",\n \"## Deployment And Rollback\",\n \"## Availability And Observability\",\n ]);\n};\n\nexport const renderTestBehaviorDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"test-behavior\", \"behavior\", \"{{title}}\", [\n \"## Test Surface\",\n \"## Fixtures And Data Model\",\n \"## Execution Model\",\n \"## Assertions And Invariants\",\n \"## Isolation Rules\",\n \"## Reporting And Failure Semantics\",\n ]);\n};\n\nconst renderTemplate = (template: string, values: Record<string, string>): string => {\n return Object.entries(values).reduce((rendered, [key, value]) => {\n return rendered.split(`{{${key}}}`).join(value);\n }, template);\n};\n\nexport const renderBehaviorLeafDocTemplate = (\n config: TruthmarkConfig,\n template = renderBehaviorDocTemplateFile(),\n): string => {\n const defaultArea = config.docs.routing.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/overview.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n `${config.docs.routing.areaFilesRoot}/${defaultArea}.md`,\n );\n const today = currentDate();\n\n return renderTemplate(template, {\n area: defaultArea,\n contracts:\n \"- External contracts should link to the nearest canonical contract doc when one exists.\",\n core_rules:\n \"- Truth README files are indexes; behavior truth belongs in bounded leaf docs.\",\n current_behavior:\n \"- Document current behavior here when implementation changes make repository truth incomplete.\",\n decision: `- Decision (${today}): Truth README files are indexes; behavior truth belongs in bounded leaf docs.`,\n flows_and_states: \"- None beyond current behavior.\",\n maintenance_notes:\n \"- Update this doc when routed implementation changes alter current behavior, rules, contracts, or decisions.\",\n non_goals:\n \"- This doc is not a catch-all for unrelated repository behavior.\",\n purpose: `Describe why the default ${title.toLowerCase()} behavior surface exists and what outcome it protects.`,\n rationale:\n \"Bounded leaf docs keep agent context focused and prevent large products from accumulating unreviewable feature manuals.\",\n scope: `This bounded leaf truth doc owns the default ${title.toLowerCase()} behavior surface created by Truthmark.`,\n source_of_truth: sourceOfTruth,\n template_path: BEHAVIOR_DOC_TEMPLATE_PATH,\n title: `${title} Overview`,\n truth_kind: \"behavior\",\n });\n};\n","import type { JSONSchemaType } from \"ajv\";\n\nexport const SUPPORTED_PLATFORMS = [\n \"codex\",\n \"opencode\",\n \"claude-code\",\n \"github-copilot\",\n \"gemini-cli\",\n] as const;\n\nexport type TruthmarkPlatform = (typeof SUPPORTED_PLATFORMS)[number];\n\nexport const DEFAULT_PLATFORMS = [\n \"codex\",\n \"opencode\",\n \"claude-code\",\n \"github-copilot\",\n \"gemini-cli\",\n] as const satisfies\n readonly TruthmarkPlatform[];\n\nexport type RawDocsHierarchyConfig = {\n layout: \"hierarchical\";\n roots: Record<string, string>;\n routing: {\n root_index: string;\n area_files_root: string;\n default_area: string;\n max_delegation_depth: 1;\n };\n};\n\nexport type DocsHierarchyConfig = {\n layout: \"hierarchical\";\n roots: Record<string, string>;\n routing: {\n rootIndex: string;\n areaFilesRoot: string;\n defaultArea: string;\n maxDelegationDepth: 1;\n };\n};\n\nexport type RawTruthmarkConfig = {\n version: 1;\n platforms?: TruthmarkPlatform[];\n docs?: RawDocsHierarchyConfig;\n authority: string[];\n instruction_targets?: string[];\n frontmatter?: {\n required?: string[];\n recommended?: string[];\n };\n ignore?: string[];\n};\n\nexport type TruthmarkConfig = {\n version: 1;\n platforms: TruthmarkPlatform[];\n docs: DocsHierarchyConfig;\n authority: string[];\n instructionTargets: string[];\n frontmatter: {\n required: string[];\n recommended: string[];\n };\n ignore: string[];\n};\n\nexport const truthmarkConfigSchema: JSONSchemaType<RawTruthmarkConfig> = {\n type: \"object\",\n additionalProperties: false,\n required: [\"version\", \"authority\"],\n properties: {\n version: {\n type: \"integer\",\n const: 1,\n },\n platforms: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n enum: [...SUPPORTED_PLATFORMS],\n },\n minItems: 1,\n },\n docs: {\n type: \"object\",\n nullable: true,\n additionalProperties: false,\n required: [\"layout\", \"roots\", \"routing\"],\n properties: {\n layout: {\n type: \"string\",\n const: \"hierarchical\",\n },\n roots: {\n type: \"object\",\n required: [],\n additionalProperties: {\n type: \"string\",\n },\n },\n routing: {\n type: \"object\",\n additionalProperties: false,\n required: [\"root_index\", \"area_files_root\", \"default_area\", \"max_delegation_depth\"],\n properties: {\n root_index: {\n type: \"string\",\n },\n area_files_root: {\n type: \"string\",\n },\n default_area: {\n type: \"string\",\n },\n max_delegation_depth: {\n type: \"integer\",\n const: 1,\n },\n },\n },\n },\n },\n authority: {\n type: \"array\",\n items: {\n type: \"string\",\n },\n minItems: 1,\n },\n instruction_targets: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n },\n },\n frontmatter: {\n type: \"object\",\n nullable: true,\n additionalProperties: false,\n required: [],\n properties: {\n required: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n },\n },\n recommended: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n },\n },\n },\n },\n ignore: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n },\n },\n },\n};\n","import { DEFAULT_PLATFORMS, type TruthmarkConfig } from \"./schema.js\";\n\nexport const DEFAULT_DOCS_HIERARCHY = {\n layout: \"hierarchical\",\n roots: {\n ai: \"docs/ai\",\n standards: \"docs/standards\",\n architecture: \"docs/architecture\",\n truth: \"docs/truth\",\n },\n routing: {\n root_index: \"docs/truthmark/areas.md\",\n area_files_root: \"docs/truthmark/areas\",\n default_area: \"repository\",\n max_delegation_depth: 1,\n },\n} as const;\n\nexport const DEFAULT_AUTHORITY = [\n DEFAULT_DOCS_HIERARCHY.routing.root_index,\n `${DEFAULT_DOCS_HIERARCHY.routing.area_files_root}/**/*.md`,\n `${DEFAULT_DOCS_HIERARCHY.roots.ai}/**/*.md`,\n `${DEFAULT_DOCS_HIERARCHY.roots.standards}/**/*.md`,\n `${DEFAULT_DOCS_HIERARCHY.roots.architecture}/**/*.md`,\n `${DEFAULT_DOCS_HIERARCHY.roots.truth}/**/*.md`,\n] as const;\n\nexport const DEFAULT_INSTRUCTION_TARGETS = [\"AGENTS.md\"] as const;\n\nexport const createDefaultRawConfig = () => ({\n version: 1 as const,\n platforms: [...DEFAULT_PLATFORMS],\n docs: {\n layout: DEFAULT_DOCS_HIERARCHY.layout,\n roots: { ...DEFAULT_DOCS_HIERARCHY.roots },\n routing: { ...DEFAULT_DOCS_HIERARCHY.routing },\n },\n authority: [...DEFAULT_AUTHORITY],\n instruction_targets: [...DEFAULT_INSTRUCTION_TARGETS],\n frontmatter: {\n required: [],\n recommended: [\"status\", \"doc_type\", \"last_reviewed\", \"source_of_truth\"],\n },\n ignore: [\"node_modules/**\", \"vendor/**\", \"dist/**\", \"build/**\"],\n});\n\nexport const createDefaultConfig = (): TruthmarkConfig => ({\n version: 1,\n platforms: [...DEFAULT_PLATFORMS],\n docs: {\n layout: DEFAULT_DOCS_HIERARCHY.layout,\n roots: { ...DEFAULT_DOCS_HIERARCHY.roots },\n routing: {\n rootIndex: DEFAULT_DOCS_HIERARCHY.routing.root_index,\n areaFilesRoot: DEFAULT_DOCS_HIERARCHY.routing.area_files_root,\n defaultArea: DEFAULT_DOCS_HIERARCHY.routing.default_area,\n maxDelegationDepth: DEFAULT_DOCS_HIERARCHY.routing.max_delegation_depth,\n },\n },\n authority: [...DEFAULT_AUTHORITY],\n instructionTargets: [...DEFAULT_INSTRUCTION_TARGETS],\n frontmatter: {\n required: [],\n recommended: [\"status\", \"doc_type\", \"last_reviewed\", \"source_of_truth\"],\n },\n ignore: [\"node_modules/**\", \"vendor/**\", \"dist/**\", \"build/**\"],\n});\n","import { parse } from \"yaml\";\n\nimport type { Diagnostic } from \"../output/diagnostic.js\";\n\nexport const TRUTH_DOCUMENT_KINDS = [\n \"behavior\",\n \"contract\",\n \"architecture\",\n \"workflow\",\n \"operations\",\n \"test-behavior\",\n] as const;\n\nexport type TruthDocumentKind = (typeof TRUTH_DOCUMENT_KINDS)[number];\n\nexport type TruthDocumentEntry = {\n path: string;\n kind: TruthDocumentKind;\n kindSource: \"explicit\" | \"inferred\" | \"defaulted\";\n};\n\nexport type TruthArea = {\n id: string;\n name: string;\n key: string;\n truthDocuments: string[];\n truthDocumentEntries: TruthDocumentEntry[];\n codeSurface: string[];\n updateTruthWhen: string[];\n};\n\nexport type TruthAreaReference = {\n id: string;\n name: string;\n key: string;\n truthDocuments: string[];\n truthDocumentEntries: TruthDocumentEntry[];\n};\n\nexport type TruthAreaFileReference = {\n id: string;\n name: string;\n key: string;\n areaFiles: string[];\n codeSurface: string[];\n updateTruthWhen: string[];\n};\n\ntype ParseAreasMarkdownResult = {\n areas: TruthArea[];\n truthDocumentReferences: TruthAreaReference[];\n areaFileReferences: TruthAreaFileReference[];\n diagnostics: Diagnostic[];\n};\n\nexport type ParseAreasMarkdownOptions = {\n truthDocsRoot?: string;\n};\n\nconst slugify = (value: string): string => {\n return value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n};\n\nconst createAreaDiagnostic = (\n message: string,\n area?: string,\n severity: Diagnostic[\"severity\"] = \"error\",\n): Diagnostic => {\n return {\n category: \"area-index\",\n severity,\n message,\n area,\n };\n};\n\nconst parseListSection = (sectionLines: string[]): string[] => {\n return sectionLines\n .map((line) => line.trim())\n .filter((line) => line.startsWith(\"- \"))\n .map((line) => line.slice(2).trim().replaceAll(\"\\\\*\", \"*\"))\n .filter((line) => line.length > 0);\n};\n\nconst isTruthDocumentKind = (value: unknown): value is TruthDocumentKind => {\n return (\n typeof value === \"string\" &&\n TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind)\n );\n};\n\nexport const inferTruthDocumentKindFromPath = (\n documentPath: string,\n options: ParseAreasMarkdownOptions = {},\n): TruthDocumentKind | null => {\n const normalizedPath = documentPath.replaceAll(\"\\\\\", \"/\");\n const truthDocsRoot = options.truthDocsRoot\n ?.replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n\n if (\n (truthDocsRoot && normalizedPath.startsWith(`${truthDocsRoot}/`)) ||\n normalizedPath.startsWith(\"docs/truth/\")\n ) {\n return \"behavior\";\n }\n\n if (\n normalizedPath.startsWith(\"docs/contracts/\") ||\n normalizedPath.startsWith(\"docs/contract/\") ||\n normalizedPath.startsWith(\"docs/api/\")\n ) {\n return \"contract\";\n }\n\n if (normalizedPath.startsWith(\"docs/architecture/\")) {\n return \"architecture\";\n }\n\n if (\n normalizedPath.startsWith(\"docs/workflows/\") ||\n normalizedPath.startsWith(\"docs/workflow/\")\n ) {\n return \"workflow\";\n }\n\n if (\n normalizedPath.startsWith(\"docs/operations/\") ||\n normalizedPath.startsWith(\"docs/platform/\")\n ) {\n return \"operations\";\n }\n\n if (\n normalizedPath.startsWith(\"docs/testing/\") ||\n normalizedPath.startsWith(\"docs/tests/\")\n ) {\n return \"test-behavior\";\n }\n\n return null;\n};\n\ntype TruthDocumentsSectionResult = {\n truthDocuments: string[];\n truthDocumentEntries: TruthDocumentEntry[];\n diagnostics: Diagnostic[];\n};\n\ntype TruthDocumentsYamlFenceRange = {\n openingFenceIndex: number;\n closingFenceIndex: number | null;\n};\n\nconst findTruthDocumentsYamlFenceRange = (\n sectionLines: string[],\n): TruthDocumentsYamlFenceRange | null => {\n const trimmedLines = sectionLines.map((line) => line.trim());\n const openingFenceIndex = trimmedLines.findIndex((line) =>\n /^```(?:yaml|yml)?$/u.test(line),\n );\n\n if (openingFenceIndex === -1) {\n return null;\n }\n\n const closingFenceIndex = trimmedLines.findIndex(\n (line, index) => index > openingFenceIndex && line === \"```\",\n );\n\n return {\n openingFenceIndex,\n closingFenceIndex: closingFenceIndex === -1 ? null : closingFenceIndex,\n };\n};\n\nconst parseTruthDocumentsFromList = (\n sectionLines: string[],\n areaName: string,\n options: ParseAreasMarkdownOptions,\n): TruthDocumentsSectionResult => {\n const diagnostics: Diagnostic[] = [];\n const truthDocuments = parseListSection(sectionLines);\n const truthDocumentEntries = truthDocuments.map((documentPath) => {\n const inferredKind = inferTruthDocumentKindFromPath(documentPath, options);\n\n if (!inferredKind) {\n diagnostics.push(\n createAreaDiagnostic(\n `Truth document ${documentPath} does not match a known kind path convention; defaulting to behavior.`,\n areaName,\n \"review\",\n ),\n );\n }\n\n return {\n path: documentPath,\n kind: inferredKind ?? \"behavior\",\n kindSource: inferredKind ? (\"inferred\" as const) : (\"defaulted\" as const),\n };\n });\n\n return {\n truthDocuments,\n truthDocumentEntries,\n diagnostics,\n };\n};\n\nconst parseTruthDocumentsFromYaml = (\n sectionLines: string[],\n areaName: string,\n): TruthDocumentsSectionResult => {\n const yamlFenceRange = findTruthDocumentsYamlFenceRange(sectionLines);\n\n if (!yamlFenceRange) {\n return {\n truthDocuments: [],\n truthDocumentEntries: [],\n diagnostics: [],\n };\n }\n\n if (yamlFenceRange.closingFenceIndex === null) {\n return {\n truthDocuments: [],\n truthDocumentEntries: [],\n diagnostics: [\n createAreaDiagnostic(\n `Area ${areaName} has an unterminated fenced YAML Truth documents block.`,\n areaName,\n ),\n ],\n };\n }\n\n let parsedBlock: unknown;\n\n try {\n parsedBlock = parse(\n sectionLines\n .slice(\n yamlFenceRange.openingFenceIndex + 1,\n yamlFenceRange.closingFenceIndex,\n )\n .join(\"\\n\"),\n );\n } catch (error: unknown) {\n return {\n truthDocuments: [],\n truthDocumentEntries: [],\n diagnostics: [\n createAreaDiagnostic(\n `Area ${areaName} has invalid YAML truth document metadata: ${error instanceof Error ? error.message : String(error)}.`,\n areaName,\n ),\n ],\n };\n }\n\n const rawEntries =\n parsedBlock &&\n typeof parsedBlock === \"object\" &&\n \"truth_documents\" in parsedBlock\n ? (parsedBlock as { truth_documents?: unknown }).truth_documents\n : null;\n\n if (!Array.isArray(rawEntries)) {\n return {\n truthDocuments: [],\n truthDocumentEntries: [],\n diagnostics: [\n createAreaDiagnostic(\n `Area ${areaName} must define a truth_documents array inside the fenced YAML block.`,\n areaName,\n ),\n ],\n };\n }\n\n const diagnostics: Diagnostic[] = [];\n const truthDocumentEntries: TruthDocumentEntry[] = [];\n\n for (const rawEntry of rawEntries) {\n const path =\n rawEntry && typeof rawEntry === \"object\" && \"path\" in rawEntry\n ? (rawEntry as { path?: unknown }).path\n : null;\n const kind =\n rawEntry && typeof rawEntry === \"object\" && \"kind\" in rawEntry\n ? (rawEntry as { kind?: unknown }).kind\n : null;\n\n if (\n typeof path !== \"string\" ||\n path.trim().length === 0 ||\n !isTruthDocumentKind(kind)\n ) {\n diagnostics.push(\n createAreaDiagnostic(\n `Area ${areaName} truth_documents entries must include non-empty path and valid kind fields.`,\n areaName,\n ),\n );\n continue;\n }\n\n truthDocumentEntries.push({\n path: path.trim(),\n kind,\n kindSource: \"explicit\",\n });\n }\n\n return {\n truthDocuments: truthDocumentEntries.map((entry) => entry.path),\n truthDocumentEntries,\n diagnostics,\n };\n};\n\nconst parseTruthDocumentsSection = (\n sectionLines: string[],\n areaName: string,\n options: ParseAreasMarkdownOptions,\n): TruthDocumentsSectionResult => {\n const yamlFenceRange = findTruthDocumentsYamlFenceRange(sectionLines);\n\n if (!yamlFenceRange) {\n return parseTruthDocumentsFromList(sectionLines, areaName, options);\n }\n\n const yamlResult = parseTruthDocumentsFromYaml(sectionLines, areaName);\n\n if (\n yamlResult.diagnostics.length > 0 ||\n yamlFenceRange.closingFenceIndex === null\n ) {\n return yamlResult;\n }\n\n return yamlResult;\n};\n\nexport const parseAreasMarkdown = (\n source: string,\n options: ParseAreasMarkdownOptions = {},\n): ParseAreasMarkdownResult => {\n const lines = source.split(\"\\n\");\n const diagnostics: Diagnostic[] = [];\n const areas: TruthArea[] = [];\n const truthDocumentReferences: TruthAreaReference[] = [];\n const areaFileReferences: TruthAreaFileReference[] = [];\n let areaIndex = 0;\n\n let currentAreaName: string | null = null;\n let currentSections = new Map<string, string[]>();\n let currentSectionName: string | null = null;\n\n const flushArea = (): void => {\n if (!currentAreaName) {\n return;\n }\n\n const truthDocumentResult = parseTruthDocumentsSection(\n currentSections.get(\"Truth documents\") ?? [],\n currentAreaName,\n options,\n );\n const { truthDocuments, truthDocumentEntries } = truthDocumentResult;\n const areaFiles = parseListSection(currentSections.get(\"Area files\") ?? []);\n const codeSurface = parseListSection(\n currentSections.get(\"Code surface\") ?? [],\n );\n const updateTruthWhen = parseListSection(\n currentSections.get(\"Update truth when\") ?? [],\n );\n const areaKey = slugify(currentAreaName);\n const areaId = areaKey.length > 0 ? areaKey : `area-${areaIndex}`;\n const hasTruthDocuments = truthDocuments.length > 0;\n const hasAreaFiles = areaFiles.length > 0;\n\n areaIndex += 1;\n diagnostics.push(...truthDocumentResult.diagnostics);\n\n if (hasTruthDocuments) {\n truthDocumentReferences.push({\n id: areaId,\n name: currentAreaName,\n key: areaKey,\n truthDocuments,\n truthDocumentEntries,\n });\n }\n\n if (\n hasTruthDocuments === hasAreaFiles ||\n codeSurface.length === 0 ||\n updateTruthWhen.length === 0\n ) {\n diagnostics.push(\n createAreaDiagnostic(\n `Area ${currentAreaName} must define exactly one of Truth documents or Area files, plus Code surface and Update truth when sections.`,\n currentAreaName,\n ),\n );\n } else if (hasAreaFiles) {\n areaFileReferences.push({\n id: areaId,\n name: currentAreaName,\n key: areaKey,\n areaFiles,\n codeSurface,\n updateTruthWhen,\n });\n } else {\n areas.push({\n id: areaId,\n name: currentAreaName,\n key: areaKey,\n truthDocuments,\n truthDocumentEntries,\n codeSurface,\n updateTruthWhen,\n });\n }\n\n currentAreaName = null;\n currentSections = new Map();\n currentSectionName = null;\n };\n\n for (const line of lines) {\n const areaHeadingMatch = line.match(/^\\s{0,3}##\\s+(.*)$/u);\n\n if (areaHeadingMatch) {\n flushArea();\n currentAreaName = areaHeadingMatch[1]?.trim() ?? null;\n continue;\n }\n\n if (!currentAreaName) {\n continue;\n }\n\n if (\n /^(Truth documents|Area files|Code surface|Update truth when):$/u.test(\n line.trim(),\n )\n ) {\n currentSectionName = line.trim().slice(0, -1);\n currentSections.set(currentSectionName, []);\n continue;\n }\n\n if (currentSectionName) {\n currentSections.get(currentSectionName)?.push(line);\n }\n }\n\n flushArea();\n\n return {\n areas,\n truthDocumentReferences,\n areaFileReferences,\n diagnostics,\n };\n};\n","import { DEFAULT_DOCS_HIERARCHY } from \"../config/defaults.js\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\n\nexport const DEFAULT_TRUTH_DOCS_ROOT = DEFAULT_DOCS_HIERARCHY.roots.truth;\n\nexport const resolveTruthDocsRoot = (config: Pick<TruthmarkConfig, \"docs\">): string => {\n return config.docs.roots.truth ?? DEFAULT_TRUTH_DOCS_ROOT;\n};\n","import fs from \"node:fs/promises\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { CommandResult, DiagnosticCategory } from \"../output/diagnostic.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport { ensureRepoFile, resolveRepoPath, type FileWriteResult, writeRepoFile } from \"../fs/paths.js\";\nimport { detectHierarchyMigrationDiagnostics, scaffoldHierarchy } from \"./hierarchy.js\";\nimport { renderAgentsBlock, TRUTHMARK_BLOCK_END, TRUTHMARK_BLOCK_START } from \"../templates/agents-block.js\";\nimport { renderDefaultStandards } from \"../templates/default-standards.js\";\nimport { renderGeneratedSurfaces, type GeneratedSurface } from \"../templates/generated-surfaces.js\";\n\nconst escapeRegExp = (value: string): string => {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n};\n\nconst MANAGED_WORKFLOW_HEADING = \"## Truthmark Workflow\";\nconst LEGACY_MANAGED_LINES = [\n \"### Truth Sync\",\n \"- may read changed functional code files\",\n \"- may write truth docs only\",\n \"- must not rewrite functional code\",\n];\nconst CANONICAL_MANAGED_LINES = new Set(\n [\n ...renderAgentsBlock()\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(\n (line) =>\n line.length > 0 &&\n line !== TRUTHMARK_BLOCK_START &&\n line !== TRUTHMARK_BLOCK_END,\n ),\n ...LEGACY_MANAGED_LINES,\n ],\n);\n\nconst countCanonicalManagedLineMatches = (lines: string[]): number => {\n return lines.reduce((matchCount, line) => {\n return CANONICAL_MANAGED_LINES.has(line.trim()) ? matchCount + 1 : matchCount;\n }, 0);\n};\n\nconst isManagedChunk = (lines: string[], minimumMatches: number): boolean => {\n return countCanonicalManagedLineMatches(lines) >= minimumMatches;\n};\n\nconst removeTrailingManagedChunk = (preservedLines: string[]): void => {\n let startIndex = -1;\n\n for (let index = preservedLines.length - 1; index >= 0; index -= 1) {\n if (preservedLines[index].trim() === MANAGED_WORKFLOW_HEADING) {\n startIndex = index;\n break;\n }\n }\n\n if (startIndex === -1) {\n return;\n }\n\n const candidateChunk = preservedLines.slice(startIndex);\n const looksManaged = isManagedChunk(candidateChunk, 4);\n\n if (looksManaged) {\n preservedLines.splice(startIndex);\n }\n};\n\nconst normalizeLegacyInstructionPreamble = (content: string): string => {\n return content\n .replaceAll(\n \"Use that file as the primary repository instruction source for Codex.\",\n \"Use that file as the primary repository instruction source for this agent.\",\n )\n .replaceAll(\"Codex-specific:\", \"Agent-specific:\")\n .replaceAll(\n \"- Read `docs/README.md` for the canonical docs map.\",\n \"- Read `docs/README.md` only when choosing or updating canonical docs.\",\n )\n .replaceAll(\n \"- Use `docs/ai/agent-onboarding.md` for quick task routing.\",\n \"- Use `docs/ai/agent-onboarding.md` only when task routing is unclear or cross-area.\",\n );\n};\n\nconst upsertManagedBlock = (existingContent: string | null, block: string): string => {\n if (!existingContent || existingContent.trim().length === 0) {\n return block;\n }\n\n const normalizedExistingContent = normalizeLegacyInstructionPreamble(existingContent);\n const startMarkerPattern = new RegExp(escapeRegExp(TRUTHMARK_BLOCK_START), \"g\");\n const endMarkerPattern = new RegExp(escapeRegExp(TRUTHMARK_BLOCK_END), \"g\");\n const managedBlockPattern = new RegExp(\n `${escapeRegExp(TRUTHMARK_BLOCK_START)}[\\\\s\\\\S]*?${escapeRegExp(TRUTHMARK_BLOCK_END)}`,\n \"g\",\n );\n const completeBlocks = normalizedExistingContent.match(managedBlockPattern) ?? [];\n const startCount = normalizedExistingContent.match(startMarkerPattern)?.length ?? 0;\n const endCount = normalizedExistingContent.match(endMarkerPattern)?.length ?? 0;\n\n if (startCount === 1 && endCount === 1 && completeBlocks.length === 1) {\n return normalizedExistingContent.replace(managedBlockPattern, block);\n }\n\n const preservedLines: string[] = [];\n let insideManagedBlock = false;\n let managedLines: string[] = [];\n\n for (const line of normalizedExistingContent.split(\"\\n\")) {\n const trimmedLine = line.trim();\n\n if (trimmedLine === TRUTHMARK_BLOCK_START) {\n if (insideManagedBlock && !isManagedChunk(managedLines, 2)) {\n preservedLines.push(...managedLines);\n }\n\n insideManagedBlock = true;\n managedLines = [];\n continue;\n }\n\n if (trimmedLine === TRUTHMARK_BLOCK_END) {\n if (insideManagedBlock) {\n insideManagedBlock = false;\n managedLines = [];\n continue;\n }\n\n if (!insideManagedBlock) {\n removeTrailingManagedChunk(preservedLines);\n }\n\n continue;\n }\n\n if (insideManagedBlock) {\n managedLines.push(line);\n continue;\n }\n\n preservedLines.push(line);\n }\n\n if (insideManagedBlock && !isManagedChunk(managedLines, 2)) {\n preservedLines.push(...managedLines);\n }\n\n const preservedContent = preservedLines.join(\"\\n\").replace(/\\n{3,}/g, \"\\n\\n\").trim();\n\n if (preservedContent.length === 0) {\n return block;\n }\n\n return `${preservedContent}\\n\\n${block}`;\n};\n\nconst writeManagedAgentsFile = async (\n rootDir: string,\n path = \"AGENTS.md\",\n block: string,\n): Promise<FileWriteResult> => {\n let existingContent: string | null = null;\n\n try {\n existingContent = await fs.readFile(resolveRepoPath(rootDir, path), \"utf8\");\n } catch (error: unknown) {\n if (!(error instanceof Error) || !(\"code\" in error) || error.code !== \"ENOENT\") {\n throw error;\n }\n }\n\n return writeRepoFile(rootDir, path, upsertManagedBlock(existingContent, block));\n};\n\nconst diagnosticCategoryForPath = (\n filePath: string,\n config: TruthmarkConfig,\n): DiagnosticCategory => {\n if (filePath === \"AGENTS.md\") {\n return \"truth-sync\";\n }\n\n if (\n filePath === \"CLAUDE.md\" ||\n filePath === \"GEMINI.md\" ||\n filePath === \".github/copilot-instructions.md\" ||\n filePath.startsWith(\".github/prompts/truthmark-\") ||\n filePath.startsWith(\".github/agents/truth-\") ||\n filePath.startsWith(\".claude/agents/truth-\") ||\n filePath.startsWith(\".claude/skills/truthmark-\") ||\n filePath.startsWith(\".opencode/skills/truthmark-\") ||\n filePath.startsWith(\".opencode/agents/\") ||\n filePath.startsWith(\".codex/agents/\")\n ) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-structure/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-document/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-sync/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-preview/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-realize/\")) {\n return \"realization\";\n }\n\n if (filePath.startsWith(\".gemini/commands/truthmark/realize\")) {\n return \"realization\";\n }\n\n if (filePath.startsWith(\".gemini/commands/truthmark/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-check/\")) {\n return \"truth-sync\";\n }\n\n if (filePath === config.docs.routing.rootIndex) {\n return \"authority\";\n }\n\n return \"config\";\n};\n\nconst writePlatformFile = async (\n rootDir: string,\n file: GeneratedSurface,\n): Promise<FileWriteResult> => {\n if (file.managedBlock) {\n return writeManagedAgentsFile(rootDir, file.path, file.content);\n }\n\n return writeRepoFile(rootDir, file.path, file.content);\n};\n\nconst messageForWriteResult = (result: FileWriteResult): string => {\n switch (result.status) {\n case \"created\":\n return `Created ${result.path}.`;\n case \"updated\":\n return `Updated ${result.path}.`;\n case \"unchanged\":\n return `Unchanged ${result.path}.`;\n }\n};\n\nconst writeDiagnostics = (\n results: FileWriteResult[],\n config: TruthmarkConfig,\n): CommandResult[\"diagnostics\"] => {\n return results.map((result) => ({\n category: diagnosticCategoryForPath(result.path, config),\n severity: \"action\",\n message: messageForWriteResult(result),\n file: result.path,\n }));\n};\n\nexport const runInit = async (cwd: string): Promise<CommandResult> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const loadedConfig = await loadConfig(rootDir);\n\n if (!loadedConfig.config) {\n return {\n command: \"init\",\n summary:\n \"Truthmark init requires .truthmark/config.yml. Run truthmark config first, review the hierarchy, then run truthmark init.\",\n diagnostics: loadedConfig.diagnostics,\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n },\n };\n }\n\n const defaultStandards = renderDefaultStandards([]);\n\n const results: FileWriteResult[] = [];\n\n for (const template of defaultStandards) {\n results.push(await ensureRepoFile(rootDir, template.path, template.content));\n }\n\n const config = loadedConfig.config;\n results.push(...(await scaffoldHierarchy(rootDir, config)));\n const migrationDiagnostics = await detectHierarchyMigrationDiagnostics(rootDir, config);\n const block = renderAgentsBlock(config);\n const platformFiles = renderGeneratedSurfaces(config, block);\n\n for (const file of platformFiles) {\n results.push(await writePlatformFile(rootDir, file));\n }\n\n const changedResults = results.filter((result) => result.status !== \"unchanged\");\n\n return {\n command: \"init\",\n summary:\n changedResults.length > 0\n ? \"Initialized or updated the Truthmark repository scaffold.\"\n : \"Truthmark repository scaffold is already up to date.\",\n diagnostics: [...writeDiagnostics(results, config), ...migrationDiagnostics],\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n },\n };\n};\n","import fs from \"node:fs/promises\";\n\nimport { Ajv, type ErrorObject } from \"ajv\";\nimport { parse } from \"yaml\";\n\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { resolveRepoPath } from \"../fs/paths.js\";\nimport {\n DEFAULT_DOCS_HIERARCHY,\n DEFAULT_INSTRUCTION_TARGETS,\n} from \"./defaults.js\";\nimport {\n DEFAULT_PLATFORMS,\n type RawTruthmarkConfig,\n type TruthmarkConfig,\n truthmarkConfigSchema,\n} from \"./schema.js\";\n\nconst ajv = new Ajv({ allErrors: true });\nconst validateTruthmarkConfig = ajv.compile(truthmarkConfigSchema);\n\nexport type LoadConfigResult = {\n status: \"loaded\" | \"missing\" | \"invalid\";\n config: TruthmarkConfig | null;\n diagnostics: Diagnostic[];\n configPath: string;\n};\n\nconst toConfigDiagnostic = (message: string, file: string): Diagnostic => {\n return {\n category: \"config\",\n severity: \"error\",\n message,\n file,\n };\n};\n\nconst normalizeConfig = (rawConfig: RawTruthmarkConfig): TruthmarkConfig => {\n const rawDocs = rawConfig.docs ?? {\n layout: DEFAULT_DOCS_HIERARCHY.layout,\n roots: { ...DEFAULT_DOCS_HIERARCHY.roots },\n routing: { ...DEFAULT_DOCS_HIERARCHY.routing },\n };\n const roots: Record<string, string> = { ...DEFAULT_DOCS_HIERARCHY.roots, ...rawDocs.roots };\n\n return {\n version: rawConfig.version,\n platforms: rawConfig.platforms ?? [...DEFAULT_PLATFORMS],\n docs: {\n layout: rawDocs.layout,\n roots,\n routing: {\n rootIndex: rawDocs.routing.root_index,\n areaFilesRoot: rawDocs.routing.area_files_root,\n defaultArea: rawDocs.routing.default_area,\n maxDelegationDepth: rawDocs.routing.max_delegation_depth,\n },\n },\n authority: rawConfig.authority,\n instructionTargets: rawConfig.instruction_targets ?? [...DEFAULT_INSTRUCTION_TARGETS],\n frontmatter: {\n required: rawConfig.frontmatter?.required ?? [],\n recommended: rawConfig.frontmatter?.recommended ?? [],\n },\n ignore: rawConfig.ignore ?? [],\n };\n};\n\nexport const loadConfig = async (rootDir: string): Promise<LoadConfigResult> => {\n const configPath = \".truthmark/config.yml\";\n const absolutePath = resolveRepoPath(rootDir, configPath);\n\n let source: string;\n\n try {\n source = await fs.readFile(absolutePath, \"utf8\");\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return {\n status: \"missing\",\n config: null,\n diagnostics: [toConfigDiagnostic(\"Missing .truthmark/config.yml.\", configPath)],\n configPath,\n };\n }\n\n throw error;\n }\n\n let parsedConfig: unknown;\n\n try {\n parsedConfig = parse(source);\n } catch (error: unknown) {\n return {\n status: \"invalid\",\n config: null,\n diagnostics: [\n toConfigDiagnostic(\n `Invalid YAML: ${error instanceof Error ? error.message : String(error)}`,\n configPath,\n ),\n ],\n configPath,\n };\n }\n\n if (!validateTruthmarkConfig(parsedConfig)) {\n return {\n status: \"invalid\",\n config: null,\n diagnostics: (validateTruthmarkConfig.errors ?? []).map((error: ErrorObject) => {\n const propertyPath = error.instancePath || \"/\";\n const additionalProperty =\n error.keyword === \"additionalProperties\" &&\n error.params &&\n \"additionalProperty\" in error.params\n ? String(error.params.additionalProperty)\n : null;\n const message = additionalProperty\n ? `${propertyPath} additional property ${additionalProperty} is not allowed`\n : `${propertyPath} ${error.message ?? \"is invalid\"}`.trim();\n\n return toConfigDiagnostic(message, configPath);\n }),\n configPath,\n };\n }\n\n return {\n status: \"loaded\",\n config: normalizeConfig(parsedConfig as RawTruthmarkConfig),\n diagnostics: [],\n configPath,\n };\n};\n","import fs from \"node:fs/promises\";\nimport fg from \"fast-glob\";\nimport { DEFAULT_DOCS_HIERARCHY } from \"../config/defaults.js\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { FileWriteResult } from \"../fs/paths.js\";\nimport { ensureRepoFile, resolveRepoPath } from \"../fs/paths.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { parseAreasMarkdown } from \"../routing/areas.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\nimport {\n ARCHITECTURE_DOC_TEMPLATE_PATH,\n BEHAVIOR_DOC_TEMPLATE_PATH,\n CONTRACT_DOC_TEMPLATE_PATH,\n OPERATIONS_DOC_TEMPLATE_PATH,\n TEST_BEHAVIOR_DOC_TEMPLATE_PATH,\n WORKFLOW_DOC_TEMPLATE_PATH,\n renderChildAreaTemplate,\n renderArchitectureDocTemplateFile,\n renderBehaviorDocTemplateFile,\n renderContractDocTemplateFile,\n renderTruthDomainReadmeTemplate,\n renderTruthRootReadmeTemplate,\n renderHierarchicalAreasIndexTemplate,\n renderOperationsDocTemplateFile,\n renderBehaviorLeafDocTemplate,\n renderTestBehaviorDocTemplateFile,\n renderWorkflowDocTemplateFile,\n} from \"../templates/init-files.js\";\n\nconst KNOWN_DEFAULT_ROOTS = [\n DEFAULT_DOCS_HIERARCHY.roots.truth,\n \"docs/api\",\n DEFAULT_DOCS_HIERARCHY.roots.architecture,\n DEFAULT_DOCS_HIERARCHY.roots.standards,\n \"docs/guides\",\n] as const;\n\nconst hasMarkdownFiles = async (rootDir: string, root: string): Promise<boolean> => {\n const matches = await fg([`${root}/**/*.md`], {\n cwd: rootDir,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n return matches.length > 0;\n};\n\nconst truthRoot = resolveTruthDocsRoot;\n\nconst rootIndexReferencesChildRoute = async (\n rootDir: string,\n rootIndexPath: string,\n childRoutePath: string,\n): Promise<boolean> => {\n const rootIndexSource = await fs.readFile(resolveRepoPath(rootDir, rootIndexPath), \"utf8\");\n const parsedRootIndex = parseAreasMarkdown(rootIndexSource);\n\n return parsedRootIndex.areaFileReferences.some((areaReference) =>\n areaReference.areaFiles.includes(childRoutePath),\n );\n};\n\nconst readBehaviorDocTemplate = async (rootDir: string): Promise<string> => {\n try {\n return await fs.readFile(resolveRepoPath(rootDir, BEHAVIOR_DOC_TEMPLATE_PATH), \"utf8\");\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return renderBehaviorDocTemplateFile();\n }\n throw error;\n }\n};\n\nexport const scaffoldHierarchy = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<FileWriteResult[]> => {\n const results: FileWriteResult[] = [];\n const truthDocsRoot = truthRoot(config);\n const truthDomainRoot = `${truthDocsRoot}/${config.docs.routing.defaultArea}`;\n const childRoutePath = `${config.docs.routing.areaFilesRoot}/${config.docs.routing.defaultArea}.md`;\n\n results.push(\n await ensureRepoFile(\n rootDir,\n config.docs.routing.rootIndex,\n renderHierarchicalAreasIndexTemplate(config),\n ),\n );\n if (\n await rootIndexReferencesChildRoute(rootDir, config.docs.routing.rootIndex, childRoutePath)\n ) {\n results.push(await ensureRepoFile(rootDir, childRoutePath, renderChildAreaTemplate(config)));\n }\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDocsRoot}/README.md`,\n renderTruthRootReadmeTemplate(config),\n ),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDomainRoot}/README.md`,\n renderTruthDomainReadmeTemplate(config),\n ),\n );\n results.push(\n await ensureRepoFile(rootDir, BEHAVIOR_DOC_TEMPLATE_PATH, renderBehaviorDocTemplateFile()),\n );\n results.push(\n await ensureRepoFile(rootDir, CONTRACT_DOC_TEMPLATE_PATH, renderContractDocTemplateFile()),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n ARCHITECTURE_DOC_TEMPLATE_PATH,\n renderArchitectureDocTemplateFile(),\n ),\n );\n results.push(\n await ensureRepoFile(rootDir, WORKFLOW_DOC_TEMPLATE_PATH, renderWorkflowDocTemplateFile()),\n );\n results.push(\n await ensureRepoFile(rootDir, OPERATIONS_DOC_TEMPLATE_PATH, renderOperationsDocTemplateFile()),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n TEST_BEHAVIOR_DOC_TEMPLATE_PATH,\n renderTestBehaviorDocTemplateFile(),\n ),\n );\n const behaviorDocTemplate = await readBehaviorDocTemplate(rootDir);\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDomainRoot}/overview.md`,\n renderBehaviorLeafDocTemplate(config, behaviorDocTemplate),\n ),\n );\n return results;\n};\n\nexport const detectHierarchyMigrationDiagnostics = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<Diagnostic[]> => {\n const configuredRoots = new Set(Object.values(config.docs.roots));\n const diagnostics: Diagnostic[] = [];\n for (const defaultRoot of KNOWN_DEFAULT_ROOTS) {\n if (configuredRoots.has(defaultRoot)) {\n continue;\n }\n if (await hasMarkdownFiles(rootDir, defaultRoot)) {\n diagnostics.push({\n category: \"config\",\n severity: \"review\",\n message: `Configured hierarchy no longer includes ${defaultRoot}, but markdown still exists there. Perform manual migration before relying on the new hierarchy.`,\n file: \".truthmark/config.yml\",\n });\n }\n }\n return diagnostics;\n};\n","export type ClaimEvidenceResult = \"supported\" | \"narrowed\" | \"removed\" | \"blocked\";\n\nexport type ClaimEvidenceItem = {\n claim: string;\n evidence: string[];\n result: ClaimEvidenceResult;\n};\n\nexport type AuditEvidenceConfidence = \"high\" | \"medium\" | \"low\";\n\nexport type AuditEvidenceItem = {\n finding: string;\n evidence: string[];\n suggestedFix: string;\n confidence: AuditEvidenceConfidence;\n};\n\nexport const renderClaimEvidenceCheckedSection = (\n items: ClaimEvidenceItem[],\n): string => {\n return [\n \"Evidence checked:\",\n ...items.map((item) => {\n return [\n `- Claim: ${item.claim}`,\n ` Evidence: ${item.evidence.join(\" / \")}`,\n ` Result: ${item.result}`,\n ].join(\"\\n\");\n }),\n ].join(\"\\n\");\n};\n\nexport const renderAuditEvidenceCheckedSection = (\n items: AuditEvidenceItem[],\n): string => {\n return [\n \"Evidence checked:\",\n ...items.map((item) => {\n return [\n `- Finding: ${item.finding}`,\n ` Evidence: ${item.evidence.join(\" / \")}`,\n ` Suggested fix: ${item.suggestedFix}`,\n ` Confidence: ${item.confidence}`,\n ].join(\"\\n\");\n }),\n ].join(\"\\n\");\n};\n","import { createDefaultConfig } from \"../config/defaults.js\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\n\nexport { resolveTruthDocsRoot } from \"../truth/docs.js\";\nexport type {\n AuditEvidenceConfidence,\n AuditEvidenceItem,\n ClaimEvidenceItem,\n ClaimEvidenceResult,\n} from \"../truth/evidence.js\";\nexport {\n renderAuditEvidenceCheckedSection,\n renderClaimEvidenceCheckedSection,\n} from \"../truth/evidence.js\";\n\nexport const DECISION_TRUTH_INSTRUCTIONS = [\n \"Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed.\",\n \"Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail.\",\n \"Update Product Decisions and Rationale when a decision changes behavior.\",\n].join(\"\\n\");\n\nexport const EVIDENCE_AUTHORITY_INSTRUCTIONS = [\n \"Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority.\",\n \"Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries.\",\n].join(\"\\n\");\n\nexport const REPOSITORY_INTELLIGENCE_INSTRUCTIONS = [\n \"Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available.\",\n \"They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries.\",\n \"If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated.\",\n].join(\"\\n\");\n\nexport const FEATURE_DOC_TEMPLATE_INSTRUCTIONS = [\n \"When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/<kind>-doc.md` template.\",\n \"Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior.\",\n \"Align existing docs to that template while preserving accurate authored content.\",\n \"If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section.\",\n \"Teams may edit the template files under docs/templates/ to define their local truth-doc standards.\",\n].join(\"\\n\");\n\nexport const renderTruthDocOwnershipGateSection = (\n subject: string,\n outcome: string,\n): string => {\n return [\n \"Truth-doc ownership gate:\",\n `- before editing or relying on ${subject}, verify each target/source truth doc is a bounded owner for the behavior`,\n \"- if a target/source doc mixes independent owners, spans unrelated behaviors, acts as an index, or needs cross-owner edits, do not patch or in-place repair it\",\n `- ${outcome}`,\n \"- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable\",\n ].join(\"\\n\");\n};\n\nexport const TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS = [\n \"Product Decisions/Rationale preservation gate:\",\n \"- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc\",\n \"- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index\",\n \"- remove or narrow a decision or rationale only when checkout evidence shows it is stale or unsupported, and report the exact claim, evidence, and result\",\n \"- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing\",\n \"- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked\",\n].join(\"\\n\");\n\nexport const renderTruthDocRestructureGateSection = (scope: string): string => {\n return [\n \"Truth-doc shape repair gate:\",\n `- ${scope}`,\n \"- repair shape in place only after the ownership gate confirms the doc is the right bounded owner\",\n \"- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work\",\n \"- repair shape when a narrow edit would make truth worse: missing template sections, stale evidence conflicts, cross-section updates within one owner, or wrong frontmatter/source/headings\",\n \"- preserve supported claims; remove, narrow, or block unsupported or stale claims\",\n \"- report docs restructured and why a narrow edit was not sufficient\",\n ].join(\"\\n\");\n};\n\nexport const ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS = [\n \"Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership.\",\n \"Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries.\",\n].join(\"\\n\");\n\nexport const renderRouteFirstEvidenceGateSection = (\n subject: string,\n noImpactedDocOutcome: string,\n): string => {\n return [\n \"Evidence Gate:\",\n `- route-first: map ${subject} to bounded route owners and primary canonical docs`,\n \"- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale\",\n \"- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions\",\n \"- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts\",\n \"- remove, narrow, or block unsupported claims\",\n `- ${noImpactedDocOutcome}`,\n ].join(\"\\n\");\n};\n\nexport const renderTopologyEvidenceGateSection = (): string => {\n return [\n \"Evidence Gate:\",\n \"- apply the Evidence Gate before finishing when Truth Structure writes routed docs, ownership claims, Product Decisions, or Rationale\",\n \"- support ownership/behavior claims with topology or primary checkout evidence from layout, implementation boundaries, docs, config, route files, tests, templates, schemas, or contracts\",\n \"- tests/examples/canonical docs corroborate; remove, narrow, or block unsupported claims\",\n ].join(\"\\n\");\n};\n\nexport const renderAuditEvidenceGateSection = (): string => {\n return [\n \"Evidence Gate:\",\n \"- support each finding and suggested fix with evidence from config, route files, canonical docs, implementation, templates, or tests\",\n \"- canonical docs are context, not sole proof when implementation conflicts\",\n \"- remove unsupported findings or mark open questions; validate changed claims if you edit docs\",\n ].join(\"\\n\");\n};\n\nexport const renderCodexSubagentModeSection = (\n agents: string[],\n parentRule: string,\n writeAgents: string[] = [],\n): string => {\n const writeAgentLines =\n writeAgents.length > 0\n ? [\n `- dispatch write-capable project agents only with explicit write leases: ${writeAgents.join(\", \")}`,\n \"- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields\",\n \"- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes\",\n \"- parent must inspect the actual checkout diff against each lease before accepting a worker report\",\n ]\n : [];\n const readOnlyScope = writeAgents.length > 0 ? \"for verification\" : \"only\";\n const readOnlyWorkerLabel = writeAgents.length > 0 ? \"read-only workers\" : \"workers\";\n\n return [\n \"Codex subagent mode:\",\n \"- use automatically when this workflow runs in Codex and the parent agent chooses bounded subagent fan-out\",\n `- dispatch read-only project agents ${readOnlyScope}: ${agents.join(\", \")}`,\n `- ${readOnlyWorkerLabel} inspect checkout evidence directly, return structured findings, and must not edit files`,\n `- parent supplies bounded evidence shards; ${readOnlyWorkerLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`,\n ...writeAgentLines,\n `- ${parentRule}`,\n ].join(\"\\n\");\n};\n\nexport const renderOpenCodeSubagentModeSection = (\n agents: string[],\n parentRule: string,\n writeAgents: string[] = [],\n): string => {\n const mentions = agents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeMentions = writeAgents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeAgentLines =\n writeMentions.length > 0\n ? [\n `- dispatch write-capable project subagents only with explicit write leases: ${writeMentions.join(\", \")}`,\n \"- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields\",\n \"- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes\",\n \"- parent must inspect the actual checkout diff against each lease before accepting a worker report\",\n ]\n : [];\n const readOnlyScope = writeAgents.length > 0 ? \"for verification\" : \"only\";\n const readOnlyWorkerLabel = writeAgents.length > 0 ? \"read-only workers\" : \"workers\";\n\n return [\n \"OpenCode subagent mode:\",\n \"- use automatically when this workflow runs in OpenCode and the parent agent chooses bounded subagent fan-out\",\n `- dispatch read-only project subagents ${readOnlyScope}: ${mentions.join(\", \")}`,\n `- ${readOnlyWorkerLabel} inspect checkout evidence directly, return structured findings, and must not edit files`,\n `- parent supplies bounded evidence shards; ${readOnlyWorkerLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`,\n ...writeAgentLines,\n `- ${parentRule}`,\n ].join(\"\\n\");\n};\n\nexport const renderClaudeSubagentModeSection = (\n agents: string[],\n parentRule: string,\n writeAgents: string[] = [],\n): string => {\n const mentions = agents.map((agent) => `${agent.replace(/_/gu, \"-\")} subagent`);\n const writeMentions = writeAgents.map(\n (agent) => `${agent.replace(/_/gu, \"-\")} subagent`,\n );\n const writeAgentLines =\n writeMentions.length > 0\n ? [\n `- dispatch write-capable project subagents only with explicit write leases: ${writeMentions.join(\", \")}`,\n \"- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields\",\n \"- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes\",\n \"- parent must inspect the actual checkout diff against each lease before accepting a worker report\",\n ]\n : [];\n const readOnlyScope = writeAgents.length > 0 ? \"for verification\" : \"only\";\n const readOnlySubagentLabel =\n writeAgents.length > 0 ? \"read-only subagents\" : \"subagents\";\n\n return [\n \"Claude Code subagent mode:\",\n \"- use automatically when this workflow runs in Claude Code and the parent agent chooses bounded subagent fan-out\",\n `- dispatch read-only project subagents ${readOnlyScope}: ${mentions.join(\", \")}`,\n `- ${readOnlySubagentLabel} inspect checkout evidence directly, return structured findings, and must not edit files`,\n `- parent supplies bounded evidence shards; ${readOnlySubagentLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`,\n ...writeAgentLines,\n `- ${parentRule}`,\n ].join(\"\\n\");\n};\n\nexport const renderCopilotCustomAgentModeSection = (\n agents: string[],\n parentRule: string,\n writeAgents: string[] = [],\n): string => {\n const mentions = agents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeMentions = writeAgents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeAgentLines =\n writeMentions.length > 0\n ? [\n `- dispatch write-capable project custom agents only with explicit write leases: ${writeMentions.join(\", \")}`,\n \"- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields\",\n \"- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes\",\n \"- parent must inspect the actual checkout diff against each lease before accepting a worker report\",\n ]\n : [];\n const readOnlyScope = writeAgents.length > 0 ? \"for verification\" : \"only\";\n const readOnlyCustomAgentLabel =\n writeAgents.length > 0 ? \"read-only custom agents\" : \"custom agents\";\n\n return [\n \"Copilot custom-agent mode:\",\n \"- use automatically when this workflow runs in Copilot and the parent agent chooses bounded custom-agent fan-out\",\n `- dispatch read-only project custom agents ${readOnlyScope}: ${mentions.join(\", \")}`,\n `- ${readOnlyCustomAgentLabel} inspect checkout evidence directly, return structured findings, and must not edit files`,\n `- parent supplies bounded evidence shards; ${readOnlyCustomAgentLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`,\n ...writeAgentLines,\n `- ${parentRule}`,\n ].join(\"\\n\");\n};\n\nexport const defaultAgentConfig = (): TruthmarkConfig => {\n return createDefaultConfig();\n};\n\nexport const renderHierarchySummary = (config: TruthmarkConfig): string => {\n const truthRoot = resolveTruthDocsRoot(config);\n\n return [\n \"Truthmark hierarchy:\",\n \"- Config: .truthmark/config.yml\",\n `- Root route index: ${config.docs.routing.rootIndex}`,\n `- Area route files: ${config.docs.routing.areaFilesRoot}/**/*.md`,\n `- Truth docs: ${truthRoot}/**/*.md`,\n ].join(\"\\n\");\n};\n","import fs from \"node:fs\";\n\ntype TruthmarkPackageJson = {\n version: string;\n};\n\nconst packageJson = JSON.parse(\n fs.readFileSync(new URL(\"../package.json\", import.meta.url), \"utf8\"),\n) as TruthmarkPackageJson;\n\nexport const TRUTHMARK_VERSION = packageJson.version;\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport { defaultAgentConfig, resolveTruthDocsRoot } from \"../agents/shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\n\nexport const TRUTHMARK_BLOCK_START = \"<!-- truthmark:start -->\";\nexport const TRUTHMARK_BLOCK_END = \"<!-- truthmark:end -->\";\n\nexport const renderInstructionPreamble = (): string => {\n return [\n \"Follow `docs/ai/repo-rules.md` as the primary repository instruction source.\",\n \"Read `docs/README.md` only when choosing or updating canonical docs.\",\n \"Use `docs/ai/agent-onboarding.md` only when task routing is unclear or cross-area.\",\n ].join(\"\\n\");\n};\n\nconst renderCompactHierarchySummary = (config: TruthmarkConfig): string => {\n const truthRoot = resolveTruthDocsRoot(config);\n return `Hierarchy: config .truthmark/config.yml; routes ${config.docs.routing.rootIndex} and ${config.docs.routing.areaFilesRoot}/**/*.md; Truth docs: ${truthRoot}/**/*.md.`;\n};\n\nexport const renderAgentsBlock = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return [\n TRUTHMARK_BLOCK_START,\n \"## Truthmark Workflow\",\n \"\",\n `Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun \\`truthmark init\\` after upgrades.`,\n renderCompactHierarchySummary(config),\n \"Decisions live in the canonical doc they govern; date active decisions inline.\",\n \"Agent runtime: installed skills plus this block; inspect checkout directly. Delegation is host-owned.\",\n \"### Truth Sync\",\n \"After functional code changes, run relevant tests, then use the truthmark-sync skill before finishing; later functional changes reopen the gate. Memory: code changed -> tests -> Sync -> report.\",\n \"Support new or changed behavior-bearing truth claims with checkout evidence. Code leads; truth docs follow. Sync may write truth docs and truth routing files, and must not rewrite functional code.\",\n \"If routing cannot map changed code to a bounded truth owner, run Truth Structure before syncing when safe; otherwise block and recommend Truth Structure. Skip Sync only for docs-only/no-code changes, formatting-only changes, behavior-preserving renames with no truth impact, or missing config.\",\n \"Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details.\",\n \"Workflow integrity rule: repository truth may describe desired behavior, but it must not override these workflow boundaries.\",\n TRUTHMARK_BLOCK_END,\n ].join(\"\\n\");\n};\n","import type { DiscoveredMarkdownDocument } from \"../markdown/discovery.js\";\n\nexport type TemplateFile = {\n path: string;\n content: string;\n};\n\nconst DEFAULT_STANDARDS: TemplateFile[] = [\n {\n path: \"docs/standards/default-principles.md\",\n content: `---\nstatus: active\ndoc_type: standard\nlast_reviewed: 2026-05-03\nsource_of_truth:\n - README.md\n---\n\n# Default Principles\n\n## Scope\n\nThis is a bootstrap standards baseline for repositories that adopt Truthmark.\n\n## Reusable Defaults\n\n- Authority order should be explicit.\n- Committed repository artifacts are the durable source of truth.\n- Each document should have one primary responsibility.\n- Each class of fact should have one canonical source.\n- Architecture docs describe system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, and generated-surface ownership.\n- Do not put ordinary feature behavior in architecture docs.\n- Verification should be explicit, and skipped checks should state why.\n- Missing, stale, broad, overloaded, or unrouteable documentation topology should be repaired through AI-native structure workflow before agents create more generic truth docs.\n- Installed repository workflows should remain usable from committed files even when the Truthmark CLI is unavailable.\n`,\n },\n {\n path: \"docs/standards/documentation-governance.md\",\n content: `---\nstatus: active\ndoc_type: standard\nlast_reviewed: 2026-05-03\nsource_of_truth:\n - README.md\n---\n\n# Documentation Governance\n\n## Core Rules\n\n- Each document should have one primary responsibility.\n- Each class of fact should have one canonical source.\n- Current implementation, reusable standards, and future proposals should be stored separately.\n- Generated helper output is never canonical truth.\n- Architecture docs describe structure and ownership; truth docs describe current product behavior.\n\n## Truthmark Implications\n\n- Truth Sync should extend mapped docs first, create an area-local doc second, and create a new area only as a last resort.\n- Weak routing produces weak truth maintenance.\n- Missing, stale, broad, overloaded, or unrouteable routing should trigger Truth Structure before more generic truth docs are created.\n`,\n },\n];\n\nexport const renderDefaultStandards = (\n documents: DiscoveredMarkdownDocument[],\n): TemplateFile[] => {\n const existingPaths = new Set(documents.map((document) => document.path));\n\n return DEFAULT_STANDARDS.filter((template) => !existingPaths.has(template.path));\n};\n","export type TruthmarkWorkflowId =\n | \"truthmark-sync\"\n | \"truthmark-structure\"\n | \"truthmark-document\"\n | \"truthmark-preview\"\n | \"truthmark-realize\"\n | \"truthmark-check\";\n\nexport type TruthmarkReadOnlySubagentId =\n | \"truth_route_auditor\"\n | \"truth_claim_verifier\"\n | \"truth_doc_reviewer\";\nexport type TruthmarkWriteSubagentId = \"truth_doc_writer\";\nexport type TruthmarkSubagentId =\n | TruthmarkReadOnlySubagentId\n | TruthmarkWriteSubagentId;\n\nexport type TruthmarkWorkflowManifestEntry = {\n id: TruthmarkWorkflowId;\n displayName: string;\n description: string;\n shortDescription: string;\n defaultPrompt: string;\n allowImplicitInvocation: boolean;\n positiveTriggers: string[];\n negativeTriggers: string[];\n forbiddenAdjacency: string[];\n requiredGates: string[];\n allowedWrites: string[];\n reportSections: string[];\n subagents?: TruthmarkReadOnlySubagentId[];\n writeSubagents?: TruthmarkWriteSubagentId[];\n};\n\nexport const TRUTHMARK_WORKFLOW_MANIFEST = {\n \"truthmark-sync\": {\n id: \"truthmark-sync\",\n displayName: \"Truthmark Sync\",\n description:\n \"Use automatically at finish-time after functional code changes, or explicit /truthmark-sync, $truthmark-sync, or /truthmark:sync. Skip docs-only, formatting-only, behavior-preserving renames, missing config, and no-code changes. Not for doc-first realization or manual topology design.\",\n shortDescription:\n \"Sync truth docs from functional code changes; skip docs-only/no-code changes\",\n defaultPrompt:\n \"Use $truthmark-sync after functional code changes; skip docs-only/no-code changes.\",\n allowImplicitInvocation: true,\n positiveTriggers: [\n \"functional code changed since last successful Truth Sync\",\n \"explicit /truthmark-sync, $truthmark-sync, or /truthmark:sync\",\n ],\n negativeTriggers: [\n \"documentation-only change\",\n \"formatting-only change\",\n \"behavior-preserving rename\",\n \"missing Truthmark config\",\n \"no functional code changes\",\n ],\n forbiddenAdjacency: [\n \"doc-first implementation belongs to Truth Realize\",\n \"manual topology design belongs to Truth Structure\",\n ],\n requiredGates: [\n \"topology quality\",\n \"truth-doc ownership\",\n \"Product Decisions/Rationale preservation\",\n \"truth-doc shape repair when restructuring\",\n \"Evidence Gate\",\n ],\n allowedWrites: [\"canonical truth docs\", \"truth routing files\"],\n reportSections: [\n \"Changed code reviewed\",\n \"Ownership reviewed\",\n \"Structure required\",\n \"Truth docs updated\",\n \"Truth docs split\",\n \"Evidence checked\",\n \"Notes\",\n ],\n subagents: [\"truth_route_auditor\", \"truth_claim_verifier\"],\n writeSubagents: [\"truth_doc_writer\"],\n },\n \"truthmark-structure\": {\n id: \"truthmark-structure\",\n displayName: \"Truthmark Structure\",\n description:\n \"Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, needs split/repair, or needs new area setup. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code.\",\n shortDescription: \"Design, repair, or set up Truthmark area routing\",\n defaultPrompt:\n \"Use $truthmark-structure to design, repair, or set up Truthmark area routing.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"split broad repository routing into bounded areas\",\n \"repair missing, stale, catch-all, unrouteable, or mixed-owner truth ownership\",\n \"onboard a new code area into Truthmark routing\",\n \"new package, controller, domain, or product area lacks bounded truth ownership\",\n ],\n negativeTriggers: [\n \"document existing implemented behavior\",\n \"sync truth after a functional code diff\",\n \"realize truth docs into code\",\n ],\n forbiddenAdjacency: [\n \"must not implement functional code\",\n \"must not patch mixed-owner docs as shape repair\",\n ],\n requiredGates: [\n \"truth-doc ownership\",\n \"Product Decisions/Rationale preservation\",\n \"truth-doc shape repair when restructuring\",\n \"Evidence Gate\",\n ],\n allowedWrites: [\"truth routing files\", \"starter canonical truth docs\"],\n reportSections: [\n \"Topology reviewed\",\n \"Areas reviewed\",\n \"Routing updated\",\n \"Initial truth boundary\",\n \"Truth docs created\",\n \"Truth docs split\",\n \"Truth docs restructured\",\n \"Evidence checked\",\n \"Topology decisions\",\n \"Notes\",\n ],\n subagents: [\"truth_route_auditor\"],\n },\n \"truthmark-document\": {\n id: \"truthmark-document\",\n displayName: \"Truthmark Document\",\n description:\n \"Use when the user asks to document existing implemented behavior, or Sync, Check, or Structure finds implemented behavior missing canonical truth. Not for functional-code changes, doc-first implementation, or topology repair that needs Structure.\",\n shortDescription: \"Document existing implemented behavior\",\n defaultPrompt:\n \"Use $truthmark-document to document existing implemented behavior.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"document existing implemented behavior\",\n \"handoff finds implemented behavior missing canonical truth\",\n ],\n negativeTriggers: [\n \"functional-code change that requires Truth Sync\",\n \"doc-first implementation\",\n \"topology repair that needs Truth Structure\",\n ],\n forbiddenAdjacency: [\n \"must not edit functional code\",\n \"must not repair mixed-owner docs in place\",\n ],\n requiredGates: [\n \"truth-doc ownership\",\n \"Product Decisions/Rationale preservation\",\n \"Evidence Gate\",\n \"truth-doc shape repair when restructuring\",\n ],\n allowedWrites: [\"canonical truth docs\", \"truth routing files\"],\n reportSections: [\n \"Implementation reviewed\",\n \"Ownership reviewed\",\n \"Structure required\",\n \"Truth docs created\",\n \"Truth docs updated\",\n \"Truth docs restructured\",\n \"Routing updated\",\n \"Evidence checked\",\n \"Notes\",\n ],\n subagents: [\"truth_route_auditor\", \"truth_claim_verifier\"],\n writeSubagents: [\"truth_doc_writer\"],\n },\n \"truthmark-realize\": {\n id: \"truthmark-realize\",\n displayName: \"Truthmark Realize\",\n description:\n \"Use when the user explicitly asks to realize Truthmark truth docs into code, including /truthmark-realize, $truthmark-realize, or /truthmark:realize. Not for syncing docs after code changes, documenting existing code, topology repair, or truth audits.\",\n shortDescription: \"Realize truth docs into code\",\n defaultPrompt: \"Use $truthmark-realize to realize the updated truth docs into code.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\"explicitly realize truth docs into functional code\"],\n negativeTriggers: [\n \"sync docs after code changes\",\n \"document existing implemented behavior\",\n \"topology repair\",\n \"truth audit\",\n ],\n forbiddenAdjacency: [\n \"must not edit truth docs\",\n \"must not edit truth routing\",\n ],\n requiredGates: [\"truth-doc ownership\"],\n allowedWrites: [\"functional code\"],\n reportSections: [\"Truth docs used\", \"Code updated\", \"Verification\"],\n },\n \"truthmark-preview\": {\n id: \"truthmark-preview\",\n displayName: \"Truthmark Preview\",\n description:\n \"Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check.\",\n shortDescription:\n \"Preview likely workflow routing before edits; read-only and explicit\",\n defaultPrompt:\n \"Use $truthmark-preview to preview likely Truthmark routing before edits.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"explicit request to preview Truthmark workflow routing before edits\",\n \"explicit request for likely route owner, target docs, expected writes, or subagent plan\",\n ],\n negativeTriggers: [\n \"normal validation or final correctness audit\",\n \"automatic preflight or finish-time gate\",\n \"request to mutate truth docs, routing, or code\",\n ],\n forbiddenAdjacency: [\n \"must not replace Truth Check\",\n \"must not run Truth Sync automatically\",\n \"must not authorize later edits or issue write leases\",\n ],\n requiredGates: [\n \"read-only boundary\",\n \"intended-not-authorized handoff\",\n \"blocking ambiguity disclosure\",\n ],\n allowedWrites: [\"none by default\"],\n reportSections: [\n \"Requested outcome\",\n \"Likely workflow\",\n \"Why this workflow\",\n \"Likely route owner\",\n \"Expected write classes\",\n \"Expected target files\",\n \"Suggested subagent use\",\n \"Blocking ambiguity\",\n \"Handoff\",\n ],\n subagents: [\"truth_route_auditor\"],\n },\n \"truthmark-check\": {\n id: \"truthmark-check\",\n displayName: \"Truthmark Check\",\n description:\n \"Use when the user asks to audit repository truth health, routing, ownership, or canonical docs. Not for normal lint/test/typecheck/code-review verification, finish-time Sync, or silently rewriting docs.\",\n shortDescription: \"Audit repository truth health\",\n defaultPrompt: \"Use $truthmark-check to audit repository truth health.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"audit repository truth health\",\n \"audit routing, ownership, or canonical docs\",\n ],\n negativeTriggers: [\n \"normal lint/test/typecheck verification\",\n \"code review\",\n \"finish-time Truth Sync\",\n ],\n forbiddenAdjacency: [\n \"must not replace ordinary verification\",\n \"must not silently rewrite docs\",\n ],\n requiredGates: [\"audit Evidence Gate\"],\n allowedWrites: [\"none by default\"],\n reportSections: [\n \"Files reviewed\",\n \"Issues found\",\n \"Fixes suggested\",\n \"Evidence checked\",\n \"Validation\",\n ],\n subagents: [\n \"truth_route_auditor\",\n \"truth_claim_verifier\",\n \"truth_doc_reviewer\",\n ],\n },\n} satisfies Record<TruthmarkWorkflowId, TruthmarkWorkflowManifestEntry>;\n\nexport const TRUTHMARK_WORKFLOW_IDS = Object.keys(\n TRUTHMARK_WORKFLOW_MANIFEST,\n) as TruthmarkWorkflowId[];\n\nexport const getTruthmarkWorkflow = (\n id: TruthmarkWorkflowId,\n): TruthmarkWorkflowManifestEntry => {\n return TRUTHMARK_WORKFLOW_MANIFEST[id];\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n renderAuditEvidenceCheckedSection,\n renderAuditEvidenceGateSection,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n defaultAgentConfig,\n renderHierarchySummary,\n} from \"./shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const TRUTH_CHECK_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-check; Codex /truthmark-check or $truthmark-check; Claude Code /truthmark-check; GitHub Copilot /truthmark-check; Gemini CLI /truthmark:check.\";\n\nexport const renderTruthCheckReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const rootRouteIndex = config.docs.routing.rootIndex;\n return `Truth Check: completed\n\nFiles reviewed:\n- ${rootRouteIndex}\n\nIssues found:\n- none\n\nFixes suggested:\n- none\n\n${renderAuditEvidenceCheckedSection([\n {\n finding: \"The root route index is present and maps repository truth owners.\",\n evidence: [\".truthmark/config.yml:1\", `${rootRouteIndex}:1`],\n suggestedFix: \"none\",\n confidence: \"high\",\n },\n ])}\n\nValidation:\n- truthmark check`;\n};\n\nexport const renderTruthCheckSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCodexSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n includeOpenCodeSubagentMode?: boolean;\n } = {},\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-check\");\n const claudeSubagentMode = options.includeClaudeSubagentMode\n ? `${renderClaudeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns the final Truth Check report\",\n )}\\n\\n`\n : \"\";\n const codexSubagentMode = options.includeCodexSubagentMode\n ? `${renderCodexSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns the final Truth Check report\",\n )}\\n\\n`\n : \"\";\n const copilotCustomAgentMode = options.includeCopilotCustomAgentMode\n ? `${renderCopilotCustomAgentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns the final Truth Check report\",\n )}\\n\\n`\n : \"\";\n const openCodeSubagentMode = options.includeOpenCodeSubagentMode\n ? `${renderOpenCodeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns the final Truth Check report\",\n )}\\n\\n`\n : \"\";\n const subagentMode = `${claudeSubagentMode}${codexSubagentMode}${copilotCustomAgentMode}${openCodeSubagentMode}`;\n\n return `---\nname: truthmark-check\ndescription: ${workflow.description}\nargument-hint: Optional area, doc path, or audit focus\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\n# Truthmark Check\n\nUse this skill to audit repository truth health.\n\nInvocations: ${TRUTH_CHECK_EXPLICIT_INVOCATIONS}\n\nTruth Check is agent-led:\n\n- inspect .truthmark/config.yml, ${config.docs.routing.rootIndex}, canonical docs, and relevant implementation directly\n- ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n- inspect the configured root route index at ${config.docs.routing.rootIndex} and relevant child route files under ${config.docs.routing.areaFilesRoot}/\n- check that current docs describe current code rather than historical plans\n- check that ${config.docs.routing.rootIndex} routes code surfaces to canonical truth docs\n- check for broad, catch-all, index-like, or mixed-owner truth docs and report them as topology issues requiring Truth Structure\n- check that canonical behavior docs keep active Product Decisions and Rationale sections\n- optionally run truthmark check when local tooling is available\n- must not require the truthmark binary; direct inspection is always valid\n- report issues and suggested fixes without silently rewriting unrelated files\n- if follow-up docs edits are needed for mixed-owner docs, run or recommend Truth Structure before editing\n${renderAuditEvidenceGateSection()}\n\n${subagentMode}${renderHierarchySummary(config)}\n${DECISION_TRUTH_INSTRUCTIONS}\n\nReport completion in this shape:\n\n${renderMarkdownExample(renderTruthCheckReportExample(config))}`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS,\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n FEATURE_DOC_TEMPLATE_INSTRUCTIONS,\n REPOSITORY_INTELLIGENCE_INSTRUCTIONS,\n TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n renderClaimEvidenceCheckedSection,\n renderRouteFirstEvidenceGateSection,\n renderHierarchySummary,\n renderTruthDocOwnershipGateSection,\n renderTruthDocRestructureGateSection,\n resolveTruthDocsRoot,\n} from \"./shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-document; Codex /truthmark-document or $truthmark-document; Claude Code /truthmark-document; GitHub Copilot /truthmark-document; Gemini CLI /truthmark:document.\";\n\nexport const renderTruthDocumentReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n\n return `Truth Document: completed\n\nImplementation reviewed:\n- src/routing/area-resolver.ts\n\nTruth docs created:\n- ${truthDocsRoot}/contracts.md\n\nTruth docs updated:\n- ${truthDocsRoot}/check-diagnostics.md\n\nTruth docs restructured:\n- ${truthDocsRoot}/check-diagnostics.md\n\nRouting updated:\n- ${config.docs.routing.rootIndex}\n\n${renderClaimEvidenceCheckedSection([\n {\n claim: \"Route resolution behavior is documented in the contracts truth doc.\",\n evidence: [\n \"src/routing/area-resolver.ts:14\",\n `${config.docs.routing.rootIndex}:9`,\n ],\n result: \"supported\",\n },\n ])}\n\nNotes:\n- Documented routing and behavior from route handlers and tests.`;\n};\n\nexport const renderTruthDocumentSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCodexSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n includeOpenCodeSubagentMode?: boolean;\n } = {},\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-document\");\n const claudeSubagentMode = options.includeClaudeSubagentMode\n ? `${renderClaudeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const codexSubagentMode = options.includeCodexSubagentMode\n ? `${renderCodexSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const copilotCustomAgentMode = options.includeCopilotCustomAgentMode\n ? `${renderCopilotCustomAgentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const openCodeSubagentMode = options.includeOpenCodeSubagentMode\n ? `${renderOpenCodeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const subagentMode = `${claudeSubagentMode}${codexSubagentMode}${copilotCustomAgentMode}${openCodeSubagentMode}`;\n\n return `---\nname: truthmark-document\ndescription: ${workflow.description}\nargument-hint: Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\n# Truthmark Document\n\nUse this skill to document existing implemented behavior when no functional-code changes are required for the task.\nInvocations: ${TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS}\n\nTruth Document is manual and implementation-first:\n\n- run only when the user explicitly asks to generate or update truth docs for existing behavior, or when Truth Sync, Truth Check, or Truth Structure reports implemented behavior that lacks canonical truth docs\n- inspect .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, existing canonical docs, implementation code, and tests directly\n- ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n- document current implemented behavior; do not invent future behavior or planned endpoints\n- may write canonical truth docs and ${config.docs.routing.rootIndex} or relevant child route files only\n- must not write functional code\n- when routing is missing, stale, broad, overloaded, catch-all, or cannot map the behavior to a bounded truth owner, run Truth Structure first when routing repair is safe and in scope\n- block and recommend Truth Structure when routing repair is unsafe, ambiguous, or outside the task boundary\n- keep feature README.md files as indexes rather than truth-document targets\n- create or update bounded leaf truth docs when behavior does not fit an existing leaf doc\n- keep behavior truth docs behavior-oriented, not endpoint-oriented, unless the endpoint itself is the behavior boundary\n- keep API endpoint details in the nearest contract truth doc when such a doc owns the API contract\n- preserve unrelated authored content\n${renderTruthDocOwnershipGateSection(\n \"the implemented behavior and candidate truth docs\",\n \"if the target doc is broad, mixed-owner, index-like, or the documented behavior spans independent owners, run Truth Structure first when safe and in scope; otherwise block and recommend Truth Structure\",\n )}\n${TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS}\n${renderRouteFirstEvidenceGateSection(\n \"the documented behavior\",\n \"if no truth doc changed, report why current truth was already sufficient or why documentation was blocked\",\n )}\n${subagentMode}${REPOSITORY_INTELLIGENCE_INSTRUCTIONS}\n${FEATURE_DOC_TEMPLATE_INSTRUCTIONS}\n${renderTruthDocRestructureGateSection(\n \"Truth Document may restructure only truth docs for the implemented behavior being documented.\",\n )}\n${ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS}\n${renderHierarchySummary(config)}\n${DECISION_TRUTH_INSTRUCTIONS}\nParent post-document verification:\n- verify only truth docs and leased truth routing files changed during document work\n- block on functional code, generated host surfaces, or unrelated diffs caused by document work\n- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it\n- verify the final report records ownership review, structure requirement, restructure, routing update, or blocked reason when applicable\n\nReport completion in this shape:\n${renderMarkdownExample(renderTruthDocumentReportExample(config))}`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n defaultAgentConfig,\n renderHierarchySummary,\n resolveTruthDocsRoot,\n} from \"./shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const TRUTH_PREVIEW_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview.\";\n\nexport const renderTruthPreviewReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n\n return `Truth Preview: completed\n\nRequested outcome:\n- preview likely Truthmark workflow routing before edits\n\nLikely workflow:\n- truthmark-document\n\nWhy this workflow:\n- positive trigger: document existing implemented behavior\n- negative triggers considered: functional-code change, doc-first implementation, topology repair, truth audit\n- forbidden adjacency considered: must not edit functional code\n\nLikely route owner:\n- route file: ${config.docs.routing.rootIndex}\n- truth doc: ${truthDocsRoot}/example.md\n- confidence: medium\n\nExpected write classes:\n- truth docs\n\nExpected target files:\n- ${truthDocsRoot}/example.md\n\nSuggested subagent use:\n- read-only verifiers: truth_route_auditor\n- write workers: none in Preview\n- leases needed: none in Preview\n\nBlocking ambiguity:\n- none identified in preview\n\nHandoff:\n- Run the selected Truthmark workflow after user approval.`;\n};\n\nexport const renderTruthPreviewSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-preview\");\n\n return `---\nname: truthmark-preview\ndescription: ${workflow.description}\nargument-hint: Optional requested outcome, code area, doc path, or routing question\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\nUse this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits.\n\nInvocations: ${TRUTH_PREVIEW_EXPLICIT_INVOCATIONS}\n\nTruth Preview is read-only. Its report is intended, not authorized.\n\nPurpose:\n- preview the likely Truthmark workflow, route owner, target files, expected write classes, suggested subagent use, and blocking ambiguity before edits happen\n- hand off to the selected workflow after user approval\n- keep the selector thin so agents can avoid loading or acting through heavier workflows prematurely\n\nRead:\n- .truthmark/config.yml\n- ${config.docs.routing.rootIndex}\n- relevant child route files under ${config.docs.routing.areaFilesRoot}/\n- relevant truth docs and implementation files needed to preview ownership\n- ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n\nDo not:\n- must not edit files\n- must not create truth docs\n- must not update routing\n- must not run Truth Sync automatically\n- must not replace Truth Check\n- must not claim final correctness\n- must not issue write leases\n- must not mutate code\n\nSuggested subagent use:\n- optional read-only verifier: truth_route_auditor\n- write workers: none\n- leases needed: none\n\n${renderHierarchySummary(config)}\n\nReport completion in this shape:\n${renderMarkdownExample(renderTruthPreviewReportExample(config))}`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS,\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n FEATURE_DOC_TEMPLATE_INSTRUCTIONS,\n TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderClaimEvidenceCheckedSection,\n renderCopilotCustomAgentModeSection,\n renderHierarchySummary,\n renderTopologyEvidenceGateSection,\n renderTruthDocOwnershipGateSection,\n renderTruthDocRestructureGateSection,\n resolveTruthDocsRoot,\n} from \"./shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-structure; Codex /truthmark-structure or $truthmark-structure; Claude Code /truthmark-structure; GitHub Copilot /truthmark-structure; Gemini CLI /truthmark:structure.\";\n\nexport const renderTruthStructureReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n\n return `Truth Structure: completed\nTopology reviewed:\n- controllers: src/auth/**\n- docs root: ${truthDocsRoot}\n- route files: ${config.docs.routing.rootIndex}\nAreas reviewed:\n- src/auth/**\nRouting updated:\n- ${config.docs.routing.rootIndex}\nInitial truth boundary:\n- Area: Authentication\n- Code: src/auth/**\n- Truth owner: ${truthDocsRoot}/authentication/session.md\n- Scope: session behavior only\nTruth docs created:\n- ${truthDocsRoot}/authentication/session.md\nTruth docs split:\n- ${truthDocsRoot}/authentication/README.md -> ${truthDocsRoot}/authentication/session.md\nTruth docs restructured:\n- ${truthDocsRoot}/authentication/README.md\n${renderClaimEvidenceCheckedSection([\n {\n claim: \"Session behavior belongs to a dedicated Authentication truth owner.\",\n evidence: [\"src/auth/**\", `${config.docs.routing.rootIndex}:7`],\n result: \"supported\",\n },\n ])}\nTopology decisions:\n- Added an Authentication area because session behavior has a distinct code surface and truth owner.\nNotes:\n- Added an Authentication area for session behavior.`;\n};\n\nexport const renderTruthStructureSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n } = {},\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n const claudeSubagentMode = options.includeClaudeSubagentMode\n ? `${renderClaudeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns all Truth Structure writes and final topology decisions\",\n )}\\n`\n : \"\";\n const copilotCustomAgentMode = options.includeCopilotCustomAgentMode\n ? `${renderCopilotCustomAgentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns all Truth Structure writes and final topology decisions\",\n )}\\n`\n : \"\";\n const subagentMode = `${claudeSubagentMode}${copilotCustomAgentMode}`;\n\n return `---\nname: truthmark-structure\ndescription: ${workflow.description}\nargument-hint: Optional area, directory, or routing concern\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\nUse this skill to design or repair Truthmark area structure.\nInvocations: ${TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS}\nTruth Structure is agent-native:\n- inspect repository layout, current docs, .truthmark/config.yml, ${config.docs.routing.rootIndex}, and relevant code directly\n- ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n- inspect the configured root route index at ${config.docs.routing.rootIndex} and relevant child route files under ${config.docs.routing.areaFilesRoot}/\n- define areas by product or behavior ownership, not by mechanical directory mirroring\n- create or repair ${config.docs.routing.rootIndex}\n- create starter truth docs when useful and when they belong in the canonical current-truth surface\n- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter.\n- Starter truth docs must include ## Product Decisions and ## Rationale sections.\n${subagentMode}\n${FEATURE_DOC_TEMPLATE_INSTRUCTIONS}\n- use ${truthDocsRoot}/**, docs/architecture/**, or docs/standards/** for current truth destinations\n- use only canonical current-truth destinations for starter truth docs\n- keep active Product Decisions and Rationale in the canonical doc that owns the behavior\n- preserve unrelated authored content\n## New area setup\nUse when a user asks to onboard a new code area into Truthmark, a new package, controller, domain, or product area lacks bounded truth ownership, or a new product area needs routing and starter truth docs.\nDo:\n- inspect the named code area\n- infer bounded product or behavior ownership\n- choose the owning route when ownership is clear; otherwise propose the route and block for review\n- create or update the child route entry or file\n- create starter truth docs only where current truth is missing\n- report the initial truth boundary\nDo not:\n- do not edit functional code\n- do not perform full behavior documentation unless evidence is inspected and the task explicitly asks for it\n- do not patch broad or mixed-owner docs in place\n- do not create generic catch-all docs\n- do not treat README files as Sync targets\n## Topology Governance\nTruth Structure owns documentation topology. Do not depend on humans to manually organize ${truthDocsRoot}. Treat the configured truth root as a managed semantic root.\nInspect controllers, routes, handlers, services, packages, tests, existing truth docs, and route files; infer product and domain ownership from behavior boundaries, not from mechanical directory mirroring.\nWhen topology pressure exists, repair structure before creating or extending truth docs.\n${renderTruthDocOwnershipGateSection(\n \"candidate route owners and current truth docs\",\n \"if a truth doc mixes independent owners, route ownership is broad, or a split is required for bounded ownership, split and reroute into bounded truth docs when safe; otherwise block with manual-review files\",\n)}\n${TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS}\nTopology pressure signals:\n- one area maps broad code such as src/**, app/**, server/**, services/**, or packages/**\n- one area maps multiple unrelated controllers, route groups, services, or bounded contexts\n- one truth doc owns unrelated behaviors or unrelated endpoint families\n- the configured truth root has many direct non-index docs\n- a changed controller, route, or service cannot map to a specific behavior doc\n- Truth Sync would need to create a new generic truth doc because routing is too broad\n- endpoint or controller names reveal domains missing from ${config.docs.routing.areaFilesRoot}/**\nUse these review thresholds as guidance:\n- more than 10 direct truth docs in one folder\n- more than 15 leaf areas in one child route file\n- more than 8 truth docs mapped to one area\n- more than 5 controllers mapped through one catch-all area\nRepair rules:\n- split broad, overloaded, or catch-all areas into behavior-owned child route files\n- split mixed-owner truth docs into bounded owner docs before adding new behavior claims\n- create route files under ${config.docs.routing.areaFilesRoot}/ when a product/domain boundary is clear\n- create behavior truth docs under the configured truth root only when behavior lacks a current doc\n- README.md files are indexes, not Truth Sync targets\n- prefer bounded leaf truth docs at <truth-root>/<domain>/<behavior>.md\n- keep behavior truth docs behavior-oriented, not endpoint-oriented\n- keep API endpoint details in the nearest contract truth doc when such a doc exists\n- update routing so future Truth Sync can target small docs\n- preserve existing authored docs; move or rewrite only when needed to remove ambiguity\n- report Truth docs split when one broad or mixed-owner truth doc becomes multiple bounded docs\n${renderTruthDocRestructureGateSection(\n \"Truth Structure may restructure broader routed docs when topology, ownership, or doc-shape repair is already in scope.\",\n)}\n${renderTopologyEvidenceGateSection()}\n${ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS}\n- Do not finish topology repair with routed canonical current-truth docs missing Product Decisions or Rationale sections.\n- If an existing canonical doc lacks either section, add the missing heading beside Current Behavior with a concise current-state placeholder or active decision.\nPortable fallback:\n- If this skill surface is unavailable, perform the same workflow directly from committed repository files.\n- Do not require the truthmark CLI.\n- Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, canonical docs, and representative implementation code.\n- Use a subagent only when the host supports that pattern; otherwise perform the topology repair inline.\n${renderHierarchySummary(config)}\n${DECISION_TRUTH_INSTRUCTIONS}\nReport completion in this shape:\n${renderMarkdownExample(renderTruthStructureReportExample(config))}`;\n};\n","import {\n renderClaimEvidenceCheckedSection,\n type ClaimEvidenceItem,\n type ClaimEvidenceResult,\n} from \"../truth/evidence.js\";\n\nimport type { TruthSyncSkipReason } from \"./policy.js\";\n\nexport type TruthSyncCompletedReportInput = {\n changedCode: string[];\n truthDocsUpdated: string[];\n evidenceChecked: ClaimEvidenceItem[];\n notes: string[];\n};\n\nexport type TruthSyncCompletedReport = TruthSyncCompletedReportInput & {\n status: \"completed\";\n};\n\nexport type TruthSyncSkippedReportInput = {\n reason: TruthSyncSkipReason;\n};\n\nexport type TruthSyncBlockedReportInput = {\n reason: string;\n manualReviewFiles?: string[];\n nextAction: string;\n};\n\nconst renderBulletSection = (title: string, items: string[]): string => {\n return `${title}:\\n${items.map((item) => `- ${item}`).join(\"\\n\")}`;\n};\n\nconst parseBulletSection = (source: string, title: string): string[] => {\n const section = source\n .split(\"\\n\\n\")\n .find((candidate) => candidate.startsWith(`${title}:\\n`));\n\n if (!section) {\n return [];\n }\n\n return section\n .split(\"\\n\")\n .slice(1)\n .filter((line) => line.startsWith(\"- \"))\n .map((line) => line.slice(2));\n};\n\nconst isClaimEvidenceResult = (value: string): value is ClaimEvidenceResult => {\n return [\"supported\", \"narrowed\", \"removed\", \"blocked\"].includes(value);\n};\n\nconst parseEvidenceCheckedSection = (source: string): ClaimEvidenceItem[] => {\n const section = source\n .split(\"\\n\\n\")\n .find((candidate) => candidate.startsWith(\"Evidence checked:\\n\"));\n\n if (!section) {\n throw new Error(\"Evidence checked section is required.\");\n }\n\n const lines = section.split(\"\\n\").slice(1);\n const items: ClaimEvidenceItem[] = [];\n\n for (let index = 0; index < lines.length; index += 3) {\n const claimLine = lines[index];\n const evidenceLine = lines[index + 1];\n const resultLine = lines[index + 2];\n\n if (\n !claimLine?.startsWith(\"- Claim: \") ||\n !evidenceLine?.startsWith(\" Evidence: \") ||\n !resultLine?.startsWith(\" Result: \")\n ) {\n throw new Error(\"Evidence checked entries must include Claim, Evidence, and Result fields.\");\n }\n\n const result = resultLine.slice(\" Result: \".length);\n\n if (!isClaimEvidenceResult(result)) {\n throw new Error(\"Evidence checked result is invalid.\");\n }\n\n items.push({\n claim: claimLine.slice(\"- Claim: \".length),\n evidence: evidenceLine.slice(\" Evidence: \".length).split(\" / \"),\n result,\n });\n }\n\n return items;\n};\n\nexport const renderTruthSyncCompletedReport = (\n input: TruthSyncCompletedReportInput,\n): string => {\n return [\n \"Truth Sync: completed\",\n renderBulletSection(\"Changed code reviewed\", input.changedCode),\n renderBulletSection(\"Truth docs updated\", input.truthDocsUpdated),\n renderClaimEvidenceCheckedSection(input.evidenceChecked),\n renderBulletSection(\"Notes\", input.notes),\n ].join(\"\\n\\n\");\n};\n\nexport const parseTruthSyncReport = (source: string): TruthSyncCompletedReport => {\n if (!source.startsWith(\"Truth Sync: completed\")) {\n throw new Error(\"Only completed Truth Sync reports can be parsed.\");\n }\n\n return {\n status: \"completed\",\n changedCode: parseBulletSection(source, \"Changed code reviewed\"),\n truthDocsUpdated: parseBulletSection(source, \"Truth docs updated\"),\n evidenceChecked: parseEvidenceCheckedSection(source),\n notes: parseBulletSection(source, \"Notes\"),\n };\n};\n\nexport const renderTruthSyncSkippedReport = (\n input: TruthSyncSkippedReportInput,\n): string => {\n return [\"Truth Sync: skipped\", renderBulletSection(\"Reason\", [input.reason])].join(\"\\n\\n\");\n};\n\nexport const renderTruthSyncBlockedReport = (\n input: TruthSyncBlockedReportInput,\n): string => {\n const sections = [\n \"Truth Sync: blocked\",\n renderBulletSection(\"Reason\", [input.reason]),\n ];\n\n if ((input.manualReviewFiles?.length ?? 0) > 0) {\n sections.push(renderBulletSection(\"Files requiring manual review\", input.manualReviewFiles!));\n }\n\n sections.push(renderBulletSection(\"Next action\", [input.nextAction]));\n\n return [\n ...sections,\n ].join(\"\\n\\n\");\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS,\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n FEATURE_DOC_TEMPLATE_INSTRUCTIONS,\n REPOSITORY_INTELLIGENCE_INSTRUCTIONS,\n TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n renderRouteFirstEvidenceGateSection,\n renderHierarchySummary,\n renderTruthDocOwnershipGateSection,\n renderTruthDocRestructureGateSection,\n resolveTruthDocsRoot,\n} from \"./shared.js\";\nimport {\n renderTruthSyncBlockedReport,\n renderTruthSyncCompletedReport,\n} from \"../sync/report.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nexport const TRUTH_SYNC_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-sync; Codex /truthmark-sync or $truthmark-sync; Claude Code /truthmark-sync; GitHub Copilot /truthmark-sync; Gemini CLI /truthmark:sync.\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const renderTruthSyncWorkerPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return `### Truth Sync Worker\nThe parent provides the task focus, explicit write lease, and any repository context already gathered.\nWorker rules:\n- require a write lease with workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields before editing\n- inspect relevant staged, unstaged, and untracked functional code directly\n- read .truthmark/config.yml, ${config.docs.routing.rootIndex}, and canonical truth docs directly\n- Code verification is parent-owned; report what was run or why it was not run\n- may write only leased truth docs and leased truth routing files for Truth Sync alignment\n- must not rewrite functional code or generated host surfaces\n- stop and report blocked when the required edit needs an off-lease file\nReturn result in this shape:\n- status: completed | blocked\n- worker: string\n- shard: string\n- filesChanged: string[]\n- changedCodeReviewed: string[]\n- ownershipReviewed: string[]\n- structureRequired?: string[]\n- truthDocsUpdated: string[]\n- routingDocsUpdated: string[]\n- truthDocsSplit?: string[]\n- evidenceChecked: { claim: string; evidence: string[]; result: supported | narrowed | removed | blocked }[]\n- offLeaseChanges: string[]\n- notes: string[]\n- blockedReason?: string\n- manualReviewFiles?: string[]`;\n};\n\nexport const renderTruthSyncSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCodexSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n includeOpenCodeSubagentMode?: boolean;\n } = {},\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n const claudeSubagentMode = options.includeClaudeSubagentMode\n ? `${renderClaudeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const codexSubagentMode = options.includeCodexSubagentMode\n ? `${renderCodexSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const copilotCustomAgentMode = options.includeCopilotCustomAgentMode\n ? `${renderCopilotCustomAgentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const openCodeSubagentMode = options.includeOpenCodeSubagentMode\n ? `${renderOpenCodeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const subagentMode = `${claudeSubagentMode}${codexSubagentMode}${copilotCustomAgentMode}${openCodeSubagentMode}`;\n\n return `---\nname: truthmark-sync\ndescription: ${workflow.description}\nargument-hint: Optional changed-code area, truth-doc area, or sync focus\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\nUse this skill automatically before finishing when functional code changed since the last successful Truth Sync. Also run it immediately when the user explicitly invokes Truth Sync.\nInvocations: ${TRUTH_SYNC_EXPLICIT_INVOCATIONS}\nExplicit invocation runs immediately. Later functional-code changes reopen the finish-time requirement, and an earlier explicit run satisfies the finish gate only if no later functional-code changes occur.\nSkip when changes are documentation-only, formatting-only, clearly behavior-preserving renames with no truth impact, when no Truthmark config exists yet, or when there are no functional code changes.\nParent workflow:\n1. Inspect git status, staged changes, unstaged changes, and untracked files directly.\n2. Read .truthmark/config.yml, the configured root route index at ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, and relevant canonical docs.\n3. Identify functional-code changes and the nearest truth docs or routing repairs.\n4. ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run.\n6. Dispatch bounded Truth Sync workers only when the host supports subagent dispatch and the acting agent chooses that path; otherwise execute the same sync task inline.\n${subagentMode}Topology quality gate:\n- before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner\n- if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc\n- run Truth Structure before syncing when topology repair is safe and in scope\n- block and recommend Truth Structure when topology repair is unsafe, ambiguous, or outside the current task boundary\n- report the route files and changed code paths that require structure repair\n- README.md files are indexes, not Truth Sync targets\n- must not append behavior details to a README.md index\n- create or update a bounded leaf truth doc when behavior changes do not fit an existing leaf doc\n${renderTruthDocOwnershipGateSection(\n \"changed functional files and impacted truth docs\",\n \"if an impacted doc is broad, mixed-owner, index-like, or the update spans independent behavior owners, run Truth Structure before syncing when safe and in scope; otherwise block and recommend Truth Structure\",\n )}\n${TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS}\n${FEATURE_DOC_TEMPLATE_INSTRUCTIONS}\n${renderTruthDocRestructureGateSection(\n \"Truth Sync may restructure only truth docs impacted by the current functional-code change.\",\n )}\n${ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS}\n${renderRouteFirstEvidenceGateSection(\n \"changed functional files\",\n \"if no impacted doc changed, report why truth was already current or why sync was skipped\",\n )}\n${REPOSITORY_INTELLIGENCE_INSTRUCTIONS}\nOptional validation tooling:\n- you may run truthmark check when local tooling is available\n- do not require the truthmark binary; direct checkout inspection is the canonical path\n- optional validation must not replace agent judgment about docs and routing\n- update Product Decisions and Rationale when a behavior change comes from a decision change\n${renderHierarchySummary(config)}\n${DECISION_TRUTH_INSTRUCTIONS}\nParent post-sync verification:\n- verify only truth docs and leased truth routing files changed during sync\n- block on any unrelated diff caused by the sync step\n- block if functional code changed during sync\n- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it\n- validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked\n- verify the updated docs correspond to the reviewed changed-code surface\n- verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired\n- blocked outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files\nReport completion in this shape:\n${renderMarkdownExample(\n renderTruthSyncCompletedReport({\n changedCode: [\"src/auth/session.ts\"],\n truthDocsUpdated: [`${truthDocsRoot}/repository/overview.md`],\n evidenceChecked: [\n {\n claim: \"Session timeout behavior is documented in the mapped repository truth doc.\",\n evidence: [\"src/auth/session.ts:12\", `${config.docs.routing.rootIndex}:11`],\n result: \"supported\",\n },\n ],\n notes: [\"Updated session timeout behavior.\"],\n }),\n )}\nBlocked report example:\n${renderMarkdownExample(\n renderTruthSyncBlockedReport({\n reason: \"routing repair is not allowed\",\n manualReviewFiles: [config.docs.routing.rootIndex],\n nextAction: \"update routing metadata and rerun Truth Sync\",\n }),\n )}`;\n};\n","import micromatch from \"micromatch\";\nimport { parse as parseYaml } from \"yaml\";\n\nimport type {\n TruthmarkWorkflowId,\n TruthmarkWriteSubagentId,\n} from \"./workflow-manifest.js\";\n\nexport const TRUTHMARK_WRITE_WORKER_REPORT_FIELDS = [\n \"status\",\n \"worker\",\n \"workflow\",\n \"shard\",\n \"filesChanged\",\n \"claimsChecked\",\n \"evidenceChecked\",\n \"offLeaseChanges\",\n \"blockers\",\n \"notes\",\n] as const;\n\nexport type TruthmarkWriteWorkerReportField =\n (typeof TRUTHMARK_WRITE_WORKER_REPORT_FIELDS)[number];\n\nexport type TruthmarkWriteLease = {\n workflow: TruthmarkWorkflowId;\n worker: TruthmarkWriteSubagentId;\n shard: string;\n objective: string;\n requiredReads: string[];\n allowedReads?: string[];\n allowedWrites: string[];\n forbiddenWrites: string[];\n evidenceRequired: string[];\n verification?: string[];\n reportFields: string[];\n};\n\nexport type TruthmarkWriteLeaseChangeValidation = {\n allowedChanges: string[];\n forbiddenChanges: string[];\n offLeaseChanges: string[];\n};\n\nexport type TruthmarkWriteWorkerReport = Record<string, unknown>;\n\nexport type TruthmarkWriteWorkerAcceptanceReasonCode =\n | \"missing-report-field\"\n | \"invalid-report-field\"\n | \"invalid-report-status\"\n | \"identity-mismatch\"\n | \"forbidden-actual-diff\"\n | \"off-lease-actual-diff\"\n | \"reported-files-mismatch\"\n | \"completed-with-reported-off-lease-changes\"\n | \"completed-with-blockers\"\n | \"blocked-without-blockers\";\n\nexport type TruthmarkWriteWorkerAcceptanceReason = {\n code: TruthmarkWriteWorkerAcceptanceReasonCode;\n message: string;\n field?: string;\n files?: string[];\n expected?: string;\n actual?: string;\n};\n\nexport type TruthmarkWriteWorkerAcceptanceValidation = {\n status: \"accepted\" | \"blocked\" | \"rejected\";\n reasons: TruthmarkWriteWorkerAcceptanceReason[];\n changeValidation: TruthmarkWriteLeaseChangeValidation;\n actualChangedFiles: string[];\n reportedFilesChanged: string[];\n};\n\nconst normalizePath = (filePath: string): string => {\n return filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/u, \"\");\n};\n\nconst matchesAny = (filePath: string, patterns: string[]): boolean => {\n if (patterns.length === 0) {\n return false;\n }\n\n return micromatch.isMatch(normalizePath(filePath), patterns);\n};\n\nconst uniqueSorted = (values: string[]): string[] => {\n return Array.from(new Set(values)).sort((left, right) => left.localeCompare(right));\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n};\n\nconst hasOwn = (record: Record<string, unknown>, key: string): boolean => {\n return Object.prototype.hasOwnProperty.call(record, key);\n};\n\nconst readStringArrayField = (\n report: TruthmarkWriteWorkerReport,\n field: string,\n): string[] | undefined => {\n const value = report[field];\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\")) {\n return undefined;\n }\n return uniqueSorted(value.map(normalizePath));\n};\n\nconst equalStringArrays = (left: string[], right: string[]): boolean => {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n};\n\nexport const parseTruthmarkWriteWorkerReport = (\n source: string,\n): TruthmarkWriteWorkerReport => {\n const parsed = parseYaml(source);\n if (!isRecord(parsed)) {\n throw new Error(\"Truthmark write worker report must be a YAML object.\");\n }\n return parsed;\n};\n\nexport const validateTruthmarkWriteLeaseChanges = (\n lease: TruthmarkWriteLease,\n changedFiles: string[],\n): TruthmarkWriteLeaseChangeValidation => {\n const normalizedFiles = uniqueSorted(changedFiles.map(normalizePath));\n const forbiddenChanges = normalizedFiles.filter((filePath) =>\n matchesAny(filePath, lease.forbiddenWrites),\n );\n const outsideAllowedWrites = normalizedFiles.filter(\n (filePath) => !matchesAny(filePath, lease.allowedWrites),\n );\n const offLeaseChanges = uniqueSorted([\n ...forbiddenChanges,\n ...outsideAllowedWrites,\n ]);\n\n return {\n allowedChanges: normalizedFiles.filter(\n (filePath) => !offLeaseChanges.includes(filePath),\n ),\n forbiddenChanges,\n offLeaseChanges,\n };\n};\n\nexport const validateTruthmarkWriteWorkerAcceptance = ({\n lease,\n workerReport,\n actualChangedFiles,\n}: {\n lease: TruthmarkWriteLease;\n workerReport: TruthmarkWriteWorkerReport;\n actualChangedFiles: string[];\n}): TruthmarkWriteWorkerAcceptanceValidation => {\n const reasons: TruthmarkWriteWorkerAcceptanceReason[] = [];\n const normalizedActualChangedFiles = uniqueSorted(actualChangedFiles.map(normalizePath));\n const requiredReportFields = uniqueSorted([\n ...lease.reportFields,\n ...(lease.worker === \"truth_doc_writer\" ? TRUTHMARK_WRITE_WORKER_REPORT_FIELDS : []),\n ]);\n\n for (const field of requiredReportFields) {\n if (!hasOwn(workerReport, field)) {\n reasons.push({\n code: \"missing-report-field\",\n field,\n message: `Worker report is missing required field ${field}.`,\n });\n }\n }\n\n const reportStatus = workerReport.status;\n if (\n hasOwn(workerReport, \"status\") &&\n reportStatus !== \"completed\" &&\n reportStatus !== \"blocked\"\n ) {\n reasons.push({\n code: \"invalid-report-status\",\n field: \"status\",\n message: \"Worker report status must be completed or blocked.\",\n });\n }\n\n for (const field of [\"worker\", \"workflow\", \"shard\"] as const) {\n const actual = workerReport[field];\n const expected = lease[field];\n if (hasOwn(workerReport, field) && typeof actual !== \"string\") {\n reasons.push({\n code: \"invalid-report-field\",\n field,\n message: `Worker report field ${field} must be a string.`,\n });\n } else if (typeof actual === \"string\" && actual !== expected) {\n reasons.push({\n code: \"identity-mismatch\",\n field,\n expected,\n actual,\n message: `Worker report ${field} does not match the lease.`,\n });\n }\n }\n\n for (const field of [\n \"filesChanged\",\n \"claimsChecked\",\n \"evidenceChecked\",\n \"offLeaseChanges\",\n \"blockers\",\n \"notes\",\n ]) {\n if (hasOwn(workerReport, field) && readStringArrayField(workerReport, field) === undefined) {\n reasons.push({\n code: \"invalid-report-field\",\n field,\n message: `Worker report field ${field} must be a string array.`,\n });\n }\n }\n\n const reportedFilesChanged = readStringArrayField(workerReport, \"filesChanged\") ?? [];\n const reportedOffLeaseChanges = readStringArrayField(workerReport, \"offLeaseChanges\") ?? [];\n const reportedBlockers = readStringArrayField(workerReport, \"blockers\") ?? [];\n const changeValidation = validateTruthmarkWriteLeaseChanges(\n lease,\n normalizedActualChangedFiles,\n );\n\n if (changeValidation.forbiddenChanges.length > 0) {\n reasons.push({\n code: \"forbidden-actual-diff\",\n files: changeValidation.forbiddenChanges,\n message: \"Actual worker diff includes forbidden lease paths.\",\n });\n }\n\n if (changeValidation.offLeaseChanges.length > 0) {\n reasons.push({\n code: \"off-lease-actual-diff\",\n files: changeValidation.offLeaseChanges,\n message: \"Actual worker diff includes paths outside allowedWrites.\",\n });\n }\n\n if (!equalStringArrays(reportedFilesChanged, normalizedActualChangedFiles)) {\n reasons.push({\n code: \"reported-files-mismatch\",\n files: reportedFilesChanged,\n message: \"Worker report filesChanged does not match the actual worker diff.\",\n });\n }\n\n if (reportStatus === \"completed\" && reportedOffLeaseChanges.length > 0) {\n reasons.push({\n code: \"completed-with-reported-off-lease-changes\",\n files: reportedOffLeaseChanges,\n message: \"Completed worker reports must not include offLeaseChanges.\",\n });\n }\n\n if (reportStatus === \"completed\" && reportedBlockers.length > 0) {\n reasons.push({\n code: \"completed-with-blockers\",\n message: \"Completed worker reports must not include blockers.\",\n });\n }\n\n if (reportStatus === \"blocked\" && reportedBlockers.length === 0) {\n reasons.push({\n code: \"blocked-without-blockers\",\n message: \"Blocked worker reports must include at least one blocker.\",\n });\n }\n\n if (reasons.length === 0 && reportStatus === \"completed\") {\n return {\n status: \"accepted\",\n reasons,\n changeValidation,\n actualChangedFiles: normalizedActualChangedFiles,\n reportedFilesChanged,\n };\n }\n\n if (reasons.length === 0 && reportStatus === \"blocked\") {\n return {\n status: \"blocked\",\n reasons,\n changeValidation,\n actualChangedFiles: normalizedActualChangedFiles,\n reportedFilesChanged,\n };\n }\n\n return {\n status: \"rejected\",\n reasons,\n changeValidation,\n actualChangedFiles: normalizedActualChangedFiles,\n reportedFilesChanged,\n };\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderHierarchySummary,\n renderOpenCodeSubagentModeSection,\n renderTruthDocOwnershipGateSection,\n resolveTruthDocsRoot,\n} from \"../agents/shared.js\";\nimport {\n TRUTH_CHECK_EXPLICIT_INVOCATIONS,\n renderTruthCheckSkillBody,\n} from \"../agents/truth-check.js\";\nimport {\n TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS,\n renderTruthDocumentSkillBody,\n} from \"../agents/truth-document.js\";\nimport {\n TRUTH_PREVIEW_EXPLICIT_INVOCATIONS,\n renderTruthPreviewSkillBody,\n} from \"../agents/truth-preview.js\";\nimport {\n TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS,\n renderTruthStructureSkillBody,\n} from \"../agents/truth-structure.js\";\nimport {\n TRUTH_SYNC_EXPLICIT_INVOCATIONS,\n renderTruthSyncSkillBody,\n} from \"../agents/truth-sync.js\";\nimport { TRUTHMARK_WRITE_WORKER_REPORT_FIELDS } from \"../agents/write-lease.js\";\nimport {\n getTruthmarkWorkflow,\n type TruthmarkWorkflowId,\n type TruthmarkReadOnlySubagentId,\n type TruthmarkWriteSubagentId,\n} from \"../agents/workflow-manifest.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\n\nexport const TRUTHMARK_STRUCTURE_SKILL_PATH =\n \".codex/skills/truthmark-structure/SKILL.md\";\n\nexport const TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-structure/agents/openai.yaml\";\n\nexport const TRUTHMARK_DOCUMENT_SKILL_PATH =\n \".codex/skills/truthmark-document/SKILL.md\";\n\nexport const TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-document/agents/openai.yaml\";\n\nexport const TRUTHMARK_SYNC_SKILL_PATH =\n \".codex/skills/truthmark-sync/SKILL.md\";\n\nexport const TRUTHMARK_SYNC_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-sync/agents/openai.yaml\";\n\nexport const TRUTHMARK_REALIZE_SKILL_PATH =\n \".codex/skills/truthmark-realize/SKILL.md\";\n\nexport const TRUTHMARK_REALIZE_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-realize/agents/openai.yaml\";\n\nexport const TRUTHMARK_CHECK_SKILL_PATH =\n \".codex/skills/truthmark-check/SKILL.md\";\n\nexport const TRUTHMARK_CHECK_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-check/agents/openai.yaml\";\n\nexport const TRUTHMARK_PREVIEW_SKILL_PATH =\n \".codex/skills/truthmark-preview/SKILL.md\";\n\nexport const TRUTHMARK_PREVIEW_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-preview/agents/openai.yaml\";\n\nexport const TRUTHMARK_ROUTE_AUDITOR_AGENT_PATH =\n \".codex/agents/truth-route-auditor.toml\";\n\nexport const TRUTHMARK_CLAIM_VERIFIER_AGENT_PATH =\n \".codex/agents/truth-claim-verifier.toml\";\n\nexport const TRUTHMARK_DOC_REVIEWER_AGENT_PATH =\n \".codex/agents/truth-doc-reviewer.toml\";\nexport const TRUTHMARK_DOC_WRITER_AGENT_PATH =\n \".codex/agents/truth-doc-writer.toml\";\n\nexport const TRUTHMARK_OPENCODE_ROUTE_AUDITOR_AGENT_PATH =\n \".opencode/agents/truth-route-auditor.md\";\n\nexport const TRUTHMARK_OPENCODE_CLAIM_VERIFIER_AGENT_PATH =\n \".opencode/agents/truth-claim-verifier.md\";\n\nexport const TRUTHMARK_OPENCODE_DOC_REVIEWER_AGENT_PATH =\n \".opencode/agents/truth-doc-reviewer.md\";\nexport const TRUTHMARK_OPENCODE_DOC_WRITER_AGENT_PATH =\n \".opencode/agents/truth-doc-writer.md\";\n\nexport const TRUTHMARK_CLAUDE_ROUTE_AUDITOR_AGENT_PATH =\n \".claude/agents/truth-route-auditor.md\";\n\nexport const TRUTHMARK_CLAUDE_CLAIM_VERIFIER_AGENT_PATH =\n \".claude/agents/truth-claim-verifier.md\";\n\nexport const TRUTHMARK_CLAUDE_DOC_REVIEWER_AGENT_PATH =\n \".claude/agents/truth-doc-reviewer.md\";\nexport const TRUTHMARK_CLAUDE_DOC_WRITER_AGENT_PATH =\n \".claude/agents/truth-doc-writer.md\";\n\nexport const TRUTHMARK_GEMINI_STRUCTURE_COMMAND_PATH =\n \".gemini/commands/truthmark/structure.toml\";\n\nexport const TRUTHMARK_GEMINI_DOCUMENT_COMMAND_PATH =\n \".gemini/commands/truthmark/document.toml\";\n\nexport const TRUTHMARK_GEMINI_SYNC_COMMAND_PATH =\n \".gemini/commands/truthmark/sync.toml\";\n\nexport const TRUTHMARK_GEMINI_REALIZE_COMMAND_PATH =\n \".gemini/commands/truthmark/realize.toml\";\n\nexport const TRUTHMARK_GEMINI_CHECK_COMMAND_PATH =\n \".gemini/commands/truthmark/check.toml\";\n\nexport const TRUTHMARK_GEMINI_PREVIEW_COMMAND_PATH =\n \".gemini/commands/truthmark/preview.toml\";\n\nexport const TRUTHMARK_COPILOT_STRUCTURE_PROMPT_PATH =\n \".github/prompts/truthmark-structure.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_DOCUMENT_PROMPT_PATH =\n \".github/prompts/truthmark-document.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_SYNC_PROMPT_PATH =\n \".github/prompts/truthmark-sync.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH =\n \".github/prompts/truthmark-realize.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_CHECK_PROMPT_PATH =\n \".github/prompts/truthmark-check.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_PREVIEW_PROMPT_PATH =\n \".github/prompts/truthmark-preview.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH =\n \".github/agents/truth-route-auditor.agent.md\";\n\nexport const TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH =\n \".github/agents/truth-claim-verifier.agent.md\";\n\nexport const TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH =\n \".github/agents/truth-doc-reviewer.agent.md\";\nexport const TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH =\n \".github/agents/truth-doc-writer.agent.md\";\n\nconst renderGeminiCommand = (description: string, prompt: string): string => {\n return `description = \"${description}\"\nprompt = '''\n${prompt}\n'''\n`;\n};\n\nconst renderCopilotPromptFile = (\n description: string,\n prompt: string,\n): string => {\n return `---\nagent: 'agent'\ndescription: '${description}'\n---\n\n${prompt}\n`;\n};\n\nconst renderTomlString = (value: string): string => {\n return `\"${value.replace(/\\\\/gu, \"\\\\\\\\\").replace(/\"/gu, '\\\\\"')}\"`;\n};\n\nconst renderTomlStringArray = (values: string[]): string => {\n return `[${values.map(renderTomlString).join(\", \")}]`;\n};\n\ntype TruthmarkSkillPackageHost = \"codex\" | \"opencode\" | \"claude-code\";\n\ntype TruthmarkSkillPackageFile = {\n path: string;\n content: string;\n};\n\ntype WorkflowPackageDefinition = {\n title: string;\n argumentHint: string;\n invocations: string;\n use: (config: TruthmarkConfig) => string;\n quickRules: (config: TruthmarkConfig) => string[];\n parentRule?: string;\n};\n\nconst TRUTH_REALIZE_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize.\";\n\nconst WORKFLOW_PACKAGE_DEFINITIONS: Record<\n TruthmarkWorkflowId,\n WorkflowPackageDefinition\n> = {\n \"truthmark-structure\": {\n title: \"Truthmark Structure\",\n argumentHint: \"Optional area, directory, or routing concern\",\n invocations: TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS,\n use: () => \"Use this skill to design or repair Truthmark area structure.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, current docs, and relevant code directly.`,\n \"Define areas by product or behavior ownership, not by mechanical directory mirroring.\",\n \"Do not edit functional code.\",\n \"Read support/procedure.md before writing route or starter truth-doc changes.\",\n \"Read support/report-template.md before the final report.\",\n ],\n parentRule:\n \"Parent agent owns all Truth Structure writes and final topology decisions\",\n },\n \"truthmark-document\": {\n title: \"Truthmark Document\",\n argumentHint:\n \"Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document\",\n invocations: TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS,\n use: () =>\n \"Use this skill to document existing implemented behavior when no functional-code changes are required for the task.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, existing canonical docs, implementation code, and tests directly.`,\n \"Document current implemented behavior; do not invent future behavior.\",\n \"May write canonical truth docs and truth routing files only; must not write functional code.\",\n \"Read support/procedure.md before editing truth docs.\",\n \"Read support/subagents-and-leases.md before dispatching or accepting worker output.\",\n \"Read support/report-template.md before the final report.\",\n ],\n parentRule:\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n },\n \"truthmark-sync\": {\n title: \"Truthmark Sync\",\n argumentHint: \"Optional changed-code area, truth-doc area, or sync focus\",\n invocations: TRUTH_SYNC_EXPLICIT_INVOCATIONS,\n use: () =>\n \"Use this skill automatically before finishing when functional code changed since the last successful Truth Sync. Also run it immediately when the user explicitly invokes Truth Sync.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n \"Skip docs-only, formatting-only, behavior-preserving renames with no truth impact, missing config, and no-code changes.\",\n `Read .truthmark/config.yml, the configured root route index at ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, and relevant canonical docs.`,\n \"direct checkout inspection is the canonical path; do not require the truthmark binary.\",\n \"May write canonical truth docs and truth routing files only; must not rewrite functional code.\",\n \"Read support/procedure.md before editing truth docs.\",\n \"Read support/subagents-and-leases.md before dispatching or accepting worker output.\",\n \"Read support/report-template.md before the final report.\",\n ],\n parentRule:\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n },\n \"truthmark-preview\": {\n title: \"Truthmark Preview\",\n argumentHint:\n \"Optional requested outcome, code area, doc path, or routing question\",\n invocations: TRUTH_PREVIEW_EXPLICIT_INVOCATIONS,\n use: () =>\n \"Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, and only the truth docs or implementation files needed to preview ownership.`,\n \"Truth Preview is read-only; this report is intended, not authorized.\",\n \"must not edit files and must not issue write leases; do not run Truth Sync automatically, replace Truth Check, claim final correctness, or mutate code.\",\n \"Use optional read-only route-auditor evidence only when it reduces context or clarifies ownership.\",\n \"Hand off to the selected workflow after user approval.\",\n ],\n parentRule: \"Parent agent owns the final Truth Preview report\",\n },\n \"truthmark-realize\": {\n title: \"Truthmark Realize\",\n argumentHint:\n \"Optional truth doc path, area, or desired code behavior to realize\",\n invocations: TRUTH_REALIZE_EXPLICIT_INVOCATIONS,\n use: () =>\n \"Use this skill only when the user explicitly asks to realize truth docs into code.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read the source truth docs, .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files, tests, and relevant functional code directly.`,\n \"Truth docs lead; code follows.\",\n \"may write functional code only; must not edit truth docs or truth routing while realizing those docs.\",\n \"Read support/procedure.md before changing code.\",\n \"Read support/report-template.md before the final report.\",\n ],\n },\n \"truthmark-check\": {\n title: \"Truthmark Check\",\n argumentHint: \"Optional area, doc path, or audit focus\",\n invocations: TRUTH_CHECK_EXPLICIT_INVOCATIONS,\n use: () => \"Use this skill to audit repository truth health.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, canonical docs, and relevant implementation directly.`,\n \"Report issues and suggested fixes; do not silently rewrite unrelated files.\",\n \"Direct checkout inspection is valid even when local tooling is unavailable.\",\n \"Read support/procedure.md before auditing details.\",\n \"Read support/subagents-and-leases.md before dispatching verifier subagents.\",\n \"Read support/report-template.md before the final report.\",\n ],\n parentRule: \"Parent agent owns the final Truth Check report\",\n },\n};\n\nconst stripWorkflowSkillFrontmatter = (body: string): string => {\n return body.replace(/^---\\n[\\s\\S]*?\\n---\\n\\n?/u, \"\").trim();\n};\n\nconst splitWorkflowSupport = (\n body: string,\n): { procedure: string; reportTemplate: string } => {\n const stripped = stripWorkflowSkillFrontmatter(body);\n const marker = \"Report completion in this shape:\";\n const markerIndex = stripped.indexOf(marker);\n\n if (markerIndex === -1) {\n return {\n procedure: stripped,\n reportTemplate: \"Report completion in the workflow-specific shape.\",\n };\n }\n\n return {\n procedure: stripped.slice(0, markerIndex).trim(),\n reportTemplate: stripped.slice(markerIndex).trim(),\n };\n};\n\nconst renderSkillSupportFile = (title: string, body: string): string => {\n return `# ${title}\n\nGenerated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\n${body}\n`;\n};\n\nconst renderStandaloneWorkflowSkillBody = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n): string => {\n switch (workflowId) {\n case \"truthmark-structure\":\n return renderTruthStructureSkillBody(config);\n case \"truthmark-document\":\n return renderTruthDocumentSkillBody(config);\n case \"truthmark-sync\":\n return renderTruthSyncSkillBody(config);\n case \"truthmark-preview\":\n return renderTruthPreviewSkillBody(config);\n case \"truthmark-realize\":\n return renderTruthmarkRealizeSkillBody(config);\n case \"truthmark-check\":\n return renderTruthCheckSkillBody(config);\n }\n};\n\nconst renderWorkflowEntrypoint = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n supportFiles: string[],\n): string => {\n const workflow = getTruthmarkWorkflow(workflowId);\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const supportFileList = supportFiles\n .map((supportFile) => `- ${supportFile}`)\n .join(\"\\n\");\n\n return `---\nname: ${workflowId}\ndescription: ${workflow.description}\nargument-hint: ${definition.argumentHint}\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\n# ${definition.title}\n\n${definition.use(config)}\n\nInvocations: ${definition.invocations}\n\nQuick procedure:\n${definition\n .quickRules(config)\n .map((rule) => `- ${rule}`)\n .join(\"\\n\")}\n\nProgressive disclosure:\n${supportFileList}\n`;\n};\n\nconst renderWorkflowSubagentSupport = (\n workflowId: TruthmarkWorkflowId,\n host: TruthmarkSkillPackageHost,\n): string | undefined => {\n const workflow = getTruthmarkWorkflow(workflowId);\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const readAgents = workflow.subagents ?? [];\n const writeAgents = workflow.writeSubagents ?? [];\n\n if (readAgents.length === 0 && writeAgents.length === 0) {\n return undefined;\n }\n\n if (definition.parentRule === undefined) {\n return undefined;\n }\n\n switch (host) {\n case \"codex\":\n return renderCodexSubagentModeSection(\n readAgents,\n definition.parentRule,\n writeAgents,\n );\n case \"opencode\":\n return renderOpenCodeSubagentModeSection(\n readAgents,\n definition.parentRule,\n writeAgents,\n );\n case \"claude-code\":\n return renderClaudeSubagentModeSection(\n readAgents,\n definition.parentRule,\n writeAgents,\n );\n }\n};\n\nexport const renderTruthmarkSkillPackage = ({\n skillPath,\n workflowId,\n host,\n config = defaultAgentConfig(),\n}: {\n skillPath: string;\n workflowId: TruthmarkWorkflowId;\n host: TruthmarkSkillPackageHost;\n config?: TruthmarkConfig;\n}): TruthmarkSkillPackageFile[] => {\n const skillDirectory = skillPath.replace(/\\/SKILL\\.md$/u, \"\");\n const supportDirectory = `${skillDirectory}/support`;\n const { procedure, reportTemplate } = splitWorkflowSupport(\n renderStandaloneWorkflowSkillBody(workflowId, config),\n );\n const subagents = renderWorkflowSubagentSupport(workflowId, host);\n const supportFiles = [\n \"support/procedure.md\",\n \"support/report-template.md\",\n ...(subagents === undefined ? [] : [\"support/subagents-and-leases.md\"]),\n ];\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const files: TruthmarkSkillPackageFile[] = [\n {\n path: skillPath,\n content: renderWorkflowEntrypoint(workflowId, config, supportFiles),\n },\n {\n path: `${supportDirectory}/procedure.md`,\n content: renderSkillSupportFile(\n `${definition.title} Procedure`,\n procedure,\n ),\n },\n {\n path: `${supportDirectory}/report-template.md`,\n content: renderSkillSupportFile(\n `${definition.title} Report Template`,\n reportTemplate,\n ),\n },\n ];\n\n if (subagents !== undefined) {\n files.push({\n path: `${supportDirectory}/subagents-and-leases.md`,\n content: renderSkillSupportFile(\n `${definition.title} Subagents And Leases`,\n subagents,\n ),\n });\n }\n\n return files;\n};\n\nconst normalizeOpenCodePermissionPath = (path: string): string => {\n const normalized = path\n .replace(/\\\\/gu, \"/\")\n .replace(/^\\.\\//u, \"\")\n .replace(/\\/+$/u, \"\");\n\n return normalized === \"\" ? \".\" : normalized;\n};\n\nconst appendOpenCodePermissionGlob = (root: string, glob: string): string => {\n return root === \".\" ? glob.replace(/^\\//u, \"\") : `${root}${glob}`;\n};\n\nconst renderOpenCodeWriterEditAllowRules = (\n config: TruthmarkConfig,\n): string => {\n const truthDocsRoot = normalizeOpenCodePermissionPath(\n resolveTruthDocsRoot(config),\n );\n const rootRouteIndex = normalizeOpenCodePermissionPath(\n config.docs.routing.rootIndex,\n );\n const areaFilesRoot = normalizeOpenCodePermissionPath(\n config.docs.routing.areaFilesRoot,\n );\n const allowedPatterns = [\n appendOpenCodePermissionGlob(truthDocsRoot, \"/**\"),\n rootRouteIndex,\n appendOpenCodePermissionGlob(areaFilesRoot, \"/**/*.md\"),\n ];\n\n return [...new Set(allowedPatterns)]\n .map((pattern) => ` ${JSON.stringify(pattern)}: allow`)\n .join(\"\\n\");\n};\n\ntype TruthmarkSubagentProfile = {\n codexName: string;\n copilotName: string;\n description: string;\n nicknameCandidates: string[];\n instructions: string;\n};\n\nconst READ_ONLY_SUBAGENT_CONTEXT_BOUNDARY = `Context boundary:\nDo not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence.\nUse only the parent-assigned shard plus required checkout evidence files.\nReturn findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes.`;\n\nconst renderReadOnlySubagentInstructions = (instructions: string): string => {\n return `${instructions}\n${READ_ONLY_SUBAGENT_CONTEXT_BOUNDARY}`;\n};\n\nconst TRUTHMARK_SUBAGENT_PROFILES = {\n truth_route_auditor: {\n codexName: \"truth_route_auditor\",\n copilotName: \"truth-route-auditor\",\n description:\n \"Read-only Truthmark route auditor for bounded routing and ownership verification.\",\n nicknameCandidates: [\"Route Audit\", \"Route Trace\", \"Route Check\"],\n instructions: `Stay read-only.\nAudit one bounded Truthmark route, area, or doc shard assigned by the parent.\nRead .truthmark/config.yml, the root route index, relevant child route files, mapped truth docs, and relevant implementation files directly.\nFind missing, stale, broad, overloaded, catch-all, mixed-owner, or unrouteable ownership.\nDo not edit files, stage changes, or propose broad rewrites.\nReturn JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes.\nrecommendedWorkflow must be one of: none, truthmark-document, truthmark-structure.`,\n },\n truth_claim_verifier: {\n codexName: \"truth_claim_verifier\",\n copilotName: \"truth-claim-verifier\",\n description:\n \"Read-only Truthmark claim verifier for checking canonical truth against checkout evidence.\",\n nicknameCandidates: [\"Claim Audit\", \"Claim Trace\", \"Claim Check\"],\n instructions: `Stay read-only.\nVerify the behavior-bearing truth claims assigned by the parent against primary checkout evidence.\nUse implementation, tests, config, routing, generated templates, schemas, or explicit evidence blocks as primary evidence.\nCanonical docs and examples can corroborate but are not sole proof when implementation conflicts.\nFor every checked claim, classify the result as supported | narrowed | removed | blocked.\nDo not edit files, stage changes, or invent missing behavior.\nReturn JSON only with keys: scope, filesReviewed, claimsChecked, evidence, unsupportedClaims, confidence, recommendedWorkflow, notes.`,\n },\n truth_doc_reviewer: {\n codexName: \"truth_doc_reviewer\",\n copilotName: \"truth-doc-reviewer\",\n description:\n \"Read-only Truthmark doc reviewer for shape, decision, rationale, and evidence hygiene.\",\n nicknameCandidates: [\"Doc Audit\", \"Doc Shape\", \"Doc Check\"],\n instructions: `Stay read-only.\nReview assigned canonical truth docs for frontmatter, source_of_truth, required template sections, Evidence checked entries, Product Decisions, and Rationale.\nFlag README.md files used as behavior truth targets, mixed-owner docs, and shape repairs that should move to Truth Structure.\nDo not edit files, stage changes, or rewrite docs.\nReturn JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes.\nrecommendedWorkflow must be one of: none, truthmark-document, truthmark-structure.`,\n },\n} satisfies Record<TruthmarkReadOnlySubagentId, TruthmarkSubagentProfile>;\ntype TruthmarkWriteSubagentProfile = {\n codexName: string;\n copilotName: string;\n description: string;\n nicknameCandidates: string[];\n instructions: string;\n};\nconst TRUTHMARK_WRITE_SUBAGENT_PROFILES = {\n truth_doc_writer: {\n codexName: \"truth_doc_writer\",\n copilotName: \"truth-doc-writer\",\n description:\n \"Write-capable Truthmark doc worker for one parent-leased truth-document shard.\",\n nicknameCandidates: [\"Doc Writer\", \"Truth Writer\", \"Doc Sync\"],\n instructions: `Write one leased Truthmark truth-document shard assigned by the parent.\nRequire an explicit write lease before editing. The lease must name workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields.\nRead every requiredReads entry directly before editing.\nEdit only leased canonical truth docs or leased truth routing files. Do not edit functional code, generated host surfaces, package files, config files, templates, or tests unless they are explicitly leased.\nDo not expand your own write scope. If the task needs an off-lease file, stop and report blocked.\nBlock when ownership is missing or ambiguous, evidence does not support the requested claim, another worker changed the leased file, generated surfaces appear stale, or a required edit is outside the lease.\nReturn YAML only with keys: ${TRUTHMARK_WRITE_WORKER_REPORT_FIELDS.join(\", \")}.\nstatus must be completed or blocked.\nfilesChanged must list only files you actually changed.\noffLeaseChanges must be empty for completed reports.\nThe parent must validate the actual checkout diff before accepting your report.`,\n },\n} satisfies Record<TruthmarkWriteSubagentId, TruthmarkWriteSubagentProfile>;\n\nconst renderCodexReadOnlyAgent = ({\n name,\n description,\n nicknameCandidates,\n developerInstructions,\n}: {\n name: string;\n description: string;\n nicknameCandidates: string[];\n developerInstructions: string;\n}): string => {\n return `# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\nname = ${renderTomlString(name)}\ndescription = ${renderTomlString(description)}\nsandbox_mode = \"read-only\"\nnickname_candidates = ${renderTomlStringArray(nicknameCandidates)}\ndeveloper_instructions = \"\"\"\n${developerInstructions}\n\"\"\"\n`;\n};\nconst renderCodexWriteAgent = ({\n name,\n description,\n nicknameCandidates,\n developerInstructions,\n}: {\n name: string;\n description: string;\n nicknameCandidates: string[];\n developerInstructions: string;\n}): string => {\n return `# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\nname = ${renderTomlString(name)}\ndescription = ${renderTomlString(description)}\nsandbox_mode = \"workspace-write\"\nnickname_candidates = ${renderTomlStringArray(nicknameCandidates)}\ndeveloper_instructions = \"\"\"\n${developerInstructions}\n\"\"\"\n`;\n};\n\nconst renderCopilotReadOnlyAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkSubagentProfile): string => {\n const agentInstructions = renderReadOnlySubagentInstructions(instructions);\n\n return `---\nname: ${copilotName}\ndescription: ${description}\ntools: [read, search]\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\n${agentInstructions}\n`;\n};\nconst renderCopilotWriteAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkWriteSubagentProfile): string => {\n return `---\nname: ${copilotName}\ndescription: ${description}\ntools: [read, search, edit]\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\n${instructions}\n`;\n};\n\nconst renderClaudeReadOnlyAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkSubagentProfile): string => {\n const agentInstructions = renderReadOnlySubagentInstructions(instructions);\n\n return `---\nname: ${copilotName}\ndescription: ${description}\ntools: Read, Grep, Glob, LS\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: use the ${copilotName} subagent.\n\n${agentInstructions}\n`;\n};\nconst renderClaudeWriteAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkWriteSubagentProfile): string => {\n return `---\nname: ${copilotName}\ndescription: ${description}\ntools: Read, Grep, Glob, LS, Edit, MultiEdit\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: use the ${copilotName} subagent with an explicit parent write lease.\n\n${instructions}\n`;\n};\n\nexport const renderTruthmarkRouteAuditorAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor;\n\n return renderCodexReadOnlyAgent({\n name: profile.codexName,\n description: profile.description,\n nicknameCandidates: profile.nicknameCandidates,\n developerInstructions: renderReadOnlySubagentInstructions(\n profile.instructions,\n ),\n });\n};\n\nexport const renderTruthmarkClaimVerifierAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier;\n\n return renderCodexReadOnlyAgent({\n name: profile.codexName,\n description: profile.description,\n nicknameCandidates: profile.nicknameCandidates,\n developerInstructions: renderReadOnlySubagentInstructions(\n profile.instructions,\n ),\n });\n};\n\nexport const renderTruthmarkDocReviewerAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer;\n\n return renderCodexReadOnlyAgent({\n name: profile.codexName,\n description: profile.description,\n nicknameCandidates: profile.nicknameCandidates,\n developerInstructions: renderReadOnlySubagentInstructions(\n profile.instructions,\n ),\n });\n};\nexport const renderTruthmarkDocWriterAgent = (): string => {\n const profile = TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer;\n\n return renderCodexWriteAgent({\n name: profile.codexName,\n description: profile.description,\n nicknameCandidates: profile.nicknameCandidates,\n developerInstructions: profile.instructions,\n });\n};\n\nexport const renderTruthmarkCopilotRouteAuditorAgent = (): string => {\n return renderCopilotReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor,\n );\n};\n\nexport const renderTruthmarkCopilotClaimVerifierAgent = (): string => {\n return renderCopilotReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier,\n );\n};\n\nexport const renderTruthmarkCopilotDocReviewerAgent = (): string => {\n return renderCopilotReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer,\n );\n};\nexport const renderTruthmarkCopilotDocWriterAgent = (): string => {\n return renderCopilotWriteAgent(\n TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer,\n );\n};\n\nexport const renderTruthmarkClaudeRouteAuditorAgent = (): string => {\n return renderClaudeReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor,\n );\n};\n\nexport const renderTruthmarkClaudeClaimVerifierAgent = (): string => {\n return renderClaudeReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier,\n );\n};\n\nexport const renderTruthmarkClaudeDocReviewerAgent = (): string => {\n return renderClaudeReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer,\n );\n};\nexport const renderTruthmarkClaudeDocWriterAgent = (): string => {\n return renderClaudeWriteAgent(\n TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer,\n );\n};\n\nconst renderOpenCodeReadOnlyAgent = ({\n invocation,\n description,\n instructions,\n}: {\n invocation: string;\n description: string;\n instructions: string;\n}): string => {\n const agentInstructions = renderReadOnlySubagentInstructions(instructions);\n\n return `---\ndescription: ${description}\nmode: subagent\npermission:\n edit: deny\n task: deny\n webfetch: deny\n websearch: deny\n external_directory: deny\n bash:\n \"*\": ask\n \"git status*\": allow\n \"git diff*\": allow\n \"git log*\": allow\n \"rg *\": allow\n \"grep *\": allow\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: @${invocation}\n\n${agentInstructions}\n`;\n};\nconst renderOpenCodeWriteAgent = ({\n invocation,\n description,\n instructions,\n config,\n}: {\n invocation: string;\n description: string;\n instructions: string;\n config: TruthmarkConfig;\n}): string => {\n const editAllowRules = renderOpenCodeWriterEditAllowRules(config);\n\n return `---\ndescription: ${description}\nmode: subagent\npermission:\n read: allow\n list: allow\n grep: allow\n glob: allow\n edit:\n \"*\": deny\n${editAllowRules}\n task: deny\n webfetch: deny\n websearch: deny\n external_directory: deny\n bash:\n \"*\": ask\n \"git status*\": allow\n \"git diff*\": allow\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: @${invocation}\n\n${instructions}\n`;\n};\n\nexport const renderTruthmarkOpenCodeRouteAuditorAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor;\n\n return renderOpenCodeReadOnlyAgent({\n invocation: profile.copilotName,\n description: profile.description,\n instructions: profile.instructions,\n });\n};\n\nexport const renderTruthmarkOpenCodeClaimVerifierAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier;\n\n return renderOpenCodeReadOnlyAgent({\n invocation: profile.copilotName,\n description: profile.description,\n instructions: profile.instructions,\n });\n};\n\nexport const renderTruthmarkOpenCodeDocReviewerAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer;\n\n return renderOpenCodeReadOnlyAgent({\n invocation: profile.copilotName,\n description: profile.description,\n instructions: profile.instructions,\n });\n};\nexport const renderTruthmarkOpenCodeDocWriterAgent = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const profile = TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer;\n\n return renderOpenCodeWriteAgent({\n invocation: profile.copilotName,\n description: profile.description,\n instructions: profile.instructions,\n config,\n });\n};\n\nexport const renderTruthmarkStructureSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthStructureSkillBody(config);\n};\n\nexport const renderTruthmarkStructureLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthStructureSkillBody(config);\n};\n\nexport const renderTruthmarkStructureClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthStructureSkillBody(config, {\n includeClaudeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkStructureSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkDocumentSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthDocumentSkillBody(config, {\n includeCodexSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkDocumentLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthDocumentSkillBody(config);\n};\n\nexport const renderTruthmarkDocumentClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthDocumentSkillBody(config, {\n includeClaudeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkDocumentOpenCodeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthDocumentSkillBody(config, {\n includeOpenCodeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkDocumentSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-document\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkSyncSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthSyncSkillBody(config, { includeCodexSubagentMode: true });\n};\n\nexport const renderTruthmarkSyncLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthSyncSkillBody(config);\n};\n\nexport const renderTruthmarkSyncClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthSyncSkillBody(config, { includeClaudeSubagentMode: true });\n};\n\nexport const renderTruthmarkSyncOpenCodeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthSyncSkillBody(config, {\n includeOpenCodeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkSyncSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nconst renderTruthmarkRealizeSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n const workflow = getTruthmarkWorkflow(\"truthmark-realize\");\n\n return `---\nname: truthmark-realize\ndescription: ${workflow.description}\nargument-hint: Optional truth doc path, area, or desired code behavior to realize\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\n# Truthmark Realize\n\nUse this skill only when the user explicitly asks to realize truth docs into code.\n\nInvocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize.\n\nTruth Realize is doc-first:\n\n- truth docs lead\n- code follows\n- Truth Realize never edits the truth docs it is realizing\n\nWorkflow:\n\n1. Read the updated truth docs named by the user, or infer the relevant docs from ${config.docs.routing.rootIndex}.\n2. Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files, tests, and the relevant functional code.\n3. ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n${renderTruthDocOwnershipGateSection(\n \"source truth docs before writing code\",\n \"if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document\",\n)}\n4. Update functional code only so implementation matches bounded, current truth claims from the source docs.\n5. Do not edit truth docs or truth routing while realizing those docs.\n6. Run relevant tests for the changed code.\n7. Report changed code files and verification steps.\n${renderHierarchySummary(config)}\n\nRead and write boundaries:\n\n- may read truth docs, routing docs, and relevant functional code\n- may write functional code only\n- must not edit truth docs or truth routing while realizing those docs\n\nReport completion in this shape:\n\n\\`\\`\\`md\nTruth Realize: completed\n\nTruth docs used:\n- ${truthDocsRoot}/authentication/session-timeout.md\n\nCode updated:\n- src/auth/session.ts\n\nVerification:\n- npm test -- auth\n\\`\\`\\`\n`;\n};\n\nexport const renderTruthmarkRealizeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthmarkRealizeSkillBody(config);\n};\n\nexport const renderTruthmarkRealizeLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthmarkRealizeSkillBody(config);\n};\n\nexport const renderTruthmarkRealizeSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-realize\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkPreviewSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthPreviewSkillBody(config);\n};\n\nexport const renderTruthmarkPreviewLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthPreviewSkillBody(config);\n};\n\nexport const renderTruthmarkPreviewClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthPreviewSkillBody(config);\n};\n\nexport const renderTruthmarkPreviewOpenCodeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthPreviewSkillBody(config);\n};\n\nexport const renderTruthmarkPreviewSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-preview\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkCheckSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthCheckSkillBody(config, { includeCodexSubagentMode: true });\n};\n\nexport const renderTruthmarkCheckLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthCheckSkillBody(config);\n};\n\nexport const renderTruthmarkCheckClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthCheckSkillBody(config, { includeClaudeSubagentMode: true });\n};\n\nexport const renderTruthmarkCheckOpenCodeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthCheckSkillBody(config, {\n includeOpenCodeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkCheckSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-check\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkGeminiStructureCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthStructureSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiDocumentCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-document\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthDocumentSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiSyncCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthSyncSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiRealizeCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-realize\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthmarkRealizeSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiCheckCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-check\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthCheckSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiPreviewCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-preview\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthPreviewSkillBody(config),\n );\n};\n\nexport const renderTruthmarkCopilotStructurePrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthStructureSkillBody(config, {\n includeCopilotCustomAgentMode: true,\n }),\n );\n};\n\nexport const renderTruthmarkCopilotDocumentPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-document\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthDocumentSkillBody(config, {\n includeCopilotCustomAgentMode: true,\n }),\n );\n};\n\nexport const renderTruthmarkCopilotSyncPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthSyncSkillBody(config, {\n includeCopilotCustomAgentMode: true,\n }),\n );\n};\n\nexport const renderTruthmarkCopilotRealizePrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-realize\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthmarkRealizeSkillBody(config),\n );\n};\n\nexport const renderTruthmarkCopilotCheckPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-check\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthCheckSkillBody(config, {\n includeCopilotCustomAgentMode: true,\n }),\n );\n};\n\nexport const renderTruthmarkCopilotPreviewPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-preview\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthPreviewSkillBody(config),\n );\n};\n","import type { TruthmarkConfig, TruthmarkPlatform } from \"../config/schema.js\";\nimport { renderAgentsBlock } from \"./agents-block.js\";\nimport {\n renderTruthmarkCopilotCheckPrompt,\n renderTruthmarkCopilotClaimVerifierAgent,\n renderTruthmarkCopilotDocumentPrompt,\n renderTruthmarkCopilotDocReviewerAgent,\n renderTruthmarkCopilotDocWriterAgent,\n renderTruthmarkCopilotPreviewPrompt,\n renderTruthmarkCopilotRealizePrompt,\n renderTruthmarkCopilotRouteAuditorAgent,\n renderTruthmarkCopilotStructurePrompt,\n renderTruthmarkCopilotSyncPrompt,\n renderTruthmarkClaudeClaimVerifierAgent,\n renderTruthmarkClaudeDocReviewerAgent,\n renderTruthmarkClaudeDocWriterAgent,\n renderTruthmarkClaudeRouteAuditorAgent,\n renderTruthmarkClaimVerifierAgent,\n renderTruthmarkDocumentSkillMetadata,\n renderTruthmarkDocReviewerAgent,\n renderTruthmarkDocWriterAgent,\n renderTruthmarkGeminiCheckCommand,\n renderTruthmarkGeminiDocumentCommand,\n renderTruthmarkGeminiPreviewCommand,\n renderTruthmarkGeminiRealizeCommand,\n renderTruthmarkGeminiStructureCommand,\n renderTruthmarkGeminiSyncCommand,\n renderTruthmarkCheckSkillMetadata,\n renderTruthmarkOpenCodeClaimVerifierAgent,\n renderTruthmarkOpenCodeDocReviewerAgent,\n renderTruthmarkOpenCodeDocWriterAgent,\n renderTruthmarkOpenCodeRouteAuditorAgent,\n renderTruthmarkPreviewSkillMetadata,\n renderTruthmarkRealizeSkillMetadata,\n renderTruthmarkRouteAuditorAgent,\n renderTruthmarkSkillPackage,\n renderTruthmarkStructureSkillMetadata,\n renderTruthmarkSyncSkillMetadata,\n TRUTHMARK_CHECK_SKILL_METADATA_PATH,\n TRUTHMARK_CHECK_SKILL_PATH,\n TRUTHMARK_CLAUDE_CLAIM_VERIFIER_AGENT_PATH,\n TRUTHMARK_CLAUDE_DOC_REVIEWER_AGENT_PATH,\n TRUTHMARK_CLAUDE_DOC_WRITER_AGENT_PATH,\n TRUTHMARK_CLAUDE_ROUTE_AUDITOR_AGENT_PATH,\n TRUTHMARK_CLAIM_VERIFIER_AGENT_PATH,\n TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH,\n TRUTHMARK_COPILOT_CHECK_PROMPT_PATH,\n TRUTHMARK_COPILOT_DOCUMENT_PROMPT_PATH,\n TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH,\n TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH,\n TRUTHMARK_COPILOT_PREVIEW_PROMPT_PATH,\n TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH,\n TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH,\n TRUTHMARK_COPILOT_STRUCTURE_PROMPT_PATH,\n TRUTHMARK_COPILOT_SYNC_PROMPT_PATH,\n TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH,\n TRUTHMARK_DOCUMENT_SKILL_PATH,\n TRUTHMARK_DOC_REVIEWER_AGENT_PATH,\n TRUTHMARK_DOC_WRITER_AGENT_PATH,\n TRUTHMARK_GEMINI_CHECK_COMMAND_PATH,\n TRUTHMARK_GEMINI_DOCUMENT_COMMAND_PATH,\n TRUTHMARK_GEMINI_PREVIEW_COMMAND_PATH,\n TRUTHMARK_GEMINI_REALIZE_COMMAND_PATH,\n TRUTHMARK_GEMINI_STRUCTURE_COMMAND_PATH,\n TRUTHMARK_GEMINI_SYNC_COMMAND_PATH,\n TRUTHMARK_OPENCODE_CLAIM_VERIFIER_AGENT_PATH,\n TRUTHMARK_OPENCODE_DOC_REVIEWER_AGENT_PATH,\n TRUTHMARK_OPENCODE_DOC_WRITER_AGENT_PATH,\n TRUTHMARK_OPENCODE_ROUTE_AUDITOR_AGENT_PATH,\n TRUTHMARK_PREVIEW_SKILL_METADATA_PATH,\n TRUTHMARK_PREVIEW_SKILL_PATH,\n TRUTHMARK_REALIZE_SKILL_METADATA_PATH,\n TRUTHMARK_REALIZE_SKILL_PATH,\n TRUTHMARK_ROUTE_AUDITOR_AGENT_PATH,\n TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH,\n TRUTHMARK_STRUCTURE_SKILL_PATH,\n TRUTHMARK_SYNC_SKILL_METADATA_PATH,\n TRUTHMARK_SYNC_SKILL_PATH,\n} from \"./workflow-surfaces.js\";\n\nexport type GeneratedSurface = {\n path: string;\n content: string;\n managedBlock?: boolean;\n};\n\nconst codexFiles = (config: TruthmarkConfig): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_STRUCTURE_SKILL_PATH,\n workflowId: \"truthmark-structure\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH,\n content: renderTruthmarkStructureSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_DOCUMENT_SKILL_PATH,\n workflowId: \"truthmark-document\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH,\n content: renderTruthmarkDocumentSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_SYNC_SKILL_PATH,\n workflowId: \"truthmark-sync\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_SYNC_SKILL_METADATA_PATH,\n content: renderTruthmarkSyncSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_PREVIEW_SKILL_PATH,\n workflowId: \"truthmark-preview\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_PREVIEW_SKILL_METADATA_PATH,\n content: renderTruthmarkPreviewSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CHECK_SKILL_PATH,\n workflowId: \"truthmark-check\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_CHECK_SKILL_METADATA_PATH,\n content: renderTruthmarkCheckSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_REALIZE_SKILL_PATH,\n workflowId: \"truthmark-realize\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_REALIZE_SKILL_METADATA_PATH,\n content: renderTruthmarkRealizeSkillMetadata(),\n },\n {\n path: TRUTHMARK_ROUTE_AUDITOR_AGENT_PATH,\n content: renderTruthmarkRouteAuditorAgent(),\n },\n {\n path: TRUTHMARK_CLAIM_VERIFIER_AGENT_PATH,\n content: renderTruthmarkClaimVerifierAgent(),\n },\n {\n path: TRUTHMARK_DOC_REVIEWER_AGENT_PATH,\n content: renderTruthmarkDocReviewerAgent(),\n },\n {\n path: TRUTHMARK_DOC_WRITER_AGENT_PATH,\n content: renderTruthmarkDocWriterAgent(),\n },\n ];\n\n return files;\n};\n\nconst opencodeFiles = (config: TruthmarkConfig): GeneratedSurface[] => {\n return [\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-structure/SKILL.md\",\n workflowId: \"truthmark-structure\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-document/SKILL.md\",\n workflowId: \"truthmark-document\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-sync/SKILL.md\",\n workflowId: \"truthmark-sync\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-preview/SKILL.md\",\n workflowId: \"truthmark-preview\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-check/SKILL.md\",\n workflowId: \"truthmark-check\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-realize/SKILL.md\",\n workflowId: \"truthmark-realize\",\n host: \"opencode\",\n config,\n }),\n {\n path: TRUTHMARK_OPENCODE_ROUTE_AUDITOR_AGENT_PATH,\n content: renderTruthmarkOpenCodeRouteAuditorAgent(),\n },\n {\n path: TRUTHMARK_OPENCODE_CLAIM_VERIFIER_AGENT_PATH,\n content: renderTruthmarkOpenCodeClaimVerifierAgent(),\n },\n {\n path: TRUTHMARK_OPENCODE_DOC_REVIEWER_AGENT_PATH,\n content: renderTruthmarkOpenCodeDocReviewerAgent(),\n },\n {\n path: TRUTHMARK_OPENCODE_DOC_WRITER_AGENT_PATH,\n content: renderTruthmarkOpenCodeDocWriterAgent(config),\n },\n ];\n};\n\nconst claudeFiles = (\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n return [\n ...instructionBlockFiles([\"CLAUDE.md\"], block),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-structure/SKILL.md\",\n workflowId: \"truthmark-structure\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-document/SKILL.md\",\n workflowId: \"truthmark-document\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-sync/SKILL.md\",\n workflowId: \"truthmark-sync\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-preview/SKILL.md\",\n workflowId: \"truthmark-preview\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-check/SKILL.md\",\n workflowId: \"truthmark-check\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-realize/SKILL.md\",\n workflowId: \"truthmark-realize\",\n host: \"claude-code\",\n config,\n }),\n {\n path: TRUTHMARK_CLAUDE_ROUTE_AUDITOR_AGENT_PATH,\n content: renderTruthmarkClaudeRouteAuditorAgent(),\n },\n {\n path: TRUTHMARK_CLAUDE_CLAIM_VERIFIER_AGENT_PATH,\n content: renderTruthmarkClaudeClaimVerifierAgent(),\n },\n {\n path: TRUTHMARK_CLAUDE_DOC_REVIEWER_AGENT_PATH,\n content: renderTruthmarkClaudeDocReviewerAgent(),\n },\n {\n path: TRUTHMARK_CLAUDE_DOC_WRITER_AGENT_PATH,\n content: renderTruthmarkClaudeDocWriterAgent(),\n },\n ];\n};\n\nconst copilotFiles = (\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n ...instructionBlockFiles([\".github/copilot-instructions.md\"], block),\n {\n path: TRUTHMARK_COPILOT_STRUCTURE_PROMPT_PATH,\n content: renderTruthmarkCopilotStructurePrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_DOCUMENT_PROMPT_PATH,\n content: renderTruthmarkCopilotDocumentPrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_SYNC_PROMPT_PATH,\n content: renderTruthmarkCopilotSyncPrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_PREVIEW_PROMPT_PATH,\n content: renderTruthmarkCopilotPreviewPrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_CHECK_PROMPT_PATH,\n content: renderTruthmarkCopilotCheckPrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH,\n content: renderTruthmarkCopilotRealizePrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH,\n content: renderTruthmarkCopilotRouteAuditorAgent(),\n },\n {\n path: TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH,\n content: renderTruthmarkCopilotClaimVerifierAgent(),\n },\n {\n path: TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH,\n content: renderTruthmarkCopilotDocReviewerAgent(),\n },\n {\n path: TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH,\n content: renderTruthmarkCopilotDocWriterAgent(),\n },\n ];\n\n return files;\n};\n\nconst instructionBlockFiles = (\n paths: string[],\n block: string,\n): GeneratedSurface[] => {\n return paths.map((path) => ({\n path,\n content: block,\n managedBlock: true,\n }));\n};\n\nconst filesForPlatform = (\n platform: TruthmarkPlatform,\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n switch (platform) {\n case \"codex\":\n return codexFiles(config);\n case \"opencode\":\n return opencodeFiles(config);\n case \"claude-code\":\n return claudeFiles(config, block);\n case \"github-copilot\":\n return copilotFiles(config, block);\n case \"gemini-cli\":\n return [\n ...instructionBlockFiles([\"GEMINI.md\"], block),\n {\n path: TRUTHMARK_GEMINI_STRUCTURE_COMMAND_PATH,\n content: renderTruthmarkGeminiStructureCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_DOCUMENT_COMMAND_PATH,\n content: renderTruthmarkGeminiDocumentCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_SYNC_COMMAND_PATH,\n content: renderTruthmarkGeminiSyncCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_PREVIEW_COMMAND_PATH,\n content: renderTruthmarkGeminiPreviewCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_CHECK_COMMAND_PATH,\n content: renderTruthmarkGeminiCheckCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_REALIZE_COMMAND_PATH,\n content: renderTruthmarkGeminiRealizeCommand(config),\n },\n ];\n }\n};\n\nexport const renderGeneratedSurfaces = (\n config: TruthmarkConfig,\n block = renderAgentsBlock(config),\n): GeneratedSurface[] => {\n const files = [\n ...instructionBlockFiles(config.instructionTargets, block),\n ...config.platforms.flatMap((platform) =>\n filesForPlatform(platform, config, block),\n ),\n ];\n\n return Array.from(\n new Map(files.map((file) => [file.path, file])).values(),\n ).sort((left, right) => left.path.localeCompare(right.path));\n};\n","import fs from \"node:fs/promises\";\n\nimport fg from \"fast-glob\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport { DEFAULT_DOCS_HIERARCHY } from \"../config/defaults.js\";\nimport { resolveWorktreePath, getGitRepository } from \"../git/repository.js\";\nimport { hashText } from \"../markdown/hash.js\";\n\nexport type BranchScopeData = {\n repositoryRoot: string;\n worktreePath: string;\n branchName: string | null;\n headSha: string | null;\n identity: string;\n relevantFileHashes: Record<string, string>;\n};\n\nexport class BranchScopeFileError extends Error {\n file: string;\n\n constructor(file: string, message: string) {\n super(message);\n this.name = \"BranchScopeFileError\";\n this.file = file;\n }\n}\n\nconst RELEVANT_BRANCH_SCOPE_FILES = [\".truthmark/config.yml\"] as const;\n\nconst toBranchIdentity = (branchName: string | null, headSha: string | null): string => {\n if (branchName && headSha) {\n return `${branchName}@${headSha}`;\n }\n\n if (branchName) {\n return `unborn:${branchName}`;\n }\n\n return headSha ? `detached:${headSha}` : \"detached:unknown\";\n};\n\nexport const createBranchScopeData = (\n repository: {\n repositoryRoot: string;\n worktreePath: string;\n branchName: string | null;\n headSha: string | null;\n },\n relevantFileHashes: Record<string, string> = {},\n): BranchScopeData => {\n return {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n headSha: repository.headSha,\n identity: toBranchIdentity(repository.branchName, repository.headSha),\n relevantFileHashes,\n };\n};\n\nexport const getBranchScopeData = async (cwd: string): Promise<BranchScopeData> => {\n const repository = await getGitRepository(cwd);\n const relevantFileHashes: Record<string, string> = {};\n const loadResult = await loadConfig(repository.worktreePath);\n const rootIndex =\n loadResult.config?.docs.routing.rootIndex ?? DEFAULT_DOCS_HIERARCHY.routing.root_index;\n const areaFilesRoot =\n loadResult.config?.docs.routing.areaFilesRoot ?? DEFAULT_DOCS_HIERARCHY.routing.area_files_root;\n const relevantFiles = new Set<string>([...RELEVANT_BRANCH_SCOPE_FILES, rootIndex]);\n const routeFiles = await fg([`${areaFilesRoot}/**/*.md`], {\n cwd: repository.worktreePath,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n\n for (const routeFile of routeFiles) {\n relevantFiles.add(routeFile);\n }\n\n for (const relativePath of [...relevantFiles].sort()) {\n try {\n const source = await fs.readFile(resolveWorktreePath(repository, relativePath), \"utf8\");\n\n relevantFileHashes[relativePath] = hashText(source);\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n continue;\n }\n\n const detail = error instanceof Error ? error.message : \"unknown error\";\n\n throw new BranchScopeFileError(\n relativePath,\n `Branch-scope file ${relativePath} could not be read safely: ${detail}`,\n );\n }\n }\n\n return createBranchScopeData(repository, relevantFileHashes);\n};\n","import { createHash } from \"node:crypto\";\n\nconst toStableValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => toStableValue(entry));\n }\n\n if (value && typeof value === \"object\") {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((stable, key) => {\n stable[key] = toStableValue((value as Record<string, unknown>)[key]);\n return stable;\n }, {});\n }\n\n return value;\n};\n\nexport const hashText = (value: string): string => {\n return createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n};\n\nexport const hashJsonLike = (value: unknown): string => {\n return hashText(JSON.stringify(toStableValue(value)));\n};","import fs from \"node:fs/promises\";\n\nimport fg from \"fast-glob\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\n\nconst looksLikeGlob = (pattern: string): boolean => {\n return /[*?[\\]{}()!+@]/u.test(pattern);\n};\n\nconst pathExists = async (absolutePath: string): Promise<boolean> => {\n try {\n await fs.stat(absolutePath);\n return true;\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n\n throw error;\n }\n};\n\nexport type AuthorityCheckResult = {\n paths: string[];\n diagnostics: Diagnostic[];\n};\n\nexport const checkAuthority = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<AuthorityCheckResult> => {\n const diagnostics: Diagnostic[] = [];\n const orderedPaths: string[] = [];\n const seenPaths = new Set<string>();\n\n for (const entry of config.authority) {\n if (looksLikeGlob(entry)) {\n try {\n resolveRepoPath(rootDir, entry);\n } catch {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Authority entry ${entry} must stay inside the repository root.`,\n file: entry,\n });\n continue;\n }\n\n const matches = (await fg([entry], { cwd: rootDir, onlyFiles: true })).sort();\n\n if (matches.length === 0) {\n diagnostics.push({\n category: \"authority\",\n severity: \"review\",\n message: `Authority glob ${entry} did not match any files.`,\n file: entry,\n });\n }\n\n for (const match of matches) {\n try {\n const absoluteMatchPath = resolveRepoPath(rootDir, match);\n await assertRepoContainment(rootDir, absoluteMatchPath);\n } catch {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Authority path ${match} must stay inside the repository root.`,\n file: match,\n });\n continue;\n }\n\n if (!seenPaths.has(match)) {\n seenPaths.add(match);\n orderedPaths.push(match);\n }\n }\n\n continue;\n }\n\n let absoluteEntryPath: string;\n\n try {\n absoluteEntryPath = resolveRepoPath(rootDir, entry);\n await assertRepoContainment(rootDir, absoluteEntryPath);\n } catch {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Authority entry ${entry} must stay inside the repository root.`,\n file: entry,\n });\n continue;\n }\n\n if (!(await pathExists(absoluteEntryPath))) {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Missing authority file ${entry}.`,\n file: entry,\n });\n continue;\n }\n\n if (!seenPaths.has(entry)) {\n seenPaths.add(entry);\n orderedPaths.push(entry);\n }\n }\n\n return {\n paths: orderedPaths,\n diagnostics,\n };\n};\n","import fs from \"node:fs/promises\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n TRUTH_DOCUMENT_KINDS,\n type TruthDocumentEntry,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\n\nconst isTruthDocumentKind = (\n value: string,\n): value is TruthDocumentKind =>\n TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind);\n\nexport const checkFrontmatter = async (\n rootDir: string,\n config: TruthmarkConfig,\n markdownPaths: string[],\n truthDocumentEntries: TruthDocumentEntry[] = [],\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n const truthDocumentMap = new Map(\n truthDocumentEntries.map((entry) => [entry.path, entry]),\n );\n\n for (const markdownPath of markdownPaths) {\n if (!markdownPath.endsWith(\".md\")) {\n continue;\n }\n\n const absolutePath = resolveRepoPath(rootDir, markdownPath);\n\n await assertRepoContainment(rootDir, absolutePath);\n\n const source = await fs.readFile(absolutePath, \"utf8\");\n let document;\n\n try {\n document = parseMarkdownDocument(source);\n } catch (error: unknown) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Invalid frontmatter: ${error instanceof Error ? error.message : String(error)}`,\n file: markdownPath,\n });\n continue;\n }\n\n for (const field of config.frontmatter.required) {\n if (!(field in document.frontmatter)) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Missing required frontmatter field ${field}.`,\n file: markdownPath,\n });\n }\n }\n\n for (const field of config.frontmatter.recommended) {\n if (!(field in document.frontmatter)) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"review\",\n message: `Missing recommended frontmatter field ${field}.`,\n file: markdownPath,\n });\n }\n }\n\n const routedTruthDocument = truthDocumentMap.get(markdownPath);\n const truthKind = document.frontmatter.truth_kind;\n\n if (truthKind !== undefined) {\n if (typeof truthKind !== \"string\" || !isTruthDocumentKind(truthKind)) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Frontmatter truth_kind must be one of ${TRUTH_DOCUMENT_KINDS.join(\", \")}.`,\n file: markdownPath,\n });\n continue;\n }\n\n if (\n routedTruthDocument &&\n routedTruthDocument.kindSource !== \"defaulted\" &&\n truthKind !== routedTruthDocument.kind\n ) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Frontmatter truth_kind ${truthKind} must match routed truth kind ${routedTruthDocument.kind}.`,\n file: markdownPath,\n });\n }\n }\n }\n\n return diagnostics;\n};","import matter from \"gray-matter\";\nimport { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport { visit } from \"unist-util-visit\";\n\ntype Heading = {\n depth: number;\n text: string;\n};\n\nexport type ParsedMarkdownDocument = {\n frontmatter: Record<string, unknown>;\n headings: Heading[];\n internalLinks: string[];\n};\n\ntype MdastNode = {\n type: string;\n depth?: number;\n url?: string;\n value?: string;\n children?: MdastNode[];\n};\n\nconst extractText = (node: MdastNode): string => {\n if (typeof node.value === \"string\") {\n return node.value;\n }\n\n return (node.children ?? []).map((child) => extractText(child)).join(\"\").trim();\n};\n\nconst isInternalLink = (url: string): boolean => {\n return url.startsWith(\"#\") || (!url.includes(\"://\") && !url.startsWith(\"mailto:\"));\n};\n\nexport const parseMarkdownDocument = (source: string): ParsedMarkdownDocument => {\n const parsed = matter(source);\n const tree = unified().use(remarkParse).parse(parsed.content) as MdastNode;\n const headings: Heading[] = [];\n const internalLinks: string[] = [];\n\n visit(tree, (node: MdastNode) => {\n if (node.type === \"heading\" && typeof node.depth === \"number\") {\n headings.push({\n depth: node.depth,\n text: extractText(node),\n });\n }\n\n if (node.type === \"link\" && typeof node.url === \"string\" && isInternalLink(node.url)) {\n internalLinks.push(node.url);\n }\n });\n\n return {\n frontmatter: parsed.data,\n headings,\n internalLinks,\n };\n};","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { assertRepoContainment, resolveRepoPath, toRepoRelativePath } from \"../fs/paths.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\n\nconst pathExists = async (absolutePath: string): Promise<boolean> => {\n try {\n await fs.stat(absolutePath);\n return true;\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n\n throw error;\n }\n};\n\nexport const checkLinks = async (\n rootDir: string,\n markdownPaths: string[],\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n\n for (const markdownPath of markdownPaths) {\n if (!markdownPath.endsWith(\".md\")) {\n continue;\n }\n\n const absolutePath = resolveRepoPath(rootDir, markdownPath);\n const source = await fs.readFile(absolutePath, \"utf8\");\n let document;\n\n try {\n document = parseMarkdownDocument(source);\n } catch {\n continue;\n }\n\n for (const link of document.internalLinks) {\n if (link.startsWith(\"#\")) {\n continue;\n }\n\n const targetPath = link.split(\"#\")[0] ?? \"\";\n\n if (targetPath.length === 0) {\n continue;\n }\n\n const absoluteTarget = path.resolve(path.dirname(absolutePath), targetPath);\n const relativeTarget = toRepoRelativePath(rootDir, absoluteTarget);\n\n try {\n await assertRepoContainment(rootDir, absoluteTarget);\n } catch {\n diagnostics.push({\n category: \"links\",\n severity: \"error\",\n message: `Internal link to ${relativeTarget} must stay inside the repository root.`,\n file: markdownPath,\n });\n continue;\n }\n\n if (!(await pathExists(absoluteTarget))) {\n diagnostics.push({\n category: \"links\",\n severity: \"error\",\n message: `Broken internal link to ${relativeTarget}.`,\n file: markdownPath,\n });\n }\n }\n }\n\n return diagnostics;\n};","import fs from \"node:fs/promises\";\n\nimport fg from \"fast-glob\";\nimport micromatch from \"micromatch\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport { resolveAreaRouting } from \"../routing/area-resolver.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport type { TruthDocumentEntry } from \"../routing/areas.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\n\nexport type AreasCheckResult = {\n diagnostics: Diagnostic[];\n truthDocumentPaths: string[];\n truthDocumentEntries: TruthDocumentEntry[];\n routePrecision: {\n leafAreaCount: number;\n broadAreaCount: number;\n };\n topologyPressureCount: number;\n};\n\nconst looksLikeGlob = (pattern: string): boolean => {\n return /[*?[\\]{}()!+@]/u.test(pattern);\n};\n\nconst pathExists = async (absolutePath: string): Promise<boolean> => {\n try {\n await fs.stat(absolutePath);\n return true;\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n\n throw error;\n }\n};\n\nconst COVERAGE_SCAN_PATTERNS = [\n \"app/**/*\",\n \"api/**/*\",\n \"apps/**/*\",\n \"bin/**/*\",\n \"client/**/*\",\n \"cmd/**/*\",\n \"frontend/**/*\",\n \"infra/**/*\",\n \"infrastructure/**/*\",\n \"internal/**/*\",\n \"k8s/**/*\",\n \"kubernetes/**/*\",\n \"lib/**/*\",\n \"packages/**/*\",\n \"pkg/**/*\",\n \"proto/**/*\",\n \"schema/**/*\",\n \"schemas/**/*\",\n \"scripts/**/*\",\n \"server/**/*\",\n \"services/**/*\",\n \"src/**/*\",\n \"terraform/**/*\",\n \"web/**/*\",\n \".github/workflows/**/*\",\n] as const;\n\nconst BROAD_CODE_SURFACES = new Set([\n \"app/**\",\n \"apps/**\",\n \"server/**\",\n \"services/**\",\n \"src/**\",\n \"packages/**\",\n]);\n\nconst isBroadCodeSurface = (pattern: string): boolean => {\n return BROAD_CODE_SURFACES.has(pattern.replace(/\\/\\*\\*\\/\\*$/u, \"/**\"));\n};\n\nexport const checkAreas = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<AreasCheckResult> => {\n const routing = await resolveAreaRouting(rootDir, {\n rootIndex: config.docs.routing.rootIndex,\n areaFilesRoot: config.docs.routing.areaFilesRoot,\n truthDocsRoot: resolveTruthDocsRoot(config),\n });\n\n const discoveredCodeFiles = await fg([...COVERAGE_SCAN_PATTERNS], {\n cwd: rootDir,\n onlyFiles: true,\n ignore: config.ignore,\n followSymbolicLinks: false,\n dot: true,\n });\n const rawCodeFiles = discoveredCodeFiles.filter(\n (filePath) => classifyPath(filePath, config.ignore) === \"functional-code\",\n );\n const diagnostics: Diagnostic[] = [...routing.diagnostics];\n const truthDocumentPaths: string[] = [];\n const seenTruthDocumentPaths = new Set<string>();\n const truthDocumentEntryMap = new Map<string, TruthDocumentEntry>();\n const areaCoverage = routing.areas.map((area) => ({\n area,\n valid: true,\n patterns: [] as string[],\n }));\n const codeFiles: string[] = [];\n\n for (const codeFile of rawCodeFiles.sort()) {\n try {\n await assertRepoContainment(rootDir, resolveRepoPath(rootDir, codeFile));\n codeFiles.push(codeFile);\n } catch {\n continue;\n }\n }\n\n const truthReferences = routing.truthDocumentReferences;\n\n for (const area of truthReferences) {\n let areaHasTruthDocumentErrors = false;\n const registerTruthDocumentEntry = (truthDocumentEntry: TruthDocumentEntry): boolean => {\n const existingEntry = truthDocumentEntryMap.get(truthDocumentEntry.path);\n\n if (existingEntry && existingEntry.kind !== truthDocumentEntry.kind) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document ${truthDocumentEntry.path} is routed with conflicting kinds ${existingEntry.kind} and ${truthDocumentEntry.kind}.`,\n area: area.name,\n file: truthDocumentEntry.path,\n });\n return false;\n }\n\n if (!existingEntry) {\n truthDocumentEntryMap.set(truthDocumentEntry.path, truthDocumentEntry);\n }\n\n return true;\n };\n\n for (const truthDocument of area.truthDocuments) {\n if (looksLikeGlob(truthDocument)) {\n const routedGlobEntry = area.truthDocumentEntries.find(\n (entry) => entry.path === truthDocument,\n );\n const matches = (await fg([truthDocument], { cwd: rootDir, onlyFiles: true })).sort();\n\n if (matches.length === 0) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document glob ${truthDocument} did not match any files.`,\n area: area.name,\n file: truthDocument,\n });\n areaHasTruthDocumentErrors = true;\n continue;\n }\n\n for (const match of matches) {\n try {\n const absoluteMatchPath = resolveRepoPath(rootDir, match);\n await assertRepoContainment(rootDir, absoluteMatchPath);\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document ${match} must stay inside the repository root.`,\n area: area.name,\n file: match,\n });\n areaHasTruthDocumentErrors = true;\n continue;\n }\n\n if (!seenTruthDocumentPaths.has(match)) {\n seenTruthDocumentPaths.add(match);\n truthDocumentPaths.push(match);\n }\n if (\n routedGlobEntry &&\n !registerTruthDocumentEntry({\n ...routedGlobEntry,\n path: match,\n })\n ) {\n areaHasTruthDocumentErrors = true;\n }\n }\n\n continue;\n }\n\n let absoluteTruthDocumentPath: string;\n\n try {\n absoluteTruthDocumentPath = resolveRepoPath(rootDir, truthDocument);\n await assertRepoContainment(rootDir, absoluteTruthDocumentPath);\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document ${truthDocument} must stay inside the repository root.`,\n area: area.name,\n file: truthDocument,\n });\n areaHasTruthDocumentErrors = true;\n continue;\n }\n\n if (!(await pathExists(absoluteTruthDocumentPath))) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Missing truth document ${truthDocument}.`,\n area: area.name,\n file: truthDocument,\n });\n areaHasTruthDocumentErrors = true;\n continue;\n }\n\n if (!seenTruthDocumentPaths.has(truthDocument)) {\n seenTruthDocumentPaths.add(truthDocument);\n truthDocumentPaths.push(truthDocument);\n }\n\n const routedEntry = area.truthDocumentEntries.find((entry) => entry.path === truthDocument);\n\n if (routedEntry && !registerTruthDocumentEntry(routedEntry)) {\n areaHasTruthDocumentErrors = true;\n }\n }\n\n if (areaHasTruthDocumentErrors) {\n const matchingArea = areaCoverage.find(\n (entry) =>\n entry.area.name === area.name &&\n entry.area.truthDocuments.length === area.truthDocuments.length &&\n entry.area.truthDocuments.every(\n (truthDocument, index) => truthDocument === area.truthDocuments[index],\n ),\n );\n if (matchingArea) {\n matchingArea.valid = false;\n }\n }\n }\n\n for (const entry of areaCoverage) {\n const { area } = entry;\n for (const codeSurfaceEntry of area.codeSurface) {\n if (looksLikeGlob(codeSurfaceEntry)) {\n try {\n resolveRepoPath(rootDir, codeSurfaceEntry);\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Code surface ${codeSurfaceEntry} must stay inside the repository root.`,\n area: area.name,\n file: codeSurfaceEntry,\n });\n entry.valid = false;\n continue;\n }\n\n const matches = await fg([codeSurfaceEntry], {\n cwd: rootDir,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n\n let containedMatches = 0;\n\n for (const match of matches) {\n try {\n await assertRepoContainment(rootDir, resolveRepoPath(rootDir, match));\n containedMatches += 1;\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Code surface ${match} must stay inside the repository root.`,\n area: area.name,\n file: match,\n });\n }\n }\n\n if (containedMatches === 0) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"review\",\n message: `Code surface glob ${codeSurfaceEntry} did not match any files.`,\n area: area.name,\n file: codeSurfaceEntry,\n });\n } else {\n entry.patterns.push(codeSurfaceEntry);\n }\n\n continue;\n }\n\n let absoluteCodeSurfacePath: string;\n\n try {\n absoluteCodeSurfacePath = resolveRepoPath(rootDir, codeSurfaceEntry);\n await assertRepoContainment(rootDir, absoluteCodeSurfacePath);\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Code surface ${codeSurfaceEntry} must stay inside the repository root.`,\n area: area.name,\n file: codeSurfaceEntry,\n });\n entry.valid = false;\n continue;\n }\n\n if (!(await pathExists(absoluteCodeSurfacePath))) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Missing code surface file ${codeSurfaceEntry}.`,\n area: area.name,\n file: codeSurfaceEntry,\n });\n continue;\n }\n\n entry.patterns.push(codeSurfaceEntry);\n }\n }\n\n for (const codeFile of codeFiles.sort()) {\n const matched = areaCoverage.some(\n (entry) =>\n entry.valid && entry.patterns.some((pattern) => micromatch.isMatch(codeFile, pattern)),\n );\n\n if (!matched) {\n diagnostics.push({\n category: \"coverage\",\n severity: \"review\",\n message: `Code file ${codeFile} is not covered by any Truthmark area mapping.`,\n file: codeFile,\n });\n }\n }\n\n const broadAreaCount = routing.areas.filter((area) =>\n area.codeSurface.some((pattern) => isBroadCodeSurface(pattern)),\n ).length;\n const topologyPressureCount =\n broadAreaCount +\n diagnostics.filter(\n (diagnostic) => diagnostic.category === \"area-index\" && diagnostic.severity === \"review\",\n ).length;\n\n return {\n diagnostics,\n truthDocumentPaths,\n truthDocumentEntries: [...truthDocumentEntryMap.values()],\n routePrecision: {\n leafAreaCount: routing.areas.length,\n broadAreaCount,\n },\n topologyPressureCount,\n };\n};\n","import fs from \"node:fs/promises\";\n\nimport fg from \"fast-glob\";\nimport micromatch from \"micromatch\";\n\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n parseAreasMarkdown,\n type TruthArea,\n type TruthAreaReference,\n} from \"./areas.js\";\n\nexport type AreaRoutingConfig = {\n rootIndex: string;\n areaFilesRoot: string;\n truthDocsRoot?: string;\n};\n\nexport type ResolvedTruthArea = TruthArea & {\n sourcePath: string;\n parentName?: string;\n};\n\nexport type ResolvedAreaRouting = {\n areas: ResolvedTruthArea[];\n truthDocumentReferences: TruthAreaReference[];\n truthDocumentPaths: string[];\n routeFiles: string[];\n diagnostics: Diagnostic[];\n};\n\nconst unique = (values: string[]): string[] => {\n return [...new Set(values)];\n};\n\nconst normalizeGlobPath = (value: string): string => {\n return value.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/u, \"\");\n};\n\nconst concretePrefix = (pattern: string): string => {\n const normalizedPattern = normalizeGlobPath(pattern);\n const wildcardIndex = normalizedPattern.search(/[*?[{(!+@]/u);\n const prefix = wildcardIndex === -1 ? normalizedPattern : normalizedPattern.slice(0, wildcardIndex);\n\n return prefix.replace(/[^/]*$/u, \"\");\n};\n\nconst isCodeSurfaceWithinParent = (childPattern: string, parentPatterns: string[]): boolean => {\n const childPrefix = concretePrefix(childPattern);\n\n if (childPrefix.length === 0) {\n return false;\n }\n\n return parentPatterns.some((parentPattern) => {\n return micromatch.isMatch(childPrefix, parentPattern) || micromatch.isMatch(childPattern, parentPattern);\n });\n};\n\nconst ensureChildPath = async (\n rootDir: string,\n areaFilesRoot: string,\n filePath: string,\n): Promise<Diagnostic | null> => {\n try {\n const absoluteChild = resolveRepoPath(rootDir, filePath);\n const absoluteRoot = resolveRepoPath(rootDir, areaFilesRoot);\n await assertRepoContainment(rootDir, absoluteChild);\n await assertRepoContainment(rootDir, absoluteRoot);\n\n if (!absoluteChild.startsWith(`${absoluteRoot}/`)) {\n return {\n category: \"area-index\",\n severity: \"error\",\n message: `Area file ${filePath} must live under ${areaFilesRoot}.`,\n file: filePath,\n };\n }\n } catch {\n return {\n category: \"area-index\",\n severity: \"error\",\n message: `Area file ${filePath} must stay inside the repository root.`,\n file: filePath,\n };\n }\n\n return null;\n};\n\nconst readRouteFile = async (\n rootDir: string,\n filePath: string,\n): Promise<{ source: string | null; diagnostic: Diagnostic | null }> => {\n try {\n return {\n source: await fs.readFile(resolveRepoPath(rootDir, filePath), \"utf8\"),\n diagnostic: null,\n };\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return {\n source: null,\n diagnostic: {\n category: \"area-index\",\n severity: \"error\",\n message: `Missing area file ${filePath}.`,\n file: filePath,\n },\n };\n }\n\n throw error;\n }\n};\n\nexport const resolveAreaRouting = async (\n rootDir: string,\n config: AreaRoutingConfig,\n): Promise<ResolvedAreaRouting> => {\n const diagnostics: Diagnostic[] = [];\n const routeFiles = [config.rootIndex];\n const areas: ResolvedTruthArea[] = [];\n const truthDocumentReferences: TruthAreaReference[] = [];\n const truthDocumentPaths: string[] = [];\n const rootRead = await readRouteFile(rootDir, config.rootIndex);\n\n if (rootRead.diagnostic) {\n return {\n areas,\n truthDocumentReferences,\n truthDocumentPaths,\n routeFiles,\n diagnostics: [rootRead.diagnostic],\n };\n }\n\n const rootParsed = parseAreasMarkdown(rootRead.source ?? \"\", {\n truthDocsRoot: config.truthDocsRoot,\n });\n diagnostics.push(\n ...rootParsed.diagnostics.map((diagnostic) => ({\n ...diagnostic,\n file: diagnostic.file ?? config.rootIndex,\n })),\n );\n truthDocumentReferences.push(...rootParsed.truthDocumentReferences);\n areas.push(...rootParsed.areas.map((area) => ({ ...area, sourcePath: config.rootIndex })));\n\n const referencedChildFiles = new Set<string>();\n\n for (const area of rootParsed.areaFileReferences) {\n for (const areaFile of area.areaFiles) {\n if (referencedChildFiles.has(areaFile)) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Area file ${areaFile} is referenced more than once.`,\n file: areaFile,\n area: area.name,\n });\n }\n\n referencedChildFiles.add(areaFile);\n }\n }\n\n for (const area of rootParsed.areaFileReferences) {\n for (const areaFile of area.areaFiles) {\n const childPathDiagnostic = await ensureChildPath(rootDir, config.areaFilesRoot, areaFile);\n\n if (childPathDiagnostic) {\n diagnostics.push(childPathDiagnostic);\n continue;\n }\n\n const childRead = await readRouteFile(rootDir, areaFile);\n\n if (childRead.diagnostic) {\n diagnostics.push(childRead.diagnostic);\n continue;\n }\n\n routeFiles.push(areaFile);\n const childParsed = parseAreasMarkdown(childRead.source ?? \"\", {\n truthDocsRoot: config.truthDocsRoot,\n });\n diagnostics.push(\n ...childParsed.diagnostics.map((diagnostic) => ({\n ...diagnostic,\n file: diagnostic.file ?? areaFile,\n })),\n );\n truthDocumentReferences.push(...childParsed.truthDocumentReferences);\n\n if (childParsed.areaFileReferences.length > 0) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: \"Child area files must contain leaf areas only.\",\n file: areaFile,\n area: area.name,\n });\n continue;\n }\n\n areas.push(\n ...childParsed.areas.map((childArea) => {\n for (const childCodeSurface of childArea.codeSurface) {\n if (!isCodeSurfaceWithinParent(childCodeSurface, area.codeSurface)) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"review\",\n message: `Child code surface ${childCodeSurface} is outside parent area ${area.name} code surface.`,\n file: areaFile,\n area: childArea.name,\n });\n }\n }\n\n return {\n ...childArea,\n sourcePath: areaFile,\n parentName: area.name,\n };\n }),\n );\n }\n }\n\n const routeFilesUnderRoot = await fg([`${config.areaFilesRoot}/**/*.md`], {\n cwd: rootDir,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n\n for (const routeFile of routeFilesUnderRoot.sort()) {\n if (!referencedChildFiles.has(routeFile)) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"review\",\n message: `Area file ${routeFile} is not referenced by the root route index.`,\n file: routeFile,\n });\n }\n }\n\n const areaKeys = new Map<string, ResolvedTruthArea>();\n\n for (const area of areas) {\n const existingArea = areaKeys.get(area.key);\n\n if (existingArea) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Duplicate area key ${area.key} appears in ${existingArea.name} and ${area.name}.`,\n area: area.name,\n });\n continue;\n }\n\n areaKeys.set(area.key, area);\n }\n\n for (const area of areas) {\n truthDocumentPaths.push(...area.truthDocuments);\n }\n\n return {\n areas,\n truthDocumentReferences,\n truthDocumentPaths: unique(truthDocumentPaths),\n routeFiles: unique(routeFiles),\n diagnostics,\n };\n};\n","import micromatch from \"micromatch\";\n\nexport type PathClassification =\n | \"functional-code\"\n | \"markdown\"\n | \"config\"\n | \"ignored\"\n | \"derived\"\n | \"other\";\n\nconst CODE_EXTENSIONS = new Set([\n \".c\",\n \".cc\",\n \".cpp\",\n \".cs\",\n \".cts\",\n \".cjs\",\n \".ex\",\n \".exs\",\n \".gql\",\n \".go\",\n \".graphql\",\n \".h\",\n \".hpp\",\n \".hrl\",\n \".java\",\n \".js\",\n \".jsx\",\n \".kt\",\n \".kts\",\n \".lua\",\n \".mjs\",\n \".mts\",\n \".php\",\n \".proto\",\n \".py\",\n \".rb\",\n \".rs\",\n \".scala\",\n \".sh\",\n \".swift\",\n \".tf\",\n \".tfvars\",\n \".ts\",\n \".tsx\",\n]);\n\nconst CONFIG_EXTENSIONS = new Set([\n \".cfg\",\n \".conf\",\n \".env\",\n \".ini\",\n \".json\",\n \".jsonc\",\n \".toml\",\n \".yaml\",\n \".yml\",\n]);\n\nconst CONFIG_BASENAMES = new Set([\n \".editorconfig\",\n \".gitattributes\",\n \".gitignore\",\n \"Dockerfile\",\n \"package-lock.json\",\n \"package.json\",\n \"pnpm-lock.yaml\",\n \"tsconfig.json\",\n \"yarn.lock\",\n]);\n\nconst CONFIG_SUFFIXES = [\n \".config.cjs\",\n \".config.js\",\n \".config.mjs\",\n \".config.ts\",\n \".config.tsx\",\n \".config.jsx\",\n];\n\nconst COMMON_CODE_DIRECTORIES =\n /(^|\\/)(api|app|apps|bin|client|cmd|components|frontend|infra|infrastructure|k8s|kubernetes|lib|packages|proto|schema|schemas|scripts|server|services|src|terraform|web)\\//u;\nconst FUNCTIONAL_CONFIG_DIRECTORIES =\n /(^|\\/)(api|infra|infrastructure|k8s|kubernetes|schema|schemas|terraform)\\//u;\nconst FUNCTIONAL_CONFIG_BASENAMES = new Set([\n \"openapi.json\",\n \"openapi.yaml\",\n \"openapi.yml\",\n \"swagger.json\",\n \"swagger.yaml\",\n \"swagger.yml\",\n]);\n\nconst normalizePath = (filePath: string): string => {\n return filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\//u, \"\");\n};\n\nconst getBaseName = (filePath: string): string => {\n const segments = normalizePath(filePath).split(\"/\");\n\n return segments.at(-1) ?? filePath;\n};\n\nconst getExtension = (filePath: string): string => {\n const baseName = getBaseName(filePath);\n const extensionIndex = baseName.lastIndexOf(\".\");\n\n if (extensionIndex <= 0) {\n return \"\";\n }\n\n return baseName.slice(extensionIndex).toLowerCase();\n};\n\nconst isConfigPath = (filePath: string): boolean => {\n const normalizedPath = normalizePath(filePath);\n const baseName = getBaseName(normalizedPath);\n const extension = getExtension(normalizedPath);\n\n return (\n CONFIG_BASENAMES.has(baseName) ||\n CONFIG_EXTENSIONS.has(extension) ||\n CONFIG_SUFFIXES.some((suffix) => baseName.endsWith(suffix))\n );\n};\n\nconst isFunctionalConfigPath = (filePath: string): boolean => {\n const normalizedPath = normalizePath(filePath);\n const baseName = getBaseName(normalizedPath).toLowerCase();\n const extension = getExtension(normalizedPath);\n\n return (\n normalizedPath.startsWith(\".github/workflows/\") ||\n FUNCTIONAL_CONFIG_BASENAMES.has(baseName) ||\n ((extension === \".yaml\" || extension === \".yml\" || extension === \".json\") &&\n FUNCTIONAL_CONFIG_DIRECTORIES.test(normalizedPath))\n );\n};\n\nconst isCodeLikePath = (filePath: string): boolean => {\n const normalizedPath = normalizePath(filePath);\n const extension = getExtension(normalizedPath);\n\n if (CODE_EXTENSIONS.has(extension)) {\n return true;\n }\n\n return extension.length === 0 && COMMON_CODE_DIRECTORIES.test(normalizedPath);\n};\n\nexport const classifyPath = (\n filePath: string,\n ignorePatterns: string[],\n): PathClassification => {\n const normalizedPath = normalizePath(filePath);\n\n if (normalizedPath === \".truthmark/config.yml\") {\n return \"config\";\n }\n\n if (normalizedPath.startsWith(\".truthmark/\")) {\n return \"derived\";\n }\n\n if (\n normalizedPath.startsWith(\".claude/\") ||\n normalizedPath.startsWith(\".codex/\") ||\n normalizedPath.startsWith(\".gemini/commands/\") ||\n normalizedPath.startsWith(\".opencode/\") ||\n normalizedPath === \".github/copilot-instructions.md\" ||\n normalizedPath.startsWith(\".github/agents/truth-\") ||\n normalizedPath.startsWith(\".github/prompts/truthmark-\") ||\n normalizedPath === \"AGENTS.md\" ||\n normalizedPath === \"CLAUDE.md\" ||\n normalizedPath === \"GEMINI.md\" ||\n normalizedPath.startsWith(\".gemini/commands/truthmark/\")\n ) {\n return \"derived\";\n }\n\n if (ignorePatterns.length > 0 && micromatch.isMatch(normalizedPath, ignorePatterns)) {\n return \"ignored\";\n }\n\n if (normalizedPath.toLowerCase().endsWith(\".md\")) {\n return \"markdown\";\n }\n\n if (isFunctionalConfigPath(normalizedPath)) {\n return \"functional-code\";\n }\n\n if (isConfigPath(normalizedPath)) {\n return \"config\";\n }\n\n if (isCodeLikePath(normalizedPath)) {\n return \"functional-code\";\n }\n\n return \"other\";\n};\n","import fs from \"node:fs/promises\";\n\nimport micromatch from \"micromatch\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { resolveRepoPath } from \"../fs/paths.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n TRUTH_DOCUMENT_KINDS,\n inferTruthDocumentKindFromPath,\n type TruthDocumentEntry,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\n\nconst REQUIRED_DECISION_HEADINGS = [\"Scope\", \"Product Decisions\", \"Rationale\"];\n\nconst isTruthDocumentKind = (value: string): value is TruthDocumentKind => {\n return TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind);\n};\n\nconst escapeRegExp = (value: string): string => {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n};\n\nconst hasHeading = (source: string, heading: string): boolean => {\n return new RegExp(`^#{2,3}\\\\s+${escapeRegExp(heading)}\\\\s*$`, \"mu\").test(source);\n};\n\nconst kindSpecificHeadingMessages = (\n source: string,\n kind: TruthDocumentKind | null,\n): string[] => {\n if (kind === null) {\n return [];\n }\n\n if (kind === \"behavior\") {\n return hasHeading(source, \"Current Behavior\") ? [] : [\"Current Behavior\"];\n }\n\n if (kind === \"contract\") {\n const missingMessages: string[] = [];\n\n if (!hasHeading(source, \"Contract Surface\")) {\n missingMessages.push(\"Contract Surface\");\n }\n\n if (\n !hasHeading(source, \"Inputs\") &&\n !hasHeading(source, \"Outputs\") &&\n !hasHeading(source, \"Compatibility Rules\")\n ) {\n missingMessages.push(\"one of Inputs, Outputs, or Compatibility Rules\");\n }\n\n return missingMessages;\n }\n\n if (kind === \"architecture\") {\n return hasHeading(source, \"Boundaries\") || hasHeading(source, \"Components\")\n ? []\n : [\"Boundaries or Components\"];\n }\n\n if (kind === \"workflow\") {\n const missingMessages: string[] = [];\n\n if (!hasHeading(source, \"Triggers\")) {\n missingMessages.push(\"Triggers\");\n }\n\n if (!hasHeading(source, \"Execution Model\")) {\n missingMessages.push(\"Execution Model\");\n }\n\n return missingMessages;\n }\n\n if (kind === \"operations\") {\n return hasHeading(source, \"Runtime Topology\") || hasHeading(source, \"Configuration\")\n ? []\n : [\"Runtime Topology or Configuration\"];\n }\n\n if (kind === \"test-behavior\") {\n const missingMessages: string[] = [];\n\n if (!hasHeading(source, \"Execution Model\")) {\n missingMessages.push(\"Execution Model\");\n }\n\n if (\n !hasHeading(source, \"Fixtures And Data Model\") &&\n !hasHeading(source, \"Assertions And Invariants\")\n ) {\n missingMessages.push(\"Fixtures And Data Model or Assertions And Invariants\");\n }\n\n return missingMessages;\n }\n\n return [];\n};\n\nconst decisionTruthGlobs = (config: TruthmarkConfig): string[] => {\n return [\n config.docs.roots.architecture,\n resolveTruthDocsRoot(config),\n config.docs.roots.api,\n ]\n .filter((root): root is string => Boolean(root))\n .map((root) => `${root}/**/*.md`);\n};\n\nconst isDecisionTruthCandidate = (config: TruthmarkConfig, filePath: string): boolean => {\n return !filePath.endsWith(\"/README.md\") && micromatch.isMatch(filePath, decisionTruthGlobs(config));\n};\n\nexport const checkDecisionSections = async (\n rootDir: string,\n config: TruthmarkConfig,\n markdownPaths: string[],\n truthDocumentEntries: TruthDocumentEntry[] = [],\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n const truthDocumentMap = new Map(\n truthDocumentEntries.map((entry) => [entry.path, entry]),\n );\n const candidatePaths = [...new Set(markdownPaths)]\n .filter(\n (filePath) =>\n truthDocumentMap.has(filePath) || isDecisionTruthCandidate(config, filePath),\n )\n .sort();\n\n for (const filePath of candidatePaths) {\n const source = await fs.readFile(resolveRepoPath(rootDir, filePath), \"utf8\");\n const document = parseMarkdownDocument(source);\n const routedTruthDocument = truthDocumentMap.get(filePath);\n const frontmatterTruthKind =\n typeof document.frontmatter.truth_kind === \"string\"\n ? document.frontmatter.truth_kind\n : null;\n const routedTruthKind =\n routedTruthDocument?.kindSource === \"defaulted\" ? null : routedTruthDocument?.kind;\n const truthKind =\n routedTruthKind ??\n (frontmatterTruthKind && isTruthDocumentKind(frontmatterTruthKind)\n ? frontmatterTruthKind\n : inferTruthDocumentKindFromPath(filePath));\n const missingHeadings = REQUIRED_DECISION_HEADINGS.filter(\n (heading) => !hasHeading(source, heading),\n );\n missingHeadings.push(...kindSpecificHeadingMessages(source, truthKind));\n\n if (missingHeadings.length === 0) {\n continue;\n }\n\n diagnostics.push({\n category: \"doc-structure\",\n severity: \"review\",\n message: `Canonical truth doc ${filePath} should include ${missingHeadings.join(\" and \")} section(s). Decisions should live beside current behavior, not in timestamped planning logs.`,\n file: filePath,\n });\n }\n\n return diagnostics;\n};\n","import fs from \"node:fs/promises\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { resolveRepoPath } from \"../fs/paths.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { TRUTHMARK_BLOCK_END, TRUTHMARK_BLOCK_START } from \"../templates/agents-block.js\";\nimport { renderGeneratedSurfaces } from \"../templates/generated-surfaces.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\n\nconst readOptionalFile = async (rootDir: string, filePath: string): Promise<string | null> => {\n try {\n return await fs.readFile(resolveRepoPath(rootDir, filePath), \"utf8\");\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return null;\n }\n\n throw error;\n }\n};\n\nconst extractManagedBlock = (content: string): string | null => {\n const startIndex = content.indexOf(TRUTHMARK_BLOCK_START);\n const endIndex = content.indexOf(TRUTHMARK_BLOCK_END);\n\n if (startIndex === -1 || endIndex === -1 || endIndex < startIndex) {\n return null;\n }\n\n return content.slice(startIndex, endIndex + TRUTHMARK_BLOCK_END.length);\n};\n\nconst normalizeGeneratedSurfaceContent = (content: string | null): string | null => {\n if (content === null) {\n return null;\n }\n\n return content.replace(/\\r\\n/g, \"\\n\").replace(/\\n$/u, \"\");\n};\n\nconst versionMarkers = (content: string): string[] => {\n const markers: string[] = [];\n const patterns = [\n /truthmark-version:\\s*([^\\s]+)/gu,\n /Generated by Truthmark\\s+([^\\s.]+(?:\\.[^\\s.]+){1,2})/gu,\n /^version:\\s*\"(\\d+\\.\\d+\\.\\d+)\"\\s*$/gmu,\n ];\n\n for (const pattern of patterns) {\n for (const match of content.matchAll(pattern)) {\n if (match[1]) {\n markers.push(match[1]);\n }\n }\n }\n\n return markers;\n};\n\nexport const checkGeneratedSurfaces = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n\n for (const surface of renderGeneratedSurfaces(config)) {\n const content = await readOptionalFile(rootDir, surface.path);\n\n if (content === null) {\n diagnostics.push({\n category: \"generated-surface\",\n severity: \"review\",\n message: `Generated surface ${surface.path} is missing; rerun truthmark init.`,\n file: surface.path,\n });\n continue;\n }\n\n const comparableContent = normalizeGeneratedSurfaceContent(\n surface.managedBlock ? extractManagedBlock(content) : content,\n );\n const expectedContent = normalizeGeneratedSurfaceContent(surface.content);\n\n if (comparableContent !== expectedContent) {\n diagnostics.push({\n category: \"generated-surface\",\n severity: \"review\",\n message: `Generated surface ${surface.path} is stale; rerun truthmark init.`,\n file: surface.path,\n });\n }\n\n const versionContent = surface.managedBlock ? comparableContent ?? \"\" : content;\n const mismatchedVersions = versionMarkers(versionContent).filter(\n (version) => version !== TRUTHMARK_VERSION,\n );\n\n if (mismatchedVersions.length > 0) {\n diagnostics.push({\n category: \"generated-surface\",\n severity: \"review\",\n message: `Generated surface ${surface.path} has Truthmark version ${mismatchedVersions[0]} but current version is ${TRUTHMARK_VERSION}; rerun truthmark init.`,\n file: surface.path,\n });\n }\n }\n\n return diagnostics;\n};\n","import path from \"node:path\";\n\nimport micromatch from \"micromatch\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { buildRepoIndex } from \"../repo-index/build.js\";\nimport { isJavaScriptLikePath } from \"../repo-index/file-tree.js\";\nimport { analyzeTypeScriptSource } from \"../repo-index/typescript-symbols.js\";\nimport type { ExportEntry, ImportEdge, RouteMapRoute } from \"../repo-index/types.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport { getChangedFiles, readBaseFile } from \"./git-diff.js\";\nimport type { ImpactOptions, ImpactRoute, ImpactSet, PublicSymbolChange } from \"./types.js\";\n\nconst uniqueSorted = (values: string[]): string[] => [...new Set(values)].sort();\n\nconst routeMatchesFile = (route: RouteMapRoute, filePath: string): boolean => {\n return route.codeSurface.some((pattern) => micromatch.isMatch(filePath, pattern));\n};\n\nconst routeOwnsTruthDoc = (route: RouteMapRoute, filePath: string): boolean => {\n return route.truthDocs.includes(filePath);\n};\n\nconst toImpactRoute = (route: RouteMapRoute): ImpactRoute => ({\n id: route.id,\n name: route.name,\n key: route.key,\n sourcePath: route.sourcePath,\n truthDocs: [...route.truthDocs].sort(),\n codeSurface: [...route.codeSurface].sort(),\n});\nconst changedPathSet = (changedFiles: { path: string; previousPath?: string }[]): Set<string> => {\n return new Set(\n changedFiles.flatMap((file) => [file.path, ...(file.previousPath ? [file.previousPath] : [])]),\n );\n};\n\nconst changedFilePaths = (changedFile: { path: string; previousPath?: string }): string[] => {\n return [changedFile.path, ...(changedFile.previousPath ? [changedFile.previousPath] : [])];\n};\n\nconst resolveImportPath = (importEdge: ImportEdge): string | null => {\n if (!importEdge.specifier.startsWith(\".\")) {\n return null;\n }\n\n const basePath = path.posix.normalize(path.posix.join(path.posix.dirname(importEdge.from), importEdge.specifier));\n const withoutExtension = basePath.replace(/\\.[cm]?[jt]sx?$/u, \"\");\n\n return withoutExtension;\n};\n\nconst importTargetsChangedFile = (importEdge: ImportEdge, changedPath: string): boolean => {\n const resolved = resolveImportPath(importEdge);\n if (!resolved) {\n return false;\n }\n\n return changedPath.replace(/\\.[cm]?[jt]sx?$/u, \"\") === resolved;\n};\n\nconst pathSegments = (filePath: string): string[] => filePath.split(\"/\").filter(Boolean);\n\nconst testHintMatchesChangedFile = (hints: string[], changedPath: string): boolean => {\n const changedBaseName = path.posix.basename(changedPath);\n const changedSegments = pathSegments(changedPath);\n\n return hints.some((hint) => changedBaseName.startsWith(hint) || changedSegments.includes(hint));\n};\n\nconst changedSymbolsFor = async (\n cwd: string,\n base: string,\n basePath: string,\n currentPath: string,\n currentExports: ExportEntry[],\n): Promise<PublicSymbolChange[]> => {\n if (!isJavaScriptLikePath(basePath) && !isJavaScriptLikePath(currentPath)) {\n return [];\n }\n\n const baseSource = await readBaseFile(cwd, base, basePath);\n const baseExports = baseSource ? analyzeTypeScriptSource(basePath, baseSource).exports : [];\n const currentByName = new Map(currentExports.map((entry) => [entry.name, entry]));\n const baseByName = new Map(baseExports.map((entry) => [entry.name, entry]));\n const changes: PublicSymbolChange[] = [];\n\n if (basePath !== currentPath) {\n for (const entry of currentExports) {\n changes.push({ path: currentPath, name: entry.name, kind: entry.kind, change: \"added\" });\n }\n for (const entry of baseExports) {\n changes.push({ path: basePath, name: entry.name, kind: entry.kind, change: \"removed\" });\n }\n return changes;\n }\n\n for (const [name, entry] of currentByName) {\n if (!baseByName.has(name)) {\n changes.push({ path: currentPath, name, kind: entry.kind, change: \"added\" });\n }\n }\n\n for (const [name, entry] of baseByName) {\n if (!currentByName.has(name)) {\n changes.push({ path: basePath, name, kind: entry.kind, change: \"removed\" });\n }\n }\n\n return changes;\n};\n\nexport const buildImpactSet = async (\n cwd: string,\n options: ImpactOptions,\n): Promise<ImpactSet> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const [loadResult, repoIndex, changedFilesResult] = await Promise.all([\n loadConfig(rootDir),\n buildRepoIndex(rootDir),\n getChangedFiles(rootDir, options.base),\n ]);\n const changedFiles = changedFilesResult.files;\n const ignore = loadResult.config?.ignore ?? [];\n const diagnostics: Diagnostic[] = [...repoIndex.diagnostics, ...changedFilesResult.diagnostics];\n const affectedRoutes = new Map<string, ImpactRoute>();\n const affectedTruthDocs: string[] = [];\n const affectedTests: string[] = [];\n const changedPublicSymbols: PublicSymbolChange[] = [];\n const knownTestPaths = new Set(repoIndex.tests.map((test) => test.path));\n\n for (const changedFile of changedFiles) {\n const routeCandidatePaths = changedFilePaths(changedFile);\n if (routeCandidatePaths.some((filePath) => knownTestPaths.has(filePath))) {\n affectedTests.push(changedFile.path);\n }\n const matchingRoutes = repoIndex.routeMap.routes.filter(\n (route) =>\n routeCandidatePaths.some(\n (filePath) => routeMatchesFile(route, filePath) || routeOwnsTruthDoc(route, filePath),\n ),\n );\n\n for (const route of matchingRoutes) {\n affectedRoutes.set(route.key, toImpactRoute(route));\n affectedTruthDocs.push(...route.truthDocs);\n if (route.truthDocs.length === 0) {\n diagnostics.push({\n category: \"impact\",\n severity: \"review\",\n message: `Changed file ${changedFile.path} maps to route ${route.name} but the route has no truth document.`,\n file: changedFile.path,\n area: route.name,\n });\n }\n }\n\n if (\n matchingRoutes.length === 0 &&\n !routeCandidatePaths.some((filePath) => knownTestPaths.has(filePath)) &&\n routeCandidatePaths.some((filePath) => classifyPath(filePath, ignore) === \"functional-code\")\n ) {\n diagnostics.push({\n category: \"impact\",\n severity: \"review\",\n message: `Changed file ${changedFile.path} is not mapped to a Truthmark route.`,\n file: changedFile.path,\n });\n }\n\n const currentExports = repoIndex.exports.filter((entry) => entry.path === changedFile.path);\n changedPublicSymbols.push(\n ...(await changedSymbolsFor(\n rootDir,\n options.base,\n changedFile.previousPath ?? changedFile.path,\n changedFile.path,\n currentExports,\n )),\n );\n }\n const uniqueAffectedTruthDocs = uniqueSorted(affectedTruthDocs);\n const changedPaths = changedPathSet(changedFiles);\n for (const symbol of changedPublicSymbols) {\n if (uniqueAffectedTruthDocs.length === 0) {\n diagnostics.push({\n category: \"impact\",\n severity: \"review\",\n message: `Changed public symbol ${symbol.name} in ${symbol.path} has no affected truth document.`,\n file: symbol.path,\n data: {\n symbol: symbol.name,\n change: symbol.change,\n },\n });\n continue;\n }\n if (!uniqueAffectedTruthDocs.some((truthDoc) => changedPaths.has(truthDoc))) {\n diagnostics.push({\n category: \"impact\",\n severity: \"review\",\n message: `Changed public symbol ${symbol.name} in ${symbol.path} has affected truth docs but none were changed in this impact set.`,\n file: symbol.path,\n data: {\n symbol: symbol.name,\n change: symbol.change,\n affectedTruthDocs: uniqueAffectedTruthDocs,\n },\n });\n }\n }\n\n for (const test of repoIndex.tests) {\n const testImports = repoIndex.imports.filter((edge) => edge.from === test.path);\n const importsChangedFile = changedFiles.some((changedFile) =>\n changedFilePaths(changedFile).some((filePath) =>\n testImports.some((importEdge) => importTargetsChangedFile(importEdge, filePath)),\n ),\n );\n const hintMatchesChangedFile = changedFiles.some((changedFile) =>\n changedFilePaths(changedFile).some((filePath) =>\n testHintMatchesChangedFile(test.targetHints, filePath),\n ),\n );\n\n if (importsChangedFile || hintMatchesChangedFile) {\n affectedTests.push(test.path);\n }\n }\n\n return {\n schemaVersion: \"impact-set/v0\",\n base: options.base,\n headSha: repository.headSha,\n changedFiles,\n affectedRoutes: [...affectedRoutes.values()].sort((left, right) =>\n left.key.localeCompare(right.key),\n ),\n affectedTruthDocs: uniqueAffectedTruthDocs,\n affectedTests: uniqueSorted(affectedTests),\n changedPublicSymbols: changedPublicSymbols.sort((left, right) =>\n `${left.path}:${left.name}:${left.change}`.localeCompare(`${right.path}:${right.name}:${right.change}`),\n ),\n diagnostics,\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { discoverRepoFiles, isJavaScriptLikePath } from \"./file-tree.js\";\nimport { discoverPackageMetadata } from \"./package-metadata.js\";\nimport { buildRouteMap } from \"./route-map.js\";\nimport { analyzeTypeScriptSource } from \"./typescript-symbols.js\";\nimport type { ExportEntry, ImportEdge, PublicSymbolEntry, RepoIndex } from \"./types.js\";\n\nexport const buildRepoIndex = async (cwd: string): Promise<RepoIndex> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const loadResult = await loadConfig(rootDir);\n const ignore = loadResult.config?.ignore ?? [];\n const diagnostics: Diagnostic[] = [...loadResult.diagnostics];\n const [packages, fileTree, routeMap] = await Promise.all([\n discoverPackageMetadata(rootDir),\n discoverRepoFiles(rootDir, ignore),\n buildRouteMap(rootDir),\n ]);\n const imports: ImportEdge[] = [];\n const exports: ExportEntry[] = [];\n const publicSymbols: PublicSymbolEntry[] = [];\n\n diagnostics.push(...routeMap.diagnostics);\n\n for (const file of fileTree.files) {\n if (!isJavaScriptLikePath(file.path)) {\n continue;\n }\n\n const source = await fs.readFile(path.join(rootDir, file.path), \"utf8\");\n const analysis = analyzeTypeScriptSource(file.path, source);\n imports.push(...analysis.imports);\n exports.push(...analysis.exports);\n publicSymbols.push(...analysis.publicSymbols);\n }\n\n return {\n schemaVersion: \"repo-index/v0\",\n repository: {\n root: rootDir,\n branchName: repository.branchName,\n headSha: repository.headSha,\n },\n packages,\n files: fileTree.files,\n docs: fileTree.docs,\n tests: fileTree.tests,\n imports: imports.sort((left, right) => `${left.from}:${left.specifier}`.localeCompare(`${right.from}:${right.specifier}`)),\n exports: exports.sort((left, right) => `${left.path}:${left.name}`.localeCompare(`${right.path}:${right.name}`)),\n publicSymbols: publicSymbols.sort((left, right) =>\n `${left.path}:${left.name}`.localeCompare(`${right.path}:${right.name}`),\n ),\n routeMap,\n diagnostics,\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { execa } from \"execa\";\nimport fg from \"fast-glob\";\nimport matter from \"gray-matter\";\nimport micromatch from \"micromatch\";\n\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport type { RepoDocEntry, RepoFileEntry, RepoFileKind, RepoTestEntry } from \"./types.js\";\n\nconst languageByExtension = new Map<string, string>([\n [\".ts\", \"typescript\"],\n [\".tsx\", \"typescript\"],\n [\".js\", \"javascript\"],\n [\".jsx\", \"javascript\"],\n [\".mjs\", \"javascript\"],\n [\".cjs\", \"javascript\"],\n [\".md\", \"markdown\"],\n [\".json\", \"json\"],\n [\".yml\", \"yaml\"],\n [\".yaml\", \"yaml\"],\n [\".toml\", \"toml\"],\n]);\n\nconst sourceExtensions = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\n\nexport const isJavaScriptLikePath = (filePath: string): boolean => {\n return sourceExtensions.has(path.posix.extname(filePath));\n};\n\nconst isTestPath = (filePath: string): boolean => {\n return (\n filePath.startsWith(\"tests/\") ||\n filePath.includes(\"/__tests__/\") ||\n /(?:^|[./-])(test|spec)\\.[cm]?[jt]sx?$/u.test(path.posix.basename(filePath))\n );\n};\n\nconst fileKind = (filePath: string, ignore: string[]): RepoFileKind => {\n const classification = classifyPath(filePath, ignore);\n if (classification === \"derived\") {\n return \"generated\";\n }\n if (isTestPath(filePath)) {\n return \"test\";\n }\n if (filePath.endsWith(\".md\")) {\n return \"doc\";\n }\n if (classification === \"functional-code\") {\n return \"source\";\n }\n if (classification === \"markdown\") {\n return \"doc\";\n }\n if (classification === \"config\") {\n return \"config\";\n }\n\n return \"other\";\n};\n\nconst targetHintsForTest = (filePath: string): string[] => {\n const hints = new Set<string>();\n const basename = path.posix.basename(filePath).replace(/\\.(test|spec)\\.[cm]?[jt]sx?$/u, \"\");\n if (basename.length > 0) {\n hints.add(basename);\n }\n\n const segments = filePath.split(\"/\");\n const testRootIndex = segments.findIndex((segment) => segment === \"tests\" || segment === \"__tests__\");\n if (testRootIndex >= 0) {\n for (const segment of segments.slice(testRootIndex + 1, -1)) {\n if (segment.length > 0) {\n hints.add(segment);\n }\n }\n }\n\n return [...hints].sort();\n};\n\nconst defaultIgnore = [\".git/**\", \"node_modules/**\", \"dist/**\", \"build/**\"];\n\nconst normalizePath = (filePath: string): string => filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/u, \"\");\n\nconst gitDiscoverableFiles = async (rootDir: string): Promise<string[] | null> => {\n const result = await execa(\n \"git\",\n [\"ls-files\", \"--cached\", \"--others\", \"--exclude-standard\", \"--deduplicate\"],\n {\n cwd: rootDir,\n reject: false,\n },\n );\n if ((result.exitCode ?? 1) !== 0) {\n return null;\n }\n return result.stdout\n .split(\"\\n\")\n .map((line) => normalizePath(line.trim()))\n .filter((line) => line.length > 0);\n};\n\nconst isIgnoredPath = (filePath: string, ignore: string[]): boolean => {\n return micromatch.isMatch(filePath, [...defaultIgnore, ...ignore]);\n};\n\nexport const discoverRepoFiles = async (\n rootDir: string,\n ignore: string[],\n): Promise<{ files: RepoFileEntry[]; docs: RepoDocEntry[]; tests: RepoTestEntry[] }> => {\n const discoveredFiles =\n (await gitDiscoverableFiles(rootDir)) ??\n (await fg([\"**/*\"], {\n cwd: rootDir,\n onlyFiles: true,\n dot: true,\n ignore: [...defaultIgnore, ...ignore],\n followSymbolicLinks: false,\n }));\n const files: RepoFileEntry[] = [];\n const docs: RepoDocEntry[] = [];\n const tests: RepoTestEntry[] = [];\n\n for (const filePath of discoveredFiles.filter((entry) => !isIgnoredPath(entry, ignore)).sort()) {\n const extension = path.posix.extname(filePath);\n const kind = fileKind(filePath, ignore);\n\n files.push({\n path: filePath,\n kind,\n language: languageByExtension.get(extension) ?? null,\n });\n\n if (kind === \"test\") {\n tests.push({\n path: filePath,\n targetHints: targetHintsForTest(filePath),\n });\n }\n\n if (kind === \"doc\") {\n const source = await fs.readFile(path.join(rootDir, filePath), \"utf8\");\n const parsed = matter(source);\n const markdown = parseMarkdownDocument(parsed.content);\n const title = markdown.headings.find((heading) => heading.depth === 1)?.text ?? null;\n const sourceOfTruth = Array.isArray(parsed.data.source_of_truth)\n ? parsed.data.source_of_truth.filter((entry: unknown): entry is string => typeof entry === \"string\")\n : [];\n\n docs.push({\n path: filePath,\n title,\n docType: typeof parsed.data.doc_type === \"string\" ? parsed.data.doc_type : null,\n truthKind: typeof parsed.data.truth_kind === \"string\" ? parsed.data.truth_kind : null,\n sourceOfTruth: sourceOfTruth.sort(),\n });\n }\n }\n\n return {\n files: files.sort((left, right) => left.path.localeCompare(right.path)),\n docs: docs.sort((left, right) => left.path.localeCompare(right.path)),\n tests: tests.sort((left, right) => left.path.localeCompare(right.path)),\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport fg from \"fast-glob\";\n\nimport type { PackageMetadata } from \"./types.js\";\n\nconst packageManagerFor = async (\n rootDir: string,\n packageDir: string,\n): Promise<PackageMetadata[\"manager\"]> => {\n const lockfiles: Array<[string, PackageMetadata[\"manager\"]]> = [\n [\"package-lock.json\", \"npm\"],\n [\"pnpm-lock.yaml\", \"pnpm\"],\n [\"yarn.lock\", \"yarn\"],\n [\"bun.lockb\", \"bun\"],\n [\"bun.lock\", \"bun\"],\n ];\n\n for (const [lockfile, manager] of lockfiles) {\n try {\n await fs.access(path.join(rootDir, packageDir, lockfile));\n return manager;\n } catch {\n continue;\n }\n }\n\n return \"npm\";\n};\n\nexport const discoverPackageMetadata = async (rootDir: string): Promise<PackageMetadata[]> => {\n const packageFiles = await fg([\"package.json\", \"*/package.json\", \"packages/*/package.json\"], {\n cwd: rootDir,\n onlyFiles: true,\n ignore: [\"node_modules/**\", \"dist/**\", \"build/**\"],\n followSymbolicLinks: false,\n });\n const packages: PackageMetadata[] = [];\n\n for (const packageFile of packageFiles.sort()) {\n const packageDir = path.posix.dirname(packageFile) === \".\" ? \"\" : path.posix.dirname(packageFile);\n const raw = JSON.parse(await fs.readFile(path.join(rootDir, packageFile), \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n private?: unknown;\n scripts?: unknown;\n };\n const scripts =\n raw.scripts && typeof raw.scripts === \"object\" ? Object.keys(raw.scripts).sort() : [];\n\n packages.push({\n path: packageFile,\n manager: await packageManagerFor(rootDir, packageDir),\n name: typeof raw.name === \"string\" ? raw.name : null,\n version: typeof raw.version === \"string\" ? raw.version : null,\n private: typeof raw.private === \"boolean\" ? raw.private : null,\n scripts,\n });\n }\n\n return packages;\n};\n","import { loadConfig } from \"../config/load.js\";\nimport { resolveAreaRouting } from \"../routing/area-resolver.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\nimport type { RouteMap } from \"./types.js\";\n\nexport const buildRouteMap = async (rootDir: string): Promise<RouteMap> => {\n const loadResult = await loadConfig(rootDir);\n\n if (!loadResult.config) {\n return {\n schemaVersion: \"route-map/v0\",\n routes: [],\n diagnostics: loadResult.diagnostics,\n };\n }\n\n const routing = await resolveAreaRouting(rootDir, {\n rootIndex: loadResult.config.docs.routing.rootIndex,\n areaFilesRoot: loadResult.config.docs.routing.areaFilesRoot,\n truthDocsRoot: resolveTruthDocsRoot(loadResult.config),\n });\n\n return {\n schemaVersion: \"route-map/v0\",\n routes: routing.areas\n .map((area) => ({\n id: area.id,\n name: area.name,\n key: area.key,\n sourcePath: area.sourcePath,\n parentName: area.parentName,\n codeSurface: [...area.codeSurface].sort(),\n truthDocs: [...area.truthDocuments].sort(),\n updateTruthWhen: [...area.updateTruthWhen],\n }))\n .sort((left, right) => left.key.localeCompare(right.key)),\n diagnostics: routing.diagnostics,\n };\n};\n","import ts from \"typescript\";\n\nimport type { ExportEntry, ImportEdge, PublicSymbolEntry } from \"./types.js\";\n\nexport type TypeScriptSourceAnalysis = {\n imports: ImportEdge[];\n exports: ExportEntry[];\n publicSymbols: PublicSymbolEntry[];\n};\n\nconst sortStrings = (values: string[]): string[] => [...new Set(values)].sort();\n\nconst hasExportModifier = (node: ts.Node): boolean => {\n return Boolean(\n ts.canHaveModifiers(node) &&\n ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword),\n );\n};\n\nconst declarationName = (node: { name?: ts.PropertyName | ts.BindingName }): string | null => {\n if (!node.name || !ts.isIdentifier(node.name)) {\n return null;\n }\n\n return node.name.text;\n};\n\nconst addExport = (\n exports: ExportEntry[],\n publicSymbols: PublicSymbolEntry[],\n path: string,\n name: string | null,\n kind: ExportEntry[\"kind\"],\n): void => {\n if (!name) {\n return;\n }\n\n const entry = { path, name, kind };\n exports.push(entry);\n publicSymbols.push(entry);\n};\n\nexport const analyzeTypeScriptSource = (\n path: string,\n source: string,\n): TypeScriptSourceAnalysis => {\n const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);\n const imports: ImportEdge[] = [];\n const exports: ExportEntry[] = [];\n const publicSymbols: PublicSymbolEntry[] = [];\n\n for (const statement of sourceFile.statements) {\n if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {\n const imported: string[] = [];\n const clause = statement.importClause;\n\n if (clause?.name) {\n imported.push(\"default\");\n }\n if (clause?.namedBindings && ts.isNamespaceImport(clause.namedBindings)) {\n imported.push(\"*\");\n }\n if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) {\n for (const element of clause.namedBindings.elements) {\n imported.push(element.propertyName?.text ?? element.name.text);\n }\n }\n\n imports.push({\n from: path,\n specifier: statement.moduleSpecifier.text,\n imported: sortStrings(imported),\n });\n continue;\n }\n\n if (ts.isExportDeclaration(statement)) {\n if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {\n for (const element of statement.exportClause.elements) {\n addExport(exports, publicSymbols, path, element.name.text, \"re-export\");\n }\n }\n continue;\n }\n\n if (ts.isFunctionDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"function\");\n continue;\n }\n\n if (ts.isClassDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"class\");\n continue;\n }\n\n if (ts.isInterfaceDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"interface\");\n continue;\n }\n\n if (ts.isTypeAliasDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"type\");\n continue;\n }\n\n if (ts.isEnumDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"enum\");\n continue;\n }\n\n if (ts.isVariableStatement(statement) && hasExportModifier(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n addExport(exports, publicSymbols, path, declarationName(declaration), \"const\");\n }\n }\n }\n\n return {\n imports: imports.sort((left, right) => left.specifier.localeCompare(right.specifier)),\n exports: exports.sort((left, right) => left.name.localeCompare(right.name)),\n publicSymbols: publicSymbols.sort((left, right) => left.name.localeCompare(right.name)),\n };\n};\n","import { execa } from \"execa\";\n\nimport { getUncommittedChanges } from \"../git/changes.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport type { ChangedFileStatus, ImpactFile } from \"./types.js\";\n\nconst normalizePath = (filePath: string): string => filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\//u, \"\");\n\nconst statusForCode = (code: string): ChangedFileStatus => {\n if (code.startsWith(\"A\")) return \"added\";\n if (code.startsWith(\"D\")) return \"deleted\";\n if (code.startsWith(\"R\")) return \"renamed\";\n if (code.startsWith(\"C\")) return \"copied\";\n if (code.startsWith(\"T\")) return \"type-changed\";\n return \"modified\";\n};\n\nconst mergeFile = (files: Map<string, ImpactFile>, next: ImpactFile): void => {\n const existing = files.get(next.path);\n if (!existing) {\n files.set(next.path, next);\n return;\n }\n\n files.set(next.path, {\n ...existing,\n status:\n existing.status === \"deleted\" || existing.status === \"renamed\" ? existing.status : next.status,\n previousPath: existing.previousPath ?? next.previousPath,\n staged: existing.staged || next.staged,\n unstaged: existing.unstaged || next.unstaged,\n untracked: existing.untracked || next.untracked,\n deleted: existing.deleted || next.deleted,\n });\n};\n\nexport type ChangedFilesResult = {\n files: ImpactFile[];\n diagnostics: Diagnostic[];\n};\nexport const getChangedFiles = async (cwd: string, base: string): Promise<ChangedFilesResult> => {\n const repository = await getGitRepository(cwd);\n const files = new Map<string, ImpactFile>();\n const diagnostics: Diagnostic[] = [];\n let diff = await execa(\"git\", [\"diff\", \"--name-status\", \"--find-renames\", `${base}...HEAD`], {\n cwd: repository.worktreePath,\n reject: false,\n });\n\n if ((diff.exitCode ?? 1) !== 0) {\n diff = await execa(\"git\", [\"diff\", \"--name-status\", \"--find-renames\", base, \"HEAD\"], {\n cwd: repository.worktreePath,\n reject: false,\n });\n }\n\n if ((diff.exitCode ?? 1) === 0) {\n for (const line of diff.stdout.split(\"\\n\").filter(Boolean)) {\n const [rawStatus, rawPath, rawNewPath] = line.split(\"\\t\");\n const filePath = normalizePath(rawNewPath ?? rawPath);\n const previousPath = rawNewPath && rawStatus.startsWith(\"R\") ? normalizePath(rawPath) : undefined;\n\n mergeFile(files, {\n path: filePath,\n previousPath,\n status: statusForCode(rawStatus),\n staged: false,\n unstaged: false,\n untracked: false,\n deleted: rawStatus.startsWith(\"D\"),\n });\n }\n } else {\n diagnostics.push({\n category: \"impact\",\n severity: \"error\",\n message: `Unable to compare base ref ${base} to HEAD.`,\n });\n }\n\n for (const change of await getUncommittedChanges(repository.worktreePath)) {\n mergeFile(files, {\n path: change.path,\n status: change.untracked ? \"added\" : change.deleted ? \"deleted\" : \"modified\",\n staged: change.staged,\n unstaged: change.unstaged,\n untracked: change.untracked,\n deleted: change.deleted,\n });\n }\n\n return {\n files: [...files.values()].sort((left, right) => left.path.localeCompare(right.path)),\n diagnostics,\n };\n};\n\nexport const readBaseFile = async (\n cwd: string,\n base: string,\n filePath: string,\n): Promise<string | null> => {\n const repository = await getGitRepository(cwd);\n const result = await execa(\"git\", [\"show\", `${base}:${filePath}`], {\n cwd: repository.worktreePath,\n reject: false,\n });\n\n return (result.exitCode ?? 1) === 0 ? result.stdout : null;\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { execa } from \"execa\";\n\nimport { getGitRepository } from \"./repository.js\";\n\nexport type UncommittedChange = {\n path: string;\n staged: boolean;\n unstaged: boolean;\n untracked: boolean;\n deleted: boolean;\n};\n\nconst normalizePath = (filePath: string): string => {\n return filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\//u, \"\");\n};\n\nconst listChangedPaths = async (cwd: string, args: string[]): Promise<string[]> => {\n const result = await execa(\"git\", args, { cwd });\n\n return result.stdout\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => normalizePath(line));\n};\n\nconst pathExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n};\n\nconst getOrCreateChange = (\n changesByPath: Map<string, UncommittedChange>,\n filePath: string,\n): UncommittedChange => {\n const existingChange = changesByPath.get(filePath);\n\n if (existingChange) {\n return existingChange;\n }\n\n const nextChange: UncommittedChange = {\n path: filePath,\n staged: false,\n unstaged: false,\n untracked: false,\n deleted: false,\n };\n\n changesByPath.set(filePath, nextChange);\n\n return nextChange;\n};\n\nexport const getUncommittedChanges = async (cwd: string): Promise<UncommittedChange[]> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const [stagedPaths, unstagedPaths, untrackedPaths, stagedDeletedPaths, unstagedDeletedPaths] =\n await Promise.all([\n listChangedPaths(rootDir, [\"diff\", \"--name-only\", \"--cached\", \"--diff-filter=ACDMRTUXB\"]),\n listChangedPaths(rootDir, [\"diff\", \"--name-only\", \"--diff-filter=ACDMRTUXB\"]),\n listChangedPaths(rootDir, [\"ls-files\", \"--others\", \"--exclude-standard\"]),\n listChangedPaths(rootDir, [\"diff\", \"--name-only\", \"--cached\", \"--diff-filter=D\"]),\n listChangedPaths(rootDir, [\"diff\", \"--name-only\", \"--diff-filter=D\"]),\n ]);\n const changesByPath = new Map<string, UncommittedChange>();\n\n for (const stagedPath of stagedPaths) {\n getOrCreateChange(changesByPath, stagedPath).staged = true;\n }\n\n for (const unstagedPath of unstagedPaths) {\n getOrCreateChange(changesByPath, unstagedPath).unstaged = true;\n }\n\n for (const untrackedPath of untrackedPaths) {\n getOrCreateChange(changesByPath, untrackedPath).untracked = true;\n }\n\n const deletedPathCandidates = new Set([...stagedDeletedPaths, ...unstagedDeletedPaths]);\n\n for (const deletedPath of deletedPathCandidates) {\n const change = getOrCreateChange(changesByPath, deletedPath);\n change.deleted = !(await pathExists(path.join(rootDir, deletedPath)));\n }\n\n return Array.from(changesByPath.values()).sort((left, right) => {\n return left.path.localeCompare(right.path);\n });\n};","import fs from \"node:fs/promises\";\nimport fg from \"fast-glob\";\n\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport { hashText } from \"../markdown/hash.js\";\nimport { isJavaScriptLikePath } from \"../repo-index/file-tree.js\";\nimport { analyzeTypeScriptSource } from \"../repo-index/typescript-symbols.js\";\nimport { parseEvidenceReferences } from \"./parse.js\";\nimport type { EvidenceReference } from \"./types.js\";\n\nconst pathExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n};\n\nconst diagnosticFor = (reference: EvidenceReference, message: string): Diagnostic => ({\n category: \"freshness\",\n severity: \"error\",\n message,\n file: reference.truthDocPath,\n data: {\n reference: reference.path,\n source: reference.source,\n },\n});\n\nconst isGlobReference = (referencePath: string): boolean => /[*?[\\]{}()]/u.test(referencePath);\n\nconst validateGlob = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic | null> => {\n if (reference.path.startsWith(\"../\") || reference.path.startsWith(\"/\")) {\n return diagnosticFor(reference, `Referenced file pattern ${reference.path} must stay inside the repository root.`);\n }\n const matches = await fg(reference.path, {\n cwd: rootDir,\n dot: true,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n return matches.length > 0\n ? null\n : diagnosticFor(reference, `Referenced file pattern ${reference.path} does not match any file.`);\n};\n\nconst validateSymbol = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic | null> => {\n if (!reference.symbol || !isJavaScriptLikePath(reference.path)) {\n return null;\n }\n\n const source = await fs.readFile(resolveRepoPath(rootDir, reference.path), \"utf8\");\n const analysis = analyzeTypeScriptSource(reference.path, source);\n const hasSymbol = analysis.publicSymbols.some((symbol) => symbol.name === reference.symbol);\n\n return hasSymbol\n ? null\n : diagnosticFor(reference, `Evidence symbol ${reference.symbol} was not found in ${reference.path}.`);\n};\n\nconst validateHash = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic | null> => {\n if (!reference.contentHash) {\n return null;\n }\n if (!reference.contentHash.startsWith(\"sha256:\")) {\n return diagnosticFor(reference, `Evidence hash for ${reference.path} must use sha256:.`);\n }\n\n const source = await fs.readFile(resolveRepoPath(rootDir, reference.path), \"utf8\");\n const lines = source.split(\"\\n\");\n const startLine = reference.startLine ?? 1;\n const endLine = reference.endLine ?? lines.length;\n\n if (startLine < 1 || endLine < startLine || endLine > lines.length) {\n return diagnosticFor(reference, `Evidence line span for ${reference.path} is outside the file.`);\n }\n\n const actualHash = `sha256:${hashText(lines.slice(startLine - 1, endLine).join(\"\\n\"))}`;\n\n return actualHash === reference.contentHash\n ? null\n : diagnosticFor(reference, `Evidence hash for ${reference.path} is stale.`);\n};\n\nconst validateLineSpan = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic | null> => {\n if (reference.startLine === undefined && reference.endLine === undefined) {\n return null;\n }\n\n const source = await fs.readFile(resolveRepoPath(rootDir, reference.path), \"utf8\");\n const lines = source.split(\"\\n\");\n const startLine = reference.startLine ?? 1;\n const endLine = reference.endLine ?? lines.length;\n\n return startLine < 1 || endLine < startLine || endLine > lines.length\n ? diagnosticFor(reference, `Evidence line span for ${reference.path} is outside the file.`)\n : null;\n};\n\nconst validateReference = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n\n try {\n if (isGlobReference(reference.path)) {\n const globDiagnostic = await validateGlob(rootDir, reference);\n return globDiagnostic ? [globDiagnostic] : [];\n }\n\n const absolutePath = resolveRepoPath(rootDir, reference.path);\n await assertRepoContainment(rootDir, absolutePath);\n\n if (!(await pathExists(absolutePath))) {\n diagnostics.push(diagnosticFor(reference, `Referenced file ${reference.path} does not exist.`));\n return diagnostics;\n }\n\n const symbolDiagnostic = await validateSymbol(rootDir, reference);\n if (symbolDiagnostic) {\n diagnostics.push(symbolDiagnostic);\n }\n\n const lineSpanDiagnostic = await validateLineSpan(rootDir, reference);\n if (lineSpanDiagnostic) {\n diagnostics.push(lineSpanDiagnostic);\n } else {\n const hashDiagnostic = await validateHash(rootDir, reference);\n if (hashDiagnostic) {\n diagnostics.push(hashDiagnostic);\n }\n }\n } catch {\n diagnostics.push(diagnosticFor(reference, `Referenced file ${reference.path} must stay inside the repository root.`));\n }\n\n return diagnostics;\n};\n\nexport const validateEvidenceReferences = async (\n rootDir: string,\n truthDocPaths: string[],\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n\n for (const truthDocPath of [...truthDocPaths].sort()) {\n const references = await parseEvidenceReferences(rootDir, truthDocPath);\n\n for (const reference of references) {\n diagnostics.push(...(await validateReference(rootDir, reference)));\n }\n }\n\n return diagnostics;\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport matter from \"gray-matter\";\nimport { parse } from \"yaml\";\n\nimport type { EvidenceReference } from \"./types.js\";\n\nconst evidenceBlockPattern = /```ya?ml\\s*\\n([\\s\\S]*?)```/giu;\n\nconst repoRootPrefixes = [\".codex/\", \".github/\", \".truthmark/\", \"docs/\", \"src/\", \"tests/\"];\n\nconst normalizeReferencePath = (truthDocPath: string, referencePath: string): string => {\n const strippedPath = referencePath.split(\"#\")[0]?.trim() ?? \"\";\n const isRepoRelative = repoRootPrefixes.some((prefix) => strippedPath.startsWith(prefix));\n\n if (!isRepoRelative && (strippedPath.startsWith(\".\") || !strippedPath.includes(\"/\"))) {\n return path.posix.normalize(path.posix.join(path.posix.dirname(truthDocPath), strippedPath));\n }\n\n return path.posix.normalize(strippedPath);\n};\n\nconst toEvidenceReference = (\n truthDocPath: string,\n raw: unknown,\n): EvidenceReference | null => {\n if (!raw || typeof raw !== \"object\" || !(\"path\" in raw) || typeof raw.path !== \"string\") {\n return null;\n }\n\n return {\n truthDocPath,\n path: normalizeReferencePath(truthDocPath, raw.path),\n symbol: \"symbol\" in raw && typeof raw.symbol === \"string\" ? raw.symbol : undefined,\n startLine: \"start_line\" in raw && typeof raw.start_line === \"number\" ? raw.start_line : undefined,\n endLine: \"end_line\" in raw && typeof raw.end_line === \"number\" ? raw.end_line : undefined,\n contentHash:\n \"content_hash\" in raw && typeof raw.content_hash === \"string\" ? raw.content_hash : undefined,\n source: \"evidence-block\",\n };\n};\n\nexport const parseEvidenceReferences = async (\n rootDir: string,\n truthDocPath: string,\n): Promise<EvidenceReference[]> => {\n const source = await fs.readFile(path.join(rootDir, truthDocPath), \"utf8\");\n const parsed = matter(source);\n const references: EvidenceReference[] = [];\n const sourceOfTruth = Array.isArray(parsed.data.source_of_truth) ? parsed.data.source_of_truth : [];\n\n for (const entry of sourceOfTruth) {\n if (typeof entry !== \"string\") {\n continue;\n }\n\n references.push({\n truthDocPath,\n path: normalizeReferencePath(truthDocPath, entry),\n source: \"frontmatter\",\n });\n }\n\n for (const match of parsed.content.matchAll(evidenceBlockPattern)) {\n const block = parse(match[1] ?? \"\") as unknown;\n const rawEvidence =\n block && typeof block === \"object\" && \"evidence\" in block\n ? (block as { evidence?: unknown }).evidence\n : null;\n\n if (!Array.isArray(rawEvidence)) {\n continue;\n }\n\n for (const rawReference of rawEvidence) {\n const reference = toEvidenceReference(truthDocPath, rawReference);\n if (reference) {\n references.push(reference);\n }\n }\n }\n\n return references;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { buildImpactSet } from \"../impact/build.js\";\nimport type { ImpactSet } from \"../impact/types.js\";\nimport { validateEvidenceReferences } from \"../evidence/validate.js\";\n\nexport type FreshnessCheckResult = {\n diagnostics: Diagnostic[];\n impactSet: ImpactSet;\n};\n\nexport const checkFreshness = async (\n rootDir: string,\n _config: TruthmarkConfig,\n truthDocumentPaths: string[],\n base: string,\n): Promise<FreshnessCheckResult> => {\n const impactSet = await buildImpactSet(rootDir, { base });\n const diagnostics: Diagnostic[] = [...(await validateEvidenceReferences(rootDir, truthDocumentPaths))];\n\n for (const diagnostic of impactSet.diagnostics) {\n if (diagnostic.category !== \"impact\") {\n continue;\n }\n\n diagnostics.push({\n ...diagnostic,\n category: \"freshness\",\n message: diagnostic.message.replace(\"not mapped to a Truthmark route\", \"not routed to truth ownership\"),\n });\n }\n\n return {\n diagnostics,\n impactSet,\n };\n};\n","import type { CommandResult } from \"../output/diagnostic.js\";\nimport { loadConfig } from \"../config/load.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport { getBranchScopeData } from \"./branch-scope.js\";\nimport { checkAuthority } from \"./authority.js\";\nimport { checkFrontmatter } from \"./frontmatter.js\";\nimport { checkLinks } from \"./links.js\";\nimport { checkAreas } from \"./areas.js\";\nimport { checkDecisionSections } from \"./decisions.js\";\nimport { checkGeneratedSurfaces } from \"./generated-surfaces.js\";\nimport { checkFreshness } from \"../freshness/check.js\";\n\nexport type CheckOptions = {\n base?: string;\n};\n\nconst summarizeDiagnostics = (diagnostics: CommandResult[\"diagnostics\"]): string => {\n const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === \"error\").length;\n const reviewCount = diagnostics.filter((diagnostic) => diagnostic.severity === \"review\").length;\n\n if (diagnostics.length === 0) {\n return \"Truthmark check completed with no diagnostics.\";\n }\n\n return `Truthmark check completed with ${errorCount} error diagnostics and ${reviewCount} review diagnostics.`;\n};\n\nexport const runCheck = async (cwd: string, options: CheckOptions = {}): Promise<CommandResult> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const branchScope = await getBranchScopeData(rootDir);\n const loadResult = await loadConfig(rootDir);\n\n if (!loadResult.config) {\n return {\n command: \"check\",\n summary: summarizeDiagnostics(loadResult.diagnostics),\n diagnostics: loadResult.diagnostics,\n data: {\n branchScope,\n },\n };\n }\n\n const authority = await checkAuthority(rootDir, loadResult.config);\n const areas = await checkAreas(rootDir, loadResult.config);\n const markdownPaths = [...new Set([...authority.paths, ...areas.truthDocumentPaths])];\n const frontmatter = await checkFrontmatter(\n rootDir,\n loadResult.config,\n markdownPaths,\n areas.truthDocumentEntries,\n );\n const links = await checkLinks(rootDir, markdownPaths);\n const decisionSections = await checkDecisionSections(\n rootDir,\n loadResult.config,\n markdownPaths,\n areas.truthDocumentEntries,\n );\n const generatedSurfaces = await checkGeneratedSurfaces(rootDir, loadResult.config);\n const freshness = options.base\n ? await checkFreshness(rootDir, loadResult.config, areas.truthDocumentPaths, options.base)\n : null;\n const diagnostics = [\n ...loadResult.diagnostics,\n ...authority.diagnostics,\n ...frontmatter,\n ...links,\n ...areas.diagnostics,\n ...decisionSections,\n ...generatedSurfaces,\n ...(freshness?.diagnostics ?? []),\n ];\n const truthVisibility = {\n routePrecision: areas.routePrecision,\n unmappedSurfaceCount: diagnostics.filter((diagnostic) => diagnostic.category === \"coverage\")\n .length,\n staleGeneratedSurfaceCount: new Set(\n generatedSurfaces.map((diagnostic) => diagnostic.file).filter(Boolean),\n ).size,\n syncCompletenessIssueCount: diagnostics.filter(\n (diagnostic) =>\n diagnostic.category === \"doc-structure\" || diagnostic.category === \"generated-surface\",\n ).length,\n topologyPressureCount: areas.topologyPressureCount,\n freshnessDiagnosticCount: freshness?.diagnostics.length ?? 0,\n };\n\n return {\n command: \"check\",\n summary: summarizeDiagnostics(diagnostics),\n diagnostics,\n data: {\n branchScope,\n truthVisibility,\n ...(freshness ? { impactSet: freshness.impactSet } : {}),\n },\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport fg from \"fast-glob\";\n\nimport { buildImpactSet } from \"../impact/build.js\";\nimport type { ImpactSet } from \"../impact/types.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { buildRepoIndex } from \"../repo-index/build.js\";\nimport type { RepoDocEntry, RouteMap } from \"../repo-index/types.js\";\nimport type {\n ContextDocument,\n ContextPack,\n ContextPackOptions,\n ContextSourceFile,\n} from \"./types.js\";\n\nconst uniqueSorted = (values: string[]): string[] => [...new Set(values)].sort();\n\ntype ContextRoute = {\n codeSurface: string[];\n};\n\nconst repoRootPrefixes = [\".codex/\", \".github/\", \".truthmark/\", \"docs/\", \"src/\", \"tests/\"];\n\nconst isGlobReference = (referencePath: string): boolean => /[*?[\\]{}()]/u.test(referencePath);\n\nconst normalizeDocReferencePath = (docPath: string, referencePath: string): string | null => {\n const strippedPath = referencePath.split(\"#\")[0]?.trim() ?? \"\";\n if (strippedPath.length === 0 || strippedPath.startsWith(\"/\")) {\n return null;\n }\n\n const isRepoRelative = repoRootPrefixes.some((prefix) => strippedPath.startsWith(prefix));\n const normalized = isRepoRelative\n ? path.posix.normalize(strippedPath)\n : path.posix.normalize(path.posix.join(path.posix.dirname(docPath), strippedPath));\n\n return normalized === \"..\" || normalized.startsWith(\"../\") ? null : normalized;\n};\n\nconst readIfExists = async (rootDir: string, filePath: string): Promise<string | null> => {\n try {\n return await fs.readFile(path.join(rootDir, filePath), \"utf8\");\n } catch {\n return null;\n }\n};\n\nconst boundedContent = (\n filePath: string,\n content: string,\n warnings: Diagnostic[],\n): ContextSourceFile => {\n const lines = content.split(\"\\n\");\n\n if (lines.length <= 200) {\n return { path: filePath, content, truncated: false };\n }\n\n warnings.push({\n category: \"context-pack\",\n severity: \"review\",\n message: `Context source file ${filePath} was truncated to fit ContextPack v0 bounds.`,\n file: filePath,\n });\n\n return {\n path: filePath,\n content: [...lines.slice(0, 80), \"...\", ...lines.slice(-40)].join(\"\\n\"),\n truncated: true,\n };\n};\n\nconst documentsFor = async (\n rootDir: string,\n paths: string[],\n): Promise<ContextDocument[]> => {\n const documents: ContextDocument[] = [];\n\n for (const filePath of uniqueSorted(paths)) {\n const content = await readIfExists(rootDir, filePath);\n if (content !== null) {\n documents.push({ path: filePath, content });\n }\n }\n\n return documents;\n};\n\nconst sourceFilesFor = async (\n rootDir: string,\n paths: string[],\n warnings: Diagnostic[],\n): Promise<ContextSourceFile[]> => {\n const sourceFiles: ContextSourceFile[] = [];\n\n for (const filePath of uniqueSorted(paths)) {\n const content = await readIfExists(rootDir, filePath);\n if (content !== null) {\n sourceFiles.push(boundedContent(filePath, content, warnings));\n }\n }\n\n return sourceFiles;\n};\n\nconst sourceOfTruthPathsFor = async (\n rootDir: string,\n docs: RepoDocEntry[],\n truthDocPaths: string[],\n): Promise<string[]> => {\n const selectedTruthDocs = new Set(truthDocPaths);\n const sourcePaths: string[] = [];\n\n for (const doc of docs) {\n if (!selectedTruthDocs.has(doc.path)) {\n continue;\n }\n\n for (const referencePath of doc.sourceOfTruth) {\n const normalizedPath = normalizeDocReferencePath(doc.path, referencePath);\n if (!normalizedPath) {\n continue;\n }\n if (isGlobReference(normalizedPath)) {\n sourcePaths.push(\n ...(await fg(normalizedPath, {\n cwd: rootDir,\n dot: true,\n onlyFiles: true,\n followSymbolicLinks: false,\n })),\n );\n } else {\n sourcePaths.push(normalizedPath);\n }\n }\n }\n\n return uniqueSorted(sourcePaths);\n};\n\nconst writePathsFor = (\n workflow: ContextPackOptions[\"workflow\"],\n truthDocs: string[],\n routes: ContextRoute[],\n): string[] => {\n if (workflow === \"truth-sync\") {\n return uniqueSorted([\"docs/truthmark/areas.md\", ...truthDocs]);\n }\n\n if (workflow === \"truth-document\") {\n return uniqueSorted([\"docs/truthmark/areas.md\", ...truthDocs]);\n }\n\n return uniqueSorted(routes.flatMap((route) => route.codeSurface));\n};\n\nconst testCommandsFor = (affectedTests: string[]): string[] => {\n return affectedTests.length === 0\n ? [\"npm test\"]\n : [`npm test -- ${affectedTests.join(\" \")}`];\n};\n\nexport const buildContextPack = async (\n cwd: string,\n options: ContextPackOptions,\n): Promise<ContextPack> => {\n const repoIndex = await buildRepoIndex(cwd);\n const rootDir = repoIndex.repository.root;\n const impactSet: ImpactSet | null = options.base\n ? await buildImpactSet(rootDir, { base: options.base })\n : null;\n const routeMap: RouteMap = impactSet ? repoIndex.routeMap : repoIndex.routeMap;\n const warnings: Diagnostic[] = [];\n const truthDocPaths =\n impactSet?.affectedTruthDocs ??\n (options.workflow === \"truth-realize\" ? [] : routeMap.routes.flatMap((route) => route.truthDocs));\n const contextRoutes: ContextRoute[] =\n impactSet?.affectedRoutes ?? (options.workflow === \"truth-realize\" ? [] : routeMap.routes);\n if (options.workflow === \"truth-realize\" && !impactSet) {\n warnings.push({\n category: \"context-pack\",\n severity: \"review\",\n message: \"truth-realize requires --base to derive bounded allowed write paths.\",\n });\n }\n const sourceOfTruthPaths = await sourceOfTruthPathsFor(rootDir, repoIndex.docs, truthDocPaths);\n const sourceFilePaths = uniqueSorted([\n ...(impactSet?.changedFiles.filter((file) => !file.deleted).map((file) => file.path) ?? []),\n ...sourceOfTruthPaths,\n ]);\n\n return {\n schemaVersion: \"context-pack/v0\",\n workflow: options.workflow,\n base: options.base ?? null,\n impactSet,\n routeMap,\n allowedWritePaths: writePathsFor(options.workflow, truthDocPaths, contextRoutes),\n truthDocs: await documentsFor(rootDir, truthDocPaths),\n sourceFiles: await sourceFilesFor(rootDir, sourceFilePaths, warnings),\n testCommands: testCommandsFor(impactSet?.affectedTests ?? []),\n warnings,\n };\n};\n","import type { ContextPack } from \"./types.js\";\n\nexport const renderContextPackMarkdown = (pack: ContextPack): string => {\n const lines = [\n `# Truthmark ContextPack (${pack.workflow})`,\n \"\",\n `Schema: ${pack.schemaVersion}`,\n `Base: ${pack.base ?? \"none\"}`,\n \"\",\n \"## Allowed Write Paths\",\n ...pack.allowedWritePaths.map((filePath) => `- ${filePath}`),\n \"\",\n \"## Truth Docs\",\n ...pack.truthDocs.map((doc) => `- ${doc.path}`),\n \"\",\n \"## Source Files\",\n ...pack.sourceFiles.map((file) => `- ${file.path}${file.truncated ? \" (truncated)\" : \"\"}`),\n \"\",\n \"## Test Commands\",\n ...pack.testCommands.map((command) => `- ${command}`),\n ];\n\n return `${lines.join(\"\\n\")}\\n`;\n};\n","import { runConfig as runRepositoryConfig, type ConfigCommandOptions } from \"../config/command.js\";\nimport { runInit as runRepositoryInit } from \"../init/init.js\";\nimport { runCheck as runRepositoryCheck } from \"../checks/check.js\";\nimport type { CommandResult } from \"../output/diagnostic.js\";\nimport { buildImpactSet } from \"../impact/build.js\";\nimport { buildContextPack } from \"../context-pack/build.js\";\nimport { renderContextPackMarkdown } from \"../context-pack/render.js\";\nimport type { ContextPackWorkflow } from \"../context-pack/types.js\";\nimport { buildRepoIndex } from \"../repo-index/build.js\";\n\nexport const runConfig = async (options: ConfigCommandOptions): Promise<CommandResult> => {\n return runRepositoryConfig(process.cwd(), options);\n};\n\nexport const runInit = async (): Promise<CommandResult> => {\n return runRepositoryInit(process.cwd());\n};\n\nexport const runCheck = async (options: { base?: string } = {}): Promise<CommandResult> => {\n return runRepositoryCheck(process.cwd(), options);\n};\n\nexport const runIndex = async (): Promise<CommandResult> => {\n const repoIndex = await buildRepoIndex(process.cwd());\n const errorCount = repoIndex.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\").length;\n const reviewCount = repoIndex.diagnostics.filter((diagnostic) => diagnostic.severity === \"review\").length;\n\n return {\n command: \"index\",\n summary: `Truthmark index completed with ${errorCount} error diagnostics and ${reviewCount} review diagnostics.`,\n diagnostics: repoIndex.diagnostics,\n data: {\n repoIndex,\n routeMap: repoIndex.routeMap,\n },\n };\n};\n\nexport const runImpact = async (options: { base?: string }): Promise<CommandResult> => {\n if (!options.base) {\n return {\n command: \"impact\",\n summary: \"Truthmark impact requires --base.\",\n diagnostics: [\n {\n category: \"impact\",\n severity: \"error\",\n message: \"truthmark impact requires --base <ref>.\",\n },\n ],\n };\n }\n\n const impactSet = await buildImpactSet(process.cwd(), { base: options.base });\n const errorCount = impactSet.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\").length;\n const reviewCount = impactSet.diagnostics.filter((diagnostic) => diagnostic.severity === \"review\").length;\n\n return {\n command: \"impact\",\n summary: `Truthmark impact completed with ${errorCount} error diagnostics and ${reviewCount} review diagnostics.`,\n diagnostics: impactSet.diagnostics,\n data: {\n impactSet,\n },\n };\n};\n\nconst isContextPackWorkflow = (value: unknown): value is ContextPackWorkflow => {\n return value === \"truth-sync\" || value === \"truth-document\" || value === \"truth-realize\";\n};\n\nconst isContextPackFormat = (value: unknown): value is \"json\" | \"markdown\" | undefined => {\n return value === undefined || value === \"json\" || value === \"markdown\";\n};\n\nexport const runContext = async (options: {\n workflow?: string;\n base?: string;\n format?: string;\n}): Promise<CommandResult> => {\n if (!isContextPackWorkflow(options.workflow)) {\n return {\n command: \"context\",\n summary: \"Truthmark context requires a supported --workflow value.\",\n diagnostics: [\n {\n category: \"context-pack\",\n severity: \"error\",\n message: \"truthmark context requires --workflow truth-sync, truth-document, or truth-realize.\",\n },\n ],\n };\n }\n\n if (!isContextPackFormat(options.format)) {\n return {\n command: \"context\",\n summary: \"Truthmark context requires a supported --format value.\",\n diagnostics: [\n {\n category: \"context-pack\",\n severity: \"error\",\n message: \"truthmark context requires --format json or markdown.\",\n },\n ],\n };\n }\n\n const contextPack = await buildContextPack(process.cwd(), {\n workflow: options.workflow,\n base: options.base,\n });\n const diagnostics = contextPack.warnings;\n\n return {\n command: \"context\",\n summary: `Truthmark context generated ${contextPack.workflow} ContextPack with ${diagnostics.length} warnings.`,\n diagnostics,\n data: {\n contextPack,\n ...(options.format === \"markdown\" ? { markdown: renderContextPackMarkdown(contextPack) } : {}),\n },\n };\n};\n","import { buildProgram } from \"./program.js\";\n\nexport const main = async (argv: string[] = process.argv): Promise<void> => {\n\tawait buildProgram().parseAsync(argv);\n};\n\nmain().catch((error: unknown) => {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tprocess.stderr.write(`${message}\\n`);\n\tprocess.exitCode = 1;\n});"],"mappings":";;;AAAA,SAAS,eAAe;;;ACExB,IAAM,gBAAgB,CAAC,eAAmC;AACxD,QAAM,QAAkB,CAAC;AAEzB,MAAI,WAAW,MAAM;AACnB,UAAM,KAAK,SAAS,WAAW,IAAI,EAAE;AAAA,E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OAAO,YAA4B;AAC1C;AAAA,MACE,MAAM,WAAW;AAAA,QACf,UAAU,QAAQ;AAAA,QAClB,MAAM,QAAQ;AAAA,QACd,QAAQ,QAAQ;AAAA,MAClB,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF,CAAC;AAED,SAAO;AACT;;;AsDhHO,IAAM,OAAO,OAAO,OAAiB,QAAQ,SAAwB;AAC3E,QAAM,aAAa,EAAE,WAAW,IAAI;AACrC;AAEA,KAAK,EAAE,MAAM,CAAC,UAAmB;AAChC,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,UAAQ,OAAO,MAAM,GAAG,OAAO;AAAA,CAAI;AACnC,UAAQ,WAAW;AACpB,CAAC;","names":["fs","fs","path","path","path","path","fs","fs","fs","parse","fs","parse","fs","truthRoot","fs","truthRoot","fs","truthRoot","renderMarkdownExample","renderMarkdownExample","renderMarkdownExample","renderMarkdownExample","renderMarkdownExample","path","path","path","fs","fs","fg","fg","fs","fs","fg","fs","fg","fs","isTruthDocumentKind","fs","fs","path","pathExists","fs","path","fs","fg","micromatch","fs","fg","micromatch","micromatch","fs","fg","micromatch","looksLikeGlob","pathExists","fs","fg","micromatch","fs","micromatch","isTruthDocumentKind","escapeRegExp","micromatch","fs","fs","fs","path","micromatch","fs","path","fs","path","execa","fg","matter","micromatch","path","normalizePath","execa","micromatch","fg","fs","matter","fs","path","fg","path","fs","path","execa","fs","path","execa","normalizePath","execa","pathExists","fs","path","normalizePath","execa","micromatch","path","fs","fg","fs","path","matter","parse","pathExists","fs","fg","fs","path","fg","uniqueSorted","repoRootPrefixes","isGlobReference","path","fs","fg","runConfig","runInit","runCheck","runConfig","runInit","runCheck"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli/program.ts","../src/output/render.ts","../src/config/command.ts","../src/fs/paths.ts","../src/git/repository.ts","../src/templates/init-files.ts","../src/config/schema.ts","../src/config/defaults.ts","../src/routing/areas.ts","../src/truth/docs.ts","../src/init/init.ts","../src/config/load.ts","../src/init/hierarchy.ts","../src/truth/evidence.ts","../src/agents/shared.ts","../src/version.ts","../src/templates/agents-block.ts","../src/templates/default-standards.ts","../src/templates/workflow-surfaces.ts","../src/agents/workflow-manifest.ts","../src/agents/truth-check.ts","../src/agents/truth-document.ts","../src/agents/truth-preview.ts","../src/agents/truth-structure.ts","../src/sync/report.ts","../src/agents/truth-sync.ts","../src/agents/write-lease.ts","../src/templates/generated-surfaces.ts","../src/checks/branch-scope.ts","../src/markdown/hash.ts","../src/checks/authority.ts","../src/checks/frontmatter.ts","../src/markdown/parse.ts","../src/checks/links.ts","../src/checks/areas.ts","../src/routing/area-resolver.ts","../src/sync/classify.ts","../src/checks/decisions.ts","../src/checks/generated-surfaces.ts","../src/impact/build.ts","../src/repo-index/build.ts","../src/repo-index/file-tree.ts","../src/repo-index/package-metadata.ts","../src/repo-index/route-map.ts","../src/repo-index/typescript-symbols.ts","../src/impact/git-diff.ts","../src/git/changes.ts","../src/evidence/validate.ts","../src/evidence/parse.ts","../src/freshness/check.ts","../src/checks/check.ts","../src/context-pack/build.ts","../src/context-pack/render.ts","../src/cli/handlers.ts","../src/agents/workflow-helper-validation.ts","../src/cli/main.ts"],"sourcesContent":["import { Command } from \"commander\";\n\nimport type { CommandResult } from \"../output/diagnostic.js\";\nimport { renderHuman, renderJson } from \"../output/render.js\";\nimport {\n runCheck,\n runConfig,\n runContext,\n runImpact,\n runIndex,\n runInit,\n runValidateDocumentReport,\n runValidateSyncReport,\n runValidateWriteLease,\n} from \"./handlers.js\";\nimport type { WorkflowHelperValidationResult } from \"../agents/workflow-helper-validation.js\";\n\ntype OutputOptions = {\n json?: boolean;\n};\n\ntype ConfigOptions = OutputOptions & {\n stdout?: boolean;\n force?: boolean;\n};\n\ntype CheckCliOptions = OutputOptions & {\n base?: string;\n};\n\ntype ImpactOptions = OutputOptions & {\n base?: string;\n};\n\ntype ContextOptions = OutputOptions & {\n workflow?: string;\n base?: string;\n format?: string;\n};\n\nconst writeResult = (result: CommandResult, options: OutputOptions): void => {\n const output = options.json ? renderJson(result) : renderHuman(result);\n process.stdout.write(`${output}\\n`);\n};\nconst writeContextResult = (result: CommandResult, options: ContextOptions): void => {\n if (!options.json && options.format === \"markdown\" && typeof result.data?.markdown === \"string\") {\n process.stdout.write(result.data.markdown);\n return;\n }\n writeResult(result, options);\n};\n\nconst renderValidationHuman = (result: WorkflowHelperValidationResult): string => {\n if (result.ok === true) {\n return [`${result.helper}: ok`, ...result.checks.map((check) => `- ${check}`)].join(\"\\n\");\n }\n\n return [`${result.helper}: failed`, ...result.errors.map((error) => `- ${error}`)].join(\"\\n\");\n};\n\nconst toValidationCommandResult = (\n command: string,\n result: WorkflowHelperValidationResult,\n): CommandResult => ({\n command,\n summary: result.ok ? \"Validation passed\" : \"Validation failed\",\n diagnostics: [],\n data: {\n validation: result,\n },\n});\n\nconst writeValidationResult = (\n command: string,\n result: WorkflowHelperValidationResult,\n options: OutputOptions,\n): void => {\n const output = options.json\n ? renderJson(toValidationCommandResult(command, result))\n : renderValidationHuman(result);\n process.stdout.write(`${output}\\n`);\n\n if (!result.ok) {\n process.exitCode = 1;\n }\n};\n\nconst addJsonOption = (command: Command): Command => {\n return command.option(\"--json\", \"Render command output as JSON\");\n};\n\nexport const buildProgram = (): Command => {\n const program = new Command();\n\n program\n .name(\"truthmark\")\n .description(\"Git-native, branch-scoped truth workflow installer for local AI coding agents.\")\n .showHelpAfterError();\n\n addJsonOption(\n program\n .command(\"config\")\n .description(\"Create or render the Truthmark repository config before initialization.\")\n .option(\"--stdout\", \"Render default config in the JSON data payload without writing\")\n .option(\"--force\", \"Overwrite an existing .truthmark/config.yml\"),\n ).action(async (options: ConfigOptions) => {\n writeResult(await runConfig(options), options);\n });\n\n addJsonOption(\n program\n .command(\"init\")\n .description(\"Initialize Truthmark workflow files in the current repository.\"),\n ).action(async (options: OutputOptions) => {\n writeResult(await runInit(), options);\n });\n\n addJsonOption(\n program\n .command(\"check\")\n .description(\"Run local Truthmark diagnostics.\")\n .option(\"--base <ref>\", \"Base Git ref for freshness diagnostics\"),\n ).action(async (options: CheckCliOptions) => {\n writeResult(await runCheck({ base: options.base }), options);\n });\n\n addJsonOption(\n program.command(\"index\").description(\"Build the deterministic Truthmark repository index.\"),\n ).action(async (options: OutputOptions) => {\n writeResult(await runIndex(), options);\n });\n\n addJsonOption(\n program\n .command(\"impact\")\n .description(\"Map changed files to truth routes, docs, owners, and tests.\")\n .requiredOption(\"--base <ref>\", \"Base Git ref to compare against\"),\n ).action(async (options: ImpactOptions) => {\n writeResult(await runImpact({ base: options.base }), options);\n });\n\n addJsonOption(\n program\n .command(\"context\")\n .description(\"Generate a bounded workflow context pack.\")\n .requiredOption(\"--workflow <workflow>\", \"Workflow name: truth-sync, truth-document, or truth-realize\")\n .option(\"--base <ref>\", \"Base Git ref for impact-backed packs\")\n .option(\"--format <format>\", \"Output format: json or markdown\", \"json\"),\n ).action(async (options: ContextOptions) => {\n writeContextResult(\n await runContext({\n workflow: options.workflow,\n base: options.base,\n format: options.format,\n }),\n options,\n );\n });\n\n const validate = program\n .command(\"validate\")\n .description(\"Run optional Truthmark workflow helper validators from the installed CLI.\");\n\n addJsonOption(\n validate\n .command(\"sync-report\")\n .description(\"Validate a Truth Sync report file.\")\n .argument(\"<report-file>\", \"Truth Sync report file\"),\n ).action(async (reportFile: string, options: OutputOptions) => {\n writeValidationResult(\"validate sync-report\", await runValidateSyncReport(reportFile), options);\n });\n\n addJsonOption(\n validate\n .command(\"document-report\")\n .description(\"Validate a Truth Document report file.\")\n .argument(\"<report-file>\", \"Truth Document report file\"),\n ).action(async (reportFile: string, options: OutputOptions) => {\n writeValidationResult(\n \"validate document-report\",\n await runValidateDocumentReport(reportFile),\n options,\n );\n });\n\n addJsonOption(\n validate\n .command(\"write-lease\")\n .description(\"Validate a workflow write lease or worker report against changed files.\")\n .argument(\"<lease-or-report-file>\", \"Lease or worker report file\")\n .argument(\"<changed-files-file>\", \"Newline-separated changed file list\"),\n ).action(\n async (\n leaseOrReportFile: string,\n changedFilesFile: string,\n options: OutputOptions,\n ) => {\n writeValidationResult(\n \"validate write-lease\",\n await runValidateWriteLease(leaseOrReportFile, changedFilesFile),\n options,\n );\n },\n );\n\n return program;\n};\n","import type { CommandResult, Diagnostic } from \"./diagnostic.js\";\n\nconst formatContext = (diagnostic: Diagnostic): string => {\n const parts: string[] = [];\n\n if (diagnostic.file) {\n parts.push(`file: ${diagnostic.file}`);\n }\n\n if (diagnostic.area) {\n parts.push(`area: ${diagnostic.area}`);\n }\n\n return parts.length > 0 ? ` (${parts.join(\", \")})` : \"\";\n};\n\nconst toStableValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => toStableValue(entry));\n }\n\n if (value && typeof value === \"object\") {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((stable, key) => {\n stable[key] = toStableValue((value as Record<string, unknown>)[key]);\n return stable;\n }, {});\n }\n\n return value;\n};\n\nexport const renderHuman = (result: CommandResult): string => {\n const lines = [`truthmark ${result.command}`, result.summary];\n\n if (result.diagnostics.length > 0) {\n lines.push(\"\");\n }\n\n for (const diagnostic of result.diagnostics) {\n lines.push(\n `[${diagnostic.severity.toUpperCase()}] ${diagnostic.category}: ${diagnostic.message}${formatContext(diagnostic)}`,\n );\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const renderJson = (result: CommandResult): string => {\n return JSON.stringify(toStableValue(result), null, 2);\n};","import fs from \"node:fs/promises\";\n\nimport type { CommandResult } from \"../output/diagnostic.js\";\nimport { ensureRepoFile, resolveRepoPath, writeRepoFile } from \"../fs/paths.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport { renderConfigTemplate } from \"../templates/init-files.js\";\n\nexport type ConfigCommandOptions = {\n stdout?: boolean;\n force?: boolean;\n};\n\nconst CONFIG_PATH = \".truthmark/config.yml\";\n\nconst configExists = async (rootDir: string): Promise<boolean> => {\n try {\n await fs.stat(resolveRepoPath(rootDir, CONFIG_PATH));\n return true;\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n\n throw error;\n }\n};\n\nexport const runConfig = async (\n cwd: string,\n options: ConfigCommandOptions = {},\n): Promise<CommandResult> => {\n const repository = await getGitRepository(cwd);\n const content = renderConfigTemplate();\n\n if (options.stdout) {\n return {\n command: \"config\",\n summary: \"Rendered default Truthmark config.\",\n diagnostics: [],\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n path: CONFIG_PATH,\n content,\n },\n };\n }\n\n const exists = await configExists(repository.worktreePath);\n\n if (exists && !options.force) {\n return {\n command: \"config\",\n summary: \"Truthmark config already exists. Use --force to overwrite it.\",\n diagnostics: [\n {\n category: \"config\",\n severity: \"review\",\n message: \"Existing .truthmark/config.yml was left unchanged.\",\n file: CONFIG_PATH,\n },\n ],\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n },\n };\n }\n\n const result = options.force\n ? await writeRepoFile(repository.worktreePath, CONFIG_PATH, content)\n : await ensureRepoFile(repository.worktreePath, CONFIG_PATH, content);\n\n return {\n command: \"config\",\n summary: `Wrote Truthmark config to ${CONFIG_PATH}. Review it before running truthmark init.`,\n diagnostics: [\n {\n category: \"config\",\n severity: \"action\",\n message: result.status === \"updated\" ? `Updated ${CONFIG_PATH}.` : `Created ${CONFIG_PATH}.`,\n file: CONFIG_PATH,\n },\n ],\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n },\n };\n};\n","import path from \"node:path\";\n\nimport fs from \"node:fs/promises\";\n\nexport type FileWriteStatus = \"created\" | \"updated\" | \"unchanged\";\n\nexport type FileWriteResult = {\n path: string;\n status: FileWriteStatus;\n};\n\nconst isPathInsideRoot = (rootDir: string, targetPath: string): boolean => {\n return targetPath === rootDir || targetPath.startsWith(`${rootDir}${path.sep}`);\n};\n\nconst isNodeErrorWithCode = (error: unknown, code: string): boolean => {\n return error instanceof Error && \"code\" in error && error.code === code;\n};\n\nconst joinMissingSegments = (resolvedPath: string, missingSegments: string[]): string => {\n return missingSegments.reduce<string>((currentResolvedPath, segment) => {\n return path.join(currentResolvedPath, segment);\n }, resolvedPath);\n};\n\nconst resolveThroughExistingAncestor = async (targetPath: string): Promise<string> => {\n let currentPath = path.resolve(targetPath);\n const missingSegments: string[] = [];\n\n while (true) {\n try {\n const resolvedExistingPath = await fs.realpath(currentPath);\n\n return joinMissingSegments(resolvedExistingPath, missingSegments);\n } catch (error: unknown) {\n if (!isNodeErrorWithCode(error, \"ENOENT\")) {\n throw error;\n }\n\n try {\n const currentStat = await fs.lstat(currentPath);\n\n if (currentStat.isSymbolicLink()) {\n const linkTarget = await fs.readlink(currentPath);\n const resolvedLinkTarget = path.resolve(path.dirname(currentPath), linkTarget);\n\n return joinMissingSegments(resolvedLinkTarget, missingSegments);\n }\n } catch (lstatError: unknown) {\n if (!isNodeErrorWithCode(lstatError, \"ENOENT\")) {\n throw lstatError;\n }\n }\n\n const parentPath = path.dirname(currentPath);\n\n if (parentPath === currentPath) {\n return path.resolve(targetPath);\n }\n\n missingSegments.unshift(path.basename(currentPath));\n currentPath = parentPath;\n }\n }\n};\n\nexport const resolveRepoPath = (rootDir: string, relativePath: string): string => {\n const resolvedPath = path.resolve(rootDir, relativePath);\n\n if (!isPathInsideRoot(rootDir, resolvedPath)) {\n throw new Error(\"resolved path must stay inside the repository root\");\n }\n\n return resolvedPath;\n};\n\nexport const assertRepoContainment = async (\n rootDir: string,\n targetPath: string,\n): Promise<void> => {\n const [resolvedRootDir, resolvedTargetPath] = await Promise.all([\n resolveThroughExistingAncestor(rootDir),\n resolveThroughExistingAncestor(targetPath),\n ]);\n\n if (!isPathInsideRoot(resolvedRootDir, resolvedTargetPath)) {\n throw new Error(\"resolved path must stay inside the repository root\");\n }\n};\n\nexport const toRepoRelativePath = (rootDir: string, targetPath: string): string => {\n return path.relative(rootDir, targetPath).split(path.sep).join(\"/\");\n};\n\nconst normalizeContent = (content: string): string => {\n return content.endsWith(\"\\n\") ? content : `${content}\\n`;\n};\n\nexport const writeRepoFile = async (\n rootDir: string,\n relativePath: string,\n content: string,\n): Promise<FileWriteResult> => {\n const absolutePath = resolveRepoPath(rootDir, relativePath);\n await assertRepoContainment(rootDir, absolutePath);\n const normalizedContent = normalizeContent(content);\n\n let existingContent: string | null = null;\n\n try {\n existingContent = await fs.readFile(absolutePath, \"utf8\");\n } catch (error: unknown) {\n if (!(error instanceof Error) || !(\"code\" in error) || error.code !== \"ENOENT\") {\n throw error;\n }\n }\n\n if (existingContent === normalizedContent) {\n return {\n path: relativePath,\n status: \"unchanged\",\n };\n }\n\n await fs.mkdir(path.dirname(absolutePath), { recursive: true });\n await fs.writeFile(absolutePath, normalizedContent, \"utf8\");\n\n return {\n path: relativePath,\n status: existingContent === null ? \"created\" : \"updated\",\n };\n};\n\nexport const ensureRepoFile = async (\n rootDir: string,\n relativePath: string,\n content: string,\n): Promise<FileWriteResult> => {\n const absolutePath = resolveRepoPath(rootDir, relativePath);\n await assertRepoContainment(rootDir, absolutePath);\n const normalizedContent = normalizeContent(content);\n\n let existingContent: string | null = null;\n\n try {\n existingContent = await fs.readFile(absolutePath, \"utf8\");\n } catch (error: unknown) {\n if (!(error instanceof Error) || !(\"code\" in error) || error.code !== \"ENOENT\") {\n throw error;\n }\n }\n\n if (existingContent === null) {\n await fs.mkdir(path.dirname(absolutePath), { recursive: true });\n await fs.writeFile(absolutePath, normalizedContent, \"utf8\");\n\n return {\n path: relativePath,\n status: \"created\",\n };\n }\n\n if (existingContent.trim().length === 0) {\n await fs.mkdir(path.dirname(absolutePath), { recursive: true });\n await fs.writeFile(absolutePath, normalizedContent, \"utf8\");\n\n return {\n path: relativePath,\n status: \"updated\",\n };\n }\n\n return {\n path: relativePath,\n status: \"unchanged\",\n };\n};\n","import fs from \"node:fs/promises\";\nimport { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { execa } from \"execa\";\n\nexport type GitRepository = {\n repositoryRoot: string;\n worktreePath: string;\n branchName: string | null;\n headSha: string | null;\n isDetached: boolean;\n isUnborn: boolean;\n};\n\nconst realpathOrResolved = async (targetPath: string): Promise<string> => {\n try {\n return await fs.realpath(targetPath);\n } catch {\n return path.resolve(targetPath);\n }\n};\n\nconst runGit = async (\n cwd: string,\n args: string[],\n reject = true,\n): Promise<{ stdout: string; exitCode: number }> => {\n const result = await execa(\"git\", args, { cwd, reject });\n\n return {\n stdout: result.stdout,\n exitCode: result.exitCode ?? 1,\n };\n};\n\nexport const getGitRepository = async (cwd: string): Promise<GitRepository> => {\n const worktreePath = await realpathOrResolved(\n (await runGit(cwd, [\"rev-parse\", \"--show-toplevel\"])).stdout.trim(),\n );\n const commonDirOutput = (await runGit(cwd, [\"rev-parse\", \"--git-common-dir\"])).stdout.trim();\n const commonDir = await realpathOrResolved(path.resolve(worktreePath, commonDirOutput));\n const repositoryRoot = path.basename(commonDir) === \".git\" ? path.dirname(commonDir) : worktreePath;\n\n const branchResult = await runGit(cwd, [\"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"], false);\n const headResult = await runGit(cwd, [\"rev-parse\", \"--verify\", \"HEAD\"], false);\n\n const branchName = branchResult.exitCode === 0 ? branchResult.stdout.trim() : null;\n const headSha = headResult.exitCode === 0 ? headResult.stdout.trim() : null;\n const isDetached = branchName === null;\n const isUnborn = !isDetached && headSha === null;\n\n return {\n repositoryRoot,\n worktreePath,\n branchName,\n headSha,\n isDetached,\n isUnborn,\n };\n};\n\nexport const resolveWorktreePath = (\n repository: Pick<GitRepository, \"worktreePath\">,\n relativePath: string,\n): string => {\n const resolvedPath = path.resolve(repository.worktreePath, relativePath);\n let currentPath = resolvedPath;\n const missingSegments: string[] = [];\n\n const resolveContainedPath = (): string => {\n while (true) {\n try {\n return missingSegments.reduceRight<string>((resolvedExistingPath, segment) => {\n return path.join(resolvedExistingPath, segment);\n }, realpathSync(currentPath));\n } catch (error: unknown) {\n if (!(error instanceof Error) || !(\"code\" in error) || error.code !== \"ENOENT\") {\n throw error;\n }\n\n const parentPath = path.dirname(currentPath);\n\n if (parentPath === currentPath) {\n return resolvedPath;\n }\n\n missingSegments.unshift(path.basename(currentPath));\n currentPath = parentPath;\n }\n }\n };\n const containedPath = resolveContainedPath();\n\n if (\n containedPath !== repository.worktreePath &&\n !containedPath.startsWith(`${repository.worktreePath}${path.sep}`)\n ) {\n throw new Error(\"resolved path must stay inside the active worktree\");\n }\n\n return resolvedPath;\n};\n","import path from \"node:path\";\nimport { stringify } from \"yaml\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { DiscoveredMarkdownDocument } from \"../markdown/discovery.js\";\nimport {\n createDefaultConfig,\n createDefaultRawConfig,\n} from \"../config/defaults.js\";\nimport { inferTruthDocumentKindFromPath } from \"../routing/areas.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\n\nconst asRelativePath = (value: string): string => {\n return value.split(path.sep).join(\"/\");\n};\n\nconst currentDate = (): string => new Date().toISOString().slice(0, 10);\n\nconst resolveRelativePath = (fromPath: string, toPath: string): string => {\n return asRelativePath(path.relative(path.dirname(fromPath), toPath));\n};\n\nconst truthRoot = resolveTruthDocsRoot;\n\nconst renderTruthDocumentsMetadata = (\n documents: Array<{ path: string; kind: string }>,\n): string[] => {\n return [\n \"```yaml\",\n stringify({ truth_documents: documents }).trimEnd(),\n \"```\",\n ];\n};\n\nexport const renderConfigTemplate = (): string => {\n return stringify(createDefaultRawConfig());\n};\n\nexport const renderAreasTemplate = (\n documents: DiscoveredMarkdownDocument[],\n): string => {\n const truthDocuments =\n documents.length > 0\n ? documents.map((document) => ({\n path: document.path,\n kind: inferTruthDocumentKindFromPath(document.path) ?? \"behavior\",\n }))\n : [{ path: \"docs/truth/**/*.md\", kind: \"behavior\" }];\n\n return [\n \"# Truthmark Areas\",\n \"\",\n \"## Repository Truth Surface\",\n \"\",\n \"Truth documents:\",\n ...renderTruthDocumentsMetadata(truthDocuments),\n \"\",\n \"Code surface:\",\n \"- src/**\",\n \"\",\n \"Update truth when:\",\n \"- behavior changes affect the routed truth documents\",\n \"- API contracts or current feature behavior changes\",\n \"\",\n ].join(\"\\n\");\n};\n\nconst titleCase = (value: string): string => {\n return value\n .split(/[-_\\s]+/u)\n .filter(Boolean)\n .map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))\n .join(\" \");\n};\n\nexport const renderHierarchicalAreasIndexTemplate = (\n config: TruthmarkConfig,\n): string => {\n const defaultArea = config.docs.routing.defaultArea;\n const childPath = `${config.docs.routing.areaFilesRoot}/${defaultArea}.md`;\n const title = titleCase(defaultArea);\n const sourceOfTruth = resolveRelativePath(\n config.docs.routing.rootIndex,\n \".truthmark/config.yml\",\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: route-index\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n ` - ${sourceOfTruth}`,\n \"---\",\n \"\",\n \"# Truthmark Areas\",\n \"\",\n `## ${title}`,\n \"\",\n \"Area files:\",\n `- ${childPath}`,\n \"\",\n \"Code surface:\",\n \"- src/**\",\n \"\",\n \"Update truth when:\",\n \"- behavior changes affect the routed truth documents\",\n \"- API contracts or current feature behavior changes\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderChildAreaTemplate = (config: TruthmarkConfig): string => {\n const defaultArea = config.docs.routing.defaultArea;\n const title = titleCase(defaultArea);\n const truthDocsRoot = truthRoot(config);\n const leafTruthDoc = `${truthDocsRoot}/${defaultArea}/overview.md`;\n const templatePath = `${config.docs.routing.areaFilesRoot}/${defaultArea}.md`;\n const sourceOfTruth = resolveRelativePath(templatePath, \".truthmark/config.yml\");\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: area-route\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n ` - ${sourceOfTruth}`,\n \"---\",\n \"\",\n `# ${title} Areas`,\n \"\",\n `## ${title}`,\n \"\",\n \"Truth documents:\",\n \"```yaml\",\n \"truth_documents:\",\n ` - path: ${leafTruthDoc}`,\n \" kind: behavior\",\n \"```\",\n \"\",\n \"Code surface:\",\n \"- src/**\",\n \"\",\n \"Update truth when:\",\n \"- behavior changes affect repository truth\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderTruthRootReadmeTemplate = (\n config: TruthmarkConfig = createDefaultConfig(),\n): string => {\n const templatePath = `${truthRoot(config)}/README.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n config.docs.routing.rootIndex,\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: index\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n ` - ${sourceOfTruth}`,\n \"---\",\n \"\",\n \"# Truth Docs\",\n \"\",\n \"This directory is an index for current truth docs organized by the configured Truthmark hierarchy.\",\n \"\",\n \"README.md files are indexes, not Truth Sync targets. Keep bounded truth in leaf docs under `<domain>/<behavior>.md`.\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderTruthDomainReadmeTemplate = (config: TruthmarkConfig): string => {\n const defaultArea = config.docs.routing.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/README.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n `${config.docs.routing.areaFilesRoot}/${defaultArea}.md`,\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: index\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n ` - ${sourceOfTruth}`,\n \"---\",\n \"\",\n `# ${title} Truth Docs`,\n \"\",\n `This directory indexes bounded ${title.toLowerCase()} truth docs.`,\n \"\",\n \"README.md files are indexes, not Truth Sync targets. Keep bounded truth in leaf docs in this directory.\",\n \"\",\n \"Current leaf docs:\",\n \"\",\n \"- [Overview](overview.md)\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const BEHAVIOR_DOC_TEMPLATE_PATH = \"docs/templates/behavior-doc.md\";\nexport const CONTRACT_DOC_TEMPLATE_PATH = \"docs/templates/contract-doc.md\";\nexport const ARCHITECTURE_DOC_TEMPLATE_PATH = \"docs/templates/architecture-doc.md\";\nexport const WORKFLOW_DOC_TEMPLATE_PATH = \"docs/templates/workflow-doc.md\";\nexport const OPERATIONS_DOC_TEMPLATE_PATH = \"docs/templates/operations-doc.md\";\nexport const TEST_BEHAVIOR_DOC_TEMPLATE_PATH = \"docs/templates/test-behavior-doc.md\";\n\nexport const renderBehaviorDocTemplateFile = (): string => {\n return [\n \"---\",\n \"status: active\",\n \"doc_type: behavior\",\n \"truth_kind: behavior\",\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n \" - {{source_of_truth}}\",\n \"---\",\n \"\",\n \"# {{title}}\",\n \"\",\n \"## Purpose\",\n \"\",\n \"<!-- State why this feature exists, the user or system outcome it protects, and the problem it solves. Keep roadmap or implementation plans out of this section. -->\",\n \"\",\n \"{{purpose}}\",\n \"\",\n \"## Scope\",\n \"\",\n \"{{scope}}\",\n \"\",\n \"<!--\",\n \"This doc must own one coherent behavior surface.\",\n \"Split into another leaf doc when content introduces:\",\n \"- a distinct user or system outcome\",\n \"- a separate lifecycle or state machine\",\n \"- an unrelated rule family\",\n \"- a different external contract\",\n \"- code that should route through a different owner\",\n \"Keep README.md files as indexes only.\",\n \"-->\",\n \"\",\n \"This doc was created from the editable behavior-doc template at {{template_path}}.\",\n \"\",\n \"## Current Behavior\",\n \"\",\n \"<!-- Describe implemented behavior in present tense. Do not include desired future behavior. -->\",\n \"\",\n \"{{current_behavior}}\",\n \"\",\n \"## Core Rules\",\n \"\",\n \"<!-- Capture stable business rules, invariants, precedence rules, validation rules, and must-never constraints. Omit incidental implementation details. -->\",\n \"\",\n \"{{core_rules}}\",\n \"\",\n \"## Flows And States\",\n \"\",\n \"<!-- Use for route switches, state transitions, lifecycle stages, retries, fallbacks, and important error paths. Write 'None beyond current behavior.' when no distinct flow or state model exists. -->\",\n \"\",\n \"{{flows_and_states}}\",\n \"\",\n \"## Contracts\",\n \"\",\n \"<!-- Capture user-visible or integration contracts: CLI/API shape, inputs, outputs, diagnostics, files, events, permissions, or links to canonical contract docs. Avoid duplicating a separate canonical contract doc. -->\",\n \"\",\n \"{{contracts}}\",\n \"\",\n \"## Product Decisions\",\n \"\",\n \"<!-- Keep active decisions only. Replace stale decisions instead of appending historical logs. -->\",\n \"\",\n \"{{decision}}\",\n \"\",\n \"## Rationale\",\n \"\",\n \"<!-- Explain why the current behavior and active decisions are this way, including tradeoffs. -->\",\n \"\",\n \"{{rationale}}\",\n \"\",\n \"## Non-Goals\",\n \"\",\n \"<!-- Name adjacent behavior this doc intentionally does not own, especially tempting future expansions. -->\",\n \"\",\n \"{{non_goals}}\",\n \"\",\n \"## Maintenance Notes\",\n \"\",\n \"<!-- List related tests, routing cautions, migration notes, and common drift risks for future agents. Keep this operational, not historical. -->\",\n \"\",\n \"{{maintenance_notes}}\",\n \"\",\n ].join(\"\\n\");\n};\n\nconst renderTypedTruthDocTemplate = (\n truthKind: string,\n docType: string,\n title: string,\n sections: string[],\n): string => {\n const placeholderNameForSection = (section: string): string => {\n return section\n .replace(/^#+\\s+/u, \"\")\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n };\n\n return [\n \"---\",\n \"status: active\",\n `doc_type: ${docType}`,\n `truth_kind: ${truthKind}`,\n `last_reviewed: ${currentDate()}`,\n \"source_of_truth:\",\n \" - {{source_of_truth}}\",\n \"---\",\n \"\",\n `# ${title}`,\n \"\",\n \"## Purpose\",\n \"\",\n \"{{purpose}}\",\n \"\",\n \"## Scope\",\n \"\",\n \"{{scope}}\",\n \"\",\n ...sections.flatMap((section) => [\n section,\n \"\",\n `{{${placeholderNameForSection(section)}}}`,\n \"\",\n ]),\n \"## Product Decisions\",\n \"\",\n \"{{decision}}\",\n \"\",\n \"## Rationale\",\n \"\",\n \"{{rationale}}\",\n \"\",\n \"## Non-Goals\",\n \"\",\n \"{{non_goals}}\",\n \"\",\n \"## Maintenance Notes\",\n \"\",\n \"{{maintenance_notes}}\",\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderContractDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"contract\", \"contract\", \"{{title}}\", [\n \"## Contract Surface\",\n \"## Inputs\",\n \"## Outputs\",\n \"## Errors And Diagnostics\",\n \"## Compatibility Rules\",\n \"## Versioning And Migration\",\n ]);\n};\n\nexport const renderArchitectureDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"architecture\", \"architecture\", \"{{title}}\", [\n \"## System Role\",\n \"## Boundaries\",\n \"## Components\",\n \"## Data And Control Flow\",\n \"## Ownership\",\n \"## Cross-Cutting Constraints\",\n ]);\n};\n\nexport const renderWorkflowDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"workflow\", \"behavior\", \"{{title}}\", [\n \"## Triggers\",\n \"## Inputs\",\n \"## Execution Model\",\n \"## Steps\",\n \"## State, Retry, And Failure Behavior\",\n \"## Outputs\",\n ]);\n};\n\nexport const renderOperationsDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"operations\", \"behavior\", \"{{title}}\", [\n \"## Operational Surface\",\n \"## Runtime Topology\",\n \"## Configuration\",\n \"## Permissions\",\n \"## Deployment And Rollback\",\n \"## Availability And Observability\",\n ]);\n};\n\nexport const renderTestBehaviorDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"test-behavior\", \"behavior\", \"{{title}}\", [\n \"## Test Surface\",\n \"## Fixtures And Data Model\",\n \"## Execution Model\",\n \"## Assertions And Invariants\",\n \"## Isolation Rules\",\n \"## Reporting And Failure Semantics\",\n ]);\n};\n\nconst renderTemplate = (template: string, values: Record<string, string>): string => {\n return Object.entries(values).reduce((rendered, [key, value]) => {\n return rendered.split(`{{${key}}}`).join(value);\n }, template);\n};\n\nexport const renderBehaviorLeafDocTemplate = (\n config: TruthmarkConfig,\n template = renderBehaviorDocTemplateFile(),\n): string => {\n const defaultArea = config.docs.routing.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/overview.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n `${config.docs.routing.areaFilesRoot}/${defaultArea}.md`,\n );\n const today = currentDate();\n\n return renderTemplate(template, {\n area: defaultArea,\n contracts:\n \"- External contracts should link to the nearest canonical contract doc when one exists.\",\n core_rules:\n \"- Truth README files are indexes; behavior truth belongs in bounded leaf docs.\",\n current_behavior:\n \"- Document current behavior here when implementation changes make repository truth incomplete.\",\n decision: `- Decision (${today}): Truth README files are indexes; behavior truth belongs in bounded leaf docs.`,\n flows_and_states: \"- None beyond current behavior.\",\n maintenance_notes:\n \"- Update this doc when routed implementation changes alter current behavior, rules, contracts, or decisions.\",\n non_goals:\n \"- This doc is not a catch-all for unrelated repository behavior.\",\n purpose: `Describe why the default ${title.toLowerCase()} behavior surface exists and what outcome it protects.`,\n rationale:\n \"Bounded leaf docs keep agent context focused and prevent large products from accumulating unreviewable feature manuals.\",\n scope: `This bounded leaf truth doc owns the default ${title.toLowerCase()} behavior surface created by Truthmark.`,\n source_of_truth: sourceOfTruth,\n template_path: BEHAVIOR_DOC_TEMPLATE_PATH,\n title: `${title} Overview`,\n truth_kind: \"behavior\",\n });\n};\n","import type { JSONSchemaType } from \"ajv\";\n\nexport const SUPPORTED_PLATFORMS = [\n \"codex\",\n \"opencode\",\n \"claude-code\",\n \"github-copilot\",\n \"gemini-cli\",\n] as const;\n\nexport type TruthmarkPlatform = (typeof SUPPORTED_PLATFORMS)[number];\n\nexport const DEFAULT_PLATFORMS = [\n \"codex\",\n \"opencode\",\n \"claude-code\",\n \"github-copilot\",\n \"gemini-cli\",\n] as const satisfies\n readonly TruthmarkPlatform[];\n\nexport type RawDocsHierarchyConfig = {\n layout: \"hierarchical\";\n roots: Record<string, string>;\n routing: {\n root_index: string;\n area_files_root: string;\n default_area: string;\n max_delegation_depth: 1;\n };\n};\n\nexport type DocsHierarchyConfig = {\n layout: \"hierarchical\";\n roots: Record<string, string>;\n routing: {\n rootIndex: string;\n areaFilesRoot: string;\n defaultArea: string;\n maxDelegationDepth: 1;\n };\n};\n\nexport type RawTruthmarkConfig = {\n version: 1;\n platforms?: TruthmarkPlatform[];\n docs?: RawDocsHierarchyConfig;\n authority: string[];\n instruction_targets?: string[];\n frontmatter?: {\n required?: string[];\n recommended?: string[];\n };\n ignore?: string[];\n};\n\nexport type TruthmarkConfig = {\n version: 1;\n platforms: TruthmarkPlatform[];\n docs: DocsHierarchyConfig;\n authority: string[];\n instructionTargets: string[];\n frontmatter: {\n required: string[];\n recommended: string[];\n };\n ignore: string[];\n};\n\nexport const truthmarkConfigSchema: JSONSchemaType<RawTruthmarkConfig> = {\n type: \"object\",\n additionalProperties: false,\n required: [\"version\", \"authority\"],\n properties: {\n version: {\n type: \"integer\",\n const: 1,\n },\n platforms: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n enum: [...SUPPORTED_PLATFORMS],\n },\n minItems: 1,\n },\n docs: {\n type: \"object\",\n nullable: true,\n additionalProperties: false,\n required: [\"layout\", \"roots\", \"routing\"],\n properties: {\n layout: {\n type: \"string\",\n const: \"hierarchical\",\n },\n roots: {\n type: \"object\",\n required: [],\n additionalProperties: {\n type: \"string\",\n },\n },\n routing: {\n type: \"object\",\n additionalProperties: false,\n required: [\"root_index\", \"area_files_root\", \"default_area\", \"max_delegation_depth\"],\n properties: {\n root_index: {\n type: \"string\",\n },\n area_files_root: {\n type: \"string\",\n },\n default_area: {\n type: \"string\",\n },\n max_delegation_depth: {\n type: \"integer\",\n const: 1,\n },\n },\n },\n },\n },\n authority: {\n type: \"array\",\n items: {\n type: \"string\",\n },\n minItems: 1,\n },\n instruction_targets: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n },\n },\n frontmatter: {\n type: \"object\",\n nullable: true,\n additionalProperties: false,\n required: [],\n properties: {\n required: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n },\n },\n recommended: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n },\n },\n },\n },\n ignore: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n },\n },\n },\n};\n","import { DEFAULT_PLATFORMS, type TruthmarkConfig } from \"./schema.js\";\n\nexport const DEFAULT_DOCS_HIERARCHY = {\n layout: \"hierarchical\",\n roots: {\n ai: \"docs/ai\",\n standards: \"docs/standards\",\n architecture: \"docs/architecture\",\n truth: \"docs/truth\",\n },\n routing: {\n root_index: \"docs/truthmark/areas.md\",\n area_files_root: \"docs/truthmark/areas\",\n default_area: \"repository\",\n max_delegation_depth: 1,\n },\n} as const;\n\nexport const DEFAULT_AUTHORITY = [\n DEFAULT_DOCS_HIERARCHY.routing.root_index,\n `${DEFAULT_DOCS_HIERARCHY.routing.area_files_root}/**/*.md`,\n `${DEFAULT_DOCS_HIERARCHY.roots.ai}/**/*.md`,\n `${DEFAULT_DOCS_HIERARCHY.roots.standards}/**/*.md`,\n `${DEFAULT_DOCS_HIERARCHY.roots.architecture}/**/*.md`,\n `${DEFAULT_DOCS_HIERARCHY.roots.truth}/**/*.md`,\n] as const;\n\nexport const DEFAULT_INSTRUCTION_TARGETS = [\"AGENTS.md\"] as const;\n\nexport const createDefaultRawConfig = () => ({\n version: 1 as const,\n platforms: [...DEFAULT_PLATFORMS],\n docs: {\n layout: DEFAULT_DOCS_HIERARCHY.layout,\n roots: { ...DEFAULT_DOCS_HIERARCHY.roots },\n routing: { ...DEFAULT_DOCS_HIERARCHY.routing },\n },\n authority: [...DEFAULT_AUTHORITY],\n instruction_targets: [...DEFAULT_INSTRUCTION_TARGETS],\n frontmatter: {\n required: [],\n recommended: [\"status\", \"doc_type\", \"last_reviewed\", \"source_of_truth\"],\n },\n ignore: [\"node_modules/**\", \"vendor/**\", \"dist/**\", \"build/**\"],\n});\n\nexport const createDefaultConfig = (): TruthmarkConfig => ({\n version: 1,\n platforms: [...DEFAULT_PLATFORMS],\n docs: {\n layout: DEFAULT_DOCS_HIERARCHY.layout,\n roots: { ...DEFAULT_DOCS_HIERARCHY.roots },\n routing: {\n rootIndex: DEFAULT_DOCS_HIERARCHY.routing.root_index,\n areaFilesRoot: DEFAULT_DOCS_HIERARCHY.routing.area_files_root,\n defaultArea: DEFAULT_DOCS_HIERARCHY.routing.default_area,\n maxDelegationDepth: DEFAULT_DOCS_HIERARCHY.routing.max_delegation_depth,\n },\n },\n authority: [...DEFAULT_AUTHORITY],\n instructionTargets: [...DEFAULT_INSTRUCTION_TARGETS],\n frontmatter: {\n required: [],\n recommended: [\"status\", \"doc_type\", \"last_reviewed\", \"source_of_truth\"],\n },\n ignore: [\"node_modules/**\", \"vendor/**\", \"dist/**\", \"build/**\"],\n});\n","import { parse } from \"yaml\";\n\nimport type { Diagnostic } from \"../output/diagnostic.js\";\n\nexport const TRUTH_DOCUMENT_KINDS = [\n \"behavior\",\n \"contract\",\n \"architecture\",\n \"workflow\",\n \"operations\",\n \"test-behavior\",\n] as const;\n\nexport type TruthDocumentKind = (typeof TRUTH_DOCUMENT_KINDS)[number];\n\nexport type TruthDocumentEntry = {\n path: string;\n kind: TruthDocumentKind;\n kindSource: \"explicit\" | \"inferred\" | \"defaulted\";\n};\n\nexport type TruthArea = {\n id: string;\n name: string;\n key: string;\n truthDocuments: string[];\n truthDocumentEntries: TruthDocumentEntry[];\n codeSurface: string[];\n updateTruthWhen: string[];\n};\n\nexport type TruthAreaReference = {\n id: string;\n name: string;\n key: string;\n truthDocuments: string[];\n truthDocumentEntries: TruthDocumentEntry[];\n};\n\nexport type TruthAreaFileReference = {\n id: string;\n name: string;\n key: string;\n areaFiles: string[];\n codeSurface: string[];\n updateTruthWhen: string[];\n};\n\ntype ParseAreasMarkdownResult = {\n areas: TruthArea[];\n truthDocumentReferences: TruthAreaReference[];\n areaFileReferences: TruthAreaFileReference[];\n diagnostics: Diagnostic[];\n};\n\nexport type ParseAreasMarkdownOptions = {\n truthDocsRoot?: string;\n};\n\nconst slugify = (value: string): string => {\n return value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n};\n\nconst createAreaDiagnostic = (\n message: string,\n area?: string,\n severity: Diagnostic[\"severity\"] = \"error\",\n): Diagnostic => {\n return {\n category: \"area-index\",\n severity,\n message,\n area,\n };\n};\n\nconst parseListSection = (sectionLines: string[]): string[] => {\n return sectionLines\n .map((line) => line.trim())\n .filter((line) => line.startsWith(\"- \"))\n .map((line) => line.slice(2).trim().replaceAll(\"\\\\*\", \"*\"))\n .filter((line) => line.length > 0);\n};\n\nconst isTruthDocumentKind = (value: unknown): value is TruthDocumentKind => {\n return (\n typeof value === \"string\" &&\n TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind)\n );\n};\n\nexport const inferTruthDocumentKindFromPath = (\n documentPath: string,\n options: ParseAreasMarkdownOptions = {},\n): TruthDocumentKind | null => {\n const normalizedPath = documentPath.replaceAll(\"\\\\\", \"/\");\n const truthDocsRoot = options.truthDocsRoot\n ?.replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n\n if (\n (truthDocsRoot && normalizedPath.startsWith(`${truthDocsRoot}/`)) ||\n normalizedPath.startsWith(\"docs/truth/\")\n ) {\n return \"behavior\";\n }\n\n if (\n normalizedPath.startsWith(\"docs/contracts/\") ||\n normalizedPath.startsWith(\"docs/contract/\") ||\n normalizedPath.startsWith(\"docs/api/\")\n ) {\n return \"contract\";\n }\n\n if (normalizedPath.startsWith(\"docs/architecture/\")) {\n return \"architecture\";\n }\n\n if (\n normalizedPath.startsWith(\"docs/workflows/\") ||\n normalizedPath.startsWith(\"docs/workflow/\")\n ) {\n return \"workflow\";\n }\n\n if (\n normalizedPath.startsWith(\"docs/operations/\") ||\n normalizedPath.startsWith(\"docs/platform/\")\n ) {\n return \"operations\";\n }\n\n if (\n normalizedPath.startsWith(\"docs/testing/\") ||\n normalizedPath.startsWith(\"docs/tests/\")\n ) {\n return \"test-behavior\";\n }\n\n return null;\n};\n\ntype TruthDocumentsSectionResult = {\n truthDocuments: string[];\n truthDocumentEntries: TruthDocumentEntry[];\n diagnostics: Diagnostic[];\n};\n\ntype TruthDocumentsYamlFenceRange = {\n openingFenceIndex: number;\n closingFenceIndex: number | null;\n};\n\nconst findTruthDocumentsYamlFenceRange = (\n sectionLines: string[],\n): TruthDocumentsYamlFenceRange | null => {\n const trimmedLines = sectionLines.map((line) => line.trim());\n const openingFenceIndex = trimmedLines.findIndex((line) =>\n /^```(?:yaml|yml)?$/u.test(line),\n );\n\n if (openingFenceIndex === -1) {\n return null;\n }\n\n const closingFenceIndex = trimmedLines.findIndex(\n (line, index) => index > openingFenceIndex && line === \"```\",\n );\n\n return {\n openingFenceIndex,\n closingFenceIndex: closingFenceIndex === -1 ? null : closingFenceIndex,\n };\n};\n\nconst parseTruthDocumentsFromList = (\n sectionLines: string[],\n areaName: string,\n options: ParseAreasMarkdownOptions,\n): TruthDocumentsSectionResult => {\n const diagnostics: Diagnostic[] = [];\n const truthDocuments = parseListSection(sectionLines);\n const truthDocumentEntries = truthDocuments.map((documentPath) => {\n const inferredKind = inferTruthDocumentKindFromPath(documentPath, options);\n\n if (!inferredKind) {\n diagnostics.push(\n createAreaDiagnostic(\n `Truth document ${documentPath} does not match a known kind path convention; defaulting to behavior.`,\n areaName,\n \"review\",\n ),\n );\n }\n\n return {\n path: documentPath,\n kind: inferredKind ?? \"behavior\",\n kindSource: inferredKind ? (\"inferred\" as const) : (\"defaulted\" as const),\n };\n });\n\n return {\n truthDocuments,\n truthDocumentEntries,\n diagnostics,\n };\n};\n\nconst parseTruthDocumentsFromYaml = (\n sectionLines: string[],\n areaName: string,\n): TruthDocumentsSectionResult => {\n const yamlFenceRange = findTruthDocumentsYamlFenceRange(sectionLines);\n\n if (!yamlFenceRange) {\n return {\n truthDocuments: [],\n truthDocumentEntries: [],\n diagnostics: [],\n };\n }\n\n if (yamlFenceRange.closingFenceIndex === null) {\n return {\n truthDocuments: [],\n truthDocumentEntries: [],\n diagnostics: [\n createAreaDiagnostic(\n `Area ${areaName} has an unterminated fenced YAML Truth documents block.`,\n areaName,\n ),\n ],\n };\n }\n\n let parsedBlock: unknown;\n\n try {\n parsedBlock = parse(\n sectionLines\n .slice(\n yamlFenceRange.openingFenceIndex + 1,\n yamlFenceRange.closingFenceIndex,\n )\n .join(\"\\n\"),\n );\n } catch (error: unknown) {\n return {\n truthDocuments: [],\n truthDocumentEntries: [],\n diagnostics: [\n createAreaDiagnostic(\n `Area ${areaName} has invalid YAML truth document metadata: ${error instanceof Error ? error.message : String(error)}.`,\n areaName,\n ),\n ],\n };\n }\n\n const rawEntries =\n parsedBlock &&\n typeof parsedBlock === \"object\" &&\n \"truth_documents\" in parsedBlock\n ? (parsedBlock as { truth_documents?: unknown }).truth_documents\n : null;\n\n if (!Array.isArray(rawEntries)) {\n return {\n truthDocuments: [],\n truthDocumentEntries: [],\n diagnostics: [\n createAreaDiagnostic(\n `Area ${areaName} must define a truth_documents array inside the fenced YAML block.`,\n areaName,\n ),\n ],\n };\n }\n\n const diagnostics: Diagnostic[] = [];\n const truthDocumentEntries: TruthDocumentEntry[] = [];\n\n for (const rawEntry of rawEntries) {\n const path =\n rawEntry && typeof rawEntry === \"object\" && \"path\" in rawEntry\n ? (rawEntry as { path?: unknown }).path\n : null;\n const kind =\n rawEntry && typeof rawEntry === \"object\" && \"kind\" in rawEntry\n ? (rawEntry as { kind?: unknown }).kind\n : null;\n\n if (\n typeof path !== \"string\" ||\n path.trim().length === 0 ||\n !isTruthDocumentKind(kind)\n ) {\n diagnostics.push(\n createAreaDiagnostic(\n `Area ${areaName} truth_documents entries must include non-empty path and valid kind fields.`,\n areaName,\n ),\n );\n continue;\n }\n\n truthDocumentEntries.push({\n path: path.trim(),\n kind,\n kindSource: \"explicit\",\n });\n }\n\n return {\n truthDocuments: truthDocumentEntries.map((entry) => entry.path),\n truthDocumentEntries,\n diagnostics,\n };\n};\n\nconst parseTruthDocumentsSection = (\n sectionLines: string[],\n areaName: string,\n options: ParseAreasMarkdownOptions,\n): TruthDocumentsSectionResult => {\n const yamlFenceRange = findTruthDocumentsYamlFenceRange(sectionLines);\n\n if (!yamlFenceRange) {\n return parseTruthDocumentsFromList(sectionLines, areaName, options);\n }\n\n const yamlResult = parseTruthDocumentsFromYaml(sectionLines, areaName);\n\n if (\n yamlResult.diagnostics.length > 0 ||\n yamlFenceRange.closingFenceIndex === null\n ) {\n return yamlResult;\n }\n\n return yamlResult;\n};\n\nexport const parseAreasMarkdown = (\n source: string,\n options: ParseAreasMarkdownOptions = {},\n): ParseAreasMarkdownResult => {\n const lines = source.split(\"\\n\");\n const diagnostics: Diagnostic[] = [];\n const areas: TruthArea[] = [];\n const truthDocumentReferences: TruthAreaReference[] = [];\n const areaFileReferences: TruthAreaFileReference[] = [];\n let areaIndex = 0;\n\n let currentAreaName: string | null = null;\n let currentSections = new Map<string, string[]>();\n let currentSectionName: string | null = null;\n\n const flushArea = (): void => {\n if (!currentAreaName) {\n return;\n }\n\n const truthDocumentResult = parseTruthDocumentsSection(\n currentSections.get(\"Truth documents\") ?? [],\n currentAreaName,\n options,\n );\n const { truthDocuments, truthDocumentEntries } = truthDocumentResult;\n const areaFiles = parseListSection(currentSections.get(\"Area files\") ?? []);\n const codeSurface = parseListSection(\n currentSections.get(\"Code surface\") ?? [],\n );\n const updateTruthWhen = parseListSection(\n currentSections.get(\"Update truth when\") ?? [],\n );\n const areaKey = slugify(currentAreaName);\n const areaId = areaKey.length > 0 ? areaKey : `area-${areaIndex}`;\n const hasTruthDocuments = truthDocuments.length > 0;\n const hasAreaFiles = areaFiles.length > 0;\n\n areaIndex += 1;\n diagnostics.push(...truthDocumentResult.diagnostics);\n\n if (hasTruthDocuments) {\n truthDocumentReferences.push({\n id: areaId,\n name: currentAreaName,\n key: areaKey,\n truthDocuments,\n truthDocumentEntries,\n });\n }\n\n if (\n hasTruthDocuments === hasAreaFiles ||\n codeSurface.length === 0 ||\n updateTruthWhen.length === 0\n ) {\n diagnostics.push(\n createAreaDiagnostic(\n `Area ${currentAreaName} must define exactly one of Truth documents or Area files, plus Code surface and Update truth when sections.`,\n currentAreaName,\n ),\n );\n } else if (hasAreaFiles) {\n areaFileReferences.push({\n id: areaId,\n name: currentAreaName,\n key: areaKey,\n areaFiles,\n codeSurface,\n updateTruthWhen,\n });\n } else {\n areas.push({\n id: areaId,\n name: currentAreaName,\n key: areaKey,\n truthDocuments,\n truthDocumentEntries,\n codeSurface,\n updateTruthWhen,\n });\n }\n\n currentAreaName = null;\n currentSections = new Map();\n currentSectionName = null;\n };\n\n for (const line of lines) {\n const areaHeadingMatch = line.match(/^\\s{0,3}##\\s+(.*)$/u);\n\n if (areaHeadingMatch) {\n flushArea();\n currentAreaName = areaHeadingMatch[1]?.trim() ?? null;\n continue;\n }\n\n if (!currentAreaName) {\n continue;\n }\n\n if (\n /^(Truth documents|Area files|Code surface|Update truth when):$/u.test(\n line.trim(),\n )\n ) {\n currentSectionName = line.trim().slice(0, -1);\n currentSections.set(currentSectionName, []);\n continue;\n }\n\n if (currentSectionName) {\n currentSections.get(currentSectionName)?.push(line);\n }\n }\n\n flushArea();\n\n return {\n areas,\n truthDocumentReferences,\n areaFileReferences,\n diagnostics,\n };\n};\n","import { DEFAULT_DOCS_HIERARCHY } from \"../config/defaults.js\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\n\nexport const DEFAULT_TRUTH_DOCS_ROOT = DEFAULT_DOCS_HIERARCHY.roots.truth;\n\nexport const resolveTruthDocsRoot = (config: Pick<TruthmarkConfig, \"docs\">): string => {\n return config.docs.roots.truth ?? DEFAULT_TRUTH_DOCS_ROOT;\n};\n","import fs from \"node:fs/promises\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { CommandResult, DiagnosticCategory } from \"../output/diagnostic.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport { ensureRepoFile, resolveRepoPath, type FileWriteResult, writeRepoFile } from \"../fs/paths.js\";\nimport { detectHierarchyMigrationDiagnostics, scaffoldHierarchy } from \"./hierarchy.js\";\nimport { renderAgentsBlock, TRUTHMARK_BLOCK_END, TRUTHMARK_BLOCK_START } from \"../templates/agents-block.js\";\nimport { renderDefaultStandards } from \"../templates/default-standards.js\";\nimport { renderGeneratedSurfaces, type GeneratedSurface } from \"../templates/generated-surfaces.js\";\n\nconst escapeRegExp = (value: string): string => {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n};\n\nconst MANAGED_WORKFLOW_HEADING = \"## Truthmark Workflow\";\nconst LEGACY_MANAGED_LINES = [\n \"### Truth Sync\",\n \"- may read changed functional code files\",\n \"- may write truth docs only\",\n \"- must not rewrite functional code\",\n];\nconst CANONICAL_MANAGED_LINES = new Set(\n [\n ...renderAgentsBlock()\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(\n (line) =>\n line.length > 0 &&\n line !== TRUTHMARK_BLOCK_START &&\n line !== TRUTHMARK_BLOCK_END,\n ),\n ...LEGACY_MANAGED_LINES,\n ],\n);\n\nconst countCanonicalManagedLineMatches = (lines: string[]): number => {\n return lines.reduce((matchCount, line) => {\n return CANONICAL_MANAGED_LINES.has(line.trim()) ? matchCount + 1 : matchCount;\n }, 0);\n};\n\nconst isManagedChunk = (lines: string[], minimumMatches: number): boolean => {\n return countCanonicalManagedLineMatches(lines) >= minimumMatches;\n};\n\nconst removeTrailingManagedChunk = (preservedLines: string[]): void => {\n let startIndex = -1;\n\n for (let index = preservedLines.length - 1; index >= 0; index -= 1) {\n if (preservedLines[index].trim() === MANAGED_WORKFLOW_HEADING) {\n startIndex = index;\n break;\n }\n }\n\n if (startIndex === -1) {\n return;\n }\n\n const candidateChunk = preservedLines.slice(startIndex);\n const looksManaged = isManagedChunk(candidateChunk, 4);\n\n if (looksManaged) {\n preservedLines.splice(startIndex);\n }\n};\n\nconst normalizeLegacyInstructionPreamble = (content: string): string => {\n return content\n .replaceAll(\n \"Use that file as the primary repository instruction source for Codex.\",\n \"Use that file as the primary repository instruction source for this agent.\",\n )\n .replaceAll(\"Codex-specific:\", \"Agent-specific:\")\n .replaceAll(\n \"- Read `docs/README.md` for the canonical docs map.\",\n \"- Read `docs/README.md` only when choosing or updating canonical docs.\",\n )\n .replaceAll(\n \"- Use `docs/ai/agent-onboarding.md` for quick task routing.\",\n \"- Use `docs/ai/agent-onboarding.md` only when task routing is unclear or cross-area.\",\n );\n};\n\nconst upsertManagedBlock = (existingContent: string | null, block: string): string => {\n if (!existingContent || existingContent.trim().length === 0) {\n return block;\n }\n\n const normalizedExistingContent = normalizeLegacyInstructionPreamble(existingContent);\n const startMarkerPattern = new RegExp(escapeRegExp(TRUTHMARK_BLOCK_START), \"g\");\n const endMarkerPattern = new RegExp(escapeRegExp(TRUTHMARK_BLOCK_END), \"g\");\n const managedBlockPattern = new RegExp(\n `${escapeRegExp(TRUTHMARK_BLOCK_START)}[\\\\s\\\\S]*?${escapeRegExp(TRUTHMARK_BLOCK_END)}`,\n \"g\",\n );\n const completeBlocks = normalizedExistingContent.match(managedBlockPattern) ?? [];\n const startCount = normalizedExistingContent.match(startMarkerPattern)?.length ?? 0;\n const endCount = normalizedExistingContent.match(endMarkerPattern)?.length ?? 0;\n\n if (startCount === 1 && endCount === 1 && completeBlocks.length === 1) {\n return normalizedExistingContent.replace(managedBlockPattern, block);\n }\n\n const preservedLines: string[] = [];\n let insideManagedBlock = false;\n let managedLines: string[] = [];\n\n for (const line of normalizedExistingContent.split(\"\\n\")) {\n const trimmedLine = line.trim();\n\n if (trimmedLine === TRUTHMARK_BLOCK_START) {\n if (insideManagedBlock && !isManagedChunk(managedLines, 2)) {\n preservedLines.push(...managedLines);\n }\n\n insideManagedBlock = true;\n managedLines = [];\n continue;\n }\n\n if (trimmedLine === TRUTHMARK_BLOCK_END) {\n if (insideManagedBlock) {\n insideManagedBlock = false;\n managedLines = [];\n continue;\n }\n\n if (!insideManagedBlock) {\n removeTrailingManagedChunk(preservedLines);\n }\n\n continue;\n }\n\n if (insideManagedBlock) {\n managedLines.push(line);\n continue;\n }\n\n preservedLines.push(line);\n }\n\n if (insideManagedBlock && !isManagedChunk(managedLines, 2)) {\n preservedLines.push(...managedLines);\n }\n\n const preservedContent = preservedLines.join(\"\\n\").replace(/\\n{3,}/g, \"\\n\\n\").trim();\n\n if (preservedContent.length === 0) {\n return block;\n }\n\n return `${preservedContent}\\n\\n${block}`;\n};\n\nconst writeManagedAgentsFile = async (\n rootDir: string,\n path = \"AGENTS.md\",\n block: string,\n): Promise<FileWriteResult> => {\n let existingContent: string | null = null;\n\n try {\n existingContent = await fs.readFile(resolveRepoPath(rootDir, path), \"utf8\");\n } catch (error: unknown) {\n if (!(error instanceof Error) || !(\"code\" in error) || error.code !== \"ENOENT\") {\n throw error;\n }\n }\n\n return writeRepoFile(rootDir, path, upsertManagedBlock(existingContent, block));\n};\n\nconst diagnosticCategoryForPath = (\n filePath: string,\n config: TruthmarkConfig,\n): DiagnosticCategory => {\n if (filePath === \"AGENTS.md\") {\n return \"truth-sync\";\n }\n\n if (\n filePath === \"CLAUDE.md\" ||\n filePath === \"GEMINI.md\" ||\n filePath === \".github/copilot-instructions.md\" ||\n filePath.startsWith(\".github/prompts/truthmark-\") ||\n filePath.startsWith(\".github/agents/truth-\") ||\n filePath.startsWith(\".claude/agents/truth-\") ||\n filePath.startsWith(\".claude/skills/truthmark-\") ||\n filePath.startsWith(\".opencode/skills/truthmark-\") ||\n filePath.startsWith(\".opencode/agents/\") ||\n filePath.startsWith(\".codex/agents/\")\n ) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-structure/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-document/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-sync/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-preview/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-realize/\")) {\n return \"realization\";\n }\n\n if (filePath.startsWith(\".gemini/commands/truthmark/realize\")) {\n return \"realization\";\n }\n\n if (filePath.startsWith(\".gemini/commands/truthmark/\")) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".codex/skills/truthmark-check/\")) {\n return \"truth-sync\";\n }\n\n if (filePath === config.docs.routing.rootIndex) {\n return \"authority\";\n }\n\n return \"config\";\n};\n\nconst writePlatformFile = async (\n rootDir: string,\n file: GeneratedSurface,\n): Promise<FileWriteResult> => {\n if (file.managedBlock) {\n return writeManagedAgentsFile(rootDir, file.path, file.content);\n }\n\n return writeRepoFile(rootDir, file.path, file.content);\n};\n\nconst messageForWriteResult = (result: FileWriteResult): string => {\n switch (result.status) {\n case \"created\":\n return `Created ${result.path}.`;\n case \"updated\":\n return `Updated ${result.path}.`;\n case \"unchanged\":\n return `Unchanged ${result.path}.`;\n }\n};\n\nconst writeDiagnostics = (\n results: FileWriteResult[],\n config: TruthmarkConfig,\n): CommandResult[\"diagnostics\"] => {\n return results.map((result) => ({\n category: diagnosticCategoryForPath(result.path, config),\n severity: \"action\",\n message: messageForWriteResult(result),\n file: result.path,\n }));\n};\n\nexport const runInit = async (cwd: string): Promise<CommandResult> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const loadedConfig = await loadConfig(rootDir);\n\n if (!loadedConfig.config) {\n return {\n command: \"init\",\n summary:\n \"Truthmark init requires .truthmark/config.yml. Run truthmark config first, review the hierarchy, then run truthmark init.\",\n diagnostics: loadedConfig.diagnostics,\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n },\n };\n }\n\n const defaultStandards = renderDefaultStandards([]);\n\n const results: FileWriteResult[] = [];\n\n for (const template of defaultStandards) {\n results.push(await ensureRepoFile(rootDir, template.path, template.content));\n }\n\n const config = loadedConfig.config;\n results.push(...(await scaffoldHierarchy(rootDir, config)));\n const migrationDiagnostics = await detectHierarchyMigrationDiagnostics(rootDir, config);\n const block = renderAgentsBlock(config);\n const platformFiles = renderGeneratedSurfaces(config, block);\n\n for (const file of platformFiles) {\n results.push(await writePlatformFile(rootDir, file));\n }\n\n const changedResults = results.filter((result) => result.status !== \"unchanged\");\n\n return {\n command: \"init\",\n summary:\n changedResults.length > 0\n ? \"Initialized or updated the Truthmark repository scaffold.\"\n : \"Truthmark repository scaffold is already up to date.\",\n diagnostics: [...writeDiagnostics(results, config), ...migrationDiagnostics],\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n },\n };\n};\n","import fs from \"node:fs/promises\";\n\nimport { Ajv, type ErrorObject } from \"ajv\";\nimport { parse } from \"yaml\";\n\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { resolveRepoPath } from \"../fs/paths.js\";\nimport {\n DEFAULT_DOCS_HIERARCHY,\n DEFAULT_INSTRUCTION_TARGETS,\n} from \"./defaults.js\";\nimport {\n DEFAULT_PLATFORMS,\n type RawTruthmarkConfig,\n type TruthmarkConfig,\n truthmarkConfigSchema,\n} from \"./schema.js\";\n\nconst ajv = new Ajv({ allErrors: true });\nconst validateTruthmarkConfig = ajv.compile(truthmarkConfigSchema);\n\nexport type LoadConfigResult = {\n status: \"loaded\" | \"missing\" | \"invalid\";\n config: TruthmarkConfig | null;\n diagnostics: Diagnostic[];\n configPath: string;\n};\n\nconst toConfigDiagnostic = (message: string, file: string): Diagnostic => {\n return {\n category: \"config\",\n severity: \"error\",\n message,\n file,\n };\n};\n\nconst normalizeConfig = (rawConfig: RawTruthmarkConfig): TruthmarkConfig => {\n const rawDocs = rawConfig.docs ?? {\n layout: DEFAULT_DOCS_HIERARCHY.layout,\n roots: { ...DEFAULT_DOCS_HIERARCHY.roots },\n routing: { ...DEFAULT_DOCS_HIERARCHY.routing },\n };\n const roots: Record<string, string> = { ...DEFAULT_DOCS_HIERARCHY.roots, ...rawDocs.roots };\n\n return {\n version: rawConfig.version,\n platforms: rawConfig.platforms ?? [...DEFAULT_PLATFORMS],\n docs: {\n layout: rawDocs.layout,\n roots,\n routing: {\n rootIndex: rawDocs.routing.root_index,\n areaFilesRoot: rawDocs.routing.area_files_root,\n defaultArea: rawDocs.routing.default_area,\n maxDelegationDepth: rawDocs.routing.max_delegation_depth,\n },\n },\n authority: rawConfig.authority,\n instructionTargets: rawConfig.instruction_targets ?? [...DEFAULT_INSTRUCTION_TARGETS],\n frontmatter: {\n required: rawConfig.frontmatter?.required ?? [],\n recommended: rawConfig.frontmatter?.recommended ?? [],\n },\n ignore: rawConfig.ignore ?? [],\n };\n};\n\nexport const loadConfig = async (rootDir: string): Promise<LoadConfigResult> => {\n const configPath = \".truthmark/config.yml\";\n const absolutePath = resolveRepoPath(rootDir, configPath);\n\n let source: string;\n\n try {\n source = await fs.readFile(absolutePath, \"utf8\");\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return {\n status: \"missing\",\n config: null,\n diagnostics: [toConfigDiagnostic(\"Missing .truthmark/config.yml.\", configPath)],\n configPath,\n };\n }\n\n throw error;\n }\n\n let parsedConfig: unknown;\n\n try {\n parsedConfig = parse(source);\n } catch (error: unknown) {\n return {\n status: \"invalid\",\n config: null,\n diagnostics: [\n toConfigDiagnostic(\n `Invalid YAML: ${error instanceof Error ? error.message : String(error)}`,\n configPath,\n ),\n ],\n configPath,\n };\n }\n\n if (!validateTruthmarkConfig(parsedConfig)) {\n return {\n status: \"invalid\",\n config: null,\n diagnostics: (validateTruthmarkConfig.errors ?? []).map((error: ErrorObject) => {\n const propertyPath = error.instancePath || \"/\";\n const additionalProperty =\n error.keyword === \"additionalProperties\" &&\n error.params &&\n \"additionalProperty\" in error.params\n ? String(error.params.additionalProperty)\n : null;\n const message = additionalProperty\n ? `${propertyPath} additional property ${additionalProperty} is not allowed`\n : `${propertyPath} ${error.message ?? \"is invalid\"}`.trim();\n\n return toConfigDiagnostic(message, configPath);\n }),\n configPath,\n };\n }\n\n return {\n status: \"loaded\",\n config: normalizeConfig(parsedConfig as RawTruthmarkConfig),\n diagnostics: [],\n configPath,\n };\n};\n","import fs from \"node:fs/promises\";\nimport fg from \"fast-glob\";\nimport { DEFAULT_DOCS_HIERARCHY } from \"../config/defaults.js\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { FileWriteResult } from \"../fs/paths.js\";\nimport { ensureRepoFile, resolveRepoPath } from \"../fs/paths.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { parseAreasMarkdown } from \"../routing/areas.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\nimport {\n ARCHITECTURE_DOC_TEMPLATE_PATH,\n BEHAVIOR_DOC_TEMPLATE_PATH,\n CONTRACT_DOC_TEMPLATE_PATH,\n OPERATIONS_DOC_TEMPLATE_PATH,\n TEST_BEHAVIOR_DOC_TEMPLATE_PATH,\n WORKFLOW_DOC_TEMPLATE_PATH,\n renderChildAreaTemplate,\n renderArchitectureDocTemplateFile,\n renderBehaviorDocTemplateFile,\n renderContractDocTemplateFile,\n renderTruthDomainReadmeTemplate,\n renderTruthRootReadmeTemplate,\n renderHierarchicalAreasIndexTemplate,\n renderOperationsDocTemplateFile,\n renderBehaviorLeafDocTemplate,\n renderTestBehaviorDocTemplateFile,\n renderWorkflowDocTemplateFile,\n} from \"../templates/init-files.js\";\n\nconst KNOWN_DEFAULT_ROOTS = [\n DEFAULT_DOCS_HIERARCHY.roots.truth,\n \"docs/api\",\n DEFAULT_DOCS_HIERARCHY.roots.architecture,\n DEFAULT_DOCS_HIERARCHY.roots.standards,\n \"docs/guides\",\n] as const;\n\nconst hasMarkdownFiles = async (rootDir: string, root: string): Promise<boolean> => {\n const matches = await fg([`${root}/**/*.md`], {\n cwd: rootDir,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n return matches.length > 0;\n};\n\nconst truthRoot = resolveTruthDocsRoot;\n\nconst rootIndexReferencesChildRoute = async (\n rootDir: string,\n rootIndexPath: string,\n childRoutePath: string,\n): Promise<boolean> => {\n const rootIndexSource = await fs.readFile(resolveRepoPath(rootDir, rootIndexPath), \"utf8\");\n const parsedRootIndex = parseAreasMarkdown(rootIndexSource);\n\n return parsedRootIndex.areaFileReferences.some((areaReference) =>\n areaReference.areaFiles.includes(childRoutePath),\n );\n};\n\nconst readBehaviorDocTemplate = async (rootDir: string): Promise<string> => {\n try {\n return await fs.readFile(resolveRepoPath(rootDir, BEHAVIOR_DOC_TEMPLATE_PATH), \"utf8\");\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return renderBehaviorDocTemplateFile();\n }\n throw error;\n }\n};\n\nexport const scaffoldHierarchy = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<FileWriteResult[]> => {\n const results: FileWriteResult[] = [];\n const truthDocsRoot = truthRoot(config);\n const truthDomainRoot = `${truthDocsRoot}/${config.docs.routing.defaultArea}`;\n const childRoutePath = `${config.docs.routing.areaFilesRoot}/${config.docs.routing.defaultArea}.md`;\n\n results.push(\n await ensureRepoFile(\n rootDir,\n config.docs.routing.rootIndex,\n renderHierarchicalAreasIndexTemplate(config),\n ),\n );\n if (\n await rootIndexReferencesChildRoute(rootDir, config.docs.routing.rootIndex, childRoutePath)\n ) {\n results.push(await ensureRepoFile(rootDir, childRoutePath, renderChildAreaTemplate(config)));\n }\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDocsRoot}/README.md`,\n renderTruthRootReadmeTemplate(config),\n ),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDomainRoot}/README.md`,\n renderTruthDomainReadmeTemplate(config),\n ),\n );\n results.push(\n await ensureRepoFile(rootDir, BEHAVIOR_DOC_TEMPLATE_PATH, renderBehaviorDocTemplateFile()),\n );\n results.push(\n await ensureRepoFile(rootDir, CONTRACT_DOC_TEMPLATE_PATH, renderContractDocTemplateFile()),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n ARCHITECTURE_DOC_TEMPLATE_PATH,\n renderArchitectureDocTemplateFile(),\n ),\n );\n results.push(\n await ensureRepoFile(rootDir, WORKFLOW_DOC_TEMPLATE_PATH, renderWorkflowDocTemplateFile()),\n );\n results.push(\n await ensureRepoFile(rootDir, OPERATIONS_DOC_TEMPLATE_PATH, renderOperationsDocTemplateFile()),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n TEST_BEHAVIOR_DOC_TEMPLATE_PATH,\n renderTestBehaviorDocTemplateFile(),\n ),\n );\n const behaviorDocTemplate = await readBehaviorDocTemplate(rootDir);\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDomainRoot}/overview.md`,\n renderBehaviorLeafDocTemplate(config, behaviorDocTemplate),\n ),\n );\n return results;\n};\n\nexport const detectHierarchyMigrationDiagnostics = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<Diagnostic[]> => {\n const configuredRoots = new Set(Object.values(config.docs.roots));\n const diagnostics: Diagnostic[] = [];\n for (const defaultRoot of KNOWN_DEFAULT_ROOTS) {\n if (configuredRoots.has(defaultRoot)) {\n continue;\n }\n if (await hasMarkdownFiles(rootDir, defaultRoot)) {\n diagnostics.push({\n category: \"config\",\n severity: \"review\",\n message: `Configured hierarchy no longer includes ${defaultRoot}, but markdown still exists there. Perform manual migration before relying on the new hierarchy.`,\n file: \".truthmark/config.yml\",\n });\n }\n }\n return diagnostics;\n};\n","export type ClaimEvidenceResult = \"supported\" | \"narrowed\" | \"removed\" | \"blocked\";\n\nexport type ClaimEvidenceItem = {\n claim: string;\n evidence: string[];\n result: ClaimEvidenceResult;\n};\n\nexport type AuditEvidenceConfidence = \"high\" | \"medium\" | \"low\";\n\nexport type AuditEvidenceItem = {\n finding: string;\n evidence: string[];\n suggestedFix: string;\n confidence: AuditEvidenceConfidence;\n};\n\nexport const renderClaimEvidenceCheckedSection = (\n items: ClaimEvidenceItem[],\n): string => {\n return [\n \"Evidence checked:\",\n ...items.map((item) => {\n return [\n `- Claim: ${item.claim}`,\n ` Evidence: ${item.evidence.join(\" / \")}`,\n ` Result: ${item.result}`,\n ].join(\"\\n\");\n }),\n ].join(\"\\n\");\n};\n\nexport const renderAuditEvidenceCheckedSection = (\n items: AuditEvidenceItem[],\n): string => {\n return [\n \"Evidence checked:\",\n ...items.map((item) => {\n return [\n `- Finding: ${item.finding}`,\n ` Evidence: ${item.evidence.join(\" / \")}`,\n ` Suggested fix: ${item.suggestedFix}`,\n ` Confidence: ${item.confidence}`,\n ].join(\"\\n\");\n }),\n ].join(\"\\n\");\n};\n","import { createDefaultConfig } from \"../config/defaults.js\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\n\nexport { resolveTruthDocsRoot } from \"../truth/docs.js\";\nexport type {\n AuditEvidenceConfidence,\n AuditEvidenceItem,\n ClaimEvidenceItem,\n ClaimEvidenceResult,\n} from \"../truth/evidence.js\";\nexport {\n renderAuditEvidenceCheckedSection,\n renderClaimEvidenceCheckedSection,\n} from \"../truth/evidence.js\";\n\nexport const DECISION_TRUTH_INSTRUCTIONS = [\n \"Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed.\",\n \"Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail.\",\n \"Update Product Decisions and Rationale when a decision changes behavior.\",\n].join(\"\\n\");\n\nexport const EVIDENCE_AUTHORITY_INSTRUCTIONS = [\n \"Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority.\",\n \"Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries.\",\n].join(\"\\n\");\n\nexport const REPOSITORY_INTELLIGENCE_INSTRUCTIONS = [\n \"Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available.\",\n \"They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries.\",\n \"If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated.\",\n].join(\"\\n\");\n\nexport const FEATURE_DOC_TEMPLATE_INSTRUCTIONS = [\n \"When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/<kind>-doc.md` template.\",\n \"Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior.\",\n \"Align existing docs to that template while preserving accurate authored content.\",\n \"If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section.\",\n \"Teams may edit the template files under docs/templates/ to define their local truth-doc standards.\",\n].join(\"\\n\");\n\nexport const renderTruthDocOwnershipGateSection = (\n subject: string,\n outcome: string,\n): string => {\n return [\n \"Truth-doc ownership gate:\",\n `- before editing or relying on ${subject}, verify each target/source truth doc is a bounded owner for the behavior`,\n \"- if a target/source doc mixes independent owners, spans unrelated behaviors, acts as an index, or needs cross-owner edits, do not patch or in-place repair it\",\n `- ${outcome}`,\n \"- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable\",\n ].join(\"\\n\");\n};\n\nexport const TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS = [\n \"Product Decisions/Rationale preservation gate:\",\n \"- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc\",\n \"- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index\",\n \"- remove or narrow a decision or rationale only when checkout evidence shows it is stale or unsupported, and report the exact claim, evidence, and result\",\n \"- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing\",\n \"- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked\",\n].join(\"\\n\");\n\nexport const renderTruthDocRestructureGateSection = (scope: string): string => {\n return [\n \"Truth-doc shape repair gate:\",\n `- ${scope}`,\n \"- repair shape in place only after the ownership gate confirms the doc is the right bounded owner\",\n \"- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work\",\n \"- repair shape when a narrow edit would make truth worse: missing template sections, stale evidence conflicts, cross-section updates within one owner, or wrong frontmatter/source/headings\",\n \"- preserve supported claims; remove, narrow, or block unsupported or stale claims\",\n \"- report docs restructured and why a narrow edit was not sufficient\",\n ].join(\"\\n\");\n};\n\nexport const ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS = [\n \"Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership.\",\n \"Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries.\",\n].join(\"\\n\");\n\nexport const renderRouteFirstEvidenceGateSection = (\n subject: string,\n noImpactedDocOutcome: string,\n): string => {\n return [\n \"Evidence Gate:\",\n `- route-first: map ${subject} to bounded route owners and primary canonical docs`,\n \"- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale\",\n \"- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions\",\n \"- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts\",\n \"- remove, narrow, or block unsupported claims\",\n `- ${noImpactedDocOutcome}`,\n ].join(\"\\n\");\n};\n\nexport const renderTopologyEvidenceGateSection = (): string => {\n return [\n \"Evidence Gate:\",\n \"- apply the Evidence Gate before finishing when Truth Structure writes routed docs, ownership claims, Product Decisions, or Rationale\",\n \"- support ownership/behavior claims with topology or primary checkout evidence from layout, implementation boundaries, docs, config, route files, tests, templates, schemas, or contracts\",\n \"- tests/examples/canonical docs corroborate; remove, narrow, or block unsupported claims\",\n ].join(\"\\n\");\n};\n\nexport const renderAuditEvidenceGateSection = (): string => {\n return [\n \"Evidence Gate:\",\n \"- support each finding and suggested fix with evidence from config, route files, canonical docs, implementation, templates, or tests\",\n \"- canonical docs are context, not sole proof when implementation conflicts\",\n \"- remove unsupported findings or mark open questions; validate changed claims if you edit docs\",\n ].join(\"\\n\");\n};\n\nexport const renderCodexSubagentModeSection = (\n agents: string[],\n parentRule: string,\n writeAgents: string[] = [],\n): string => {\n const writeAgentLines =\n writeAgents.length > 0\n ? [\n `- dispatch write-capable project agents only with explicit write leases: ${writeAgents.join(\", \")}`,\n \"- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields\",\n \"- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes\",\n \"- parent must inspect the actual checkout diff against each lease before accepting a worker report\",\n ]\n : [];\n const readOnlyScope = writeAgents.length > 0 ? \"for verification\" : \"only\";\n const readOnlyWorkerLabel = writeAgents.length > 0 ? \"read-only workers\" : \"workers\";\n\n return [\n \"Codex subagent mode:\",\n \"- use automatically when this workflow runs in Codex and the parent agent chooses bounded subagent fan-out\",\n `- dispatch read-only project agents ${readOnlyScope}: ${agents.join(\", \")}`,\n `- ${readOnlyWorkerLabel} inspect checkout evidence directly, return structured findings, and must not edit files`,\n `- parent supplies bounded evidence shards; ${readOnlyWorkerLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`,\n ...writeAgentLines,\n `- ${parentRule}`,\n ].join(\"\\n\");\n};\n\nexport const renderOpenCodeSubagentModeSection = (\n agents: string[],\n parentRule: string,\n writeAgents: string[] = [],\n): string => {\n const mentions = agents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeMentions = writeAgents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeAgentLines =\n writeMentions.length > 0\n ? [\n `- dispatch write-capable project subagents only with explicit write leases: ${writeMentions.join(\", \")}`,\n \"- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields\",\n \"- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes\",\n \"- parent must inspect the actual checkout diff against each lease before accepting a worker report\",\n ]\n : [];\n const readOnlyScope = writeAgents.length > 0 ? \"for verification\" : \"only\";\n const readOnlyWorkerLabel = writeAgents.length > 0 ? \"read-only workers\" : \"workers\";\n\n return [\n \"OpenCode subagent mode:\",\n \"- use automatically when this workflow runs in OpenCode and the parent agent chooses bounded subagent fan-out\",\n `- dispatch read-only project subagents ${readOnlyScope}: ${mentions.join(\", \")}`,\n `- ${readOnlyWorkerLabel} inspect checkout evidence directly, return structured findings, and must not edit files`,\n `- parent supplies bounded evidence shards; ${readOnlyWorkerLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`,\n ...writeAgentLines,\n `- ${parentRule}`,\n ].join(\"\\n\");\n};\n\nexport const renderClaudeSubagentModeSection = (\n agents: string[],\n parentRule: string,\n writeAgents: string[] = [],\n): string => {\n const mentions = agents.map((agent) => `${agent.replace(/_/gu, \"-\")} subagent`);\n const writeMentions = writeAgents.map(\n (agent) => `${agent.replace(/_/gu, \"-\")} subagent`,\n );\n const writeAgentLines =\n writeMentions.length > 0\n ? [\n `- dispatch write-capable project subagents only with explicit write leases: ${writeMentions.join(\", \")}`,\n \"- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields\",\n \"- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes\",\n \"- parent must inspect the actual checkout diff against each lease before accepting a worker report\",\n ]\n : [];\n const readOnlyScope = writeAgents.length > 0 ? \"for verification\" : \"only\";\n const readOnlySubagentLabel =\n writeAgents.length > 0 ? \"read-only subagents\" : \"subagents\";\n\n return [\n \"Claude Code subagent mode:\",\n \"- use automatically when this workflow runs in Claude Code and the parent agent chooses bounded subagent fan-out\",\n `- dispatch read-only project subagents ${readOnlyScope}: ${mentions.join(\", \")}`,\n `- ${readOnlySubagentLabel} inspect checkout evidence directly, return structured findings, and must not edit files`,\n `- parent supplies bounded evidence shards; ${readOnlySubagentLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`,\n ...writeAgentLines,\n `- ${parentRule}`,\n ].join(\"\\n\");\n};\n\nexport const renderCopilotCustomAgentModeSection = (\n agents: string[],\n parentRule: string,\n writeAgents: string[] = [],\n): string => {\n const mentions = agents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeMentions = writeAgents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeAgentLines =\n writeMentions.length > 0\n ? [\n `- dispatch write-capable project custom agents only with explicit write leases: ${writeMentions.join(\", \")}`,\n \"- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields\",\n \"- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes\",\n \"- parent must inspect the actual checkout diff against each lease before accepting a worker report\",\n ]\n : [];\n const readOnlyScope = writeAgents.length > 0 ? \"for verification\" : \"only\";\n const readOnlyCustomAgentLabel =\n writeAgents.length > 0 ? \"read-only custom agents\" : \"custom agents\";\n\n return [\n \"Copilot custom-agent mode:\",\n \"- use automatically when this workflow runs in Copilot and the parent agent chooses bounded custom-agent fan-out\",\n `- dispatch read-only project custom agents ${readOnlyScope}: ${mentions.join(\", \")}`,\n `- ${readOnlyCustomAgentLabel} inspect checkout evidence directly, return structured findings, and must not edit files`,\n `- parent supplies bounded evidence shards; ${readOnlyCustomAgentLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`,\n ...writeAgentLines,\n `- ${parentRule}`,\n ].join(\"\\n\");\n};\n\nexport const renderGeminiSubagentModeSection = (\n agents: string[],\n parentRule: string,\n writeAgents: string[] = [],\n): string => {\n const mentions = agents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeMentions = writeAgents.map((agent) => `@${agent.replace(/_/gu, \"-\")}`);\n const writeAgentLines =\n writeMentions.length > 0\n ? [\n `- dispatch write-capable project subagents only with explicit write leases: ${writeMentions.join(\", \")}`,\n \"- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields\",\n \"- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes\",\n \"- parent must inspect the actual checkout diff against each lease before accepting a worker report\",\n ]\n : [];\n const readOnlyScope = writeAgents.length > 0 ? \"for verification\" : \"only\";\n const readOnlySubagentLabel =\n writeAgents.length > 0 ? \"read-only subagents\" : \"subagents\";\n\n return [\n \"Gemini CLI subagent mode:\",\n \"- use automatically when this workflow runs in Gemini CLI and the parent agent chooses bounded project subagent fan-out\",\n `- dispatch read-only project subagents ${readOnlyScope}: ${mentions.join(\", \")}`,\n `- ${readOnlySubagentLabel} inspect checkout evidence directly, return structured findings, and must not edit files`,\n `- parent supplies bounded evidence shards; ${readOnlySubagentLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`,\n ...writeAgentLines,\n `- ${parentRule}`,\n ].join(\"\\n\");\n};\n\nexport const defaultAgentConfig = (): TruthmarkConfig => {\n return createDefaultConfig();\n};\n\nexport const renderHierarchySummary = (config: TruthmarkConfig): string => {\n const truthRoot = resolveTruthDocsRoot(config);\n\n return [\n \"Truthmark hierarchy:\",\n \"- Config: .truthmark/config.yml\",\n `- Root route index: ${config.docs.routing.rootIndex}`,\n `- Area route files: ${config.docs.routing.areaFilesRoot}/**/*.md`,\n `- Truth docs: ${truthRoot}/**/*.md`,\n ].join(\"\\n\");\n};\n","import fs from \"node:fs\";\n\ntype TruthmarkPackageJson = {\n version: string;\n};\n\nconst packageJson = JSON.parse(\n fs.readFileSync(new URL(\"../package.json\", import.meta.url), \"utf8\"),\n) as TruthmarkPackageJson;\n\nexport const TRUTHMARK_VERSION = packageJson.version;\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport { defaultAgentConfig, resolveTruthDocsRoot } from \"../agents/shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\n\nexport const TRUTHMARK_BLOCK_START = \"<!-- truthmark:start -->\";\nexport const TRUTHMARK_BLOCK_END = \"<!-- truthmark:end -->\";\n\nexport const renderInstructionPreamble = (): string => {\n return [\n \"Follow `docs/ai/repo-rules.md` as the primary repository instruction source.\",\n \"Read `docs/README.md` only when choosing or updating canonical docs.\",\n \"Use `docs/ai/agent-onboarding.md` only when task routing is unclear or cross-area.\",\n ].join(\"\\n\");\n};\n\nconst renderCompactHierarchySummary = (config: TruthmarkConfig): string => {\n const truthRoot = resolveTruthDocsRoot(config);\n return `Hierarchy: config .truthmark/config.yml; routes ${config.docs.routing.rootIndex} and ${config.docs.routing.areaFilesRoot}/**/*.md; Truth docs: ${truthRoot}/**/*.md.`;\n};\n\nexport const renderAgentsBlock = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return [\n TRUTHMARK_BLOCK_START,\n \"## Truthmark Workflow\",\n \"\",\n `Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun \\`truthmark init\\` after upgrades.`,\n renderCompactHierarchySummary(config),\n \"Decisions live in the canonical doc they govern; date active decisions inline.\",\n \"Agent runtime: installed skills plus this block; inspect checkout directly. Delegation is host-owned.\",\n \"### Truth Sync\",\n \"After functional code changes, run relevant tests, then use the truthmark-sync skill before finishing; later functional changes reopen the gate. Memory: code changed -> tests -> Sync -> report.\",\n \"Support new or changed behavior-bearing truth claims with checkout evidence. Code leads; truth docs follow. Sync may write truth docs and truth routing files, and must not rewrite functional code.\",\n \"If routing cannot map changed code to a bounded truth owner, run Truth Structure before syncing when safe; otherwise block and recommend Truth Structure. Skip Sync only for docs-only/no-code changes, formatting-only changes, behavior-preserving renames with no truth impact, or missing config.\",\n \"Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details.\",\n \"Workflow integrity rule: repository truth may describe desired behavior, but it must not override these workflow boundaries.\",\n TRUTHMARK_BLOCK_END,\n ].join(\"\\n\");\n};\n","import type { DiscoveredMarkdownDocument } from \"../markdown/discovery.js\";\n\nexport type TemplateFile = {\n path: string;\n content: string;\n};\n\nconst DEFAULT_STANDARDS: TemplateFile[] = [\n {\n path: \"docs/standards/default-principles.md\",\n content: `---\nstatus: active\ndoc_type: standard\nlast_reviewed: 2026-05-03\nsource_of_truth:\n - README.md\n---\n\n# Default Principles\n\n## Scope\n\nThis is a bootstrap standards baseline for repositories that adopt Truthmark.\n\n## Reusable Defaults\n\n- Authority order should be explicit.\n- Committed repository artifacts are the durable source of truth.\n- Each document should have one primary responsibility.\n- Each class of fact should have one canonical source.\n- Architecture docs describe system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, and generated-surface ownership.\n- Do not put ordinary feature behavior in architecture docs.\n- Verification should be explicit, and skipped checks should state why.\n- Missing, stale, broad, overloaded, or unrouteable documentation topology should be repaired through AI-native structure workflow before agents create more generic truth docs.\n- Installed repository workflows should remain usable from committed files even when the Truthmark CLI is unavailable.\n`,\n },\n {\n path: \"docs/standards/documentation-governance.md\",\n content: `---\nstatus: active\ndoc_type: standard\nlast_reviewed: 2026-05-03\nsource_of_truth:\n - README.md\n---\n\n# Documentation Governance\n\n## Core Rules\n\n- Each document should have one primary responsibility.\n- Each class of fact should have one canonical source.\n- Current implementation, reusable standards, and future proposals should be stored separately.\n- Generated helper output is never canonical truth.\n- Architecture docs describe structure and ownership; truth docs describe current product behavior.\n\n## Truthmark Implications\n\n- Truth Sync should extend mapped docs first, create an area-local doc second, and create a new area only as a last resort.\n- Weak routing produces weak truth maintenance.\n- Missing, stale, broad, overloaded, or unrouteable routing should trigger Truth Structure before more generic truth docs are created.\n`,\n },\n];\n\nexport const renderDefaultStandards = (\n documents: DiscoveredMarkdownDocument[],\n): TemplateFile[] => {\n const existingPaths = new Set(documents.map((document) => document.path));\n\n return DEFAULT_STANDARDS.filter((template) => !existingPaths.has(template.path));\n};\n","import { stringify } from \"yaml\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderGeminiSubagentModeSection,\n renderHierarchySummary,\n renderOpenCodeSubagentModeSection,\n renderTruthDocOwnershipGateSection,\n resolveTruthDocsRoot,\n} from \"../agents/shared.js\";\nimport {\n TRUTH_CHECK_EXPLICIT_INVOCATIONS,\n renderTruthCheckSkillBody,\n} from \"../agents/truth-check.js\";\nimport {\n TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS,\n renderTruthDocumentSkillBody,\n} from \"../agents/truth-document.js\";\nimport {\n TRUTH_PREVIEW_EXPLICIT_INVOCATIONS,\n renderTruthPreviewSkillBody,\n} from \"../agents/truth-preview.js\";\nimport {\n TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS,\n renderTruthStructureSkillBody,\n} from \"../agents/truth-structure.js\";\nimport {\n TRUTH_SYNC_EXPLICIT_INVOCATIONS,\n renderTruthSyncSkillBody,\n} from \"../agents/truth-sync.js\";\nimport { TRUTHMARK_WRITE_WORKER_REPORT_FIELDS } from \"../agents/write-lease.js\";\nimport {\n getTruthmarkWorkflow,\n type TruthmarkWorkflowHelper,\n type TruthmarkWorkflowId,\n type TruthmarkReadOnlySubagentId,\n type TruthmarkWriteSubagentId,\n} from \"../agents/workflow-manifest.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\n\nexport const TRUTHMARK_STRUCTURE_SKILL_PATH =\n \".codex/skills/truthmark-structure/SKILL.md\";\n\nexport const TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-structure/agents/openai.yaml\";\n\nexport const TRUTHMARK_DOCUMENT_SKILL_PATH =\n \".codex/skills/truthmark-document/SKILL.md\";\n\nexport const TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-document/agents/openai.yaml\";\n\nexport const TRUTHMARK_SYNC_SKILL_PATH =\n \".codex/skills/truthmark-sync/SKILL.md\";\n\nexport const TRUTHMARK_SYNC_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-sync/agents/openai.yaml\";\n\nexport const TRUTHMARK_REALIZE_SKILL_PATH =\n \".codex/skills/truthmark-realize/SKILL.md\";\n\nexport const TRUTHMARK_REALIZE_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-realize/agents/openai.yaml\";\n\nexport const TRUTHMARK_CHECK_SKILL_PATH =\n \".codex/skills/truthmark-check/SKILL.md\";\n\nexport const TRUTHMARK_CHECK_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-check/agents/openai.yaml\";\n\nexport const TRUTHMARK_PREVIEW_SKILL_PATH =\n \".codex/skills/truthmark-preview/SKILL.md\";\n\nexport const TRUTHMARK_PREVIEW_SKILL_METADATA_PATH =\n \".codex/skills/truthmark-preview/agents/openai.yaml\";\n\nexport const TRUTHMARK_ROUTE_AUDITOR_AGENT_PATH =\n \".codex/agents/truth-route-auditor.toml\";\n\nexport const TRUTHMARK_CLAIM_VERIFIER_AGENT_PATH =\n \".codex/agents/truth-claim-verifier.toml\";\n\nexport const TRUTHMARK_DOC_REVIEWER_AGENT_PATH =\n \".codex/agents/truth-doc-reviewer.toml\";\nexport const TRUTHMARK_DOC_WRITER_AGENT_PATH =\n \".codex/agents/truth-doc-writer.toml\";\n\nexport const TRUTHMARK_OPENCODE_ROUTE_AUDITOR_AGENT_PATH =\n \".opencode/agents/truth-route-auditor.md\";\n\nexport const TRUTHMARK_OPENCODE_CLAIM_VERIFIER_AGENT_PATH =\n \".opencode/agents/truth-claim-verifier.md\";\n\nexport const TRUTHMARK_OPENCODE_DOC_REVIEWER_AGENT_PATH =\n \".opencode/agents/truth-doc-reviewer.md\";\nexport const TRUTHMARK_OPENCODE_DOC_WRITER_AGENT_PATH =\n \".opencode/agents/truth-doc-writer.md\";\n\nexport const TRUTHMARK_CLAUDE_ROUTE_AUDITOR_AGENT_PATH =\n \".claude/agents/truth-route-auditor.md\";\n\nexport const TRUTHMARK_CLAUDE_CLAIM_VERIFIER_AGENT_PATH =\n \".claude/agents/truth-claim-verifier.md\";\n\nexport const TRUTHMARK_CLAUDE_DOC_REVIEWER_AGENT_PATH =\n \".claude/agents/truth-doc-reviewer.md\";\nexport const TRUTHMARK_CLAUDE_DOC_WRITER_AGENT_PATH =\n \".claude/agents/truth-doc-writer.md\";\n\nexport const TRUTHMARK_GEMINI_STRUCTURE_COMMAND_PATH =\n \".gemini/commands/truthmark/structure.toml\";\n\nexport const TRUTHMARK_GEMINI_DOCUMENT_COMMAND_PATH =\n \".gemini/commands/truthmark/document.toml\";\n\nexport const TRUTHMARK_GEMINI_SYNC_COMMAND_PATH =\n \".gemini/commands/truthmark/sync.toml\";\n\nexport const TRUTHMARK_GEMINI_REALIZE_COMMAND_PATH =\n \".gemini/commands/truthmark/realize.toml\";\n\nexport const TRUTHMARK_GEMINI_CHECK_COMMAND_PATH =\n \".gemini/commands/truthmark/check.toml\";\n\nexport const TRUTHMARK_GEMINI_PREVIEW_COMMAND_PATH =\n \".gemini/commands/truthmark/preview.toml\";\n\nexport const TRUTHMARK_GEMINI_ROUTE_AUDITOR_AGENT_PATH =\n \".gemini/agents/truth-route-auditor.md\";\n\nexport const TRUTHMARK_GEMINI_CLAIM_VERIFIER_AGENT_PATH =\n \".gemini/agents/truth-claim-verifier.md\";\n\nexport const TRUTHMARK_GEMINI_DOC_REVIEWER_AGENT_PATH =\n \".gemini/agents/truth-doc-reviewer.md\";\nexport const TRUTHMARK_GEMINI_DOC_WRITER_AGENT_PATH =\n \".gemini/agents/truth-doc-writer.md\";\n\nexport const TRUTHMARK_COPILOT_STRUCTURE_PROMPT_PATH =\n \".github/prompts/truthmark-structure.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_DOCUMENT_PROMPT_PATH =\n \".github/prompts/truthmark-document.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_SYNC_PROMPT_PATH =\n \".github/prompts/truthmark-sync.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH =\n \".github/prompts/truthmark-realize.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_CHECK_PROMPT_PATH =\n \".github/prompts/truthmark-check.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_PREVIEW_PROMPT_PATH =\n \".github/prompts/truthmark-preview.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH =\n \".github/agents/truth-route-auditor.agent.md\";\n\nexport const TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH =\n \".github/agents/truth-claim-verifier.agent.md\";\n\nexport const TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH =\n \".github/agents/truth-doc-reviewer.agent.md\";\nexport const TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH =\n \".github/agents/truth-doc-writer.agent.md\";\n\nconst renderGeminiCommand = (description: string, prompt: string): string => {\n const promptWithArgs = `${prompt.trimEnd()}\\nUser focus or arguments: {{args}}`;\n\n return `description = \"${description}\"\nprompt = '''\n${promptWithArgs}\n'''\n`;\n};\n\nconst renderCopilotPromptFile = (\n description: string,\n prompt: string,\n): string => {\n return `---\nagent: 'agent'\ndescription: '${description}'\n---\n\n${prompt}\n`;\n};\n\nconst renderTomlString = (value: string): string => {\n return `\"${value.replace(/\\\\/gu, \"\\\\\\\\\").replace(/\"/gu, '\\\\\"')}\"`;\n};\n\nconst renderTomlStringArray = (values: string[]): string => {\n return `[${values.map(renderTomlString).join(\", \")}]`;\n};\n\ntype TruthmarkSkillPackageHost =\n | \"codex\"\n | \"opencode\"\n | \"claude-code\"\n | \"github-copilot\"\n | \"gemini-cli\";\n\ntype TruthmarkSkillPackageFile = {\n path: string;\n content: string;\n};\n\ntype WorkflowPackageDefinition = {\n title: string;\n argumentHint: string;\n invocations: string;\n use: (config: TruthmarkConfig) => string;\n quickRules: (config: TruthmarkConfig) => string[];\n parentRule?: string;\n};\n\nconst TRUTH_REALIZE_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize.\";\n\nconst WORKFLOW_PACKAGE_DEFINITIONS: Record<\n TruthmarkWorkflowId,\n WorkflowPackageDefinition\n> = {\n \"truthmark-structure\": {\n title: \"Truthmark Structure\",\n argumentHint: \"Optional area, directory, or routing concern\",\n invocations: TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS,\n use: () => \"Use this skill to design or repair Truthmark area structure.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, current docs, and relevant code directly.`,\n \"Define areas by product or behavior ownership, not by mechanical directory mirroring.\",\n \"Do not edit functional code.\",\n \"Read support/procedure.md before writing route or starter truth-doc changes.\",\n \"Read support/report-template.md before the final report.\",\n ],\n parentRule:\n \"Parent agent owns all Truth Structure writes and final topology decisions\",\n },\n \"truthmark-document\": {\n title: \"Truthmark Document\",\n argumentHint:\n \"Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document\",\n invocations: TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS,\n use: () =>\n \"Use this skill to document existing implemented behavior when no functional-code changes are required for the task.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, existing canonical docs, implementation code, and tests directly.`,\n \"Document current implemented behavior; do not invent future behavior.\",\n \"May write canonical truth docs and truth routing files only; must not write functional code.\",\n \"Read support/procedure.md before editing truth docs.\",\n \"Read support/subagents-and-leases.md before dispatching or accepting worker output.\",\n \"Read support/report-template.md before the final report.\",\n ],\n parentRule:\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n },\n \"truthmark-sync\": {\n title: \"Truthmark Sync\",\n argumentHint: \"Optional changed-code area, truth-doc area, or sync focus\",\n invocations: TRUTH_SYNC_EXPLICIT_INVOCATIONS,\n use: () =>\n \"Use this skill automatically before finishing when functional code changed since the last successful Truth Sync. Also run it immediately when the user explicitly invokes Truth Sync.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n \"Skip docs-only, formatting-only, behavior-preserving renames with no truth impact, missing config, and no-code changes.\",\n `Read .truthmark/config.yml, the configured root route index at ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, and relevant canonical docs.`,\n \"direct checkout inspection is the canonical path; do not require the truthmark binary.\",\n \"May write canonical truth docs and truth routing files only; must not rewrite functional code.\",\n \"Read support/procedure.md before editing truth docs.\",\n \"Read support/subagents-and-leases.md before dispatching or accepting worker output.\",\n \"Read support/report-template.md before the final report.\",\n ],\n parentRule:\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n },\n \"truthmark-preview\": {\n title: \"Truthmark Preview\",\n argumentHint:\n \"Optional requested outcome, code area, doc path, or routing question\",\n invocations: TRUTH_PREVIEW_EXPLICIT_INVOCATIONS,\n use: () =>\n \"Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, and only the truth docs or implementation files needed to preview ownership.`,\n \"Truth Preview is read-only; this report is intended, not authorized.\",\n \"must not edit files and must not issue write leases; do not run Truth Sync automatically, replace Truth Check, claim final correctness, or mutate code.\",\n \"Use optional read-only route-auditor evidence only when it reduces context or clarifies ownership.\",\n \"Hand off to the selected workflow after user approval.\",\n ],\n parentRule: \"Parent agent owns the final Truth Preview report\",\n },\n \"truthmark-realize\": {\n title: \"Truthmark Realize\",\n argumentHint:\n \"Optional truth doc path, area, or desired code behavior to realize\",\n invocations: TRUTH_REALIZE_EXPLICIT_INVOCATIONS,\n use: () =>\n \"Use this skill only when the user explicitly asks to realize truth docs into code.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read the source truth docs, .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files, tests, and relevant functional code directly.`,\n \"Truth docs lead; code follows.\",\n \"may write functional code only; must not edit truth docs or truth routing while realizing those docs.\",\n \"Read support/procedure.md before changing code.\",\n \"Read support/report-template.md before the final report.\",\n ],\n },\n \"truthmark-check\": {\n title: \"Truthmark Check\",\n argumentHint: \"Optional area, doc path, or audit focus\",\n invocations: TRUTH_CHECK_EXPLICIT_INVOCATIONS,\n use: () => \"Use this skill to audit repository truth health.\",\n quickRules: (config) => [\n \"Follow docs/ai/repo-rules.md as the repository instruction authority.\",\n `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, canonical docs, and relevant implementation directly.`,\n \"Report issues and suggested fixes; do not silently rewrite unrelated files.\",\n \"Direct checkout inspection is valid even when local tooling is unavailable.\",\n \"Read support/procedure.md before auditing details.\",\n \"Read support/subagents-and-leases.md before dispatching verifier subagents.\",\n \"Read support/report-template.md before the final report.\",\n ],\n parentRule: \"Parent agent owns the final Truth Check report\",\n },\n};\n\nconst stripWorkflowSkillFrontmatter = (body: string): string => {\n return body.replace(/^---\\n[\\s\\S]*?\\n---\\n\\n?/u, \"\").trim();\n};\n\nconst splitWorkflowSupport = (\n body: string,\n): { procedure: string; reportTemplate: string } => {\n const stripped = stripWorkflowSkillFrontmatter(body);\n const marker = \"Report completion in this shape:\";\n const markerIndex = stripped.indexOf(marker);\n\n if (markerIndex === -1) {\n return {\n procedure: stripped,\n reportTemplate: \"Report completion in the workflow-specific shape.\",\n };\n }\n\n return {\n procedure: stripped.slice(0, markerIndex).trim(),\n reportTemplate: stripped.slice(markerIndex).trim(),\n };\n};\n\nconst renderSkillSupportFile = (title: string, body: string): string => {\n return `# ${title}\n\nGenerated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\n${body}\n`;\n};\n\nconst renderHelperManifest = (helpers: TruthmarkWorkflowHelper[]): string => {\n const manifest = {\n helpers: Object.fromEntries(\n helpers.map((helper) => [\n helper.id,\n {\n optional: helper.optional,\n runner: helper.runner,\n command: helper.command,\n inputs: helper.inputs,\n output: helper.output,\n writes: helper.writes,\n ...(helper.allowedWrites === undefined\n ? {}\n : { allowedWrites: helper.allowedWrites }),\n fallback: helper.fallback,\n },\n ]),\n ),\n };\n\n return [\n `# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.`,\n stringify(manifest, { lineWidth: 0 }),\n ].join(\"\\n\");\n};\n\nconst renderHelperPolicySupport = (\n helpers: TruthmarkWorkflowHelper[],\n): string => {\n const reportHelperId =\n helpers.find((helper) => helper.id.endsWith(\"-report\"))?.id ?? helpers[0]?.id;\n const helperLines = helpers\n .map(\n (helper) =>\n `- ${helper.id}: optional ${helper.runner}; manual fallback: ${helper.fallback}`,\n )\n .join(\"\\n\");\n\n return renderSkillSupportFile(\n \"Optional Helper CLI Policy\",\n `Optional helper CLI commands may collect deterministic checkout facts or validate artifacts. If the Truthmark CLI is unavailable or too old for a declared helper, continue manually using this procedure and report which helper was skipped. Helper output is derived evidence; it does not override direct checkout inspection, workflow write boundaries, or parent acceptance.\n\nRunner detection:\n- Check the declared Truthmark CLI runner before invoking a helper.\n- Invoke helpers through the installed \\`truthmark validate ... --json\\` CLI command using argv-style arguments from helper-manifest.yml.\n- If unavailable or version-mismatched, treat the helper as skipped and use the manual fallback.\n- Do not fail the workflow solely because a helper cannot run.\n\nAvailable helpers:\n${helperLines}\n\nFinal reports should include helper status when helpers are declared for this workflow:\n\n\\`\\`\\`md\nHelper scripts:\n- ${reportHelperId}: ran, passed\n- validate-write-lease: skipped, no write lease used\n\\`\\`\\``,\n );\n};\n\nconst renderStandaloneWorkflowSkillBody = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n): string => {\n switch (workflowId) {\n case \"truthmark-structure\":\n return renderTruthStructureSkillBody(config);\n case \"truthmark-document\":\n return renderTruthDocumentSkillBody(config);\n case \"truthmark-sync\":\n return renderTruthSyncSkillBody(config);\n case \"truthmark-preview\":\n return renderTruthPreviewSkillBody(config);\n case \"truthmark-realize\":\n return renderTruthmarkRealizeSkillBody(config);\n case \"truthmark-check\":\n return renderTruthCheckSkillBody(config);\n }\n};\n\nconst renderWorkflowEntrypoint = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n supportFiles: string[],\n host: TruthmarkSkillPackageHost,\n): string => {\n const workflow = getTruthmarkWorkflow(workflowId);\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const supportFileList = supportFiles\n .map((supportFile) => `- ${supportFile}`)\n .join(\"\\n\");\n const hostUsage =\n host === \"github-copilot\"\n ? \"Use as a Copilot agent skill. Prompt files remain available under `.github/prompts/` for command-style invocation in supported Copilot IDEs.\"\n : host === \"gemini-cli\"\n ? \"Use as a Gemini CLI Agent Skill; commands remain available under `/truthmark:*` for command-first invocation.\"\n : undefined;\n\n return `---\nname: ${workflowId}\ndescription: ${workflow.description}\nargument-hint: ${definition.argumentHint}\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\n# ${definition.title}\n\n${definition.use(config)}\n${hostUsage === undefined ? \"\" : `\\n${hostUsage}\\n`}\n\nInvocations: ${definition.invocations}\n\nQuick procedure:\n${definition\n .quickRules(config)\n .map((rule) => `- ${rule}`)\n .join(\"\\n\")}\n\nProgressive disclosure:\n${supportFileList}\n`;\n};\n\nconst renderWorkflowSubagentSupport = (\n workflowId: TruthmarkWorkflowId,\n host: TruthmarkSkillPackageHost,\n): string | undefined => {\n const workflow = getTruthmarkWorkflow(workflowId);\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const readAgents = workflow.subagents ?? [];\n const writeAgents = workflow.writeSubagents ?? [];\n\n if (readAgents.length === 0 && writeAgents.length === 0) {\n return undefined;\n }\n\n if (definition.parentRule === undefined) {\n return undefined;\n }\n\n switch (host) {\n case \"codex\":\n return renderCodexSubagentModeSection(\n readAgents,\n definition.parentRule,\n writeAgents,\n );\n case \"opencode\":\n return renderOpenCodeSubagentModeSection(\n readAgents,\n definition.parentRule,\n writeAgents,\n );\n case \"claude-code\":\n return renderClaudeSubagentModeSection(\n readAgents,\n definition.parentRule,\n writeAgents,\n );\n case \"github-copilot\":\n return renderCopilotCustomAgentModeSection(\n readAgents,\n definition.parentRule,\n writeAgents,\n );\n case \"gemini-cli\":\n return renderGeminiSubagentModeSection(\n readAgents,\n definition.parentRule,\n writeAgents,\n );\n }\n};\n\nexport const renderTruthmarkSkillPackage = ({\n skillPath,\n workflowId,\n host,\n config = defaultAgentConfig(),\n}: {\n skillPath: string;\n workflowId: TruthmarkWorkflowId;\n host: TruthmarkSkillPackageHost;\n config?: TruthmarkConfig;\n}): TruthmarkSkillPackageFile[] => {\n const skillDirectory = skillPath.replace(/\\/SKILL\\.md$/u, \"\");\n const supportDirectory = `${skillDirectory}/support`;\n const { procedure, reportTemplate } = splitWorkflowSupport(\n renderStandaloneWorkflowSkillBody(workflowId, config),\n );\n const subagents = renderWorkflowSubagentSupport(workflowId, host);\n const helpers = getTruthmarkWorkflow(workflowId).helpers ?? [];\n const supportFiles = [\n \"support/procedure.md\",\n \"support/report-template.md\",\n ...(subagents === undefined ? [] : [\"support/subagents-and-leases.md\"]),\n ...(helpers.length === 0 ? [] : [\"helper-manifest.yml\", \"support/helper-policy.md\"]),\n ];\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const files: TruthmarkSkillPackageFile[] = [\n {\n path: skillPath,\n content: renderWorkflowEntrypoint(workflowId, config, supportFiles, host),\n },\n {\n path: `${supportDirectory}/procedure.md`,\n content: renderSkillSupportFile(\n `${definition.title} Procedure`,\n procedure,\n ),\n },\n {\n path: `${supportDirectory}/report-template.md`,\n content: renderSkillSupportFile(\n `${definition.title} Report Template`,\n reportTemplate,\n ),\n },\n ];\n\n if (subagents !== undefined) {\n files.push({\n path: `${supportDirectory}/subagents-and-leases.md`,\n content: renderSkillSupportFile(\n `${definition.title} Subagents And Leases`,\n subagents,\n ),\n });\n }\n\n if (helpers.length > 0) {\n files.push(\n {\n path: `${skillDirectory}/helper-manifest.yml`,\n content: renderHelperManifest(helpers),\n },\n {\n path: `${supportDirectory}/helper-policy.md`,\n content: renderHelperPolicySupport(helpers),\n },\n );\n }\n\n return files;\n};\n\nconst normalizeOpenCodePermissionPath = (path: string): string => {\n const normalized = path\n .replace(/\\\\/gu, \"/\")\n .replace(/^\\.\\//u, \"\")\n .replace(/\\/+$/u, \"\");\n\n return normalized === \"\" ? \".\" : normalized;\n};\n\nconst appendOpenCodePermissionGlob = (root: string, glob: string): string => {\n return root === \".\" ? glob.replace(/^\\//u, \"\") : `${root}${glob}`;\n};\n\nconst renderOpenCodeWriterEditAllowRules = (\n config: TruthmarkConfig,\n): string => {\n const truthDocsRoot = normalizeOpenCodePermissionPath(\n resolveTruthDocsRoot(config),\n );\n const rootRouteIndex = normalizeOpenCodePermissionPath(\n config.docs.routing.rootIndex,\n );\n const areaFilesRoot = normalizeOpenCodePermissionPath(\n config.docs.routing.areaFilesRoot,\n );\n const allowedPatterns = [\n appendOpenCodePermissionGlob(truthDocsRoot, \"/**\"),\n rootRouteIndex,\n appendOpenCodePermissionGlob(areaFilesRoot, \"/**/*.md\"),\n ];\n\n return [...new Set(allowedPatterns)]\n .map((pattern) => ` ${JSON.stringify(pattern)}: allow`)\n .join(\"\\n\");\n};\n\ntype TruthmarkSubagentProfile = {\n codexName: string;\n copilotName: string;\n description: string;\n nicknameCandidates: string[];\n instructions: string;\n};\n\nconst READ_ONLY_SUBAGENT_CONTEXT_BOUNDARY = `Context boundary:\nDo not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence.\nUse only the parent-assigned shard plus required checkout evidence files.\nReturn findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes.`;\n\nconst renderReadOnlySubagentInstructions = (instructions: string): string => {\n return `${instructions}\n${READ_ONLY_SUBAGENT_CONTEXT_BOUNDARY}`;\n};\n\nconst TRUTHMARK_SUBAGENT_PROFILES = {\n truth_route_auditor: {\n codexName: \"truth_route_auditor\",\n copilotName: \"truth-route-auditor\",\n description:\n \"Read-only Truthmark route auditor for bounded routing and ownership verification.\",\n nicknameCandidates: [\"Route Audit\", \"Route Trace\", \"Route Check\"],\n instructions: `Stay read-only.\nAudit one bounded Truthmark route, area, or doc shard assigned by the parent.\nRead .truthmark/config.yml, the root route index, relevant child route files, mapped truth docs, and relevant implementation files directly.\nFind missing, stale, broad, overloaded, catch-all, mixed-owner, or unrouteable ownership.\nDo not edit files, stage changes, or propose broad rewrites.\nReturn JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes.\nrecommendedWorkflow must be one of: none, truthmark-document, truthmark-structure.`,\n },\n truth_claim_verifier: {\n codexName: \"truth_claim_verifier\",\n copilotName: \"truth-claim-verifier\",\n description:\n \"Read-only Truthmark claim verifier for checking canonical truth against checkout evidence.\",\n nicknameCandidates: [\"Claim Audit\", \"Claim Trace\", \"Claim Check\"],\n instructions: `Stay read-only.\nVerify the behavior-bearing truth claims assigned by the parent against primary checkout evidence.\nUse implementation, tests, config, routing, generated templates, schemas, or explicit evidence blocks as primary evidence.\nCanonical docs and examples can corroborate but are not sole proof when implementation conflicts.\nFor every checked claim, classify the result as supported | narrowed | removed | blocked.\nDo not edit files, stage changes, or invent missing behavior.\nReturn JSON only with keys: scope, filesReviewed, claimsChecked, evidence, unsupportedClaims, confidence, recommendedWorkflow, notes.`,\n },\n truth_doc_reviewer: {\n codexName: \"truth_doc_reviewer\",\n copilotName: \"truth-doc-reviewer\",\n description:\n \"Read-only Truthmark doc reviewer for shape, decision, rationale, and evidence hygiene.\",\n nicknameCandidates: [\"Doc Audit\", \"Doc Shape\", \"Doc Check\"],\n instructions: `Stay read-only.\nReview assigned canonical truth docs for frontmatter, source_of_truth, required template sections, Evidence checked entries, Product Decisions, and Rationale.\nFlag README.md files used as behavior truth targets, mixed-owner docs, and shape repairs that should move to Truth Structure.\nDo not edit files, stage changes, or rewrite docs.\nReturn JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes.\nrecommendedWorkflow must be one of: none, truthmark-document, truthmark-structure.`,\n },\n} satisfies Record<TruthmarkReadOnlySubagentId, TruthmarkSubagentProfile>;\ntype TruthmarkWriteSubagentProfile = {\n codexName: string;\n copilotName: string;\n description: string;\n nicknameCandidates: string[];\n instructions: string;\n};\nconst TRUTHMARK_WRITE_SUBAGENT_PROFILES = {\n truth_doc_writer: {\n codexName: \"truth_doc_writer\",\n copilotName: \"truth-doc-writer\",\n description:\n \"Write-capable Truthmark doc worker for one parent-leased truth-document shard.\",\n nicknameCandidates: [\"Doc Writer\", \"Truth Writer\", \"Doc Sync\"],\n instructions: `Write one leased Truthmark truth-document shard assigned by the parent.\nRequire an explicit write lease before editing. The lease must name workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields.\nRead every requiredReads entry directly before editing.\nEdit only leased canonical truth docs or leased truth routing files. Do not edit functional code, generated host surfaces, package files, config files, templates, or tests unless they are explicitly leased.\nDo not expand your own write scope. If the task needs an off-lease file, stop and report blocked.\nBlock when ownership is missing or ambiguous, evidence does not support the requested claim, another worker changed the leased file, generated surfaces appear stale, or a required edit is outside the lease.\nReturn YAML only with keys: ${TRUTHMARK_WRITE_WORKER_REPORT_FIELDS.join(\", \")}.\nstatus must be completed or blocked.\nfilesChanged must list only files you actually changed.\noffLeaseChanges must be empty for completed reports.\nThe parent must validate the actual checkout diff before accepting your report.`,\n },\n} satisfies Record<TruthmarkWriteSubagentId, TruthmarkWriteSubagentProfile>;\n\nconst renderCodexReadOnlyAgent = ({\n name,\n description,\n nicknameCandidates,\n developerInstructions,\n}: {\n name: string;\n description: string;\n nicknameCandidates: string[];\n developerInstructions: string;\n}): string => {\n return `# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\nname = ${renderTomlString(name)}\ndescription = ${renderTomlString(description)}\nsandbox_mode = \"read-only\"\nnickname_candidates = ${renderTomlStringArray(nicknameCandidates)}\ndeveloper_instructions = \"\"\"\n${developerInstructions}\n\"\"\"\n`;\n};\nconst renderCodexWriteAgent = ({\n name,\n description,\n nicknameCandidates,\n developerInstructions,\n}: {\n name: string;\n description: string;\n nicknameCandidates: string[];\n developerInstructions: string;\n}): string => {\n return `# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\nname = ${renderTomlString(name)}\ndescription = ${renderTomlString(description)}\nsandbox_mode = \"workspace-write\"\nnickname_candidates = ${renderTomlStringArray(nicknameCandidates)}\ndeveloper_instructions = \"\"\"\n${developerInstructions}\n\"\"\"\n`;\n};\n\nconst renderCopilotReadOnlyAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkSubagentProfile): string => {\n const agentInstructions = renderReadOnlySubagentInstructions(instructions);\n\n return `---\nname: ${copilotName}\ndescription: ${description}\ntools: [read, search]\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\n${agentInstructions}\n`;\n};\nconst renderCopilotWriteAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkWriteSubagentProfile): string => {\n return `---\nname: ${copilotName}\ndescription: ${description}\ntools: [read, search, edit]\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\n${instructions}\n`;\n};\n\nconst renderGeminiReadOnlyAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkSubagentProfile): string => {\n const agentInstructions = renderReadOnlySubagentInstructions(instructions);\n\n return `---\nname: ${copilotName}\ndescription: ${description}\nkind: local\ntools: [read_file, grep_search]\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: @${copilotName}\n\n${agentInstructions}\n`;\n};\nconst renderGeminiWriteAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkWriteSubagentProfile): string => {\n return `---\nname: ${copilotName}\ndescription: ${description}\nkind: local\ntools: [read_file, grep_search, write_file]\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: @${copilotName} with an explicit parent write lease.\n\n${instructions}\n`;\n};\n\nconst renderClaudeReadOnlyAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkSubagentProfile): string => {\n const agentInstructions = renderReadOnlySubagentInstructions(instructions);\n\n return `---\nname: ${copilotName}\ndescription: ${description}\ntools: Read, Grep, Glob, LS\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: use the ${copilotName} subagent.\n\n${agentInstructions}\n`;\n};\nconst renderClaudeWriteAgent = ({\n copilotName,\n description,\n instructions,\n}: TruthmarkWriteSubagentProfile): string => {\n return `---\nname: ${copilotName}\ndescription: ${description}\ntools: Read, Grep, Glob, LS, Edit, MultiEdit\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: use the ${copilotName} subagent with an explicit parent write lease.\n\n${instructions}\n`;\n};\n\nexport const renderTruthmarkRouteAuditorAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor;\n\n return renderCodexReadOnlyAgent({\n name: profile.codexName,\n description: profile.description,\n nicknameCandidates: profile.nicknameCandidates,\n developerInstructions: renderReadOnlySubagentInstructions(\n profile.instructions,\n ),\n });\n};\n\nexport const renderTruthmarkClaimVerifierAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier;\n\n return renderCodexReadOnlyAgent({\n name: profile.codexName,\n description: profile.description,\n nicknameCandidates: profile.nicknameCandidates,\n developerInstructions: renderReadOnlySubagentInstructions(\n profile.instructions,\n ),\n });\n};\n\nexport const renderTruthmarkDocReviewerAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer;\n\n return renderCodexReadOnlyAgent({\n name: profile.codexName,\n description: profile.description,\n nicknameCandidates: profile.nicknameCandidates,\n developerInstructions: renderReadOnlySubagentInstructions(\n profile.instructions,\n ),\n });\n};\nexport const renderTruthmarkDocWriterAgent = (): string => {\n const profile = TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer;\n\n return renderCodexWriteAgent({\n name: profile.codexName,\n description: profile.description,\n nicknameCandidates: profile.nicknameCandidates,\n developerInstructions: profile.instructions,\n });\n};\n\nexport const renderTruthmarkCopilotRouteAuditorAgent = (): string => {\n return renderCopilotReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor,\n );\n};\n\nexport const renderTruthmarkCopilotClaimVerifierAgent = (): string => {\n return renderCopilotReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier,\n );\n};\n\nexport const renderTruthmarkCopilotDocReviewerAgent = (): string => {\n return renderCopilotReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer,\n );\n};\nexport const renderTruthmarkCopilotDocWriterAgent = (): string => {\n return renderCopilotWriteAgent(\n TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer,\n );\n};\n\nexport const renderTruthmarkGeminiRouteAuditorAgent = (): string => {\n return renderGeminiReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor,\n );\n};\n\nexport const renderTruthmarkGeminiClaimVerifierAgent = (): string => {\n return renderGeminiReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier,\n );\n};\n\nexport const renderTruthmarkGeminiDocReviewerAgent = (): string => {\n return renderGeminiReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer,\n );\n};\nexport const renderTruthmarkGeminiDocWriterAgent = (): string => {\n return renderGeminiWriteAgent(\n TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer,\n );\n};\n\nexport const renderTruthmarkClaudeRouteAuditorAgent = (): string => {\n return renderClaudeReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor,\n );\n};\n\nexport const renderTruthmarkClaudeClaimVerifierAgent = (): string => {\n return renderClaudeReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier,\n );\n};\n\nexport const renderTruthmarkClaudeDocReviewerAgent = (): string => {\n return renderClaudeReadOnlyAgent(\n TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer,\n );\n};\nexport const renderTruthmarkClaudeDocWriterAgent = (): string => {\n return renderClaudeWriteAgent(\n TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer,\n );\n};\n\nconst renderOpenCodeReadOnlyAgent = ({\n invocation,\n description,\n instructions,\n}: {\n invocation: string;\n description: string;\n instructions: string;\n}): string => {\n const agentInstructions = renderReadOnlySubagentInstructions(instructions);\n\n return `---\ndescription: ${description}\nmode: subagent\npermission:\n edit: deny\n task: deny\n webfetch: deny\n websearch: deny\n external_directory: deny\n bash:\n \"*\": ask\n \"git status*\": allow\n \"git diff*\": allow\n \"git log*\": allow\n \"rg *\": allow\n \"grep *\": allow\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: @${invocation}\n\n${agentInstructions}\n`;\n};\nconst renderOpenCodeWriteAgent = ({\n invocation,\n description,\n instructions,\n config,\n}: {\n invocation: string;\n description: string;\n instructions: string;\n config: TruthmarkConfig;\n}): string => {\n const editAllowRules = renderOpenCodeWriterEditAllowRules(config);\n\n return `---\ndescription: ${description}\nmode: subagent\npermission:\n read: allow\n list: allow\n grep: allow\n glob: allow\n edit:\n \"*\": deny\n${editAllowRules}\n task: deny\n webfetch: deny\n websearch: deny\n external_directory: deny\n bash:\n \"*\": ask\n \"git status*\": allow\n \"git diff*\": allow\n---\n\n# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades.\n\nManual invocation: @${invocation}\n\n${instructions}\n`;\n};\n\nexport const renderTruthmarkOpenCodeRouteAuditorAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor;\n\n return renderOpenCodeReadOnlyAgent({\n invocation: profile.copilotName,\n description: profile.description,\n instructions: profile.instructions,\n });\n};\n\nexport const renderTruthmarkOpenCodeClaimVerifierAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier;\n\n return renderOpenCodeReadOnlyAgent({\n invocation: profile.copilotName,\n description: profile.description,\n instructions: profile.instructions,\n });\n};\n\nexport const renderTruthmarkOpenCodeDocReviewerAgent = (): string => {\n const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer;\n\n return renderOpenCodeReadOnlyAgent({\n invocation: profile.copilotName,\n description: profile.description,\n instructions: profile.instructions,\n });\n};\nexport const renderTruthmarkOpenCodeDocWriterAgent = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const profile = TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer;\n\n return renderOpenCodeWriteAgent({\n invocation: profile.copilotName,\n description: profile.description,\n instructions: profile.instructions,\n config,\n });\n};\n\nexport const renderTruthmarkStructureSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthStructureSkillBody(config);\n};\n\nexport const renderTruthmarkStructureLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthStructureSkillBody(config);\n};\n\nexport const renderTruthmarkStructureClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthStructureSkillBody(config, {\n includeClaudeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkStructureSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkDocumentSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthDocumentSkillBody(config, {\n includeCodexSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkDocumentLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthDocumentSkillBody(config);\n};\n\nexport const renderTruthmarkDocumentClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthDocumentSkillBody(config, {\n includeClaudeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkDocumentOpenCodeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthDocumentSkillBody(config, {\n includeOpenCodeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkDocumentSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-document\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkSyncSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthSyncSkillBody(config, { includeCodexSubagentMode: true });\n};\n\nexport const renderTruthmarkSyncLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthSyncSkillBody(config);\n};\n\nexport const renderTruthmarkSyncClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthSyncSkillBody(config, { includeClaudeSubagentMode: true });\n};\n\nexport const renderTruthmarkSyncOpenCodeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthSyncSkillBody(config, {\n includeOpenCodeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkSyncSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nconst renderTruthmarkRealizeSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n const workflow = getTruthmarkWorkflow(\"truthmark-realize\");\n\n return `---\nname: truthmark-realize\ndescription: ${workflow.description}\nargument-hint: Optional truth doc path, area, or desired code behavior to realize\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\n# Truthmark Realize\n\nUse this skill only when the user explicitly asks to realize truth docs into code.\n\nInvocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize.\n\nTruth Realize is doc-first:\n\n- truth docs lead\n- code follows\n- Truth Realize never edits the truth docs it is realizing\n\nWorkflow:\n\n1. Read the updated truth docs named by the user, or infer the relevant docs from ${config.docs.routing.rootIndex}.\n2. Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files, tests, and the relevant functional code.\n3. ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n${renderTruthDocOwnershipGateSection(\n \"source truth docs before writing code\",\n \"if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document\",\n)}\n4. Update functional code only so implementation matches bounded, current truth claims from the source docs.\n5. Do not edit truth docs or truth routing while realizing those docs.\n6. Run relevant tests for the changed code.\n7. Report changed code files and verification steps.\n${renderHierarchySummary(config)}\n\nRead and write boundaries:\n\n- may read truth docs, routing docs, and relevant functional code\n- may write functional code only\n- must not edit truth docs or truth routing while realizing those docs\n\nReport completion in this shape:\n\n\\`\\`\\`md\nTruth Realize: completed\n\nTruth docs used:\n- ${truthDocsRoot}/authentication/session-timeout.md\n\nCode updated:\n- src/auth/session.ts\n\nVerification:\n- npm test -- auth\n\\`\\`\\`\n`;\n};\n\nexport const renderTruthmarkRealizeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthmarkRealizeSkillBody(config);\n};\n\nexport const renderTruthmarkRealizeLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthmarkRealizeSkillBody(config);\n};\n\nexport const renderTruthmarkRealizeSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-realize\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkPreviewSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthPreviewSkillBody(config);\n};\n\nexport const renderTruthmarkPreviewLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthPreviewSkillBody(config);\n};\n\nexport const renderTruthmarkPreviewClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthPreviewSkillBody(config);\n};\n\nexport const renderTruthmarkPreviewOpenCodeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthPreviewSkillBody(config);\n};\n\nexport const renderTruthmarkPreviewSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-preview\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkCheckSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthCheckSkillBody(config, { includeCodexSubagentMode: true });\n};\n\nexport const renderTruthmarkCheckLocalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthCheckSkillBody(config);\n};\n\nexport const renderTruthmarkCheckClaudeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthCheckSkillBody(config, { includeClaudeSubagentMode: true });\n};\n\nexport const renderTruthmarkCheckOpenCodeSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthCheckSkillBody(config, {\n includeOpenCodeSubagentMode: true,\n });\n};\n\nexport const renderTruthmarkCheckSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-check\");\n\n return `interface:\n display_name: \"${workflow.displayName}\"\n short_description: \"${workflow.shortDescription}\"\n default_prompt: \"${workflow.defaultPrompt}\"\n\npolicy:\n allow_implicit_invocation: ${workflow.allowImplicitInvocation}\n\ntruthmark:\n version: \"${TRUTHMARK_VERSION}\"\n refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkGeminiStructureCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthStructureSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiDocumentCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-document\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthDocumentSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiSyncCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthSyncSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiRealizeCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-realize\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthmarkRealizeSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiCheckCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-check\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthCheckSkillBody(config),\n );\n};\n\nexport const renderTruthmarkGeminiPreviewCommand = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-preview\");\n\n return renderGeminiCommand(\n workflow.description,\n renderTruthPreviewSkillBody(config),\n );\n};\n\nexport const renderTruthmarkCopilotStructurePrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthStructureSkillBody(config, {\n includeCopilotCustomAgentMode: true,\n }),\n );\n};\n\nexport const renderTruthmarkCopilotDocumentPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-document\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthDocumentSkillBody(config, {\n includeCopilotCustomAgentMode: true,\n }),\n );\n};\n\nexport const renderTruthmarkCopilotSyncPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthSyncSkillBody(config, {\n includeCopilotCustomAgentMode: true,\n }),\n );\n};\n\nexport const renderTruthmarkCopilotRealizePrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-realize\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthmarkRealizeSkillBody(config),\n );\n};\n\nexport const renderTruthmarkCopilotCheckPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-check\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthCheckSkillBody(config, {\n includeCopilotCustomAgentMode: true,\n }),\n );\n};\n\nexport const renderTruthmarkCopilotPreviewPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-preview\");\n\n return renderCopilotPromptFile(\n workflow.description,\n renderTruthPreviewSkillBody(config),\n );\n};\n","import { TRUTHMARK_VERSION } from \"../version.js\";\n\nexport type TruthmarkWorkflowId =\n | \"truthmark-sync\"\n | \"truthmark-structure\"\n | \"truthmark-document\"\n | \"truthmark-preview\"\n | \"truthmark-realize\"\n | \"truthmark-check\";\n\nexport type TruthmarkReadOnlySubagentId =\n | \"truth_route_auditor\"\n | \"truth_claim_verifier\"\n | \"truth_doc_reviewer\";\nexport type TruthmarkWriteSubagentId = \"truth_doc_writer\";\nexport type TruthmarkSubagentId =\n | TruthmarkReadOnlySubagentId\n | TruthmarkWriteSubagentId;\n\nexport type TruthmarkWorkflowHelperCommand = {\n argv: string[];\n};\n\nexport type TruthmarkWorkflowHelper = {\n id: string;\n optional: boolean;\n runner: string;\n command: TruthmarkWorkflowHelperCommand;\n inputs: string[];\n output: \"json\";\n writes: boolean;\n allowedWrites?: string[];\n fallback: string;\n};\n\nexport type TruthmarkWorkflowManifestEntry = {\n id: TruthmarkWorkflowId;\n displayName: string;\n description: string;\n shortDescription: string;\n defaultPrompt: string;\n allowImplicitInvocation: boolean;\n positiveTriggers: string[];\n negativeTriggers: string[];\n forbiddenAdjacency: string[];\n requiredGates: string[];\n allowedWrites: string[];\n reportSections: string[];\n subagents?: TruthmarkReadOnlySubagentId[];\n writeSubagents?: TruthmarkWriteSubagentId[];\n helpers?: TruthmarkWorkflowHelper[];\n};\n\nconst TRUTHMARK_CLI_RUNNER = `truthmark>=${TRUTHMARK_VERSION}`;\n\nconst VALIDATE_SYNC_REPORT_HELPER = {\n id: \"validate-sync-report\",\n optional: true,\n runner: TRUTHMARK_CLI_RUNNER,\n command: { argv: [\"truthmark\", \"validate\", \"sync-report\", \"<report-file>\", \"--json\"] },\n inputs: [\"sync report file\"],\n output: \"json\",\n writes: false,\n fallback:\n \"manually validate support/report-template.md and check Evidence checked entries match Claim, indented Evidence, and Result: supported | narrowed | removed | blocked\",\n} satisfies TruthmarkWorkflowHelper;\n\nconst VALIDATE_DOCUMENT_REPORT_HELPER = {\n id: \"validate-document-report\",\n optional: true,\n runner: TRUTHMARK_CLI_RUNNER,\n command: { argv: [\"truthmark\", \"validate\", \"document-report\", \"<report-file>\", \"--json\"] },\n inputs: [\"document report file\"],\n output: \"json\",\n writes: false,\n fallback:\n \"manually validate support/report-template.md required sections and structured Evidence checked entries\",\n} satisfies TruthmarkWorkflowHelper;\n\nconst VALIDATE_WRITE_LEASE_HELPER = {\n id: \"validate-write-lease\",\n optional: true,\n runner: TRUTHMARK_CLI_RUNNER,\n command: {\n argv: [\n \"truthmark\",\n \"validate\",\n \"write-lease\",\n \"<lease-or-report-file>\",\n \"<changed-files-file>\",\n \"--json\",\n ],\n },\n inputs: [\"lease or worker report yaml\", \"changed file list\"],\n output: \"json\",\n writes: false,\n fallback:\n \"manually compare declared allowedWrites and forbiddenWrites with the actual changed files\",\n} satisfies TruthmarkWorkflowHelper;\n\nexport const TRUTHMARK_WORKFLOW_MANIFEST = {\n \"truthmark-sync\": {\n id: \"truthmark-sync\",\n displayName: \"Truthmark Sync\",\n description:\n \"Use automatically at finish-time after functional code changes, or explicit /truthmark-sync, $truthmark-sync, or /truthmark:sync. Skip docs-only, formatting-only, behavior-preserving renames, missing config, and no-code changes. Not for doc-first realization or manual topology design.\",\n shortDescription:\n \"Sync truth docs from functional code changes; skip docs-only/no-code changes\",\n defaultPrompt:\n \"Use $truthmark-sync after functional code changes; skip docs-only/no-code changes.\",\n allowImplicitInvocation: true,\n positiveTriggers: [\n \"functional code changed since last successful Truth Sync\",\n \"explicit /truthmark-sync, $truthmark-sync, or /truthmark:sync\",\n ],\n negativeTriggers: [\n \"documentation-only change\",\n \"formatting-only change\",\n \"behavior-preserving rename\",\n \"missing Truthmark config\",\n \"no functional code changes\",\n ],\n forbiddenAdjacency: [\n \"doc-first implementation belongs to Truth Realize\",\n \"manual topology design belongs to Truth Structure\",\n ],\n requiredGates: [\n \"topology quality\",\n \"truth-doc ownership\",\n \"Product Decisions/Rationale preservation\",\n \"truth-doc shape repair when restructuring\",\n \"Evidence Gate\",\n ],\n allowedWrites: [\"canonical truth docs\", \"truth routing files\"],\n reportSections: [\n \"Changed code reviewed\",\n \"Ownership reviewed\",\n \"Structure required\",\n \"Truth docs updated\",\n \"Truth docs split\",\n \"Evidence checked\",\n \"Helper scripts\",\n \"Notes\",\n ],\n subagents: [\"truth_route_auditor\", \"truth_claim_verifier\"],\n writeSubagents: [\"truth_doc_writer\"],\n helpers: [VALIDATE_SYNC_REPORT_HELPER, VALIDATE_WRITE_LEASE_HELPER],\n },\n \"truthmark-structure\": {\n id: \"truthmark-structure\",\n displayName: \"Truthmark Structure\",\n description:\n \"Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, needs split/repair, or needs new area setup. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code.\",\n shortDescription: \"Design, repair, or set up Truthmark area routing\",\n defaultPrompt:\n \"Use $truthmark-structure to design, repair, or set up Truthmark area routing.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"split broad repository routing into bounded areas\",\n \"repair missing, stale, catch-all, unrouteable, or mixed-owner truth ownership\",\n \"onboard a new code area into Truthmark routing\",\n \"new package, controller, domain, or product area lacks bounded truth ownership\",\n ],\n negativeTriggers: [\n \"document existing implemented behavior\",\n \"sync truth after a functional code diff\",\n \"realize truth docs into code\",\n ],\n forbiddenAdjacency: [\n \"must not implement functional code\",\n \"must not patch mixed-owner docs as shape repair\",\n ],\n requiredGates: [\n \"truth-doc ownership\",\n \"Product Decisions/Rationale preservation\",\n \"truth-doc shape repair when restructuring\",\n \"Evidence Gate\",\n ],\n allowedWrites: [\"truth routing files\", \"starter canonical truth docs\"],\n reportSections: [\n \"Topology reviewed\",\n \"Areas reviewed\",\n \"Routing updated\",\n \"Initial truth boundary\",\n \"Truth docs created\",\n \"Truth docs split\",\n \"Truth docs restructured\",\n \"Evidence checked\",\n \"Topology decisions\",\n \"Notes\",\n ],\n subagents: [\"truth_route_auditor\"],\n },\n \"truthmark-document\": {\n id: \"truthmark-document\",\n displayName: \"Truthmark Document\",\n description:\n \"Use when the user asks to document existing implemented behavior, or Sync, Check, or Structure finds implemented behavior missing canonical truth. Not for functional-code changes, doc-first implementation, or topology repair that needs Structure.\",\n shortDescription: \"Document existing implemented behavior\",\n defaultPrompt:\n \"Use $truthmark-document to document existing implemented behavior.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"document existing implemented behavior\",\n \"handoff finds implemented behavior missing canonical truth\",\n ],\n negativeTriggers: [\n \"functional-code change that requires Truth Sync\",\n \"doc-first implementation\",\n \"topology repair that needs Truth Structure\",\n ],\n forbiddenAdjacency: [\n \"must not edit functional code\",\n \"must not repair mixed-owner docs in place\",\n ],\n requiredGates: [\n \"truth-doc ownership\",\n \"Product Decisions/Rationale preservation\",\n \"Evidence Gate\",\n \"truth-doc shape repair when restructuring\",\n ],\n allowedWrites: [\"canonical truth docs\", \"truth routing files\"],\n reportSections: [\n \"Implementation reviewed\",\n \"Ownership reviewed\",\n \"Structure required\",\n \"Truth docs created\",\n \"Truth docs updated\",\n \"Truth docs restructured\",\n \"Routing updated\",\n \"Evidence checked\",\n \"Helper scripts\",\n \"Notes\",\n ],\n subagents: [\"truth_route_auditor\", \"truth_claim_verifier\"],\n writeSubagents: [\"truth_doc_writer\"],\n helpers: [VALIDATE_DOCUMENT_REPORT_HELPER, VALIDATE_WRITE_LEASE_HELPER],\n },\n \"truthmark-realize\": {\n id: \"truthmark-realize\",\n displayName: \"Truthmark Realize\",\n description:\n \"Use when the user explicitly asks to realize Truthmark truth docs into code, including /truthmark-realize, $truthmark-realize, or /truthmark:realize. Not for syncing docs after code changes, documenting existing code, topology repair, or truth audits.\",\n shortDescription: \"Realize truth docs into code\",\n defaultPrompt: \"Use $truthmark-realize to realize the updated truth docs into code.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\"explicitly realize truth docs into functional code\"],\n negativeTriggers: [\n \"sync docs after code changes\",\n \"document existing implemented behavior\",\n \"topology repair\",\n \"truth audit\",\n ],\n forbiddenAdjacency: [\n \"must not edit truth docs\",\n \"must not edit truth routing\",\n ],\n requiredGates: [\"truth-doc ownership\"],\n allowedWrites: [\"functional code\"],\n reportSections: [\"Truth docs used\", \"Code updated\", \"Verification\"],\n },\n \"truthmark-preview\": {\n id: \"truthmark-preview\",\n displayName: \"Truthmark Preview\",\n description:\n \"Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check.\",\n shortDescription:\n \"Preview likely workflow routing before edits; read-only and explicit\",\n defaultPrompt:\n \"Use $truthmark-preview to preview likely Truthmark routing before edits.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"explicit request to preview Truthmark workflow routing before edits\",\n \"explicit request for likely route owner, target docs, expected writes, or subagent plan\",\n ],\n negativeTriggers: [\n \"normal validation or final correctness audit\",\n \"automatic preflight or finish-time gate\",\n \"request to mutate truth docs, routing, or code\",\n ],\n forbiddenAdjacency: [\n \"must not replace Truth Check\",\n \"must not run Truth Sync automatically\",\n \"must not authorize later edits or issue write leases\",\n ],\n requiredGates: [\n \"read-only boundary\",\n \"intended-not-authorized handoff\",\n \"blocking ambiguity disclosure\",\n ],\n allowedWrites: [\"none by default\"],\n reportSections: [\n \"Requested outcome\",\n \"Likely workflow\",\n \"Why this workflow\",\n \"Likely route owner\",\n \"Expected write classes\",\n \"Expected target files\",\n \"Suggested subagent use\",\n \"Blocking ambiguity\",\n \"Handoff\",\n ],\n subagents: [\"truth_route_auditor\"],\n },\n \"truthmark-check\": {\n id: \"truthmark-check\",\n displayName: \"Truthmark Check\",\n description:\n \"Use when the user asks to audit repository truth health, routing, ownership, or canonical docs. Not for normal lint/test/typecheck/code-review verification, finish-time Sync, or silently rewriting docs.\",\n shortDescription: \"Audit repository truth health\",\n defaultPrompt: \"Use $truthmark-check to audit repository truth health.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"audit repository truth health\",\n \"audit routing, ownership, or canonical docs\",\n ],\n negativeTriggers: [\n \"normal lint/test/typecheck verification\",\n \"code review\",\n \"finish-time Truth Sync\",\n ],\n forbiddenAdjacency: [\n \"must not replace ordinary verification\",\n \"must not silently rewrite docs\",\n ],\n requiredGates: [\"audit Evidence Gate\"],\n allowedWrites: [\"none by default\"],\n reportSections: [\n \"Files reviewed\",\n \"Issues found\",\n \"Fixes suggested\",\n \"Evidence checked\",\n \"Validation\",\n ],\n subagents: [\n \"truth_route_auditor\",\n \"truth_claim_verifier\",\n \"truth_doc_reviewer\",\n ],\n },\n} satisfies Record<TruthmarkWorkflowId, TruthmarkWorkflowManifestEntry>;\n\nexport const TRUTHMARK_WORKFLOW_IDS = Object.keys(\n TRUTHMARK_WORKFLOW_MANIFEST,\n) as TruthmarkWorkflowId[];\n\nexport const getTruthmarkWorkflow = (\n id: TruthmarkWorkflowId,\n): TruthmarkWorkflowManifestEntry => {\n return TRUTHMARK_WORKFLOW_MANIFEST[id];\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n renderAuditEvidenceCheckedSection,\n renderAuditEvidenceGateSection,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n defaultAgentConfig,\n renderHierarchySummary,\n} from \"./shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const TRUTH_CHECK_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-check; Codex /truthmark-check or $truthmark-check; Claude Code /truthmark-check; GitHub Copilot /truthmark-check; Gemini CLI /truthmark:check.\";\n\nexport const renderTruthCheckReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const rootRouteIndex = config.docs.routing.rootIndex;\n return `Truth Check: completed\n\nFiles reviewed:\n- ${rootRouteIndex}\n\nIssues found:\n- none\n\nFixes suggested:\n- none\n\n${renderAuditEvidenceCheckedSection([\n {\n finding: \"The root route index is present and maps repository truth owners.\",\n evidence: [\".truthmark/config.yml:1\", `${rootRouteIndex}:1`],\n suggestedFix: \"none\",\n confidence: \"high\",\n },\n ])}\n\nValidation:\n- truthmark check`;\n};\n\nexport const renderTruthCheckSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCodexSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n includeOpenCodeSubagentMode?: boolean;\n } = {},\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-check\");\n const claudeSubagentMode = options.includeClaudeSubagentMode\n ? `${renderClaudeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns the final Truth Check report\",\n )}\\n\\n`\n : \"\";\n const codexSubagentMode = options.includeCodexSubagentMode\n ? `${renderCodexSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns the final Truth Check report\",\n )}\\n\\n`\n : \"\";\n const copilotCustomAgentMode = options.includeCopilotCustomAgentMode\n ? `${renderCopilotCustomAgentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns the final Truth Check report\",\n )}\\n\\n`\n : \"\";\n const openCodeSubagentMode = options.includeOpenCodeSubagentMode\n ? `${renderOpenCodeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns the final Truth Check report\",\n )}\\n\\n`\n : \"\";\n const subagentMode = `${claudeSubagentMode}${codexSubagentMode}${copilotCustomAgentMode}${openCodeSubagentMode}`;\n\n return `---\nname: truthmark-check\ndescription: ${workflow.description}\nargument-hint: Optional area, doc path, or audit focus\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\n# Truthmark Check\n\nUse this skill to audit repository truth health.\n\nInvocations: ${TRUTH_CHECK_EXPLICIT_INVOCATIONS}\n\nTruth Check is agent-led:\n\n- inspect .truthmark/config.yml, ${config.docs.routing.rootIndex}, canonical docs, and relevant implementation directly\n- ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n- inspect the configured root route index at ${config.docs.routing.rootIndex} and relevant child route files under ${config.docs.routing.areaFilesRoot}/\n- check that current docs describe current code rather than historical plans\n- check that ${config.docs.routing.rootIndex} routes code surfaces to canonical truth docs\n- check for broad, catch-all, index-like, or mixed-owner truth docs and report them as topology issues requiring Truth Structure\n- check that canonical behavior docs keep active Product Decisions and Rationale sections\n- optionally run truthmark check when local tooling is available\n- must not require the truthmark binary; direct inspection is always valid\n- report issues and suggested fixes without silently rewriting unrelated files\n- if follow-up docs edits are needed for mixed-owner docs, run or recommend Truth Structure before editing\n${renderAuditEvidenceGateSection()}\n\n${subagentMode}${renderHierarchySummary(config)}\n${DECISION_TRUTH_INSTRUCTIONS}\n\nReport completion in this shape:\n\n${renderMarkdownExample(renderTruthCheckReportExample(config))}`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS,\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n FEATURE_DOC_TEMPLATE_INSTRUCTIONS,\n REPOSITORY_INTELLIGENCE_INSTRUCTIONS,\n TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n renderClaimEvidenceCheckedSection,\n renderRouteFirstEvidenceGateSection,\n renderHierarchySummary,\n renderTruthDocOwnershipGateSection,\n renderTruthDocRestructureGateSection,\n resolveTruthDocsRoot,\n} from \"./shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-document; Codex /truthmark-document or $truthmark-document; Claude Code /truthmark-document; GitHub Copilot /truthmark-document; Gemini CLI /truthmark:document.\";\n\nexport const renderTruthDocumentReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n const helperScripts = [\"validate-write-lease: skipped, no write lease used\"];\n\n return `Truth Document: completed\n\nImplementation reviewed:\n- src/routing/area-resolver.ts\n\nOwnership reviewed:\n- ${config.docs.routing.rootIndex}\n\nTruth docs created:\n- ${truthDocsRoot}/contracts.md\n\nTruth docs updated:\n- ${truthDocsRoot}/check-diagnostics.md\n\nTruth docs restructured:\n- ${truthDocsRoot}/check-diagnostics.md\n\nRouting updated:\n- ${config.docs.routing.rootIndex}\n\n${renderClaimEvidenceCheckedSection([\n {\n claim: \"Route resolution behavior is documented in the contracts truth doc.\",\n evidence: [\n \"src/routing/area-resolver.ts:14\",\n `${config.docs.routing.rootIndex}:9`,\n ],\n result: \"supported\",\n },\n ])}\n\nHelper scripts:\n${helperScripts.map((helperScript) => `- ${helperScript}`).join(\"\\n\")}\n\nNotes:\n- Documented routing and behavior from route handlers and tests.`;\n};\n\nexport const renderTruthDocumentSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCodexSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n includeOpenCodeSubagentMode?: boolean;\n } = {},\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-document\");\n const claudeSubagentMode = options.includeClaudeSubagentMode\n ? `${renderClaudeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const codexSubagentMode = options.includeCodexSubagentMode\n ? `${renderCodexSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const copilotCustomAgentMode = options.includeCopilotCustomAgentMode\n ? `${renderCopilotCustomAgentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const openCodeSubagentMode = options.includeOpenCodeSubagentMode\n ? `${renderOpenCodeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Document acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const subagentMode = `${claudeSubagentMode}${codexSubagentMode}${copilotCustomAgentMode}${openCodeSubagentMode}`;\n\n return `---\nname: truthmark-document\ndescription: ${workflow.description}\nargument-hint: Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\n# Truthmark Document\n\nUse this skill to document existing implemented behavior when no functional-code changes are required for the task.\nInvocations: ${TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS}\n\nTruth Document is manual and implementation-first:\n\n- run only when the user explicitly asks to generate or update truth docs for existing behavior, or when Truth Sync, Truth Check, or Truth Structure reports implemented behavior that lacks canonical truth docs\n- inspect .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, existing canonical docs, implementation code, and tests directly\n- ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n- document current implemented behavior; do not invent future behavior or planned endpoints\n- may write canonical truth docs and ${config.docs.routing.rootIndex} or relevant child route files only\n- must not write functional code\n- when routing is missing, stale, broad, overloaded, catch-all, or cannot map the behavior to a bounded truth owner, run Truth Structure first when routing repair is safe and in scope\n- block and recommend Truth Structure when routing repair is unsafe, ambiguous, or outside the task boundary\n- keep feature README.md files as indexes rather than truth-document targets\n- create or update bounded leaf truth docs when behavior does not fit an existing leaf doc\n- keep behavior truth docs behavior-oriented, not endpoint-oriented, unless the endpoint itself is the behavior boundary\n- keep API endpoint details in the nearest contract truth doc when such a doc owns the API contract\n- preserve unrelated authored content\n${renderTruthDocOwnershipGateSection(\n \"the implemented behavior and candidate truth docs\",\n \"if the target doc is broad, mixed-owner, index-like, or the documented behavior spans independent owners, run Truth Structure first when safe and in scope; otherwise block and recommend Truth Structure\",\n )}\n${TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS}\n${renderRouteFirstEvidenceGateSection(\n \"the documented behavior\",\n \"if no truth doc changed, report why current truth was already sufficient or why documentation was blocked\",\n )}\n${subagentMode}${REPOSITORY_INTELLIGENCE_INSTRUCTIONS}\n${FEATURE_DOC_TEMPLATE_INSTRUCTIONS}\n${renderTruthDocRestructureGateSection(\n \"Truth Document may restructure only truth docs for the implemented behavior being documented.\",\n )}\n${ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS}\n${renderHierarchySummary(config)}\n${DECISION_TRUTH_INSTRUCTIONS}\nHelper status reporting:\n- Validate the report body before adding this validator's own success status; the body may omit \\`validate-document-report\\` while validation is pending.\n- After \\`truthmark validate document-report <report-file> --json\\` returns \\`data.validation.ok: true\\`, append or update \\`validate-document-report: ran, passed\\` in the final report.\n- If the installed Truthmark CLI is unavailable or the helper is skipped, record \\`validate-document-report: skipped, <reason>\\` and manually validate the report shape.\n- Record \\`validate-write-lease: ran, passed\\` only after validating a concrete write lease; otherwise use a truthful skipped status such as \\`skipped, no write lease used\\`.\n- Helper output is derived evidence and never replaces direct checkout inspection, evidence review, or parent acceptance.\nParent post-document verification:\n- verify only truth docs and leased truth routing files changed during document work\n- block on functional code, generated host surfaces, or unrelated diffs caused by document work\n- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it\n- verify the final report records ownership review, structure requirement, restructure, routing update, or blocked reason when applicable\n\nReport completion in this shape:\n${renderMarkdownExample(renderTruthDocumentReportExample(config))}`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n defaultAgentConfig,\n renderHierarchySummary,\n resolveTruthDocsRoot,\n} from \"./shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const TRUTH_PREVIEW_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview.\";\n\nexport const renderTruthPreviewReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n\n return `Truth Preview: completed\n\nRequested outcome:\n- preview likely Truthmark workflow routing before edits\n\nLikely workflow:\n- truthmark-document\n\nWhy this workflow:\n- positive trigger: document existing implemented behavior\n- negative triggers considered: functional-code change, doc-first implementation, topology repair, truth audit\n- forbidden adjacency considered: must not edit functional code\n\nLikely route owner:\n- route file: ${config.docs.routing.rootIndex}\n- truth doc: ${truthDocsRoot}/example.md\n- confidence: medium\n\nExpected write classes:\n- truth docs\n\nExpected target files:\n- ${truthDocsRoot}/example.md\n\nSuggested subagent use:\n- read-only verifiers: truth_route_auditor\n- write workers: none in Preview\n- leases needed: none in Preview\n\nBlocking ambiguity:\n- none identified in preview\n\nHandoff:\n- Run the selected Truthmark workflow after user approval.`;\n};\n\nexport const renderTruthPreviewSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-preview\");\n\n return `---\nname: truthmark-preview\ndescription: ${workflow.description}\nargument-hint: Optional requested outcome, code area, doc path, or routing question\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\nUse this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits.\n\nInvocations: ${TRUTH_PREVIEW_EXPLICIT_INVOCATIONS}\n\nTruth Preview is read-only. Its report is intended, not authorized.\n\nPurpose:\n- preview the likely Truthmark workflow, route owner, target files, expected write classes, suggested subagent use, and blocking ambiguity before edits happen\n- hand off to the selected workflow after user approval\n- keep the selector thin so agents can avoid loading or acting through heavier workflows prematurely\n\nRead:\n- .truthmark/config.yml\n- ${config.docs.routing.rootIndex}\n- relevant child route files under ${config.docs.routing.areaFilesRoot}/\n- relevant truth docs and implementation files needed to preview ownership\n- ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n\nDo not:\n- must not edit files\n- must not create truth docs\n- must not update routing\n- must not run Truth Sync automatically\n- must not replace Truth Check\n- must not claim final correctness\n- must not issue write leases\n- must not mutate code\n\nSuggested subagent use:\n- optional read-only verifier: truth_route_auditor\n- write workers: none\n- leases needed: none\n\n${renderHierarchySummary(config)}\n\nReport completion in this shape:\n${renderMarkdownExample(renderTruthPreviewReportExample(config))}`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS,\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n FEATURE_DOC_TEMPLATE_INSTRUCTIONS,\n TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderClaimEvidenceCheckedSection,\n renderCopilotCustomAgentModeSection,\n renderHierarchySummary,\n renderTopologyEvidenceGateSection,\n renderTruthDocOwnershipGateSection,\n renderTruthDocRestructureGateSection,\n resolveTruthDocsRoot,\n} from \"./shared.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-structure; Codex /truthmark-structure or $truthmark-structure; Claude Code /truthmark-structure; GitHub Copilot /truthmark-structure; Gemini CLI /truthmark:structure.\";\n\nexport const renderTruthStructureReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n\n return `Truth Structure: completed\nTopology reviewed:\n- controllers: src/auth/**\n- docs root: ${truthDocsRoot}\n- route files: ${config.docs.routing.rootIndex}\nAreas reviewed:\n- src/auth/**\nRouting updated:\n- ${config.docs.routing.rootIndex}\nInitial truth boundary:\n- Area: Authentication\n- Code: src/auth/**\n- Truth owner: ${truthDocsRoot}/authentication/session.md\n- Scope: session behavior only\nTruth docs created:\n- ${truthDocsRoot}/authentication/session.md\nTruth docs split:\n- ${truthDocsRoot}/authentication/README.md -> ${truthDocsRoot}/authentication/session.md\nTruth docs restructured:\n- ${truthDocsRoot}/authentication/README.md\n${renderClaimEvidenceCheckedSection([\n {\n claim: \"Session behavior belongs to a dedicated Authentication truth owner.\",\n evidence: [\"src/auth/**\", `${config.docs.routing.rootIndex}:7`],\n result: \"supported\",\n },\n ])}\nTopology decisions:\n- Added an Authentication area because session behavior has a distinct code surface and truth owner.\nNotes:\n- Added an Authentication area for session behavior.`;\n};\n\nexport const renderTruthStructureSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n } = {},\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n const claudeSubagentMode = options.includeClaudeSubagentMode\n ? `${renderClaudeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns all Truth Structure writes and final topology decisions\",\n )}\\n`\n : \"\";\n const copilotCustomAgentMode = options.includeCopilotCustomAgentMode\n ? `${renderCopilotCustomAgentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns all Truth Structure writes and final topology decisions\",\n )}\\n`\n : \"\";\n const subagentMode = `${claudeSubagentMode}${copilotCustomAgentMode}`;\n\n return `---\nname: truthmark-structure\ndescription: ${workflow.description}\nargument-hint: Optional area, directory, or routing concern\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\nUse this skill to design or repair Truthmark area structure.\nInvocations: ${TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS}\nTruth Structure is agent-native:\n- inspect repository layout, current docs, .truthmark/config.yml, ${config.docs.routing.rootIndex}, and relevant code directly\n- ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n- inspect the configured root route index at ${config.docs.routing.rootIndex} and relevant child route files under ${config.docs.routing.areaFilesRoot}/\n- define areas by product or behavior ownership, not by mechanical directory mirroring\n- create or repair ${config.docs.routing.rootIndex}\n- create starter truth docs when useful and when they belong in the canonical current-truth surface\n- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter.\n- Starter truth docs must include ## Product Decisions and ## Rationale sections.\n${subagentMode}\n${FEATURE_DOC_TEMPLATE_INSTRUCTIONS}\n- use ${truthDocsRoot}/**, docs/architecture/**, or docs/standards/** for current truth destinations\n- use only canonical current-truth destinations for starter truth docs\n- keep active Product Decisions and Rationale in the canonical doc that owns the behavior\n- preserve unrelated authored content\n## New area setup\nUse when a user asks to onboard a new code area into Truthmark, a new package, controller, domain, or product area lacks bounded truth ownership, or a new product area needs routing and starter truth docs.\nDo:\n- inspect the named code area\n- infer bounded product or behavior ownership\n- choose the owning route when ownership is clear; otherwise propose the route and block for review\n- create or update the child route entry or file\n- create starter truth docs only where current truth is missing\n- report the initial truth boundary\nDo not:\n- do not edit functional code\n- do not perform full behavior documentation unless evidence is inspected and the task explicitly asks for it\n- do not patch broad or mixed-owner docs in place\n- do not create generic catch-all docs\n- do not treat README files as Sync targets\n## Topology Governance\nTruth Structure owns documentation topology. Do not depend on humans to manually organize ${truthDocsRoot}. Treat the configured truth root as a managed semantic root.\nInspect controllers, routes, handlers, services, packages, tests, existing truth docs, and route files; infer product and domain ownership from behavior boundaries, not from mechanical directory mirroring.\nWhen topology pressure exists, repair structure before creating or extending truth docs.\n${renderTruthDocOwnershipGateSection(\n \"candidate route owners and current truth docs\",\n \"if a truth doc mixes independent owners, route ownership is broad, or a split is required for bounded ownership, split and reroute into bounded truth docs when safe; otherwise block with manual-review files\",\n)}\n${TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS}\nTopology pressure signals:\n- one area maps broad code such as src/**, app/**, server/**, services/**, or packages/**\n- one area maps multiple unrelated controllers, route groups, services, or bounded contexts\n- one truth doc owns unrelated behaviors or unrelated endpoint families\n- the configured truth root has many direct non-index docs\n- a changed controller, route, or service cannot map to a specific behavior doc\n- Truth Sync would need to create a new generic truth doc because routing is too broad\n- endpoint or controller names reveal domains missing from ${config.docs.routing.areaFilesRoot}/**\nUse these review thresholds as guidance:\n- more than 10 direct truth docs in one folder\n- more than 15 leaf areas in one child route file\n- more than 8 truth docs mapped to one area\n- more than 5 controllers mapped through one catch-all area\nRepair rules:\n- split broad, overloaded, or catch-all areas into behavior-owned child route files\n- split mixed-owner truth docs into bounded owner docs before adding new behavior claims\n- create route files under ${config.docs.routing.areaFilesRoot}/ when a product/domain boundary is clear\n- create behavior truth docs under the configured truth root only when behavior lacks a current doc\n- README.md files are indexes, not Truth Sync targets\n- prefer bounded leaf truth docs at <truth-root>/<domain>/<behavior>.md\n- keep behavior truth docs behavior-oriented, not endpoint-oriented\n- keep API endpoint details in the nearest contract truth doc when such a doc exists\n- update routing so future Truth Sync can target small docs\n- preserve existing authored docs; move or rewrite only when needed to remove ambiguity\n- report Truth docs split when one broad or mixed-owner truth doc becomes multiple bounded docs\n${renderTruthDocRestructureGateSection(\n \"Truth Structure may restructure broader routed docs when topology, ownership, or doc-shape repair is already in scope.\",\n)}\n${renderTopologyEvidenceGateSection()}\n${ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS}\n- Do not finish topology repair with routed canonical current-truth docs missing Product Decisions or Rationale sections.\n- If an existing canonical doc lacks either section, add the missing heading beside Current Behavior with a concise current-state placeholder or active decision.\nPortable fallback:\n- If this skill surface is unavailable, perform the same workflow directly from committed repository files.\n- Do not require the truthmark CLI.\n- Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, canonical docs, and representative implementation code.\n- Use a subagent only when the host supports that pattern; otherwise perform the topology repair inline.\n${renderHierarchySummary(config)}\n${DECISION_TRUTH_INSTRUCTIONS}\nReport completion in this shape:\n${renderMarkdownExample(renderTruthStructureReportExample(config))}`;\n};\n","import {\n renderClaimEvidenceCheckedSection,\n type ClaimEvidenceItem,\n type ClaimEvidenceResult,\n} from \"../truth/evidence.js\";\n\nimport type { TruthSyncSkipReason } from \"./policy.js\";\n\nexport type TruthSyncCompletedReportInput = {\n changedCode: string[];\n ownershipReviewed: string[];\n truthDocsUpdated: string[];\n evidenceChecked: ClaimEvidenceItem[];\n helperScripts?: string[];\n notes: string[];\n};\n\nexport type TruthSyncCompletedReport = TruthSyncCompletedReportInput & {\n status: \"completed\";\n};\n\nexport type TruthSyncSkippedReportInput = {\n reason: TruthSyncSkipReason;\n};\n\nexport type TruthSyncBlockedReportInput = {\n reason: string;\n manualReviewFiles: string[];\n nextAction: string;\n};\n\nconst renderBulletSection = (title: string, items: string[]): string => {\n return `${title}:\\n${items.map((item) => `- ${item}`).join(\"\\n\")}`;\n};\n\nconst findSection = (source: string, title: string): string | undefined => {\n return source\n .split(\"\\n\\n\")\n .find((candidate) => candidate.startsWith(`${title}:\\n`));\n};\n\nconst parseBulletLines = (section: string): string[] => {\n return section\n .split(\"\\n\")\n .slice(1)\n .map((line) => {\n const match = line.match(/^-\\s+(.*)$/);\n\n return match?.[1];\n })\n .filter((line): line is string => line !== undefined);\n};\n\nconst parseBulletSection = (source: string, title: string): string[] => {\n const section = findSection(source, title);\n\n if (!section) {\n return [];\n }\n\n return parseBulletLines(section);\n};\n\nconst parseOptionalBulletSection = (source: string, title: string): string[] | undefined => {\n const section = findSection(source, title);\n\n if (!section) {\n return undefined;\n }\n\n return parseBulletLines(section);\n};\n\nconst isClaimEvidenceResult = (value: string): value is ClaimEvidenceResult => {\n return [\"supported\", \"narrowed\", \"removed\", \"blocked\"].includes(value);\n};\n\nconst hasContent = (value: string): boolean => value.trim().length > 0;\n\nconst parseEvidenceCheckedSection = (source: string): ClaimEvidenceItem[] => {\n const section = source\n .split(\"\\n\\n\")\n .find((candidate) => candidate.startsWith(\"Evidence checked:\\n\"));\n\n if (!section) {\n throw new Error(\"Evidence checked section is required.\");\n }\n\n const lines = section.split(\"\\n\").slice(1);\n const items: ClaimEvidenceItem[] = [];\n\n for (let index = 0; index < lines.length; index += 3) {\n const claimLine = lines[index];\n const evidenceLine = lines[index + 1];\n const resultLine = lines[index + 2];\n\n if (\n !claimLine?.startsWith(\"- Claim: \") ||\n !evidenceLine?.startsWith(\" Evidence: \") ||\n !resultLine?.startsWith(\" Result: \")\n ) {\n throw new Error(\"Evidence checked entries must include Claim, Evidence, and Result fields.\");\n }\n\n const result = resultLine.slice(\" Result: \".length);\n const claim = claimLine.slice(\"- Claim: \".length).trim();\n const evidence = evidenceLine\n .slice(\" Evidence: \".length)\n .split(\" / \")\n .map((value) => value.trim());\n\n if (!hasContent(claim)) {\n throw new Error(\"Evidence checked claim is required.\");\n }\n\n if (evidence.length === 0 || evidence.some((value) => !hasContent(value))) {\n throw new Error(\"Evidence checked evidence is required.\");\n }\n\n if (!isClaimEvidenceResult(result)) {\n throw new Error(\"Evidence checked result is invalid.\");\n }\n\n items.push({\n claim,\n evidence,\n result,\n });\n }\n\n return items;\n};\n\nexport const renderTruthSyncCompletedReport = (\n input: TruthSyncCompletedReportInput,\n): string => {\n return [\n \"Truth Sync: completed\",\n renderBulletSection(\"Changed code reviewed\", input.changedCode),\n renderBulletSection(\"Ownership reviewed\", input.ownershipReviewed),\n renderBulletSection(\"Truth docs updated\", input.truthDocsUpdated),\n renderClaimEvidenceCheckedSection(input.evidenceChecked),\n ...(input.helperScripts === undefined\n ? []\n : [renderBulletSection(\"Helper scripts\", input.helperScripts)]),\n renderBulletSection(\"Notes\", input.notes),\n ].join(\"\\n\\n\");\n};\n\nexport const parseTruthSyncReport = (source: string): TruthSyncCompletedReport => {\n if (!source.startsWith(\"Truth Sync: completed\")) {\n throw new Error(\"Only completed Truth Sync reports can be parsed.\");\n }\n\n const helperScripts = parseOptionalBulletSection(source, \"Helper scripts\");\n\n return {\n status: \"completed\",\n changedCode: parseBulletSection(source, \"Changed code reviewed\"),\n ownershipReviewed: parseBulletSection(source, \"Ownership reviewed\"),\n truthDocsUpdated: parseBulletSection(source, \"Truth docs updated\"),\n evidenceChecked: parseEvidenceCheckedSection(source),\n ...(helperScripts === undefined ? {} : { helperScripts }),\n notes: parseBulletSection(source, \"Notes\"),\n };\n};\n\nexport const renderTruthSyncSkippedReport = (\n input: TruthSyncSkippedReportInput,\n): string => {\n return [\"Truth Sync: skipped\", renderBulletSection(\"Reason\", [input.reason])].join(\"\\n\\n\");\n};\n\nexport const renderTruthSyncBlockedReport = (\n input: TruthSyncBlockedReportInput,\n): string => {\n const manualReviewFiles = input.manualReviewFiles.filter((file) => file.trim().length > 0);\n\n if (manualReviewFiles.length === 0) {\n throw new Error(\"Files requiring manual review must include at least one file.\");\n }\n\n const sections = [\n \"Truth Sync: blocked\",\n renderBulletSection(\"Reason\", [input.reason]),\n renderBulletSection(\"Files requiring manual review\", manualReviewFiles),\n renderBulletSection(\"Next action\", [input.nextAction]),\n ];\n\n return [\n ...sections,\n ].join(\"\\n\\n\");\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS,\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n FEATURE_DOC_TEMPLATE_INSTRUCTIONS,\n REPOSITORY_INTELLIGENCE_INSTRUCTIONS,\n TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n renderRouteFirstEvidenceGateSection,\n renderHierarchySummary,\n renderTruthDocOwnershipGateSection,\n renderTruthDocRestructureGateSection,\n resolveTruthDocsRoot,\n} from \"./shared.js\";\nimport {\n renderTruthSyncBlockedReport,\n renderTruthSyncCompletedReport,\n} from \"../sync/report.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nexport const TRUTH_SYNC_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-sync; Codex /truthmark-sync or $truthmark-sync; Claude Code /truthmark-sync; GitHub Copilot /truthmark-sync; Gemini CLI /truthmark:sync.\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nexport const renderTruthSyncWorkerPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return `### Truth Sync Worker\nThe parent provides the task focus, explicit write lease, and any repository context already gathered.\nWorker rules:\n- require a write lease with workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields before editing\n- inspect relevant staged, unstaged, and untracked functional code directly\n- read .truthmark/config.yml, ${config.docs.routing.rootIndex}, and canonical truth docs directly\n- Code verification is parent-owned; report what was run or why it was not run\n- may write only leased truth docs and leased truth routing files for Truth Sync alignment\n- must not rewrite functional code or generated host surfaces\n- stop and report blocked when the required edit needs an off-lease file\nReturn result in this shape:\n- status: completed | blocked\n- worker: string\n- shard: string\n- filesChanged: string[]\n- changedCodeReviewed: string[]\n- ownershipReviewed: string[]\n- structureRequired?: string[]\n- truthDocsUpdated: string[]\n- routingDocsUpdated: string[]\n- truthDocsSplit?: string[]\n- evidenceChecked: { claim: string; evidence: string[]; result: supported | narrowed | removed | blocked }[]\n- offLeaseChanges: string[]\n- notes: string[]\n- blockedReason?: string\n- manualReviewFiles: string[] required when status is blocked; at least one file`;\n};\n\nexport const renderTruthSyncSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCodexSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n includeOpenCodeSubagentMode?: boolean;\n } = {},\n): string => {\n const truthDocsRoot = resolveTruthDocsRoot(config);\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n const helperScripts = [\"validate-write-lease: skipped, no write lease used\"];\n const claudeSubagentMode = options.includeClaudeSubagentMode\n ? `${renderClaudeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const codexSubagentMode = options.includeCodexSubagentMode\n ? `${renderCodexSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const copilotCustomAgentMode = options.includeCopilotCustomAgentMode\n ? `${renderCopilotCustomAgentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const openCodeSubagentMode = options.includeOpenCodeSubagentMode\n ? `${renderOpenCodeSubagentModeSection(\n workflow.subagents ?? [],\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n workflow.writeSubagents ?? [],\n )}\\n`\n : \"\";\n const subagentMode = `${claudeSubagentMode}${codexSubagentMode}${copilotCustomAgentMode}${openCodeSubagentMode}`;\n\n return `---\nname: truthmark-sync\ndescription: ${workflow.description}\nargument-hint: Optional changed-code area, truth-doc area, or sync focus\nuser-invocable: true\ntruthmark-version: ${TRUTHMARK_VERSION}\n---\n\nUse this skill automatically before finishing when functional code changed since the last successful Truth Sync. Also run it immediately when the user explicitly invokes Truth Sync.\nInvocations: ${TRUTH_SYNC_EXPLICIT_INVOCATIONS}\nExplicit invocation runs immediately. Later functional-code changes reopen the finish-time requirement, and an earlier explicit run satisfies the finish gate only if no later functional-code changes occur.\nSkip when changes are documentation-only, formatting-only, clearly behavior-preserving renames with no truth impact, when no Truthmark config exists yet, or when there are no functional code changes.\nParent workflow:\n1. Inspect git status, staged changes, unstaged changes, and untracked files directly.\n2. Read .truthmark/config.yml, the configured root route index at ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, and relevant canonical docs.\n3. Identify functional-code changes and the nearest truth docs or routing repairs.\n4. ${EVIDENCE_AUTHORITY_INSTRUCTIONS}\n5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run.\n6. Dispatch bounded Truth Sync workers only when the host supports subagent dispatch and the acting agent chooses that path; otherwise execute the same sync task inline.\n${subagentMode}Topology quality gate:\n- before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner\n- if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc\n- run Truth Structure before syncing when topology repair is safe and in scope\n- block and recommend Truth Structure when topology repair is unsafe, ambiguous, or outside the current task boundary\n- report the route files and changed code paths that require structure repair\n- README.md files are indexes, not Truth Sync targets\n- must not append behavior details to a README.md index\n- create or update a bounded leaf truth doc when behavior changes do not fit an existing leaf doc\n${renderTruthDocOwnershipGateSection(\n \"changed functional files and impacted truth docs\",\n \"if an impacted doc is broad, mixed-owner, index-like, or the update spans independent behavior owners, run Truth Structure before syncing when safe and in scope; otherwise block and recommend Truth Structure\",\n )}\n${TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS}\n${FEATURE_DOC_TEMPLATE_INSTRUCTIONS}\n${renderTruthDocRestructureGateSection(\n \"Truth Sync may restructure only truth docs impacted by the current functional-code change.\",\n )}\n${ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS}\n${renderRouteFirstEvidenceGateSection(\n \"changed functional files\",\n \"if no impacted doc changed, report why truth was already current or why sync was skipped\",\n )}\n${REPOSITORY_INTELLIGENCE_INSTRUCTIONS}\nOptional validation tooling:\n- you may run truthmark check when local tooling is available\n- do not require the truthmark binary; direct checkout inspection is the canonical path\n- optional validation must not replace agent judgment about docs and routing\n- update Product Decisions and Rationale when a behavior change comes from a decision change\nHelper status reporting:\n- Validate the report body before adding this validator's own success status; the body may omit \\`validate-sync-report\\` while validation is pending.\n- After \\`truthmark validate sync-report <report-file> --json\\` returns \\`data.validation.ok: true\\`, append or update \\`validate-sync-report: ran, passed\\` in the final report.\n- If the installed Truthmark CLI is unavailable or the helper is skipped, record \\`validate-sync-report: skipped, <reason>\\` and manually validate the report shape.\n- Record \\`validate-write-lease: ran, passed\\` only after validating a concrete write lease; otherwise use a truthful skipped status such as \\`skipped, no write lease used\\`.\n- Helper output is derived evidence and never replaces direct checkout inspection, evidence review, or parent acceptance.\n${renderHierarchySummary(config)}\n${DECISION_TRUTH_INSTRUCTIONS}\nParent post-sync verification:\n- verify only truth docs and leased truth routing files changed during sync\n- block on any unrelated diff caused by the sync step\n- block if functional code changed during sync\n- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it\n- validate the final report against the structured Truth Sync report contract, including Claim, indented Evidence, and Result values supported, narrowed, removed, or blocked under Evidence checked\n- verify the updated docs correspond to the reviewed changed-code surface\n- verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired\n- blocked outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files\nReport completion in this shape:\n${renderMarkdownExample(\n renderTruthSyncCompletedReport({\n changedCode: [\"src/auth/session.ts\"],\n ownershipReviewed: [config.docs.routing.rootIndex],\n truthDocsUpdated: [`${truthDocsRoot}/repository/overview.md`],\n evidenceChecked: [\n {\n claim: \"Session timeout behavior is documented in the mapped repository truth doc.\",\n evidence: [\"src/auth/session.ts:12\", `${config.docs.routing.rootIndex}:11`],\n result: \"supported\",\n },\n ],\n helperScripts,\n notes: [\"Updated session timeout behavior.\"],\n }),\n )}\nBlocked report example:\n${renderMarkdownExample(\n renderTruthSyncBlockedReport({\n reason: \"routing repair is not allowed\",\n manualReviewFiles: [config.docs.routing.rootIndex],\n nextAction: \"update routing metadata and rerun Truth Sync\",\n }),\n )}`;\n};\n","import micromatch from \"micromatch\";\nimport { parse as parseYaml } from \"yaml\";\n\nimport type {\n TruthmarkWorkflowId,\n TruthmarkWriteSubagentId,\n} from \"./workflow-manifest.js\";\n\nexport const TRUTHMARK_WRITE_WORKER_REPORT_FIELDS = [\n \"status\",\n \"worker\",\n \"workflow\",\n \"shard\",\n \"filesChanged\",\n \"claimsChecked\",\n \"evidenceChecked\",\n \"offLeaseChanges\",\n \"blockers\",\n \"notes\",\n] as const;\n\nexport type TruthmarkWriteWorkerReportField =\n (typeof TRUTHMARK_WRITE_WORKER_REPORT_FIELDS)[number];\n\nexport type TruthmarkWriteLease = {\n workflow: TruthmarkWorkflowId;\n worker: TruthmarkWriteSubagentId;\n shard: string;\n objective: string;\n requiredReads: string[];\n allowedReads?: string[];\n allowedWrites: string[];\n forbiddenWrites: string[];\n evidenceRequired: string[];\n verification?: string[];\n reportFields: string[];\n};\n\nexport type TruthmarkWriteLeaseChangeValidation = {\n allowedChanges: string[];\n forbiddenChanges: string[];\n offLeaseChanges: string[];\n};\n\nexport type TruthmarkWriteWorkerReport = Record<string, unknown>;\n\nexport type TruthmarkWriteWorkerAcceptanceReasonCode =\n | \"missing-report-field\"\n | \"invalid-report-field\"\n | \"invalid-report-status\"\n | \"identity-mismatch\"\n | \"forbidden-actual-diff\"\n | \"off-lease-actual-diff\"\n | \"reported-files-mismatch\"\n | \"completed-with-reported-off-lease-changes\"\n | \"completed-with-blockers\"\n | \"blocked-without-blockers\";\n\nexport type TruthmarkWriteWorkerAcceptanceReason = {\n code: TruthmarkWriteWorkerAcceptanceReasonCode;\n message: string;\n field?: string;\n files?: string[];\n expected?: string;\n actual?: string;\n};\n\nexport type TruthmarkWriteWorkerAcceptanceValidation = {\n status: \"accepted\" | \"blocked\" | \"rejected\";\n reasons: TruthmarkWriteWorkerAcceptanceReason[];\n changeValidation: TruthmarkWriteLeaseChangeValidation;\n actualChangedFiles: string[];\n reportedFilesChanged: string[];\n};\n\nconst normalizePath = (filePath: string): string => {\n return filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/u, \"\");\n};\n\nconst matchesAny = (filePath: string, patterns: string[]): boolean => {\n if (patterns.length === 0) {\n return false;\n }\n\n return micromatch.isMatch(normalizePath(filePath), patterns);\n};\n\nconst uniqueSorted = (values: string[]): string[] => {\n return Array.from(new Set(values)).sort((left, right) => left.localeCompare(right));\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n};\n\nconst hasOwn = (record: Record<string, unknown>, key: string): boolean => {\n return Object.prototype.hasOwnProperty.call(record, key);\n};\n\nconst readStringArrayField = (\n report: TruthmarkWriteWorkerReport,\n field: string,\n): string[] | undefined => {\n const value = report[field];\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\")) {\n return undefined;\n }\n return uniqueSorted(value.map(normalizePath));\n};\n\nconst equalStringArrays = (left: string[], right: string[]): boolean => {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n};\n\nexport const parseTruthmarkWriteWorkerReport = (\n source: string,\n): TruthmarkWriteWorkerReport => {\n const parsed = parseYaml(source);\n if (!isRecord(parsed)) {\n throw new Error(\"Truthmark write worker report must be a YAML object.\");\n }\n return parsed;\n};\n\nexport const validateTruthmarkWriteLeaseChanges = (\n lease: TruthmarkWriteLease,\n changedFiles: string[],\n): TruthmarkWriteLeaseChangeValidation => {\n const normalizedFiles = uniqueSorted(changedFiles.map(normalizePath));\n const forbiddenChanges = normalizedFiles.filter((filePath) =>\n matchesAny(filePath, lease.forbiddenWrites),\n );\n const outsideAllowedWrites = normalizedFiles.filter(\n (filePath) => !matchesAny(filePath, lease.allowedWrites),\n );\n const offLeaseChanges = uniqueSorted([\n ...forbiddenChanges,\n ...outsideAllowedWrites,\n ]);\n\n return {\n allowedChanges: normalizedFiles.filter(\n (filePath) => !offLeaseChanges.includes(filePath),\n ),\n forbiddenChanges,\n offLeaseChanges,\n };\n};\n\nexport const validateTruthmarkWriteWorkerAcceptance = ({\n lease,\n workerReport,\n actualChangedFiles,\n}: {\n lease: TruthmarkWriteLease;\n workerReport: TruthmarkWriteWorkerReport;\n actualChangedFiles: string[];\n}): TruthmarkWriteWorkerAcceptanceValidation => {\n const reasons: TruthmarkWriteWorkerAcceptanceReason[] = [];\n const normalizedActualChangedFiles = uniqueSorted(actualChangedFiles.map(normalizePath));\n const requiredReportFields = uniqueSorted([\n ...lease.reportFields,\n ...(lease.worker === \"truth_doc_writer\" ? TRUTHMARK_WRITE_WORKER_REPORT_FIELDS : []),\n ]);\n\n for (const field of requiredReportFields) {\n if (!hasOwn(workerReport, field)) {\n reasons.push({\n code: \"missing-report-field\",\n field,\n message: `Worker report is missing required field ${field}.`,\n });\n }\n }\n\n const reportStatus = workerReport.status;\n if (\n hasOwn(workerReport, \"status\") &&\n reportStatus !== \"completed\" &&\n reportStatus !== \"blocked\"\n ) {\n reasons.push({\n code: \"invalid-report-status\",\n field: \"status\",\n message: \"Worker report status must be completed or blocked.\",\n });\n }\n\n for (const field of [\"worker\", \"workflow\", \"shard\"] as const) {\n const actual = workerReport[field];\n const expected = lease[field];\n if (hasOwn(workerReport, field) && typeof actual !== \"string\") {\n reasons.push({\n code: \"invalid-report-field\",\n field,\n message: `Worker report field ${field} must be a string.`,\n });\n } else if (typeof actual === \"string\" && actual !== expected) {\n reasons.push({\n code: \"identity-mismatch\",\n field,\n expected,\n actual,\n message: `Worker report ${field} does not match the lease.`,\n });\n }\n }\n\n for (const field of [\n \"filesChanged\",\n \"claimsChecked\",\n \"evidenceChecked\",\n \"offLeaseChanges\",\n \"blockers\",\n \"notes\",\n ]) {\n if (hasOwn(workerReport, field) && readStringArrayField(workerReport, field) === undefined) {\n reasons.push({\n code: \"invalid-report-field\",\n field,\n message: `Worker report field ${field} must be a string array.`,\n });\n }\n }\n\n const reportedFilesChanged = readStringArrayField(workerReport, \"filesChanged\") ?? [];\n const reportedOffLeaseChanges = readStringArrayField(workerReport, \"offLeaseChanges\") ?? [];\n const reportedBlockers = readStringArrayField(workerReport, \"blockers\") ?? [];\n const changeValidation = validateTruthmarkWriteLeaseChanges(\n lease,\n normalizedActualChangedFiles,\n );\n\n if (changeValidation.forbiddenChanges.length > 0) {\n reasons.push({\n code: \"forbidden-actual-diff\",\n files: changeValidation.forbiddenChanges,\n message: \"Actual worker diff includes forbidden lease paths.\",\n });\n }\n\n if (changeValidation.offLeaseChanges.length > 0) {\n reasons.push({\n code: \"off-lease-actual-diff\",\n files: changeValidation.offLeaseChanges,\n message: \"Actual worker diff includes paths outside allowedWrites.\",\n });\n }\n\n if (!equalStringArrays(reportedFilesChanged, normalizedActualChangedFiles)) {\n reasons.push({\n code: \"reported-files-mismatch\",\n files: reportedFilesChanged,\n message: \"Worker report filesChanged does not match the actual worker diff.\",\n });\n }\n\n if (reportStatus === \"completed\" && reportedOffLeaseChanges.length > 0) {\n reasons.push({\n code: \"completed-with-reported-off-lease-changes\",\n files: reportedOffLeaseChanges,\n message: \"Completed worker reports must not include offLeaseChanges.\",\n });\n }\n\n if (reportStatus === \"completed\" && reportedBlockers.length > 0) {\n reasons.push({\n code: \"completed-with-blockers\",\n message: \"Completed worker reports must not include blockers.\",\n });\n }\n\n if (reportStatus === \"blocked\" && reportedBlockers.length === 0) {\n reasons.push({\n code: \"blocked-without-blockers\",\n message: \"Blocked worker reports must include at least one blocker.\",\n });\n }\n\n if (reasons.length === 0 && reportStatus === \"completed\") {\n return {\n status: \"accepted\",\n reasons,\n changeValidation,\n actualChangedFiles: normalizedActualChangedFiles,\n reportedFilesChanged,\n };\n }\n\n if (reasons.length === 0 && reportStatus === \"blocked\") {\n return {\n status: \"blocked\",\n reasons,\n changeValidation,\n actualChangedFiles: normalizedActualChangedFiles,\n reportedFilesChanged,\n };\n }\n\n return {\n status: \"rejected\",\n reasons,\n changeValidation,\n actualChangedFiles: normalizedActualChangedFiles,\n reportedFilesChanged,\n };\n};\n","import type { TruthmarkConfig, TruthmarkPlatform } from \"../config/schema.js\";\nimport { renderAgentsBlock } from \"./agents-block.js\";\nimport {\n renderTruthmarkCopilotCheckPrompt,\n renderTruthmarkCopilotClaimVerifierAgent,\n renderTruthmarkCopilotDocumentPrompt,\n renderTruthmarkCopilotDocReviewerAgent,\n renderTruthmarkCopilotDocWriterAgent,\n renderTruthmarkCopilotPreviewPrompt,\n renderTruthmarkCopilotRealizePrompt,\n renderTruthmarkCopilotRouteAuditorAgent,\n renderTruthmarkCopilotStructurePrompt,\n renderTruthmarkCopilotSyncPrompt,\n renderTruthmarkClaudeClaimVerifierAgent,\n renderTruthmarkClaudeDocReviewerAgent,\n renderTruthmarkClaudeDocWriterAgent,\n renderTruthmarkClaudeRouteAuditorAgent,\n renderTruthmarkClaimVerifierAgent,\n renderTruthmarkDocumentSkillMetadata,\n renderTruthmarkDocReviewerAgent,\n renderTruthmarkDocWriterAgent,\n renderTruthmarkGeminiCheckCommand,\n renderTruthmarkGeminiClaimVerifierAgent,\n renderTruthmarkGeminiDocumentCommand,\n renderTruthmarkGeminiDocReviewerAgent,\n renderTruthmarkGeminiDocWriterAgent,\n renderTruthmarkGeminiPreviewCommand,\n renderTruthmarkGeminiRealizeCommand,\n renderTruthmarkGeminiRouteAuditorAgent,\n renderTruthmarkGeminiStructureCommand,\n renderTruthmarkGeminiSyncCommand,\n renderTruthmarkCheckSkillMetadata,\n renderTruthmarkOpenCodeClaimVerifierAgent,\n renderTruthmarkOpenCodeDocReviewerAgent,\n renderTruthmarkOpenCodeDocWriterAgent,\n renderTruthmarkOpenCodeRouteAuditorAgent,\n renderTruthmarkPreviewSkillMetadata,\n renderTruthmarkRealizeSkillMetadata,\n renderTruthmarkRouteAuditorAgent,\n renderTruthmarkSkillPackage,\n renderTruthmarkStructureSkillMetadata,\n renderTruthmarkSyncSkillMetadata,\n TRUTHMARK_CHECK_SKILL_METADATA_PATH,\n TRUTHMARK_CHECK_SKILL_PATH,\n TRUTHMARK_CLAUDE_CLAIM_VERIFIER_AGENT_PATH,\n TRUTHMARK_CLAUDE_DOC_REVIEWER_AGENT_PATH,\n TRUTHMARK_CLAUDE_DOC_WRITER_AGENT_PATH,\n TRUTHMARK_CLAUDE_ROUTE_AUDITOR_AGENT_PATH,\n TRUTHMARK_CLAIM_VERIFIER_AGENT_PATH,\n TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH,\n TRUTHMARK_COPILOT_CHECK_PROMPT_PATH,\n TRUTHMARK_COPILOT_DOCUMENT_PROMPT_PATH,\n TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH,\n TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH,\n TRUTHMARK_COPILOT_PREVIEW_PROMPT_PATH,\n TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH,\n TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH,\n TRUTHMARK_COPILOT_STRUCTURE_PROMPT_PATH,\n TRUTHMARK_COPILOT_SYNC_PROMPT_PATH,\n TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH,\n TRUTHMARK_DOCUMENT_SKILL_PATH,\n TRUTHMARK_DOC_REVIEWER_AGENT_PATH,\n TRUTHMARK_DOC_WRITER_AGENT_PATH,\n TRUTHMARK_GEMINI_CLAIM_VERIFIER_AGENT_PATH,\n TRUTHMARK_GEMINI_DOC_REVIEWER_AGENT_PATH,\n TRUTHMARK_GEMINI_DOC_WRITER_AGENT_PATH,\n TRUTHMARK_GEMINI_CHECK_COMMAND_PATH,\n TRUTHMARK_GEMINI_DOCUMENT_COMMAND_PATH,\n TRUTHMARK_GEMINI_PREVIEW_COMMAND_PATH,\n TRUTHMARK_GEMINI_REALIZE_COMMAND_PATH,\n TRUTHMARK_GEMINI_ROUTE_AUDITOR_AGENT_PATH,\n TRUTHMARK_GEMINI_STRUCTURE_COMMAND_PATH,\n TRUTHMARK_GEMINI_SYNC_COMMAND_PATH,\n TRUTHMARK_OPENCODE_CLAIM_VERIFIER_AGENT_PATH,\n TRUTHMARK_OPENCODE_DOC_REVIEWER_AGENT_PATH,\n TRUTHMARK_OPENCODE_DOC_WRITER_AGENT_PATH,\n TRUTHMARK_OPENCODE_ROUTE_AUDITOR_AGENT_PATH,\n TRUTHMARK_PREVIEW_SKILL_METADATA_PATH,\n TRUTHMARK_PREVIEW_SKILL_PATH,\n TRUTHMARK_REALIZE_SKILL_METADATA_PATH,\n TRUTHMARK_REALIZE_SKILL_PATH,\n TRUTHMARK_ROUTE_AUDITOR_AGENT_PATH,\n TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH,\n TRUTHMARK_STRUCTURE_SKILL_PATH,\n TRUTHMARK_SYNC_SKILL_METADATA_PATH,\n TRUTHMARK_SYNC_SKILL_PATH,\n} from \"./workflow-surfaces.js\";\n\nexport type GeneratedSurface = {\n path: string;\n content: string;\n managedBlock?: boolean;\n};\n\nconst codexFiles = (config: TruthmarkConfig): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_STRUCTURE_SKILL_PATH,\n workflowId: \"truthmark-structure\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH,\n content: renderTruthmarkStructureSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_DOCUMENT_SKILL_PATH,\n workflowId: \"truthmark-document\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH,\n content: renderTruthmarkDocumentSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_SYNC_SKILL_PATH,\n workflowId: \"truthmark-sync\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_SYNC_SKILL_METADATA_PATH,\n content: renderTruthmarkSyncSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_PREVIEW_SKILL_PATH,\n workflowId: \"truthmark-preview\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_PREVIEW_SKILL_METADATA_PATH,\n content: renderTruthmarkPreviewSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CHECK_SKILL_PATH,\n workflowId: \"truthmark-check\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_CHECK_SKILL_METADATA_PATH,\n content: renderTruthmarkCheckSkillMetadata(),\n },\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_REALIZE_SKILL_PATH,\n workflowId: \"truthmark-realize\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_REALIZE_SKILL_METADATA_PATH,\n content: renderTruthmarkRealizeSkillMetadata(),\n },\n {\n path: TRUTHMARK_ROUTE_AUDITOR_AGENT_PATH,\n content: renderTruthmarkRouteAuditorAgent(),\n },\n {\n path: TRUTHMARK_CLAIM_VERIFIER_AGENT_PATH,\n content: renderTruthmarkClaimVerifierAgent(),\n },\n {\n path: TRUTHMARK_DOC_REVIEWER_AGENT_PATH,\n content: renderTruthmarkDocReviewerAgent(),\n },\n {\n path: TRUTHMARK_DOC_WRITER_AGENT_PATH,\n content: renderTruthmarkDocWriterAgent(),\n },\n ];\n\n return files;\n};\n\nconst opencodeFiles = (config: TruthmarkConfig): GeneratedSurface[] => {\n return [\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-structure/SKILL.md\",\n workflowId: \"truthmark-structure\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-document/SKILL.md\",\n workflowId: \"truthmark-document\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-sync/SKILL.md\",\n workflowId: \"truthmark-sync\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-preview/SKILL.md\",\n workflowId: \"truthmark-preview\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-check/SKILL.md\",\n workflowId: \"truthmark-check\",\n host: \"opencode\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-realize/SKILL.md\",\n workflowId: \"truthmark-realize\",\n host: \"opencode\",\n config,\n }),\n {\n path: TRUTHMARK_OPENCODE_ROUTE_AUDITOR_AGENT_PATH,\n content: renderTruthmarkOpenCodeRouteAuditorAgent(),\n },\n {\n path: TRUTHMARK_OPENCODE_CLAIM_VERIFIER_AGENT_PATH,\n content: renderTruthmarkOpenCodeClaimVerifierAgent(),\n },\n {\n path: TRUTHMARK_OPENCODE_DOC_REVIEWER_AGENT_PATH,\n content: renderTruthmarkOpenCodeDocReviewerAgent(),\n },\n {\n path: TRUTHMARK_OPENCODE_DOC_WRITER_AGENT_PATH,\n content: renderTruthmarkOpenCodeDocWriterAgent(config),\n },\n ];\n};\n\nconst claudeFiles = (\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n return [\n ...instructionBlockFiles([\"CLAUDE.md\"], block),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-structure/SKILL.md\",\n workflowId: \"truthmark-structure\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-document/SKILL.md\",\n workflowId: \"truthmark-document\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-sync/SKILL.md\",\n workflowId: \"truthmark-sync\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-preview/SKILL.md\",\n workflowId: \"truthmark-preview\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-check/SKILL.md\",\n workflowId: \"truthmark-check\",\n host: \"claude-code\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-realize/SKILL.md\",\n workflowId: \"truthmark-realize\",\n host: \"claude-code\",\n config,\n }),\n {\n path: TRUTHMARK_CLAUDE_ROUTE_AUDITOR_AGENT_PATH,\n content: renderTruthmarkClaudeRouteAuditorAgent(),\n },\n {\n path: TRUTHMARK_CLAUDE_CLAIM_VERIFIER_AGENT_PATH,\n content: renderTruthmarkClaudeClaimVerifierAgent(),\n },\n {\n path: TRUTHMARK_CLAUDE_DOC_REVIEWER_AGENT_PATH,\n content: renderTruthmarkClaudeDocReviewerAgent(),\n },\n {\n path: TRUTHMARK_CLAUDE_DOC_WRITER_AGENT_PATH,\n content: renderTruthmarkClaudeDocWriterAgent(),\n },\n ];\n};\n\nconst copilotFiles = (\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n ...instructionBlockFiles([\".github/copilot-instructions.md\"], block),\n ...renderTruthmarkSkillPackage({\n skillPath: \".github/skills/truthmark-structure/SKILL.md\",\n workflowId: \"truthmark-structure\",\n host: \"github-copilot\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".github/skills/truthmark-document/SKILL.md\",\n workflowId: \"truthmark-document\",\n host: \"github-copilot\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".github/skills/truthmark-sync/SKILL.md\",\n workflowId: \"truthmark-sync\",\n host: \"github-copilot\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".github/skills/truthmark-preview/SKILL.md\",\n workflowId: \"truthmark-preview\",\n host: \"github-copilot\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".github/skills/truthmark-check/SKILL.md\",\n workflowId: \"truthmark-check\",\n host: \"github-copilot\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".github/skills/truthmark-realize/SKILL.md\",\n workflowId: \"truthmark-realize\",\n host: \"github-copilot\",\n config,\n }),\n {\n path: TRUTHMARK_COPILOT_STRUCTURE_PROMPT_PATH,\n content: renderTruthmarkCopilotStructurePrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_DOCUMENT_PROMPT_PATH,\n content: renderTruthmarkCopilotDocumentPrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_SYNC_PROMPT_PATH,\n content: renderTruthmarkCopilotSyncPrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_PREVIEW_PROMPT_PATH,\n content: renderTruthmarkCopilotPreviewPrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_CHECK_PROMPT_PATH,\n content: renderTruthmarkCopilotCheckPrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH,\n content: renderTruthmarkCopilotRealizePrompt(config),\n },\n {\n path: TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH,\n content: renderTruthmarkCopilotRouteAuditorAgent(),\n },\n {\n path: TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH,\n content: renderTruthmarkCopilotClaimVerifierAgent(),\n },\n {\n path: TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH,\n content: renderTruthmarkCopilotDocReviewerAgent(),\n },\n {\n path: TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH,\n content: renderTruthmarkCopilotDocWriterAgent(),\n },\n ];\n\n return files;\n};\n\nconst geminiFiles = (\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n return [\n ...instructionBlockFiles([\"GEMINI.md\"], block),\n ...renderTruthmarkSkillPackage({\n skillPath: \".gemini/skills/truthmark-structure/SKILL.md\",\n workflowId: \"truthmark-structure\",\n host: \"gemini-cli\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".gemini/skills/truthmark-document/SKILL.md\",\n workflowId: \"truthmark-document\",\n host: \"gemini-cli\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".gemini/skills/truthmark-sync/SKILL.md\",\n workflowId: \"truthmark-sync\",\n host: \"gemini-cli\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".gemini/skills/truthmark-preview/SKILL.md\",\n workflowId: \"truthmark-preview\",\n host: \"gemini-cli\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".gemini/skills/truthmark-check/SKILL.md\",\n workflowId: \"truthmark-check\",\n host: \"gemini-cli\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: \".gemini/skills/truthmark-realize/SKILL.md\",\n workflowId: \"truthmark-realize\",\n host: \"gemini-cli\",\n config,\n }),\n {\n path: TRUTHMARK_GEMINI_STRUCTURE_COMMAND_PATH,\n content: renderTruthmarkGeminiStructureCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_DOCUMENT_COMMAND_PATH,\n content: renderTruthmarkGeminiDocumentCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_SYNC_COMMAND_PATH,\n content: renderTruthmarkGeminiSyncCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_PREVIEW_COMMAND_PATH,\n content: renderTruthmarkGeminiPreviewCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_CHECK_COMMAND_PATH,\n content: renderTruthmarkGeminiCheckCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_REALIZE_COMMAND_PATH,\n content: renderTruthmarkGeminiRealizeCommand(config),\n },\n {\n path: TRUTHMARK_GEMINI_ROUTE_AUDITOR_AGENT_PATH,\n content: renderTruthmarkGeminiRouteAuditorAgent(),\n },\n {\n path: TRUTHMARK_GEMINI_CLAIM_VERIFIER_AGENT_PATH,\n content: renderTruthmarkGeminiClaimVerifierAgent(),\n },\n {\n path: TRUTHMARK_GEMINI_DOC_REVIEWER_AGENT_PATH,\n content: renderTruthmarkGeminiDocReviewerAgent(),\n },\n {\n path: TRUTHMARK_GEMINI_DOC_WRITER_AGENT_PATH,\n content: renderTruthmarkGeminiDocWriterAgent(),\n },\n ];\n};\n\nconst instructionBlockFiles = (\n paths: string[],\n block: string,\n): GeneratedSurface[] => {\n return paths.map((path) => ({\n path,\n content: block,\n managedBlock: true,\n }));\n};\n\nconst filesForPlatform = (\n platform: TruthmarkPlatform,\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n switch (platform) {\n case \"codex\":\n return codexFiles(config);\n case \"opencode\":\n return opencodeFiles(config);\n case \"claude-code\":\n return claudeFiles(config, block);\n case \"github-copilot\":\n return copilotFiles(config, block);\n case \"gemini-cli\":\n return geminiFiles(config, block);\n }\n};\n\nexport const renderGeneratedSurfaces = (\n config: TruthmarkConfig,\n block = renderAgentsBlock(config),\n): GeneratedSurface[] => {\n const files = [\n ...instructionBlockFiles(config.instructionTargets, block),\n ...config.platforms.flatMap((platform) =>\n filesForPlatform(platform, config, block),\n ),\n ];\n\n return Array.from(\n new Map(files.map((file) => [file.path, file])).values(),\n ).sort((left, right) => left.path.localeCompare(right.path));\n};\n","import fs from \"node:fs/promises\";\n\nimport fg from \"fast-glob\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport { DEFAULT_DOCS_HIERARCHY } from \"../config/defaults.js\";\nimport { resolveWorktreePath, getGitRepository } from \"../git/repository.js\";\nimport { hashText } from \"../markdown/hash.js\";\n\nexport type BranchScopeData = {\n repositoryRoot: string;\n worktreePath: string;\n branchName: string | null;\n headSha: string | null;\n identity: string;\n relevantFileHashes: Record<string, string>;\n};\n\nexport class BranchScopeFileError extends Error {\n file: string;\n\n constructor(file: string, message: string) {\n super(message);\n this.name = \"BranchScopeFileError\";\n this.file = file;\n }\n}\n\nconst RELEVANT_BRANCH_SCOPE_FILES = [\".truthmark/config.yml\"] as const;\n\nconst toBranchIdentity = (branchName: string | null, headSha: string | null): string => {\n if (branchName && headSha) {\n return `${branchName}@${headSha}`;\n }\n\n if (branchName) {\n return `unborn:${branchName}`;\n }\n\n return headSha ? `detached:${headSha}` : \"detached:unknown\";\n};\n\nexport const createBranchScopeData = (\n repository: {\n repositoryRoot: string;\n worktreePath: string;\n branchName: string | null;\n headSha: string | null;\n },\n relevantFileHashes: Record<string, string> = {},\n): BranchScopeData => {\n return {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n headSha: repository.headSha,\n identity: toBranchIdentity(repository.branchName, repository.headSha),\n relevantFileHashes,\n };\n};\n\nexport const getBranchScopeData = async (cwd: string): Promise<BranchScopeData> => {\n const repository = await getGitRepository(cwd);\n const relevantFileHashes: Record<string, string> = {};\n const loadResult = await loadConfig(repository.worktreePath);\n const rootIndex =\n loadResult.config?.docs.routing.rootIndex ?? DEFAULT_DOCS_HIERARCHY.routing.root_index;\n const areaFilesRoot =\n loadResult.config?.docs.routing.areaFilesRoot ?? DEFAULT_DOCS_HIERARCHY.routing.area_files_root;\n const relevantFiles = new Set<string>([...RELEVANT_BRANCH_SCOPE_FILES, rootIndex]);\n const routeFiles = await fg([`${areaFilesRoot}/**/*.md`], {\n cwd: repository.worktreePath,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n\n for (const routeFile of routeFiles) {\n relevantFiles.add(routeFile);\n }\n\n for (const relativePath of [...relevantFiles].sort()) {\n try {\n const source = await fs.readFile(resolveWorktreePath(repository, relativePath), \"utf8\");\n\n relevantFileHashes[relativePath] = hashText(source);\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n continue;\n }\n\n const detail = error instanceof Error ? error.message : \"unknown error\";\n\n throw new BranchScopeFileError(\n relativePath,\n `Branch-scope file ${relativePath} could not be read safely: ${detail}`,\n );\n }\n }\n\n return createBranchScopeData(repository, relevantFileHashes);\n};\n","import { createHash } from \"node:crypto\";\n\nconst toStableValue = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map((entry) => toStableValue(entry));\n }\n\n if (value && typeof value === \"object\") {\n return Object.keys(value as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((stable, key) => {\n stable[key] = toStableValue((value as Record<string, unknown>)[key]);\n return stable;\n }, {});\n }\n\n return value;\n};\n\nexport const hashText = (value: string): string => {\n return createHash(\"sha256\").update(value, \"utf8\").digest(\"hex\");\n};\n\nexport const hashJsonLike = (value: unknown): string => {\n return hashText(JSON.stringify(toStableValue(value)));\n};","import fs from \"node:fs/promises\";\n\nimport fg from \"fast-glob\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\n\nconst looksLikeGlob = (pattern: string): boolean => {\n return /[*?[\\]{}()!+@]/u.test(pattern);\n};\n\nconst pathExists = async (absolutePath: string): Promise<boolean> => {\n try {\n await fs.stat(absolutePath);\n return true;\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n\n throw error;\n }\n};\n\nexport type AuthorityCheckResult = {\n paths: string[];\n diagnostics: Diagnostic[];\n};\n\nexport const checkAuthority = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<AuthorityCheckResult> => {\n const diagnostics: Diagnostic[] = [];\n const orderedPaths: string[] = [];\n const seenPaths = new Set<string>();\n\n for (const entry of config.authority) {\n if (looksLikeGlob(entry)) {\n try {\n resolveRepoPath(rootDir, entry);\n } catch {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Authority entry ${entry} must stay inside the repository root.`,\n file: entry,\n });\n continue;\n }\n\n const matches = (await fg([entry], { cwd: rootDir, onlyFiles: true })).sort();\n\n if (matches.length === 0) {\n diagnostics.push({\n category: \"authority\",\n severity: \"review\",\n message: `Authority glob ${entry} did not match any files.`,\n file: entry,\n });\n }\n\n for (const match of matches) {\n try {\n const absoluteMatchPath = resolveRepoPath(rootDir, match);\n await assertRepoContainment(rootDir, absoluteMatchPath);\n } catch {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Authority path ${match} must stay inside the repository root.`,\n file: match,\n });\n continue;\n }\n\n if (!seenPaths.has(match)) {\n seenPaths.add(match);\n orderedPaths.push(match);\n }\n }\n\n continue;\n }\n\n let absoluteEntryPath: string;\n\n try {\n absoluteEntryPath = resolveRepoPath(rootDir, entry);\n await assertRepoContainment(rootDir, absoluteEntryPath);\n } catch {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Authority entry ${entry} must stay inside the repository root.`,\n file: entry,\n });\n continue;\n }\n\n if (!(await pathExists(absoluteEntryPath))) {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Missing authority file ${entry}.`,\n file: entry,\n });\n continue;\n }\n\n if (!seenPaths.has(entry)) {\n seenPaths.add(entry);\n orderedPaths.push(entry);\n }\n }\n\n return {\n paths: orderedPaths,\n diagnostics,\n };\n};\n","import fs from \"node:fs/promises\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n TRUTH_DOCUMENT_KINDS,\n type TruthDocumentEntry,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\n\nconst isTruthDocumentKind = (\n value: string,\n): value is TruthDocumentKind =>\n TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind);\n\nexport const checkFrontmatter = async (\n rootDir: string,\n config: TruthmarkConfig,\n markdownPaths: string[],\n truthDocumentEntries: TruthDocumentEntry[] = [],\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n const truthDocumentMap = new Map(\n truthDocumentEntries.map((entry) => [entry.path, entry]),\n );\n\n for (const markdownPath of markdownPaths) {\n if (!markdownPath.endsWith(\".md\")) {\n continue;\n }\n\n const absolutePath = resolveRepoPath(rootDir, markdownPath);\n\n await assertRepoContainment(rootDir, absolutePath);\n\n const source = await fs.readFile(absolutePath, \"utf8\");\n let document;\n\n try {\n document = parseMarkdownDocument(source);\n } catch (error: unknown) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Invalid frontmatter: ${error instanceof Error ? error.message : String(error)}`,\n file: markdownPath,\n });\n continue;\n }\n\n for (const field of config.frontmatter.required) {\n if (!(field in document.frontmatter)) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Missing required frontmatter field ${field}.`,\n file: markdownPath,\n });\n }\n }\n\n for (const field of config.frontmatter.recommended) {\n if (!(field in document.frontmatter)) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"review\",\n message: `Missing recommended frontmatter field ${field}.`,\n file: markdownPath,\n });\n }\n }\n\n const routedTruthDocument = truthDocumentMap.get(markdownPath);\n const truthKind = document.frontmatter.truth_kind;\n\n if (truthKind !== undefined) {\n if (typeof truthKind !== \"string\" || !isTruthDocumentKind(truthKind)) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Frontmatter truth_kind must be one of ${TRUTH_DOCUMENT_KINDS.join(\", \")}.`,\n file: markdownPath,\n });\n continue;\n }\n\n if (\n routedTruthDocument &&\n routedTruthDocument.kindSource !== \"defaulted\" &&\n truthKind !== routedTruthDocument.kind\n ) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Frontmatter truth_kind ${truthKind} must match routed truth kind ${routedTruthDocument.kind}.`,\n file: markdownPath,\n });\n }\n }\n }\n\n return diagnostics;\n};","import matter from \"gray-matter\";\nimport { unified } from \"unified\";\nimport remarkParse from \"remark-parse\";\nimport { visit } from \"unist-util-visit\";\n\ntype Heading = {\n depth: number;\n text: string;\n};\n\nexport type ParsedMarkdownDocument = {\n frontmatter: Record<string, unknown>;\n headings: Heading[];\n internalLinks: string[];\n};\n\ntype MdastNode = {\n type: string;\n depth?: number;\n url?: string;\n value?: string;\n children?: MdastNode[];\n};\n\nconst extractText = (node: MdastNode): string => {\n if (typeof node.value === \"string\") {\n return node.value;\n }\n\n return (node.children ?? []).map((child) => extractText(child)).join(\"\").trim();\n};\n\nconst isInternalLink = (url: string): boolean => {\n return url.startsWith(\"#\") || (!url.includes(\"://\") && !url.startsWith(\"mailto:\"));\n};\n\nexport const parseMarkdownDocument = (source: string): ParsedMarkdownDocument => {\n const parsed = matter(source);\n const tree = unified().use(remarkParse).parse(parsed.content) as MdastNode;\n const headings: Heading[] = [];\n const internalLinks: string[] = [];\n\n visit(tree, (node: MdastNode) => {\n if (node.type === \"heading\" && typeof node.depth === \"number\") {\n headings.push({\n depth: node.depth,\n text: extractText(node),\n });\n }\n\n if (node.type === \"link\" && typeof node.url === \"string\" && isInternalLink(node.url)) {\n internalLinks.push(node.url);\n }\n });\n\n return {\n frontmatter: parsed.data,\n headings,\n internalLinks,\n };\n};","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { assertRepoContainment, resolveRepoPath, toRepoRelativePath } from \"../fs/paths.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\n\nconst pathExists = async (absolutePath: string): Promise<boolean> => {\n try {\n await fs.stat(absolutePath);\n return true;\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n\n throw error;\n }\n};\n\nexport const checkLinks = async (\n rootDir: string,\n markdownPaths: string[],\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n\n for (const markdownPath of markdownPaths) {\n if (!markdownPath.endsWith(\".md\")) {\n continue;\n }\n\n const absolutePath = resolveRepoPath(rootDir, markdownPath);\n const source = await fs.readFile(absolutePath, \"utf8\");\n let document;\n\n try {\n document = parseMarkdownDocument(source);\n } catch {\n continue;\n }\n\n for (const link of document.internalLinks) {\n if (link.startsWith(\"#\")) {\n continue;\n }\n\n const targetPath = link.split(\"#\")[0] ?? \"\";\n\n if (targetPath.length === 0) {\n continue;\n }\n\n const absoluteTarget = path.resolve(path.dirname(absolutePath), targetPath);\n const relativeTarget = toRepoRelativePath(rootDir, absoluteTarget);\n\n try {\n await assertRepoContainment(rootDir, absoluteTarget);\n } catch {\n diagnostics.push({\n category: \"links\",\n severity: \"error\",\n message: `Internal link to ${relativeTarget} must stay inside the repository root.`,\n file: markdownPath,\n });\n continue;\n }\n\n if (!(await pathExists(absoluteTarget))) {\n diagnostics.push({\n category: \"links\",\n severity: \"error\",\n message: `Broken internal link to ${relativeTarget}.`,\n file: markdownPath,\n });\n }\n }\n }\n\n return diagnostics;\n};","import fs from \"node:fs/promises\";\n\nimport fg from \"fast-glob\";\nimport micromatch from \"micromatch\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport { resolveAreaRouting } from \"../routing/area-resolver.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport type { TruthDocumentEntry } from \"../routing/areas.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\n\nexport type AreasCheckResult = {\n diagnostics: Diagnostic[];\n truthDocumentPaths: string[];\n truthDocumentEntries: TruthDocumentEntry[];\n routePrecision: {\n leafAreaCount: number;\n broadAreaCount: number;\n };\n topologyPressureCount: number;\n};\n\nconst looksLikeGlob = (pattern: string): boolean => {\n return /[*?[\\]{}()!+@]/u.test(pattern);\n};\n\nconst pathExists = async (absolutePath: string): Promise<boolean> => {\n try {\n await fs.stat(absolutePath);\n return true;\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n\n throw error;\n }\n};\n\nconst COVERAGE_SCAN_PATTERNS = [\n \"app/**/*\",\n \"api/**/*\",\n \"apps/**/*\",\n \"bin/**/*\",\n \"client/**/*\",\n \"cmd/**/*\",\n \"frontend/**/*\",\n \"infra/**/*\",\n \"infrastructure/**/*\",\n \"internal/**/*\",\n \"k8s/**/*\",\n \"kubernetes/**/*\",\n \"lib/**/*\",\n \"packages/**/*\",\n \"pkg/**/*\",\n \"proto/**/*\",\n \"schema/**/*\",\n \"schemas/**/*\",\n \"scripts/**/*\",\n \"server/**/*\",\n \"services/**/*\",\n \"src/**/*\",\n \"terraform/**/*\",\n \"web/**/*\",\n \".github/workflows/**/*\",\n] as const;\n\nconst BROAD_CODE_SURFACES = new Set([\n \"app/**\",\n \"apps/**\",\n \"server/**\",\n \"services/**\",\n \"src/**\",\n \"packages/**\",\n]);\n\nconst isBroadCodeSurface = (pattern: string): boolean => {\n return BROAD_CODE_SURFACES.has(pattern.replace(/\\/\\*\\*\\/\\*$/u, \"/**\"));\n};\n\nexport const checkAreas = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<AreasCheckResult> => {\n const routing = await resolveAreaRouting(rootDir, {\n rootIndex: config.docs.routing.rootIndex,\n areaFilesRoot: config.docs.routing.areaFilesRoot,\n truthDocsRoot: resolveTruthDocsRoot(config),\n });\n\n const discoveredCodeFiles = await fg([...COVERAGE_SCAN_PATTERNS], {\n cwd: rootDir,\n onlyFiles: true,\n ignore: config.ignore,\n followSymbolicLinks: false,\n dot: true,\n });\n const rawCodeFiles = discoveredCodeFiles.filter(\n (filePath) => classifyPath(filePath, config.ignore) === \"functional-code\",\n );\n const diagnostics: Diagnostic[] = [...routing.diagnostics];\n const truthDocumentPaths: string[] = [];\n const seenTruthDocumentPaths = new Set<string>();\n const truthDocumentEntryMap = new Map<string, TruthDocumentEntry>();\n const areaCoverage = routing.areas.map((area) => ({\n area,\n valid: true,\n patterns: [] as string[],\n }));\n const codeFiles: string[] = [];\n\n for (const codeFile of rawCodeFiles.sort()) {\n try {\n await assertRepoContainment(rootDir, resolveRepoPath(rootDir, codeFile));\n codeFiles.push(codeFile);\n } catch {\n continue;\n }\n }\n\n const truthReferences = routing.truthDocumentReferences;\n\n for (const area of truthReferences) {\n let areaHasTruthDocumentErrors = false;\n const registerTruthDocumentEntry = (truthDocumentEntry: TruthDocumentEntry): boolean => {\n const existingEntry = truthDocumentEntryMap.get(truthDocumentEntry.path);\n\n if (existingEntry && existingEntry.kind !== truthDocumentEntry.kind) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document ${truthDocumentEntry.path} is routed with conflicting kinds ${existingEntry.kind} and ${truthDocumentEntry.kind}.`,\n area: area.name,\n file: truthDocumentEntry.path,\n });\n return false;\n }\n\n if (!existingEntry) {\n truthDocumentEntryMap.set(truthDocumentEntry.path, truthDocumentEntry);\n }\n\n return true;\n };\n\n for (const truthDocument of area.truthDocuments) {\n if (looksLikeGlob(truthDocument)) {\n const routedGlobEntry = area.truthDocumentEntries.find(\n (entry) => entry.path === truthDocument,\n );\n const matches = (await fg([truthDocument], { cwd: rootDir, onlyFiles: true })).sort();\n\n if (matches.length === 0) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document glob ${truthDocument} did not match any files.`,\n area: area.name,\n file: truthDocument,\n });\n areaHasTruthDocumentErrors = true;\n continue;\n }\n\n for (const match of matches) {\n try {\n const absoluteMatchPath = resolveRepoPath(rootDir, match);\n await assertRepoContainment(rootDir, absoluteMatchPath);\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document ${match} must stay inside the repository root.`,\n area: area.name,\n file: match,\n });\n areaHasTruthDocumentErrors = true;\n continue;\n }\n\n if (!seenTruthDocumentPaths.has(match)) {\n seenTruthDocumentPaths.add(match);\n truthDocumentPaths.push(match);\n }\n if (\n routedGlobEntry &&\n !registerTruthDocumentEntry({\n ...routedGlobEntry,\n path: match,\n })\n ) {\n areaHasTruthDocumentErrors = true;\n }\n }\n\n continue;\n }\n\n let absoluteTruthDocumentPath: string;\n\n try {\n absoluteTruthDocumentPath = resolveRepoPath(rootDir, truthDocument);\n await assertRepoContainment(rootDir, absoluteTruthDocumentPath);\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document ${truthDocument} must stay inside the repository root.`,\n area: area.name,\n file: truthDocument,\n });\n areaHasTruthDocumentErrors = true;\n continue;\n }\n\n if (!(await pathExists(absoluteTruthDocumentPath))) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Missing truth document ${truthDocument}.`,\n area: area.name,\n file: truthDocument,\n });\n areaHasTruthDocumentErrors = true;\n continue;\n }\n\n if (!seenTruthDocumentPaths.has(truthDocument)) {\n seenTruthDocumentPaths.add(truthDocument);\n truthDocumentPaths.push(truthDocument);\n }\n\n const routedEntry = area.truthDocumentEntries.find((entry) => entry.path === truthDocument);\n\n if (routedEntry && !registerTruthDocumentEntry(routedEntry)) {\n areaHasTruthDocumentErrors = true;\n }\n }\n\n if (areaHasTruthDocumentErrors) {\n const matchingArea = areaCoverage.find(\n (entry) =>\n entry.area.name === area.name &&\n entry.area.truthDocuments.length === area.truthDocuments.length &&\n entry.area.truthDocuments.every(\n (truthDocument, index) => truthDocument === area.truthDocuments[index],\n ),\n );\n if (matchingArea) {\n matchingArea.valid = false;\n }\n }\n }\n\n for (const entry of areaCoverage) {\n const { area } = entry;\n for (const codeSurfaceEntry of area.codeSurface) {\n if (looksLikeGlob(codeSurfaceEntry)) {\n try {\n resolveRepoPath(rootDir, codeSurfaceEntry);\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Code surface ${codeSurfaceEntry} must stay inside the repository root.`,\n area: area.name,\n file: codeSurfaceEntry,\n });\n entry.valid = false;\n continue;\n }\n\n const matches = await fg([codeSurfaceEntry], {\n cwd: rootDir,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n\n let containedMatches = 0;\n\n for (const match of matches) {\n try {\n await assertRepoContainment(rootDir, resolveRepoPath(rootDir, match));\n containedMatches += 1;\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Code surface ${match} must stay inside the repository root.`,\n area: area.name,\n file: match,\n });\n }\n }\n\n if (containedMatches === 0) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"review\",\n message: `Code surface glob ${codeSurfaceEntry} did not match any files.`,\n area: area.name,\n file: codeSurfaceEntry,\n });\n } else {\n entry.patterns.push(codeSurfaceEntry);\n }\n\n continue;\n }\n\n let absoluteCodeSurfacePath: string;\n\n try {\n absoluteCodeSurfacePath = resolveRepoPath(rootDir, codeSurfaceEntry);\n await assertRepoContainment(rootDir, absoluteCodeSurfacePath);\n } catch {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Code surface ${codeSurfaceEntry} must stay inside the repository root.`,\n area: area.name,\n file: codeSurfaceEntry,\n });\n entry.valid = false;\n continue;\n }\n\n if (!(await pathExists(absoluteCodeSurfacePath))) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Missing code surface file ${codeSurfaceEntry}.`,\n area: area.name,\n file: codeSurfaceEntry,\n });\n continue;\n }\n\n entry.patterns.push(codeSurfaceEntry);\n }\n }\n\n for (const codeFile of codeFiles.sort()) {\n const matched = areaCoverage.some(\n (entry) =>\n entry.valid && entry.patterns.some((pattern) => micromatch.isMatch(codeFile, pattern)),\n );\n\n if (!matched) {\n diagnostics.push({\n category: \"coverage\",\n severity: \"review\",\n message: `Code file ${codeFile} is not covered by any Truthmark area mapping.`,\n file: codeFile,\n });\n }\n }\n\n const broadAreaCount = routing.areas.filter((area) =>\n area.codeSurface.some((pattern) => isBroadCodeSurface(pattern)),\n ).length;\n const topologyPressureCount =\n broadAreaCount +\n diagnostics.filter(\n (diagnostic) => diagnostic.category === \"area-index\" && diagnostic.severity === \"review\",\n ).length;\n\n return {\n diagnostics,\n truthDocumentPaths,\n truthDocumentEntries: [...truthDocumentEntryMap.values()],\n routePrecision: {\n leafAreaCount: routing.areas.length,\n broadAreaCount,\n },\n topologyPressureCount,\n };\n};\n","import fs from \"node:fs/promises\";\n\nimport fg from \"fast-glob\";\nimport micromatch from \"micromatch\";\n\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n parseAreasMarkdown,\n type TruthArea,\n type TruthAreaReference,\n} from \"./areas.js\";\n\nexport type AreaRoutingConfig = {\n rootIndex: string;\n areaFilesRoot: string;\n truthDocsRoot?: string;\n};\n\nexport type ResolvedTruthArea = TruthArea & {\n sourcePath: string;\n parentName?: string;\n};\n\nexport type ResolvedAreaRouting = {\n areas: ResolvedTruthArea[];\n truthDocumentReferences: TruthAreaReference[];\n truthDocumentPaths: string[];\n routeFiles: string[];\n diagnostics: Diagnostic[];\n};\n\nconst unique = (values: string[]): string[] => {\n return [...new Set(values)];\n};\n\nconst normalizeGlobPath = (value: string): string => {\n return value.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/u, \"\");\n};\n\nconst concretePrefix = (pattern: string): string => {\n const normalizedPattern = normalizeGlobPath(pattern);\n const wildcardIndex = normalizedPattern.search(/[*?[{(!+@]/u);\n const prefix = wildcardIndex === -1 ? normalizedPattern : normalizedPattern.slice(0, wildcardIndex);\n\n return prefix.replace(/[^/]*$/u, \"\");\n};\n\nconst isCodeSurfaceWithinParent = (childPattern: string, parentPatterns: string[]): boolean => {\n const childPrefix = concretePrefix(childPattern);\n\n if (childPrefix.length === 0) {\n return false;\n }\n\n return parentPatterns.some((parentPattern) => {\n return micromatch.isMatch(childPrefix, parentPattern) || micromatch.isMatch(childPattern, parentPattern);\n });\n};\n\nconst ensureChildPath = async (\n rootDir: string,\n areaFilesRoot: string,\n filePath: string,\n): Promise<Diagnostic | null> => {\n try {\n const absoluteChild = resolveRepoPath(rootDir, filePath);\n const absoluteRoot = resolveRepoPath(rootDir, areaFilesRoot);\n await assertRepoContainment(rootDir, absoluteChild);\n await assertRepoContainment(rootDir, absoluteRoot);\n\n if (!absoluteChild.startsWith(`${absoluteRoot}/`)) {\n return {\n category: \"area-index\",\n severity: \"error\",\n message: `Area file ${filePath} must live under ${areaFilesRoot}.`,\n file: filePath,\n };\n }\n } catch {\n return {\n category: \"area-index\",\n severity: \"error\",\n message: `Area file ${filePath} must stay inside the repository root.`,\n file: filePath,\n };\n }\n\n return null;\n};\n\nconst readRouteFile = async (\n rootDir: string,\n filePath: string,\n): Promise<{ source: string | null; diagnostic: Diagnostic | null }> => {\n try {\n return {\n source: await fs.readFile(resolveRepoPath(rootDir, filePath), \"utf8\"),\n diagnostic: null,\n };\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return {\n source: null,\n diagnostic: {\n category: \"area-index\",\n severity: \"error\",\n message: `Missing area file ${filePath}.`,\n file: filePath,\n },\n };\n }\n\n throw error;\n }\n};\n\nexport const resolveAreaRouting = async (\n rootDir: string,\n config: AreaRoutingConfig,\n): Promise<ResolvedAreaRouting> => {\n const diagnostics: Diagnostic[] = [];\n const routeFiles = [config.rootIndex];\n const areas: ResolvedTruthArea[] = [];\n const truthDocumentReferences: TruthAreaReference[] = [];\n const truthDocumentPaths: string[] = [];\n const rootRead = await readRouteFile(rootDir, config.rootIndex);\n\n if (rootRead.diagnostic) {\n return {\n areas,\n truthDocumentReferences,\n truthDocumentPaths,\n routeFiles,\n diagnostics: [rootRead.diagnostic],\n };\n }\n\n const rootParsed = parseAreasMarkdown(rootRead.source ?? \"\", {\n truthDocsRoot: config.truthDocsRoot,\n });\n diagnostics.push(\n ...rootParsed.diagnostics.map((diagnostic) => ({\n ...diagnostic,\n file: diagnostic.file ?? config.rootIndex,\n })),\n );\n truthDocumentReferences.push(...rootParsed.truthDocumentReferences);\n areas.push(...rootParsed.areas.map((area) => ({ ...area, sourcePath: config.rootIndex })));\n\n const referencedChildFiles = new Set<string>();\n\n for (const area of rootParsed.areaFileReferences) {\n for (const areaFile of area.areaFiles) {\n if (referencedChildFiles.has(areaFile)) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Area file ${areaFile} is referenced more than once.`,\n file: areaFile,\n area: area.name,\n });\n }\n\n referencedChildFiles.add(areaFile);\n }\n }\n\n for (const area of rootParsed.areaFileReferences) {\n for (const areaFile of area.areaFiles) {\n const childPathDiagnostic = await ensureChildPath(rootDir, config.areaFilesRoot, areaFile);\n\n if (childPathDiagnostic) {\n diagnostics.push(childPathDiagnostic);\n continue;\n }\n\n const childRead = await readRouteFile(rootDir, areaFile);\n\n if (childRead.diagnostic) {\n diagnostics.push(childRead.diagnostic);\n continue;\n }\n\n routeFiles.push(areaFile);\n const childParsed = parseAreasMarkdown(childRead.source ?? \"\", {\n truthDocsRoot: config.truthDocsRoot,\n });\n diagnostics.push(\n ...childParsed.diagnostics.map((diagnostic) => ({\n ...diagnostic,\n file: diagnostic.file ?? areaFile,\n })),\n );\n truthDocumentReferences.push(...childParsed.truthDocumentReferences);\n\n if (childParsed.areaFileReferences.length > 0) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: \"Child area files must contain leaf areas only.\",\n file: areaFile,\n area: area.name,\n });\n continue;\n }\n\n areas.push(\n ...childParsed.areas.map((childArea) => {\n for (const childCodeSurface of childArea.codeSurface) {\n if (!isCodeSurfaceWithinParent(childCodeSurface, area.codeSurface)) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"review\",\n message: `Child code surface ${childCodeSurface} is outside parent area ${area.name} code surface.`,\n file: areaFile,\n area: childArea.name,\n });\n }\n }\n\n return {\n ...childArea,\n sourcePath: areaFile,\n parentName: area.name,\n };\n }),\n );\n }\n }\n\n const routeFilesUnderRoot = await fg([`${config.areaFilesRoot}/**/*.md`], {\n cwd: rootDir,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n\n for (const routeFile of routeFilesUnderRoot.sort()) {\n if (!referencedChildFiles.has(routeFile)) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"review\",\n message: `Area file ${routeFile} is not referenced by the root route index.`,\n file: routeFile,\n });\n }\n }\n\n const areaKeys = new Map<string, ResolvedTruthArea>();\n\n for (const area of areas) {\n const existingArea = areaKeys.get(area.key);\n\n if (existingArea) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Duplicate area key ${area.key} appears in ${existingArea.name} and ${area.name}.`,\n area: area.name,\n });\n continue;\n }\n\n areaKeys.set(area.key, area);\n }\n\n for (const area of areas) {\n truthDocumentPaths.push(...area.truthDocuments);\n }\n\n return {\n areas,\n truthDocumentReferences,\n truthDocumentPaths: unique(truthDocumentPaths),\n routeFiles: unique(routeFiles),\n diagnostics,\n };\n};\n","import micromatch from \"micromatch\";\n\nexport type PathClassification =\n | \"functional-code\"\n | \"markdown\"\n | \"config\"\n | \"ignored\"\n | \"derived\"\n | \"other\";\n\nconst CODE_EXTENSIONS = new Set([\n \".c\",\n \".cc\",\n \".cpp\",\n \".cs\",\n \".cts\",\n \".cjs\",\n \".ex\",\n \".exs\",\n \".gql\",\n \".go\",\n \".graphql\",\n \".h\",\n \".hpp\",\n \".hrl\",\n \".java\",\n \".js\",\n \".jsx\",\n \".kt\",\n \".kts\",\n \".lua\",\n \".mjs\",\n \".mts\",\n \".php\",\n \".proto\",\n \".py\",\n \".rb\",\n \".rs\",\n \".scala\",\n \".sh\",\n \".swift\",\n \".tf\",\n \".tfvars\",\n \".ts\",\n \".tsx\",\n]);\n\nconst CONFIG_EXTENSIONS = new Set([\n \".cfg\",\n \".conf\",\n \".env\",\n \".ini\",\n \".json\",\n \".jsonc\",\n \".toml\",\n \".yaml\",\n \".yml\",\n]);\n\nconst CONFIG_BASENAMES = new Set([\n \".editorconfig\",\n \".gitattributes\",\n \".gitignore\",\n \"Dockerfile\",\n \"package-lock.json\",\n \"package.json\",\n \"pnpm-lock.yaml\",\n \"tsconfig.json\",\n \"yarn.lock\",\n]);\n\nconst CONFIG_SUFFIXES = [\n \".config.cjs\",\n \".config.js\",\n \".config.mjs\",\n \".config.ts\",\n \".config.tsx\",\n \".config.jsx\",\n];\n\nconst COMMON_CODE_DIRECTORIES =\n /(^|\\/)(api|app|apps|bin|client|cmd|components|frontend|infra|infrastructure|k8s|kubernetes|lib|packages|proto|schema|schemas|scripts|server|services|src|terraform|web)\\//u;\nconst FUNCTIONAL_CONFIG_DIRECTORIES =\n /(^|\\/)(api|infra|infrastructure|k8s|kubernetes|schema|schemas|terraform)\\//u;\nconst FUNCTIONAL_CONFIG_BASENAMES = new Set([\n \"openapi.json\",\n \"openapi.yaml\",\n \"openapi.yml\",\n \"swagger.json\",\n \"swagger.yaml\",\n \"swagger.yml\",\n]);\n\nconst normalizePath = (filePath: string): string => {\n return filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\//u, \"\");\n};\n\nconst getBaseName = (filePath: string): string => {\n const segments = normalizePath(filePath).split(\"/\");\n\n return segments.at(-1) ?? filePath;\n};\n\nconst getExtension = (filePath: string): string => {\n const baseName = getBaseName(filePath);\n const extensionIndex = baseName.lastIndexOf(\".\");\n\n if (extensionIndex <= 0) {\n return \"\";\n }\n\n return baseName.slice(extensionIndex).toLowerCase();\n};\n\nconst isConfigPath = (filePath: string): boolean => {\n const normalizedPath = normalizePath(filePath);\n const baseName = getBaseName(normalizedPath);\n const extension = getExtension(normalizedPath);\n\n return (\n CONFIG_BASENAMES.has(baseName) ||\n CONFIG_EXTENSIONS.has(extension) ||\n CONFIG_SUFFIXES.some((suffix) => baseName.endsWith(suffix))\n );\n};\n\nconst isFunctionalConfigPath = (filePath: string): boolean => {\n const normalizedPath = normalizePath(filePath);\n const baseName = getBaseName(normalizedPath).toLowerCase();\n const extension = getExtension(normalizedPath);\n\n return (\n normalizedPath.startsWith(\".github/workflows/\") ||\n FUNCTIONAL_CONFIG_BASENAMES.has(baseName) ||\n ((extension === \".yaml\" || extension === \".yml\" || extension === \".json\") &&\n FUNCTIONAL_CONFIG_DIRECTORIES.test(normalizedPath))\n );\n};\n\nconst isCodeLikePath = (filePath: string): boolean => {\n const normalizedPath = normalizePath(filePath);\n const extension = getExtension(normalizedPath);\n\n if (CODE_EXTENSIONS.has(extension)) {\n return true;\n }\n\n return extension.length === 0 && COMMON_CODE_DIRECTORIES.test(normalizedPath);\n};\n\nexport const classifyPath = (\n filePath: string,\n ignorePatterns: string[],\n): PathClassification => {\n const normalizedPath = normalizePath(filePath);\n\n if (normalizedPath === \".truthmark/config.yml\") {\n return \"config\";\n }\n\n if (normalizedPath.startsWith(\".truthmark/\")) {\n return \"derived\";\n }\n\n if (\n normalizedPath.startsWith(\".claude/\") ||\n normalizedPath.startsWith(\".codex/\") ||\n normalizedPath.startsWith(\".gemini/commands/\") ||\n normalizedPath.startsWith(\".opencode/\") ||\n normalizedPath === \".github/copilot-instructions.md\" ||\n normalizedPath.startsWith(\".github/agents/truth-\") ||\n normalizedPath.startsWith(\".github/prompts/truthmark-\") ||\n normalizedPath === \"AGENTS.md\" ||\n normalizedPath === \"CLAUDE.md\" ||\n normalizedPath === \"GEMINI.md\" ||\n normalizedPath.startsWith(\".gemini/commands/truthmark/\")\n ) {\n return \"derived\";\n }\n\n if (ignorePatterns.length > 0 && micromatch.isMatch(normalizedPath, ignorePatterns)) {\n return \"ignored\";\n }\n\n if (normalizedPath.toLowerCase().endsWith(\".md\")) {\n return \"markdown\";\n }\n\n if (isFunctionalConfigPath(normalizedPath)) {\n return \"functional-code\";\n }\n\n if (isConfigPath(normalizedPath)) {\n return \"config\";\n }\n\n if (isCodeLikePath(normalizedPath)) {\n return \"functional-code\";\n }\n\n return \"other\";\n};\n","import fs from \"node:fs/promises\";\n\nimport micromatch from \"micromatch\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { resolveRepoPath } from \"../fs/paths.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n TRUTH_DOCUMENT_KINDS,\n inferTruthDocumentKindFromPath,\n type TruthDocumentEntry,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\n\nconst REQUIRED_DECISION_HEADINGS = [\"Scope\", \"Product Decisions\", \"Rationale\"];\n\nconst isTruthDocumentKind = (value: string): value is TruthDocumentKind => {\n return TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind);\n};\n\nconst escapeRegExp = (value: string): string => {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n};\n\nconst hasHeading = (source: string, heading: string): boolean => {\n return new RegExp(`^#{2,3}\\\\s+${escapeRegExp(heading)}\\\\s*$`, \"mu\").test(source);\n};\n\nconst kindSpecificHeadingMessages = (\n source: string,\n kind: TruthDocumentKind | null,\n): string[] => {\n if (kind === null) {\n return [];\n }\n\n if (kind === \"behavior\") {\n return hasHeading(source, \"Current Behavior\") ? [] : [\"Current Behavior\"];\n }\n\n if (kind === \"contract\") {\n const missingMessages: string[] = [];\n\n if (!hasHeading(source, \"Contract Surface\")) {\n missingMessages.push(\"Contract Surface\");\n }\n\n if (\n !hasHeading(source, \"Inputs\") &&\n !hasHeading(source, \"Outputs\") &&\n !hasHeading(source, \"Compatibility Rules\")\n ) {\n missingMessages.push(\"one of Inputs, Outputs, or Compatibility Rules\");\n }\n\n return missingMessages;\n }\n\n if (kind === \"architecture\") {\n return hasHeading(source, \"Boundaries\") || hasHeading(source, \"Components\")\n ? []\n : [\"Boundaries or Components\"];\n }\n\n if (kind === \"workflow\") {\n const missingMessages: string[] = [];\n\n if (!hasHeading(source, \"Triggers\")) {\n missingMessages.push(\"Triggers\");\n }\n\n if (!hasHeading(source, \"Execution Model\")) {\n missingMessages.push(\"Execution Model\");\n }\n\n return missingMessages;\n }\n\n if (kind === \"operations\") {\n return hasHeading(source, \"Runtime Topology\") || hasHeading(source, \"Configuration\")\n ? []\n : [\"Runtime Topology or Configuration\"];\n }\n\n if (kind === \"test-behavior\") {\n const missingMessages: string[] = [];\n\n if (!hasHeading(source, \"Execution Model\")) {\n missingMessages.push(\"Execution Model\");\n }\n\n if (\n !hasHeading(source, \"Fixtures And Data Model\") &&\n !hasHeading(source, \"Assertions And Invariants\")\n ) {\n missingMessages.push(\"Fixtures And Data Model or Assertions And Invariants\");\n }\n\n return missingMessages;\n }\n\n return [];\n};\n\nconst decisionTruthGlobs = (config: TruthmarkConfig): string[] => {\n return [\n config.docs.roots.architecture,\n resolveTruthDocsRoot(config),\n config.docs.roots.api,\n ]\n .filter((root): root is string => Boolean(root))\n .map((root) => `${root}/**/*.md`);\n};\n\nconst isDecisionTruthCandidate = (config: TruthmarkConfig, filePath: string): boolean => {\n return !filePath.endsWith(\"/README.md\") && micromatch.isMatch(filePath, decisionTruthGlobs(config));\n};\n\nexport const checkDecisionSections = async (\n rootDir: string,\n config: TruthmarkConfig,\n markdownPaths: string[],\n truthDocumentEntries: TruthDocumentEntry[] = [],\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n const truthDocumentMap = new Map(\n truthDocumentEntries.map((entry) => [entry.path, entry]),\n );\n const candidatePaths = [...new Set(markdownPaths)]\n .filter(\n (filePath) =>\n truthDocumentMap.has(filePath) || isDecisionTruthCandidate(config, filePath),\n )\n .sort();\n\n for (const filePath of candidatePaths) {\n const source = await fs.readFile(resolveRepoPath(rootDir, filePath), \"utf8\");\n const document = parseMarkdownDocument(source);\n const routedTruthDocument = truthDocumentMap.get(filePath);\n const frontmatterTruthKind =\n typeof document.frontmatter.truth_kind === \"string\"\n ? document.frontmatter.truth_kind\n : null;\n const routedTruthKind =\n routedTruthDocument?.kindSource === \"defaulted\" ? null : routedTruthDocument?.kind;\n const truthKind =\n routedTruthKind ??\n (frontmatterTruthKind && isTruthDocumentKind(frontmatterTruthKind)\n ? frontmatterTruthKind\n : inferTruthDocumentKindFromPath(filePath));\n const missingHeadings = REQUIRED_DECISION_HEADINGS.filter(\n (heading) => !hasHeading(source, heading),\n );\n missingHeadings.push(...kindSpecificHeadingMessages(source, truthKind));\n\n if (missingHeadings.length === 0) {\n continue;\n }\n\n diagnostics.push({\n category: \"doc-structure\",\n severity: \"review\",\n message: `Canonical truth doc ${filePath} should include ${missingHeadings.join(\" and \")} section(s). Decisions should live beside current behavior, not in timestamped planning logs.`,\n file: filePath,\n });\n }\n\n return diagnostics;\n};\n","import fs from \"node:fs/promises\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { resolveRepoPath } from \"../fs/paths.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { TRUTHMARK_BLOCK_END, TRUTHMARK_BLOCK_START } from \"../templates/agents-block.js\";\nimport { renderGeneratedSurfaces } from \"../templates/generated-surfaces.js\";\nimport { TRUTHMARK_VERSION } from \"../version.js\";\n\nconst readOptionalFile = async (rootDir: string, filePath: string): Promise<string | null> => {\n try {\n return await fs.readFile(resolveRepoPath(rootDir, filePath), \"utf8\");\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return null;\n }\n\n throw error;\n }\n};\n\nconst extractManagedBlock = (content: string): string | null => {\n const startIndex = content.indexOf(TRUTHMARK_BLOCK_START);\n const endIndex = content.indexOf(TRUTHMARK_BLOCK_END);\n\n if (startIndex === -1 || endIndex === -1 || endIndex < startIndex) {\n return null;\n }\n\n return content.slice(startIndex, endIndex + TRUTHMARK_BLOCK_END.length);\n};\n\nconst normalizeGeneratedSurfaceContent = (content: string | null): string | null => {\n if (content === null) {\n return null;\n }\n\n return content.replace(/\\r\\n/g, \"\\n\").replace(/\\n$/u, \"\");\n};\n\nconst versionMarkers = (content: string): string[] => {\n const markers: string[] = [];\n const patterns = [\n /truthmark-version:\\s*([^\\s]+)/gu,\n /Generated by Truthmark\\s+([^\\s.]+(?:\\.[^\\s.]+){1,2})/gu,\n /^version:\\s*\"(\\d+\\.\\d+\\.\\d+)\"\\s*$/gmu,\n ];\n\n for (const pattern of patterns) {\n for (const match of content.matchAll(pattern)) {\n if (match[1]) {\n markers.push(match[1]);\n }\n }\n }\n\n return markers;\n};\n\nexport const checkGeneratedSurfaces = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n\n for (const surface of renderGeneratedSurfaces(config)) {\n const content = await readOptionalFile(rootDir, surface.path);\n\n if (content === null) {\n diagnostics.push({\n category: \"generated-surface\",\n severity: \"review\",\n message: `Generated surface ${surface.path} is missing; rerun truthmark init.`,\n file: surface.path,\n });\n continue;\n }\n\n const comparableContent = normalizeGeneratedSurfaceContent(\n surface.managedBlock ? extractManagedBlock(content) : content,\n );\n const expectedContent = normalizeGeneratedSurfaceContent(surface.content);\n\n if (comparableContent !== expectedContent) {\n diagnostics.push({\n category: \"generated-surface\",\n severity: \"review\",\n message: `Generated surface ${surface.path} is stale; rerun truthmark init.`,\n file: surface.path,\n });\n }\n\n const versionContent = surface.managedBlock ? comparableContent ?? \"\" : content;\n const mismatchedVersions = versionMarkers(versionContent).filter(\n (version) => version !== TRUTHMARK_VERSION,\n );\n\n if (mismatchedVersions.length > 0) {\n diagnostics.push({\n category: \"generated-surface\",\n severity: \"review\",\n message: `Generated surface ${surface.path} has Truthmark version ${mismatchedVersions[0]} but current version is ${TRUTHMARK_VERSION}; rerun truthmark init.`,\n file: surface.path,\n });\n }\n }\n\n return diagnostics;\n};\n","import path from \"node:path\";\n\nimport micromatch from \"micromatch\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { buildRepoIndex } from \"../repo-index/build.js\";\nimport { isJavaScriptLikePath } from \"../repo-index/file-tree.js\";\nimport { analyzeTypeScriptSource } from \"../repo-index/typescript-symbols.js\";\nimport type { ExportEntry, ImportEdge, RouteMapRoute } from \"../repo-index/types.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport { getChangedFiles, readBaseFile } from \"./git-diff.js\";\nimport type { ImpactOptions, ImpactRoute, ImpactSet, PublicSymbolChange } from \"./types.js\";\n\nconst uniqueSorted = (values: string[]): string[] => [...new Set(values)].sort();\n\nconst routeMatchesFile = (route: RouteMapRoute, filePath: string): boolean => {\n return route.codeSurface.some((pattern) => micromatch.isMatch(filePath, pattern));\n};\n\nconst routeOwnsTruthDoc = (route: RouteMapRoute, filePath: string): boolean => {\n return route.truthDocs.includes(filePath);\n};\n\nconst toImpactRoute = (route: RouteMapRoute): ImpactRoute => ({\n id: route.id,\n name: route.name,\n key: route.key,\n sourcePath: route.sourcePath,\n truthDocs: [...route.truthDocs].sort(),\n codeSurface: [...route.codeSurface].sort(),\n});\nconst changedPathSet = (changedFiles: { path: string; previousPath?: string }[]): Set<string> => {\n return new Set(\n changedFiles.flatMap((file) => [file.path, ...(file.previousPath ? [file.previousPath] : [])]),\n );\n};\n\nconst changedFilePaths = (changedFile: { path: string; previousPath?: string }): string[] => {\n return [changedFile.path, ...(changedFile.previousPath ? [changedFile.previousPath] : [])];\n};\n\nconst resolveImportPath = (importEdge: ImportEdge): string | null => {\n if (!importEdge.specifier.startsWith(\".\")) {\n return null;\n }\n\n const basePath = path.posix.normalize(path.posix.join(path.posix.dirname(importEdge.from), importEdge.specifier));\n const withoutExtension = basePath.replace(/\\.[cm]?[jt]sx?$/u, \"\");\n\n return withoutExtension;\n};\n\nconst importTargetsChangedFile = (importEdge: ImportEdge, changedPath: string): boolean => {\n const resolved = resolveImportPath(importEdge);\n if (!resolved) {\n return false;\n }\n\n return changedPath.replace(/\\.[cm]?[jt]sx?$/u, \"\") === resolved;\n};\n\nconst pathSegments = (filePath: string): string[] => filePath.split(\"/\").filter(Boolean);\n\nconst testHintMatchesChangedFile = (hints: string[], changedPath: string): boolean => {\n const changedBaseName = path.posix.basename(changedPath);\n const changedSegments = pathSegments(changedPath);\n\n return hints.some((hint) => changedBaseName.startsWith(hint) || changedSegments.includes(hint));\n};\n\nconst changedSymbolsFor = async (\n cwd: string,\n base: string,\n basePath: string,\n currentPath: string,\n currentExports: ExportEntry[],\n): Promise<PublicSymbolChange[]> => {\n if (!isJavaScriptLikePath(basePath) && !isJavaScriptLikePath(currentPath)) {\n return [];\n }\n\n const baseSource = await readBaseFile(cwd, base, basePath);\n const baseExports = baseSource ? analyzeTypeScriptSource(basePath, baseSource).exports : [];\n const currentByName = new Map(currentExports.map((entry) => [entry.name, entry]));\n const baseByName = new Map(baseExports.map((entry) => [entry.name, entry]));\n const changes: PublicSymbolChange[] = [];\n\n if (basePath !== currentPath) {\n for (const entry of currentExports) {\n changes.push({ path: currentPath, name: entry.name, kind: entry.kind, change: \"added\" });\n }\n for (const entry of baseExports) {\n changes.push({ path: basePath, name: entry.name, kind: entry.kind, change: \"removed\" });\n }\n return changes;\n }\n\n for (const [name, entry] of currentByName) {\n if (!baseByName.has(name)) {\n changes.push({ path: currentPath, name, kind: entry.kind, change: \"added\" });\n }\n }\n\n for (const [name, entry] of baseByName) {\n if (!currentByName.has(name)) {\n changes.push({ path: basePath, name, kind: entry.kind, change: \"removed\" });\n }\n }\n\n return changes;\n};\n\nexport const buildImpactSet = async (\n cwd: string,\n options: ImpactOptions,\n): Promise<ImpactSet> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const [loadResult, repoIndex, changedFilesResult] = await Promise.all([\n loadConfig(rootDir),\n buildRepoIndex(rootDir),\n getChangedFiles(rootDir, options.base),\n ]);\n const changedFiles = changedFilesResult.files;\n const ignore = loadResult.config?.ignore ?? [];\n const diagnostics: Diagnostic[] = [...repoIndex.diagnostics, ...changedFilesResult.diagnostics];\n const affectedRoutes = new Map<string, ImpactRoute>();\n const affectedTruthDocs: string[] = [];\n const affectedTests: string[] = [];\n const changedPublicSymbols: PublicSymbolChange[] = [];\n const knownTestPaths = new Set(repoIndex.tests.map((test) => test.path));\n\n for (const changedFile of changedFiles) {\n const routeCandidatePaths = changedFilePaths(changedFile);\n if (routeCandidatePaths.some((filePath) => knownTestPaths.has(filePath))) {\n affectedTests.push(changedFile.path);\n }\n const matchingRoutes = repoIndex.routeMap.routes.filter(\n (route) =>\n routeCandidatePaths.some(\n (filePath) => routeMatchesFile(route, filePath) || routeOwnsTruthDoc(route, filePath),\n ),\n );\n\n for (const route of matchingRoutes) {\n affectedRoutes.set(route.key, toImpactRoute(route));\n affectedTruthDocs.push(...route.truthDocs);\n if (route.truthDocs.length === 0) {\n diagnostics.push({\n category: \"impact\",\n severity: \"review\",\n message: `Changed file ${changedFile.path} maps to route ${route.name} but the route has no truth document.`,\n file: changedFile.path,\n area: route.name,\n });\n }\n }\n\n if (\n matchingRoutes.length === 0 &&\n !routeCandidatePaths.some((filePath) => knownTestPaths.has(filePath)) &&\n routeCandidatePaths.some((filePath) => classifyPath(filePath, ignore) === \"functional-code\")\n ) {\n diagnostics.push({\n category: \"impact\",\n severity: \"review\",\n message: `Changed file ${changedFile.path} is not mapped to a Truthmark route.`,\n file: changedFile.path,\n });\n }\n\n const currentExports = repoIndex.exports.filter((entry) => entry.path === changedFile.path);\n changedPublicSymbols.push(\n ...(await changedSymbolsFor(\n rootDir,\n options.base,\n changedFile.previousPath ?? changedFile.path,\n changedFile.path,\n currentExports,\n )),\n );\n }\n const uniqueAffectedTruthDocs = uniqueSorted(affectedTruthDocs);\n const changedPaths = changedPathSet(changedFiles);\n for (const symbol of changedPublicSymbols) {\n if (uniqueAffectedTruthDocs.length === 0) {\n diagnostics.push({\n category: \"impact\",\n severity: \"review\",\n message: `Changed public symbol ${symbol.name} in ${symbol.path} has no affected truth document.`,\n file: symbol.path,\n data: {\n symbol: symbol.name,\n change: symbol.change,\n },\n });\n continue;\n }\n if (!uniqueAffectedTruthDocs.some((truthDoc) => changedPaths.has(truthDoc))) {\n diagnostics.push({\n category: \"impact\",\n severity: \"review\",\n message: `Changed public symbol ${symbol.name} in ${symbol.path} has affected truth docs but none were changed in this impact set.`,\n file: symbol.path,\n data: {\n symbol: symbol.name,\n change: symbol.change,\n affectedTruthDocs: uniqueAffectedTruthDocs,\n },\n });\n }\n }\n\n for (const test of repoIndex.tests) {\n const testImports = repoIndex.imports.filter((edge) => edge.from === test.path);\n const importsChangedFile = changedFiles.some((changedFile) =>\n changedFilePaths(changedFile).some((filePath) =>\n testImports.some((importEdge) => importTargetsChangedFile(importEdge, filePath)),\n ),\n );\n const hintMatchesChangedFile = changedFiles.some((changedFile) =>\n changedFilePaths(changedFile).some((filePath) =>\n testHintMatchesChangedFile(test.targetHints, filePath),\n ),\n );\n\n if (importsChangedFile || hintMatchesChangedFile) {\n affectedTests.push(test.path);\n }\n }\n\n return {\n schemaVersion: \"impact-set/v0\",\n base: options.base,\n headSha: repository.headSha,\n changedFiles,\n affectedRoutes: [...affectedRoutes.values()].sort((left, right) =>\n left.key.localeCompare(right.key),\n ),\n affectedTruthDocs: uniqueAffectedTruthDocs,\n affectedTests: uniqueSorted(affectedTests),\n changedPublicSymbols: changedPublicSymbols.sort((left, right) =>\n `${left.path}:${left.name}:${left.change}`.localeCompare(`${right.path}:${right.name}:${right.change}`),\n ),\n diagnostics,\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { discoverRepoFiles, isJavaScriptLikePath } from \"./file-tree.js\";\nimport { discoverPackageMetadata } from \"./package-metadata.js\";\nimport { buildRouteMap } from \"./route-map.js\";\nimport { analyzeTypeScriptSource } from \"./typescript-symbols.js\";\nimport type { ExportEntry, ImportEdge, PublicSymbolEntry, RepoIndex } from \"./types.js\";\n\nexport const buildRepoIndex = async (cwd: string): Promise<RepoIndex> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const loadResult = await loadConfig(rootDir);\n const ignore = loadResult.config?.ignore ?? [];\n const diagnostics: Diagnostic[] = [...loadResult.diagnostics];\n const [packages, fileTree, routeMap] = await Promise.all([\n discoverPackageMetadata(rootDir),\n discoverRepoFiles(rootDir, ignore),\n buildRouteMap(rootDir),\n ]);\n const imports: ImportEdge[] = [];\n const exports: ExportEntry[] = [];\n const publicSymbols: PublicSymbolEntry[] = [];\n\n diagnostics.push(...routeMap.diagnostics);\n\n for (const file of fileTree.files) {\n if (!isJavaScriptLikePath(file.path)) {\n continue;\n }\n\n const source = await fs.readFile(path.join(rootDir, file.path), \"utf8\");\n const analysis = analyzeTypeScriptSource(file.path, source);\n imports.push(...analysis.imports);\n exports.push(...analysis.exports);\n publicSymbols.push(...analysis.publicSymbols);\n }\n\n return {\n schemaVersion: \"repo-index/v0\",\n repository: {\n root: rootDir,\n branchName: repository.branchName,\n headSha: repository.headSha,\n },\n packages,\n files: fileTree.files,\n docs: fileTree.docs,\n tests: fileTree.tests,\n imports: imports.sort((left, right) => `${left.from}:${left.specifier}`.localeCompare(`${right.from}:${right.specifier}`)),\n exports: exports.sort((left, right) => `${left.path}:${left.name}`.localeCompare(`${right.path}:${right.name}`)),\n publicSymbols: publicSymbols.sort((left, right) =>\n `${left.path}:${left.name}`.localeCompare(`${right.path}:${right.name}`),\n ),\n routeMap,\n diagnostics,\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { execa } from \"execa\";\nimport fg from \"fast-glob\";\nimport matter from \"gray-matter\";\nimport micromatch from \"micromatch\";\n\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport type { RepoDocEntry, RepoFileEntry, RepoFileKind, RepoTestEntry } from \"./types.js\";\n\nconst languageByExtension = new Map<string, string>([\n [\".ts\", \"typescript\"],\n [\".tsx\", \"typescript\"],\n [\".js\", \"javascript\"],\n [\".jsx\", \"javascript\"],\n [\".mjs\", \"javascript\"],\n [\".cjs\", \"javascript\"],\n [\".md\", \"markdown\"],\n [\".json\", \"json\"],\n [\".yml\", \"yaml\"],\n [\".yaml\", \"yaml\"],\n [\".toml\", \"toml\"],\n]);\n\nconst sourceExtensions = new Set([\".ts\", \".tsx\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\n\nexport const isJavaScriptLikePath = (filePath: string): boolean => {\n return sourceExtensions.has(path.posix.extname(filePath));\n};\n\nconst isTestPath = (filePath: string): boolean => {\n return (\n filePath.startsWith(\"tests/\") ||\n filePath.includes(\"/__tests__/\") ||\n /(?:^|[./-])(test|spec)\\.[cm]?[jt]sx?$/u.test(path.posix.basename(filePath))\n );\n};\n\nconst fileKind = (filePath: string, ignore: string[]): RepoFileKind => {\n const classification = classifyPath(filePath, ignore);\n if (classification === \"derived\") {\n return \"generated\";\n }\n if (isTestPath(filePath)) {\n return \"test\";\n }\n if (filePath.endsWith(\".md\")) {\n return \"doc\";\n }\n if (classification === \"functional-code\") {\n return \"source\";\n }\n if (classification === \"markdown\") {\n return \"doc\";\n }\n if (classification === \"config\") {\n return \"config\";\n }\n\n return \"other\";\n};\n\nconst targetHintsForTest = (filePath: string): string[] => {\n const hints = new Set<string>();\n const basename = path.posix.basename(filePath).replace(/\\.(test|spec)\\.[cm]?[jt]sx?$/u, \"\");\n if (basename.length > 0) {\n hints.add(basename);\n }\n\n const segments = filePath.split(\"/\");\n const testRootIndex = segments.findIndex((segment) => segment === \"tests\" || segment === \"__tests__\");\n if (testRootIndex >= 0) {\n for (const segment of segments.slice(testRootIndex + 1, -1)) {\n if (segment.length > 0) {\n hints.add(segment);\n }\n }\n }\n\n return [...hints].sort();\n};\n\nconst defaultIgnore = [\".git/**\", \"node_modules/**\", \"dist/**\", \"build/**\"];\n\nconst normalizePath = (filePath: string): string => filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/u, \"\");\n\nconst gitDiscoverableFiles = async (rootDir: string): Promise<string[] | null> => {\n const result = await execa(\n \"git\",\n [\"ls-files\", \"--cached\", \"--others\", \"--exclude-standard\", \"--deduplicate\"],\n {\n cwd: rootDir,\n reject: false,\n },\n );\n if ((result.exitCode ?? 1) !== 0) {\n return null;\n }\n return result.stdout\n .split(\"\\n\")\n .map((line) => normalizePath(line.trim()))\n .filter((line) => line.length > 0);\n};\n\nconst isIgnoredPath = (filePath: string, ignore: string[]): boolean => {\n return micromatch.isMatch(filePath, [...defaultIgnore, ...ignore]);\n};\n\nexport const discoverRepoFiles = async (\n rootDir: string,\n ignore: string[],\n): Promise<{ files: RepoFileEntry[]; docs: RepoDocEntry[]; tests: RepoTestEntry[] }> => {\n const discoveredFiles =\n (await gitDiscoverableFiles(rootDir)) ??\n (await fg([\"**/*\"], {\n cwd: rootDir,\n onlyFiles: true,\n dot: true,\n ignore: [...defaultIgnore, ...ignore],\n followSymbolicLinks: false,\n }));\n const files: RepoFileEntry[] = [];\n const docs: RepoDocEntry[] = [];\n const tests: RepoTestEntry[] = [];\n\n for (const filePath of discoveredFiles.filter((entry) => !isIgnoredPath(entry, ignore)).sort()) {\n let stat: Awaited<ReturnType<typeof fs.stat>>;\n try {\n stat = await fs.stat(path.join(rootDir, filePath));\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n continue;\n }\n throw error;\n }\n\n if (!stat.isFile()) {\n continue;\n }\n\n const extension = path.posix.extname(filePath);\n const kind = fileKind(filePath, ignore);\n\n files.push({\n path: filePath,\n kind,\n language: languageByExtension.get(extension) ?? null,\n });\n\n if (kind === \"test\") {\n tests.push({\n path: filePath,\n targetHints: targetHintsForTest(filePath),\n });\n }\n\n if (kind === \"doc\") {\n const source = await fs.readFile(path.join(rootDir, filePath), \"utf8\");\n const parsed = matter(source);\n const markdown = parseMarkdownDocument(parsed.content);\n const title = markdown.headings.find((heading) => heading.depth === 1)?.text ?? null;\n const sourceOfTruth = Array.isArray(parsed.data.source_of_truth)\n ? parsed.data.source_of_truth.filter((entry: unknown): entry is string => typeof entry === \"string\")\n : [];\n\n docs.push({\n path: filePath,\n title,\n docType: typeof parsed.data.doc_type === \"string\" ? parsed.data.doc_type : null,\n truthKind: typeof parsed.data.truth_kind === \"string\" ? parsed.data.truth_kind : null,\n sourceOfTruth: sourceOfTruth.sort(),\n });\n }\n }\n\n return {\n files: files.sort((left, right) => left.path.localeCompare(right.path)),\n docs: docs.sort((left, right) => left.path.localeCompare(right.path)),\n tests: tests.sort((left, right) => left.path.localeCompare(right.path)),\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport fg from \"fast-glob\";\n\nimport type { PackageMetadata } from \"./types.js\";\n\nconst packageManagerFor = async (\n rootDir: string,\n packageDir: string,\n): Promise<PackageMetadata[\"manager\"]> => {\n const lockfiles: Array<[string, PackageMetadata[\"manager\"]]> = [\n [\"package-lock.json\", \"npm\"],\n [\"pnpm-lock.yaml\", \"pnpm\"],\n [\"yarn.lock\", \"yarn\"],\n [\"bun.lockb\", \"bun\"],\n [\"bun.lock\", \"bun\"],\n ];\n\n for (const [lockfile, manager] of lockfiles) {\n try {\n await fs.access(path.join(rootDir, packageDir, lockfile));\n return manager;\n } catch {\n continue;\n }\n }\n\n return \"npm\";\n};\n\nexport const discoverPackageMetadata = async (rootDir: string): Promise<PackageMetadata[]> => {\n const packageFiles = await fg([\"package.json\", \"*/package.json\", \"packages/*/package.json\"], {\n cwd: rootDir,\n onlyFiles: true,\n ignore: [\"node_modules/**\", \"dist/**\", \"build/**\"],\n followSymbolicLinks: false,\n });\n const packages: PackageMetadata[] = [];\n\n for (const packageFile of packageFiles.sort()) {\n const packageDir = path.posix.dirname(packageFile) === \".\" ? \"\" : path.posix.dirname(packageFile);\n const raw = JSON.parse(await fs.readFile(path.join(rootDir, packageFile), \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n private?: unknown;\n scripts?: unknown;\n };\n const scripts =\n raw.scripts && typeof raw.scripts === \"object\" ? Object.keys(raw.scripts).sort() : [];\n\n packages.push({\n path: packageFile,\n manager: await packageManagerFor(rootDir, packageDir),\n name: typeof raw.name === \"string\" ? raw.name : null,\n version: typeof raw.version === \"string\" ? raw.version : null,\n private: typeof raw.private === \"boolean\" ? raw.private : null,\n scripts,\n });\n }\n\n return packages;\n};\n","import { loadConfig } from \"../config/load.js\";\nimport { resolveAreaRouting } from \"../routing/area-resolver.js\";\nimport { resolveTruthDocsRoot } from \"../truth/docs.js\";\nimport type { RouteMap } from \"./types.js\";\n\nexport const buildRouteMap = async (rootDir: string): Promise<RouteMap> => {\n const loadResult = await loadConfig(rootDir);\n\n if (!loadResult.config) {\n return {\n schemaVersion: \"route-map/v0\",\n routes: [],\n diagnostics: loadResult.diagnostics,\n };\n }\n\n const routing = await resolveAreaRouting(rootDir, {\n rootIndex: loadResult.config.docs.routing.rootIndex,\n areaFilesRoot: loadResult.config.docs.routing.areaFilesRoot,\n truthDocsRoot: resolveTruthDocsRoot(loadResult.config),\n });\n\n return {\n schemaVersion: \"route-map/v0\",\n routes: routing.areas\n .map((area) => ({\n id: area.id,\n name: area.name,\n key: area.key,\n sourcePath: area.sourcePath,\n parentName: area.parentName,\n codeSurface: [...area.codeSurface].sort(),\n truthDocs: [...area.truthDocuments].sort(),\n updateTruthWhen: [...area.updateTruthWhen],\n }))\n .sort((left, right) => left.key.localeCompare(right.key)),\n diagnostics: routing.diagnostics,\n };\n};\n","import ts from \"typescript\";\n\nimport type { ExportEntry, ImportEdge, PublicSymbolEntry } from \"./types.js\";\n\nexport type TypeScriptSourceAnalysis = {\n imports: ImportEdge[];\n exports: ExportEntry[];\n publicSymbols: PublicSymbolEntry[];\n};\n\nconst sortStrings = (values: string[]): string[] => [...new Set(values)].sort();\n\nconst hasExportModifier = (node: ts.Node): boolean => {\n return Boolean(\n ts.canHaveModifiers(node) &&\n ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword),\n );\n};\n\nconst declarationName = (node: { name?: ts.PropertyName | ts.BindingName }): string | null => {\n if (!node.name || !ts.isIdentifier(node.name)) {\n return null;\n }\n\n return node.name.text;\n};\n\nconst addExport = (\n exports: ExportEntry[],\n publicSymbols: PublicSymbolEntry[],\n path: string,\n name: string | null,\n kind: ExportEntry[\"kind\"],\n): void => {\n if (!name) {\n return;\n }\n\n const entry = { path, name, kind };\n exports.push(entry);\n publicSymbols.push(entry);\n};\n\nexport const analyzeTypeScriptSource = (\n path: string,\n source: string,\n): TypeScriptSourceAnalysis => {\n const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true);\n const imports: ImportEdge[] = [];\n const exports: ExportEntry[] = [];\n const publicSymbols: PublicSymbolEntry[] = [];\n\n for (const statement of sourceFile.statements) {\n if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {\n const imported: string[] = [];\n const clause = statement.importClause;\n\n if (clause?.name) {\n imported.push(\"default\");\n }\n if (clause?.namedBindings && ts.isNamespaceImport(clause.namedBindings)) {\n imported.push(\"*\");\n }\n if (clause?.namedBindings && ts.isNamedImports(clause.namedBindings)) {\n for (const element of clause.namedBindings.elements) {\n imported.push(element.propertyName?.text ?? element.name.text);\n }\n }\n\n imports.push({\n from: path,\n specifier: statement.moduleSpecifier.text,\n imported: sortStrings(imported),\n });\n continue;\n }\n\n if (ts.isExportDeclaration(statement)) {\n if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {\n for (const element of statement.exportClause.elements) {\n addExport(exports, publicSymbols, path, element.name.text, \"re-export\");\n }\n }\n continue;\n }\n\n if (ts.isFunctionDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"function\");\n continue;\n }\n\n if (ts.isClassDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"class\");\n continue;\n }\n\n if (ts.isInterfaceDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"interface\");\n continue;\n }\n\n if (ts.isTypeAliasDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"type\");\n continue;\n }\n\n if (ts.isEnumDeclaration(statement) && hasExportModifier(statement)) {\n addExport(exports, publicSymbols, path, declarationName(statement), \"enum\");\n continue;\n }\n\n if (ts.isVariableStatement(statement) && hasExportModifier(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n addExport(exports, publicSymbols, path, declarationName(declaration), \"const\");\n }\n }\n }\n\n return {\n imports: imports.sort((left, right) => left.specifier.localeCompare(right.specifier)),\n exports: exports.sort((left, right) => left.name.localeCompare(right.name)),\n publicSymbols: publicSymbols.sort((left, right) => left.name.localeCompare(right.name)),\n };\n};\n","import { execa } from \"execa\";\n\nimport { getUncommittedChanges } from \"../git/changes.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport type { ChangedFileStatus, ImpactFile } from \"./types.js\";\n\nconst normalizePath = (filePath: string): string => filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\//u, \"\");\n\nconst statusForCode = (code: string): ChangedFileStatus => {\n if (code.startsWith(\"A\")) return \"added\";\n if (code.startsWith(\"D\")) return \"deleted\";\n if (code.startsWith(\"R\")) return \"renamed\";\n if (code.startsWith(\"C\")) return \"copied\";\n if (code.startsWith(\"T\")) return \"type-changed\";\n return \"modified\";\n};\n\nconst mergeFile = (files: Map<string, ImpactFile>, next: ImpactFile): void => {\n const existing = files.get(next.path);\n if (!existing) {\n files.set(next.path, next);\n return;\n }\n\n files.set(next.path, {\n ...existing,\n status:\n existing.status === \"deleted\" || existing.status === \"renamed\" ? existing.status : next.status,\n previousPath: existing.previousPath ?? next.previousPath,\n staged: existing.staged || next.staged,\n unstaged: existing.unstaged || next.unstaged,\n untracked: existing.untracked || next.untracked,\n deleted: existing.deleted || next.deleted,\n });\n};\n\nexport type ChangedFilesResult = {\n files: ImpactFile[];\n diagnostics: Diagnostic[];\n};\nexport const getChangedFiles = async (cwd: string, base: string): Promise<ChangedFilesResult> => {\n const repository = await getGitRepository(cwd);\n const files = new Map<string, ImpactFile>();\n const diagnostics: Diagnostic[] = [];\n let diff = await execa(\"git\", [\"diff\", \"--name-status\", \"--find-renames\", `${base}...HEAD`], {\n cwd: repository.worktreePath,\n reject: false,\n });\n\n if ((diff.exitCode ?? 1) !== 0) {\n diff = await execa(\"git\", [\"diff\", \"--name-status\", \"--find-renames\", base, \"HEAD\"], {\n cwd: repository.worktreePath,\n reject: false,\n });\n }\n\n if ((diff.exitCode ?? 1) === 0) {\n for (const line of diff.stdout.split(\"\\n\").filter(Boolean)) {\n const [rawStatus, rawPath, rawNewPath] = line.split(\"\\t\");\n const filePath = normalizePath(rawNewPath ?? rawPath);\n const previousPath = rawNewPath && rawStatus.startsWith(\"R\") ? normalizePath(rawPath) : undefined;\n\n mergeFile(files, {\n path: filePath,\n previousPath,\n status: statusForCode(rawStatus),\n staged: false,\n unstaged: false,\n untracked: false,\n deleted: rawStatus.startsWith(\"D\"),\n });\n }\n } else {\n diagnostics.push({\n category: \"impact\",\n severity: \"error\",\n message: `Unable to compare base ref ${base} to HEAD.`,\n });\n }\n\n for (const change of await getUncommittedChanges(repository.worktreePath)) {\n mergeFile(files, {\n path: change.path,\n status: change.untracked ? \"added\" : change.deleted ? \"deleted\" : \"modified\",\n staged: change.staged,\n unstaged: change.unstaged,\n untracked: change.untracked,\n deleted: change.deleted,\n });\n }\n\n return {\n files: [...files.values()].sort((left, right) => left.path.localeCompare(right.path)),\n diagnostics,\n };\n};\n\nexport const readBaseFile = async (\n cwd: string,\n base: string,\n filePath: string,\n): Promise<string | null> => {\n const repository = await getGitRepository(cwd);\n const result = await execa(\"git\", [\"show\", `${base}:${filePath}`], {\n cwd: repository.worktreePath,\n reject: false,\n });\n\n return (result.exitCode ?? 1) === 0 ? result.stdout : null;\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { execa } from \"execa\";\n\nimport { getGitRepository } from \"./repository.js\";\n\nexport type UncommittedChange = {\n path: string;\n staged: boolean;\n unstaged: boolean;\n untracked: boolean;\n deleted: boolean;\n};\n\nconst normalizePath = (filePath: string): string => {\n return filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\//u, \"\");\n};\n\nconst listChangedPaths = async (cwd: string, args: string[]): Promise<string[]> => {\n const result = await execa(\"git\", args, { cwd });\n\n return result.stdout\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => normalizePath(line));\n};\n\nconst pathExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n};\n\nconst getOrCreateChange = (\n changesByPath: Map<string, UncommittedChange>,\n filePath: string,\n): UncommittedChange => {\n const existingChange = changesByPath.get(filePath);\n\n if (existingChange) {\n return existingChange;\n }\n\n const nextChange: UncommittedChange = {\n path: filePath,\n staged: false,\n unstaged: false,\n untracked: false,\n deleted: false,\n };\n\n changesByPath.set(filePath, nextChange);\n\n return nextChange;\n};\n\nexport const getUncommittedChanges = async (cwd: string): Promise<UncommittedChange[]> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const [stagedPaths, unstagedPaths, untrackedPaths, stagedDeletedPaths, unstagedDeletedPaths] =\n await Promise.all([\n listChangedPaths(rootDir, [\"diff\", \"--name-only\", \"--cached\", \"--diff-filter=ACDMRTUXB\"]),\n listChangedPaths(rootDir, [\"diff\", \"--name-only\", \"--diff-filter=ACDMRTUXB\"]),\n listChangedPaths(rootDir, [\"ls-files\", \"--others\", \"--exclude-standard\"]),\n listChangedPaths(rootDir, [\"diff\", \"--name-only\", \"--cached\", \"--diff-filter=D\"]),\n listChangedPaths(rootDir, [\"diff\", \"--name-only\", \"--diff-filter=D\"]),\n ]);\n const changesByPath = new Map<string, UncommittedChange>();\n\n for (const stagedPath of stagedPaths) {\n getOrCreateChange(changesByPath, stagedPath).staged = true;\n }\n\n for (const unstagedPath of unstagedPaths) {\n getOrCreateChange(changesByPath, unstagedPath).unstaged = true;\n }\n\n for (const untrackedPath of untrackedPaths) {\n getOrCreateChange(changesByPath, untrackedPath).untracked = true;\n }\n\n const deletedPathCandidates = new Set([...stagedDeletedPaths, ...unstagedDeletedPaths]);\n\n for (const deletedPath of deletedPathCandidates) {\n const change = getOrCreateChange(changesByPath, deletedPath);\n change.deleted = !(await pathExists(path.join(rootDir, deletedPath)));\n }\n\n return Array.from(changesByPath.values()).sort((left, right) => {\n return left.path.localeCompare(right.path);\n });\n};","import fs from \"node:fs/promises\";\nimport fg from \"fast-glob\";\n\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport { hashText } from \"../markdown/hash.js\";\nimport { isJavaScriptLikePath } from \"../repo-index/file-tree.js\";\nimport { analyzeTypeScriptSource } from \"../repo-index/typescript-symbols.js\";\nimport { parseEvidenceReferences } from \"./parse.js\";\nimport type { EvidenceReference } from \"./types.js\";\n\nconst pathExists = async (filePath: string): Promise<boolean> => {\n try {\n await fs.access(filePath);\n return true;\n } catch {\n return false;\n }\n};\n\nconst diagnosticFor = (reference: EvidenceReference, message: string): Diagnostic => ({\n category: \"freshness\",\n severity: \"error\",\n message,\n file: reference.truthDocPath,\n data: {\n reference: reference.path,\n source: reference.source,\n },\n});\n\nconst isGlobReference = (referencePath: string): boolean => /[*?[\\]{}()]/u.test(referencePath);\n\nconst validateGlob = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic | null> => {\n if (reference.path.startsWith(\"../\") || reference.path.startsWith(\"/\")) {\n return diagnosticFor(reference, `Referenced file pattern ${reference.path} must stay inside the repository root.`);\n }\n const matches = await fg(reference.path, {\n cwd: rootDir,\n dot: true,\n onlyFiles: true,\n followSymbolicLinks: false,\n });\n return matches.length > 0\n ? null\n : diagnosticFor(reference, `Referenced file pattern ${reference.path} does not match any file.`);\n};\n\nconst validateSymbol = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic | null> => {\n if (!reference.symbol || !isJavaScriptLikePath(reference.path)) {\n return null;\n }\n\n const source = await fs.readFile(resolveRepoPath(rootDir, reference.path), \"utf8\");\n const analysis = analyzeTypeScriptSource(reference.path, source);\n const hasSymbol = analysis.publicSymbols.some((symbol) => symbol.name === reference.symbol);\n\n return hasSymbol\n ? null\n : diagnosticFor(reference, `Evidence symbol ${reference.symbol} was not found in ${reference.path}.`);\n};\n\nconst validateHash = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic | null> => {\n if (!reference.contentHash) {\n return null;\n }\n if (!reference.contentHash.startsWith(\"sha256:\")) {\n return diagnosticFor(reference, `Evidence hash for ${reference.path} must use sha256:.`);\n }\n\n const source = await fs.readFile(resolveRepoPath(rootDir, reference.path), \"utf8\");\n const lines = source.split(\"\\n\");\n const startLine = reference.startLine ?? 1;\n const endLine = reference.endLine ?? lines.length;\n\n if (startLine < 1 || endLine < startLine || endLine > lines.length) {\n return diagnosticFor(reference, `Evidence line span for ${reference.path} is outside the file.`);\n }\n\n const actualHash = `sha256:${hashText(lines.slice(startLine - 1, endLine).join(\"\\n\"))}`;\n\n return actualHash === reference.contentHash\n ? null\n : diagnosticFor(reference, `Evidence hash for ${reference.path} is stale.`);\n};\n\nconst validateLineSpan = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic | null> => {\n if (reference.startLine === undefined && reference.endLine === undefined) {\n return null;\n }\n\n const source = await fs.readFile(resolveRepoPath(rootDir, reference.path), \"utf8\");\n const lines = source.split(\"\\n\");\n const startLine = reference.startLine ?? 1;\n const endLine = reference.endLine ?? lines.length;\n\n return startLine < 1 || endLine < startLine || endLine > lines.length\n ? diagnosticFor(reference, `Evidence line span for ${reference.path} is outside the file.`)\n : null;\n};\n\nconst validateReference = async (\n rootDir: string,\n reference: EvidenceReference,\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n\n try {\n if (isGlobReference(reference.path)) {\n const globDiagnostic = await validateGlob(rootDir, reference);\n return globDiagnostic ? [globDiagnostic] : [];\n }\n\n const absolutePath = resolveRepoPath(rootDir, reference.path);\n await assertRepoContainment(rootDir, absolutePath);\n\n if (!(await pathExists(absolutePath))) {\n diagnostics.push(diagnosticFor(reference, `Referenced file ${reference.path} does not exist.`));\n return diagnostics;\n }\n\n const symbolDiagnostic = await validateSymbol(rootDir, reference);\n if (symbolDiagnostic) {\n diagnostics.push(symbolDiagnostic);\n }\n\n const lineSpanDiagnostic = await validateLineSpan(rootDir, reference);\n if (lineSpanDiagnostic) {\n diagnostics.push(lineSpanDiagnostic);\n } else {\n const hashDiagnostic = await validateHash(rootDir, reference);\n if (hashDiagnostic) {\n diagnostics.push(hashDiagnostic);\n }\n }\n } catch {\n diagnostics.push(diagnosticFor(reference, `Referenced file ${reference.path} must stay inside the repository root.`));\n }\n\n return diagnostics;\n};\n\nexport const validateEvidenceReferences = async (\n rootDir: string,\n truthDocPaths: string[],\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n\n for (const truthDocPath of [...truthDocPaths].sort()) {\n const references = await parseEvidenceReferences(rootDir, truthDocPath);\n\n for (const reference of references) {\n diagnostics.push(...(await validateReference(rootDir, reference)));\n }\n }\n\n return diagnostics;\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport matter from \"gray-matter\";\nimport { parse } from \"yaml\";\n\nimport type { EvidenceReference } from \"./types.js\";\n\nconst evidenceBlockPattern = /```ya?ml\\s*\\n([\\s\\S]*?)```/giu;\n\nconst repoRootPrefixes = [\".codex/\", \".github/\", \".truthmark/\", \"docs/\", \"src/\", \"tests/\"];\n\nconst normalizeReferencePath = (truthDocPath: string, referencePath: string): string => {\n const strippedPath = referencePath.split(\"#\")[0]?.trim() ?? \"\";\n const isRepoRelative = repoRootPrefixes.some((prefix) => strippedPath.startsWith(prefix));\n\n if (!isRepoRelative && (strippedPath.startsWith(\".\") || !strippedPath.includes(\"/\"))) {\n return path.posix.normalize(path.posix.join(path.posix.dirname(truthDocPath), strippedPath));\n }\n\n return path.posix.normalize(strippedPath);\n};\n\nconst toEvidenceReference = (\n truthDocPath: string,\n raw: unknown,\n): EvidenceReference | null => {\n if (!raw || typeof raw !== \"object\" || !(\"path\" in raw) || typeof raw.path !== \"string\") {\n return null;\n }\n\n return {\n truthDocPath,\n path: normalizeReferencePath(truthDocPath, raw.path),\n symbol: \"symbol\" in raw && typeof raw.symbol === \"string\" ? raw.symbol : undefined,\n startLine: \"start_line\" in raw && typeof raw.start_line === \"number\" ? raw.start_line : undefined,\n endLine: \"end_line\" in raw && typeof raw.end_line === \"number\" ? raw.end_line : undefined,\n contentHash:\n \"content_hash\" in raw && typeof raw.content_hash === \"string\" ? raw.content_hash : undefined,\n source: \"evidence-block\",\n };\n};\n\nexport const parseEvidenceReferences = async (\n rootDir: string,\n truthDocPath: string,\n): Promise<EvidenceReference[]> => {\n const source = await fs.readFile(path.join(rootDir, truthDocPath), \"utf8\");\n const parsed = matter(source);\n const references: EvidenceReference[] = [];\n const sourceOfTruth = Array.isArray(parsed.data.source_of_truth) ? parsed.data.source_of_truth : [];\n\n for (const entry of sourceOfTruth) {\n if (typeof entry !== \"string\") {\n continue;\n }\n\n references.push({\n truthDocPath,\n path: normalizeReferencePath(truthDocPath, entry),\n source: \"frontmatter\",\n });\n }\n\n for (const match of parsed.content.matchAll(evidenceBlockPattern)) {\n const block = parse(match[1] ?? \"\") as unknown;\n const rawEvidence =\n block && typeof block === \"object\" && \"evidence\" in block\n ? (block as { evidence?: unknown }).evidence\n : null;\n\n if (!Array.isArray(rawEvidence)) {\n continue;\n }\n\n for (const rawReference of rawEvidence) {\n const reference = toEvidenceReference(truthDocPath, rawReference);\n if (reference) {\n references.push(reference);\n }\n }\n }\n\n return references;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { buildImpactSet } from \"../impact/build.js\";\nimport type { ImpactSet } from \"../impact/types.js\";\nimport { validateEvidenceReferences } from \"../evidence/validate.js\";\n\nexport type FreshnessCheckResult = {\n diagnostics: Diagnostic[];\n impactSet: ImpactSet;\n};\n\nexport const checkFreshness = async (\n rootDir: string,\n _config: TruthmarkConfig,\n truthDocumentPaths: string[],\n base: string,\n): Promise<FreshnessCheckResult> => {\n const impactSet = await buildImpactSet(rootDir, { base });\n const diagnostics: Diagnostic[] = [...(await validateEvidenceReferences(rootDir, truthDocumentPaths))];\n\n for (const diagnostic of impactSet.diagnostics) {\n if (diagnostic.category !== \"impact\") {\n continue;\n }\n\n diagnostics.push({\n ...diagnostic,\n category: \"freshness\",\n message: diagnostic.message.replace(\"not mapped to a Truthmark route\", \"not routed to truth ownership\"),\n });\n }\n\n return {\n diagnostics,\n impactSet,\n };\n};\n","import type { CommandResult } from \"../output/diagnostic.js\";\nimport { loadConfig } from \"../config/load.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport { getBranchScopeData } from \"./branch-scope.js\";\nimport { checkAuthority } from \"./authority.js\";\nimport { checkFrontmatter } from \"./frontmatter.js\";\nimport { checkLinks } from \"./links.js\";\nimport { checkAreas } from \"./areas.js\";\nimport { checkDecisionSections } from \"./decisions.js\";\nimport { checkGeneratedSurfaces } from \"./generated-surfaces.js\";\nimport { checkFreshness } from \"../freshness/check.js\";\n\nexport type CheckOptions = {\n base?: string;\n};\n\nconst summarizeDiagnostics = (diagnostics: CommandResult[\"diagnostics\"]): string => {\n const errorCount = diagnostics.filter((diagnostic) => diagnostic.severity === \"error\").length;\n const reviewCount = diagnostics.filter((diagnostic) => diagnostic.severity === \"review\").length;\n\n if (diagnostics.length === 0) {\n return \"Truthmark check completed with no diagnostics.\";\n }\n\n return `Truthmark check completed with ${errorCount} error diagnostics and ${reviewCount} review diagnostics.`;\n};\n\nexport const runCheck = async (cwd: string, options: CheckOptions = {}): Promise<CommandResult> => {\n const repository = await getGitRepository(cwd);\n const rootDir = repository.worktreePath;\n const branchScope = await getBranchScopeData(rootDir);\n const loadResult = await loadConfig(rootDir);\n\n if (!loadResult.config) {\n return {\n command: \"check\",\n summary: summarizeDiagnostics(loadResult.diagnostics),\n diagnostics: loadResult.diagnostics,\n data: {\n branchScope,\n },\n };\n }\n\n const authority = await checkAuthority(rootDir, loadResult.config);\n const areas = await checkAreas(rootDir, loadResult.config);\n const markdownPaths = [...new Set([...authority.paths, ...areas.truthDocumentPaths])];\n const frontmatter = await checkFrontmatter(\n rootDir,\n loadResult.config,\n markdownPaths,\n areas.truthDocumentEntries,\n );\n const links = await checkLinks(rootDir, markdownPaths);\n const decisionSections = await checkDecisionSections(\n rootDir,\n loadResult.config,\n markdownPaths,\n areas.truthDocumentEntries,\n );\n const generatedSurfaces = await checkGeneratedSurfaces(rootDir, loadResult.config);\n const freshness = options.base\n ? await checkFreshness(rootDir, loadResult.config, areas.truthDocumentPaths, options.base)\n : null;\n const diagnostics = [\n ...loadResult.diagnostics,\n ...authority.diagnostics,\n ...frontmatter,\n ...links,\n ...areas.diagnostics,\n ...decisionSections,\n ...generatedSurfaces,\n ...(freshness?.diagnostics ?? []),\n ];\n const truthVisibility = {\n routePrecision: areas.routePrecision,\n unmappedSurfaceCount: diagnostics.filter((diagnostic) => diagnostic.category === \"coverage\")\n .length,\n staleGeneratedSurfaceCount: new Set(\n generatedSurfaces.map((diagnostic) => diagnostic.file).filter(Boolean),\n ).size,\n syncCompletenessIssueCount: diagnostics.filter(\n (diagnostic) =>\n diagnostic.category === \"doc-structure\" || diagnostic.category === \"generated-surface\",\n ).length,\n topologyPressureCount: areas.topologyPressureCount,\n freshnessDiagnosticCount: freshness?.diagnostics.length ?? 0,\n };\n\n return {\n command: \"check\",\n summary: summarizeDiagnostics(diagnostics),\n diagnostics,\n data: {\n branchScope,\n truthVisibility,\n ...(freshness ? { impactSet: freshness.impactSet } : {}),\n },\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport fg from \"fast-glob\";\n\nimport { buildImpactSet } from \"../impact/build.js\";\nimport type { ImpactSet } from \"../impact/types.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { buildRepoIndex } from \"../repo-index/build.js\";\nimport type { RepoDocEntry, RouteMap } from \"../repo-index/types.js\";\nimport type {\n ContextDocument,\n ContextPack,\n ContextPackOptions,\n ContextSourceFile,\n} from \"./types.js\";\n\nconst uniqueSorted = (values: string[]): string[] => [...new Set(values)].sort();\n\ntype ContextRoute = {\n codeSurface: string[];\n};\n\nconst repoRootPrefixes = [\".codex/\", \".github/\", \".truthmark/\", \"docs/\", \"src/\", \"tests/\"];\n\nconst isGlobReference = (referencePath: string): boolean => /[*?[\\]{}()]/u.test(referencePath);\n\nconst normalizeDocReferencePath = (docPath: string, referencePath: string): string | null => {\n const strippedPath = referencePath.split(\"#\")[0]?.trim() ?? \"\";\n if (strippedPath.length === 0 || strippedPath.startsWith(\"/\")) {\n return null;\n }\n\n const isRepoRelative = repoRootPrefixes.some((prefix) => strippedPath.startsWith(prefix));\n const normalized = isRepoRelative\n ? path.posix.normalize(strippedPath)\n : path.posix.normalize(path.posix.join(path.posix.dirname(docPath), strippedPath));\n\n return normalized === \"..\" || normalized.startsWith(\"../\") ? null : normalized;\n};\n\nconst readIfExists = async (rootDir: string, filePath: string): Promise<string | null> => {\n try {\n return await fs.readFile(path.join(rootDir, filePath), \"utf8\");\n } catch {\n return null;\n }\n};\n\nconst boundedContent = (\n filePath: string,\n content: string,\n warnings: Diagnostic[],\n): ContextSourceFile => {\n const lines = content.split(\"\\n\");\n\n if (lines.length <= 200) {\n return { path: filePath, content, truncated: false };\n }\n\n warnings.push({\n category: \"context-pack\",\n severity: \"review\",\n message: `Context source file ${filePath} was truncated to fit ContextPack v0 bounds.`,\n file: filePath,\n });\n\n return {\n path: filePath,\n content: [...lines.slice(0, 80), \"...\", ...lines.slice(-40)].join(\"\\n\"),\n truncated: true,\n };\n};\n\nconst documentsFor = async (\n rootDir: string,\n paths: string[],\n): Promise<ContextDocument[]> => {\n const documents: ContextDocument[] = [];\n\n for (const filePath of uniqueSorted(paths)) {\n const content = await readIfExists(rootDir, filePath);\n if (content !== null) {\n documents.push({ path: filePath, content });\n }\n }\n\n return documents;\n};\n\nconst sourceFilesFor = async (\n rootDir: string,\n paths: string[],\n warnings: Diagnostic[],\n): Promise<ContextSourceFile[]> => {\n const sourceFiles: ContextSourceFile[] = [];\n\n for (const filePath of uniqueSorted(paths)) {\n const content = await readIfExists(rootDir, filePath);\n if (content !== null) {\n sourceFiles.push(boundedContent(filePath, content, warnings));\n }\n }\n\n return sourceFiles;\n};\n\nconst sourceOfTruthPathsFor = async (\n rootDir: string,\n docs: RepoDocEntry[],\n truthDocPaths: string[],\n): Promise<string[]> => {\n const selectedTruthDocs = new Set(truthDocPaths);\n const sourcePaths: string[] = [];\n\n for (const doc of docs) {\n if (!selectedTruthDocs.has(doc.path)) {\n continue;\n }\n\n for (const referencePath of doc.sourceOfTruth) {\n const normalizedPath = normalizeDocReferencePath(doc.path, referencePath);\n if (!normalizedPath) {\n continue;\n }\n if (isGlobReference(normalizedPath)) {\n sourcePaths.push(\n ...(await fg(normalizedPath, {\n cwd: rootDir,\n dot: true,\n onlyFiles: true,\n followSymbolicLinks: false,\n })),\n );\n } else {\n sourcePaths.push(normalizedPath);\n }\n }\n }\n\n return uniqueSorted(sourcePaths);\n};\n\nconst writePathsFor = (\n workflow: ContextPackOptions[\"workflow\"],\n truthDocs: string[],\n routes: ContextRoute[],\n): string[] => {\n if (workflow === \"truth-sync\") {\n return uniqueSorted([\"docs/truthmark/areas.md\", ...truthDocs]);\n }\n\n if (workflow === \"truth-document\") {\n return uniqueSorted([\"docs/truthmark/areas.md\", ...truthDocs]);\n }\n\n return uniqueSorted(routes.flatMap((route) => route.codeSurface));\n};\n\nconst testCommandsFor = (affectedTests: string[]): string[] => {\n return affectedTests.length === 0\n ? [\"npm test\"]\n : [`npm test -- ${affectedTests.join(\" \")}`];\n};\n\nexport const buildContextPack = async (\n cwd: string,\n options: ContextPackOptions,\n): Promise<ContextPack> => {\n const repoIndex = await buildRepoIndex(cwd);\n const rootDir = repoIndex.repository.root;\n const impactSet: ImpactSet | null = options.base\n ? await buildImpactSet(rootDir, { base: options.base })\n : null;\n const routeMap: RouteMap = impactSet ? repoIndex.routeMap : repoIndex.routeMap;\n const warnings: Diagnostic[] = [];\n const truthDocPaths =\n impactSet?.affectedTruthDocs ??\n (options.workflow === \"truth-realize\" ? [] : routeMap.routes.flatMap((route) => route.truthDocs));\n const contextRoutes: ContextRoute[] =\n impactSet?.affectedRoutes ?? (options.workflow === \"truth-realize\" ? [] : routeMap.routes);\n if (options.workflow === \"truth-realize\" && !impactSet) {\n warnings.push({\n category: \"context-pack\",\n severity: \"review\",\n message: \"truth-realize requires --base to derive bounded allowed write paths.\",\n });\n }\n const sourceOfTruthPaths = await sourceOfTruthPathsFor(rootDir, repoIndex.docs, truthDocPaths);\n const sourceFilePaths = uniqueSorted([\n ...(impactSet?.changedFiles.filter((file) => !file.deleted).map((file) => file.path) ?? []),\n ...sourceOfTruthPaths,\n ]);\n\n return {\n schemaVersion: \"context-pack/v0\",\n workflow: options.workflow,\n base: options.base ?? null,\n impactSet,\n routeMap,\n allowedWritePaths: writePathsFor(options.workflow, truthDocPaths, contextRoutes),\n truthDocs: await documentsFor(rootDir, truthDocPaths),\n sourceFiles: await sourceFilesFor(rootDir, sourceFilePaths, warnings),\n testCommands: testCommandsFor(impactSet?.affectedTests ?? []),\n warnings,\n };\n};\n","import type { ContextPack } from \"./types.js\";\n\nexport const renderContextPackMarkdown = (pack: ContextPack): string => {\n const lines = [\n `# Truthmark ContextPack (${pack.workflow})`,\n \"\",\n `Schema: ${pack.schemaVersion}`,\n `Base: ${pack.base ?? \"none\"}`,\n \"\",\n \"## Allowed Write Paths\",\n ...pack.allowedWritePaths.map((filePath) => `- ${filePath}`),\n \"\",\n \"## Truth Docs\",\n ...pack.truthDocs.map((doc) => `- ${doc.path}`),\n \"\",\n \"## Source Files\",\n ...pack.sourceFiles.map((file) => `- ${file.path}${file.truncated ? \" (truncated)\" : \"\"}`),\n \"\",\n \"## Test Commands\",\n ...pack.testCommands.map((command) => `- ${command}`),\n ];\n\n return `${lines.join(\"\\n\")}\\n`;\n};\n","import { runConfig as runRepositoryConfig, type ConfigCommandOptions } from \"../config/command.js\";\nimport { runInit as runRepositoryInit } from \"../init/init.js\";\nimport { runCheck as runRepositoryCheck } from \"../checks/check.js\";\nimport type { CommandResult } from \"../output/diagnostic.js\";\nimport { buildImpactSet } from \"../impact/build.js\";\nimport { buildContextPack } from \"../context-pack/build.js\";\nimport { renderContextPackMarkdown } from \"../context-pack/render.js\";\nimport type { ContextPackWorkflow } from \"../context-pack/types.js\";\nimport fs from \"node:fs/promises\";\n\nimport {\n validateTruthDocumentReportText,\n validateTruthSyncReportText,\n validateWriteLeaseText,\n type WorkflowHelperValidationResult,\n} from \"../agents/workflow-helper-validation.js\";\nimport { buildRepoIndex } from \"../repo-index/build.js\";\n\nexport const runConfig = async (options: ConfigCommandOptions): Promise<CommandResult> => {\n return runRepositoryConfig(process.cwd(), options);\n};\n\nexport const runInit = async (): Promise<CommandResult> => {\n return runRepositoryInit(process.cwd());\n};\n\nexport const runCheck = async (options: { base?: string } = {}): Promise<CommandResult> => {\n return runRepositoryCheck(process.cwd(), options);\n};\n\nexport const runIndex = async (): Promise<CommandResult> => {\n const repoIndex = await buildRepoIndex(process.cwd());\n const errorCount = repoIndex.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\").length;\n const reviewCount = repoIndex.diagnostics.filter((diagnostic) => diagnostic.severity === \"review\").length;\n\n return {\n command: \"index\",\n summary: `Truthmark index completed with ${errorCount} error diagnostics and ${reviewCount} review diagnostics.`,\n diagnostics: repoIndex.diagnostics,\n data: {\n repoIndex,\n routeMap: repoIndex.routeMap,\n },\n };\n};\n\nexport const runImpact = async (options: { base?: string }): Promise<CommandResult> => {\n if (!options.base) {\n return {\n command: \"impact\",\n summary: \"Truthmark impact requires --base.\",\n diagnostics: [\n {\n category: \"impact\",\n severity: \"error\",\n message: \"truthmark impact requires --base <ref>.\",\n },\n ],\n };\n }\n\n const impactSet = await buildImpactSet(process.cwd(), { base: options.base });\n const errorCount = impactSet.diagnostics.filter((diagnostic) => diagnostic.severity === \"error\").length;\n const reviewCount = impactSet.diagnostics.filter((diagnostic) => diagnostic.severity === \"review\").length;\n\n return {\n command: \"impact\",\n summary: `Truthmark impact completed with ${errorCount} error diagnostics and ${reviewCount} review diagnostics.`,\n diagnostics: impactSet.diagnostics,\n data: {\n impactSet,\n },\n };\n};\n\nconst isContextPackWorkflow = (value: unknown): value is ContextPackWorkflow => {\n return value === \"truth-sync\" || value === \"truth-document\" || value === \"truth-realize\";\n};\n\nconst isContextPackFormat = (value: unknown): value is \"json\" | \"markdown\" | undefined => {\n return value === undefined || value === \"json\" || value === \"markdown\";\n};\n\nconst readHelperFile = async (filePath: string, helper: string): Promise<string | WorkflowHelperValidationResult> => {\n try {\n return await fs.readFile(filePath, \"utf8\");\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return { ok: false, helper, errors: [`could not read file: ${message}`] };\n }\n};\n\nexport const runValidateSyncReport = async (\n reportFile: string,\n): Promise<WorkflowHelperValidationResult> => {\n const text = await readHelperFile(reportFile, \"validate-sync-report\");\n return typeof text === \"string\" ? validateTruthSyncReportText(text) : text;\n};\n\nexport const runValidateDocumentReport = async (\n reportFile: string,\n): Promise<WorkflowHelperValidationResult> => {\n const text = await readHelperFile(reportFile, \"validate-document-report\");\n return typeof text === \"string\" ? validateTruthDocumentReportText(text) : text;\n};\n\nexport const runValidateWriteLease = async (\n leaseFile: string,\n changedFilesFile: string,\n): Promise<WorkflowHelperValidationResult> => {\n const leaseText = await readHelperFile(leaseFile, \"validate-write-lease\");\n if (typeof leaseText !== \"string\") {\n return leaseText;\n }\n\n const changedText = await readHelperFile(changedFilesFile, \"validate-write-lease\");\n if (typeof changedText !== \"string\") {\n return changedText;\n }\n\n return validateWriteLeaseText(leaseText, changedText);\n};\n\nexport const runContext = async (options: {\n workflow?: string;\n base?: string;\n format?: string;\n}): Promise<CommandResult> => {\n if (!isContextPackWorkflow(options.workflow)) {\n return {\n command: \"context\",\n summary: \"Truthmark context requires a supported --workflow value.\",\n diagnostics: [\n {\n category: \"context-pack\",\n severity: \"error\",\n message: \"truthmark context requires --workflow truth-sync, truth-document, or truth-realize.\",\n },\n ],\n };\n }\n\n if (!isContextPackFormat(options.format)) {\n return {\n command: \"context\",\n summary: \"Truthmark context requires a supported --format value.\",\n diagnostics: [\n {\n category: \"context-pack\",\n severity: \"error\",\n message: \"truthmark context requires --format json or markdown.\",\n },\n ],\n };\n }\n\n const contextPack = await buildContextPack(process.cwd(), {\n workflow: options.workflow,\n base: options.base,\n });\n const diagnostics = contextPack.warnings;\n\n return {\n command: \"context\",\n summary: `Truthmark context generated ${contextPack.workflow} ContextPack with ${diagnostics.length} warnings.`,\n diagnostics,\n data: {\n contextPack,\n ...(options.format === \"markdown\" ? { markdown: renderContextPackMarkdown(contextPack) } : {}),\n },\n };\n};\n","import { parse as parseYaml } from \"yaml\";\n\nimport { parseTruthSyncReport } from \"../sync/report.js\";\n\nexport type WorkflowHelperValidationResult =\n | {\n ok: true;\n helper: string;\n checks: string[];\n }\n | {\n ok: false;\n helper: string;\n errors: string[];\n };\n\nconst escapeRegex = (value: string): string =>\n value\n .split(\"\")\n .map((char) => (\".+*?^$()[]{}|\\\\\".includes(char) ? `\\\\${char}` : char))\n .join(\"\");\n\nconst hasLabel = (text: string, label: string): boolean => {\n const escaped = escapeRegex(label);\n return new RegExp(String.raw`(^|\\n)\\s*(?:#{1,6}\\s*)?${escaped}\\s*:?\\s*(\\n|$)`, \"iu\").test(\n text,\n );\n};\n\nconst getSection = (text: string, label: string): string | null => {\n const lines = text.split(/\\r?\\n/u);\n const labelPattern = new RegExp(String.raw`^(?:#{1,6}\\s*)?${escapeRegex(label)}\\s*:?\\s*$`, \"iu\");\n const sectionHeaderPattern = /^(?:#{1,6}\\s*)?[A-Z][A-Za-z0-9 ]+:\\s*$/u;\n const startIndex = lines.findIndex((line) => labelPattern.test(line));\n\n if (startIndex === -1) {\n return null;\n }\n\n const nextSectionOffset = lines\n .slice(startIndex + 1)\n .findIndex((line) => sectionHeaderPattern.test(line));\n const endIndex = nextSectionOffset === -1 ? lines.length : startIndex + 1 + nextSectionOffset;\n\n return lines.slice(startIndex + 1, endIndex).join(\"\\n\").trim();\n};\n\nconst requireBulletSection = (\n text: string,\n label: string,\n errors: string[],\n checks: string[],\n): void => {\n const section = getSection(text, label);\n\n if (section === null) {\n errors.push(`missing required section: ${label}`);\n return;\n }\n\n if (!/^-\\s+\\S/mu.test(section)) {\n errors.push(`${label} must include at least one bullet`);\n return;\n }\n\n checks.push(label);\n};\n\nconst validateEvidenceChecked = (text: string, errors: string[], checks: string[]): void => {\n const section = getSection(text, \"Evidence checked\");\n\n if (section === null || section === \"\") {\n errors.push(\"Evidence checked must include at least one structured entry\");\n return;\n }\n\n const entries = section\n .split(/\\n(?=-\\s+)/u)\n .map((entry) => entry.trim())\n .filter(Boolean);\n\n if (entries.length === 0) {\n errors.push(\"Evidence checked must include at least one structured entry\");\n return;\n }\n\n const entryPattern =\n /^- Claim:\\s*\\S[^\\n]*\\n {2,}Evidence:\\s*\\S[^\\n]*\\n {2,}Result:\\s*(supported|narrowed|removed|blocked)\\s*$/iu;\n for (const [index, entry] of entries.entries()) {\n if (!entryPattern.test(entry)) {\n errors.push(\n `Evidence checked entry ${\n index + 1\n } must match '- Claim: ...' followed by indented 'Evidence: ...' and 'Result: supported | narrowed | removed | blocked'`,\n );\n }\n }\n\n if (errors.length === 0) {\n checks.push(\n \"Evidence checked entries include Claim:, Evidence:, and Result: supported | narrowed | removed | blocked\",\n );\n }\n};\n\nconst validateHelperScriptEntries = (\n entries: string[] | undefined,\n requiredHelpers: string[],\n errors: string[],\n checks: string[],\n): void => {\n if (entries === undefined || entries.length === 0) {\n errors.push(\"Helper scripts must include status for optional helpers\");\n return;\n }\n\n const statusPattern = /^(?:-\\s*)?([a-z0-9-]+):\\s*(?:ran,\\s*passed|skipped,\\s*\\S.*)$/iu;\n const validHelperIds = new Set<string>();\n\n for (const entry of entries) {\n const match = entry.trim().match(statusPattern);\n if (match === null) {\n errors.push(\n \"Helper scripts entries must match '- helper-id: ran, passed' or '- helper-id: skipped, reason'; ran, failed is not valid for completed reports\",\n );\n continue;\n }\n\n validHelperIds.add(match[1].toLowerCase());\n }\n\n for (const helperId of requiredHelpers) {\n if (!validHelperIds.has(helperId.toLowerCase())) {\n errors.push(`missing Helper scripts status: ${helperId}`);\n }\n }\n\n if (errors.length === 0) {\n checks.push(`Helper scripts statuses include ${requiredHelpers.join(\", \")}`);\n }\n};\n\nconst validateHelperScripts = (\n text: string,\n requiredHelpers: string[],\n errors: string[],\n checks: string[],\n): void => {\n const section = getSection(text, \"Helper scripts\");\n const entries = section\n ?.split(/\\n/u)\n .map((entry) => entry.trim())\n .filter(Boolean);\n\n validateHelperScriptEntries(entries, requiredHelpers, errors, checks);\n};\n\nexport const validateTruthSyncReportText = (text: string): WorkflowHelperValidationResult => {\n const helper = \"validate-sync-report\";\n const statusMatch = text.match(/^\\s*Truth Sync:\\s*(completed|blocked|skipped)\\b/imu);\n if (statusMatch === null) {\n return {\n ok: false,\n helper,\n errors: [\"missing Truth Sync status: expected completed, blocked, or skipped\"],\n };\n }\n\n const status = statusMatch[1].toLowerCase();\n const checks = [`status: ${status}`];\n const errors: string[] = [];\n\n if (status === \"completed\") {\n try {\n const report = parseTruthSyncReport(text.trimStart());\n\n for (const [label, items] of [\n [\"Changed code reviewed\", report.changedCode],\n [\"Ownership reviewed\", report.ownershipReviewed],\n [\"Truth docs updated\", report.truthDocsUpdated],\n [\"Notes\", report.notes],\n ] as const) {\n if (items.length === 0) {\n errors.push(`${label} must include at least one bullet`);\n } else {\n checks.push(label);\n }\n }\n\n if (report.evidenceChecked.length === 0) {\n errors.push(\"Evidence checked must include at least one structured entry\");\n } else {\n checks.push(\n \"Evidence checked entries include Claim:, Evidence:, and Result: supported | narrowed | removed | blocked\",\n );\n }\n\n validateHelperScriptEntries(\n report.helperScripts,\n [\"validate-write-lease\"],\n errors,\n checks,\n );\n } catch (error) {\n errors.push(error instanceof Error ? error.message : \"invalid Truth Sync report\");\n }\n } else if (status === \"skipped\") {\n requireBulletSection(text, \"Reason\", errors, checks);\n } else if (status === \"blocked\") {\n requireBulletSection(text, \"Reason\", errors, checks);\n requireBulletSection(text, \"Files requiring manual review\", errors, checks);\n requireBulletSection(text, \"Next action\", errors, checks);\n }\n\n return errors.length > 0 ? { ok: false, helper, errors } : { ok: true, helper, checks };\n};\n\nexport const validateTruthDocumentReportText = (text: string): WorkflowHelperValidationResult => {\n const helper = \"validate-document-report\";\n const statusMatch = text.match(/^\\s*Truth Document:\\s*(completed|blocked)\\b/imu);\n if (statusMatch === null) {\n return {\n ok: false,\n helper,\n errors: [\"missing Truth Document status: expected completed or blocked\"],\n };\n }\n\n const status = statusMatch[1].toLowerCase();\n const checks = [`status: ${status}`];\n const errors: string[] = [];\n\n if (status === \"completed\") {\n for (const label of [\"Implementation reviewed\", \"Ownership reviewed\", \"Notes\"]) {\n requireBulletSection(text, label, errors, checks);\n }\n\n if (hasLabel(text, \"Evidence checked\")) {\n checks.push(\"Evidence checked\");\n } else {\n errors.push(\"missing required section: Evidence checked\");\n }\n\n if (hasLabel(text, \"Helper scripts\")) {\n checks.push(\"Helper scripts\");\n } else {\n errors.push(\"missing required section: Helper scripts\");\n }\n\n const truthDocsUpdated = getSection(text, \"Truth docs updated\");\n const truthDocsCreated = getSection(text, \"Truth docs created\");\n if (truthDocsUpdated === null && truthDocsCreated === null) {\n errors.push(\"missing required section: Truth docs updated or Truth docs created\");\n } else if (\n ![truthDocsUpdated, truthDocsCreated].some(\n (section) => section !== null && /^-\\s+\\S/mu.test(section),\n )\n ) {\n errors.push(\"Truth docs updated or Truth docs created must include at least one bullet\");\n } else {\n checks.push(\"Truth docs updated or created\");\n }\n\n validateEvidenceChecked(text, errors, checks);\n validateHelperScripts(text, [\"validate-write-lease\"], errors, checks);\n } else if (status === \"blocked\") {\n requireBulletSection(text, \"Reason\", errors, checks);\n }\n\n return errors.length > 0 ? { ok: false, helper, errors } : { ok: true, helper, checks };\n};\n\nconst cleanPathValue = (value: string): string => value.trim().replace(/^[\"']|[\"']$/gu, \"\");\nconst normalizePath = (value: string): string => cleanPathValue(value).replace(/^\\.\\//u, \"\");\nconst windowsDriveAbsolutePattern = /^[A-Za-z]:[\\\\/]/u;\nconst uncPathPattern = /^[/\\\\]{2}[^/\\\\]+[/\\\\]+[^/\\\\]+/u;\n\nconst isUnsafePathValue = (value: string): boolean => {\n const cleanValue = cleanPathValue(value);\n const pathValue = cleanValue.endsWith(\"/**\") ? cleanValue.slice(0, -3) : cleanValue;\n return (\n pathValue.startsWith(\"/\") ||\n pathValue.startsWith(\"\\\\\") ||\n windowsDriveAbsolutePattern.test(pathValue) ||\n uncPathPattern.test(pathValue) ||\n pathValue.split(/[\\\\/]+/u).includes(\"..\")\n );\n};\n\ntype WriteLeaseListFields = {\n allowedWrites: string[];\n forbiddenWrites: string[];\n errors: string[];\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst findWriteLeaseRecord = (value: unknown): Record<string, unknown> | null => {\n if (!isRecord(value)) {\n return null;\n }\n\n if (\n Object.prototype.hasOwnProperty.call(value, \"allowedWrites\") ||\n Object.prototype.hasOwnProperty.call(value, \"forbiddenWrites\")\n ) {\n return value;\n }\n\n for (const nestedKey of [\"writeLease\", \"lease\"] as const) {\n const nested = value[nestedKey];\n if (isRecord(nested)) {\n return nested;\n }\n }\n\n return value;\n};\n\nconst readStringArray = (\n record: Record<string, unknown>,\n field: \"allowedWrites\" | \"forbiddenWrites\",\n errors: string[],\n): string[] => {\n const value = record[field];\n\n if (!Array.isArray(value) || !value.every((item) => typeof item === \"string\")) {\n errors.push(`${field} must be an array of strings`);\n return [];\n }\n\n return value;\n};\n\nconst parseListFields = (text: string): WriteLeaseListFields => {\n const errors: string[] = [];\n let parsed: unknown;\n\n try {\n parsed = parseYaml(text);\n } catch (error: unknown) {\n return {\n allowedWrites: [],\n forbiddenWrites: [],\n errors: [\n `manual-validation required: invalid write lease YAML${\n error instanceof Error ? `: ${error.message}` : \"\"\n }`,\n ],\n };\n }\n\n const record = findWriteLeaseRecord(parsed);\n if (record === null) {\n return {\n allowedWrites: [],\n forbiddenWrites: [],\n errors: [\"write lease YAML must be an object\"],\n };\n }\n\n return {\n allowedWrites: readStringArray(record, \"allowedWrites\", errors),\n forbiddenWrites: readStringArray(record, \"forbiddenWrites\", errors),\n errors,\n };\n};\n\nconst isSupportedPattern = (pattern: string): boolean => {\n const withoutTrailingGlob = pattern.endsWith(\"/**\") ? pattern.slice(0, -3) : pattern;\n return !/[?*[\\]{}]/u.test(withoutTrailingGlob);\n};\n\nconst matchesPattern = (filePath: string, pattern: string): boolean => {\n if (pattern.endsWith(\"/**\")) {\n const prefix = pattern.slice(0, -3).replace(/\\/+$/u, \"\");\n return filePath === prefix || filePath.startsWith(`${prefix}/`);\n }\n\n return filePath === pattern;\n};\n\nexport const validateWriteLeaseText = (\n leaseText: string,\n changedText: string,\n): WorkflowHelperValidationResult => {\n const helper = \"validate-write-lease\";\n const parsed = parseListFields(leaseText);\n const rawAllowedWrites = parsed.allowedWrites.map(cleanPathValue).filter(Boolean);\n const rawForbiddenWrites = parsed.forbiddenWrites.map(cleanPathValue).filter(Boolean);\n const rawChangedFiles = changedText\n .split(/\\r?\\n/u)\n .map(cleanPathValue)\n .filter(Boolean);\n const allowedWrites = rawAllowedWrites.map(normalizePath).filter(Boolean);\n const forbiddenWrites = rawForbiddenWrites.map(normalizePath).filter(Boolean);\n const changedFiles = rawChangedFiles.map(normalizePath).filter(Boolean);\n const checks: string[] = [];\n const errors: string[] = [...parsed.errors];\n\n for (const pattern of rawAllowedWrites) {\n if (isUnsafePathValue(pattern)) {\n errors.push(`invalid allowedWrites path: ${pattern}`);\n }\n }\n\n for (const pattern of rawForbiddenWrites) {\n if (isUnsafePathValue(pattern)) {\n errors.push(`invalid forbiddenWrites path: ${pattern}`);\n }\n }\n\n for (const filePath of rawChangedFiles) {\n if (isUnsafePathValue(filePath)) {\n errors.push(`invalid changed file path: ${filePath}`);\n }\n }\n\n for (const pattern of [...allowedWrites, ...forbiddenWrites]) {\n if (!isSupportedPattern(pattern)) {\n errors.push(`manual-validation required: unsupported write pattern ${pattern}`);\n }\n }\n\n if (allowedWrites.length === 0) {\n errors.push(\"manual-validation required: no allowedWrites entries found\");\n }\n\n if (errors.length === 0) {\n for (const filePath of changedFiles) {\n if (!allowedWrites.some((pattern) => matchesPattern(filePath, pattern))) {\n errors.push(`${filePath} is outside allowedWrites`);\n continue;\n }\n\n const forbiddenPattern = forbiddenWrites.find((pattern) => matchesPattern(filePath, pattern));\n if (forbiddenPattern !== undefined) {\n errors.push(`${filePath} matches forbiddenWrites pattern ${forbiddenPattern}`);\n continue;\n }\n\n checks.push(filePath);\n }\n }\n\n return errors.length > 0 ? { ok: false, helper, errors } : { ok: true, helper, checks };\n};\n","import { buildProgram } from \"./program.js\";\n\nexport const main = async (argv: string[] = process.argv): Promise<void> => {\n\tawait buildProgram().parseAsync(argv);\n};\n\nmain().catch((error: unknown) => {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tprocess.stderr.write(`${message}\\n`);\n\tprocess.exitCode = 1;\n});"],"mappings":";;;AAAA,SAAS,eAAe;;;ACExB,IAAM,gBAAgB,CAAC,eAAmC;AACxD,QAAM,QAAkB,CAAC;AAEzB,MAAI,WAAW,MAAM;AACnB,UAAM,KAAK,SAAS,WAAW,IAAI,EAAE;AAAA,EACvC;AAEA,MAAI,WAAW,MAAM;AACnB,UAAM,KA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MAAM,CAAC,UAAmB;AAChC,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,UAAQ,OAAO,MAAM,GAAG,OAAO;AAAA,CAAI;AACnC,UAAQ,WAAW;AACpB,CAAC;","names":["fs","fs","path","path","path","path","fs","fs","fs","parse","fs","parse","fs","truthRoot","fs","truthRoot","fs","truthRoot","stringify","renderMarkdownExample","renderMarkdownExample","renderMarkdownExample","renderMarkdownExample","renderMarkdownExample","stringify","path","path","path","fs","fs","fg","fg","fs","fs","fg","fs","fg","fs","isTruthDocumentKind","fs","fs","path","pathExists","fs","path","fs","fg","micromatch","fs","fg","micromatch","micromatch","fs","fg","micromatch","looksLikeGlob","pathExists","fs","fg","micromatch","fs","micromatch","isTruthDocumentKind","escapeRegExp","micromatch","fs","fs","fs","path","micromatch","fs","path","fs","path","execa","fg","matter","micromatch","path","normalizePath","execa","micromatch","fg","fs","matter","fs","path","fg","path","fs","path","execa","fs","path","execa","normalizePath","execa","pathExists","fs","path","normalizePath","execa","micromatch","path","fs","fg","fs","path","matter","parse","pathExists","fs","fg","fs","path","fg","uniqueSorted","repoRootPrefixes","isGlobReference","path","fs","fg","fs","parseYaml","normalizePath","parseYaml","runConfig","runInit","runCheck","fs","runConfig","runInit","runCheck"]}
|