truthmark 2.2.5 → 2.2.7
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.md +19 -3
- package/dist/main.js +1095 -692
- package/dist/main.js.map +1 -1
- package/docs/README.md +13 -11
- package/docs/readmes/README.ar.md +4 -0
- package/docs/readmes/README.de.md +4 -0
- package/docs/readmes/README.el.md +4 -0
- package/docs/readmes/README.es.md +4 -0
- package/docs/readmes/README.fr.md +4 -0
- package/docs/readmes/README.id.md +4 -0
- package/docs/readmes/README.it.md +4 -0
- package/docs/readmes/README.ja.md +4 -0
- package/docs/readmes/README.ko.md +4 -0
- package/docs/readmes/README.pl.md +4 -0
- package/docs/readmes/README.pt.md +4 -0
- package/docs/readmes/README.ru.md +4 -0
- package/docs/readmes/README.tr.md +4 -0
- package/docs/readmes/README.vi.md +4 -0
- package/docs/readmes/README.zh.md +4 -0
- package/package.json +7 -7
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/checks/generated-surfaces.ts","../src/truth/evidence.ts","../src/agents/shared.ts","../src/templates/agents-block.ts","../src/agents/workflow-manifest.ts","../src/agents/truth-check.ts","../src/agents/truth-document.ts","../src/agents/truthmark-portal.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/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/impact/build.ts","../src/repo-index/file-tree.ts","../src/truth/source-references.ts","../src/repo-index/package-metadata.ts","../src/repo-index/route-map.ts","../src/repo-index/build.ts","../src/impact/git-diff.ts","../src/git/changes.ts","../src/freshness/check.ts","../src/evidence/validate.ts","../src/evidence/parse.ts","../src/checks/scorecard.ts","../src/checks/check.ts","../src/workflow-state/build.ts","../src/workflow-state/action-context.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 runImpact,\n runIndex,\n runInit,\n runValidateDocumentReport,\n runValidateSyncReport,\n runValidateWriteLease,\n runWorkflowStatus,\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 WorkflowOptions = OutputOptions & {\n workflow?: string;\n base?: string;\n};\n\nconst markFailedWhenErrorDiagnosticsExist = (result: CommandResult): void => {\n if (result.diagnostics.some((diagnostic) => diagnostic.severity === \"error\")) {\n process.exitCode = 1;\n }\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 markFailedWhenErrorDiagnosticsExist(result);\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\n .command(\"index\")\n .description(\"Inspect derived Truthmark workflow routing metadata for the current checkout.\"),\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 const workflow = program\n .command(\"workflow\")\n .description(\"Inspect agent-facing Truthmark workflow state.\");\n\n addJsonOption(\n workflow\n .command(\"status\")\n .description(\"Return schema-versioned workflow state for a canonical workflow ID.\")\n .option(\"--workflow <workflow>\", \"Canonical workflow ID, such as truthmark-sync\")\n .option(\"--base <ref>\", \"Base Git ref for impact-backed workflow state\"),\n ).action(async (options: WorkflowOptions) => {\n writeResult(\n await runWorkflowStatus({\n workflow: options.workflow,\n base: options.base,\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\ntype 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 {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} 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 = resolveEngineeringTruthRoot;\n\nconst renderLaneRootReadmeSummary = (\n lane: \"product\" | \"engineering\",\n): string => {\n if (lane === \"product\") {\n return [\n \"Product truth owns capability promises, boundaries, decisions, and acceptance criteria.\",\n \"Product lane docs state what must be true, why it matters, and what success means.\",\n ].join(\" \");\n }\n\n return [\n \"Engineering truth owns current realization, contracts, architecture, workflows, operations, and tests.\",\n \"Engineering lane docs describe how the repository currently implements and operates the behavior.\",\n ].join(\" \");\n};\n\nconst renderLaneRootLeafDocGuidance = (\n lane: \"product\" | \"engineering\",\n): string => {\n if (lane === \"product\") {\n return \"README.md files are indexes, not Truth Sync targets. Keep product truth in bounded capability docs.\";\n }\n\n return \"README.md files are indexes, not Truth Sync targets. Keep engineering truth in bounded behavior, contract, architecture, workflow, operations, and test docs.\";\n};\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:\n inferTruthDocumentKindFromPath(document.path) ??\n \"engineering-behavior\",\n }))\n : [\n {\n path: `${createDefaultConfig().truthmark.paths.engineeringTruthRoot}/**/*.md`,\n kind: \"engineering-behavior\",\n lane: \"engineering\",\n },\n ];\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.truthmark.routes.defaultArea;\n const childPath = `${config.truthmark.paths.routeAreasRoot}/${defaultArea}.md`;\n const title = titleCase(defaultArea);\n const sourceOfTruth = resolveRelativePath(\n config.truthmark.paths.routesIndex,\n \".truthmark/config.yml\",\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: route-index\",\n `last_reviewed: ${currentDate()}`,\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 \"## Source References\",\n \"\",\n `- ${sourceOfTruth}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderChildAreaTemplate = (config: TruthmarkConfig): string => {\n const defaultArea = config.truthmark.routes.defaultArea;\n const title = titleCase(defaultArea);\n const truthDocsRoot = truthRoot(config);\n const bootstrapTruthDoc = `${truthDocsRoot}/${defaultArea}/bootstrap-routing.md`;\n const templatePath = `${config.truthmark.paths.routeAreasRoot}/${defaultArea}.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n \".truthmark/config.yml\",\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: area-route\",\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n `# ${title} Areas`,\n \"\",\n `## ${title}`,\n \"\",\n \"Truth documents:\",\n \"```yaml\",\n \"truth_documents:\",\n ` - path: ${bootstrapTruthDoc}`,\n \" kind: engineering-workflow\",\n \" lane: engineering\",\n \"```\",\n \"\",\n \"This is a provisional bootstrap route. It exists only to make fresh repositories routeable until real product, service, domain, or ownership areas are created.\",\n \"\",\n \"Code surface:\",\n \"- src/**\",\n \"\",\n \"Update truth when:\",\n \"- this provisional bootstrap route is the only match for a real code surface\",\n \"- route ownership is still broad, mixed, or ambiguous\",\n \"- Run Truth Structure before normal Truth Sync so the touched code gets a bounded owner\",\n \"\",\n \"## Source References\",\n \"\",\n `- ${sourceOfTruth}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderBootstrapRoutingDocTemplate = (\n config: TruthmarkConfig,\n): string => {\n const defaultArea = config.truthmark.routes.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/bootstrap-routing.md`;\n const routePath = `${config.truthmark.paths.routeAreasRoot}/${defaultArea}.md`;\n const routeSource = resolveRelativePath(templatePath, routePath);\n const configSource = resolveRelativePath(\n templatePath,\n \".truthmark/config.yml\",\n );\n const today = currentDate();\n\n return [\n \"---\",\n \"status: active\",\n \"truth_kind: engineering-workflow\",\n `last_reviewed: ${today}`,\n \"---\",\n \"\",\n `# ${title} Bootstrap Routing`,\n \"\",\n \"## Purpose\",\n \"\",\n `This doc records the provisional broad route for ${defaultArea}.`,\n \"This doc is a bootstrap handoff, not a behavior truth dumping ground.\",\n \"It is not a substitute for bounded product and engineering truth docs.\",\n \"\",\n \"## Scope\",\n \"\",\n \"This doc owns only the initial routing workflow for a fresh Truthmark repository whose default route still maps a broad code surface such as `src/**`.\",\n \"It does not own implementation behavior under that code surface.\",\n \"\",\n \"## Current Implementation Behavior\",\n \"\",\n \"The scaffold creates this provisional bootstrap handoff only when a default broad route needs a canonical owner. Agents use it as a signal to run Truth Structure and create bounded routes before normal Truth Sync, not as a place to accumulate implementation claims.\",\n \"\",\n \"## Product Truth Links\",\n \"\",\n \"- None. This is an engineering bootstrap handoff for routing setup, not a product promise.\",\n \"\",\n \"## Triggers\",\n \"\",\n \"- A real code change maps only to this provisional broad route.\",\n \"- Truth Sync cannot identify a specific behavior-owned route and bounded truth owner.\",\n \"- A maintainer or agent is onboarding the first real product, service, domain, package, or ownership area.\",\n \"\",\n \"## Inputs\",\n \"\",\n \"- Current route files under the configured Truthmark route root.\",\n \"- The touched code, tests, configuration, and existing docs needed to infer the smallest real owner.\",\n \"- Repository instruction files that exist in the checkout.\",\n \"\",\n \"## Execution Model\",\n \"\",\n \"Run Truth Structure before normal Truth Sync when real code changes touch only this broad route. Truth Structure should create or repair bounded areas first; Truth Sync should then update the bounded owner docs.\",\n \"\",\n \"## Steps\",\n \"\",\n \"1. Treat this route as provisional and insufficient for normal behavior maintenance.\",\n \"2. Inspect the touched code/test surface and infer the narrowest durable owner.\",\n \"3. Create or repair route entries and truth docs for that owner.\",\n \"4. Leave this bootstrap doc small; do not append behavior details here.\",\n \"5. Resume Truth Sync only after the touched code resolves to a bounded owner.\",\n \"\",\n \"## State, Retry, And Failure Behavior\",\n \"\",\n \"If ownership cannot be inferred safely, stop and report manual-review files instead of widening this route or adding generic behavior prose.\",\n \"\",\n \"## Outputs\",\n \"\",\n \"- Bounded route areas and lane-appropriate truth docs for the touched surface.\",\n \"- A compact manual handoff report when ownership remains ambiguous.\",\n \"\",\n \"## Engineering Decisions\",\n \"\",\n `- Decision (${today}): Default broad routing is provisional bootstrap state. Agents should create bounded areas before normal Truth Sync rather than extending a catch-all overview doc.`,\n \"\",\n \"## Rationale\",\n \"\",\n \"Scoped ownership keeps agent context close to affected files and prevents broad default docs from absorbing unrelated behavior. This preserves agent-native truth maintenance without adding a token-heavy discovery layer.\",\n \"\",\n \"## Non-Goals\",\n \"\",\n \"- This doc is not a repository behavior overview.\",\n \"- This doc is not a product capability or engineering behavior owner.\",\n \"- This doc is not a permanent home for claims about files under `src/**`.\",\n \"\",\n \"## Maintenance Notes\",\n \"\",\n \"Keep this doc short. When a repository has real bounded routes, prefer updating those routes and their truth docs instead of expanding this bootstrap handoff.\",\n \"\",\n \"## Source References\",\n \"\",\n `- ${routeSource}`,\n `- ${configSource}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderTruthRootReadmeTemplate = (\n config: TruthmarkConfig = createDefaultConfig(),\n lane: \"product\" | \"engineering\" = \"engineering\",\n): string => {\n const templatePath = `${lane === \"product\" ? resolveProductTruthRoot(config) : resolveEngineeringTruthRoot(config)}/README.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n config.truthmark.paths.routesIndex,\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: index\",\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n \"# Truth Docs\",\n \"\",\n \"This directory is an index for current truth docs organized by the configured Truthmark hierarchy.\",\n \"\",\n renderLaneRootReadmeSummary(lane),\n \"\",\n renderLaneRootLeafDocGuidance(lane),\n \"\",\n \"## Source References\",\n \"\",\n `- ${sourceOfTruth}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderTruthDomainReadmeTemplate = (\n config: TruthmarkConfig,\n): string => {\n const defaultArea = config.truthmark.routes.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/README.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n `${config.truthmark.paths.routeAreasRoot}/${defaultArea}.md`,\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: index\",\n `last_reviewed: ${currentDate()}`,\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 \"- [Bootstrap routing](bootstrap-routing.md)\",\n \"\",\n \"## Source References\",\n \"\",\n `- ${sourceOfTruth}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const BEHAVIOR_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-behavior.md\";\nexport const CONTRACT_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-contract.md\";\nexport const ARCHITECTURE_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-architecture.md\";\nexport const WORKFLOW_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-workflow.md\";\nexport const OPERATIONS_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-operations.md\";\nexport const TEST_BEHAVIOR_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-test-behavior.md\";\nexport const PRODUCT_CAPABILITY_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/product-capability.md\";\n\ntype TemplateSectionSpec = {\n heading: string;\n placeholder: string;\n guidance: string[];\n};\n\ntype ParsedTemplateSection = {\n heading: string;\n block: string;\n};\n\nconst renderTemplateSection = (section: TemplateSectionSpec): string[] => {\n return [\n section.heading,\n \"\",\n \"<!--\",\n ...section.guidance,\n \"-->\",\n \"\",\n `{{${section.placeholder}}}`,\n \"\",\n ];\n};\n\nconst titleToPlaceholder = (title: string): string => {\n return title\n .replace(/^#+\\s+/u, \"\")\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n};\n\nconst findTemplateSectionHeadings = (\n template: string,\n): Array<{ heading: string; index: number }> => {\n const matches: Array<{ heading: string; index: number }> = [];\n let fencedCodeMarker: \"`\" | \"~\" | null = null;\n let fencedCodeLength = 0;\n\n for (const lineMatch of template.matchAll(/^.*(?:\\r?\\n|$)/gm)) {\n const rawLine = lineMatch[0];\n if (rawLine.length === 0) {\n continue;\n }\n\n const line = rawLine.replace(/\\r?\\n$/u, \"\");\n const fenceMatch = /^(?: {0,3})(`{3,}|~{3,})/u.exec(line);\n\n if (fenceMatch) {\n const marker = fenceMatch[1]?.[0] as \"`\" | \"~\";\n const length = fenceMatch[1]?.length ?? 0;\n\n if (fencedCodeMarker === null) {\n fencedCodeMarker = marker;\n fencedCodeLength = length;\n } else if (marker === fencedCodeMarker && length >= fencedCodeLength) {\n fencedCodeMarker = null;\n fencedCodeLength = 0;\n }\n\n continue;\n }\n\n if (fencedCodeMarker === null && /^## .+$/u.test(line)) {\n matches.push({ heading: line.trim(), index: lineMatch.index });\n }\n }\n\n return matches;\n};\n\nconst parseTemplateSections = (\n template: string,\n): { preamble: string; sections: ParsedTemplateSection[] } => {\n const matches = findTemplateSectionHeadings(template);\n\n if (matches.length === 0) {\n return { preamble: template.trimEnd(), sections: [] };\n }\n\n const sections = matches.map((match, index) => {\n const start = match.index;\n const next = matches[index + 1];\n const end = next?.index ?? template.length;\n\n return {\n heading: match.heading,\n block: template.slice(start, end).trimEnd(),\n };\n });\n\n return {\n preamble: template.slice(0, matches[0]?.index ?? 0).trimEnd(),\n sections,\n };\n};\n\nconst LEGACY_MANAGED_TEMPLATE_HEADINGS = new Map<string, string>([\n [\"## Current Behavior\", \"## Current Implementation Behavior\"],\n [\"## Source Evidence\", \"## Source References\"],\n]);\n\nconst resolveManagedTemplateHeading = (heading: string): string => {\n return LEGACY_MANAGED_TEMPLATE_HEADINGS.get(heading) ?? heading;\n};\n\nconst stripManagedFrontmatterFields = (preamble: string): string => {\n if (!preamble.startsWith(\"---\\n\")) {\n return preamble;\n }\n\n const lines = preamble.split(\"\\n\");\n const closingIndex = lines.findIndex(\n (line, index) => index > 0 && line.trim() === \"---\",\n );\n if (closingIndex < 0) {\n return preamble;\n }\n\n const fieldsToRemove = new Set([\"source_of_truth\", \"doc_type\", \"truth_lane\"]);\n const keptFrontmatterLines: string[] = [];\n let skippingManagedField = false;\n\n for (const line of lines.slice(1, closingIndex)) {\n const keyMatch = /^([A-Za-z0-9_-]+):(\\s|$)/u.exec(line);\n if (keyMatch) {\n skippingManagedField = fieldsToRemove.has(keyMatch[1] ?? \"\");\n }\n\n if (!skippingManagedField) {\n keptFrontmatterLines.push(line);\n }\n }\n\n return [\n \"---\",\n ...keptFrontmatterLines,\n \"---\",\n ...lines.slice(closingIndex + 1),\n ]\n .join(\"\\n\")\n .trimEnd();\n};\n\nexport const mergeTruthDocTemplate = (\n existingTemplate: string,\n defaultTemplate: string,\n): string => {\n if (existingTemplate.trim().length === 0) {\n return defaultTemplate;\n }\n\n const defaultParsed = parseTemplateSections(defaultTemplate);\n const existingParsed = parseTemplateSections(existingTemplate);\n const defaultHeadings = new Set(\n defaultParsed.sections.map((section) => section.heading),\n );\n const customBeforeDefault = new Map<string, ParsedTemplateSection[]>();\n const trailingCustomSections: ParsedTemplateSection[] = [];\n\n existingParsed.sections.forEach((section, index) => {\n if (defaultHeadings.has(resolveManagedTemplateHeading(section.heading))) {\n return;\n }\n\n const nextDefaultSection = existingParsed.sections\n .slice(index + 1)\n .find((candidate) =>\n defaultHeadings.has(resolveManagedTemplateHeading(candidate.heading)),\n );\n\n if (nextDefaultSection) {\n const nextDefaultHeading = resolveManagedTemplateHeading(\n nextDefaultSection.heading,\n );\n const bucket = customBeforeDefault.get(nextDefaultHeading) ?? [];\n bucket.push(section);\n customBeforeDefault.set(nextDefaultHeading, bucket);\n return;\n }\n\n trailingCustomSections.push(section);\n });\n\n const mergedSections = defaultParsed.sections.flatMap((section) => [\n ...(customBeforeDefault.get(section.heading) ?? []),\n section,\n ]);\n\n return [\n stripManagedFrontmatterFields(existingParsed.preamble),\n ...mergedSections.map((section) => section.block),\n ...trailingCustomSections.map((section) => section.block),\n \"\",\n ]\n .filter((block) => block.length > 0)\n .join(\"\\n\\n\");\n};\n\nexport const renderBehaviorDocTemplateFile = (): string => {\n return [\n \"---\",\n \"status: active\",\n \"truth_kind: engineering-behavior\",\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n \"# {{title}}\",\n \"\",\n \"## Purpose\",\n \"\",\n \"<!--\",\n \"State the user/system outcome this behavior protects and why it exists.\",\n \"Include the problem boundary and durable value; exclude roadmap, implementation plan, and historical narrative.\",\n \"List the code, config, docs, or tests that support the claim in Source References rather than prose-only assertion.\",\n \"-->\",\n \"\",\n \"{{purpose}}\",\n \"\",\n \"## Scope\",\n \"\",\n \"<!--\",\n \"Define the one coherent behavior surface this document owns.\",\n \"Include in-scope actors, entrypoints, state/data owned by this doc, and explicit handoffs to neighboring truth docs.\",\n \"Split into another leaf doc when content introduces a distinct outcome, state machine, rule family, external contract, or route owner.\",\n \"Keep README.md files as indexes only.\",\n \"-->\",\n \"\",\n \"{{scope}}\",\n \"\",\n \"This doc was created from the editable engineering-behavior template at {{template_path}}.\",\n \"\",\n \"## Current Implementation Behavior\",\n \"\",\n \"<!--\",\n \"Describe only current implemented behavior in present tense.\",\n \"Cover observable behavior, important defaults, and user/system-visible effects; exclude desired future behavior and speculative design.\",\n \"Every non-obvious claim should be checkable from Source References.\",\n \"-->\",\n \"\",\n \"{{current_implementation_behavior}}\",\n \"\",\n \"## Core Rules\",\n \"\",\n \"<!--\",\n \"Capture stable business rules, invariants, precedence rules, validation rules, and must-never constraints.\",\n \"Separate rules from incidental implementation details; cite current implementation or tests for rule enforcement.\",\n \"-->\",\n \"\",\n \"{{core_rules}}\",\n \"\",\n \"## Flows And States\",\n \"\",\n \"<!--\",\n \"Document state transitions, lifecycle stages, retries, fallbacks, route switches, and important error paths.\",\n \"State 'None beyond current behavior.' when this behavior has no distinct flow or state model.\",\n \"-->\",\n \"\",\n \"{{flows_and_states}}\",\n \"\",\n \"## Contracts\",\n \"\",\n \"<!--\",\n \"Capture user-visible or integration contracts: CLI/API shape, inputs, outputs, diagnostics, files, events, permissions, or links to canonical contract docs.\",\n \"Avoid duplicating a separate canonical contract doc; link to it when contract ownership lives elsewhere.\",\n \"-->\",\n \"\",\n \"{{contracts}}\",\n \"\",\n \"## Product Truth Links\",\n \"\",\n \"<!--\",\n \"List product truth docs this engineering doc realizes; author canonical realizes links in route YAML, not doc frontmatter.\",\n \"Use 'None.' when this is purely internal engineering behavior.\",\n \"-->\",\n \"\",\n \"{{product_truth_links}}\",\n \"\",\n \"## Engineering Decisions\",\n \"\",\n \"<!--\",\n \"Keep active decisions only, dated inline when added or changed.\",\n \"Explain decisions that shape behavior, boundaries, rejected alternatives, or migration constraints; replace stale decisions instead of appending historical logs.\",\n \"-->\",\n \"\",\n \"{{engineering_decisions}}\",\n \"\",\n \"## Rationale\",\n \"\",\n \"<!--\",\n \"Explain why the current behavior and active decisions are this way, including tradeoffs and constraints.\",\n \"Tie rationale to evidence-backed behavior; do not use this as a changelog.\",\n \"-->\",\n \"\",\n \"{{rationale}}\",\n \"\",\n \"## Non-Goals\",\n \"\",\n \"<!--\",\n \"Name adjacent behavior this doc intentionally does not own, especially tempting future expansions or neighboring route owners.\",\n \"Use this section to prevent scope creep and duplicate truth ownership.\",\n \"-->\",\n \"\",\n \"{{non_goals}}\",\n \"\",\n \"## Maintenance Notes\",\n \"\",\n \"<!--\",\n \"List related tests, routing cautions, migration notes, evidence drift risks, and review triggers for future maintainers or agents.\",\n \"Keep this operational and current-state focused, not historical.\",\n \"-->\",\n \"\",\n \"{{maintenance_notes}}\",\n \"\",\n \"## Source References\",\n \"\",\n \"<!--\",\n \"List source files, tests, configs, generated templates, route files, or product instructions that support current claims.\",\n \"-->\",\n \"\",\n \"{{source_references}}\",\n \"\",\n ].join(\"\\n\");\n};\n\nconst sectionSpec = (\n heading: string,\n guidance: string[],\n placeholder = titleToPlaceholder(heading),\n): TemplateSectionSpec => ({ heading, guidance, placeholder });\n\nconst PURPOSE_SECTION = sectionSpec(\"## Purpose\", [\n \"State the software-engineering outcome this document protects and why the documented surface exists.\",\n \"Include durable value, impacted users/systems, and the problem boundary; exclude roadmap, implementation plans, and historical narrative.\",\n \"Keep claims traceable to Source References rather than prose-only assertion.\",\n]);\n\nconst SCOPE_SECTION = sectionSpec(\"## Scope\", [\n \"Define the one coherent surface this document owns, including actors, entrypoints, owned state/data, and handoffs to neighboring truth docs.\",\n \"Call out important out-of-scope boundaries here or in Non-Goals; split the doc when it mixes distinct outcomes, lifecycles, contracts, or owners.\",\n]);\n\nconst PRODUCT_DECISIONS_SECTION = sectionSpec(\n \"## Product Decisions\",\n [\n \"Keep active decisions only, dated inline when added or changed.\",\n \"Capture decisions that shape behavior, interfaces, boundaries, compatibility, risk acceptance, or migration constraints.\",\n \"Replace stale decisions instead of appending historical logs.\",\n ],\n \"decision\",\n);\n\nconst ENGINEERING_DECISIONS_SECTION = sectionSpec(\n \"## Engineering Decisions\",\n [\n \"Keep active engineering, architecture, contract, workflow, or operational decisions only, dated inline when added or changed.\",\n \"Do not restate product promises, product rationale, or business decisions here; link product truth instead.\",\n \"Replace stale decisions instead of appending historical logs.\",\n ],\n \"engineering_decisions\",\n);\n\nconst RATIONALE_SECTION = sectionSpec(\"## Rationale\", [\n \"Explain why the current behavior, structure, or contract is this way, including tradeoffs and constraints.\",\n \"Tie rationale to evidence-backed facts and active decisions; do not use this as a changelog.\",\n]);\n\nconst NON_GOALS_SECTION = sectionSpec(\"## Non-Goals\", [\n \"Name adjacent behavior, responsibilities, interfaces, or future expansions this doc intentionally does not own.\",\n \"Use this section to prevent scope creep and duplicate truth ownership.\",\n]);\n\nconst MAINTENANCE_NOTES_SECTION = sectionSpec(\"## Maintenance Notes\", [\n \"List related tests, routing cautions, migration notes, compatibility risks, evidence drift risks, and review triggers for future maintainers or agents.\",\n \"Keep this operational and current-state focused, not historical.\",\n]);\n\nconst SOURCE_REFERENCES_SECTION = sectionSpec(\n \"## Source References\",\n [\n \"List source files, tests, configs, generated templates, route files, or product instructions that support current claims.\",\n ],\n \"source_references\",\n);\n\nconst renderTypedTruthDocTemplate = (\n truthKind: string,\n title: string,\n sections: TemplateSectionSpec[],\n): string => {\n return [\n \"---\",\n \"status: active\",\n `truth_kind: ${truthKind}`,\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n `# ${title}`,\n \"\",\n ...renderTemplateSection(PURPOSE_SECTION),\n ...renderTemplateSection(SCOPE_SECTION),\n ...sections.flatMap(renderTemplateSection),\n ...renderTemplateSection(ENGINEERING_DECISIONS_SECTION),\n ...renderTemplateSection(RATIONALE_SECTION),\n ...renderTemplateSection(NON_GOALS_SECTION),\n ...renderTemplateSection(MAINTENANCE_NOTES_SECTION),\n ...renderTemplateSection(SOURCE_REFERENCES_SECTION),\n ].join(\"\\n\");\n};\n\nconst CORE_LANE_INVARIANT =\n \"Do not make product docs a summary of engineering docs. Do not make engineering docs a detailed version of product docs. Product truth says what must be true and why. Engineering truth says how the repository currently realizes it.\";\n\nconst renderProductTruthDocTemplate = (\n truthKind: \"product-capability\",\n title: string,\n sections: TemplateSectionSpec[],\n includeNonGoals: boolean,\n): string => {\n return [\n \"---\",\n \"status: active\",\n `truth_kind: ${truthKind}`,\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n `# ${title}`,\n \"\",\n \"<!--\",\n CORE_LANE_INVARIANT,\n \"Product docs may cite code directly when code proves current product behavior, but keep implementation flow, renderer internals, CLI envelopes, and generated file inventories in engineering truth.\",\n \"-->\",\n \"\",\n ...sections.flatMap(renderTemplateSection),\n ...renderTemplateSection(PRODUCT_DECISIONS_SECTION),\n ...renderTemplateSection(\n sectionSpec(\n \"## Engineering Realization Links\",\n [\n \"List engineering truth that realizes this product truth; author canonical realized_by links in route YAML, not doc frontmatter.\",\n \"Do not summarize those engineering docs.\",\n ],\n \"engineering_realization_links\",\n ),\n ),\n ...(includeNonGoals ? renderTemplateSection(NON_GOALS_SECTION) : []),\n ...renderTemplateSection(SOURCE_REFERENCES_SECTION),\n ].join(\"\\n\");\n};\n\nexport const renderProductCapabilityDocTemplateFile = (): string => {\n return renderProductTruthDocTemplate(\n \"product-capability\",\n \"{{title}}\",\n [\n sectionSpec(\"## Capability Promise\", [\n \"State the single user-visible capability and what must be true for users or stakeholders.\",\n \"Do not describe implementation mechanics here.\",\n ]),\n sectionSpec(\"## Users And Value\", [\n \"Describe who benefits from the capability and the durable value it protects.\",\n \"Tie claims to repository evidence, explicit user instruction, or current behavior.\",\n ]),\n sectionSpec(\"## Capability Scope\", [\n \"Define what this capability includes and excludes, including product boundary constraints and adjacent systems.\",\n \"Capture important scope limits, ownership boundaries, and non-goal pointers here; keep technical contracts in engineering truth.\",\n ]),\n sectionSpec(\"## Current Product Behavior\", [\n \"Describe current implemented user-visible behavior in present tense.\",\n \"Code files may appear in Source References when they directly prove current behavior.\",\n ]),\n sectionSpec(\"## Acceptance Criteria\", [\n \"List observable criteria that show the capability promise is currently satisfied.\",\n \"Include criteria that review whether the capability stays within its stated scope and boundary.\",\n \"Use criteria that can be reviewed from repository evidence or explicit product instruction.\",\n ]),\n ],\n true,\n );\n};\n\nexport const renderContractDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-contract\", \"{{title}}\", [\n sectionSpec(\"## Contract Surface\", [\n \"Identify the owned API, CLI, file format, event, protocol, permission boundary, or integration surface.\",\n \"State consumers/producers, stability level, and the source files/tests that define the contract.\",\n ]),\n sectionSpec(\"## Inputs\", [\n \"Document accepted parameters, payloads, files, environment/config keys, permissions, and validation rules.\",\n \"Include required/optional status, defaults, constraints, and normalization behavior.\",\n ]),\n sectionSpec(\"## Outputs\", [\n \"Document returned values, emitted files/events, state changes, side effects, and success diagnostics.\",\n \"Make externally observable behavior explicit enough for compatibility review.\",\n ]),\n sectionSpec(\"## Errors And Diagnostics\", [\n \"List error classes, exit/status codes, user-facing diagnostics, retries, and recoverability expectations.\",\n \"Distinguish validation errors, dependency failures, authorization failures, and internal faults when applicable.\",\n ]),\n sectionSpec(\"## Compatibility Rules\", [\n \"State backward/forward compatibility guarantees, tolerated inputs, deprecation rules, and breaking-change triggers.\",\n \"Include compatibility tests or review questions that protect the contract.\",\n ]),\n sectionSpec(\"## Versioning And Migration\", [\n \"Document version negotiation, schema/API version fields, rollout requirements, migration steps, and rollback expectations.\",\n \"State 'Not versioned' only when the implementation truly has no versioning or migration surface.\",\n ]),\n ]);\n};\n\nexport const renderArchitectureDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-architecture\", \"{{title}}\", [\n sectionSpec(\"## System Role\", [\n \"Describe the current architectural role of this subsystem/component in the larger system.\",\n \"State the primary responsibilities, consumers, providers, and why this boundary exists now.\",\n ]),\n sectionSpec(\"## Boundaries\", [\n \"Define owned code/config/data, external dependencies, trust boundaries, and interfaces crossed by this architecture.\",\n \"Name what is deliberately outside the boundary and link neighboring architecture or contract docs when they own it.\",\n ]),\n sectionSpec(\"## Components\", [\n \"List the major runtime/build-time components, modules, services, jobs, or generated artifacts and their responsibilities.\",\n \"Keep the component list current and evidence-backed; avoid speculative target architecture.\",\n ]),\n sectionSpec(\"## Data And Control Flow\", [\n \"Describe important data movement, command/control paths, synchronization points, state ownership, and failure paths.\",\n \"Call out persistence, queues, caches, external calls, and security-sensitive transitions where relevant.\",\n ]),\n sectionSpec(\"## Ownership\", [\n \"Document team/module ownership, review responsibility, operational responsibility, and escalation paths if known.\",\n \"If ownership is inferred from codeowners, config, or repository structure, cite that evidence.\",\n ]),\n sectionSpec(\"## Cross-Cutting Constraints\", [\n \"Record active constraints such as security, privacy, reliability, performance, portability, maintainability, compliance, and cost.\",\n \"Tie constraints to source evidence, tests, standards, or operational requirements where available.\",\n ]),\n ]);\n};\n\nexport const renderWorkflowDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-workflow\", \"{{title}}\", [\n sectionSpec(\"## Triggers\", [\n \"List events, commands, schedules, user actions, webhooks, or dependency signals that start this workflow.\",\n \"Include preconditions, authorization requirements, debounce/coalescing behavior, and disabled states when applicable.\",\n ]),\n sectionSpec(\"## Inputs\", [\n \"Document data, files, config, context, credentials, and environmental assumptions consumed by the workflow.\",\n \"Include validation, defaults, and normalization that happen before execution.\",\n ]),\n sectionSpec(\"## Execution Model\", [\n \"Describe synchronous/asynchronous execution, concurrency, locking, leases, batching, ordering, and idempotency behavior.\",\n \"State whether the workflow waits for user action, runs in the background, is distributed, or is delegated to another system.\",\n ]),\n sectionSpec(\"## Steps\", [\n \"Capture the current ordered steps or phases at a level useful for maintenance and review.\",\n \"Reference implementation entrypoints instead of duplicating line-by-line code behavior.\",\n ]),\n sectionSpec(\"## State, Retry, And Failure Behavior\", [\n \"Document state transitions, retries, timeouts, compensation, fallback, partial-success, and terminal-failure behavior.\",\n \"Make externally visible failure semantics and recovery responsibilities clear.\",\n ]),\n sectionSpec(\"## Outputs\", [\n \"List artifacts, state changes, notifications, logs, metrics, diagnostics, and downstream triggers produced by the workflow.\",\n \"Include success criteria and handoff points to other truth docs or systems.\",\n ]),\n ]);\n};\n\nexport const renderOperationsDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-operations\", \"{{title}}\", [\n sectionSpec(\"## Operational Surface\", [\n \"Describe what operators, maintainers, or automated systems can observe or control for this surface.\",\n \"Include commands, dashboards, alerts, runbooks, jobs, or operational APIs that define current operations.\",\n ]),\n sectionSpec(\"## Runtime Topology\", [\n \"Document services, processes, containers, hosts, regions, dependencies, queues, stores, and network boundaries involved at runtime.\",\n \"State single-node/local behavior explicitly when there is no distributed topology.\",\n ]),\n sectionSpec(\"## Configuration\", [\n \"List operational config, environment variables, feature flags, secrets references, defaults, and reload/restart requirements.\",\n \"Do not include secret values; describe storage and rotation expectations instead.\",\n ]),\n sectionSpec(\"## Permissions\", [\n \"Document required identities, roles, scopes, filesystem/network permissions, and least-privilege boundaries.\",\n \"Include user-facing authorization behavior and operator access requirements when relevant.\",\n ]),\n sectionSpec(\"## Deployment And Rollback\", [\n \"Describe deployment mechanism, migration ordering, compatibility windows, rollback path, and known irreversible operations.\",\n \"Call out manual review points, smoke checks, and post-deploy verification responsibilities.\",\n ]),\n sectionSpec(\"## Availability And Observability\", [\n \"Capture availability expectations, health checks, metrics, logs, traces, alerts, SLO/error-budget signals, and known blind spots.\",\n \"Include what maintainers should inspect first during incidents or degraded behavior.\",\n ]),\n ]);\n};\n\nexport const renderTestBehaviorDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-test-behavior\", \"{{title}}\", [\n sectionSpec(\"## Test Surface\", [\n \"Define the behavior, contract, architecture, or workflow surface these tests verify.\",\n \"Link the canonical truth docs and code paths the tests are meant to protect.\",\n ]),\n sectionSpec(\"## Fixtures And Data Model\", [\n \"Document fixtures, factories, seeds, mocks/fakes, test repositories, external-service substitutes, and data lifecycle rules.\",\n \"Include cleanup, determinism, privacy, and cross-test contamination constraints.\",\n ]),\n sectionSpec(\"## Execution Model\", [\n \"Describe how tests run: command, framework, parallelism, isolation, network/filesystem assumptions, and required services.\",\n \"State whether tests are unit, integration, e2e, contract, smoke, regression, or generated checks.\",\n ]),\n sectionSpec(\"## Assertions And Invariants\", [\n \"List the critical assertions, invariants, failure modes, and negative cases that make the tests meaningful.\",\n \"Tie assertions to product/contract rules rather than incidental implementation details.\",\n ]),\n sectionSpec(\"## Isolation Rules\", [\n \"Document transaction boundaries, temp directories, fake clocks, network blocking, shared resources, and teardown rules.\",\n \"Call out known order dependencies or flake risks and how they are controlled.\",\n ]),\n sectionSpec(\"## Reporting And Failure Semantics\", [\n \"Describe diagnostics, snapshots, logs, coverage signals, retry policy, and how maintainers should interpret failures.\",\n \"Include escalation or quarantine criteria for flaky or environment-sensitive tests.\",\n ]),\n ]);\n};\n\nconst renderTemplate = (\n template: string,\n values: Record<string, string>,\n): 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.truthmark.routes.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/overview.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n `${config.truthmark.paths.routeAreasRoot}/${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_implementation_behavior:\n \"- Document current behavior here when implementation changes make repository truth incomplete.\",\n engineering_decisions: `- 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 product_truth_links: \"- None.\",\n scope: `This bounded leaf truth doc owns the default ${title.toLowerCase()} behavior surface created by Truthmark.`,\n source_references: `- ${sourceOfTruth}`,\n template_path: BEHAVIOR_DOC_TEMPLATE_PATH,\n title: `${title} Overview`,\n truth_kind: \"engineering-behavior\",\n });\n};\n","import type { JSONSchemaType } from \"ajv\";\n\nconst SUPPORTED_PLATFORMS = [\n \"codex\",\n \"opencode\",\n \"claude-code\",\n \"github-copilot\",\n \"antigravity\",\n \"cursor\",\n] as const;\n\nexport type TruthmarkPlatform = (typeof SUPPORTED_PLATFORMS)[number];\n\nexport const DEFAULT_PLATFORMS = [] as const satisfies readonly TruthmarkPlatform[];\n\ntype TruthmarkPortalConfig = {\n enabled: boolean;\n};\n\ntype RawTruthmarkWorkspaceConfig = {\n workspace: string;\n generated: {\n portal: TruthmarkPortalConfig;\n };\n};\n\ntype TruthmarkWorkspaceConfig = {\n workspace: string;\n routes: {\n index: string;\n areas: string;\n defaultArea: string;\n maxDelegationDepth: 1;\n };\n truth: {\n productRoot: string;\n engineeringRoot: string;\n };\n templates: {\n root: string;\n };\n generated: {\n portal: TruthmarkPortalConfig;\n };\n paths: {\n routesIndex: string;\n routeAreasRoot: string;\n productTruthRoot: string;\n engineeringTruthRoot: string;\n truthRoot?: string;\n templatesRoot: string;\n portalOutput: string;\n portalTemplate: string;\n };\n controlledPaths: string[];\n};\n\nexport type RawTruthmarkConfig = {\n version: 2;\n platforms?: TruthmarkPlatform[];\n truthmark: RawTruthmarkWorkspaceConfig;\n instruction_targets?: string[];\n frontmatter?: {\n required?: string[];\n recommended?: string[];\n };\n ignore?: string[];\n};\n\nexport type TruthmarkConfig = {\n version: 2;\n platforms: TruthmarkPlatform[];\n truthmark: TruthmarkWorkspaceConfig;\n instructionTargets: string[];\n frontmatter: {\n required: string[];\n recommended: string[];\n };\n ignore: string[];\n};\n\nexport const truthmarkConfigSchema = {\n type: \"object\",\n additionalProperties: false,\n required: [\"version\", \"truthmark\"],\n properties: {\n version: {\n type: \"integer\",\n const: 2,\n },\n platforms: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n enum: [...SUPPORTED_PLATFORMS],\n },\n minItems: 1,\n },\n truthmark: {\n type: \"object\",\n additionalProperties: false,\n required: [\"workspace\", \"generated\"],\n properties: {\n workspace: {\n type: \"string\",\n },\n generated: {\n type: \"object\",\n additionalProperties: false,\n required: [\"portal\"],\n properties: {\n portal: {\n type: \"object\",\n additionalProperties: false,\n required: [\"enabled\"],\n properties: {\n enabled: { type: \"boolean\" },\n },\n },\n },\n },\n },\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} as unknown as JSONSchemaType<RawTruthmarkConfig>;\n","import { DEFAULT_PLATFORMS, type TruthmarkConfig } from \"./schema.js\";\n\nexport const DEFAULT_TRUTHMARK_WORKSPACE = {\n workspace: \"docs/truthmark\",\n generated: {\n portal: {\n enabled: false,\n },\n },\n} as const;\n\nexport const DERIVED_TRUTHMARK_PATHS = {\n routesIndex: \"routes/areas.md\",\n routeAreasRoot: \"routes/areas\",\n defaultArea: \"repository\",\n maxDelegationDepth: 1,\n productTruthRoot: \"product\",\n engineeringTruthRoot: \"engineering\",\n templatesRoot: \"templates\",\n portalOutput: \"generated/portal\",\n portalTemplate: \"templates/portal.html\",\n} as const;\n\nexport const DEFAULT_INSTRUCTION_TARGETS = [\"AGENTS.md\"] as const;\n\nexport const createDefaultRawConfig = () => ({\n version: 2 as const,\n truthmark: {\n workspace: DEFAULT_TRUTHMARK_WORKSPACE.workspace,\n generated: {\n portal: { ...DEFAULT_TRUTHMARK_WORKSPACE.generated.portal },\n },\n },\n instruction_targets: [...DEFAULT_INSTRUCTION_TARGETS],\n frontmatter: {\n required: [],\n recommended: [\"status\", \"last_reviewed\"],\n },\n ignore: [\"node_modules/**\", \"vendor/**\", \"dist/**\", \"build/**\"],\n});\n\nexport const createDefaultConfig = (): TruthmarkConfig => ({\n version: 2,\n platforms: [...DEFAULT_PLATFORMS],\n truthmark: {\n workspace: DEFAULT_TRUTHMARK_WORKSPACE.workspace,\n routes: {\n index: DERIVED_TRUTHMARK_PATHS.routesIndex,\n areas: DERIVED_TRUTHMARK_PATHS.routeAreasRoot,\n defaultArea: DERIVED_TRUTHMARK_PATHS.defaultArea,\n maxDelegationDepth: DERIVED_TRUTHMARK_PATHS.maxDelegationDepth,\n },\n truth: {\n productRoot: DERIVED_TRUTHMARK_PATHS.productTruthRoot,\n engineeringRoot: DERIVED_TRUTHMARK_PATHS.engineeringTruthRoot,\n },\n templates: { root: DERIVED_TRUTHMARK_PATHS.templatesRoot },\n generated: {\n portal: { ...DEFAULT_TRUTHMARK_WORKSPACE.generated.portal },\n },\n paths: {\n routesIndex: \"docs/truthmark/routes/areas.md\",\n routeAreasRoot: \"docs/truthmark/routes/areas\",\n productTruthRoot: \"docs/truthmark/product\",\n engineeringTruthRoot: \"docs/truthmark/engineering\",\n templatesRoot: \"docs/truthmark/templates\",\n portalOutput: \"docs/truthmark/generated/portal\",\n portalTemplate: \"docs/truthmark/templates/portal.html\",\n },\n controlledPaths: [\n \"docs/truthmark/routes/areas.md\",\n \"docs/truthmark/routes/areas/**/*.md\",\n \"docs/truthmark/product/**/*.md\",\n \"docs/truthmark/engineering/**/*.md\",\n \"docs/truthmark/templates/*.md\",\n ],\n },\n instructionTargets: [...DEFAULT_INSTRUCTION_TARGETS],\n frontmatter: {\n required: [],\n recommended: [\"status\", \"last_reviewed\"],\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 \"product-capability\",\n \"engineering-behavior\",\n \"engineering-contract\",\n \"engineering-workflow\",\n \"engineering-architecture\",\n \"engineering-operations\",\n \"engineering-test-behavior\",\n] as const;\n\nexport type TruthDocumentKind = (typeof TRUTH_DOCUMENT_KINDS)[number];\nexport type TruthDocumentLane = \"product\" | \"engineering\";\n\nexport type TruthDocumentEntry = {\n path: string;\n kind: TruthDocumentKind;\n kindSource: \"explicit\" | \"inferred\" | \"defaulted\";\n lane: TruthDocumentLane;\n laneSource: \"explicit\" | \"inferred\" | \"defaulted\";\n realizedBy: string[];\n realizes: string[];\n dependsOn: string[];\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\nconst uniqueSorted = (values: string[]): string[] =>\n [...new Set(values)].sort();\n\nexport const mergeTruthDocumentEntryRelationships = (\n first: TruthDocumentEntry,\n second: TruthDocumentEntry,\n): TruthDocumentEntry => ({\n ...first,\n realizedBy: uniqueSorted([...first.realizedBy, ...second.realizedBy]),\n realizes: uniqueSorted([...first.realizes, ...second.realizes]),\n dependsOn: uniqueSorted([...first.dependsOn, ...second.dependsOn]),\n});\n\ntype 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 productTruthRoot?: string;\n engineeringTruthRoot?: string;\n};\n\nconst DEFAULT_PRODUCT_TRUTH_DOCS_ROOT = \"docs/truthmark/product\";\nconst DEFAULT_ENGINEERING_TRUTH_DOCS_ROOT = \"docs/truthmark/engineering\";\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 productTruthRoot = (\n options.productTruthRoot ?? DEFAULT_PRODUCT_TRUTH_DOCS_ROOT\n )\n ?.replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n const engineeringTruthRoot = (\n options.engineeringTruthRoot ??\n options.truthDocsRoot ??\n DEFAULT_ENGINEERING_TRUTH_DOCS_ROOT\n )\n ?.replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n\n if (productTruthRoot && normalizedPath.startsWith(`${productTruthRoot}/`)) {\n return \"product-capability\";\n }\n\n if (\n engineeringTruthRoot &&\n normalizedPath.startsWith(`${engineeringTruthRoot}/`)\n ) {\n if (normalizedPath.includes(\"/contracts/\")) return \"engineering-contract\";\n if (normalizedPath.includes(\"/workflows/\")) return \"engineering-workflow\";\n if (normalizedPath.includes(\"/architecture/\"))\n return \"engineering-architecture\";\n if (normalizedPath.includes(\"/operations/\"))\n return \"engineering-operations\";\n if (normalizedPath.includes(\"/tests/\")) return \"engineering-test-behavior\";\n return \"engineering-behavior\";\n }\n\n return null;\n};\n\nconst inferTruthDocumentLaneFromPath = (\n documentPath: string,\n options: ParseAreasMarkdownOptions = {},\n): TruthDocumentLane | null => {\n const normalizedPath = documentPath.replaceAll(\"\\\\\", \"/\");\n const productTruthRoot = (\n options.productTruthRoot ?? DEFAULT_PRODUCT_TRUTH_DOCS_ROOT\n )\n .replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n const engineeringTruthRoot = (\n options.engineeringTruthRoot ??\n options.truthDocsRoot ??\n DEFAULT_ENGINEERING_TRUTH_DOCS_ROOT\n )\n .replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n\n if (normalizedPath.startsWith(`${productTruthRoot}/`)) {\n return \"product\";\n }\n\n if (normalizedPath.startsWith(`${engineeringTruthRoot}/`)) {\n return \"engineering\";\n }\n\n return null;\n};\n\nexport const laneForTruthDocumentKind = (\n kind: TruthDocumentKind,\n): TruthDocumentLane => {\n return kind.startsWith(\"product-\") ? \"product\" : \"engineering\";\n};\n\nexport const docTypeForTruthDocumentKind = (\n kind: TruthDocumentKind,\n): string => {\n if (kind.startsWith(\"product-\")) {\n return \"product\";\n }\n return kind.slice(\"engineering-\".length);\n};\n\nconst parseStringListField = (rawEntry: unknown, field: string): string[] => {\n if (!rawEntry || typeof rawEntry !== \"object\" || !(field in rawEntry)) {\n return [];\n }\n\n const value = (rawEntry as Record<string, unknown>)[field];\n\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.filter((entry): entry is string => typeof entry === \"string\");\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 const inferredLane = inferTruthDocumentLaneFromPath(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 ?? \"engineering-behavior\",\n kindSource: inferredKind ? (\"inferred\" as const) : (\"defaulted\" as const),\n lane: inferredLane ?? \"engineering\",\n laneSource: inferredLane ? (\"inferred\" as const) : (\"defaulted\" as const),\n realizedBy: [],\n realizes: [],\n dependsOn: [],\n };\n });\n\n return {\n truthDocuments,\n truthDocumentEntries,\n diagnostics,\n };\n};\n\nconst parseTruthDocumentsFromYaml = (\n sectionLines: string[],\n areaName: string,\n options: ParseAreasMarkdownOptions,\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 const lane =\n rawEntry && typeof rawEntry === \"object\" && \"lane\" in rawEntry\n ? (rawEntry as { lane?: unknown }).lane\n : null;\n const inferredKind =\n typeof path === \"string\"\n ? inferTruthDocumentKindFromPath(path, options)\n : null;\n const inferredLane =\n typeof path === \"string\"\n ? inferTruthDocumentLaneFromPath(path, options)\n : null;\n const normalizedKind = isTruthDocumentKind(kind) ? kind : inferredKind;\n const normalizedLane =\n lane === \"product\" || lane === \"engineering\"\n ? lane\n : normalizedKind\n ? laneForTruthDocumentKind(normalizedKind)\n : inferredLane;\n\n if (\n typeof path !== \"string\" ||\n path.trim().length === 0 ||\n !normalizedKind ||\n !normalizedLane\n ) {\n diagnostics.push(\n createAreaDiagnostic(\n `Area ${areaName} truth_documents entries must include non-empty path plus valid lane and kind fields.`,\n areaName,\n ),\n );\n continue;\n }\n\n truthDocumentEntries.push({\n path: path.trim(),\n kind: normalizedKind,\n kindSource: isTruthDocumentKind(kind) ? \"explicit\" : \"inferred\",\n lane: normalizedLane,\n laneSource:\n lane === \"product\" || lane === \"engineering\" ? \"explicit\" : \"inferred\",\n realizedBy: parseStringListField(rawEntry, \"realized_by\"),\n realizes: parseStringListField(rawEntry, \"realizes\"),\n dependsOn: parseStringListField(rawEntry, \"depends_on\"),\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(\n sectionLines,\n areaName,\n options,\n );\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 const heading = areaHeadingMatch[1]?.trim() ?? null;\n flushArea();\n currentAreaName = heading === \"Source References\" ? null : heading;\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 type { TruthmarkConfig } from \"../config/schema.js\";\n\nexport type TruthLane = \"product\" | \"engineering\";\n\nexport const PRODUCT_TRUTH_KINDS = [\"product-capability\"] as const;\nexport const ENGINEERING_TRUTH_KINDS = [\n \"engineering-behavior\",\n \"engineering-contract\",\n \"engineering-workflow\",\n \"engineering-architecture\",\n \"engineering-operations\",\n \"engineering-test-behavior\",\n] as const;\n\nexport const resolveTruthDocsRoot = (config: Pick<TruthmarkConfig, \"truthmark\">): string => {\n return config.truthmark.paths.engineeringTruthRoot;\n};\n\nexport const resolveProductTruthRoot = (config: Pick<TruthmarkConfig, \"truthmark\">): string => {\n return config.truthmark.paths.productTruthRoot;\n};\n\nexport const resolveEngineeringTruthRoot = (\n config: Pick<TruthmarkConfig, \"truthmark\">,\n): string => {\n return config.truthmark.paths.engineeringTruthRoot;\n};\n\nexport const truthLaneRoots = (config: Pick<TruthmarkConfig, \"truthmark\">) => ({\n product: resolveProductTruthRoot(config),\n engineering: resolveEngineeringTruthRoot(config),\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 { resolveRepoPath, type FileWriteResult, writeRepoFile } from \"../fs/paths.js\";\nimport { scaffoldHierarchy } from \"./hierarchy.js\";\nimport { findAutoRemovableRetiredGeneratedSurfaces } from \"../checks/generated-surfaces.js\";\nimport { renderAgentsBlock, TRUTHMARK_BLOCK_END, TRUTHMARK_BLOCK_START } from \"../templates/agents-block.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 CANONICAL_MANAGED_LINES = new Set(\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);\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 upsertManagedBlock = (existingContent: string | null, block: string): string => {\n if (!existingContent || existingContent.trim().length === 0) {\n return block;\n }\n\n const normalizedExistingContent = 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 === \".github/prompts/truthmark-realize.prompt.md\" ||\n filePath.startsWith(\".github/skills/truthmark-realize/\") ||\n filePath.startsWith(\".claude/skills/truthmark-realize/\") ||\n filePath.startsWith(\".opencode/skills/truthmark-realize/\") ||\n filePath.startsWith(\".agents/skills/truthmark-realize/\") ||\n filePath.startsWith(\".antigravity/rules/truthmark-realize\") ||\n filePath.startsWith(\".cursor/rules/truthmark-realize\") ||\n filePath.startsWith(\".cursor/skills/truthmark-realize/\")\n ) {\n return \"realization\";\n }\n\n if (\n filePath === \"CLAUDE.md\" ||\n filePath === \".github/copilot-instructions.md\" ||\n filePath.startsWith(\".github/prompts/truthmark-\") ||\n filePath.startsWith(\".github/agents/truth-\") ||\n filePath.startsWith(\".github/skills/truthmark-\") ||\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 filePath.startsWith(\".antigravity/rules/truthmark-\") ||\n filePath.startsWith(\".cursor/rules/truthmark-\") ||\n filePath.startsWith(\".cursor/skills/truthmark-\")\n ) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".agents/skills/truthmark-\")) {\n return \"truth-sync\";\n }\n\n\n if (filePath === config.truthmark.paths.routesIndex) {\n return \"area-index\";\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 workspace paths, 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 results: FileWriteResult[] = [];\n\n const config = loadedConfig.config;\n results.push(...(await scaffoldHierarchy(rootDir, config)));\n const block = renderAgentsBlock(config);\n const platformFiles = renderGeneratedSurfaces(config, block);\n const expectedSurfacePaths = new Set(platformFiles.map((file) => file.path));\n\n for (const file of platformFiles) {\n results.push(await writePlatformFile(rootDir, file));\n }\n\n const obsoleteSurfacePaths = await findAutoRemovableRetiredGeneratedSurfaces(\n rootDir,\n expectedSurfacePaths,\n );\n\n for (const obsoletePath of obsoleteSurfacePaths) {\n await fs.rm(resolveRepoPath(rootDir, obsoletePath), { force: true });\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),\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\";\nimport path from \"node:path\";\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 { DEFAULT_INSTRUCTION_TARGETS, DERIVED_TRUTHMARK_PATHS } 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 category: \"config\",\n severity: \"error\",\n message,\n file,\n});\n\nexport const normalizeRepoRelativePath = (value: string): string => {\n const slashNormalized = value.replace(/\\\\/gu, \"/\");\n return path.posix.normalize(slashNormalized).replace(/\\/+$/u, \"\");\n};\n\nconst isUnsafeRepoRelativePath = (value: string): boolean => {\n const slashNormalized = value.replace(/\\\\/gu, \"/\");\n const normalized = normalizeRepoRelativePath(value);\n const parts = slashNormalized.split(\"/\");\n\n return (\n normalized.length === 0 ||\n normalized === \".\" ||\n normalized === \"..\" ||\n path.isAbsolute(value) ||\n path.posix.isAbsolute(slashNormalized) ||\n path.win32.isAbsolute(value) ||\n /^[A-Za-z]:/u.test(value) ||\n normalized.startsWith(\"../\") ||\n parts.includes(\"..\")\n );\n};\n\nconst joinWorkspacePath = (workspace: string, childPath: string): string => {\n return normalizeRepoRelativePath(`${workspace}/${childPath}`);\n};\n\nconst portalOutputFor = (workspace: string): string =>\n joinWorkspacePath(workspace, DERIVED_TRUTHMARK_PATHS.portalOutput);\n\nconst pathsOverlap = (left: string, right: string): boolean => {\n const normalizedLeft = normalizeRepoRelativePath(left);\n const normalizedRight = normalizeRepoRelativePath(right);\n\n return (\n normalizedLeft === normalizedRight ||\n normalizedLeft.startsWith(`${normalizedRight}/`) ||\n normalizedRight.startsWith(`${normalizedLeft}/`)\n );\n};\n\nconst CONFIG_PATH = \".truthmark/config.yml\";\nconst FORBIDDEN_WORKSPACE_OVERLAPS = [\n \".git\",\n \".truthmark\",\n \"package.json\",\n \"package-lock.json\",\n \"pnpm-lock.yaml\",\n \"yarn.lock\",\n \"src\",\n \"tests\",\n] as const;\n\nconst unsupportedShapeDiagnostics = (parsedConfig: unknown, configPath: string): Diagnostic[] => {\n if (!parsedConfig || typeof parsedConfig !== \"object\" || Array.isArray(parsedConfig)) {\n return [];\n }\n\n const record = parsedConfig as Record<string, unknown>;\n const diagnostics: Diagnostic[] = [];\n\n if (record.version !== 2) {\n diagnostics.push(\n toConfigDiagnostic(\n \"Unsupported Truthmark config shape. This release requires version: 2 with a truthmark workspace block.\",\n configPath,\n ),\n );\n }\n\n if (\"docs\" in record || \"authority\" in record) {\n diagnostics.push(\n toConfigDiagnostic(\n \"Unsupported Truthmark config shape. Remove old docs.roots and legacy authority settings; use version: 2 truthmark.workspace paths.\",\n configPath,\n ),\n );\n }\n\n return diagnostics;\n};\n\nconst validateWorkspacePaths = (\n rawConfig: RawTruthmarkConfig,\n configPath: string,\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const workspace = normalizeRepoRelativePath(rawConfig.truthmark.workspace);\n\n if (\n isUnsafeRepoRelativePath(rawConfig.truthmark.workspace) ||\n FORBIDDEN_WORKSPACE_OVERLAPS.some((forbidden) => pathsOverlap(workspace, forbidden))\n ) {\n diagnostics.push(\n toConfigDiagnostic(\n \"truthmark.workspace must be a non-empty repo-relative directory that does not overlap repository control, package, source, test, or instruction paths.\",\n configPath,\n ),\n );\n }\n\n for (const target of rawConfig.instruction_targets ?? DEFAULT_INSTRUCTION_TARGETS) {\n if (isUnsafeRepoRelativePath(target) || pathsOverlap(workspace, target)) {\n diagnostics.push(\n toConfigDiagnostic(\n \"instruction_targets must be repo-relative files outside truthmark.workspace.\",\n configPath,\n ),\n );\n }\n }\n\n return diagnostics;\n};\n\nconst normalizeConfig = (rawConfig: RawTruthmarkConfig): TruthmarkConfig => {\n const workspace = normalizeRepoRelativePath(rawConfig.truthmark.workspace);\n const routesIndex = joinWorkspacePath(workspace, DERIVED_TRUTHMARK_PATHS.routesIndex);\n const routeAreasRoot = joinWorkspacePath(workspace, DERIVED_TRUTHMARK_PATHS.routeAreasRoot);\n const productTruthRoot = joinWorkspacePath(workspace, DERIVED_TRUTHMARK_PATHS.productTruthRoot);\n const engineeringTruthRoot = joinWorkspacePath(\n workspace,\n DERIVED_TRUTHMARK_PATHS.engineeringTruthRoot,\n );\n const templatesRoot = joinWorkspacePath(workspace, DERIVED_TRUTHMARK_PATHS.templatesRoot);\n const portalOutput = portalOutputFor(workspace);\n const portalTemplate = joinWorkspacePath(workspace, DERIVED_TRUTHMARK_PATHS.portalTemplate);\n\n return {\n version: rawConfig.version,\n platforms: rawConfig.platforms ?? [...DEFAULT_PLATFORMS],\n truthmark: {\n workspace,\n routes: {\n index: DERIVED_TRUTHMARK_PATHS.routesIndex,\n areas: DERIVED_TRUTHMARK_PATHS.routeAreasRoot,\n defaultArea: DERIVED_TRUTHMARK_PATHS.defaultArea,\n maxDelegationDepth: DERIVED_TRUTHMARK_PATHS.maxDelegationDepth,\n },\n truth: {\n productRoot: DERIVED_TRUTHMARK_PATHS.productTruthRoot,\n engineeringRoot: DERIVED_TRUTHMARK_PATHS.engineeringTruthRoot,\n },\n templates: {\n root: DERIVED_TRUTHMARK_PATHS.templatesRoot,\n },\n generated: {\n portal: {\n enabled: rawConfig.truthmark.generated.portal.enabled,\n },\n },\n paths: {\n routesIndex,\n routeAreasRoot,\n productTruthRoot,\n engineeringTruthRoot,\n templatesRoot,\n portalOutput,\n portalTemplate,\n },\n controlledPaths: [\n routesIndex,\n `${routeAreasRoot}/**/*.md`,\n `${productTruthRoot}/**/*.md`,\n `${engineeringTruthRoot}/**/*.md`,\n `${templatesRoot}/*.md`,\n ],\n },\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 absolutePath = resolveRepoPath(rootDir, CONFIG_PATH);\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.\", CONFIG_PATH)],\n configPath: CONFIG_PATH,\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 CONFIG_PATH,\n ),\n ],\n configPath: CONFIG_PATH,\n };\n }\n\n const unsupportedDiagnostics = unsupportedShapeDiagnostics(parsedConfig, CONFIG_PATH);\n if (unsupportedDiagnostics.length > 0) {\n return {\n status: \"invalid\",\n config: null,\n diagnostics: unsupportedDiagnostics,\n configPath: CONFIG_PATH,\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, CONFIG_PATH);\n }),\n configPath: CONFIG_PATH,\n };\n }\n\n const pathDiagnostics = validateWorkspacePaths(parsedConfig as RawTruthmarkConfig, CONFIG_PATH);\n\n if (pathDiagnostics.length > 0) {\n return {\n status: \"invalid\",\n config: null,\n diagnostics: pathDiagnostics,\n configPath: CONFIG_PATH,\n };\n }\n\n return {\n status: \"loaded\",\n config: normalizeConfig(parsedConfig as RawTruthmarkConfig),\n diagnostics: [],\n configPath: CONFIG_PATH,\n };\n};\n","import fs from \"node:fs/promises\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { FileWriteResult } from \"../fs/paths.js\";\nimport { ensureRepoFile, resolveRepoPath, writeRepoFile } from \"../fs/paths.js\";\nimport { parseAreasMarkdown } from \"../routing/areas.js\";\nimport {\n resolveEngineeringTruthRoot,\n resolveTruthDocsRoot,\n} from \"../truth/docs.js\";\nimport {\n renderChildAreaTemplate,\n mergeTruthDocTemplate,\n renderArchitectureDocTemplateFile,\n renderBehaviorDocTemplateFile,\n renderContractDocTemplateFile,\n renderTruthDomainReadmeTemplate,\n renderTruthRootReadmeTemplate,\n renderHierarchicalAreasIndexTemplate,\n renderOperationsDocTemplateFile,\n renderProductCapabilityDocTemplateFile,\n renderBootstrapRoutingDocTemplate,\n renderTestBehaviorDocTemplateFile,\n renderWorkflowDocTemplateFile,\n} from \"../templates/init-files.js\";\n\nconst truthRoot = resolveTruthDocsRoot;\nconst BEHAVIOR_DOC_TEMPLATE_FILE_NAME = \"engineering-behavior.md\";\nconst CONTRACT_DOC_TEMPLATE_FILE_NAME = \"engineering-contract.md\";\nconst ARCHITECTURE_DOC_TEMPLATE_FILE_NAME = \"engineering-architecture.md\";\nconst WORKFLOW_DOC_TEMPLATE_FILE_NAME = \"engineering-workflow.md\";\nconst OPERATIONS_DOC_TEMPLATE_FILE_NAME = \"engineering-operations.md\";\nconst TEST_BEHAVIOR_DOC_TEMPLATE_FILE_NAME = \"engineering-test-behavior.md\";\nconst PRODUCT_CAPABILITY_DOC_TEMPLATE_FILE_NAME = \"product-capability.md\";\n\nconst rootIndexReferencesChildRoute = async (\n rootDir: string,\n rootIndexPath: string,\n childRoutePath: string,\n): Promise<boolean> => {\n const rootIndexSource = await fs.readFile(\n resolveRepoPath(rootDir, rootIndexPath),\n \"utf8\",\n );\n const parsedRootIndex = parseAreasMarkdown(rootIndexSource);\n\n return parsedRootIndex.areaFileReferences.some((areaReference) =>\n areaReference.areaFiles.includes(childRoutePath),\n );\n};\n\nconst truthTemplatePath = (\n config: TruthmarkConfig,\n fileName: string,\n): string => {\n return `${config.truthmark.paths.templatesRoot}/${fileName}`;\n};\n\nconst ensureOrUpdateTruthDocTemplate = async (\n rootDir: string,\n templatePath: string,\n defaultTemplate: string,\n): Promise<FileWriteResult> => {\n const seededResult = await ensureRepoFile(\n rootDir,\n templatePath,\n defaultTemplate,\n );\n\n if (seededResult.status !== \"unchanged\") {\n return seededResult;\n }\n\n const existingTemplate = await fs.readFile(\n resolveRepoPath(rootDir, templatePath),\n \"utf8\",\n );\n const mergedTemplate = mergeTruthDocTemplate(\n existingTemplate,\n defaultTemplate,\n );\n\n return writeRepoFile(rootDir, templatePath, mergedTemplate);\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.truthmark.routes.defaultArea}`;\n const childRoutePath = `${config.truthmark.paths.routeAreasRoot}/${config.truthmark.routes.defaultArea}.md`;\n\n results.push(\n await ensureRepoFile(\n rootDir,\n config.truthmark.paths.routesIndex,\n renderHierarchicalAreasIndexTemplate(config),\n ),\n );\n if (\n await rootIndexReferencesChildRoute(\n rootDir,\n config.truthmark.paths.routesIndex,\n childRoutePath,\n )\n ) {\n results.push(\n await ensureRepoFile(\n rootDir,\n childRoutePath,\n renderChildAreaTemplate(config),\n ),\n );\n }\n results.push(\n await ensureRepoFile(\n rootDir,\n `${resolveEngineeringTruthRoot(config)}/README.md`,\n renderTruthRootReadmeTemplate(config, \"engineering\"),\n ),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n `${config.truthmark.paths.productTruthRoot}/README.md`,\n renderTruthRootReadmeTemplate(config, \"product\"),\n ),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDomainRoot}/README.md`,\n renderTruthDomainReadmeTemplate(config),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, BEHAVIOR_DOC_TEMPLATE_FILE_NAME),\n renderBehaviorDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, CONTRACT_DOC_TEMPLATE_FILE_NAME),\n renderContractDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, ARCHITECTURE_DOC_TEMPLATE_FILE_NAME),\n renderArchitectureDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, WORKFLOW_DOC_TEMPLATE_FILE_NAME),\n renderWorkflowDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, OPERATIONS_DOC_TEMPLATE_FILE_NAME),\n renderOperationsDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, TEST_BEHAVIOR_DOC_TEMPLATE_FILE_NAME),\n renderTestBehaviorDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, PRODUCT_CAPABILITY_DOC_TEMPLATE_FILE_NAME),\n renderProductCapabilityDocTemplateFile(),\n ),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDomainRoot}/bootstrap-routing.md`,\n renderBootstrapRoutingDocTemplate(config),\n ),\n );\n return results;\n};\n","import fs from \"node:fs/promises\";\nimport type { Dirent } from \"node:fs\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { resolveRepoPath } from \"../fs/paths.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n TRUTHMARK_BLOCK_END,\n TRUTHMARK_BLOCK_START,\n} from \"../templates/agents-block.js\";\nimport { renderGeneratedSurfaces } from \"../templates/generated-surfaces.js\";\n\nconst readOptionalFile = async (\n rootDir: string,\n filePath: string,\n): 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 = (\n content: string | null,\n): 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 GENERATED_HOST_SKILL_ROOTS = [\n \".agents/skills\",\n \".opencode/skills\",\n \".claude/skills\",\n \".github/skills\",\n \".cursor/skills\",\n] as const;\n\nconst RETIRED_SKILL_HELPER_PATHS = [\n \"helper-manifest.yml\",\n \"support/helper-policy.md\",\n] as const;\n\nconst RETIRED_PACKAGE_DIRECTORIES = [\"truthmark-preview\"] as const;\n\nconst RETIRED_GENERATED_SURFACE_PATHS = [\n \"GEMINI.md\",\n \".github/prompts/truthmark-preview.prompt.md\",\n \".cursor/rules/truthmark-structure.mdc\",\n \".cursor/rules/truthmark-document.mdc\",\n \".cursor/rules/truthmark-sync.mdc\",\n \".cursor/rules/truthmark-realize.mdc\",\n \".cursor/rules/truthmark-check.mdc\",\n \".cursor/rules/truthmark-portal.mdc\",\n] as const;\n\nconst RETIRED_GENERATED_SURFACE_ROOTS = [\".gemini\"] as const;\n\nconst isRetiredGeminiSurfacePath = (filePath: string): boolean =>\n filePath === \"GEMINI.md\" || filePath.startsWith(\".gemini/\");\n\nconst obsoleteGeneratedSurfaceMessage = (surfacePath: string): string => {\n if (isRetiredGeminiSurfacePath(surfacePath)) {\n return `Generated surface ${surfacePath} is obsolete; remove stale Gemini instructions manually if they are no longer wanted.`;\n }\n\n return `Generated surface ${surfacePath} is obsolete; rerun truthmark init.`;\n};\n\ntype RetiredSurfaceCollectionOptions = {\n includeGeminiSurfaces?: boolean;\n};\n\nconst pathExists = async (absolutePath: string): Promise<boolean> => {\n try {\n await fs.access(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 listDirectoryFiles = async (\n rootDir: string,\n packageRoot: string,\n): Promise<string[]> => {\n const stack = [packageRoot];\n const files: string[] = [];\n\n while (stack.length > 0) {\n const current = stack.pop();\n\n if (current === undefined) {\n continue;\n }\n\n const absoluteCurrent = resolveRepoPath(rootDir, current);\n const entries = await fs.readdir(absoluteCurrent, {\n withFileTypes: true,\n });\n\n for (const entry of entries) {\n const next = `${current}/${entry.name}`;\n\n if (entry.isDirectory()) {\n stack.push(next);\n } else {\n files.push(next);\n }\n }\n }\n\n return files;\n};\n\nconst collectRetiredGeneratedSurfaces = async (\n rootDir: string,\n expectedSurfacePaths: Set<string>,\n options: RetiredSurfaceCollectionOptions = {},\n): Promise<string[]> => {\n const legacyCandidates = new Set<string>();\n const includeGeminiSurfaces = options.includeGeminiSurfaces ?? true;\n\n for (const retiredPath of RETIRED_GENERATED_SURFACE_PATHS) {\n if (!includeGeminiSurfaces && isRetiredGeminiSurfacePath(retiredPath)) {\n continue;\n }\n\n const absoluteRetiredPath = resolveRepoPath(rootDir, retiredPath);\n\n if (\n (await pathExists(absoluteRetiredPath)) &&\n !expectedSurfacePaths.has(retiredPath)\n ) {\n legacyCandidates.add(retiredPath);\n }\n }\n\n for (const retiredRoot of RETIRED_GENERATED_SURFACE_ROOTS) {\n if (!includeGeminiSurfaces && isRetiredGeminiSurfacePath(`${retiredRoot}/`)) {\n continue;\n }\n\n const absoluteRetiredRoot = resolveRepoPath(rootDir, retiredRoot);\n\n if (!(await pathExists(absoluteRetiredRoot))) {\n continue;\n }\n\n const retiredFiles = await listDirectoryFiles(rootDir, retiredRoot);\n\n for (const filePath of retiredFiles) {\n if (!expectedSurfacePaths.has(filePath)) {\n legacyCandidates.add(filePath);\n }\n }\n }\n\n for (const skillRoot of GENERATED_HOST_SKILL_ROOTS) {\n const absoluteSkillRoot = resolveRepoPath(rootDir, skillRoot);\n\n let skillPackages: Dirent[] = [];\n\n try {\n skillPackages = await fs.readdir(absoluteSkillRoot, {\n withFileTypes: true,\n });\n } catch (error: unknown) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n continue;\n }\n\n throw error;\n }\n\n const packageNames = skillPackages\n .filter((entry) => entry.isDirectory() && entry.name.startsWith(\"truthmark-\"))\n .map((entry) => entry.name);\n\n for (const packageName of RETIRED_PACKAGE_DIRECTORIES) {\n if (!packageNames.includes(packageName)) {\n continue;\n }\n\n const packageRoot = `${skillRoot}/${packageName}`;\n const packageFiles = await listDirectoryFiles(rootDir, packageRoot);\n\n for (const filePath of packageFiles) {\n if (!expectedSurfacePaths.has(filePath)) {\n legacyCandidates.add(filePath);\n }\n }\n }\n\n for (const packageName of packageNames) {\n for (const retiredName of RETIRED_SKILL_HELPER_PATHS) {\n const retiredPath = `${packageName}/${retiredName}`;\n const relativeRetiredPath = `${skillRoot}/${retiredPath}`;\n const absoluteRetiredPath = resolveRepoPath(rootDir, relativeRetiredPath);\n\n if (\n (await pathExists(absoluteRetiredPath)) &&\n !expectedSurfacePaths.has(relativeRetiredPath)\n ) {\n legacyCandidates.add(relativeRetiredPath);\n }\n }\n }\n }\n\n return Array.from(legacyCandidates);\n};\n\nexport const checkGeneratedSurfaces = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n const renderedSurfaces = renderGeneratedSurfaces(config);\n\n for (const surface of renderedSurfaces) {\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\n const staleSurfaces = await collectRetiredGeneratedSurfaces(\n rootDir,\n new Set(renderedSurfaces.map((surface) => surface.path)),\n );\n\n for (const surfacePath of staleSurfaces) {\n diagnostics.push({\n category: \"generated-surface\",\n severity: \"review\",\n message: obsoleteGeneratedSurfaceMessage(surfacePath),\n file: surfacePath,\n });\n }\n\n return diagnostics;\n};\n\nexport const findRetiredGeneratedSurfaces = async (\n rootDir: string,\n expectedSurfacePaths: Set<string>,\n): Promise<string[]> => {\n return collectRetiredGeneratedSurfaces(rootDir, expectedSurfacePaths);\n};\n\nexport const findAutoRemovableRetiredGeneratedSurfaces = async (\n rootDir: string,\n expectedSurfacePaths: Set<string>,\n): Promise<string[]> => {\n return collectRetiredGeneratedSurfaces(rootDir, expectedSurfacePaths, {\n includeGeminiSurfaces: false,\n });\n};\n","export type ClaimEvidenceResult = \"supported\" | \"narrowed\" | \"removed\" | \"blocked\";\n\nexport type ClaimEvidenceItem = {\n claim: string;\n evidence: string[];\n result: ClaimEvidenceResult;\n};\n\ntype AuditEvidenceConfidence = \"high\" | \"medium\" | \"low\";\n\ntype 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 {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"../truth/docs.js\";\n\nexport {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n resolveTruthDocsRoot,\n} from \"../truth/docs.js\";\n\nconst renderBulletLine = (line: string): string => {\n const normalized = line.trim().replace(/^-\\s*/u, \"\");\n return `- ${normalized}`;\n};\n\nexport const renderBulletBlock = (lines: string, indent = \" \"): string => {\n return lines\n .split(/\\n/u)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => `${indent}${renderBulletLine(line)}`)\n .join(\"\\n\");\n};\n\nexport const renderLaneClassificationRuleBlock = (\n config: TruthmarkConfig = defaultAgentConfig(),\n indent = \" \",\n): string => {\n const [, ...rules] =\n renderLaneClassificationInstructions(config).split(/\\n/u);\n\n return renderBulletBlock(rules.join(\"\\n\"), indent);\n};\n\nexport const renderReadOnlyLaneClassificationRuleBlock = (\n config: TruthmarkConfig = defaultAgentConfig(),\n indent = \" \",\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n\n return renderBulletBlock(\n [\n \"classify the request or changed surface as product-lane, engineering-lane, both-lane, or ambiguous for reporting only\",\n `product-lane ownership belongs under ${productTruthRoot} and describes product promises, boundaries, rationale, decisions, and success criteria`,\n `engineering-lane ownership belongs under ${engineeringTruthRoot} and describes source-backed current realization, contracts, architecture, workflows, operations, or tests`,\n \"both-lane ownership uses separate product and engineering docs cross-linked in route YAML with realized_by and realizes, not in doc frontmatter\",\n \"ambiguous lane ownership should be reported for manual handoff or routed to Truth Structure\",\n LANE_INVARIANT,\n ].join(\"\\n\"),\n indent,\n );\n};\n\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 \"Product decisions belong in product truth; engineering, architecture, contract, workflow, and operational decisions belong in engineering truth.\",\n].join(\"\\n\");\n\nexport const LANE_INVARIANT =\n \"Do not make product docs a summary of engineering docs. Do not make engineering docs a detailed version of product docs. Product truth says what must be true and why. Engineering truth says how the repository currently realizes it.\";\n\nexport const renderLaneClassificationInstructions = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n\n return [\n \"Lane review questions:\",\n \"- before writing canonical truth docs, classify the request or change as product-lane, engineering-lane, both-lane, or ambiguous\",\n `- product-lane writes belong under ${productTruthRoot} and state product promises, boundaries, rationale, decisions, and success criteria`,\n `- engineering-lane writes belong under ${engineeringTruthRoot} and state source-backed current realization, contracts, architecture, workflows, operations, or tests`,\n \"- both-lane work must write separate product and engineering docs and cross-link them in route YAML with realized_by and realizes, not in doc frontmatter\",\n \"- ambiguous lane ownership must stop or invoke Truth Structure instead of writing a mixed document\",\n `- ${LANE_INVARIANT}`,\n ].join(\"\\n\");\n};\n\nexport const EVIDENCE_AUTHORITY_INSTRUCTIONS = [\n \"Repository instruction files and explicitly configured policy docs remain instruction authority when present; do not assume a repository uses any particular policy path.\",\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 WorkflowState/action context may guide routing, write boundaries, 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 any present Truthmark config, 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 template under the configured Truthmark templates root.\",\n \"Supported kinds: product-capability, engineering-behavior, engineering-contract, engineering-architecture, engineering-workflow, engineering-operations, and engineering-test-behavior.\",\n \"Treat the HTML comments under each template section as normative authoring guidance for that section.\",\n \"Align existing docs to that template and write or repair section content so it satisfies the comment guidance while preserving accurate authored content.\",\n \"If the template is missing, use lane-specific sections: product truth says what must be true and why; engineering truth says how the repository currently realizes it.\",\n \"Teams may edit template files under the configured Truthmark templates root to define their local truth-doc standards.\",\n].join(\"\\n\");\n\nexport const TRUTH_DOC_AUTHORING_STYLE_INSTRUCTIONS =\n \"Prefer diff-friendly Markdown: one durable claim per bullet or line, paragraphs no longer than one or two short sentences, and bullets or tables for rules, criteria, fields, files, and lists.\";\n\nexport const renderTruthDocOwnershipGateSection = (\n subject: string,\n outcome: string,\n): string => {\n return [\n \"Truth-doc ownership review:\",\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 Manual handoff reason as applicable\",\n ].join(\"\\n\");\n};\n\nexport const TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS = [\n \"Decision/Rationale preservation review:\",\n \"- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions, Engineering Decisions, and Rationale sections in every source or touched truth doc\",\n \"- preserve each current decision and rationale in the correct product or engineering lane owner; 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, stop with manual-review files instead of deleting it or guessing\",\n \"- after the edit, verify every touched truth doc keeps lane-appropriate decision/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 review:\",\n `- ${scope}`,\n \"- repair shape in place only after the ownership review 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 record unsupported or stale claims for manual handoff\",\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 checklist:\",\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, lane-specific 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 record unsupported claims for manual handoff\",\n `- ${noImpactedDocOutcome}`,\n ].join(\"\\n\");\n};\n\nexport const renderTopologyEvidenceGateSection = (): string => {\n return [\n \"Evidence checklist:\",\n \"- apply the evidence checklist before finishing when Truth Structure writes routed docs, ownership claims, lane-specific 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 record unsupported claims for manual handoff\",\n ].join(\"\\n\");\n};\n\nexport const renderAuditEvidenceGateSection = (): string => {\n return [\n \"Evidence checklist:\",\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 =\n 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(\n (agent) => `@${agent.replace(/_/gu, \"-\")}`,\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 readOnlyWorkerLabel =\n 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(\n (agent) => `${agent.replace(/_/gu, \"-\")} subagent`,\n );\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(\n (agent) => `@${agent.replace(/_/gu, \"-\")}`,\n );\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 productRoot = resolveProductTruthRoot(config);\n const engineeringRoot = resolveEngineeringTruthRoot(config);\n\n return [\n \"Truthmark hierarchy hints:\",\n \"- Config, when present: .truthmark/config.yml\",\n `- Root route index, when present: ${config.truthmark.paths.routesIndex}`,\n `- Area route files, when present: ${config.truthmark.paths.routeAreasRoot}/**/*.md`,\n `- Product truth docs, when present: ${productRoot}/**/*.md`,\n `- Engineering truth docs, when present: ${engineeringRoot}/**/*.md`,\n ].join(\"\\n\");\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n defaultAgentConfig,\n resolveProductTruthRoot,\n resolveEngineeringTruthRoot,\n} from \"../agents/shared.js\";\n\nexport const TRUTHMARK_BLOCK_START = \"<!-- truthmark:start -->\";\nexport const TRUTHMARK_BLOCK_END = \"<!-- truthmark:end -->\";\n\nconst renderCompactHierarchySummary = (config: TruthmarkConfig): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n const truthDocRoots = Array.from(\n new Set([productTruthRoot, engineeringTruthRoot]),\n ).map((truthRoot) => `${truthRoot}/**/*.md`);\n\n return `Hierarchy hints: config .truthmark/config.yml when present; routes ${config.truthmark.paths.routesIndex} and ${config.truthmark.paths.routeAreasRoot}/**/*.md when present; Truth docs: ${truthDocRoots.join(\" and \")} when present.`;\n};\n\nexport const renderAgentsBlock = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const portalLine = config.truthmark.generated.portal.enabled\n ? `Truthmark Portal is a separate manual-only presentation workflow. Run it only when explicitly requested; it writes generated non-canonical static files under ${config.truthmark.paths.portalOutput}/. Markdown remains canonical.`\n : null;\n\n return [\n TRUTHMARK_BLOCK_START,\n \"## Truthmark Workflow\",\n \"\",\n \"Truthmark-managed block. Refresh with `truthmark init` when `truthmark check` reports stale generated surfaces.\",\n renderCompactHierarchySummary(config),\n \"Decisions live in the canonical doc they govern; date active decisions inline.\",\n \"Agent runtime: host-native skill packages/adapters 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 need a fresh Sync review. 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 stop 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 Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details.\",\n ...(portalLine === null ? [] : [portalLine]),\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","export type TruthmarkWorkflowId =\n | \"truthmark-sync\"\n | \"truthmark-structure\"\n | \"truthmark-document\"\n | \"truthmark-realize\"\n | \"truthmark-check\"\n | \"truthmark-portal\";\n\nexport type TruthmarkReadOnlySubagentId =\n | \"truth_route_auditor\"\n | \"truth_claim_verifier\"\n | \"truth_doc_reviewer\";\nexport type TruthmarkWriteSubagentId = \"truth_doc_writer\";\ntype 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 reviewQuestions: string[];\n allowedWrites: string[];\n reportSections: string[];\n subagents?: TruthmarkReadOnlySubagentId[];\n writeSubagents?: TruthmarkWriteSubagentId[];\n helpers?: TruthmarkWorkflowHelper[];\n};\n\nconst TRUTHMARK_CLI_RUNNER = \"truthmark\";\n\nconst VALIDATE_SYNC_REPORT_HELPER = {\n id: \"validate-sync-report\",\n optional: true,\n runner: TRUTHMARK_CLI_RUNNER,\n command: {\n argv: [\"truthmark\", \"validate\", \"sync-report\", \"<report-file>\", \"--json\"],\n },\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: {\n argv: [\n \"truthmark\",\n \"validate\",\n \"document-report\",\n \"<report-file>\",\n \"--json\",\n ],\n },\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 reviewQuestions: [\n \"topology review\",\n \"truth-doc ownership\",\n \"lane classification\",\n \"Decision/Rationale preservation\",\n \"truth-doc shape repair when restructuring\",\n \"Evidence checklist\",\n ],\n allowedWrites: [\"canonical truth docs\", \"truth routing files\"],\n reportSections: [\n \"Changed code reviewed\",\n \"Sync Intent\",\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 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 reviewQuestions: [\n \"truth-doc ownership\",\n \"lane classification\",\n \"Decision/Rationale preservation\",\n \"lane split and relationship repair\",\n \"truth-doc shape repair when restructuring\",\n \"Evidence checklist\",\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 reviewQuestions: [\n \"truth-doc ownership\",\n \"lane classification\",\n \"Decision/Rationale preservation\",\n \"Evidence checklist\",\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 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:\n \"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 except through follow-up Truth Sync\",\n \"must not edit truth routing except through follow-up Truth Sync\",\n ],\n reviewQuestions: [\"lane classification\", \"truth-doc ownership\"],\n allowedWrites: [\"functional code\"],\n reportSections: [\"Truth docs used\", \"Code updated\", \"Verification\"],\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 reviewQuestions: [\"audit evidence checklist\"],\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 \"truthmark-portal\": {\n id: \"truthmark-portal\",\n displayName: \"Truthmark Portal\",\n description:\n \"Use when the user explicitly asks to generate, refresh, or update the Truthmark Portal static HTML site. Not for code change sync, route repair, truth validation/checking, documenting behavior, realizing docs into code, or machine-readable agent context.\",\n shortDescription: \"Generate a committed static HTML Truthmark Portal\",\n defaultPrompt:\n \"Use $truthmark-portal only when explicitly asked to generate or refresh the committed static HTML Portal.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"generate the Truthmark Portal\",\n \"refresh the committed HTML docs site\",\n \"create a browsable project map from Truthmark docs\",\n \"update the Truthmark Portal output\",\n \"make a human-readable static site from the truth docs\",\n ],\n negativeTriggers: [\n \"code change sync\",\n \"route ownership repair\",\n \"truth validation or checking\",\n \"document implemented behavior\",\n \"realize docs into code\",\n \"machine-readable agent context\",\n ],\n forbiddenAdjacency: [\n \"must not run automatically at completion\",\n \"must not replace Truth Sync, Truth Check, Truth Document, Truth Realize, or Truth Structure\",\n \"must not write outside the fixed Portal output directory\",\n ],\n reviewQuestions: [\n \"manual-only invocation\",\n \"Portal output containment\",\n \"Markdown canonical statement\",\n \"source provenance\",\n ],\n allowedWrites: [\"fixed Portal output directory only\"],\n reportSections: [\n \"Output path\",\n \"Page count\",\n \"Diagrams/assets\",\n \"Source docs reviewed\",\n \"Skipped/ambiguous docs\",\n \"Validation\",\n \"Markdown canonical statement\",\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 renderBulletBlock,\n renderHierarchySummary,\n renderReadOnlyLaneClassificationRuleBlock,\n} from \"./shared.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; Antigravity @truthmark-check; Cursor /truthmark-check.\";\n\nexport const renderTruthCheckReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const rootRouteIndex = config.truthmark.paths.routesIndex;\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:\n \"The root route index is present and maps repository truth owners.\",\n evidence: [`${rootRouteIndex}:1`],\n suggestedFix: \"none\",\n confidence: \"high\",\n },\n])}\n\nValidation:\n- truthmark check`;\n};\n\nexport const renderTruthCheckProcedureBody = (\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 `# Truthmark Check\n\nUse this skill to audit repository truth health.\n\nTruth Check is agent-led:\n\n- inspect .truthmark/config.yml and configured route files only when they exist; then inspect canonical docs and relevant implementation directly\n- inspect the configured root route index at ${config.truthmark.paths.routesIndex} and relevant child route files under ${config.truthmark.paths.routeAreasRoot}/ when they exist\n- Evidence authority:\n${renderBulletBlock(EVIDENCE_AUTHORITY_INSTRUCTIONS)}\n- Lane classification:\n${renderReadOnlyLaneClassificationRuleBlock(config)}\n- check that current docs describe current code rather than historical plans\n- keep lane and cross-lane checks route-first and bounded:\n - for a narrow audit, inspect only the routed area and directly linked counterpart docs\n - for root-wide truth health, first build a cheap route-map/index from route files, then inspect only mismatches and linked leaves\n - inspect product counterparts for engineering docs only when route YAML claims a product relationship, or when the user explicitly asks for user-visible product coverage\n- check lane root/kind alignment for product truth under ${config.truthmark.paths.productTruthRoot} and engineering truth under ${config.truthmark.paths.engineeringTruthRoot}\n- check route YAML cross-lane realized_by and realizes links for existence and lane compatibility\n- report missing product links for user-visible engineering docs only as a second-pass review diagnostic, not as default full-document reads or hard errors\n- check product docs do not contain engineering execution flow, generated file inventories, or CLI envelope mechanics\n- check engineering docs do not contain product promises, product rationale, or Product Decisions sections\n- never judge whether a product decision is commercially correct, valuable, prioritized, or desirable\n- check that route files map code surfaces to canonical truth docs when route files exist\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 docs keep lane-appropriate 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};\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\n return `---\nname: truthmark-check\ndescription: ${workflow.description}\nargument-hint: Optional area, doc path, or audit focus\nuser-invocable: true\n---\n\n${renderTruthCheckProcedureBody(config, options)}\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_AUTHORING_STYLE_INSTRUCTIONS,\n TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS,\n defaultAgentConfig,\n renderBulletBlock,\n renderLaneClassificationRuleBlock,\n renderClaimEvidenceCheckedSection,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n renderRouteFirstEvidenceGateSection,\n renderHierarchySummary,\n renderTruthDocOwnershipGateSection,\n renderTruthDocRestructureGateSection,\n resolveEngineeringTruthRoot,\n} from \"./shared.js\";\n\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; Antigravity @truthmark-document; Cursor /truthmark-document.\";\n\nexport const renderTruthDocumentReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n return `Truth Document: completed\n\nImplementation reviewed:\n- src/routing/area-resolver.ts\n\nOwnership reviewed:\n- ${config.truthmark.paths.routesIndex}\n\nTruth docs created:\n- ${engineeringTruthRoot}/contracts/routing.md\n\nTruth docs updated:\n- ${engineeringTruthRoot}/behaviors/check-diagnostics.md\n\nTruth docs restructured:\n- ${engineeringTruthRoot}/behaviors/check-diagnostics.md\n\nRouting updated:\n- ${config.truthmark.paths.routesIndex}\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.truthmark.paths.routesIndex}:9`,\n ],\n result: \"supported\",\n },\n ])}\n\nNotes:\n- Documented routing and behavior from route handlers and tests.`;\n};\n\nexport const renderTruthDocumentProcedureBody = (\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 `# Truthmark Document\n\nUse this skill to document existing implemented behavior when no functional-code changes are required for the task.\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 and configured route files only when they exist; then inspect existing canonical docs, implementation code, and tests directly\n- Evidence authority:\n${renderBulletBlock(EVIDENCE_AUTHORITY_INSTRUCTIONS)}\n- Lane classification:\n${renderLaneClassificationRuleBlock(config)}\n- document current implemented behavior; do not invent future behavior or planned endpoints\n- may write canonical truth docs and ${config.truthmark.paths.routesIndex} 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- stop 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- write product capability/boundary truth under ${config.truthmark.paths.productTruthRoot} when documenting product promise, boundary, rationale, or user/stakeholder value\n- write engineering truth under ${config.truthmark.paths.engineeringTruthRoot} when documenting implementation behavior, contracts, architecture, workflows, operations, or tests\n- for both-lane documentation requests, write separate product and engineering docs and cross-link them in route YAML with realized_by and realizes, not in doc frontmatter\n- keep engineering behavior truth 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 stop 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${TRUTH_DOC_AUTHORING_STYLE_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}\nOptional validation: when local tooling is available, you may validate the final report with \\`truthmark validate document-report <report-file> --json\\`; direct checkout inspection and evidence review remain authoritative.\nParent post-document verification:\n- verify only truth docs and leased truth routing files changed during document work\n- stop 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 expected report fields before accepting it\n- verify the final report records ownership review, structure requirement, restructure, routing update, or manual handoff reason when applicable`;\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\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\n---\n\n${renderTruthDocumentProcedureBody(config, options)}\nReport completion in this shape:\n${renderMarkdownExample(renderTruthDocumentReportExample(config))}`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport { defaultAgentConfig, renderHierarchySummary } from \"./shared.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nexport const TRUTHMARK_PORTAL_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-portal; Codex /truthmark-portal or $truthmark-portal; Claude Code /truthmark-portal; GitHub Copilot /truthmark-portal; Antigravity @truthmark-portal; Cursor /truthmark-portal.\";\n\nexport const renderTruthmarkPortalProcedureBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const output = config.truthmark.paths.portalOutput;\n const template = config.truthmark.paths.portalTemplate;\n\n return `# Truthmark Portal\n\nTruthmark Portal is a manual-only presentation workflow. It is never an automatic completion workflow, never Truth Sync, and runs only when the user explicitly asks to generate, refresh, or update the committed static HTML Portal.\n\nCore rules:\n\n- Markdown remains canonical; generated HTML is presentation only.\n- Read Markdown directly from the checkout; the workflow does not require the truthmark CLI or package.\n- truthmark check/index may be used only as optional supporting evidence when available.\n- Determined Portal output is ${output}.\n- Determined Portal template path is ${template}; use built-in template instructions if that file is absent.\n- The workflow may replace the entire output directory, but writes are limited to the fixed Portal output directory only.\n- Portal writes are generated non-canonical static files for human browsing.\n- Generate a committed multi-page static HTML site with local CSS, JavaScript, assets, and search metadata under the output directory.\n- Use no remote dependencies by default: no remote scripts, analytics, fonts, CSS, or CDN assets.\n- Include source provenance and the Markdown canonical disclaimer on every page.\n- Store manifest and search data under output/assets only.\n- There is no .truthmark/index.json dependency; do not require or create it as infrastructure.\n- Pictures and screenshots require an explicit user or template request.\n\nWorkflow:\n\n1. Confirm the user explicitly requested Portal generation or refresh.\n2. Inspect .truthmark/config.yml and configured route docs only when they exist; read repository instruction files when present, truth docs, architecture docs, standards docs, and the determined Portal template when present.\n3. Validate the determined output path is repo-relative, non-empty, inside the repository, and does not overlap canonical docs, source roots, routing files, or instruction targets.\n4. Plan the generated page inventory, diagrams/assets, source docs reviewed, and skipped or ambiguous docs.\n5. Replace or write only under ${output}; do not edit canonical Markdown, routing, source code, or instruction files unless the user explicitly changes scope.\n6. Generate the multi-page static site with local assets/search metadata and visible source provenance.\n7. Validate entry page, links where practical, provenance/disclaimers, local-only assets, and that metadata remains under ${output}/assets.\n${renderHierarchySummary(config)}`;\n};\n\nexport const renderTruthmarkPortalSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-portal\");\n const output = config.truthmark.paths.portalOutput;\n\n return `---\nname: truthmark-portal\ndescription: ${workflow.description}\nargument-hint: Optional portal generation focus\nuser-invocable: true\n---\n\n${renderTruthmarkPortalProcedureBody(config)}\nReport completion in this shape:\n\n\\`\\`\\`md\nTruthmark Portal: completed\n\nOutput path:\n- ${output}\n\nPage count:\n- <count>\n\nDiagrams/assets:\n- <generated diagrams/assets or none>\n\nSource docs reviewed:\n- <source markdown paths>\n\nSkipped/ambiguous docs:\n- <paths and reason, or none>\n\nValidation:\n- <checks performed>\n\nMarkdown canonical statement:\n- Markdown remains canonical; generated Portal HTML is non-canonical presentation only.\n\\`\\`\\`\n`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n defaultAgentConfig,\n renderBulletBlock,\n renderClaudeSubagentModeSection,\n renderClaimEvidenceCheckedSection,\n renderCopilotCustomAgentModeSection,\n renderHierarchySummary,\n renderLaneClassificationRuleBlock,\n renderTopologyEvidenceGateSection,\n renderTruthDocOwnershipGateSection,\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"./shared.js\";\n\n\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; Antigravity @truthmark-structure; Cursor /truthmark-structure.\";\n\nexport const renderTruthStructureReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n\n return `Truth Structure: completed\nTopology reviewed:\n- controllers: src/auth/**\n- product docs root: ${productTruthRoot}\n- engineering docs root: ${engineeringTruthRoot}\n- route files: ${config.truthmark.paths.routesIndex}\nAreas reviewed:\n- src/auth/**\nRouting updated:\n- ${config.truthmark.paths.routesIndex}\nInitial truth boundary:\n- Area: Authentication\n- Code: src/auth/**\n- Product owner: ${productTruthRoot}/capabilities/authentication-session.md\n- Engineering owner: ${engineeringTruthRoot}/behaviors/authentication-session.md\n- Scope: session behavior only\nTruth docs created:\n- ${productTruthRoot}/capabilities/authentication-session.md\n- ${engineeringTruthRoot}/behaviors/authentication-session.md\nTruth docs split:\n- docs/truthmark/truth/authentication/README.md -> ${productTruthRoot}/capabilities/authentication-session.md and ${engineeringTruthRoot}/behaviors/authentication-session.md\nTruth docs restructured:\n- docs/truthmark/truth/authentication/README.md\n${renderClaimEvidenceCheckedSection([\n {\n claim:\n \"Session behavior belongs to a dedicated Authentication truth owner.\",\n evidence: [\"src/auth/**\", `${config.truthmark.paths.routesIndex}: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 renderTruthStructureProcedureBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n } = {},\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(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 `Use this skill to design or repair Truthmark area structure.\n\nTruth Structure is agent-native:\n- inspect repository layout, current docs, Truthmark config and route files when present, and relevant code directly\n- Evidence authority:\n${renderBulletBlock(EVIDENCE_AUTHORITY_INSTRUCTIONS)}\n- Lane classification:\n${renderLaneClassificationRuleBlock(config)}\n- inspect the configured root route index at ${config.truthmark.paths.routesIndex} and relevant child route files under ${config.truthmark.paths.routeAreasRoot}/ when they exist\n- define areas by product or behavior ownership, not by mechanical directory mirroring\n- create or repair ${config.truthmark.paths.routesIndex}\n- create skeletal starter truth docs only when missing ownership would otherwise block future workflows\n- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, truth_kind, and last_reviewed inside that frontmatter. Put source references in the final ## Source References section, not in frontmatter.\n- Starter truth docs are ownership anchors, not behavior writeups: include only the title, bounded area/scope, and Source References needed to make routing explicit.\n- Starter truth docs must keep product and engineering truth in separate files; leave substantive behavior, contract, architecture, workflow, operations, or test prose to Truth Document.\n${subagentMode}\n- use ${productTruthRoot}/** for product truth destinations\n- use ${engineeringTruthRoot}/** for engineering truth destinations\n- use only canonical current-truth destinations for starter truth docs\n- keep Product Decisions in product truth and Engineering Decisions in engineering truth when selecting destinations; report any relocation need instead of rewriting decision prose during topology review\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 stop for manual 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, lane splits, decision relocation, and relationship repair. Do not depend on humans to manually organize ${productTruthRoot} or ${engineeringTruthRoot}. Treat both configured lane roots as managed semantic roots.\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 route structure before creating or extending truth ownership anchors.\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 or reroute only the ownership topology when safe; otherwise stop with manual-review files\",\n)}\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- either configured lane 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.truthmark.paths.routeAreasRoot}/**\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 or flag mixed-owner truth docs for bounded owners before any workflow adds new behavior claims\n- create route files under ${config.truthmark.paths.routeAreasRoot}/ when a product/domain boundary is clear\n- create skeletal engineering ownership anchors under ${engineeringTruthRoot} only when behavior lacks a current owner\n- create skeletal product ownership anchors under ${productTruthRoot} only when product promise, boundary, rationale, or user-visible capability ownership is in scope\n- README.md files are indexes, not Truth Sync targets\n- prefer bounded product docs under product/capabilities or product/decisions and engineering docs under engineering/<kind>/<surface>.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${renderTopologyEvidenceGateSection()}\n- Do not finish topology repair with mixed product/engineering authority in a single canonical truth doc.\n- If an existing canonical doc has wrong-lane sections, report the lane repair needed and only move content when the topology split explicitly requires it.\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- Inspect .truthmark/config.yml and configured route files only when they exist; then inspect 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}`;\n};\n\nexport const renderTruthStructureSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n } = {},\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n\n return `---\nname: truthmark-structure\ndescription: ${workflow.description}\nargument-hint: Optional area, directory, or routing concern\nuser-invocable: true\n---\n\n${renderTruthStructureProcedureBody(config, options)}\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 TruthSyncIntent = {\n changedCodeReviewed: string[];\n affectedRouteOrTruthOwner: string[];\n targetTruthDocs: string[];\n intendedUpdate: string[];\n evidenceToVerify: string[];\n userProvidedDecisionRationale: string[];\n noUpdateNeededRationale: string[];\n blockers: string[];\n};\n\nexport type TruthSyncCompletedReportInput = {\n changedCode: string[];\n syncIntent?: TruthSyncIntent;\n ownershipReviewed: string[];\n truthDocsUpdated: string[];\n decisionRationaleCaptured?: string[];\n evidenceChecked: ClaimEvidenceItem[];\n helperScripts?: string[];\n notes: string[];\n};\n\nexport type TruthSyncCompletedReport = Omit<\n TruthSyncCompletedReportInput,\n \"decisionRationaleCaptured\"\n> & {\n status: \"completed\";\n decisionRationaleCaptured: string[];\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 parseRequiredBulletSection = (source: string, title: string): string[] => {\n const section = findSection(source, title);\n\n if (!section) {\n throw new Error(`${title} section is required.`);\n }\n\n const entries = parseBulletLines(section);\n if (entries.length === 0) {\n throw new Error(`${title} must include at least one bullet.`);\n }\n\n return entries;\n};\n\nconst formatIntentValues = (values: string[]): string => values.join(\" / \");\n\nconst renderSyncIntentSection = (intent: TruthSyncIntent): string => {\n return [\n \"Sync Intent:\",\n `- Changed code reviewed: ${formatIntentValues(intent.changedCodeReviewed)}`,\n `- Affected route/truth owner: ${formatIntentValues(intent.affectedRouteOrTruthOwner)}`,\n `- Target truth docs: ${formatIntentValues(intent.targetTruthDocs)}`,\n `- Intended update: ${formatIntentValues(intent.intendedUpdate)}`,\n `- Evidence to verify: ${formatIntentValues(intent.evidenceToVerify)}`,\n `- User-provided decisions/rationale: ${formatIntentValues(intent.userProvidedDecisionRationale)}`,\n `- No-update-needed rationale: ${formatIntentValues(intent.noUpdateNeededRationale)}`,\n `- Blockers: ${formatIntentValues(intent.blockers)}`,\n ].join(\"\\n\");\n};\n\nconst parseIntentValues = (value: string): string[] => {\n return value\n .split(\" / \")\n .map((item) => item.trim())\n .filter(hasContent);\n};\n\nconst parseSyncIntentSection = (source: string): TruthSyncIntent | undefined => {\n const entries = parseOptionalBulletSection(source, \"Sync Intent\");\n\n if (entries === undefined) {\n return undefined;\n }\n\n const values = new Map<string, string>();\n for (const entry of entries) {\n const separator = entry.indexOf(\":\");\n if (separator === -1) {\n continue;\n }\n values.set(entry.slice(0, separator), entry.slice(separator + 1).trim());\n }\n\n return {\n changedCodeReviewed: parseIntentValues(values.get(\"Changed code reviewed\") ?? \"\"),\n affectedRouteOrTruthOwner: parseIntentValues(values.get(\"Affected route/truth owner\") ?? \"\"),\n targetTruthDocs: parseIntentValues(values.get(\"Target truth docs\") ?? \"\"),\n intendedUpdate: parseIntentValues(values.get(\"Intended update\") ?? \"\"),\n evidenceToVerify: parseIntentValues(values.get(\"Evidence to verify\") ?? \"\"),\n userProvidedDecisionRationale: parseIntentValues(\n values.get(\"User-provided decisions/rationale\") ?? \"\",\n ),\n noUpdateNeededRationale: parseIntentValues(values.get(\"No-update-needed rationale\") ?? \"\"),\n blockers: parseIntentValues(values.get(\"Blockers\") ?? \"\"),\n };\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 ...(input.syncIntent === undefined ? [] : [renderSyncIntentSection(input.syncIntent)]),\n renderBulletSection(\"Ownership reviewed\", input.ownershipReviewed),\n renderBulletSection(\"Truth docs updated\", input.truthDocsUpdated),\n renderBulletSection(\n \"Decision/rationale captured\",\n input.decisionRationaleCaptured ?? [\"none provided in task conversation\"],\n ),\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 const syncIntent = parseSyncIntentSection(source);\n\n return {\n status: \"completed\",\n changedCode: parseBulletSection(source, \"Changed code reviewed\"),\n ...(syncIntent === undefined ? {} : { syncIntent }),\n ownershipReviewed: parseBulletSection(source, \"Ownership reviewed\"),\n truthDocsUpdated: parseBulletSection(source, \"Truth docs updated\"),\n decisionRationaleCaptured: parseRequiredBulletSection(\n source,\n \"Decision/rationale captured\",\n ),\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 EVIDENCE_AUTHORITY_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n renderHierarchySummary,\n renderBulletBlock,\n resolveEngineeringTruthRoot,\n} from \"./shared.js\";\nimport {\n renderTruthSyncBlockedReport,\n renderTruthSyncCompletedReport,\n} from \"../sync/report.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; Antigravity @truthmark-sync; Cursor /truthmark-sync.\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nconst renderTruthSyncProductDecisionRuleBlock = (\n config: TruthmarkConfig,\n): string => {\n return renderBulletBlock(\n [\n \"ask whether a user-visible promise, capability boundary, API contract, acceptance criterion, or explicit user/product evidence changed\",\n `if yes, update or route product truth under ${config.truthmark.paths.productTruthRoot} as well as engineering truth under ${config.truthmark.paths.engineeringTruthRoot}`,\n `if no, default to engineering truth under ${config.truthmark.paths.engineeringTruthRoot} for internal implementation changes`,\n \"when both lanes change, keep separate product and engineering docs cross-linked through route YAML with realized_by and realizes\",\n \"when ownership is ambiguous, stop or route to Truth Structure instead of writing a mixed document\",\n ].join(\"\\n\"),\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- inspect .truthmark/config.yml and configured route files (${config.truthmark.paths.routesIndex}; ${config.truthmark.paths.routeAreasRoot}/) only when they exist; then inspect canonical truth docs directly\n- ask whether a user-visible promise, capability boundary, API contract, acceptance criterion, or explicit user/product evidence changed\n- review the task conversation for user-provided decisions, rationale, constraints, tradeoffs, rejection reasons, or scope boundaries before writing truth docs\n- if yes, carry that user-provided decision context into Sync Intent and report where it was placed or why it needs manual handoff\n- if yes, update or route product truth as well as engineering truth; if no, default internal implementation changes to engineering truth\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- userProvidedDecisionRationale: 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- decisionRationaleCaptured: string[]\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 renderTruthSyncProcedureBody = (\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-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 `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.\nExplicit invocation runs immediately when the user directly requests this workflow. Later functional-code changes need a fresh finish-time review, and an earlier explicit run satisfies the finish-time review 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. Inspect .truthmark/config.yml and configured route files only when they exist; then inspect relevant canonical docs.\n3. Identify functional-code changes and the nearest truth docs or routing repairs.\n4. Evidence authority:\n${renderBulletBlock(EVIDENCE_AUTHORITY_INSTRUCTIONS)}\n5. Product truth decision:\n${renderTruthSyncProductDecisionRuleBlock(config)}\n6. Capture decision context from the task conversation: ask whether the user provided a product or technical decision, rationale, constraint, tradeoff, rejection reason, or scope boundary. Preserve concise user-provided decision rationale in Sync Intent before truth edits, route it to Product Decisions, Engineering Decisions, Rationale, Capability Scope, Non-Goals, Maintenance Notes, or the relevant workflow/contract section, and report whether it was placed, skipped because none was provided, or needs manual handoff.\n7. Update engineering truth first after code changes. Product truth is opt-in for externally visible promises, product boundaries, APIs, acceptance criteria, or explicit user/product evidence.\n8. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run.\n9. 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.\n10. Fill Sync Intent before editing truth docs or truth routing files:\n - Changed code reviewed: functional files, tests, configs, generated outputs, or other implementation evidence inspected\n - Affected route/truth owner: bounded route area or canonical truth owner that maps the change\n - Target truth docs: docs expected to change, or docs reviewed and left unchanged\n - Intended update: claim/doc/routing update planned before writing\n - Evidence to verify: checkout evidence that will support, narrow, remove, or record each claim for manual handoff\n - User-provided decisions/rationale: decisions, rationale, constraints, tradeoffs, rejection reasons, or scope boundaries from the current task conversation, or \"none provided\"\n - No-update-needed rationale: why mapped truth is already current when no truth doc should change\n - Blockers: missing routing, ambiguous ownership, failed verification, unavailable evidence, or off-boundary write needs\n11. Only edit allowed truth docs/routes after Sync Intent is clear; if ownership is ambiguous, repair topology first when the repair is safe and in scope, otherwise stop and recommend Truth Structure instead of guessing.\n${subagentMode}Topology review and repair:\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, run Truth Structure before syncing when topology repair is safe and in scope\n- safe in-scope topology repair may update truth routing files and create or update bounded leaf truth docs needed to map the changed functional code; keep the repair limited to the affected route owner\n- stop and recommend Truth Structure only when topology repair is unsafe, ambiguous, or outside the current task boundary\n- report the route files and changed code paths that required structure repair\n- do not create another generic truth doc\n- README.md files are indexes, not Truth Sync targets\n- must not append behavior details to a README.md index\n- write engineering truth under ${config.truthmark.paths.engineeringTruthRoot}; product truth updates under ${config.truthmark.paths.productTruthRoot} are allowed only for explicit current product behavior changes\nOptional validation tooling:\n- you may run truthmark check when local tooling is available\n- you may validate the final report with \\`truthmark validate sync-report <report-file> --json\\` when 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 only in product truth and Engineering Decisions only in engineering truth when evidence supports the lane-specific decision change\n${renderHierarchySummary(config)}\nParent post-sync verification:\n- verify only truth docs and leased truth routing files changed during sync\n- stop on any unrelated diff caused by the sync step\n- stop if functional code changed during sync\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 reviewed checkout evidence, changed-code impact, or a recorded stale-truth correction made within the sync write lease\n- verify the final report records ownership review, structure requirement, split, restructure, or manual handoff reason when the ownership review applies\n- manual handoff outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files`;\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 engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n return `---\nname: truthmark-sync\ndescription: ${workflow.description}\nargument-hint: Optional changed-code area, truth-doc area, or sync focus\nuser-invocable: true\n---\n\n${renderTruthSyncProcedureBody(config, options)}\nReport completion in this shape:\n${renderMarkdownExample(\n renderTruthSyncCompletedReport({\n changedCode: [\"src/auth/session.ts\"],\n syncIntent: {\n changedCodeReviewed: [\"src/auth/session.ts\"],\n affectedRouteOrTruthOwner: [\n `${config.truthmark.paths.routeAreasRoot}/authentication.md`,\n ],\n targetTruthDocs: [`${engineeringTruthRoot}/behaviors/session-timeout.md`],\n intendedUpdate: [\"Update session timeout behavior.\"],\n evidenceToVerify: [\n \"src/auth/session.ts:12\",\n `${config.truthmark.paths.routeAreasRoot}/authentication.md:11`,\n ],\n userProvidedDecisionRationale: [\n \"User rationale: session timeout behavior changed for internal implementation consistency\",\n ],\n noUpdateNeededRationale: [\"not applicable; mapped truth is stale\"],\n blockers: [\"none\"],\n },\n ownershipReviewed: [`${config.truthmark.paths.routeAreasRoot}/authentication.md`],\n truthDocsUpdated: [`${engineeringTruthRoot}/behaviors/session-timeout.md`],\n evidenceChecked: [\n {\n claim:\n \"Session timeout behavior is documented in the bounded authentication behavior truth doc.\",\n evidence: [\n \"src/auth/session.ts:12\",\n `${config.truthmark.paths.routeAreasRoot}/authentication.md:11`,\n ],\n result: \"supported\",\n },\n ],\n decisionRationaleCaptured: [\n \"Placed user rationale in the bounded authentication behavior truth doc under Engineering Decisions/Rationale.\",\n ],\n notes: [\"Updated session timeout behavior.\"],\n }),\n)}\nBlocked report example:\n${renderMarkdownExample(\n renderTruthSyncBlockedReport({\n reason: \"Changed code maps only to the provisional bootstrap route.\",\n manualReviewFiles: [\n \"src/auth/**\",\n `${config.truthmark.paths.routeAreasRoot}/${config.truthmark.routes.defaultArea}.md`,\n ],\n nextAction: \"Run Truth Structure for src/auth/** before updating behavior truth.\",\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 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\ntype 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\ntype 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 renderCopilotCustomAgentModeSection,\n renderHierarchySummary,\n renderOpenCodeSubagentModeSection,\n renderTruthDocOwnershipGateSection,\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"../agents/shared.js\";\nimport {\n renderTruthCheckProcedureBody,\n renderTruthCheckReportExample,\n renderTruthCheckSkillBody,\n} from \"../agents/truth-check.js\";\nimport {\n renderTruthDocumentProcedureBody,\n renderTruthDocumentReportExample,\n renderTruthDocumentSkillBody,\n} from \"../agents/truth-document.js\";\nimport {\n renderTruthmarkPortalProcedureBody,\n renderTruthmarkPortalSkillBody,\n} from \"../agents/truthmark-portal.js\";\nimport {\n renderTruthStructureProcedureBody,\n renderTruthStructureReportExample,\n renderTruthStructureSkillBody,\n} from \"../agents/truth-structure.js\";\nimport {\n renderTruthSyncProcedureBody,\n renderTruthSyncSkillBody,\n} from \"../agents/truth-sync.js\";\nimport {\n renderTruthSyncBlockedReport,\n renderTruthSyncCompletedReport,\n} from \"../sync/report.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\";\n\nexport const TRUTHMARK_STRUCTURE_SKILL_PATH =\n \".agents/skills/truthmark-structure/SKILL.md\";\n\nexport const TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-structure/agents/openai.yaml\";\n\nexport const TRUTHMARK_DOCUMENT_SKILL_PATH =\n \".agents/skills/truthmark-document/SKILL.md\";\n\nexport const TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-document/agents/openai.yaml\";\n\nexport const TRUTHMARK_SYNC_SKILL_PATH =\n \".agents/skills/truthmark-sync/SKILL.md\";\n\nexport const TRUTHMARK_SYNC_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-sync/agents/openai.yaml\";\n\nexport const TRUTHMARK_REALIZE_SKILL_PATH =\n \".agents/skills/truthmark-realize/SKILL.md\";\n\nexport const TRUTHMARK_REALIZE_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-realize/agents/openai.yaml\";\n\nexport const TRUTHMARK_CHECK_SKILL_PATH =\n \".agents/skills/truthmark-check/SKILL.md\";\n\nexport const TRUTHMARK_CHECK_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-check/agents/openai.yaml\";\n\nexport const TRUTHMARK_PORTAL_SKILL_PATH =\n \".agents/skills/truthmark-portal/SKILL.md\";\n\nexport const TRUTHMARK_PORTAL_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-portal/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_ANTIGRAVITY_STRUCTURE_RULE_PATH =\n \".antigravity/rules/truthmark-structure.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_DOCUMENT_RULE_PATH =\n \".antigravity/rules/truthmark-document.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_SYNC_RULE_PATH =\n \".antigravity/rules/truthmark-sync.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_REALIZE_RULE_PATH =\n \".antigravity/rules/truthmark-realize.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_CHECK_RULE_PATH =\n \".antigravity/rules/truthmark-check.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_PORTAL_RULE_PATH =\n \".antigravity/rules/truthmark-portal.md\";\n\nexport const TRUTHMARK_CURSOR_STRUCTURE_SKILL_PATH =\n \".cursor/skills/truthmark-structure/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_DOCUMENT_SKILL_PATH =\n \".cursor/skills/truthmark-document/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_SYNC_SKILL_PATH =\n \".cursor/skills/truthmark-sync/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_REALIZE_SKILL_PATH =\n \".cursor/skills/truthmark-realize/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_CHECK_SKILL_PATH =\n \".cursor/skills/truthmark-check/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_PORTAL_SKILL_PATH =\n \".cursor/skills/truthmark-portal/SKILL.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_PORTAL_PROMPT_PATH =\n \".github/prompts/truthmark-portal.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH =\n \".github/agents/truth-route-auditor.md\";\n\nexport const TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH =\n \".github/agents/truth-claim-verifier.md\";\n\nexport const TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH =\n \".github/agents/truth-doc-reviewer.md\";\nexport const TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH =\n \".github/agents/truth-doc-writer.md\";\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 workflowSupportFiles = (workflowId: TruthmarkWorkflowId): string[] => {\n const workflow = getTruthmarkWorkflow(workflowId);\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const hasSubagentSupport =\n definition.parentRule !== undefined &&\n ((workflow.subagents?.length ?? 0) > 0 ||\n (workflow.writeSubagents?.length ?? 0) > 0);\n\n return [\n \"support/procedure.md\",\n \"support/report-template.md\",\n ...(hasSubagentSupport ? [\"support/subagents-and-leases.md\"] : []),\n ];\n};\n\nconst renderWorkflowCommandAdapterInstructions = (\n workflowId: TruthmarkWorkflowId,\n root: string,\n hostName: string,\n surfaceKind: \"command\" | \"prompt\",\n): string => {\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const canonicalFiles = [\"SKILL.md\", ...workflowSupportFiles(workflowId)]\n .map((supportFile) => `- ${root}/${supportFile}`)\n .join(\"\\n\");\n\n return `This ${surfaceKind} is the ${hostName} entrypoint for ${definition.title}.\n\nDo not invoke another Truthmark command from here.\n\nRead these host-local files in order only as needed:\n${canonicalFiles}\n\nIf skill entrypoints are unavailable, use the host's direct evidence-first manual fallback procedure.`;\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 | \"cursor\";\n\ntype TruthmarkSkillPackageFile = {\n path: string;\n content: string;\n};\n\ntype WorkflowPackageDefinition = {\n title: string;\n argumentHint: string;\n use: (config: TruthmarkConfig) => string;\n quickRules: (config: TruthmarkConfig) => string[];\n parentRule?: string;\n};\n\nconst routeFilesHint = (config: TruthmarkConfig): string =>\n `${config.truthmark.paths.routesIndex}; ${config.truthmark.paths.routeAreasRoot}/`;\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 use: () => \"Use this skill to design or repair Truthmark area structure.\",\n quickRules: (config) => [\n \"Follow repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n `Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then inspect 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 ],\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 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 repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n `Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then inspect 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 ],\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 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 repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n \"Skip docs-only, formatting-only, behavior-preserving renames with no truth impact, missing config, and no-code changes.\",\n `Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then inspect relevant canonical docs directly.`,\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 ],\n parentRule:\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n },\n \"truthmark-realize\": {\n title: \"Truthmark Realize\",\n argumentHint:\n \"Optional truth doc path, area, or desired code behavior to realize\",\n use: () =>\n \"Use this skill only when the user explicitly asks to realize truth docs into code.\",\n quickRules: (config) => [\n \"Follow repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n `Read the source truth docs, inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist, then inspect 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 ],\n },\n \"truthmark-check\": {\n title: \"Truthmark Check\",\n argumentHint: \"Optional area, doc path, or audit focus\",\n use: () => \"Use this skill to audit repository truth health.\",\n quickRules: (config) => [\n \"Follow repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n `Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then inspect canonical docs and relevant implementation directly.`,\n \"Report issues and suggested fixes; do not silently rewrite unrelated files.\",\n ],\n parentRule: \"Parent agent owns the final Truth Check report\",\n },\n \"truthmark-portal\": {\n title: \"Truthmark Portal\",\n argumentHint: \"Optional portal generation focus\",\n use: () =>\n \"Use this skill only when the user explicitly asks to generate or refresh the committed static HTML Truthmark Portal.\",\n quickRules: (config) => [\n \"Follow repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n \"Truthmark Portal is manual-only; never run it automatically at completion and never treat it as Truth Sync.\",\n \"Markdown remains canonical; generated HTML is non-canonical presentation only.\",\n \"Read Markdown directly; the workflow does not require the truthmark CLI or package.\",\n \"Generate committed, generated non-canonical static files for humans.\",\n `Write only under fixed Portal output ${config.truthmark.paths.portalOutput}.`,\n `Use determined Portal template ${config.truthmark.paths.portalTemplate} when present; no .truthmark/index.json dependency.`,\n \"Use no remote dependencies by default and include source provenance on every page.\",\n ],\n },\n};\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nconst renderWorkflowReportTemplate = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n\n switch (workflowId) {\n case \"truthmark-structure\":\n return `Report completion in this shape:\\n${renderMarkdownExample(\n renderTruthStructureReportExample(config),\n )}`;\n case \"truthmark-document\":\n return `Report completion in this shape:\\n${renderMarkdownExample(\n renderTruthDocumentReportExample(config),\n )}`;\n case \"truthmark-sync\":\n return `Report completion in this shape:\\n${renderMarkdownExample(\n renderTruthSyncCompletedReport({\n changedCode: [\"src/auth/session.ts\"],\n syncIntent: {\n changedCodeReviewed: [\"src/auth/session.ts\"],\n affectedRouteOrTruthOwner: [\n `${config.truthmark.paths.routeAreasRoot}/authentication.md`,\n ],\n targetTruthDocs: [`${engineeringTruthRoot}/behaviors/session-timeout.md`],\n intendedUpdate: [\"Update session timeout behavior.\"],\n evidenceToVerify: [\n \"src/auth/session.ts:12\",\n `${config.truthmark.paths.routeAreasRoot}/authentication.md:11`,\n ],\n userProvidedDecisionRationale: [\n \"User rationale: session timeout behavior changed for internal implementation consistency\",\n ],\n noUpdateNeededRationale: [\"not applicable; mapped truth is stale\"],\n blockers: [\"none\"],\n },\n ownershipReviewed: [\n `${config.truthmark.paths.routeAreasRoot}/authentication.md`,\n ],\n truthDocsUpdated: [`${engineeringTruthRoot}/behaviors/session-timeout.md`],\n evidenceChecked: [\n {\n claim:\n \"Session timeout behavior is documented in the bounded authentication behavior truth doc.\",\n evidence: [\n \"src/auth/session.ts:12\",\n `${config.truthmark.paths.routeAreasRoot}/authentication.md:11`,\n ],\n result: \"supported\",\n },\n ],\n decisionRationaleCaptured: [\n \"Placed user rationale in the bounded authentication behavior truth doc under Engineering Decisions/Rationale.\",\n ],\n notes: [\"Updated session timeout behavior.\"],\n }),\n )}\\nBlocked report example:\\n${renderMarkdownExample(\n renderTruthSyncBlockedReport({\n reason: \"Changed code maps only to the provisional bootstrap route.\",\n manualReviewFiles: [\n \"src/auth/**\",\n `${config.truthmark.paths.routeAreasRoot}/${config.truthmark.routes.defaultArea}.md`,\n ],\n nextAction: \"Run Truth Structure for src/auth/** before updating behavior truth.\",\n }),\n )}`;\n case \"truthmark-realize\":\n return `Report completion in this shape:\\n\\n${renderMarkdownExample(`Truth Realize: completed\n\nTruth docs used:\n- ${productTruthRoot}/capabilities/authentication-session.md\n- ${engineeringTruthRoot}/behaviors/authentication-session.md\n\nCode updated:\n- src/auth/session.ts\n\nVerification:\n- npm test -- auth`)}`;\n case \"truthmark-check\":\n return `Report completion in this shape:\\n\\n${renderMarkdownExample(\n renderTruthCheckReportExample(config),\n )}`;\n case \"truthmark-portal\":\n return `Report completion in this shape:\\n\\n${renderMarkdownExample(`Truthmark Portal: completed\n\nOutput path:\n- ${config.truthmark.paths.portalOutput}\n\nPage count:\n- <count>\n\nDiagrams/assets:\n- <generated diagrams/assets or none>\n\nSource docs reviewed:\n- <source markdown paths>\n\nSkipped/ambiguous docs:\n- <paths and reason, or none>\n\nValidation:\n- <checks performed>\n\nMarkdown canonical statement:\n- Markdown remains canonical; generated Portal HTML is non-canonical presentation only.`)}`;\n }\n};\n\nconst renderWorkflowSupportParts = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n): { procedure: string; reportTemplate: string } => {\n return {\n procedure: renderWorkflowProcedure(workflowId, config),\n reportTemplate: renderWorkflowReportTemplate(workflowId, config),\n };\n};\n\nconst renderSkillSupportFile = (title: string, body: string): string => {\n return `# ${title}\n\nTruthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\n\n${body}\n`;\n};\n\nconst renderWorkflowProcedure = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n): string => {\n switch (workflowId) {\n case \"truthmark-structure\":\n return renderTruthStructureProcedureBody(config);\n case \"truthmark-document\":\n return renderTruthDocumentProcedureBody(config);\n case \"truthmark-sync\":\n return renderTruthSyncProcedureBody(config);\n case \"truthmark-realize\":\n return renderTruthmarkRealizeProcedureBody(config);\n case \"truthmark-check\":\n return renderTruthCheckProcedureBody(config);\n case \"truthmark-portal\":\n return renderTruthmarkPortalProcedureBody(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 supportFileUsage = (supportFile: string): string => {\n if (supportFile === \"support/procedure.md\") {\n return \"read before edits or detailed auditing; contains core review questions\";\n }\n\n if (supportFile === \"support/report-template.md\") {\n return \"read before the final report\";\n }\n\n if (supportFile === \"support/subagents-and-leases.md\") {\n return \"read only when using subagents, leases, or accepting worker output\";\n }\n\n return \"available when relevant to the current step\";\n };\n const supportFileList = supportFiles\n .map((supportFile) => `- ${supportFile} — ${supportFileUsage(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 === \"cursor\"\n ? \"Use as a Cursor Agent Skill. Cursor discovers project skills under `.cursor/skills/`, selects them from the description when relevant, and supports manual `/` invocation.\"\n : undefined;\n\n return `---\nname: ${workflowId}\ndescription: ${workflow.description}\nargument-hint: ${definition.argumentHint}\nuser-invocable: true\n---\n\n# ${definition.title}\n\n${definition.use(config)}${hostUsage === undefined ? \"\" : `\\n\\n${hostUsage}`}\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 \"cursor\":\n return undefined;\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 } = renderWorkflowSupportParts(\n workflowId,\n 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, 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 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 truthDocRoots = Array.from(\n new Set([\n normalizeOpenCodePermissionPath(resolveProductTruthRoot(config)),\n normalizeOpenCodePermissionPath(resolveEngineeringTruthRoot(config)),\n ]),\n );\n const rootRouteIndex = normalizeOpenCodePermissionPath(\n config.truthmark.paths.routesIndex,\n );\n const areaFilesRoot = normalizeOpenCodePermissionPath(\n config.truthmark.paths.routeAreasRoot,\n );\n const allowedPatterns = [\n ...truthDocRoots.map((root) => appendOpenCodePermissionGlob(root, \"/**\")),\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, .github/copilot-instructions.md, .cursor/skills, .antigravity/rules, 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.\nInspect .truthmark/config.yml and route files only when they exist; then inspect mapped truth docs and relevant implementation files directly.\nUse a route-first bounded strategy: narrow audits inspect only the routed area and directly linked counterpart docs; root-wide health first builds a cheap route-map/index from route files, then inspects only mismatches and linked leaves.\nFind missing, stale, broad, overloaded, catch-all, mixed-owner, or unrouteable ownership.\nValidate route ownership against lane-specific roots and route kind:\n- confirm mapped truth docs resolve to the correct lane root (product or engineering) for their kind\n- flag mismatch between assigned route kind and resolved doc kind (for example, product-capability routed to engineering paths)\n- verify route-doc linkage for lane pairings via realized_by and realizes before recommending edits\n- inspect product counterparts for engineering docs only when route YAML claims a product relationship, or when the parent explicitly asks for user-visible product coverage\n- treat missing product links for user-visible engineering docs as a second-pass diagnostic, not a default full-document read.\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 compact frontmatter, required template sections, final Source References entries, Evidence checked entries, and lane-appropriate decision sections (Product Decisions in product truth, Engineering Decisions in engineering truth).\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 `# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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 `# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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 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 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 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 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 refresh_command: \"truthmark init\"\n`;\n};\n\nconst renderTruthmarkRealizeProcedureBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return `# Truthmark Realize\n\nUse this skill only when the user explicitly asks to realize truth docs into code.\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 configured route files when present.\n2. Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then read 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, stop 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};\n\nconst renderTruthmarkRealizeSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(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\n---\n\n${renderTruthmarkRealizeProcedureBody(config)}\nReport completion in this shape:\n\n\\`\\`\\`md\nTruth Realize: completed\n\nTruth docs used:\n- ${productTruthRoot}/capabilities/authentication-session.md\n- ${engineeringTruthRoot}/behaviors/authentication-session.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 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 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 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 refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkPortalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthmarkPortalSkillBody(config);\n};\n\nexport const renderTruthmarkPortalSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-portal\");\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 refresh_command: \"truthmark init\"\n`;\n};\n\nconst renderWorkflowRuleFile = ({\n workflowId,\n hostName,\n ruleName,\n config = defaultAgentConfig(),\n}: {\n workflowId: TruthmarkWorkflowId;\n hostName: string;\n ruleName: string;\n config?: TruthmarkConfig;\n}): string => {\n const workflow = getTruthmarkWorkflow(workflowId);\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const { procedure, reportTemplate } = renderWorkflowSupportParts(\n workflowId,\n config,\n );\n const body = `# ${definition.title}\n\nTruthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\n\nThis rule is the ${hostName} entrypoint for ${definition.title}.\n\nDo not invoke another Truthmark command from here.\n\nManual invocation: @${ruleName}\n\nIf skill entrypoints are unavailable, use the host's direct evidence-first manual fallback procedure.\n\nDescription: ${workflow.description}\n\n## Procedure\n\n${procedure}\n\n## Report Template\n\n${reportTemplate}\n`;\n\n return body;\n};\n\nconst renderCopilotWorkflowPrompt = (\n workflowId: TruthmarkWorkflowId,\n root: string,\n): string => {\n const workflow = getTruthmarkWorkflow(workflowId);\n\n return renderCopilotPromptFile(\n workflow.description,\n renderWorkflowCommandAdapterInstructions(\n workflowId,\n root,\n \"GitHub Copilot\",\n \"prompt\",\n ),\n );\n};\n\nexport const renderTruthmarkAntigravityStructureRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-structure\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-structure\",\n config,\n });\n\nexport const renderTruthmarkAntigravityDocumentRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-document\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-document\",\n config,\n });\n\nexport const renderTruthmarkAntigravitySyncRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-sync\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-sync\",\n config,\n });\n\nexport const renderTruthmarkAntigravityRealizeRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-realize\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-realize\",\n config,\n });\n\nexport const renderTruthmarkAntigravityCheckRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-check\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-check\",\n config,\n });\n\nexport const renderTruthmarkAntigravityPortalRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-portal\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-portal\",\n config,\n });\n\nexport const renderTruthmarkCopilotStructurePrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-structure\",\n \".github/skills/truthmark-structure\",\n );\n};\n\nexport const renderTruthmarkCopilotDocumentPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-document\",\n \".github/skills/truthmark-document\",\n );\n};\n\nexport const renderTruthmarkCopilotSyncPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-sync\",\n \".github/skills/truthmark-sync\",\n );\n};\n\nexport const renderTruthmarkCopilotRealizePrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-realize\",\n \".github/skills/truthmark-realize\",\n );\n};\n\nexport const renderTruthmarkCopilotCheckPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-check\",\n \".github/skills/truthmark-check\",\n );\n};\n\nexport const renderTruthmarkCopilotPortalPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-portal\",\n \".github/skills/truthmark-portal\",\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 renderTruthmarkCopilotPortalPrompt,\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 renderTruthmarkAntigravityCheckRule,\n renderTruthmarkAntigravityDocumentRule,\n renderTruthmarkAntigravityPortalRule,\n renderTruthmarkAntigravityRealizeRule,\n renderTruthmarkAntigravityStructureRule,\n renderTruthmarkAntigravitySyncRule,\n renderTruthmarkSkillPackage,\n renderTruthmarkCheckSkillMetadata,\n renderTruthmarkOpenCodeClaimVerifierAgent,\n renderTruthmarkOpenCodeDocReviewerAgent,\n renderTruthmarkOpenCodeDocWriterAgent,\n renderTruthmarkOpenCodeRouteAuditorAgent,\n renderTruthmarkPortalSkillMetadata,\n renderTruthmarkRealizeSkillMetadata,\n renderTruthmarkRouteAuditorAgent,\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_ANTIGRAVITY_CHECK_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_DOCUMENT_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_PORTAL_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_REALIZE_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_STRUCTURE_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_SYNC_RULE_PATH,\n TRUTHMARK_CURSOR_CHECK_SKILL_PATH,\n TRUTHMARK_CURSOR_DOCUMENT_SKILL_PATH,\n TRUTHMARK_CURSOR_PORTAL_SKILL_PATH,\n TRUTHMARK_CURSOR_REALIZE_SKILL_PATH,\n TRUTHMARK_CURSOR_STRUCTURE_SKILL_PATH,\n TRUTHMARK_CURSOR_SYNC_SKILL_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_PORTAL_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_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_PORTAL_SKILL_METADATA_PATH,\n TRUTHMARK_PORTAL_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_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 if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_PORTAL_SKILL_PATH,\n workflowId: \"truthmark-portal\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_PORTAL_SKILL_METADATA_PATH,\n content: renderTruthmarkPortalSkillMetadata(),\n },\n );\n }\n\n return files;\n};\n\nconst opencodeFiles = (config: TruthmarkConfig): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\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-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 if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-portal/SKILL.md\",\n workflowId: \"truthmark-portal\",\n host: \"opencode\",\n config,\n }),\n );\n }\n\n return files;\n};\n\nconst claudeFiles = (\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\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-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 if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-portal/SKILL.md\",\n workflowId: \"truthmark-portal\",\n host: \"claude-code\",\n config,\n }),\n );\n }\n\n return files;\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-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_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 if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: \".github/skills/truthmark-portal/SKILL.md\",\n workflowId: \"truthmark-portal\",\n host: \"github-copilot\",\n config,\n }),\n {\n path: TRUTHMARK_COPILOT_PORTAL_PROMPT_PATH,\n content: renderTruthmarkCopilotPortalPrompt(config),\n },\n );\n }\n\n return files;\n};\n\nconst antigravityFiles = (config: TruthmarkConfig): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n {\n path: TRUTHMARK_ANTIGRAVITY_STRUCTURE_RULE_PATH,\n content: renderTruthmarkAntigravityStructureRule(config),\n },\n {\n path: TRUTHMARK_ANTIGRAVITY_DOCUMENT_RULE_PATH,\n content: renderTruthmarkAntigravityDocumentRule(config),\n },\n {\n path: TRUTHMARK_ANTIGRAVITY_SYNC_RULE_PATH,\n content: renderTruthmarkAntigravitySyncRule(config),\n },\n {\n path: TRUTHMARK_ANTIGRAVITY_CHECK_RULE_PATH,\n content: renderTruthmarkAntigravityCheckRule(config),\n },\n {\n path: TRUTHMARK_ANTIGRAVITY_REALIZE_RULE_PATH,\n content: renderTruthmarkAntigravityRealizeRule(config),\n },\n ];\n\n if (config.truthmark.generated.portal.enabled) {\n files.push({\n path: TRUTHMARK_ANTIGRAVITY_PORTAL_RULE_PATH,\n content: renderTruthmarkAntigravityPortalRule(config),\n });\n }\n\n return files;\n};\n\nconst cursorFiles = (config: TruthmarkConfig): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_STRUCTURE_SKILL_PATH,\n workflowId: \"truthmark-structure\",\n host: \"cursor\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_DOCUMENT_SKILL_PATH,\n workflowId: \"truthmark-document\",\n host: \"cursor\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_SYNC_SKILL_PATH,\n workflowId: \"truthmark-sync\",\n host: \"cursor\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_CHECK_SKILL_PATH,\n workflowId: \"truthmark-check\",\n host: \"cursor\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_REALIZE_SKILL_PATH,\n workflowId: \"truthmark-realize\",\n host: \"cursor\",\n config,\n }),\n ];\n\n if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_PORTAL_SKILL_PATH,\n workflowId: \"truthmark-portal\",\n host: \"cursor\",\n config,\n }),\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 \"antigravity\":\n return antigravityFiles(config);\n case \"cursor\":\n return cursorFiles(config);\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 { createDefaultConfig } 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\nclass 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\nconst 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 defaultConfig = createDefaultConfig();\n const rootIndex = loadResult.config?.truthmark.paths.routesIndex ?? defaultConfig.truthmark.paths.routesIndex;\n const areaFilesRoot =\n loadResult.config?.truthmark.paths.routeAreasRoot ?? defaultConfig.truthmark.paths.routeAreasRoot;\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 checkControlledPaths = async (\n rootDir: string,\n controlledPaths: string[],\n): Promise<AuthorityCheckResult> => {\n const diagnostics: Diagnostic[] = [];\n const orderedPaths: string[] = [];\n const seenPaths = new Set<string>();\n\n for (const entry of controlledPaths) {\n if (looksLikeGlob(entry)) {\n try {\n resolveRepoPath(rootDir, entry);\n } catch {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Truthmark-controlled path ${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: `Truthmark-controlled 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: `Truthmark-controlled 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: `Truthmark-controlled path ${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 Truthmark-controlled 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\nexport const checkAuthority = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<AuthorityCheckResult> => {\n return checkControlledPaths(rootDir, config.truthmark.controlledPaths);\n};\n","import fs from \"node:fs/promises\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport { parseFrontmatter } from \"../markdown/frontmatter.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n TRUTH_DOCUMENT_KINDS,\n laneForTruthDocumentKind,\n type TruthDocumentEntry,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\n\nconst isTruthDocumentKind = (value: string): value is TruthDocumentKind =>\n TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind);\n\nconst ROUTE_RELATIONSHIP_FRONTMATTER_FIELDS = [\n \"realized_by\",\n \"realizes\",\n \"depends_on\",\n];\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 parseFrontmatter(source, { throwOnInvalid: true });\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 const truthLane = document.frontmatter.truth_lane;\n const isTruthDocument =\n routedTruthDocument !== undefined || truthKind !== undefined;\n\n if (isTruthDocument) {\n for (const field of ROUTE_RELATIONSHIP_FRONTMATTER_FIELDS) {\n if (field in document.frontmatter) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Frontmatter field ${field} is not allowed on truth documents; author relationship metadata in fenced route YAML entries instead.`,\n file: markdownPath,\n });\n }\n }\n }\n\n if (\n truthLane !== undefined &&\n truthLane !== \"product\" &&\n truthLane !== \"engineering\"\n ) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: \"Frontmatter truth_lane must be product or engineering.\",\n file: markdownPath,\n });\n }\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 if (\n typeof truthKind === \"string\" &&\n isTruthDocumentKind(truthKind) &&\n truthLane !== undefined &&\n (truthLane === \"product\" || truthLane === \"engineering\") &&\n truthLane !== laneForTruthDocumentKind(truthKind)\n ) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Frontmatter truth_lane ${truthLane} must match truth_kind ${truthKind}.`,\n file: markdownPath,\n });\n }\n }\n }\n\n return diagnostics;\n};\n","import { parse } from \"yaml\";\n\nexport type ParsedFrontmatterDocument = {\n data: Record<string, unknown>;\n content: string;\n};\n\nexport type ParseFrontmatterOptions = {\n throwOnInvalid?: boolean;\n};\n\nconst openingDelimiterPattern = /^(?:\\uFEFF)?---[ \\t]*(?:\\r?\\n|$)/u;\nconst closingDelimiterPattern = /^---[ \\t]*(?:\\r?\\n|$)/mu;\n\nconst asRecord = (value: unknown): Record<string, unknown> => {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n\n return {};\n};\n\nexport const parseFrontmatter = (\n source: string,\n options: ParseFrontmatterOptions = {},\n): ParsedFrontmatterDocument => {\n const openingMatch = openingDelimiterPattern.exec(source);\n if (!openingMatch) {\n return {\n data: {},\n content: source.replace(/^\\uFEFF/u, \"\"),\n };\n }\n\n const bodyStart = openingMatch[0].length;\n const bodyAndContent = source.slice(bodyStart);\n const closingMatch = closingDelimiterPattern.exec(bodyAndContent);\n if (!closingMatch || typeof closingMatch.index !== \"number\") {\n return {\n data: {},\n content: source.replace(/^\\uFEFF/u, \"\"),\n };\n }\n\n const yamlSource = bodyAndContent.slice(0, closingMatch.index);\n const content = bodyAndContent.slice(closingMatch.index + closingMatch[0].length);\n let data: Record<string, unknown> = {};\n if (yamlSource.trim().length > 0) {\n try {\n data = asRecord(parse(yamlSource));\n } catch (error: unknown) {\n if (options.throwOnInvalid) {\n throw error;\n }\n data = {};\n }\n }\n\n return {\n data,\n content,\n };\n};\n","import { parseFrontmatter } from \"./frontmatter.js\";\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 = parseFrontmatter(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 {\n laneForTruthDocumentKind,\n mergeTruthDocumentEntryRelationships,\n type TruthDocumentEntry,\n} from \"../routing/areas.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} 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\nconst PRODUCT_LINK_REVIEW_KINDS = new Set([\n \"engineering-behavior\",\n \"engineering-workflow\",\n \"engineering-contract\",\n]);\n\nconst normalizeRoot = (value: string): string =>\n value.replaceAll(\"\\\\\", \"/\").replace(/\\/+$/u, \"\");\n\nconst validateLaneShape = (\n entry: TruthDocumentEntry,\n config: TruthmarkConfig,\n areaName: string,\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const productRoot = normalizeRoot(resolveProductTruthRoot(config));\n const engineeringRoot = normalizeRoot(resolveEngineeringTruthRoot(config));\n const normalizedPath = entry.path.replaceAll(\"\\\\\", \"/\");\n const expectedLane = laneForTruthDocumentKind(entry.kind);\n\n if (entry.lane !== expectedLane) {\n diagnostics.push({\n category: \"lane-shape\",\n severity: \"error\",\n message: `Truth document ${entry.path} declares ${entry.kind} in ${entry.lane} lane; ${entry.kind} belongs to the ${expectedLane} lane.`,\n area: areaName,\n file: entry.path,\n });\n }\n\n if (\n entry.lane === \"product\" &&\n !normalizedPath.startsWith(`${productRoot}/`)\n ) {\n diagnostics.push({\n category: \"lane-shape\",\n severity: \"error\",\n message: `Product truth document ${entry.path} must live under ${productRoot}.`,\n area: areaName,\n file: entry.path,\n });\n }\n\n if (\n entry.lane === \"engineering\" &&\n !normalizedPath.startsWith(`${engineeringRoot}/`)\n ) {\n diagnostics.push({\n category: \"lane-shape\",\n severity: \"error\",\n message: `Engineering truth document ${entry.path} must live under ${engineeringRoot}.`,\n area: areaName,\n file: entry.path,\n });\n }\n\n return diagnostics;\n};\n\nconst validateRelationshipTargets = (\n entries: TruthDocumentEntry[],\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const byPath = new Map(entries.map((entry) => [entry.path, entry]));\n\n for (const entry of entries) {\n for (const target of entry.realizedBy) {\n const targetEntry = byPath.get(target);\n if (!targetEntry) {\n diagnostics.push({\n category: \"traceability\",\n severity: \"error\",\n message: `Product truth document ${entry.path} declares missing engineering realization ${target}.`,\n file: entry.path,\n });\n } else if (targetEntry.lane !== \"engineering\") {\n diagnostics.push({\n category: \"traceability\",\n severity: \"error\",\n message: `Product truth document ${entry.path} realized_by target ${target} must point to engineering truth.`,\n file: entry.path,\n });\n }\n }\n\n for (const target of entry.realizes) {\n const targetEntry = byPath.get(target);\n if (!targetEntry) {\n diagnostics.push({\n category: \"traceability\",\n severity: \"error\",\n message: `Engineering truth document ${entry.path} declares missing product truth ${target}.`,\n file: entry.path,\n });\n } else if (targetEntry.lane !== \"product\") {\n diagnostics.push({\n category: \"traceability\",\n severity: \"error\",\n message: `Engineering truth document ${entry.path} realizes target ${target} must point to product truth.`,\n file: entry.path,\n });\n }\n }\n }\n\n return diagnostics;\n};\n\nconst validateMissingProductLinkReviews = (\n entries: TruthDocumentEntry[],\n reportedPaths: Set<string>,\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const hasProductTruth = entries.some((entry) => entry.lane === \"product\");\n\n if (!hasProductTruth) {\n return diagnostics;\n }\n\n for (const entry of entries) {\n if (\n entry.lane === \"engineering\" &&\n PRODUCT_LINK_REVIEW_KINDS.has(entry.kind) &&\n entry.realizes.length === 0 &&\n !reportedPaths.has(entry.path)\n ) {\n reportedPaths.add(entry.path);\n diagnostics.push({\n category: \"traceability\",\n severity: \"review\",\n message: `User-visible engineering truth document ${entry.path} should link product truth with realizes when it implements a product capability.`,\n file: entry.path,\n });\n }\n }\n\n return diagnostics;\n};\n\nexport const checkAreas = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<AreasCheckResult> => {\n const routing = await resolveAreaRouting(rootDir, {\n rootIndex: config.truthmark.paths.routesIndex,\n areaFilesRoot: config.truthmark.paths.routeAreasRoot,\n productTruthRoot: resolveProductTruthRoot(config),\n engineeringTruthRoot: resolveEngineeringTruthRoot(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 reportedMissingProductLinkPaths = new Set<string>();\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 areaTruthDocumentEntries: TruthDocumentEntry[] = [];\n const registerTruthDocumentEntry = (\n truthDocumentEntry: TruthDocumentEntry,\n ): 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 && existingEntry.lane !== truthDocumentEntry.lane) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document ${truthDocumentEntry.path} is routed with conflicting lanes ${existingEntry.lane} and ${truthDocumentEntry.lane}.`,\n area: area.name,\n file: truthDocumentEntry.path,\n });\n return false;\n }\n\n if (!existingEntry) {\n truthDocumentEntryMap.set(truthDocumentEntry.path, truthDocumentEntry);\n } else {\n truthDocumentEntryMap.set(\n truthDocumentEntry.path,\n mergeTruthDocumentEntryRelationships(\n existingEntry,\n truthDocumentEntry,\n ),\n );\n }\n\n areaTruthDocumentEntries.push(truthDocumentEntry);\n diagnostics.push(\n ...validateLaneShape(truthDocumentEntry, config, area.name),\n );\n\n return true;\n };\n\n for (const [\n truthDocumentIndex,\n truthDocument,\n ] of area.truthDocuments.entries()) {\n const routedEntry = area.truthDocumentEntries[truthDocumentIndex];\n\n if (looksLikeGlob(truthDocument)) {\n const matches = (\n await fg([truthDocument], { cwd: rootDir, onlyFiles: true })\n ).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 routedEntry &&\n !registerTruthDocumentEntry({\n ...routedEntry,\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 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) =>\n truthDocument === area.truthDocuments[index],\n ),\n );\n if (matchingArea) {\n matchingArea.valid = false;\n }\n }\n\n diagnostics.push(\n ...validateMissingProductLinkReviews(\n areaTruthDocumentEntries,\n reportedMissingProductLinkPaths,\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(\n rootDir,\n resolveRepoPath(rootDir, match),\n );\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 &&\n 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) =>\n diagnostic.category === \"area-index\" &&\n diagnostic.severity === \"review\",\n ).length;\n\n const truthDocumentEntries = [...truthDocumentEntryMap.values()];\n diagnostics.push(...validateRelationshipTargets(truthDocumentEntries));\n\n return {\n diagnostics,\n truthDocumentPaths,\n truthDocumentEntries,\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 productTruthRoot?: string;\n engineeringTruthRoot?: string;\n};\n\ntype 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 productTruthRoot: config.productTruthRoot,\n engineeringTruthRoot: config.engineeringTruthRoot,\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 productTruthRoot: config.productTruthRoot,\n engineeringTruthRoot: config.engineeringTruthRoot,\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(\".agents/skills/truthmark-\") ||\n normalizedPath.startsWith(\".claude/\") ||\n normalizedPath.startsWith(\".codex/\") ||\n normalizedPath.startsWith(\".opencode/\") ||\n normalizedPath.startsWith(\".antigravity/rules/truthmark-\") ||\n normalizedPath.startsWith(\".cursor/rules/truthmark-\") ||\n normalizedPath.startsWith(\".cursor/skills/truthmark-\") ||\n normalizedPath === \".github/copilot-instructions.md\" ||\n normalizedPath.startsWith(\".github/agents/truth-\") ||\n normalizedPath.startsWith(\".github/prompts/truthmark-\") ||\n normalizedPath.startsWith(\".github/skills/truthmark-\") ||\n normalizedPath === \"AGENTS.md\" ||\n normalizedPath === \"CLAUDE.md\"\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 laneForTruthDocumentKind,\n type TruthDocumentEntry,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\nimport {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"../truth/docs.js\";\n\nconst PRODUCT_CAPABILITY_REQUIRED_HEADINGS = [\n \"Capability Promise\",\n \"Users And Value\",\n \"Capability Scope\",\n \"Current Product Behavior\",\n \"Acceptance Criteria\",\n \"Product Decisions\",\n \"Engineering Realization Links\",\n \"Non-Goals\",\n];\nconst ENGINEERING_REQUIRED_HEADINGS = [\n \"Purpose\",\n \"Scope\",\n \"Current Implementation Behavior\",\n \"Source References\",\n \"Product Truth Links\",\n \"Maintenance Notes\",\n];\nconst FORBIDDEN_PRODUCT_HEADINGS = [\n \"Execution Flow\",\n \"Execution Model\",\n \"Generated File Inventory\",\n \"CLI Envelope Details\",\n \"Data And Control Flow\",\n];\nconst FORBIDDEN_ENGINEERING_HEADINGS = [\n \"Product Promise\",\n \"User / Stakeholder Value\",\n \"Product Decisions\",\n \"Product Rationale\",\n \"Business Boundary\",\n];\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(\n source,\n );\n};\n\nconst kindSpecificHeadingMessages = (\n source: string,\n kind: TruthDocumentKind | null,\n): string[] => {\n if (kind === null) {\n return [];\n }\n\n if (kind === \"engineering-behavior\") {\n return hasHeading(source, \"Current Implementation Behavior\")\n ? []\n : [\"Current Implementation Behavior\"];\n }\n\n if (kind === \"engineering-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 === \"engineering-architecture\") {\n return hasHeading(source, \"Boundaries\") || hasHeading(source, \"Components\")\n ? []\n : [\"Boundaries or Components\"];\n }\n\n if (kind === \"engineering-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 === \"engineering-operations\") {\n return hasHeading(source, \"Runtime Topology\") ||\n hasHeading(source, \"Configuration\")\n ? []\n : [\"Runtime Topology or Configuration\"];\n }\n\n if (kind === \"engineering-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(\n \"Fixtures And Data Model or Assertions And Invariants\",\n );\n }\n\n return missingMessages;\n }\n\n return [];\n};\n\nconst productRequiredHeadings = (kind: TruthDocumentKind | null): string[] => {\n if (kind === \"product-capability\") {\n return PRODUCT_CAPABILITY_REQUIRED_HEADINGS;\n }\n\n return PRODUCT_CAPABILITY_REQUIRED_HEADINGS;\n};\n\nconst decisionTruthGlobs = (config: TruthmarkConfig): string[] => {\n return [\n `${resolveProductTruthRoot(config)}/**/*.md`,\n `${resolveEngineeringTruthRoot(config)}/**/*.md`,\n ];\n};\n\nconst isDecisionTruthCandidate = (\n config: TruthmarkConfig,\n filePath: string,\n): boolean => {\n return (\n !filePath.endsWith(\"/README.md\") &&\n micromatch.isMatch(filePath, decisionTruthGlobs(config))\n );\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) ||\n isDecisionTruthCandidate(config, filePath),\n )\n .sort();\n\n for (const filePath of candidatePaths) {\n const source = await fs.readFile(\n resolveRepoPath(rootDir, filePath),\n \"utf8\",\n );\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\"\n ? null\n : routedTruthDocument?.kind;\n const truthKind =\n routedTruthKind ??\n (frontmatterTruthKind && isTruthDocumentKind(frontmatterTruthKind)\n ? frontmatterTruthKind\n : inferTruthDocumentKindFromPath(filePath));\n const lane =\n routedTruthDocument?.lane ??\n (truthKind\n ? laneForTruthDocumentKind(truthKind)\n : filePath.startsWith(resolveProductTruthRoot(config))\n ? \"product\"\n : \"engineering\");\n const requiredHeadings =\n lane === \"product\"\n ? productRequiredHeadings(truthKind)\n : ENGINEERING_REQUIRED_HEADINGS;\n const missingHeadings = requiredHeadings.filter(\n (heading) => !hasHeading(source, heading),\n );\n if (lane === \"engineering\") {\n missingHeadings.push(...kindSpecificHeadingMessages(source, truthKind));\n }\n const forbiddenHeadings = (\n lane === \"product\"\n ? FORBIDDEN_PRODUCT_HEADINGS\n : FORBIDDEN_ENGINEERING_HEADINGS\n ).filter((heading) => hasHeading(source, heading));\n\n if (missingHeadings.length === 0 && forbiddenHeadings.length === 0) {\n continue;\n }\n\n if (missingHeadings.length > 0) {\n diagnostics.push({\n category: \"doc-structure\",\n severity: \"review\",\n message: `Canonical ${lane} truth doc ${filePath} should include ${missingHeadings.join(\" and \")} section(s). Product truth says what must be true and why; engineering truth says how the repository currently realizes it.`,\n file: filePath,\n });\n }\n\n if (forbiddenHeadings.length > 0) {\n diagnostics.push({\n category: \"lane-drift\",\n severity: \"error\",\n message: `Canonical ${lane} truth doc ${filePath} contains wrong-lane section(s): ${forbiddenHeadings.join(\", \")}.`,\n file: filePath,\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 type { RouteMapRoute } from \"../repo-index/types.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport { getChangedFiles } from \"./git-diff.js\";\nimport type { ImpactOptions, ImpactRoute, ImpactSet } 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});\n\nconst changedFilePaths = (changedFile: { path: string; previousPath?: string }): string[] => {\n return [changedFile.path, ...(changedFile.previousPath ? [changedFile.previousPath] : [])];\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\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 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\n const uniqueAffectedTruthDocs = uniqueSorted(affectedTruthDocs);\n for (const test of repoIndex.tests) {\n const hintMatchesChangedFile = changedFiles.some((changedFile) =>\n changedFilePaths(changedFile).some((filePath) =>\n testHintMatchesChangedFile(test.targetHints, filePath),\n ),\n );\n\n if (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 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 micromatch from \"micromatch\";\n\nimport { parseFrontmatter } from \"../markdown/frontmatter.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport {\n TRUTH_DOCUMENT_KINDS,\n docTypeForTruthDocumentKind,\n laneForTruthDocumentKind,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport { parseSourceReferences } from \"../truth/source-references.js\";\nimport type {\n RepoDocEntry,\n RepoFileEntry,\n RepoFileKind,\n RepoTestEntry,\n} 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 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\n .basename(filePath)\n .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(\n (segment) => segment === \"tests\" || segment === \"__tests__\",\n );\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 =>\n filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/u, \"\");\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\nconst gitDiscoverableFiles = async (\n rootDir: string,\n): 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<{\n files: RepoFileEntry[];\n docs: RepoDocEntry[];\n tests: RepoTestEntry[];\n}> => {\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\n .filter((entry) => !isIgnoredPath(entry, ignore))\n .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 (\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\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 = parseFrontmatter(source);\n const markdown = parseMarkdownDocument(parsed.content);\n const title =\n markdown.headings.find((heading) => heading.depth === 1)?.text ?? null;\n const sourceOfTruth = parseSourceReferences(source, filePath);\n const truthKind =\n typeof parsed.data.truth_kind === \"string\"\n ? parsed.data.truth_kind\n : null;\n const derivedTruthKind = isTruthDocumentKind(truthKind)\n ? truthKind\n : null;\n\n docs.push({\n path: filePath,\n title,\n docType:\n typeof parsed.data.doc_type === \"string\"\n ? parsed.data.doc_type\n : derivedTruthKind\n ? docTypeForTruthDocumentKind(derivedTruthKind)\n : null,\n truthKind,\n truthLane:\n typeof parsed.data.truth_lane === \"string\"\n ? parsed.data.truth_lane\n : derivedTruthKind\n ? laneForTruthDocumentKind(derivedTruthKind)\n : null,\n sourceOfTruth: sourceOfTruth.sort(),\n realizedBy: [],\n realizes: [],\n dependsOn: [],\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 path from \"node:path\";\n\nimport { parseFrontmatter } from \"../markdown/frontmatter.js\";\n\nconst repoRootPrefixes = [\n \".codex/\",\n \".github/\",\n \".truthmark/\",\n \"docs/\",\n \"src/\",\n \"tests/\",\n];\nconst sourceReferencesHeadingPattern = /^##\\s+Source References\\s*$/imu;\nconst nextSecondLevelHeadingPattern = /^##\\s+/imu;\nconst bulletReferencePattern = /^\\s*[-*]\\s+(.+?)\\s*$/u;\nconst markdownLinkPattern = /^\\s*\\[[^\\]]+\\]\\(([^)]+)\\)\\s*$/u;\nconst backtickPathPattern = /^\\s*`([^`]+)`\\s*$/u;\n\nexport const normalizeSourceReferencePath = (\n truthDocPath: string,\n referencePath: string,\n): string => {\n const strippedPath = referencePath.split(\"#\")[0]?.trim() ?? \"\";\n const isRepoRelative = repoRootPrefixes.some((prefix) =>\n strippedPath.startsWith(prefix),\n );\n\n if (\n !isRepoRelative &&\n (strippedPath.startsWith(\".\") || !strippedPath.includes(\"/\"))\n ) {\n return path.posix.normalize(\n path.posix.join(path.posix.dirname(truthDocPath), strippedPath),\n );\n }\n\n return path.posix.normalize(strippedPath);\n};\n\nconst normalizeReferenceText = (value: string): string => {\n const trimmed = value.trim();\n const markdownLinkMatch = markdownLinkPattern.exec(trimmed);\n if (markdownLinkMatch) {\n return markdownLinkMatch[1]?.trim() ?? \"\";\n }\n\n const backtickMatch = backtickPathPattern.exec(trimmed);\n if (backtickMatch) {\n return backtickMatch[1]?.trim() ?? \"\";\n }\n\n return trimmed;\n};\n\nconst parseSourceReferencesSection = (content: string): string[] => {\n const headingMatch = sourceReferencesHeadingPattern.exec(content);\n if (!headingMatch || typeof headingMatch.index !== \"number\") {\n return [];\n }\n\n const sectionStart = headingMatch.index + headingMatch[0].length;\n const afterHeading = content.slice(sectionStart);\n const nextHeadingMatch = nextSecondLevelHeadingPattern.exec(afterHeading);\n const section = nextHeadingMatch\n ? afterHeading.slice(0, nextHeadingMatch.index)\n : afterHeading;\n const references: string[] = [];\n\n for (const line of section.split(\"\\n\")) {\n const bulletMatch = bulletReferencePattern.exec(line);\n if (!bulletMatch) {\n continue;\n }\n\n const reference = normalizeReferenceText(bulletMatch[1] ?? \"\");\n if (reference.length > 0 && !reference.startsWith(\"{{\")) {\n references.push(reference);\n }\n }\n\n return references;\n};\n\nexport const parseSourceReferences = (\n source: string,\n truthDocPath: string,\n): string[] => {\n const parsed = parseFrontmatter(source);\n const references = new Set<string>();\n const frontmatterSourceOfTruth = Array.isArray(parsed.data.source_of_truth)\n ? parsed.data.source_of_truth\n : [];\n\n for (const entry of frontmatterSourceOfTruth) {\n if (typeof entry === \"string\") {\n references.add(normalizeSourceReferencePath(truthDocPath, entry));\n }\n }\n\n for (const entry of parseSourceReferencesSection(parsed.content)) {\n references.add(normalizeSourceReferencePath(truthDocPath, entry));\n }\n\n return [...references].sort();\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 {\n mergeTruthDocumentEntryRelationships,\n type TruthDocumentEntry,\n} from \"../routing/areas.js\";\nimport {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"../truth/docs.js\";\nimport type { RouteMap } from \"./types.js\";\n\nconst mergedEntryMap = (\n entries: TruthDocumentEntry[],\n): Map<string, TruthDocumentEntry> => {\n const byPath = new Map<string, TruthDocumentEntry>();\n\n for (const entry of entries) {\n const existingEntry = byPath.get(entry.path);\n if (\n existingEntry &&\n existingEntry.kind === entry.kind &&\n existingEntry.lane === entry.lane\n ) {\n byPath.set(\n entry.path,\n mergeTruthDocumentEntryRelationships(existingEntry, entry),\n );\n } else if (!existingEntry) {\n byPath.set(entry.path, entry);\n }\n }\n\n return byPath;\n};\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.truthmark.paths.routesIndex,\n areaFilesRoot: loadResult.config.truthmark.paths.routeAreasRoot,\n productTruthRoot: resolveProductTruthRoot(loadResult.config),\n engineeringTruthRoot: resolveEngineeringTruthRoot(loadResult.config),\n });\n\n const mergedTruthDocumentEntries = mergedEntryMap(\n routing.areas.flatMap((area) => area.truthDocumentEntries),\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 truthDocumentEntries: [\n ...new Map(\n area.truthDocumentEntries.map((entry) => [\n entry.path,\n mergedTruthDocumentEntries.get(entry.path) ?? entry,\n ]),\n ).values(),\n ].sort((left, right) => left.path.localeCompare(right.path)),\n updateTruthWhen: [...area.updateTruthWhen],\n }))\n .sort((left, right) => left.key.localeCompare(right.key)),\n diagnostics: routing.diagnostics,\n };\n};\n","import { loadConfig } from \"../config/load.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { discoverRepoFiles } from \"./file-tree.js\";\nimport { discoverPackageMetadata } from \"./package-metadata.js\";\nimport { buildRouteMap } from \"./route-map.js\";\nimport type { 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\n diagnostics.push(...routeMap.diagnostics);\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 routeMap,\n diagnostics,\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 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\";\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[] = [];\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 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 { 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: \"source-traceability\",\n severity: \"error\",\n message,\n file: reference.truthDocPath,\n data: {\n reference: reference.path,\n source: reference.source,\n },\n});\n\nconst parseDiagnosticFor = (truthDocPath: string, error: unknown): Diagnostic => ({\n category: \"source-traceability\",\n severity: \"error\",\n message: `Malformed evidence YAML block in ${truthDocPath}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n file: truthDocPath,\n data: {\n source: \"evidence-block\",\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 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 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 let references: EvidenceReference[];\n try {\n references = await parseEvidenceReferences(rootDir, truthDocPath);\n } catch (error) {\n diagnostics.push(parseDiagnosticFor(truthDocPath, error));\n continue;\n }\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 { parse } from \"yaml\";\n\nimport { parseFrontmatter } from \"../markdown/frontmatter.js\";\n\nimport type { EvidenceReference } from \"./types.js\";\nimport {\n normalizeSourceReferencePath,\n parseSourceReferences,\n} from \"../truth/source-references.js\";\n\nconst yamlFencePattern = /```ya?ml\\s*\\n([\\s\\S]*?)```/giu;\nconst topLevelEvidenceMarkerPattern = /^evidence\\s*:/imu;\n\nconst toEvidenceReference = (\n truthDocPath: string,\n raw: unknown,\n): EvidenceReference | null => {\n if (\n !raw ||\n typeof raw !== \"object\" ||\n !(\"path\" in raw) ||\n typeof raw.path !== \"string\"\n ) {\n return null;\n }\n\n return {\n truthDocPath,\n path: normalizeSourceReferencePath(truthDocPath, raw.path),\n symbol:\n \"symbol\" in raw && typeof raw.symbol === \"string\"\n ? raw.symbol\n : undefined,\n startLine:\n \"start_line\" in raw && typeof raw.start_line === \"number\"\n ? raw.start_line\n : undefined,\n endLine:\n \"end_line\" in raw && typeof raw.end_line === \"number\"\n ? raw.end_line\n : undefined,\n contentHash:\n \"content_hash\" in raw && typeof raw.content_hash === \"string\"\n ? raw.content_hash\n : 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 = parseFrontmatter(source);\n const references: EvidenceReference[] = [];\n\n for (const entry of parseSourceReferences(source, truthDocPath)) {\n references.push({\n truthDocPath,\n path: entry,\n source: \"source-references\",\n });\n }\n\n for (const match of parsed.content.matchAll(yamlFencePattern)) {\n const yamlBlock = match[1] ?? \"\";\n if (!topLevelEvidenceMarkerPattern.test(yamlBlock)) {\n continue;\n }\n\n const block = parse(yamlBlock) 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 { Diagnostic } from \"../output/diagnostic.js\";\n\nexport const TRUTH_HEALTH_SCORECARD_SCHEMA_VERSION = \"truthmark-scorecard/v0\" as const;\n\nexport const TRUTH_HEALTH_DIMENSION_IDS = [\n \"routing-coverage\",\n \"ownership-clarity\",\n \"source-traceability\",\n \"branch-freshness\",\n \"generated-surface-freshness\",\n \"truth-doc-structure\",\n \"decision-rationale-preservation\",\n] as const;\n\nexport type TruthHealthDimensionId = (typeof TRUTH_HEALTH_DIMENSION_IDS)[number];\n\nexport type TruthHealthDimensionStatus = \"pass\" | \"warn\" | \"fail\" | \"not-run\";\n\nexport type TruthHealthScorecardDimension = {\n id: TruthHealthDimensionId;\n status: TruthHealthDimensionStatus;\n diagnosticIndexes: number[];\n evidence?: string[];\n};\n\nexport type TruthHealthScorecard = {\n schemaVersion: typeof TRUTH_HEALTH_SCORECARD_SCHEMA_VERSION;\n dimensions: TruthHealthScorecardDimension[];\n};\n\nexport type TruthHealthScorecardContext = {\n branchFreshnessRan: boolean;\n branchFreshnessNotRunReason?: string;\n routingChecksRan?: boolean;\n ownershipChecksRan?: boolean;\n evidenceChecksRan?: boolean;\n generatedSurfaceChecksRan?: boolean;\n truthDocStructureChecksRan?: boolean;\n decisionRationaleChecksRan?: boolean;\n};\n\nconst EVIDENCE_LIMIT = 2;\n\nconst textIncludesAny = (text: string, needles: string[]): boolean => {\n const normalized = text.toLowerCase();\n return needles.some((needle) => normalized.includes(needle));\n};\n\nconst diagnosticText = (diagnostic: Diagnostic): string => {\n const dataText = diagnostic.data ? JSON.stringify(diagnostic.data) : \"\";\n return `${diagnostic.message} ${diagnostic.file ?? \"\"} ${diagnostic.area ?? \"\"} ${dataText}`;\n};\n\nconst isRouteAmbiguityDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"context-pack\" &&\n textIncludesAny(diagnosticText(diagnostic), [\n \"route\",\n \"routing\",\n \"ownership\",\n \"write boundary\",\n \"allowed write\",\n ]);\n\nconst isSourceTraceabilityDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"source-traceability\" ||\n (diagnostic.category === \"links\" &&\n textIncludesAny(diagnosticText(diagnostic), [\n \"source_of_truth\",\n \"source of truth\",\n \"source evidence\",\n \"evidence\",\n ]));\n\nconst isMarkdownShapeDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"authority\" &&\n textIncludesAny(diagnosticText(diagnostic), [\"markdown\", \"heading\", \"section\"]);\n\nconst isOwnershipFreshnessDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"freshness\" &&\n textIncludesAny(diagnosticText(diagnostic), [\n \"route\",\n \"routing\",\n \"ownership\",\n \"truth owner\",\n \"truth ownership\",\n \"affected truth document\",\n ]);\n\nconst isDecisionRationaleDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"doc-structure\" &&\n textIncludesAny(diagnosticText(diagnostic), [\"product decisions\", \"rationale\"]);\n\nconst mapsToDimension = (\n diagnostic: Diagnostic,\n dimensionId: TruthHealthDimensionId,\n): boolean => {\n switch (dimensionId) {\n case \"routing-coverage\":\n return [\"config\", \"authority\", \"area-index\", \"coverage\", \"repo-index\"].includes(\n diagnostic.category,\n );\n case \"ownership-clarity\":\n return (\n [\"config\", \"area-index\", \"coverage\", \"impact\"].includes(diagnostic.category) ||\n isRouteAmbiguityDiagnostic(diagnostic) ||\n isOwnershipFreshnessDiagnostic(diagnostic)\n );\n case \"source-traceability\":\n return isSourceTraceabilityDiagnostic(diagnostic);\n case \"branch-freshness\":\n return diagnostic.category === \"freshness\";\n case \"generated-surface-freshness\":\n return diagnostic.category === \"config\" || diagnostic.category === \"generated-surface\";\n case \"truth-doc-structure\":\n return (\n diagnostic.category === \"config\" ||\n diagnostic.category === \"frontmatter\" ||\n diagnostic.category === \"links\" ||\n diagnostic.category === \"doc-structure\" ||\n isMarkdownShapeDiagnostic(diagnostic)\n );\n case \"decision-rationale-preservation\":\n return isDecisionRationaleDiagnostic(diagnostic);\n }\n};\n\nconst checkerRanForDimension = (\n dimensionId: TruthHealthDimensionId,\n context: TruthHealthScorecardContext,\n): boolean => {\n switch (dimensionId) {\n case \"routing-coverage\":\n return context.routingChecksRan ?? true;\n case \"ownership-clarity\":\n return context.ownershipChecksRan ?? true;\n case \"source-traceability\":\n return context.evidenceChecksRan ?? true;\n case \"branch-freshness\":\n return context.branchFreshnessRan;\n case \"generated-surface-freshness\":\n return context.generatedSurfaceChecksRan ?? true;\n case \"truth-doc-structure\":\n return context.truthDocStructureChecksRan ?? true;\n case \"decision-rationale-preservation\":\n return context.decisionRationaleChecksRan ?? true;\n }\n};\n\nconst statusForDiagnostics = (\n diagnostics: Diagnostic[],\n diagnosticIndexes: number[],\n checkerRan: boolean,\n): TruthHealthDimensionStatus => {\n if (diagnosticIndexes.length > 0) {\n return diagnosticIndexes.some((index) => diagnostics[index]?.severity === \"error\")\n ? \"fail\"\n : \"warn\";\n }\n\n return checkerRan ? \"pass\" : \"not-run\";\n};\n\nconst evidenceForDiagnostics = (\n diagnostics: Diagnostic[],\n diagnosticIndexes: number[],\n status: TruthHealthDimensionStatus,\n dimensionId: TruthHealthDimensionId,\n context: TruthHealthScorecardContext,\n): string[] | undefined => {\n if (status === \"pass\") {\n return undefined;\n }\n\n if (diagnosticIndexes.length === 0) {\n if (dimensionId === \"branch-freshness\") {\n return [context.branchFreshnessNotRunReason ?? \"base not supplied\"];\n }\n\n return [\"checker not run\"];\n }\n\n return diagnosticIndexes.slice(0, EVIDENCE_LIMIT).map((index) => {\n const diagnostic = diagnostics[index];\n const subject = diagnostic.file ?? diagnostic.area;\n return subject ? `${diagnostic.category}:${subject}` : diagnostic.category;\n });\n};\n\nexport const buildTruthHealthScorecard = (\n diagnostics: Diagnostic[],\n context: TruthHealthScorecardContext,\n): TruthHealthScorecard => ({\n schemaVersion: TRUTH_HEALTH_SCORECARD_SCHEMA_VERSION,\n dimensions: TRUTH_HEALTH_DIMENSION_IDS.map((dimensionId) => {\n const diagnosticIndexes = diagnostics.flatMap((diagnostic, index) =>\n mapsToDimension(diagnostic, dimensionId) ? [index] : [],\n );\n const status = statusForDiagnostics(\n diagnostics,\n diagnosticIndexes,\n checkerRanForDimension(dimensionId, context),\n );\n const evidence = evidenceForDiagnostics(\n diagnostics,\n diagnosticIndexes,\n status,\n dimensionId,\n context,\n );\n\n return {\n id: dimensionId,\n status,\n diagnosticIndexes,\n ...(evidence ? { evidence } : {}),\n };\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\";\nimport { validateEvidenceReferences } from \"../evidence/validate.js\";\nimport { buildTruthHealthScorecard } from \"./scorecard.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 const scorecard = buildTruthHealthScorecard(loadResult.diagnostics, {\n branchFreshnessRan: false,\n branchFreshnessNotRunReason: options.base ? \"config unavailable\" : \"base not supplied\",\n routingChecksRan: false,\n ownershipChecksRan: false,\n evidenceChecksRan: false,\n generatedSurfaceChecksRan: false,\n truthDocStructureChecksRan: false,\n decisionRationaleChecksRan: false,\n });\n\n return {\n command: \"check\",\n summary: summarizeDiagnostics(loadResult.diagnostics),\n diagnostics: loadResult.diagnostics,\n data: {\n branchScope,\n scorecard,\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 sourceTraceability = await validateEvidenceReferences(rootDir, areas.truthDocumentPaths);\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 ...sourceTraceability,\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 const scorecard = buildTruthHealthScorecard(diagnostics, {\n branchFreshnessRan: Boolean(freshness),\n branchFreshnessNotRunReason: options.base ? \"freshness checker skipped\" : \"base not supplied\",\n evidenceChecksRan: true,\n });\n\n return {\n command: \"check\",\n summary: summarizeDiagnostics(diagnostics),\n diagnostics,\n data: {\n branchScope,\n truthVisibility,\n scorecard,\n ...(freshness ? { impactSet: freshness.impactSet } : {}),\n },\n };\n};\n","import { execa } from \"execa\";\nimport micromatch from \"micromatch\";\n\nimport {\n TRUTHMARK_WORKFLOW_MANIFEST,\n type TruthmarkWorkflowManifestEntry,\n type TruthmarkWorkflowId,\n} from \"../agents/workflow-manifest.js\";\nimport { loadConfig } from \"../config/load.js\";\nimport { runCheck } from \"../checks/check.js\";\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 { RepoIndex } from \"../repo-index/types.js\";\nimport { buildWorkflowActionContext } from \"./action-context.js\";\nimport type {\n BuildWorkflowStateOptions,\n WorkflowApplicability,\n WorkflowActionContextData,\n WorkflowAdvisoryCard,\n WorkflowHelperValidationCommand,\n WorkflowState,\n} from \"./types.js\";\n\nconst helperCommandsFor = (\n workflow: TruthmarkWorkflowId,\n): WorkflowHelperValidationCommand[] =>\n (\n (TRUTHMARK_WORKFLOW_MANIFEST[workflow] as TruthmarkWorkflowManifestEntry)\n .helpers ?? []\n ).map((helper) => ({\n id: helper.id,\n runner: helper.runner,\n argv: [...helper.command.argv],\n optional: helper.optional,\n }));\n\nconst uniqueSorted = (values: string[]): string[] =>\n [...new Set(values.filter((value) => value.length > 0))].sort();\n\nconst isWriteCapable = (workflow: TruthmarkWorkflowId): boolean =>\n workflow !== \"truthmark-check\";\n\nconst DEFAULT_BASE_CANDIDATES = [\n \"@{upstream}\",\n \"origin/main\",\n \"main\",\n \"origin/master\",\n \"master\",\n];\n\nconst selectComparisonBase = async (\n rootDir: string,\n suppliedBase?: string,\n): Promise<string | null> => {\n if (suppliedBase) {\n return suppliedBase;\n }\n\n for (const candidate of DEFAULT_BASE_CANDIDATES) {\n const result = await execa(\n \"git\",\n [\"rev-parse\", \"--verify\", `${candidate}^{commit}`],\n {\n cwd: rootDir,\n reject: false,\n },\n );\n if ((result.exitCode ?? 1) === 0) {\n return candidate;\n }\n }\n\n return null;\n};\n\nconst routeFilesFor = (repoIndex: RepoIndex): string[] =>\n uniqueSorted(repoIndex.routeMap.routes.map((route) => route.sourcePath));\n\nconst candidateStaleTruthDocsFor = (\n repoIndex: RepoIndex,\n primaryTruthDocs: string[],\n impactSet: ImpactSet | null,\n diagnostics: Diagnostic[],\n): string[] => {\n const indexedTruthDocs = new Set(\n repoIndex.routeMap.routes.flatMap((route) => route.truthDocs),\n );\n const primary = new Set(primaryTruthDocs);\n const candidates = new Set<string>();\n const changedPaths = new Set(\n (impactSet?.changedFiles ?? []).flatMap((file) => [\n file.path,\n ...(file.previousPath ? [file.previousPath] : []),\n ]),\n );\n const docEntries = new Map(\n repoIndex.routeMap.routes\n .flatMap((route) => route.truthDocumentEntries)\n .map((entry) => [entry.path, entry]),\n );\n\n const addCandidate = (truthDoc: string): void => {\n if (indexedTruthDocs.has(truthDoc) && !primary.has(truthDoc)) {\n candidates.add(truthDoc);\n }\n };\n\n const linkedTruthDocs = (truthDoc: string): string[] => {\n const entry = docEntries.get(truthDoc);\n return uniqueSorted([\n ...(entry?.realizedBy ?? []),\n ...(entry?.realizes ?? []),\n ...(entry?.dependsOn ?? []),\n ...[...docEntries.values()]\n .filter(\n (candidate) =>\n candidate.realizedBy.includes(truthDoc) ||\n candidate.realizes.includes(truthDoc) ||\n candidate.dependsOn.includes(truthDoc),\n )\n .map((candidate) => candidate.path),\n ]);\n };\n\n for (const truthDoc of [...primary, ...changedPaths].filter((path) =>\n indexedTruthDocs.has(path),\n )) {\n for (const linkedTruthDoc of linkedTruthDocs(truthDoc)) {\n addCandidate(linkedTruthDoc);\n }\n }\n\n for (const diagnostic of diagnostics) {\n if (diagnostic.category === \"freshness\" && diagnostic.file) {\n addCandidate(diagnostic.file);\n }\n }\n\n for (const route of repoIndex.routeMap.routes) {\n if (changedPaths.has(route.sourcePath)) {\n route.truthDocs.forEach(addCandidate);\n }\n }\n\n for (const doc of repoIndex.docs) {\n if (!indexedTruthDocs.has(doc.path) || primary.has(doc.path)) {\n continue;\n }\n\n if (\n doc.sourceOfTruth.some((reference) =>\n [...changedPaths].some(\n (changedPath) =>\n reference === changedPath || micromatch.isMatch(changedPath, reference),\n ),\n )\n ) {\n candidates.add(doc.path);\n }\n }\n\n return uniqueSorted([...candidates]);\n};\n\nconst hasUnmappedFunctionalChange = (impactSet: ImpactSet | null): boolean =>\n impactSet?.diagnostics.some(\n (diagnostic) =>\n diagnostic.category === \"impact\" &&\n /not mapped to a Truthmark route|no affected truth document/u.test(\n diagnostic.message,\n ),\n ) ?? false;\n\nconst applicabilityFor = (\n workflow: TruthmarkWorkflowId,\n diagnostics: Diagnostic[],\n impactSet: ImpactSet | null,\n): WorkflowApplicability => {\n const reasons: string[] = [];\n\n if (\n diagnostics.some((diagnostic) =>\n diagnostic.message.includes(\"Missing .truthmark/config.yml\"),\n )\n ) {\n reasons.push(\"Missing .truthmark/config.yml.\");\n return {\n state: isWriteCapable(workflow)\n ? \"needs_manual_review\"\n : \"not_applicable\",\n reasons,\n };\n }\n\n if (workflow === \"truthmark-sync\" && !impactSet) {\n reasons.push(\n \"Choose a comparison base with --base <ref> when workflow status cannot infer one automatically.\",\n );\n return { state: \"needs_manual_review\", reasons };\n }\n\n if (workflow === \"truthmark-realize\" && !impactSet) {\n reasons.push(\n \"Choose a comparison base with --base <ref> so the helper can suggest bounded code-write paths.\",\n );\n return { state: \"needs_manual_review\", reasons };\n }\n\n if (hasUnmappedFunctionalChange(impactSet)) {\n reasons.push(\n \"Changed functional files need route ownership review before truth-doc suggestions are reliable.\",\n );\n return { state: \"needs_routing_review\", reasons };\n }\n\n if (diagnostics.some((diagnostic) => diagnostic.severity === \"error\")) {\n reasons.push(\n \"Existing diagnostics need manual review before using helper write suggestions.\",\n );\n return { state: \"needs_manual_review\", reasons };\n }\n\n return { state: \"ready\", reasons };\n};\n\nconst workflowCardFor = (\n workflow: TruthmarkWorkflowId,\n applicability: WorkflowApplicability,\n diagnostics: Diagnostic[],\n impactSet: ImpactSet | null,\n): WorkflowAdvisoryCard => {\n const helpers = helperCommandsFor(workflow);\n const diagnosticQuestions = diagnostics\n .filter((diagnostic) => diagnostic.severity === \"error\")\n .map((diagnostic) => diagnostic.message);\n\n return {\n affectedFiles: uniqueSorted(\n impactSet?.changedFiles.map((file) => file.path) ?? [],\n ),\n likelyRouteOwners: uniqueSorted(\n impactSet?.affectedRoutes.map((route) => route.sourcePath) ?? [],\n ),\n suggestedTruthDocs:\n applicability.state === \"needs_routing_review\"\n ? []\n : uniqueSorted(impactSet?.affectedTruthDocs ?? []),\n openQuestions: uniqueSorted([\n ...applicability.reasons,\n ...diagnosticQuestions,\n ]),\n skippedHelperStatus: helpers.map((helper) => ({\n helper: helper.id,\n status: \"skipped\" as const,\n reason:\n \"workflow status does not run optional helpers; inspect the checkout directly or run the helper manually when useful.\",\n })),\n };\n};\n\nconst contextDataFor = (\n workflow: TruthmarkWorkflowId,\n repoIndex: RepoIndex,\n config: Awaited<ReturnType<typeof loadConfig>>[\"config\"],\n impactSet: ImpactSet | null,\n diagnostics: Diagnostic[],\n): WorkflowActionContextData => {\n if (!config) {\n return {};\n }\n\n const routeFiles = routeFilesFor(repoIndex);\n const indexedTruthDocs = uniqueSorted(\n repoIndex.routeMap.routes.flatMap((route) => route.truthDocs),\n );\n const primaryTruthDocs = uniqueSorted(impactSet?.affectedTruthDocs ?? []);\n const candidateStaleTruthDocs =\n workflow === \"truthmark-sync\"\n ? candidateStaleTruthDocsFor(\n repoIndex,\n primaryTruthDocs,\n impactSet,\n diagnostics,\n )\n : [];\n const truthDocs =\n workflow === \"truthmark-sync\"\n ? uniqueSorted([...primaryTruthDocs, ...candidateStaleTruthDocs])\n : uniqueSorted(impactSet?.affectedTruthDocs ?? indexedTruthDocs);\n\n return {\n routeIndexPath: config.truthmark.paths.routesIndex,\n routeFiles,\n truthRoot: config.truthmark.paths.truthRoot,\n truthDocs,\n primaryTruthDocs:\n workflow === \"truthmark-sync\" ? primaryTruthDocs : truthDocs,\n candidateStaleTruthDocs,\n starterTruthDocs: workflow === \"truthmark-structure\" ? truthDocs : [],\n codeWritePaths:\n workflow === \"truthmark-realize\"\n ? uniqueSorted(\n impactSet?.affectedRoutes.flatMap((route) => route.codeSurface) ??\n [],\n )\n : [],\n portalEnabled: config.truthmark.generated.portal.enabled,\n portalOutputPath: config.truthmark.paths.portalOutput,\n routes: repoIndex.routeMap.routes,\n };\n};\n\nconst nextStepsFor = (\n workflow: TruthmarkWorkflowId,\n applicability: WorkflowApplicability,\n comparisonBase: string | null,\n): string[] => {\n if (applicability.state === \"needs_routing_review\") {\n return [\n \"Run Truth Structure or repair route ownership before writing truth docs.\",\n ];\n }\n\n if (\n (workflow === \"truthmark-sync\" || workflow === \"truthmark-realize\") &&\n applicability.state === \"needs_manual_review\" &&\n !comparisonBase\n ) {\n return [\n workflow === \"truthmark-sync\"\n ? \"Rerun with --base <ref> so the helper can suggest changed-file impact.\"\n : \"Rerun with --base <ref> so the helper can suggest bounded code-write paths.\",\n ];\n }\n\n return [];\n};\n\nexport const buildWorkflowState = async (\n cwd: string,\n options: BuildWorkflowStateOptions,\n): Promise<WorkflowState> => {\n const manifestEntry = TRUTHMARK_WORKFLOW_MANIFEST[options.workflow];\n if (!manifestEntry) {\n throw new Error(`Unknown Truthmark workflow: ${String(options.workflow)}`);\n }\n\n const repoIndex = await buildRepoIndex(cwd);\n const rootDir = repoIndex.repository.root;\n const loadResult = await loadConfig(rootDir);\n const comparisonBase = options.base\n ? options.base\n : options.workflow === \"truthmark-sync\"\n ? await selectComparisonBase(rootDir)\n : null;\n const impactSet = comparisonBase\n ? await buildImpactSet(rootDir, { base: comparisonBase })\n : null;\n const checkResult = await runCheck(\n cwd,\n comparisonBase ? { base: comparisonBase } : {},\n );\n const diagnostics = [\n ...loadResult.diagnostics,\n ...repoIndex.diagnostics,\n ...(impactSet?.diagnostics ?? []),\n ...checkResult.diagnostics,\n ];\n const applicability = applicabilityFor(\n options.workflow,\n diagnostics,\n impactSet,\n );\n const actionData =\n applicability.state === \"needs_manual_review\" ||\n applicability.state === \"needs_routing_review\"\n ? {}\n : contextDataFor(\n options.workflow,\n repoIndex,\n loadResult.config,\n impactSet,\n diagnostics,\n );\n\n return {\n schemaVersion: \"truthmark-workflow/v0\",\n workflow: options.workflow,\n applicability,\n actionContext: buildWorkflowActionContext(manifestEntry, actionData),\n workflowCard: workflowCardFor(\n options.workflow,\n applicability,\n diagnostics,\n impactSet,\n ),\n changedFiles: impactSet?.changedFiles ?? [],\n affectedRoutes: impactSet?.affectedRoutes ?? [],\n targetTruthDocs:\n applicability.state === \"needs_routing_review\"\n ? []\n : (impactSet?.affectedTruthDocs ?? []),\n diagnostics,\n checks: {\n reviewChecklist: [...manifestEntry.reviewQuestions],\n recommended: [...manifestEntry.positiveTriggers],\n helpers: helperCommandsFor(options.workflow),\n affectedTests: impactSet?.affectedTests ?? [],\n },\n nextSteps: nextStepsFor(options.workflow, applicability, comparisonBase),\n reportSections: [...manifestEntry.reportSections],\n };\n};\n","import type { TruthmarkWorkflowManifestEntry } from \"../agents/workflow-manifest.js\";\nimport type {\n WorkflowActionContext,\n WorkflowActionContextData,\n WorkflowActionMode,\n WorkflowHelperValidationCommand,\n} from \"./types.js\";\n\nconst uniqueSorted = (values: string[]): string[] =>\n [...new Set(values.filter((value) => value.length > 0))].sort();\n\nconst helperCommandsFor = (\n manifestEntry: TruthmarkWorkflowManifestEntry,\n): WorkflowHelperValidationCommand[] =>\n (manifestEntry.helpers ?? []).map((helper) => ({\n id: helper.id,\n runner: helper.runner,\n argv: [...helper.command.argv],\n optional: helper.optional,\n }));\n\nconst evidenceFor = (manifestEntry: TruthmarkWorkflowManifestEntry): string[] =>\n manifestEntry.reviewQuestions.filter((question) =>\n /evidence|ownership|containment/iu.test(question),\n );\n\nconst baseContext = (\n manifestEntry: TruthmarkWorkflowManifestEntry,\n mode: WorkflowActionMode,\n allowedWritePaths: string[],\n routeFiles: string[],\n primaryTruthDocs: string[],\n candidateStaleTruthDocs: string[],\n forbiddenWritePaths: string[],\n writeLeaseRequired: boolean,\n): WorkflowActionContext => ({\n mode,\n allowedWritePaths: uniqueSorted(allowedWritePaths),\n routeFiles: uniqueSorted(routeFiles),\n primaryTruthDocs: uniqueSorted(primaryTruthDocs),\n candidateStaleTruthDocs: uniqueSorted(candidateStaleTruthDocs),\n forbiddenWritePaths: uniqueSorted(forbiddenWritePaths),\n stopConditions: [\n ...manifestEntry.negativeTriggers,\n ...manifestEntry.forbiddenAdjacency,\n ],\n evidencePrompts: uniqueSorted([\n ...evidenceFor(manifestEntry),\n ...(candidateStaleTruthDocs.length > 0\n ? [\n \"Record checkout evidence and the reason before touching a candidate stale truth doc outside primaryTruthDocs.\",\n ]\n : []),\n ]),\n helperValidationCommands: helperCommandsFor(manifestEntry),\n writeLeaseRequired,\n});\n\nexport const buildWorkflowActionContext = (\n manifestEntry: TruthmarkWorkflowManifestEntry,\n data: WorkflowActionContextData = {},\n): WorkflowActionContext => {\n if (manifestEntry.id === \"truthmark-check\") {\n return baseContext(manifestEntry, \"read-only\", [], [], [], [], [], false);\n }\n\n if (\n manifestEntry.id === \"truthmark-sync\" ||\n manifestEntry.id === \"truthmark-document\"\n ) {\n const routeFiles = data.routeFiles ?? [];\n const primaryTruthDocs = data.primaryTruthDocs ?? data.truthDocs ?? [];\n const candidateStaleTruthDocs = data.candidateStaleTruthDocs ?? [];\n return baseContext(\n manifestEntry,\n \"truth-doc-write\",\n [\n ...(data.routeIndexPath ? [data.routeIndexPath] : []),\n ...routeFiles,\n ...primaryTruthDocs,\n ...candidateStaleTruthDocs,\n ],\n routeFiles,\n primaryTruthDocs,\n candidateStaleTruthDocs,\n [],\n true,\n );\n }\n\n if (manifestEntry.id === \"truthmark-structure\") {\n return baseContext(\n manifestEntry,\n \"route-write\",\n [\n ...(data.routeIndexPath ? [data.routeIndexPath] : []),\n ...(data.routeFiles ?? []),\n ...(data.starterTruthDocs ?? []),\n ],\n data.routeFiles ?? [],\n data.starterTruthDocs ?? [],\n [],\n [],\n true,\n );\n }\n\n if (manifestEntry.id === \"truthmark-realize\") {\n return baseContext(\n manifestEntry,\n \"code-write\",\n data.codeWritePaths ?? [],\n data.routeFiles ?? [],\n data.truthDocs ?? [],\n [],\n [\n ...(data.routeIndexPath ? [data.routeIndexPath] : []),\n ...(data.routeFiles ?? []),\n ...(data.truthRoot ? [`${data.truthRoot}/**/*.md`] : []),\n ...(data.truthDocs ?? []),\n ],\n false,\n );\n }\n\n return baseContext(\n manifestEntry,\n \"portal-write\",\n data.portalEnabled && data.portalOutputPath\n ? [`${data.portalOutputPath}/**`]\n : [],\n [],\n [],\n [],\n [],\n false,\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 {\n TRUTHMARK_WORKFLOW_IDS,\n type TruthmarkWorkflowId,\n} from \"../agents/workflow-manifest.js\";\nimport { buildWorkflowState } from \"../workflow-state/build.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 isTruthmarkWorkflowId = (value: unknown): value is TruthmarkWorkflowId => {\n return typeof value === \"string\" && TRUTHMARK_WORKFLOW_IDS.includes(value as TruthmarkWorkflowId);\n};\n\nconst invalidWorkflowResult = (\n command: \"workflow status\",\n workflow: string | undefined,\n): CommandResult => ({\n command,\n summary: workflow\n ? `Truthmark workflow requires a supported full workflow ID; received ${workflow}.`\n : \"Truthmark workflow requires --workflow.\",\n diagnostics: [\n {\n category: \"workflow-state\",\n severity: \"error\",\n message: workflow\n ? `Unknown Truthmark workflow: ${workflow}. Use a canonical full manifest ID such as truthmark-sync or truthmark-check.`\n : `truthmark ${command} requires --workflow <workflow>.`,\n },\n ],\n data: {\n request: workflow ? { workflow } : {},\n },\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 runWorkflowStatus = async (options: {\n workflow?: string;\n base?: string;\n}): Promise<CommandResult> => {\n if (!isTruthmarkWorkflowId(options.workflow)) {\n return invalidWorkflowResult(\"workflow status\", options.workflow);\n }\n\n const workflowState = await buildWorkflowState(process.cwd(), {\n workflow: options.workflow,\n ...(options.base ? { base: options.base } : {}),\n });\n\n return {\n command: \"workflow status\",\n summary: `Truthmark workflow status completed for ${options.workflow}.`,\n diagnostics: workflowState.diagnostics,\n data: {\n request: {\n workflow: options.workflow,\n ...(options.base ? { base: options.base } : {}),\n },\n workflowState,\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 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 && requiredHelpers.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 [\"Decision/rationale captured\", report.decisionRationaleCaptured],\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 const completedTargets = [\n ...report.truthDocsUpdated,\n ...(report.syncIntent?.targetTruthDocs ?? []),\n ];\n const bootstrapTargets = completedTargets.filter(isBootstrapRoutingDocPath);\n if (bootstrapTargets.length > 0) {\n errors.push(\n `bootstrap-routing.md is a provisional topology handoff, not a completed behavior-update target: ${bootstrapTargets.join(\", \")}`,\n );\n }\n\n if (report.syncIntent !== undefined) {\n checks.push(\"Sync Intent\");\n }\n\n validateHelperScriptEntries(report.helperScripts, [], errors, checks);\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 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, [], 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 isBootstrapRoutingDocPath = (value: string): boolean =>\n normalizePath(value).endsWith(\"/bootstrap-routing.md\");\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,KAAK,SAAS,WAAW,IAAI,EAAE;AAAA,EACvC;AAEA,SAAO,MAAM,SAAS,IAAI,KA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AAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,IAAM,cAAc,CAClB,SACA,UACA,cAAc,mBAAmB,OAA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MACE;AAAA,MACA,MAAM,0BAA0B,UAAU;AAAA,MAC1C;AAAA,IACF;AAAA,EACF,CAAC;AAED;AAAA,IACE,SACG,QAAQ,aAAa,EACrB,YAAY,yEAAyE,EACrF,SAAS,0BAA0B,6BAA6B,EAChE,SAAS,wBAAwB,qCAAqC;AAAA,EAC3E,EAAE;AAAA,IACA,OACE,mBACA,kBACA,YACG;AACH;AAAA,QACE;AAAA,QACA,MAAM,sBAAsB,mBAAmB,gBAAgB;AAAA,QAC/D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;;;AuD/MO,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","path","parse","path","CONFIG_PATH","fs","parse","fs","truthRoot","fs","fs","truthRoot","path","path","fs","path","fs","fs","fs","fs","fg","pathExists","fs","fg","fs","parse","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","path","micromatch","fs","path","execa","fg","micromatch","path","path","path","normalizePath","isTruthDocumentKind","execa","micromatch","fg","fs","fs","path","fg","execa","fs","path","execa","normalizePath","execa","pathExists","fs","path","normalizePath","execa","uniqueSorted","micromatch","path","fs","fg","fs","path","parse","fs","path","parse","pathExists","fs","fg","scorecard","execa","micromatch","uniqueSorted","helperCommandsFor","uniqueSorted","execa","path","micromatch","fs","parseYaml","normalizePath","parseYaml","runConfig","runInit","runCheck","fs","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/truth/evidence.ts","../src/agents/shared.ts","../src/templates/agents-block.ts","../src/managed-block.ts","../src/init/hierarchy.ts","../src/agents/workflow-manifest.ts","../src/agents/truth-check.ts","../src/agents/truth-document.ts","../src/agents/truthmark-portal.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/init/lifecycle.ts","../src/init/uninstall.ts","../src/checks/branch-scope.ts","../src/markdown/hash.ts","../src/checks/authority.ts","../src/checks/frontmatter.ts","../src/markdown/frontmatter.ts","../src/markdown/parse.ts","../src/checks/links.ts","../src/checks/areas.ts","../src/git/files.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/file-tree.ts","../src/truth/source-references.ts","../src/repo-index/package-metadata.ts","../src/repo-index/route-map.ts","../src/repo-index/build.ts","../src/impact/git-diff.ts","../src/git/changes.ts","../src/freshness/check.ts","../src/evidence/validate.ts","../src/evidence/parse.ts","../src/checks/scorecard.ts","../src/checks/check.ts","../src/workflow-state/build.ts","../src/workflow-state/action-context.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 runImpact,\n runIndex,\n runInit,\n runUninstall,\n runValidateDocumentReport,\n runValidateSyncReport,\n runValidateWriteLease,\n runWorkflowStatus,\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 WorkflowOptions = OutputOptions & {\n workflow?: string;\n base?: string;\n};\n\ntype UninstallOptions = OutputOptions & { dryRun?: boolean; apply?: boolean };\n\nconst markFailedWhenErrorDiagnosticsExist = (result: CommandResult): void => {\n if (\n result.diagnostics.some((diagnostic) => diagnostic.severity === \"error\")\n ) {\n process.exitCode = 1;\n }\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 markFailedWhenErrorDiagnosticsExist(result);\n};\n\nconst renderValidationHuman = (\n result: WorkflowHelperValidationResult,\n): string => {\n if (result.ok === true) {\n return [\n `${result.helper}: ok`,\n ...result.checks.map((check) => `- ${check}`),\n ].join(\"\\n\");\n }\n\n return [\n `${result.helper}: failed`,\n ...result.errors.map((error) => `- ${error}`),\n ].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(\n \"Git-native, branch-scoped truth workflow installer for local AI coding agents.\",\n )\n .showHelpAfterError();\n\n addJsonOption(\n program\n .command(\"config\")\n .description(\n \"Create or render the Truthmark repository config before initialization.\",\n )\n .option(\n \"--stdout\",\n \"Render default config in the JSON data payload without writing\",\n )\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(\n \"Initialize Truthmark workflow files in the current repository.\",\n ),\n ).action(async (options: OutputOptions) => {\n writeResult(await runInit(), options);\n });\n\n addJsonOption(\n program\n .command(\"uninstall\")\n .description(\n \"Remove recognized generated host surfaces while preserving truth, config, Portal output, Gemini, and user files.\",\n )\n .option(\"--dry-run\", \"Plan removals without changing files\")\n .option(\"--apply\", \"Apply the planned safe removals\"),\n ).action(async (options: UninstallOptions) => {\n if (Boolean(options.dryRun) === Boolean(options.apply)) {\n program.error(\n \"truthmark uninstall requires exactly one of --dry-run or --apply\",\n );\n return;\n }\n writeResult(\n await runUninstall(options.apply ? \"apply\" : \"dry-run\"),\n options,\n );\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\n .command(\"index\")\n .description(\n \"Inspect derived Truthmark workflow routing metadata for the current checkout.\",\n ),\n ).action(async (options: OutputOptions) => {\n writeResult(await runIndex(), options);\n });\n\n addJsonOption(\n program\n .command(\"impact\")\n .description(\n \"Map changed files to truth routes, docs, owners, and tests.\",\n )\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 const workflow = program\n .command(\"workflow\")\n .description(\"Inspect agent-facing Truthmark workflow state.\");\n\n addJsonOption(\n workflow\n .command(\"status\")\n .description(\n \"Return schema-versioned workflow state for a canonical workflow ID.\",\n )\n .option(\n \"--workflow <workflow>\",\n \"Canonical workflow ID, such as truthmark-sync\",\n )\n .option(\"--base <ref>\", \"Base Git ref for impact-backed workflow state\"),\n ).action(async (options: WorkflowOptions) => {\n writeResult(\n await runWorkflowStatus({\n workflow: options.workflow,\n base: options.base,\n }),\n options,\n );\n });\n\n const validate = program\n .command(\"validate\")\n .description(\n \"Run optional Truthmark workflow helper validators from the installed CLI.\",\n );\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(\n \"validate sync-report\",\n await runValidateSyncReport(reportFile),\n options,\n );\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(\n \"Validate a workflow write lease or worker report against changed files.\",\n )\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\ntype 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 pathSegments = (absolutePath: string): string[] => {\n return absolutePath.split(path.sep);\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 isSafeExactFile = async (\n rootDir: string,\n relativePath: string,\n allowMissing: boolean,\n): Promise<boolean> => {\n try {\n const absolutePath = resolveRepoPath(rootDir, relativePath);\n await assertRepoContainment(rootDir, absolutePath);\n const relative = path.relative(rootDir, absolutePath);\n const segments = pathSegments(relative);\n\n if (segments.length === 0 || segments.every((segment) => segment.length === 0)) {\n return false;\n }\n\n let current = rootDir;\n for (let index = 0; index < segments.length; index += 1) {\n const segment = segments[index];\n current = path.join(current, segment);\n\n try {\n const stat = await fs.lstat(current);\n\n if (stat.isSymbolicLink()) {\n return false;\n }\n\n const isFinal = index === segments.length - 1;\n if (isFinal) {\n return stat.isFile() && stat.nlink === 1;\n }\n\n if (!stat.isDirectory()) {\n return false;\n }\n } catch (error: unknown) {\n if (!isNodeErrorWithCode(error, \"ENOENT\")) {\n throw error;\n }\n\n return allowMissing;\n }\n }\n\n return false;\n } catch {\n return false;\n }\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 {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} 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 = resolveEngineeringTruthRoot;\n\nconst renderLaneRootReadmeSummary = (\n lane: \"product\" | \"engineering\",\n): string => {\n if (lane === \"product\") {\n return [\n \"Product truth owns capability promises, boundaries, decisions, and acceptance criteria.\",\n \"Product lane docs state what must be true, why it matters, and what success means.\",\n ].join(\" \");\n }\n\n return [\n \"Engineering truth owns current realization, contracts, architecture, workflows, operations, and tests.\",\n \"Engineering lane docs describe how the repository currently implements and operates the behavior.\",\n ].join(\" \");\n};\n\nconst renderLaneRootLeafDocGuidance = (\n lane: \"product\" | \"engineering\",\n): string => {\n if (lane === \"product\") {\n return \"README.md files are indexes, not Truth Sync targets. Keep product truth in bounded capability docs.\";\n }\n\n return \"README.md files are indexes, not Truth Sync targets. Keep engineering truth in bounded behavior, contract, architecture, workflow, operations, and test docs.\";\n};\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:\n inferTruthDocumentKindFromPath(document.path) ??\n \"engineering-behavior\",\n }))\n : [\n {\n path: `${createDefaultConfig().truthmark.paths.engineeringTruthRoot}/**/*.md`,\n kind: \"engineering-behavior\",\n lane: \"engineering\",\n },\n ];\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.truthmark.routes.defaultArea;\n const childPath = `${config.truthmark.paths.routeAreasRoot}/${defaultArea}.md`;\n const title = titleCase(defaultArea);\n const sourceOfTruth = resolveRelativePath(\n config.truthmark.paths.routesIndex,\n \".truthmark/config.yml\",\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: route-index\",\n `last_reviewed: ${currentDate()}`,\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 \"## Source References\",\n \"\",\n `- ${sourceOfTruth}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderChildAreaTemplate = (config: TruthmarkConfig): string => {\n const defaultArea = config.truthmark.routes.defaultArea;\n const title = titleCase(defaultArea);\n const truthDocsRoot = truthRoot(config);\n const bootstrapTruthDoc = `${truthDocsRoot}/${defaultArea}/bootstrap-routing.md`;\n const templatePath = `${config.truthmark.paths.routeAreasRoot}/${defaultArea}.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n \".truthmark/config.yml\",\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: area-route\",\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n `# ${title} Areas`,\n \"\",\n `## ${title}`,\n \"\",\n \"Truth documents:\",\n \"```yaml\",\n \"truth_documents:\",\n ` - path: ${bootstrapTruthDoc}`,\n \" kind: engineering-workflow\",\n \" lane: engineering\",\n \"```\",\n \"\",\n \"This is a provisional bootstrap route. It exists only to make fresh repositories routeable until real product, service, domain, or ownership areas are created.\",\n \"\",\n \"Code surface:\",\n \"- src/**\",\n \"\",\n \"Update truth when:\",\n \"- this provisional bootstrap route is the only match for a real code surface\",\n \"- route ownership is still broad, mixed, or ambiguous\",\n \"- Run Truth Structure before normal Truth Sync so the touched code gets a bounded owner\",\n \"\",\n \"## Source References\",\n \"\",\n `- ${sourceOfTruth}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderBootstrapRoutingDocTemplate = (\n config: TruthmarkConfig,\n): string => {\n const defaultArea = config.truthmark.routes.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/bootstrap-routing.md`;\n const routePath = `${config.truthmark.paths.routeAreasRoot}/${defaultArea}.md`;\n const routeSource = resolveRelativePath(templatePath, routePath);\n const configSource = resolveRelativePath(\n templatePath,\n \".truthmark/config.yml\",\n );\n const today = currentDate();\n\n return [\n \"---\",\n \"status: active\",\n \"truth_kind: engineering-workflow\",\n `last_reviewed: ${today}`,\n \"---\",\n \"\",\n `# ${title} Bootstrap Routing`,\n \"\",\n \"## Purpose\",\n \"\",\n `This doc records the provisional broad route for ${defaultArea}.`,\n \"This doc is a bootstrap handoff, not a behavior truth dumping ground.\",\n \"It is not a substitute for bounded product and engineering truth docs.\",\n \"\",\n \"## Scope\",\n \"\",\n \"This doc owns only the initial routing workflow for a fresh Truthmark repository whose default route still maps a broad code surface such as `src/**`.\",\n \"It does not own implementation behavior under that code surface.\",\n \"\",\n \"## Current Implementation Behavior\",\n \"\",\n \"The scaffold creates this provisional bootstrap handoff only when a default broad route needs a canonical owner. Agents use it as a signal to run Truth Structure and create bounded routes before normal Truth Sync, not as a place to accumulate implementation claims.\",\n \"\",\n \"## Product Truth Links\",\n \"\",\n \"- None. This is an engineering bootstrap handoff for routing setup, not a product promise.\",\n \"\",\n \"## Triggers\",\n \"\",\n \"- A real code change maps only to this provisional broad route.\",\n \"- Truth Sync cannot identify a specific behavior-owned route and bounded truth owner.\",\n \"- A maintainer or agent is onboarding the first real product, service, domain, package, or ownership area.\",\n \"\",\n \"## Inputs\",\n \"\",\n \"- Current route files under the configured Truthmark route root.\",\n \"- The touched code, tests, configuration, and existing docs needed to infer the smallest real owner.\",\n \"- Repository instruction files that exist in the checkout.\",\n \"\",\n \"## Execution Model\",\n \"\",\n \"Run Truth Structure before normal Truth Sync when real code changes touch only this broad route. Truth Structure should create or repair bounded areas first; Truth Sync should then update the bounded owner docs.\",\n \"\",\n \"## Steps\",\n \"\",\n \"1. Treat this route as provisional and insufficient for normal behavior maintenance.\",\n \"2. Inspect the touched code/test surface and infer the narrowest durable owner.\",\n \"3. Create or repair route entries and truth docs for that owner.\",\n \"4. Leave this bootstrap doc small; do not append behavior details here.\",\n \"5. Resume Truth Sync only after the touched code resolves to a bounded owner.\",\n \"\",\n \"## State, Retry, And Failure Behavior\",\n \"\",\n \"If ownership cannot be inferred safely, stop and report manual-review files instead of widening this route or adding generic behavior prose.\",\n \"\",\n \"## Outputs\",\n \"\",\n \"- Bounded route areas and lane-appropriate truth docs for the touched surface.\",\n \"- A compact manual handoff report when ownership remains ambiguous.\",\n \"\",\n \"## Engineering Decisions\",\n \"\",\n `- Decision (${today}): Default broad routing is provisional bootstrap state. Agents should create bounded areas before normal Truth Sync rather than extending a catch-all overview doc.`,\n \"\",\n \"## Rationale\",\n \"\",\n \"Scoped ownership keeps agent context close to affected files and prevents broad default docs from absorbing unrelated behavior. This preserves agent-native truth maintenance without adding a token-heavy discovery layer.\",\n \"\",\n \"## Non-Goals\",\n \"\",\n \"- This doc is not a repository behavior overview.\",\n \"- This doc is not a product capability or engineering behavior owner.\",\n \"- This doc is not a permanent home for claims about files under `src/**`.\",\n \"\",\n \"## Maintenance Notes\",\n \"\",\n \"Keep this doc short. When a repository has real bounded routes, prefer updating those routes and their truth docs instead of expanding this bootstrap handoff.\",\n \"\",\n \"## Source References\",\n \"\",\n `- ${routeSource}`,\n `- ${configSource}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderTruthRootReadmeTemplate = (\n config: TruthmarkConfig = createDefaultConfig(),\n lane: \"product\" | \"engineering\" = \"engineering\",\n): string => {\n const templatePath = `${lane === \"product\" ? resolveProductTruthRoot(config) : resolveEngineeringTruthRoot(config)}/README.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n config.truthmark.paths.routesIndex,\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: index\",\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n \"# Truth Docs\",\n \"\",\n \"This directory is an index for current truth docs organized by the configured Truthmark hierarchy.\",\n \"\",\n renderLaneRootReadmeSummary(lane),\n \"\",\n renderLaneRootLeafDocGuidance(lane),\n \"\",\n \"## Source References\",\n \"\",\n `- ${sourceOfTruth}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const renderTruthDomainReadmeTemplate = (\n config: TruthmarkConfig,\n): string => {\n const defaultArea = config.truthmark.routes.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/README.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n `${config.truthmark.paths.routeAreasRoot}/${defaultArea}.md`,\n );\n\n return [\n \"---\",\n \"status: active\",\n \"doc_type: index\",\n `last_reviewed: ${currentDate()}`,\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 \"- [Bootstrap routing](bootstrap-routing.md)\",\n \"\",\n \"## Source References\",\n \"\",\n `- ${sourceOfTruth}`,\n \"\",\n ].join(\"\\n\");\n};\n\nexport const BEHAVIOR_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-behavior.md\";\nexport const CONTRACT_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-contract.md\";\nexport const ARCHITECTURE_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-architecture.md\";\nexport const WORKFLOW_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-workflow.md\";\nexport const OPERATIONS_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-operations.md\";\nexport const TEST_BEHAVIOR_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/engineering-test-behavior.md\";\nexport const PRODUCT_CAPABILITY_DOC_TEMPLATE_PATH =\n \"docs/truthmark/templates/product-capability.md\";\n\ntype TemplateSectionSpec = {\n heading: string;\n placeholder: string;\n guidance: string[];\n};\n\ntype ParsedTemplateSection = {\n heading: string;\n block: string;\n};\n\nconst renderTemplateSection = (section: TemplateSectionSpec): string[] => {\n return [\n section.heading,\n \"\",\n \"<!--\",\n ...section.guidance,\n \"-->\",\n \"\",\n `{{${section.placeholder}}}`,\n \"\",\n ];\n};\n\nconst titleToPlaceholder = (title: string): string => {\n return title\n .replace(/^#+\\s+/u, \"\")\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n};\n\nconst findTemplateSectionHeadings = (\n template: string,\n): Array<{ heading: string; index: number }> => {\n const matches: Array<{ heading: string; index: number }> = [];\n let fencedCodeMarker: \"`\" | \"~\" | null = null;\n let fencedCodeLength = 0;\n\n for (const lineMatch of template.matchAll(/^.*(?:\\r?\\n|$)/gm)) {\n const rawLine = lineMatch[0];\n if (rawLine.length === 0) {\n continue;\n }\n\n const line = rawLine.replace(/\\r?\\n$/u, \"\");\n const fenceMatch = /^(?: {0,3})(`{3,}|~{3,})/u.exec(line);\n\n if (fenceMatch) {\n const marker = fenceMatch[1]?.[0] as \"`\" | \"~\";\n const length = fenceMatch[1]?.length ?? 0;\n\n if (fencedCodeMarker === null) {\n fencedCodeMarker = marker;\n fencedCodeLength = length;\n } else if (marker === fencedCodeMarker && length >= fencedCodeLength) {\n fencedCodeMarker = null;\n fencedCodeLength = 0;\n }\n\n continue;\n }\n\n if (fencedCodeMarker === null && /^## .+$/u.test(line)) {\n matches.push({ heading: line.trim(), index: lineMatch.index });\n }\n }\n\n return matches;\n};\n\nconst parseTemplateSections = (\n template: string,\n): { preamble: string; sections: ParsedTemplateSection[] } => {\n const matches = findTemplateSectionHeadings(template);\n\n if (matches.length === 0) {\n return { preamble: template.trimEnd(), sections: [] };\n }\n\n const sections = matches.map((match, index) => {\n const start = match.index;\n const next = matches[index + 1];\n const end = next?.index ?? template.length;\n\n return {\n heading: match.heading,\n block: template.slice(start, end).trimEnd(),\n };\n });\n\n return {\n preamble: template.slice(0, matches[0]?.index ?? 0).trimEnd(),\n sections,\n };\n};\n\nconst LEGACY_MANAGED_TEMPLATE_HEADINGS = new Map<string, string>([\n [\"## Current Behavior\", \"## Current Implementation Behavior\"],\n [\"## Source Evidence\", \"## Source References\"],\n]);\n\nconst resolveManagedTemplateHeading = (heading: string): string => {\n return LEGACY_MANAGED_TEMPLATE_HEADINGS.get(heading) ?? heading;\n};\n\nconst stripManagedFrontmatterFields = (preamble: string): string => {\n if (!preamble.startsWith(\"---\\n\")) {\n return preamble;\n }\n\n const lines = preamble.split(\"\\n\");\n const closingIndex = lines.findIndex(\n (line, index) => index > 0 && line.trim() === \"---\",\n );\n if (closingIndex < 0) {\n return preamble;\n }\n\n const fieldsToRemove = new Set([\"source_of_truth\", \"doc_type\", \"truth_lane\"]);\n const keptFrontmatterLines: string[] = [];\n let skippingManagedField = false;\n\n for (const line of lines.slice(1, closingIndex)) {\n const keyMatch = /^([A-Za-z0-9_-]+):(\\s|$)/u.exec(line);\n if (keyMatch) {\n skippingManagedField = fieldsToRemove.has(keyMatch[1] ?? \"\");\n }\n\n if (!skippingManagedField) {\n keptFrontmatterLines.push(line);\n }\n }\n\n return [\n \"---\",\n ...keptFrontmatterLines,\n \"---\",\n ...lines.slice(closingIndex + 1),\n ]\n .join(\"\\n\")\n .trimEnd();\n};\n\nexport const mergeTruthDocTemplate = (\n existingTemplate: string,\n defaultTemplate: string,\n): string => {\n if (existingTemplate.trim().length === 0) {\n return defaultTemplate;\n }\n\n const defaultParsed = parseTemplateSections(defaultTemplate);\n const existingParsed = parseTemplateSections(existingTemplate);\n const defaultHeadings = new Set(\n defaultParsed.sections.map((section) => section.heading),\n );\n const customBeforeDefault = new Map<string, ParsedTemplateSection[]>();\n const trailingCustomSections: ParsedTemplateSection[] = [];\n\n existingParsed.sections.forEach((section, index) => {\n if (defaultHeadings.has(resolveManagedTemplateHeading(section.heading))) {\n return;\n }\n\n const nextDefaultSection = existingParsed.sections\n .slice(index + 1)\n .find((candidate) =>\n defaultHeadings.has(resolveManagedTemplateHeading(candidate.heading)),\n );\n\n if (nextDefaultSection) {\n const nextDefaultHeading = resolveManagedTemplateHeading(\n nextDefaultSection.heading,\n );\n const bucket = customBeforeDefault.get(nextDefaultHeading) ?? [];\n bucket.push(section);\n customBeforeDefault.set(nextDefaultHeading, bucket);\n return;\n }\n\n trailingCustomSections.push(section);\n });\n\n const mergedSections = defaultParsed.sections.flatMap((section) => [\n ...(customBeforeDefault.get(section.heading) ?? []),\n section,\n ]);\n\n return [\n stripManagedFrontmatterFields(existingParsed.preamble),\n ...mergedSections.map((section) => section.block),\n ...trailingCustomSections.map((section) => section.block),\n \"\",\n ]\n .filter((block) => block.length > 0)\n .join(\"\\n\\n\");\n};\n\nexport const renderBehaviorDocTemplateFile = (): string => {\n return [\n \"---\",\n \"status: active\",\n \"truth_kind: engineering-behavior\",\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n \"# {{title}}\",\n \"\",\n \"## Purpose\",\n \"\",\n \"<!--\",\n \"State the user/system outcome this behavior protects and why it exists.\",\n \"Include the problem boundary and durable value; exclude roadmap, implementation plan, and historical narrative.\",\n \"List the code, config, docs, or tests that support the claim in Source References rather than prose-only assertion.\",\n \"-->\",\n \"\",\n \"{{purpose}}\",\n \"\",\n \"## Scope\",\n \"\",\n \"<!--\",\n \"Define the one coherent behavior surface this document owns.\",\n \"Include in-scope actors, entrypoints, state/data owned by this doc, and explicit handoffs to neighboring truth docs.\",\n \"Split into another leaf doc when content introduces a distinct outcome, state machine, rule family, external contract, or route owner.\",\n \"Keep README.md files as indexes only.\",\n \"-->\",\n \"\",\n \"{{scope}}\",\n \"\",\n \"This doc was created from the editable engineering-behavior template at {{template_path}}.\",\n \"\",\n \"## Current Implementation Behavior\",\n \"\",\n \"<!--\",\n \"Describe only current implemented behavior in present tense.\",\n \"Cover observable behavior, important defaults, and user/system-visible effects; exclude desired future behavior and speculative design.\",\n \"Every non-obvious claim should be checkable from Source References.\",\n \"-->\",\n \"\",\n \"{{current_implementation_behavior}}\",\n \"\",\n \"## Core Rules\",\n \"\",\n \"<!--\",\n \"Capture stable business rules, invariants, precedence rules, validation rules, and must-never constraints.\",\n \"Separate rules from incidental implementation details; cite current implementation or tests for rule enforcement.\",\n \"-->\",\n \"\",\n \"{{core_rules}}\",\n \"\",\n \"## Behavior Scenarios\",\n \"\",\n \"<!--\",\n \"Use compact scenario blocks only where they clarify normal, fallback, or compatibility-critical behavior.\",\n \"Write scenarios as current truth, not desired requirements: `#### Scenario: <implemented case>` followed by `- **GIVEN** ...`, `- **WHEN** ...`, `- **THEN** ...`, and optional `- **AND** ...` bullets.\",\n \"Keep each bullet evidence-backed and observable; do not force a scenario for every rule.\",\n \"-->\",\n \"\",\n \"{{behavior_scenarios}}\",\n \"\",\n \"## Flows And States\",\n \"\",\n \"<!--\",\n \"Document state transitions, lifecycle stages, retries, fallbacks, route switches, and important error paths.\",\n \"State 'None beyond current behavior.' when this behavior has no distinct flow or state model.\",\n \"-->\",\n \"\",\n \"{{flows_and_states}}\",\n \"\",\n \"## Contracts\",\n \"\",\n \"<!--\",\n \"Capture user-visible or integration contracts: CLI/API shape, inputs, outputs, diagnostics, files, events, permissions, or links to canonical contract docs.\",\n \"Avoid duplicating a separate canonical contract doc; link to it when contract ownership lives elsewhere.\",\n \"-->\",\n \"\",\n \"{{contracts}}\",\n \"\",\n \"## Product Truth Links\",\n \"\",\n \"<!--\",\n \"List product truth docs this engineering doc realizes; author canonical realizes links in route YAML, not doc frontmatter.\",\n \"Use 'None.' when this is purely internal engineering behavior.\",\n \"-->\",\n \"\",\n \"{{product_truth_links}}\",\n \"\",\n \"## Engineering Decisions\",\n \"\",\n \"<!--\",\n \"Keep active decisions only, dated inline when added or changed.\",\n \"Explain decisions that shape behavior, boundaries, rejected alternatives, or migration constraints; replace stale decisions instead of appending historical logs.\",\n \"-->\",\n \"\",\n \"{{engineering_decisions}}\",\n \"\",\n \"## Rationale\",\n \"\",\n \"<!--\",\n \"Explain why the current behavior and active decisions are this way, including tradeoffs and constraints.\",\n \"Tie rationale to evidence-backed behavior; do not use this as a changelog.\",\n \"-->\",\n \"\",\n \"{{rationale}}\",\n \"\",\n \"## Non-Goals\",\n \"\",\n \"<!--\",\n \"Name adjacent behavior this doc intentionally does not own, especially tempting future expansions or neighboring route owners.\",\n \"Use this section to prevent scope creep and duplicate truth ownership.\",\n \"-->\",\n \"\",\n \"{{non_goals}}\",\n \"\",\n \"## Maintenance Notes\",\n \"\",\n \"<!--\",\n \"List related tests, routing cautions, migration notes, evidence drift risks, and review triggers for future maintainers or agents.\",\n \"Keep this operational and current-state focused, not historical.\",\n \"-->\",\n \"\",\n \"{{maintenance_notes}}\",\n \"\",\n \"## Source References\",\n \"\",\n \"<!--\",\n \"List source files, tests, configs, generated templates, route files, or product instructions that support current claims.\",\n \"-->\",\n \"\",\n \"{{source_references}}\",\n \"\",\n ].join(\"\\n\");\n};\n\nconst sectionSpec = (\n heading: string,\n guidance: string[],\n placeholder = titleToPlaceholder(heading),\n): TemplateSectionSpec => ({ heading, guidance, placeholder });\n\nconst PURPOSE_SECTION = sectionSpec(\"## Purpose\", [\n \"State the software-engineering outcome this document protects and why the documented surface exists.\",\n \"Include durable value, impacted users/systems, and the problem boundary; exclude roadmap, implementation plans, and historical narrative.\",\n \"Keep claims traceable to Source References rather than prose-only assertion.\",\n]);\n\nconst SCOPE_SECTION = sectionSpec(\"## Scope\", [\n \"Define the one coherent surface this document owns, including actors, entrypoints, owned state/data, and handoffs to neighboring truth docs.\",\n \"Call out important out-of-scope boundaries here or in Non-Goals; split the doc when it mixes distinct outcomes, lifecycles, contracts, or owners.\",\n]);\n\nconst PRODUCT_DECISIONS_SECTION = sectionSpec(\n \"## Product Decisions\",\n [\n \"Keep active decisions only, dated inline when added or changed.\",\n \"Capture decisions that shape behavior, interfaces, boundaries, compatibility, risk acceptance, or migration constraints.\",\n \"Replace stale decisions instead of appending historical logs.\",\n ],\n \"decision\",\n);\n\nconst ENGINEERING_DECISIONS_SECTION = sectionSpec(\n \"## Engineering Decisions\",\n [\n \"Keep active engineering, architecture, contract, workflow, or operational decisions only, dated inline when added or changed.\",\n \"Do not restate product promises, product rationale, or business decisions here; link product truth instead.\",\n \"Replace stale decisions instead of appending historical logs.\",\n ],\n \"engineering_decisions\",\n);\n\nconst RATIONALE_SECTION = sectionSpec(\"## Rationale\", [\n \"Explain why the current behavior, structure, or contract is this way, including tradeoffs and constraints.\",\n \"Tie rationale to evidence-backed facts and active decisions; do not use this as a changelog.\",\n]);\n\nconst NON_GOALS_SECTION = sectionSpec(\"## Non-Goals\", [\n \"Name adjacent behavior, responsibilities, interfaces, or future expansions this doc intentionally does not own.\",\n \"Use this section to prevent scope creep and duplicate truth ownership.\",\n]);\n\nconst MAINTENANCE_NOTES_SECTION = sectionSpec(\"## Maintenance Notes\", [\n \"List related tests, routing cautions, migration notes, compatibility risks, evidence drift risks, and review triggers for future maintainers or agents.\",\n \"Keep this operational and current-state focused, not historical.\",\n]);\n\nconst SOURCE_REFERENCES_SECTION = sectionSpec(\n \"## Source References\",\n [\n \"List source files, tests, configs, generated templates, route files, or product instructions that support current claims.\",\n ],\n \"source_references\",\n);\n\nconst renderTypedTruthDocTemplate = (\n truthKind: string,\n title: string,\n sections: TemplateSectionSpec[],\n): string => {\n return [\n \"---\",\n \"status: active\",\n `truth_kind: ${truthKind}`,\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n `# ${title}`,\n \"\",\n ...renderTemplateSection(PURPOSE_SECTION),\n ...renderTemplateSection(SCOPE_SECTION),\n ...sections.flatMap(renderTemplateSection),\n ...renderTemplateSection(ENGINEERING_DECISIONS_SECTION),\n ...renderTemplateSection(RATIONALE_SECTION),\n ...renderTemplateSection(NON_GOALS_SECTION),\n ...renderTemplateSection(MAINTENANCE_NOTES_SECTION),\n ...renderTemplateSection(SOURCE_REFERENCES_SECTION),\n ].join(\"\\n\");\n};\n\nconst CORE_LANE_INVARIANT =\n \"Do not make product docs a summary of engineering docs. Do not make engineering docs a detailed version of product docs. Product truth says what must be true and why. Engineering truth says how the repository currently realizes it.\";\n\nconst renderProductTruthDocTemplate = (\n truthKind: \"product-capability\",\n title: string,\n sections: TemplateSectionSpec[],\n includeNonGoals: boolean,\n): string => {\n return [\n \"---\",\n \"status: active\",\n `truth_kind: ${truthKind}`,\n `last_reviewed: ${currentDate()}`,\n \"---\",\n \"\",\n `# ${title}`,\n \"\",\n \"<!--\",\n CORE_LANE_INVARIANT,\n \"Product docs may cite code directly when code proves current product behavior, but keep implementation flow, renderer internals, CLI envelopes, and generated file inventories in engineering truth.\",\n \"-->\",\n \"\",\n ...sections.flatMap(renderTemplateSection),\n ...renderTemplateSection(PRODUCT_DECISIONS_SECTION),\n ...renderTemplateSection(\n sectionSpec(\n \"## Engineering Realization Links\",\n [\n \"List engineering truth that realizes this product truth; author canonical realized_by links in route YAML, not doc frontmatter.\",\n \"Do not summarize those engineering docs.\",\n ],\n \"engineering_realization_links\",\n ),\n ),\n ...(includeNonGoals ? renderTemplateSection(NON_GOALS_SECTION) : []),\n ...renderTemplateSection(SOURCE_REFERENCES_SECTION),\n ].join(\"\\n\");\n};\n\nexport const renderProductCapabilityDocTemplateFile = (): string => {\n return renderProductTruthDocTemplate(\n \"product-capability\",\n \"{{title}}\",\n [\n sectionSpec(\"## Capability Promise\", [\n \"State the single user-visible capability and what must be true for users or stakeholders.\",\n \"Do not describe implementation mechanics here.\",\n ]),\n sectionSpec(\"## Users And Value\", [\n \"Describe who benefits from the capability and the durable value it protects.\",\n \"Tie claims to repository evidence, explicit user instruction, or current behavior.\",\n ]),\n sectionSpec(\"## Capability Scope\", [\n \"Define what this capability includes and excludes, including product boundary constraints and adjacent systems.\",\n \"Capture important scope limits, ownership boundaries, and non-goal pointers here; keep technical contracts in engineering truth.\",\n ]),\n sectionSpec(\"## Current Product Behavior\", [\n \"Describe current implemented user-visible behavior in present tense.\",\n \"Code files may appear in Source References when they directly prove current behavior.\",\n ]),\n sectionSpec(\"## Acceptance Criteria\", [\n \"List observable criteria that show the capability promise is currently satisfied.\",\n \"Include criteria that review whether the capability stays within its stated scope and boundary.\",\n \"Use criteria that can be reviewed from repository evidence or explicit product instruction.\",\n ]),\n ],\n true,\n );\n};\n\nexport const renderContractDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-contract\", \"{{title}}\", [\n sectionSpec(\"## Contract Surface\", [\n \"Identify the owned API, CLI, file format, event, protocol, permission boundary, or integration surface.\",\n \"State consumers/producers, stability level, and the source files/tests that define the contract.\",\n ]),\n sectionSpec(\"## Inputs\", [\n \"Document accepted parameters, payloads, files, environment/config keys, permissions, and validation rules.\",\n \"Include required/optional status, defaults, constraints, and normalization behavior.\",\n ]),\n sectionSpec(\"## Outputs\", [\n \"Document returned values, emitted files/events, state changes, side effects, and success diagnostics.\",\n \"Make externally observable behavior explicit enough for compatibility review.\",\n ]),\n sectionSpec(\"## Errors And Diagnostics\", [\n \"List error classes, exit/status codes, user-facing diagnostics, retries, and recoverability expectations.\",\n \"Distinguish validation errors, dependency failures, authorization failures, and internal faults when applicable.\",\n ]),\n sectionSpec(\"## Compatibility Rules\", [\n \"State backward/forward compatibility guarantees, tolerated inputs, deprecation rules, and breaking-change triggers.\",\n \"Include compatibility tests or review questions that protect the contract.\",\n ]),\n sectionSpec(\"## Versioning And Migration\", [\n \"Document version negotiation, schema/API version fields, rollout requirements, migration steps, and rollback expectations.\",\n \"State 'Not versioned' only when the implementation truly has no versioning or migration surface.\",\n ]),\n ]);\n};\n\nexport const renderArchitectureDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-architecture\", \"{{title}}\", [\n sectionSpec(\"## System Role\", [\n \"Describe the current architectural role of this subsystem/component in the larger system.\",\n \"State the primary responsibilities, consumers, providers, and why this boundary exists now.\",\n ]),\n sectionSpec(\"## Boundaries\", [\n \"Define owned code/config/data, external dependencies, trust boundaries, and interfaces crossed by this architecture.\",\n \"Name what is deliberately outside the boundary and link neighboring architecture or contract docs when they own it.\",\n ]),\n sectionSpec(\"## Components\", [\n \"List the major runtime/build-time components, modules, services, jobs, or generated artifacts and their responsibilities.\",\n \"Keep the component list current and evidence-backed; avoid speculative target architecture.\",\n ]),\n sectionSpec(\"## Data And Control Flow\", [\n \"Describe important data movement, command/control paths, synchronization points, state ownership, and failure paths.\",\n \"Call out persistence, queues, caches, external calls, and security-sensitive transitions where relevant.\",\n ]),\n sectionSpec(\"## Ownership\", [\n \"Document team/module ownership, review responsibility, operational responsibility, and escalation paths if known.\",\n \"If ownership is inferred from codeowners, config, or repository structure, cite that evidence.\",\n ]),\n sectionSpec(\"## Cross-Cutting Constraints\", [\n \"Record active constraints such as security, privacy, reliability, performance, portability, maintainability, compliance, and cost.\",\n \"Tie constraints to source evidence, tests, standards, or operational requirements where available.\",\n ]),\n ]);\n};\n\nexport const renderWorkflowDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-workflow\", \"{{title}}\", [\n sectionSpec(\"## Triggers\", [\n \"List events, commands, schedules, user actions, webhooks, or dependency signals that start this workflow.\",\n \"Include preconditions, authorization requirements, debounce/coalescing behavior, and disabled states when applicable.\",\n ]),\n sectionSpec(\"## Inputs\", [\n \"Document data, files, config, context, credentials, and environmental assumptions consumed by the workflow.\",\n \"Include validation, defaults, and normalization that happen before execution.\",\n ]),\n sectionSpec(\"## Execution Model\", [\n \"Describe synchronous/asynchronous execution, concurrency, locking, leases, batching, ordering, and idempotency behavior.\",\n \"State whether the workflow waits for user action, runs in the background, is distributed, or is delegated to another system.\",\n ]),\n sectionSpec(\"## Steps\", [\n \"Capture the current ordered steps or phases at a level useful for maintenance and review.\",\n \"Reference implementation entrypoints instead of duplicating line-by-line code behavior.\",\n ]),\n sectionSpec(\"## State, Retry, And Failure Behavior\", [\n \"Document state transitions, retries, timeouts, compensation, fallback, partial-success, and terminal-failure behavior.\",\n \"Make externally visible failure semantics and recovery responsibilities clear.\",\n ]),\n sectionSpec(\"## Outputs\", [\n \"List artifacts, state changes, notifications, logs, metrics, diagnostics, and downstream triggers produced by the workflow.\",\n \"Include success criteria and handoff points to other truth docs or systems.\",\n ]),\n ]);\n};\n\nexport const renderOperationsDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-operations\", \"{{title}}\", [\n sectionSpec(\"## Operational Surface\", [\n \"Describe what operators, maintainers, or automated systems can observe or control for this surface.\",\n \"Include commands, dashboards, alerts, runbooks, jobs, or operational APIs that define current operations.\",\n ]),\n sectionSpec(\"## Runtime Topology\", [\n \"Document services, processes, containers, hosts, regions, dependencies, queues, stores, and network boundaries involved at runtime.\",\n \"State single-node/local behavior explicitly when there is no distributed topology.\",\n ]),\n sectionSpec(\"## Configuration\", [\n \"List operational config, environment variables, feature flags, secrets references, defaults, and reload/restart requirements.\",\n \"Do not include secret values; describe storage and rotation expectations instead.\",\n ]),\n sectionSpec(\"## Permissions\", [\n \"Document required identities, roles, scopes, filesystem/network permissions, and least-privilege boundaries.\",\n \"Include user-facing authorization behavior and operator access requirements when relevant.\",\n ]),\n sectionSpec(\"## Deployment And Rollback\", [\n \"Describe deployment mechanism, migration ordering, compatibility windows, rollback path, and known irreversible operations.\",\n \"Call out manual review points, smoke checks, and post-deploy verification responsibilities.\",\n ]),\n sectionSpec(\"## Availability And Observability\", [\n \"Capture availability expectations, health checks, metrics, logs, traces, alerts, SLO/error-budget signals, and known blind spots.\",\n \"Include what maintainers should inspect first during incidents or degraded behavior.\",\n ]),\n ]);\n};\n\nexport const renderTestBehaviorDocTemplateFile = (): string => {\n return renderTypedTruthDocTemplate(\"engineering-test-behavior\", \"{{title}}\", [\n sectionSpec(\"## Test Surface\", [\n \"Define the behavior, contract, architecture, or workflow surface these tests verify.\",\n \"Link the canonical truth docs and code paths the tests are meant to protect.\",\n ]),\n sectionSpec(\"## Fixtures And Data Model\", [\n \"Document fixtures, factories, seeds, mocks/fakes, test repositories, external-service substitutes, and data lifecycle rules.\",\n \"Include cleanup, determinism, privacy, and cross-test contamination constraints.\",\n ]),\n sectionSpec(\"## Execution Model\", [\n \"Describe how tests run: command, framework, parallelism, isolation, network/filesystem assumptions, and required services.\",\n \"State whether tests are unit, integration, e2e, contract, smoke, regression, or generated checks.\",\n ]),\n sectionSpec(\"## Assertions And Invariants\", [\n \"List the critical assertions, invariants, failure modes, and negative cases that make the tests meaningful.\",\n \"Tie assertions to product/contract rules rather than incidental implementation details.\",\n ]),\n sectionSpec(\"## Isolation Rules\", [\n \"Document transaction boundaries, temp directories, fake clocks, network blocking, shared resources, and teardown rules.\",\n \"Call out known order dependencies or flake risks and how they are controlled.\",\n ]),\n sectionSpec(\"## Reporting And Failure Semantics\", [\n \"Describe diagnostics, snapshots, logs, coverage signals, retry policy, and how maintainers should interpret failures.\",\n \"Include escalation or quarantine criteria for flaky or environment-sensitive tests.\",\n ]),\n ]);\n};\n\nconst renderTemplate = (\n template: string,\n values: Record<string, string>,\n): 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.truthmark.routes.defaultArea;\n const title = titleCase(defaultArea);\n const templatePath = `${truthRoot(config)}/${defaultArea}/overview.md`;\n const sourceOfTruth = resolveRelativePath(\n templatePath,\n `${config.truthmark.paths.routeAreasRoot}/${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_implementation_behavior:\n \"- Document current behavior here when implementation changes make repository truth incomplete.\",\n engineering_decisions: `- 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 product_truth_links: \"- None.\",\n scope: `This bounded leaf truth doc owns the default ${title.toLowerCase()} behavior surface created by Truthmark.`,\n source_references: `- ${sourceOfTruth}`,\n template_path: BEHAVIOR_DOC_TEMPLATE_PATH,\n title: `${title} Overview`,\n truth_kind: \"engineering-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 \"antigravity\",\n \"cursor\",\n] as const;\n\nexport type TruthmarkPlatform = (typeof SUPPORTED_PLATFORMS)[number];\n\n// Omitted platforms are deliberate host-neutral state: no active platform ownership is inferred; empty means deprovisioned.\nexport const DEFAULT_PLATFORMS =\n [] as const satisfies readonly TruthmarkPlatform[];\n\ntype TruthmarkPortalConfig = {\n enabled: boolean;\n};\n\ntype RawTruthmarkWorkspaceConfig = {\n workspace: string;\n generated: {\n portal: TruthmarkPortalConfig;\n };\n};\n\ntype TruthmarkWorkspaceConfig = {\n workspace: string;\n routes: {\n index: string;\n areas: string;\n defaultArea: string;\n maxDelegationDepth: 1;\n };\n truth: {\n productRoot: string;\n engineeringRoot: string;\n };\n templates: {\n root: string;\n };\n generated: {\n portal: TruthmarkPortalConfig;\n };\n paths: {\n routesIndex: string;\n routeAreasRoot: string;\n productTruthRoot: string;\n engineeringTruthRoot: string;\n truthRoot?: string;\n templatesRoot: string;\n portalOutput: string;\n portalTemplate: string;\n };\n controlledPaths: string[];\n};\n\nexport type RawTruthmarkConfig = {\n version: 2;\n platforms?: TruthmarkPlatform[];\n truthmark: RawTruthmarkWorkspaceConfig;\n instruction_targets?: string[];\n frontmatter?: {\n required?: string[];\n recommended?: string[];\n };\n ignore?: string[];\n};\n\nexport type TruthmarkConfig = {\n version: 2;\n platforms: TruthmarkPlatform[];\n truthmark: TruthmarkWorkspaceConfig;\n frontmatter: {\n required: string[];\n recommended: string[];\n };\n ignore: string[];\n};\n\nexport const truthmarkConfigSchema = {\n type: \"object\",\n additionalProperties: false,\n required: [\"version\", \"truthmark\"],\n properties: {\n version: {\n type: \"integer\",\n const: 2,\n },\n platforms: {\n type: \"array\",\n nullable: true,\n items: {\n type: \"string\",\n enum: [...SUPPORTED_PLATFORMS],\n },\n minItems: 1,\n },\n truthmark: {\n type: \"object\",\n additionalProperties: false,\n required: [\"workspace\", \"generated\"],\n properties: {\n workspace: {\n type: \"string\",\n },\n generated: {\n type: \"object\",\n additionalProperties: false,\n required: [\"portal\"],\n properties: {\n portal: {\n type: \"object\",\n additionalProperties: false,\n required: [\"enabled\"],\n properties: {\n enabled: { type: \"boolean\" },\n },\n },\n },\n },\n },\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} as unknown as JSONSchemaType<RawTruthmarkConfig>;\n","import { DEFAULT_PLATFORMS, type TruthmarkConfig } from \"./schema.js\";\n\nexport const DEFAULT_TRUTHMARK_WORKSPACE = {\n workspace: \"docs/truthmark\",\n generated: {\n portal: {\n enabled: false,\n },\n },\n} as const;\n\nexport const DERIVED_TRUTHMARK_PATHS = {\n routesIndex: \"routes/areas.md\",\n routeAreasRoot: \"routes/areas\",\n defaultArea: \"repository\",\n maxDelegationDepth: 1,\n productTruthRoot: \"product\",\n engineeringTruthRoot: \"engineering\",\n templatesRoot: \"templates\",\n portalOutput: \"generated/portal\",\n portalTemplate: \"templates/portal.html\",\n} as const;\n\nexport const createDefaultRawConfig = () => ({\n version: 2 as const,\n truthmark: {\n workspace: DEFAULT_TRUTHMARK_WORKSPACE.workspace,\n generated: {\n portal: { ...DEFAULT_TRUTHMARK_WORKSPACE.generated.portal },\n },\n },\n frontmatter: {\n required: [],\n recommended: [\"status\", \"last_reviewed\"],\n },\n ignore: [\"node_modules/**\", \"vendor/**\", \"dist/**\", \"build/**\"],\n});\n\nexport const createDefaultConfig = (): TruthmarkConfig => ({\n version: 2,\n platforms: [...DEFAULT_PLATFORMS],\n truthmark: {\n workspace: DEFAULT_TRUTHMARK_WORKSPACE.workspace,\n routes: {\n index: DERIVED_TRUTHMARK_PATHS.routesIndex,\n areas: DERIVED_TRUTHMARK_PATHS.routeAreasRoot,\n defaultArea: DERIVED_TRUTHMARK_PATHS.defaultArea,\n maxDelegationDepth: DERIVED_TRUTHMARK_PATHS.maxDelegationDepth,\n },\n truth: {\n productRoot: DERIVED_TRUTHMARK_PATHS.productTruthRoot,\n engineeringRoot: DERIVED_TRUTHMARK_PATHS.engineeringTruthRoot,\n },\n templates: { root: DERIVED_TRUTHMARK_PATHS.templatesRoot },\n generated: {\n portal: { ...DEFAULT_TRUTHMARK_WORKSPACE.generated.portal },\n },\n paths: {\n routesIndex: \"docs/truthmark/routes/areas.md\",\n routeAreasRoot: \"docs/truthmark/routes/areas\",\n productTruthRoot: \"docs/truthmark/product\",\n engineeringTruthRoot: \"docs/truthmark/engineering\",\n templatesRoot: \"docs/truthmark/templates\",\n portalOutput: \"docs/truthmark/generated/portal\",\n portalTemplate: \"docs/truthmark/templates/portal.html\",\n },\n controlledPaths: [\n \"docs/truthmark/routes/areas.md\",\n \"docs/truthmark/routes/areas/**/*.md\",\n \"docs/truthmark/product/**/*.md\",\n \"docs/truthmark/engineering/**/*.md\",\n \"docs/truthmark/templates/*.md\",\n ],\n },\n frontmatter: {\n required: [],\n recommended: [\"status\", \"last_reviewed\"],\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 \"product-capability\",\n \"engineering-behavior\",\n \"engineering-contract\",\n \"engineering-workflow\",\n \"engineering-architecture\",\n \"engineering-operations\",\n \"engineering-test-behavior\",\n] as const;\n\nexport type TruthDocumentKind = (typeof TRUTH_DOCUMENT_KINDS)[number];\nexport type TruthDocumentLane = \"product\" | \"engineering\";\n\nexport type TruthDocumentEntry = {\n path: string;\n kind: TruthDocumentKind;\n kindSource: \"explicit\" | \"inferred\" | \"defaulted\";\n lane: TruthDocumentLane;\n laneSource: \"explicit\" | \"inferred\" | \"defaulted\";\n realizedBy: string[];\n realizes: string[];\n dependsOn: string[];\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\nconst uniqueSorted = (values: string[]): string[] =>\n [...new Set(values)].sort();\n\nexport const mergeTruthDocumentEntryRelationships = (\n first: TruthDocumentEntry,\n second: TruthDocumentEntry,\n): TruthDocumentEntry => ({\n ...first,\n realizedBy: uniqueSorted([...first.realizedBy, ...second.realizedBy]),\n realizes: uniqueSorted([...first.realizes, ...second.realizes]),\n dependsOn: uniqueSorted([...first.dependsOn, ...second.dependsOn]),\n});\n\ntype 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 productTruthRoot?: string;\n engineeringTruthRoot?: string;\n};\n\nconst DEFAULT_PRODUCT_TRUTH_DOCS_ROOT = \"docs/truthmark/product\";\nconst DEFAULT_ENGINEERING_TRUTH_DOCS_ROOT = \"docs/truthmark/engineering\";\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 productTruthRoot = (\n options.productTruthRoot ?? DEFAULT_PRODUCT_TRUTH_DOCS_ROOT\n )\n ?.replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n const engineeringTruthRoot = (\n options.engineeringTruthRoot ??\n options.truthDocsRoot ??\n DEFAULT_ENGINEERING_TRUTH_DOCS_ROOT\n )\n ?.replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n\n if (productTruthRoot && normalizedPath.startsWith(`${productTruthRoot}/`)) {\n return \"product-capability\";\n }\n\n if (\n engineeringTruthRoot &&\n normalizedPath.startsWith(`${engineeringTruthRoot}/`)\n ) {\n if (normalizedPath.includes(\"/contracts/\")) return \"engineering-contract\";\n if (normalizedPath.includes(\"/workflows/\")) return \"engineering-workflow\";\n if (normalizedPath.includes(\"/architecture/\"))\n return \"engineering-architecture\";\n if (normalizedPath.includes(\"/operations/\"))\n return \"engineering-operations\";\n if (normalizedPath.includes(\"/tests/\")) return \"engineering-test-behavior\";\n return \"engineering-behavior\";\n }\n\n return null;\n};\n\nconst inferTruthDocumentLaneFromPath = (\n documentPath: string,\n options: ParseAreasMarkdownOptions = {},\n): TruthDocumentLane | null => {\n const normalizedPath = documentPath.replaceAll(\"\\\\\", \"/\");\n const productTruthRoot = (\n options.productTruthRoot ?? DEFAULT_PRODUCT_TRUTH_DOCS_ROOT\n )\n .replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n const engineeringTruthRoot = (\n options.engineeringTruthRoot ??\n options.truthDocsRoot ??\n DEFAULT_ENGINEERING_TRUTH_DOCS_ROOT\n )\n .replaceAll(\"\\\\\", \"/\")\n .replace(/\\/+$/u, \"\");\n\n if (normalizedPath.startsWith(`${productTruthRoot}/`)) {\n return \"product\";\n }\n\n if (normalizedPath.startsWith(`${engineeringTruthRoot}/`)) {\n return \"engineering\";\n }\n\n return null;\n};\n\nexport const laneForTruthDocumentKind = (\n kind: TruthDocumentKind,\n): TruthDocumentLane => {\n return kind.startsWith(\"product-\") ? \"product\" : \"engineering\";\n};\n\nexport const docTypeForTruthDocumentKind = (\n kind: TruthDocumentKind,\n): string => {\n if (kind.startsWith(\"product-\")) {\n return \"product\";\n }\n return kind.slice(\"engineering-\".length);\n};\n\nconst parseStringListField = (rawEntry: unknown, field: string): string[] => {\n if (!rawEntry || typeof rawEntry !== \"object\" || !(field in rawEntry)) {\n return [];\n }\n\n const value = (rawEntry as Record<string, unknown>)[field];\n\n if (!Array.isArray(value)) {\n return [];\n }\n\n return value.filter((entry): entry is string => typeof entry === \"string\");\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 const inferredLane = inferTruthDocumentLaneFromPath(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 ?? \"engineering-behavior\",\n kindSource: inferredKind ? (\"inferred\" as const) : (\"defaulted\" as const),\n lane: inferredLane ?? \"engineering\",\n laneSource: inferredLane ? (\"inferred\" as const) : (\"defaulted\" as const),\n realizedBy: [],\n realizes: [],\n dependsOn: [],\n };\n });\n\n return {\n truthDocuments,\n truthDocumentEntries,\n diagnostics,\n };\n};\n\nconst parseTruthDocumentsFromYaml = (\n sectionLines: string[],\n areaName: string,\n options: ParseAreasMarkdownOptions,\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 const lane =\n rawEntry && typeof rawEntry === \"object\" && \"lane\" in rawEntry\n ? (rawEntry as { lane?: unknown }).lane\n : null;\n const inferredKind =\n typeof path === \"string\"\n ? inferTruthDocumentKindFromPath(path, options)\n : null;\n const inferredLane =\n typeof path === \"string\"\n ? inferTruthDocumentLaneFromPath(path, options)\n : null;\n const normalizedKind = isTruthDocumentKind(kind) ? kind : inferredKind;\n const normalizedLane =\n lane === \"product\" || lane === \"engineering\"\n ? lane\n : normalizedKind\n ? laneForTruthDocumentKind(normalizedKind)\n : inferredLane;\n\n if (\n typeof path !== \"string\" ||\n path.trim().length === 0 ||\n !normalizedKind ||\n !normalizedLane\n ) {\n diagnostics.push(\n createAreaDiagnostic(\n `Area ${areaName} truth_documents entries must include non-empty path plus valid lane and kind fields.`,\n areaName,\n ),\n );\n continue;\n }\n\n truthDocumentEntries.push({\n path: path.trim(),\n kind: normalizedKind,\n kindSource: isTruthDocumentKind(kind) ? \"explicit\" : \"inferred\",\n lane: normalizedLane,\n laneSource:\n lane === \"product\" || lane === \"engineering\" ? \"explicit\" : \"inferred\",\n realizedBy: parseStringListField(rawEntry, \"realized_by\"),\n realizes: parseStringListField(rawEntry, \"realizes\"),\n dependsOn: parseStringListField(rawEntry, \"depends_on\"),\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(\n sectionLines,\n areaName,\n options,\n );\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 const heading = areaHeadingMatch[1]?.trim() ?? null;\n flushArea();\n currentAreaName = heading === \"Source References\" ? null : heading;\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 type { TruthmarkConfig } from \"../config/schema.js\";\n\nexport type TruthLane = \"product\" | \"engineering\";\n\nexport const PRODUCT_TRUTH_KINDS = [\"product-capability\"] as const;\nexport const ENGINEERING_TRUTH_KINDS = [\n \"engineering-behavior\",\n \"engineering-contract\",\n \"engineering-workflow\",\n \"engineering-architecture\",\n \"engineering-operations\",\n \"engineering-test-behavior\",\n] as const;\n\nexport const resolveTruthDocsRoot = (config: Pick<TruthmarkConfig, \"truthmark\">): string => {\n return config.truthmark.paths.engineeringTruthRoot;\n};\n\nexport const resolveProductTruthRoot = (config: Pick<TruthmarkConfig, \"truthmark\">): string => {\n return config.truthmark.paths.productTruthRoot;\n};\n\nexport const resolveEngineeringTruthRoot = (\n config: Pick<TruthmarkConfig, \"truthmark\">,\n): string => {\n return config.truthmark.paths.engineeringTruthRoot;\n};\n\nexport const truthLaneRoots = (config: Pick<TruthmarkConfig, \"truthmark\">) => ({\n product: resolveProductTruthRoot(config),\n engineering: resolveEngineeringTruthRoot(config),\n});\n","import fs from \"node:fs/promises\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport { upsertManagedBlock as upsertManagedInstructionBlock } from \"../managed-block.js\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type {\n CommandResult,\n DiagnosticCategory,\n} from \"../output/diagnostic.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport {\n resolveRepoPath,\n type FileWriteResult,\n writeRepoFile,\n} from \"../fs/paths.js\";\nimport { scaffoldHierarchy } from \"./hierarchy.js\";\nimport { renderAgentsBlock } from \"../templates/agents-block.js\";\nimport {\n renderGeneratedSurfaces,\n type GeneratedSurface,\n} from \"../templates/generated-surfaces.js\";\nimport { applyLifecyclePlan, buildLifecyclePlan } from \"./lifecycle.js\";\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 (\n !(error instanceof Error) ||\n !(\"code\" in error) ||\n error.code !== \"ENOENT\"\n ) {\n throw error;\n }\n }\n\n return writeRepoFile(\n rootDir,\n path,\n upsertManagedInstructionBlock(existingContent, block),\n );\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 === \".github/prompts/truthmark-realize.prompt.md\" ||\n filePath.startsWith(\".github/skills/truthmark-realize/\") ||\n filePath.startsWith(\".claude/skills/truthmark-realize/\") ||\n filePath.startsWith(\".opencode/skills/truthmark-realize/\") ||\n filePath.startsWith(\".agents/skills/truthmark-realize/\") ||\n filePath.startsWith(\".antigravity/rules/truthmark-realize\") ||\n filePath.startsWith(\".cursor/rules/truthmark-realize\") ||\n filePath.startsWith(\".cursor/skills/truthmark-realize/\")\n ) {\n return \"realization\";\n }\n\n if (\n filePath === \"CLAUDE.md\" ||\n filePath === \".github/copilot-instructions.md\" ||\n filePath.startsWith(\".github/prompts/truthmark-\") ||\n filePath.startsWith(\".github/agents/truth-\") ||\n filePath.startsWith(\".github/skills/truthmark-\") ||\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 filePath.startsWith(\".antigravity/rules/truthmark-\") ||\n filePath.startsWith(\".cursor/rules/truthmark-\") ||\n filePath.startsWith(\".cursor/skills/truthmark-\")\n ) {\n return \"truth-sync\";\n }\n\n if (filePath.startsWith(\".agents/skills/truthmark-\")) {\n return \"truth-sync\";\n }\n\n if (filePath === config.truthmark.paths.routesIndex) {\n return \"area-index\";\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 workspace paths, 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 results: FileWriteResult[] = [];\n\n const config = loadedConfig.config;\n const block = renderAgentsBlock(config);\n const platformFiles = renderGeneratedSurfaces(config, block);\n const lifecyclePlan = await buildLifecyclePlan(\n rootDir,\n config,\n \"apply\",\n platformFiles,\n );\n if (!lifecyclePlan.applicable) {\n return {\n command: \"init\",\n summary:\n \"Truthmark init made no changes because generated-surface preflight failed.\",\n diagnostics: [...loadedConfig.diagnostics, ...lifecyclePlan.diagnostics],\n data: { lifecyclePlan },\n };\n }\n const appliedLifecyclePlan = await applyLifecyclePlan(rootDir, lifecyclePlan);\n if (!appliedLifecyclePlan.applicable) {\n return {\n command: \"init\",\n summary:\n \"Truthmark init made no changes because generated-surface preflight failed.\",\n diagnostics: [\n ...loadedConfig.diagnostics,\n ...appliedLifecyclePlan.diagnostics,\n ],\n data: { lifecyclePlan: appliedLifecyclePlan },\n };\n }\n\n results.push(...(await scaffoldHierarchy(rootDir, config)));\n for (const file of platformFiles) {\n results.push(await writePlatformFile(rootDir, file));\n }\n\n const changedResults = results.filter(\n (result) => result.status !== \"unchanged\",\n );\n const lifecycleChanged = appliedLifecyclePlan.entries.some(\n ({ action }) =>\n action === \"remove-file\" || action === \"remove-managed-block\",\n );\n\n return {\n command: \"init\",\n summary:\n changedResults.length > 0 || lifecycleChanged\n ? \"Initialized or updated the Truthmark repository scaffold.\"\n : \"Truthmark repository scaffold is already up to date.\",\n diagnostics: [\n ...loadedConfig.diagnostics,\n ...appliedLifecyclePlan.diagnostics,\n ...appliedLifecyclePlan.entries.map((entry) => ({\n category: \"generated-surface\" as const,\n severity:\n entry.action === \"remove-file\" ||\n entry.action === \"remove-managed-block\"\n ? (\"action\" as const)\n : (\"review\" as const),\n message: `${entry.action}: ${entry.reason}`,\n file: entry.path,\n })),\n ...writeDiagnostics(results, config),\n ],\n data: {\n repositoryRoot: repository.repositoryRoot,\n worktreePath: repository.worktreePath,\n branchName: repository.branchName,\n isDetached: repository.isDetached,\n isUnborn: repository.isUnborn,\n lifecyclePlan: appliedLifecyclePlan,\n },\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\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 { DERIVED_TRUTHMARK_PATHS } 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 category: \"config\",\n severity: \"error\",\n message,\n file,\n});\n\nexport const normalizeRepoRelativePath = (value: string): string => {\n const slashNormalized = value.replace(/\\\\/gu, \"/\");\n return path.posix.normalize(slashNormalized).replace(/\\/+$/u, \"\");\n};\n\nconst isUnsafeRepoRelativePath = (value: string): boolean => {\n const slashNormalized = value.replace(/\\\\/gu, \"/\");\n const normalized = normalizeRepoRelativePath(value);\n const parts = slashNormalized.split(\"/\");\n\n return (\n normalized.length === 0 ||\n normalized === \".\" ||\n normalized === \"..\" ||\n path.isAbsolute(value) ||\n path.posix.isAbsolute(slashNormalized) ||\n path.win32.isAbsolute(value) ||\n /^[A-Za-z]:/u.test(value) ||\n normalized.startsWith(\"../\") ||\n parts.includes(\"..\")\n );\n};\n\nconst joinWorkspacePath = (workspace: string, childPath: string): string => {\n return normalizeRepoRelativePath(`${workspace}/${childPath}`);\n};\n\nconst portalOutputFor = (workspace: string): string =>\n joinWorkspacePath(workspace, DERIVED_TRUTHMARK_PATHS.portalOutput);\n\nconst pathsOverlap = (left: string, right: string): boolean => {\n const normalizedLeft = normalizeRepoRelativePath(left);\n const normalizedRight = normalizeRepoRelativePath(right);\n\n return (\n normalizedLeft === normalizedRight ||\n normalizedLeft.startsWith(`${normalizedRight}/`) ||\n normalizedRight.startsWith(`${normalizedLeft}/`)\n );\n};\n\nconst CONFIG_PATH = \".truthmark/config.yml\";\nconst FORBIDDEN_WORKSPACE_OVERLAPS = [\n \".git\",\n \".truthmark\",\n \"package.json\",\n \"package-lock.json\",\n \"pnpm-lock.yaml\",\n \"yarn.lock\",\n \"src\",\n \"tests\",\n] as const;\n\nconst unsupportedShapeDiagnostics = (\n parsedConfig: unknown,\n configPath: string,\n): Diagnostic[] => {\n if (\n !parsedConfig ||\n typeof parsedConfig !== \"object\" ||\n Array.isArray(parsedConfig)\n ) {\n return [];\n }\n\n const record = parsedConfig as Record<string, unknown>;\n const diagnostics: Diagnostic[] = [];\n\n if (record.version !== 2) {\n diagnostics.push(\n toConfigDiagnostic(\n \"Unsupported Truthmark config shape. This release requires version: 2 with a truthmark workspace block.\",\n configPath,\n ),\n );\n }\n\n if (\"docs\" in record || \"authority\" in record) {\n diagnostics.push(\n toConfigDiagnostic(\n \"Unsupported Truthmark config shape. Remove old docs.roots and legacy authority settings; use version: 2 truthmark.workspace paths.\",\n configPath,\n ),\n );\n }\n\n return diagnostics;\n};\n\nconst validateWorkspacePaths = (\n rawConfig: RawTruthmarkConfig,\n configPath: string,\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const workspace = normalizeRepoRelativePath(rawConfig.truthmark.workspace);\n\n if (\n isUnsafeRepoRelativePath(rawConfig.truthmark.workspace) ||\n FORBIDDEN_WORKSPACE_OVERLAPS.some((forbidden) =>\n pathsOverlap(workspace, forbidden),\n )\n ) {\n diagnostics.push(\n toConfigDiagnostic(\n \"truthmark.workspace must be a non-empty repo-relative directory that does not overlap repository control, package, source, test, or instruction paths.\",\n configPath,\n ),\n );\n }\n\n return diagnostics;\n};\n\nconst normalizeConfig = (rawConfig: RawTruthmarkConfig): TruthmarkConfig => {\n const workspace = normalizeRepoRelativePath(rawConfig.truthmark.workspace);\n const routesIndex = joinWorkspacePath(\n workspace,\n DERIVED_TRUTHMARK_PATHS.routesIndex,\n );\n const routeAreasRoot = joinWorkspacePath(\n workspace,\n DERIVED_TRUTHMARK_PATHS.routeAreasRoot,\n );\n const productTruthRoot = joinWorkspacePath(\n workspace,\n DERIVED_TRUTHMARK_PATHS.productTruthRoot,\n );\n const engineeringTruthRoot = joinWorkspacePath(\n workspace,\n DERIVED_TRUTHMARK_PATHS.engineeringTruthRoot,\n );\n const templatesRoot = joinWorkspacePath(\n workspace,\n DERIVED_TRUTHMARK_PATHS.templatesRoot,\n );\n const portalOutput = portalOutputFor(workspace);\n const portalTemplate = joinWorkspacePath(\n workspace,\n DERIVED_TRUTHMARK_PATHS.portalTemplate,\n );\n\n return {\n version: rawConfig.version,\n platforms: rawConfig.platforms ?? [...DEFAULT_PLATFORMS],\n truthmark: {\n workspace,\n routes: {\n index: DERIVED_TRUTHMARK_PATHS.routesIndex,\n areas: DERIVED_TRUTHMARK_PATHS.routeAreasRoot,\n defaultArea: DERIVED_TRUTHMARK_PATHS.defaultArea,\n maxDelegationDepth: DERIVED_TRUTHMARK_PATHS.maxDelegationDepth,\n },\n truth: {\n productRoot: DERIVED_TRUTHMARK_PATHS.productTruthRoot,\n engineeringRoot: DERIVED_TRUTHMARK_PATHS.engineeringTruthRoot,\n },\n templates: {\n root: DERIVED_TRUTHMARK_PATHS.templatesRoot,\n },\n generated: {\n portal: {\n enabled: rawConfig.truthmark.generated.portal.enabled,\n },\n },\n paths: {\n routesIndex,\n routeAreasRoot,\n productTruthRoot,\n engineeringTruthRoot,\n templatesRoot,\n portalOutput,\n portalTemplate,\n },\n controlledPaths: [\n routesIndex,\n `${routeAreasRoot}/**/*.md`,\n `${productTruthRoot}/**/*.md`,\n `${engineeringTruthRoot}/**/*.md`,\n `${templatesRoot}/*.md`,\n ],\n },\n frontmatter: {\n required: rawConfig.frontmatter?.required ?? [],\n recommended: rawConfig.frontmatter?.recommended ?? [],\n },\n ignore: rawConfig.ignore ?? [],\n };\n};\n\nconst compatibilityDiagnostics = (\n rawConfig: RawTruthmarkConfig,\n configPath: string,\n): Diagnostic[] => {\n if (!(\"instruction_targets\" in rawConfig)) {\n return [];\n }\n\n return [\n {\n category: \"config\",\n severity: \"review\",\n message:\n \"instruction_targets is accepted for compatibility but ignored; select platforms to control managed instruction-file writes.\",\n file: configPath,\n },\n ];\n};\n\nexport const loadConfig = async (\n rootDir: string,\n): Promise<LoadConfigResult> => {\n const absolutePath = resolveRepoPath(rootDir, CONFIG_PATH);\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: [\n toConfigDiagnostic(\"Missing .truthmark/config.yml.\", CONFIG_PATH),\n ],\n configPath: CONFIG_PATH,\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 CONFIG_PATH,\n ),\n ],\n configPath: CONFIG_PATH,\n };\n }\n\n const unsupportedDiagnostics = unsupportedShapeDiagnostics(\n parsedConfig,\n CONFIG_PATH,\n );\n if (unsupportedDiagnostics.length > 0) {\n return {\n status: \"invalid\",\n config: null,\n diagnostics: unsupportedDiagnostics,\n configPath: CONFIG_PATH,\n };\n }\n\n if (!validateTruthmarkConfig(parsedConfig)) {\n return {\n status: \"invalid\",\n config: null,\n diagnostics: (validateTruthmarkConfig.errors ?? []).map(\n (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, CONFIG_PATH);\n },\n ),\n configPath: CONFIG_PATH,\n };\n }\n\n const pathDiagnostics = validateWorkspacePaths(\n parsedConfig as RawTruthmarkConfig,\n CONFIG_PATH,\n );\n\n if (pathDiagnostics.length > 0) {\n return {\n status: \"invalid\",\n config: null,\n diagnostics: pathDiagnostics,\n configPath: CONFIG_PATH,\n };\n }\n\n return {\n status: \"loaded\",\n config: normalizeConfig(parsedConfig as RawTruthmarkConfig),\n diagnostics: compatibilityDiagnostics(\n parsedConfig as RawTruthmarkConfig,\n CONFIG_PATH,\n ),\n configPath: CONFIG_PATH,\n };\n};\n","export type ClaimEvidenceResult = \"supported\" | \"narrowed\" | \"removed\" | \"blocked\";\n\nexport type ClaimEvidenceItem = {\n claim: string;\n evidence: string[];\n result: ClaimEvidenceResult;\n};\n\ntype AuditEvidenceConfidence = \"high\" | \"medium\" | \"low\";\n\ntype 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 {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"../truth/docs.js\";\n\nexport {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n resolveTruthDocsRoot,\n} from \"../truth/docs.js\";\n\nconst renderBulletLine = (line: string): string => {\n const normalized = line.trim().replace(/^-\\s*/u, \"\");\n return `- ${normalized}`;\n};\n\nexport const renderBulletBlock = (lines: string, indent = \" \"): string => {\n return lines\n .split(/\\n/u)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => `${indent}${renderBulletLine(line)}`)\n .join(\"\\n\");\n};\n\nexport const renderLaneClassificationRuleBlock = (\n config: TruthmarkConfig = defaultAgentConfig(),\n indent = \" \",\n): string => {\n const [, ...rules] =\n renderLaneClassificationInstructions(config).split(/\\n/u);\n\n return renderBulletBlock(rules.join(\"\\n\"), indent);\n};\n\nexport const renderReadOnlyLaneClassificationRuleBlock = (\n config: TruthmarkConfig = defaultAgentConfig(),\n indent = \" \",\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n\n return renderBulletBlock(\n [\n \"classify the request or changed surface as product-lane, engineering-lane, both-lane, or ambiguous for reporting only\",\n `product-lane ownership belongs under ${productTruthRoot} and describes product promises, boundaries, rationale, decisions, and success criteria`,\n `engineering-lane ownership belongs under ${engineeringTruthRoot} and describes source-backed current realization, contracts, architecture, workflows, operations, or tests`,\n \"both-lane ownership uses separate product and engineering docs cross-linked in route YAML with realized_by and realizes, not in doc frontmatter\",\n \"ambiguous lane ownership should be reported for manual handoff or routed to Truth Structure\",\n LANE_INVARIANT,\n ].join(\"\\n\"),\n indent,\n );\n};\n\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 \"Product decisions belong in product truth; engineering, architecture, contract, workflow, and operational decisions belong in engineering truth.\",\n].join(\"\\n\");\n\nexport const LANE_INVARIANT =\n \"Do not make product docs a summary of engineering docs. Do not make engineering docs a detailed version of product docs. Product truth says what must be true and why. Engineering truth says how the repository currently realizes it.\";\n\nexport const renderLaneClassificationInstructions = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n\n return [\n \"Lane review questions:\",\n \"- before writing canonical truth docs, classify the request or change as product-lane, engineering-lane, both-lane, or ambiguous\",\n `- product-lane writes belong under ${productTruthRoot} and state product promises, boundaries, rationale, decisions, and success criteria`,\n `- engineering-lane writes belong under ${engineeringTruthRoot} and state source-backed current realization, contracts, architecture, workflows, operations, or tests`,\n \"- both-lane work must write separate product and engineering docs and cross-link them in route YAML with realized_by and realizes, not in doc frontmatter\",\n \"- ambiguous lane ownership must stop or invoke Truth Structure instead of writing a mixed document\",\n `- ${LANE_INVARIANT}`,\n ].join(\"\\n\");\n};\n\nexport const EVIDENCE_AUTHORITY_INSTRUCTIONS = [\n \"Repository instruction files and explicitly configured policy docs remain instruction authority when present; do not assume a repository uses any particular policy path.\",\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 WorkflowState/action context may guide routing, write boundaries, 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 any present Truthmark config, 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 template under the configured Truthmark templates root.\",\n \"Supported kinds: product-capability, engineering-behavior, engineering-contract, engineering-architecture, engineering-workflow, engineering-operations, and engineering-test-behavior.\",\n \"Treat the HTML comments under each template section as normative authoring guidance for that section.\",\n \"Align existing docs to that template and write or repair section content so it satisfies the comment guidance while preserving accurate authored content.\",\n \"If the template is missing, use lane-specific sections: product truth says what must be true and why; engineering truth says how the repository currently realizes it.\",\n \"Teams may edit template files under the configured Truthmark templates root to define their local truth-doc standards.\",\n].join(\"\\n\");\n\nexport const TRUTH_DOC_AUTHORING_STYLE_INSTRUCTIONS = [\n \"Truth-doc prose style:\",\n \"- Use professional, plain technical prose. Prefer specific current-state claims over promotional, symbolic, or generic significance language.\",\n \"- Avoid common AI-writing tells: pivotal, crucial, underscores, serves as, stands as, showcases, landscape, vague expert attributions, and generic upbeat conclusions.\",\n \"- Keep claims evidence-backed and diff-friendly: one durable claim per bullet or line; paragraphs should be no longer than one or two short sentences.\",\n \"- Do not add personality, rhetorical flourish, first-person commentary, or marketing tone.\",\n \"- Rewrite dense or formulaic prose only when it improves readability without removing scope, evidence, decisions, or source references.\",\n].join(\"\\n\");\n\nexport const renderTruthDocOwnershipGateSection = (\n subject: string,\n outcome: string,\n): string => {\n return [\n \"Truth-doc ownership review:\",\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 Manual handoff reason as applicable\",\n ].join(\"\\n\");\n};\n\nexport const TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS = [\n \"Decision/Rationale preservation review:\",\n \"- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions, Engineering Decisions, and Rationale sections in every source or touched truth doc\",\n \"- preserve each current decision and rationale in the correct product or engineering lane owner; 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, stop with manual-review files instead of deleting it or guessing\",\n \"- after the edit, verify every touched truth doc keeps lane-appropriate decision/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 review:\",\n `- ${scope}`,\n \"- repair shape in place only after the ownership review 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 record unsupported or stale claims for manual handoff\",\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 checklist:\",\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, lane-specific 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 record unsupported claims for manual handoff\",\n `- ${noImpactedDocOutcome}`,\n ].join(\"\\n\");\n};\n\nexport const renderTopologyEvidenceGateSection = (): string => {\n return [\n \"Evidence checklist:\",\n \"- apply the evidence checklist before finishing when Truth Structure writes routed docs, ownership claims, lane-specific 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 record unsupported claims for manual handoff\",\n ].join(\"\\n\");\n};\n\nexport const renderAuditEvidenceGateSection = (): string => {\n return [\n \"Evidence checklist:\",\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 =\n 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(\n (agent) => `@${agent.replace(/_/gu, \"-\")}`,\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 readOnlyWorkerLabel =\n 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(\n (agent) => `${agent.replace(/_/gu, \"-\")} subagent`,\n );\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(\n (agent) => `@${agent.replace(/_/gu, \"-\")}`,\n );\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 productRoot = resolveProductTruthRoot(config);\n const engineeringRoot = resolveEngineeringTruthRoot(config);\n\n return [\n \"Truthmark hierarchy hints:\",\n \"- Config, when present: .truthmark/config.yml\",\n `- Root route index, when present: ${config.truthmark.paths.routesIndex}`,\n `- Area route files, when present: ${config.truthmark.paths.routeAreasRoot}/**/*.md`,\n `- Product truth docs, when present: ${productRoot}/**/*.md`,\n `- Engineering truth docs, when present: ${engineeringRoot}/**/*.md`,\n ].join(\"\\n\");\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n defaultAgentConfig,\n resolveProductTruthRoot,\n resolveEngineeringTruthRoot,\n} from \"../agents/shared.js\";\n\nexport const TRUTHMARK_BLOCK_START = \"<!-- truthmark:start -->\";\nexport const TRUTHMARK_BLOCK_END = \"<!-- truthmark:end -->\";\n\nconst renderCompactHierarchySummary = (config: TruthmarkConfig): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n const truthDocRoots = Array.from(\n new Set([productTruthRoot, engineeringTruthRoot]),\n ).map((truthRoot) => `${truthRoot}/**/*.md`);\n\n return `Hierarchy hints: config .truthmark/config.yml when present; routes ${config.truthmark.paths.routesIndex} and ${config.truthmark.paths.routeAreasRoot}/**/*.md when present; Truth docs: ${truthDocRoots.join(\" and \")} when present.`;\n};\n\nexport const renderAgentsBlock = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const portalLine = config.truthmark.generated.portal.enabled\n ? `Truthmark Portal is a separate manual-only presentation workflow. Run it only when explicitly requested; it writes generated non-canonical static files under ${config.truthmark.paths.portalOutput}/. Markdown remains canonical.`\n : null;\n\n return [\n TRUTHMARK_BLOCK_START,\n \"## Truthmark Workflow\",\n \"\",\n \"Truthmark-managed block. Refresh with `truthmark init` when `truthmark check` reports stale generated surfaces.\",\n renderCompactHierarchySummary(config),\n \"Decisions live in the canonical doc they govern; date active decisions inline.\",\n \"Agent runtime: host-native skill packages/adapters 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 need a fresh Sync review. 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 stop 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 Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details.\",\n ...(portalLine === null ? [] : [portalLine]),\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 { TRUTHMARK_BLOCK_END, TRUTHMARK_BLOCK_START } from \"./templates/agents-block.js\";\n\nexport type ParsedManagedBlock =\n | { status: \"absent\" }\n | { status: \"valid\"; start: number; end: number }\n | { status: \"malformed\" };\n\nconst findMarkerIndexes = (content: string, marker: string): number[] => {\n const indexes: number[] = [];\n let cursor = 0;\n\n while (true) {\n const index = content.indexOf(marker, cursor);\n if (index === -1) {\n return indexes;\n }\n\n indexes.push(index);\n cursor = index + marker.length;\n }\n};\n\nexport const parseManagedBlock = (content: string): ParsedManagedBlock => {\n const starts = findMarkerIndexes(content, TRUTHMARK_BLOCK_START);\n const ends = findMarkerIndexes(content, TRUTHMARK_BLOCK_END);\n\n if (starts.length === 0 && ends.length === 0) {\n return { status: \"absent\" };\n }\n\n if (starts.length !== 1 || ends.length !== 1) {\n return { status: \"malformed\" };\n }\n\n const start = starts[0];\n const endStart = ends[0];\n\n if (start === -1 || endStart === -1 || endStart < start) {\n return { status: \"malformed\" };\n }\n\n return {\n status: \"valid\",\n start,\n end: endStart + TRUTHMARK_BLOCK_END.length,\n };\n};\n\nexport const extractManagedBlock = (content: string): string | null => {\n const block = parseManagedBlock(content);\n\n if (block.status !== \"valid\") {\n return null;\n }\n\n return content.slice(block.start, block.end);\n};\n\nconst trimmedBoundary = (value: string): string => value.replace(/\\n+$/u, \"\");\n\nexport const upsertManagedBlock = (\n existingContent: string | null,\n block: string,\n): string => {\n if (existingContent === null || existingContent.trim().length === 0) {\n return block;\n }\n\n const marker = parseManagedBlock(existingContent);\n\n if (marker.status !== \"valid\") {\n return `${trimmedBoundary(existingContent)}\\n\\n${block}`;\n }\n\n const before = trimmedBoundary(existingContent.slice(0, marker.start));\n const after = existingContent.slice(marker.end).replace(/^\\n+/u, \"\");\n\n if (before.length === 0 && after.length === 0) {\n return block;\n }\n\n if (before.length === 0) {\n return `${block}\\n\\n${after}`;\n }\n\n if (after.length === 0) {\n return `${before}\\n\\n${block}`;\n }\n\n return `${before}\\n\\n${block}\\n\\n${after}`;\n};\n","import fs from \"node:fs/promises\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport type { FileWriteResult } from \"../fs/paths.js\";\nimport { ensureRepoFile, resolveRepoPath, writeRepoFile } from \"../fs/paths.js\";\nimport { parseAreasMarkdown } from \"../routing/areas.js\";\nimport {\n resolveEngineeringTruthRoot,\n resolveTruthDocsRoot,\n} from \"../truth/docs.js\";\nimport {\n renderChildAreaTemplate,\n mergeTruthDocTemplate,\n renderArchitectureDocTemplateFile,\n renderBehaviorDocTemplateFile,\n renderContractDocTemplateFile,\n renderTruthDomainReadmeTemplate,\n renderTruthRootReadmeTemplate,\n renderHierarchicalAreasIndexTemplate,\n renderOperationsDocTemplateFile,\n renderProductCapabilityDocTemplateFile,\n renderBootstrapRoutingDocTemplate,\n renderTestBehaviorDocTemplateFile,\n renderWorkflowDocTemplateFile,\n} from \"../templates/init-files.js\";\n\nconst truthRoot = resolveTruthDocsRoot;\nconst BEHAVIOR_DOC_TEMPLATE_FILE_NAME = \"engineering-behavior.md\";\nconst CONTRACT_DOC_TEMPLATE_FILE_NAME = \"engineering-contract.md\";\nconst ARCHITECTURE_DOC_TEMPLATE_FILE_NAME = \"engineering-architecture.md\";\nconst WORKFLOW_DOC_TEMPLATE_FILE_NAME = \"engineering-workflow.md\";\nconst OPERATIONS_DOC_TEMPLATE_FILE_NAME = \"engineering-operations.md\";\nconst TEST_BEHAVIOR_DOC_TEMPLATE_FILE_NAME = \"engineering-test-behavior.md\";\nconst PRODUCT_CAPABILITY_DOC_TEMPLATE_FILE_NAME = \"product-capability.md\";\n\nconst rootIndexReferencesChildRoute = async (\n rootDir: string,\n rootIndexPath: string,\n childRoutePath: string,\n): Promise<boolean> => {\n const rootIndexSource = await fs.readFile(\n resolveRepoPath(rootDir, rootIndexPath),\n \"utf8\",\n );\n const parsedRootIndex = parseAreasMarkdown(rootIndexSource);\n\n return parsedRootIndex.areaFileReferences.some((areaReference) =>\n areaReference.areaFiles.includes(childRoutePath),\n );\n};\n\nconst truthTemplatePath = (\n config: TruthmarkConfig,\n fileName: string,\n): string => {\n return `${config.truthmark.paths.templatesRoot}/${fileName}`;\n};\n\nconst ensureOrUpdateTruthDocTemplate = async (\n rootDir: string,\n templatePath: string,\n defaultTemplate: string,\n): Promise<FileWriteResult> => {\n const seededResult = await ensureRepoFile(\n rootDir,\n templatePath,\n defaultTemplate,\n );\n\n if (seededResult.status !== \"unchanged\") {\n return seededResult;\n }\n\n const existingTemplate = await fs.readFile(\n resolveRepoPath(rootDir, templatePath),\n \"utf8\",\n );\n const mergedTemplate = mergeTruthDocTemplate(\n existingTemplate,\n defaultTemplate,\n );\n\n return writeRepoFile(rootDir, templatePath, mergedTemplate);\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.truthmark.routes.defaultArea}`;\n const childRoutePath = `${config.truthmark.paths.routeAreasRoot}/${config.truthmark.routes.defaultArea}.md`;\n\n results.push(\n await ensureRepoFile(\n rootDir,\n config.truthmark.paths.routesIndex,\n renderHierarchicalAreasIndexTemplate(config),\n ),\n );\n if (\n await rootIndexReferencesChildRoute(\n rootDir,\n config.truthmark.paths.routesIndex,\n childRoutePath,\n )\n ) {\n results.push(\n await ensureRepoFile(\n rootDir,\n childRoutePath,\n renderChildAreaTemplate(config),\n ),\n );\n }\n results.push(\n await ensureRepoFile(\n rootDir,\n `${resolveEngineeringTruthRoot(config)}/README.md`,\n renderTruthRootReadmeTemplate(config, \"engineering\"),\n ),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n `${config.truthmark.paths.productTruthRoot}/README.md`,\n renderTruthRootReadmeTemplate(config, \"product\"),\n ),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDomainRoot}/README.md`,\n renderTruthDomainReadmeTemplate(config),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, BEHAVIOR_DOC_TEMPLATE_FILE_NAME),\n renderBehaviorDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, CONTRACT_DOC_TEMPLATE_FILE_NAME),\n renderContractDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, ARCHITECTURE_DOC_TEMPLATE_FILE_NAME),\n renderArchitectureDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, WORKFLOW_DOC_TEMPLATE_FILE_NAME),\n renderWorkflowDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, OPERATIONS_DOC_TEMPLATE_FILE_NAME),\n renderOperationsDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, TEST_BEHAVIOR_DOC_TEMPLATE_FILE_NAME),\n renderTestBehaviorDocTemplateFile(),\n ),\n );\n results.push(\n await ensureOrUpdateTruthDocTemplate(\n rootDir,\n truthTemplatePath(config, PRODUCT_CAPABILITY_DOC_TEMPLATE_FILE_NAME),\n renderProductCapabilityDocTemplateFile(),\n ),\n );\n results.push(\n await ensureRepoFile(\n rootDir,\n `${truthDomainRoot}/bootstrap-routing.md`,\n renderBootstrapRoutingDocTemplate(config),\n ),\n );\n return results;\n};\n","export type TruthmarkWorkflowId =\n | \"truthmark-sync\"\n | \"truthmark-structure\"\n | \"truthmark-document\"\n | \"truthmark-realize\"\n | \"truthmark-check\"\n | \"truthmark-portal\";\n\nexport type TruthmarkReadOnlySubagentId =\n | \"truth_route_auditor\"\n | \"truth_claim_verifier\"\n | \"truth_doc_reviewer\";\nexport type TruthmarkWriteSubagentId = \"truth_doc_writer\";\ntype 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 reviewQuestions: string[];\n allowedWrites: string[];\n reportSections: string[];\n subagents?: TruthmarkReadOnlySubagentId[];\n writeSubagents?: TruthmarkWriteSubagentId[];\n helpers?: TruthmarkWorkflowHelper[];\n};\n\nconst TRUTHMARK_CLI_RUNNER = \"truthmark\";\n\nconst VALIDATE_SYNC_REPORT_HELPER = {\n id: \"validate-sync-report\",\n optional: true,\n runner: TRUTHMARK_CLI_RUNNER,\n command: {\n argv: [\"truthmark\", \"validate\", \"sync-report\", \"<report-file>\", \"--json\"],\n },\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: {\n argv: [\n \"truthmark\",\n \"validate\",\n \"document-report\",\n \"<report-file>\",\n \"--json\",\n ],\n },\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 reviewQuestions: [\n \"topology review\",\n \"truth-doc ownership\",\n \"lane classification\",\n \"Decision/Rationale preservation\",\n \"truth-doc shape repair when restructuring\",\n \"Evidence checklist\",\n ],\n allowedWrites: [\"canonical truth docs\", \"truth routing files\"],\n reportSections: [\n \"Changed code reviewed\",\n \"Sync Intent\",\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 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 reviewQuestions: [\n \"truth-doc ownership\",\n \"lane classification\",\n \"Decision/Rationale preservation\",\n \"lane split and relationship repair\",\n \"truth-doc shape repair when restructuring\",\n \"Evidence checklist\",\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 reviewQuestions: [\n \"truth-doc ownership\",\n \"lane classification\",\n \"Decision/Rationale preservation\",\n \"Evidence checklist\",\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 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:\n \"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 except through follow-up Truth Sync\",\n \"must not edit truth routing except through follow-up Truth Sync\",\n ],\n reviewQuestions: [\"lane classification\", \"truth-doc ownership\"],\n allowedWrites: [\"functional code\"],\n reportSections: [\"Truth docs used\", \"Code updated\", \"Verification\"],\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 reviewQuestions: [\"audit evidence checklist\"],\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 \"truthmark-portal\": {\n id: \"truthmark-portal\",\n displayName: \"Truthmark Portal\",\n description:\n \"Use when the user explicitly asks to generate, refresh, or update the Truthmark Portal static HTML site. Not for code change sync, route repair, truth validation/checking, documenting behavior, realizing docs into code, or machine-readable agent context.\",\n shortDescription: \"Generate a committed static HTML Truthmark Portal\",\n defaultPrompt:\n \"Use $truthmark-portal only when explicitly asked to generate or refresh the committed static HTML Portal.\",\n allowImplicitInvocation: false,\n positiveTriggers: [\n \"generate the Truthmark Portal\",\n \"refresh the committed HTML docs site\",\n \"create a browsable project map from Truthmark docs\",\n \"update the Truthmark Portal output\",\n \"make a human-readable static site from the truth docs\",\n ],\n negativeTriggers: [\n \"code change sync\",\n \"route ownership repair\",\n \"truth validation or checking\",\n \"document implemented behavior\",\n \"realize docs into code\",\n \"machine-readable agent context\",\n ],\n forbiddenAdjacency: [\n \"must not run automatically at completion\",\n \"must not replace Truth Sync, Truth Check, Truth Document, Truth Realize, or Truth Structure\",\n \"must not write outside the fixed Portal output directory\",\n ],\n reviewQuestions: [\n \"manual-only invocation\",\n \"Portal output containment\",\n \"Markdown canonical statement\",\n \"source provenance\",\n ],\n allowedWrites: [\"fixed Portal output directory only\"],\n reportSections: [\n \"Output path\",\n \"Page count\",\n \"Diagrams/assets\",\n \"Source docs reviewed\",\n \"Skipped/ambiguous docs\",\n \"Validation\",\n \"Markdown canonical statement\",\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 renderBulletBlock,\n renderHierarchySummary,\n renderReadOnlyLaneClassificationRuleBlock,\n} from \"./shared.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; Antigravity @truthmark-check; Cursor /truthmark-check.\";\n\nexport const renderTruthCheckReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const rootRouteIndex = config.truthmark.paths.routesIndex;\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:\n \"The root route index is present and maps repository truth owners.\",\n evidence: [`${rootRouteIndex}:1`],\n suggestedFix: \"none\",\n confidence: \"high\",\n },\n])}\n\nValidation:\n- truthmark check`;\n};\n\nexport const renderTruthCheckProcedureBody = (\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 `# Truthmark Check\n\nUse this skill to audit repository truth health.\n\nTruth Check is agent-led:\n\n- inspect .truthmark/config.yml and configured route files only when they exist; then inspect canonical docs and relevant implementation directly\n- inspect the configured root route index at ${config.truthmark.paths.routesIndex} and relevant child route files under ${config.truthmark.paths.routeAreasRoot}/ when they exist\n- Evidence authority:\n${renderBulletBlock(EVIDENCE_AUTHORITY_INSTRUCTIONS)}\n- Lane classification:\n${renderReadOnlyLaneClassificationRuleBlock(config)}\n- check that current docs describe current code rather than historical plans\n- keep lane and cross-lane checks route-first and bounded:\n - for a narrow audit, inspect only the routed area and directly linked counterpart docs\n - for root-wide truth health, first build a cheap route-map/index from route files, then inspect only mismatches and linked leaves\n - inspect product counterparts for engineering docs only when route YAML claims a product relationship, or when the user explicitly asks for user-visible product coverage\n- check lane root/kind alignment for product truth under ${config.truthmark.paths.productTruthRoot} and engineering truth under ${config.truthmark.paths.engineeringTruthRoot}\n- check route YAML cross-lane realized_by and realizes links for existence and lane compatibility\n- report missing product links for user-visible engineering docs only as a second-pass review diagnostic, not as default full-document reads or hard errors\n- check product docs do not contain engineering execution flow, generated file inventories, or CLI envelope mechanics\n- check engineering docs do not contain product promises, product rationale, or Product Decisions sections\n- never judge whether a product decision is commercially correct, valuable, prioritized, or desirable\n- check that route files map code surfaces to canonical truth docs when route files exist\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 docs keep lane-appropriate 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};\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\n return `---\nname: truthmark-check\ndescription: ${workflow.description}\nargument-hint: Optional area, doc path, or audit focus\nuser-invocable: true\n---\n\n${renderTruthCheckProcedureBody(config, options)}\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_AUTHORING_STYLE_INSTRUCTIONS,\n TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS,\n defaultAgentConfig,\n renderBulletBlock,\n renderLaneClassificationRuleBlock,\n renderClaimEvidenceCheckedSection,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n renderRouteFirstEvidenceGateSection,\n renderHierarchySummary,\n renderTruthDocOwnershipGateSection,\n renderTruthDocRestructureGateSection,\n resolveEngineeringTruthRoot,\n} from \"./shared.js\";\n\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; Antigravity @truthmark-document; Cursor /truthmark-document.\";\n\nexport const renderTruthDocumentReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n return `Truth Document: completed\n\nImplementation reviewed:\n- src/routing/area-resolver.ts\n\nOwnership reviewed:\n- ${config.truthmark.paths.routesIndex}\n\nTruth docs created:\n- ${engineeringTruthRoot}/contracts/routing.md\n\nTruth docs updated:\n- ${engineeringTruthRoot}/behaviors/check-diagnostics.md\n\nTruth docs restructured:\n- ${engineeringTruthRoot}/behaviors/check-diagnostics.md\n\nRouting updated:\n- ${config.truthmark.paths.routesIndex}\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.truthmark.paths.routesIndex}:9`,\n ],\n result: \"supported\",\n },\n ])}\n\nNotes:\n- Documented routing and behavior from route handlers and tests.`;\n};\n\nexport const renderTruthDocumentProcedureBody = (\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 `# Truthmark Document\n\nUse this skill to document existing implemented behavior when no functional-code changes are required for the task.\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 and configured route files only when they exist; then inspect existing canonical docs, implementation code, and tests directly\n- Evidence authority:\n${renderBulletBlock(EVIDENCE_AUTHORITY_INSTRUCTIONS)}\n- Lane classification:\n${renderLaneClassificationRuleBlock(config)}\n- document current implemented behavior; do not invent future behavior or planned endpoints\n- may write canonical truth docs and ${config.truthmark.paths.routesIndex} 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- stop 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- write product capability/boundary truth under ${config.truthmark.paths.productTruthRoot} when documenting product promise, boundary, rationale, or user/stakeholder value\n- write engineering truth under ${config.truthmark.paths.engineeringTruthRoot} when documenting implementation behavior, contracts, architecture, workflows, operations, or tests\n- for both-lane documentation requests, write separate product and engineering docs and cross-link them in route YAML with realized_by and realizes, not in doc frontmatter\n- keep engineering behavior truth 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 stop 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${TRUTH_DOC_AUTHORING_STYLE_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}\nOptional validation: when local tooling is available, you may validate the final report with \\`truthmark validate document-report <report-file> --json\\`; direct checkout inspection and evidence review remain authoritative.\nParent post-document verification:\n- verify only truth docs and leased truth routing files changed during document work\n- stop 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 expected report fields before accepting it\n- verify the final report records ownership review, structure requirement, restructure, routing update, or manual handoff reason when applicable`;\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\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\n---\n\n${renderTruthDocumentProcedureBody(config, options)}\nReport completion in this shape:\n${renderMarkdownExample(renderTruthDocumentReportExample(config))}`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport { defaultAgentConfig, renderHierarchySummary } from \"./shared.js\";\nimport { getTruthmarkWorkflow } from \"./workflow-manifest.js\";\n\nexport const TRUTHMARK_PORTAL_EXPLICIT_INVOCATIONS =\n \"OpenCode /skill truthmark-portal; Codex /truthmark-portal or $truthmark-portal; Claude Code /truthmark-portal; GitHub Copilot /truthmark-portal; Antigravity @truthmark-portal; Cursor /truthmark-portal.\";\n\nexport const renderTruthmarkPortalProcedureBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const output = config.truthmark.paths.portalOutput;\n const template = config.truthmark.paths.portalTemplate;\n\n return `# Truthmark Portal\n\nTruthmark Portal is a manual-only presentation workflow. It is never an automatic completion workflow, never Truth Sync, and runs only when the user explicitly asks to generate, refresh, or update the committed static HTML Portal.\n\nCore rules:\n\n- Markdown remains canonical; generated HTML is presentation only.\n- Read Markdown directly from the checkout; the workflow does not require the truthmark CLI or package.\n- truthmark check/index may be used only as optional supporting evidence when available.\n- Determined Portal output is ${output}.\n- Determined Portal template path is ${template}; use built-in template instructions if that file is absent.\n- The workflow may replace the entire output directory, but writes are limited to the fixed Portal output directory only.\n- Portal writes are generated non-canonical static files for human browsing.\n- Generate a committed multi-page static HTML site with local CSS, JavaScript, assets, and search metadata under the output directory.\n- Use no remote dependencies by default: no remote scripts, analytics, fonts, CSS, or CDN assets.\n- Include source provenance and the Markdown canonical disclaimer on every page.\n- Store manifest and search data under output/assets only.\n- There is no .truthmark/index.json dependency; do not require or create it as infrastructure.\n- Pictures and screenshots require an explicit user or template request.\n\nWorkflow:\n\n1. Confirm the user explicitly requested Portal generation or refresh.\n2. Inspect .truthmark/config.yml and configured route docs only when they exist; read repository instruction files when present, truth docs, architecture docs, standards docs, and the determined Portal template when present.\n3. Validate the determined output path is repo-relative, non-empty, inside the repository, and does not overlap canonical docs, source roots, routing files, or instruction targets.\n4. Plan the generated page inventory, diagrams/assets, source docs reviewed, and skipped or ambiguous docs.\n5. Replace or write only under ${output}; do not edit canonical Markdown, routing, source code, or instruction files unless the user explicitly changes scope.\n6. Generate the multi-page static site with local assets/search metadata and visible source provenance.\n7. Validate entry page, links where practical, provenance/disclaimers, local-only assets, and that metadata remains under ${output}/assets.\n${renderHierarchySummary(config)}`;\n};\n\nexport const renderTruthmarkPortalSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-portal\");\n const output = config.truthmark.paths.portalOutput;\n\n return `---\nname: truthmark-portal\ndescription: ${workflow.description}\nargument-hint: Optional portal generation focus\nuser-invocable: true\n---\n\n${renderTruthmarkPortalProcedureBody(config)}\nReport completion in this shape:\n\n\\`\\`\\`md\nTruthmark Portal: completed\n\nOutput path:\n- ${output}\n\nPage count:\n- <count>\n\nDiagrams/assets:\n- <generated diagrams/assets or none>\n\nSource docs reviewed:\n- <source markdown paths>\n\nSkipped/ambiguous docs:\n- <paths and reason, or none>\n\nValidation:\n- <checks performed>\n\nMarkdown canonical statement:\n- Markdown remains canonical; generated Portal HTML is non-canonical presentation only.\n\\`\\`\\`\n`;\n};\n","import type { TruthmarkConfig } from \"../config/schema.js\";\nimport {\n DECISION_TRUTH_INSTRUCTIONS,\n EVIDENCE_AUTHORITY_INSTRUCTIONS,\n defaultAgentConfig,\n renderBulletBlock,\n renderClaudeSubagentModeSection,\n renderClaimEvidenceCheckedSection,\n renderCopilotCustomAgentModeSection,\n renderHierarchySummary,\n renderLaneClassificationRuleBlock,\n renderTopologyEvidenceGateSection,\n renderTruthDocOwnershipGateSection,\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"./shared.js\";\n\n\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; Antigravity @truthmark-structure; Cursor /truthmark-structure.\";\n\nexport const renderTruthStructureReportExample = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n\n return `Truth Structure: completed\nTopology reviewed:\n- controllers: src/auth/**\n- product docs root: ${productTruthRoot}\n- engineering docs root: ${engineeringTruthRoot}\n- route files: ${config.truthmark.paths.routesIndex}\nAreas reviewed:\n- src/auth/**\nRouting updated:\n- ${config.truthmark.paths.routesIndex}\nInitial truth boundary:\n- Area: Authentication\n- Code: src/auth/**\n- Product owner: ${productTruthRoot}/capabilities/authentication-session.md\n- Engineering owner: ${engineeringTruthRoot}/behaviors/authentication-session.md\n- Scope: session behavior only\nTruth docs created:\n- ${productTruthRoot}/capabilities/authentication-session.md\n- ${engineeringTruthRoot}/behaviors/authentication-session.md\nTruth docs split:\n- docs/truthmark/truth/authentication/README.md -> ${productTruthRoot}/capabilities/authentication-session.md and ${engineeringTruthRoot}/behaviors/authentication-session.md\nTruth docs restructured:\n- docs/truthmark/truth/authentication/README.md\n${renderClaimEvidenceCheckedSection([\n {\n claim:\n \"Session behavior belongs to a dedicated Authentication truth owner.\",\n evidence: [\"src/auth/**\", `${config.truthmark.paths.routesIndex}: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 renderTruthStructureProcedureBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n } = {},\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(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 `Use this skill to design or repair Truthmark area structure.\n\nTruth Structure is agent-native:\n- inspect repository layout, current docs, Truthmark config and route files when present, and relevant code directly\n- Evidence authority:\n${renderBulletBlock(EVIDENCE_AUTHORITY_INSTRUCTIONS)}\n- Lane classification:\n${renderLaneClassificationRuleBlock(config)}\n- inspect the configured root route index at ${config.truthmark.paths.routesIndex} and relevant child route files under ${config.truthmark.paths.routeAreasRoot}/ when they exist\n- define areas by product or behavior ownership, not by mechanical directory mirroring\n- create or repair ${config.truthmark.paths.routesIndex}\n- create skeletal starter truth docs only when missing ownership would otherwise block future workflows\n- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, truth_kind, and last_reviewed inside that frontmatter. Put source references in the final ## Source References section, not in frontmatter.\n- Starter truth docs are ownership anchors, not behavior writeups: include only the title, bounded area/scope, and Source References needed to make routing explicit.\n- Starter truth docs must keep product and engineering truth in separate files; leave substantive behavior, contract, architecture, workflow, operations, or test prose to Truth Document.\n${subagentMode}\n- use ${productTruthRoot}/** for product truth destinations\n- use ${engineeringTruthRoot}/** for engineering truth destinations\n- use only canonical current-truth destinations for starter truth docs\n- keep Product Decisions in product truth and Engineering Decisions in engineering truth when selecting destinations; report any relocation need instead of rewriting decision prose during topology review\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 stop for manual 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, lane splits, decision relocation, and relationship repair. Do not depend on humans to manually organize ${productTruthRoot} or ${engineeringTruthRoot}. Treat both configured lane roots as managed semantic roots.\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 route structure before creating or extending truth ownership anchors.\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 or reroute only the ownership topology when safe; otherwise stop with manual-review files\",\n)}\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- either configured lane 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.truthmark.paths.routeAreasRoot}/**\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 or flag mixed-owner truth docs for bounded owners before any workflow adds new behavior claims\n- create route files under ${config.truthmark.paths.routeAreasRoot}/ when a product/domain boundary is clear\n- create skeletal engineering ownership anchors under ${engineeringTruthRoot} only when behavior lacks a current owner\n- create skeletal product ownership anchors under ${productTruthRoot} only when product promise, boundary, rationale, or user-visible capability ownership is in scope\n- README.md files are indexes, not Truth Sync targets\n- prefer bounded product docs under product/capabilities or product/decisions and engineering docs under engineering/<kind>/<surface>.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${renderTopologyEvidenceGateSection()}\n- Do not finish topology repair with mixed product/engineering authority in a single canonical truth doc.\n- If an existing canonical doc has wrong-lane sections, report the lane repair needed and only move content when the topology split explicitly requires it.\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- Inspect .truthmark/config.yml and configured route files only when they exist; then inspect 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}`;\n};\n\nexport const renderTruthStructureSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n options: {\n includeClaudeSubagentMode?: boolean;\n includeCopilotCustomAgentMode?: boolean;\n } = {},\n): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-structure\");\n\n return `---\nname: truthmark-structure\ndescription: ${workflow.description}\nargument-hint: Optional area, directory, or routing concern\nuser-invocable: true\n---\n\n${renderTruthStructureProcedureBody(config, options)}\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 TruthSyncIntent = {\n changedCodeReviewed: string[];\n affectedRouteOrTruthOwner: string[];\n targetTruthDocs: string[];\n intendedUpdate: string[];\n evidenceToVerify: string[];\n userProvidedDecisionRationale: string[];\n noUpdateNeededRationale: string[];\n blockers: string[];\n};\n\nexport type TruthSyncCompletedReportInput = {\n changedCode: string[];\n syncIntent?: TruthSyncIntent;\n ownershipReviewed: string[];\n truthDocsUpdated: string[];\n decisionRationaleCaptured?: string[];\n evidenceChecked: ClaimEvidenceItem[];\n helperScripts?: string[];\n notes: string[];\n};\n\nexport type TruthSyncCompletedReport = Omit<\n TruthSyncCompletedReportInput,\n \"decisionRationaleCaptured\"\n> & {\n status: \"completed\";\n decisionRationaleCaptured: string[];\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 parseRequiredBulletSection = (source: string, title: string): string[] => {\n const section = findSection(source, title);\n\n if (!section) {\n throw new Error(`${title} section is required.`);\n }\n\n const entries = parseBulletLines(section);\n if (entries.length === 0) {\n throw new Error(`${title} must include at least one bullet.`);\n }\n\n return entries;\n};\n\nconst formatIntentValues = (values: string[]): string => values.join(\" / \");\n\nconst renderSyncIntentSection = (intent: TruthSyncIntent): string => {\n return [\n \"Sync Intent:\",\n `- Changed code reviewed: ${formatIntentValues(intent.changedCodeReviewed)}`,\n `- Affected route/truth owner: ${formatIntentValues(intent.affectedRouteOrTruthOwner)}`,\n `- Target truth docs: ${formatIntentValues(intent.targetTruthDocs)}`,\n `- Intended update: ${formatIntentValues(intent.intendedUpdate)}`,\n `- Evidence to verify: ${formatIntentValues(intent.evidenceToVerify)}`,\n `- User-provided decisions/rationale: ${formatIntentValues(intent.userProvidedDecisionRationale)}`,\n `- No-update-needed rationale: ${formatIntentValues(intent.noUpdateNeededRationale)}`,\n `- Blockers: ${formatIntentValues(intent.blockers)}`,\n ].join(\"\\n\");\n};\n\nconst parseIntentValues = (value: string): string[] => {\n return value\n .split(\" / \")\n .map((item) => item.trim())\n .filter(hasContent);\n};\n\nconst parseSyncIntentSection = (source: string): TruthSyncIntent | undefined => {\n const entries = parseOptionalBulletSection(source, \"Sync Intent\");\n\n if (entries === undefined) {\n return undefined;\n }\n\n const values = new Map<string, string>();\n for (const entry of entries) {\n const separator = entry.indexOf(\":\");\n if (separator === -1) {\n continue;\n }\n values.set(entry.slice(0, separator), entry.slice(separator + 1).trim());\n }\n\n return {\n changedCodeReviewed: parseIntentValues(values.get(\"Changed code reviewed\") ?? \"\"),\n affectedRouteOrTruthOwner: parseIntentValues(values.get(\"Affected route/truth owner\") ?? \"\"),\n targetTruthDocs: parseIntentValues(values.get(\"Target truth docs\") ?? \"\"),\n intendedUpdate: parseIntentValues(values.get(\"Intended update\") ?? \"\"),\n evidenceToVerify: parseIntentValues(values.get(\"Evidence to verify\") ?? \"\"),\n userProvidedDecisionRationale: parseIntentValues(\n values.get(\"User-provided decisions/rationale\") ?? \"\",\n ),\n noUpdateNeededRationale: parseIntentValues(values.get(\"No-update-needed rationale\") ?? \"\"),\n blockers: parseIntentValues(values.get(\"Blockers\") ?? \"\"),\n };\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 ...(input.syncIntent === undefined ? [] : [renderSyncIntentSection(input.syncIntent)]),\n renderBulletSection(\"Ownership reviewed\", input.ownershipReviewed),\n renderBulletSection(\"Truth docs updated\", input.truthDocsUpdated),\n renderBulletSection(\n \"Decision/rationale captured\",\n input.decisionRationaleCaptured ?? [\"none provided in task conversation\"],\n ),\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 const syncIntent = parseSyncIntentSection(source);\n\n return {\n status: \"completed\",\n changedCode: parseBulletSection(source, \"Changed code reviewed\"),\n ...(syncIntent === undefined ? {} : { syncIntent }),\n ownershipReviewed: parseBulletSection(source, \"Ownership reviewed\"),\n truthDocsUpdated: parseBulletSection(source, \"Truth docs updated\"),\n decisionRationaleCaptured: parseRequiredBulletSection(\n source,\n \"Decision/rationale captured\",\n ),\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 EVIDENCE_AUTHORITY_INSTRUCTIONS,\n TRUTH_DOC_AUTHORING_STYLE_INSTRUCTIONS,\n defaultAgentConfig,\n renderClaudeSubagentModeSection,\n renderCodexSubagentModeSection,\n renderCopilotCustomAgentModeSection,\n renderOpenCodeSubagentModeSection,\n renderHierarchySummary,\n renderBulletBlock,\n resolveEngineeringTruthRoot,\n} from \"./shared.js\";\nimport {\n renderTruthSyncBlockedReport,\n renderTruthSyncCompletedReport,\n} from \"../sync/report.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; Antigravity @truthmark-sync; Cursor /truthmark-sync.\";\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nconst renderTruthSyncProductDecisionRuleBlock = (\n config: TruthmarkConfig,\n): string => {\n return renderBulletBlock(\n [\n \"ask whether a user-visible promise, capability boundary, API contract, acceptance criterion, or explicit user/product evidence changed\",\n `if yes, update or route product truth under ${config.truthmark.paths.productTruthRoot} as well as engineering truth under ${config.truthmark.paths.engineeringTruthRoot}`,\n `if no, default to engineering truth under ${config.truthmark.paths.engineeringTruthRoot} for internal implementation changes`,\n \"when both lanes change, keep separate product and engineering docs cross-linked through route YAML with realized_by and realizes\",\n \"when ownership is ambiguous, stop or route to Truth Structure instead of writing a mixed document\",\n ].join(\"\\n\"),\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- inspect .truthmark/config.yml and configured route files (${config.truthmark.paths.routesIndex}; ${config.truthmark.paths.routeAreasRoot}/) only when they exist; then inspect canonical truth docs directly\n- ask whether a user-visible promise, capability boundary, API contract, acceptance criterion, or explicit user/product evidence changed\n- review the task conversation for user-provided decisions, rationale, constraints, tradeoffs, rejection reasons, or scope boundaries before writing truth docs\n- if yes, carry that user-provided decision context into Sync Intent and report where it was placed or why it needs manual handoff\n- if yes, update or route product truth as well as engineering truth; if no, default internal implementation changes to engineering truth\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- userProvidedDecisionRationale: 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- decisionRationaleCaptured: string[]\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 renderTruthSyncProcedureBody = (\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-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 `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.\nExplicit invocation runs immediately when the user directly requests this workflow. Later functional-code changes need a fresh finish-time review, and an earlier explicit run satisfies the finish-time review 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. Inspect .truthmark/config.yml and configured route files only when they exist; then inspect relevant canonical docs.\n3. Identify functional-code changes and the nearest truth docs or routing repairs.\n4. Evidence authority:\n${renderBulletBlock(EVIDENCE_AUTHORITY_INSTRUCTIONS)}\n5. Product truth decision:\n${renderTruthSyncProductDecisionRuleBlock(config)}\n6. Capture decision context from the task conversation: ask whether the user provided a product or technical decision, rationale, constraint, tradeoff, rejection reason, or scope boundary. Preserve concise user-provided decision rationale in Sync Intent before truth edits, route it to Product Decisions, Engineering Decisions, Rationale, Capability Scope, Non-Goals, Maintenance Notes, or the relevant workflow/contract section, and report whether it was placed, skipped because none was provided, or needs manual handoff.\n7. Update engineering truth first after code changes. Product truth is opt-in for externally visible promises, product boundaries, APIs, acceptance criteria, or explicit user/product evidence.\n8. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run.\n9. 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.\n10. Fill Sync Intent before editing truth docs or truth routing files:\n - Changed code reviewed: functional files, tests, configs, generated outputs, or other implementation evidence inspected\n - Affected route/truth owner: bounded route area or canonical truth owner that maps the change\n - Target truth docs: docs expected to change, or docs reviewed and left unchanged\n - Intended update: claim/doc/routing update planned before writing\n - Evidence to verify: checkout evidence that will support, narrow, remove, or record each claim for manual handoff\n - User-provided decisions/rationale: decisions, rationale, constraints, tradeoffs, rejection reasons, or scope boundaries from the current task conversation, or \"none provided\"\n - No-update-needed rationale: why mapped truth is already current when no truth doc should change\n - Blockers: missing routing, ambiguous ownership, failed verification, unavailable evidence, or off-boundary write needs\n11. Only edit allowed truth docs/routes after Sync Intent is clear; if ownership is ambiguous, repair topology first when the repair is safe and in scope, otherwise stop and recommend Truth Structure instead of guessing.\n${TRUTH_DOC_AUTHORING_STYLE_INSTRUCTIONS}\n${subagentMode}Topology review and repair:\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, run Truth Structure before syncing when topology repair is safe and in scope\n- safe in-scope topology repair may update truth routing files and create or update bounded leaf truth docs needed to map the changed functional code; keep the repair limited to the affected route owner\n- stop and recommend Truth Structure only when topology repair is unsafe, ambiguous, or outside the current task boundary\n- report the route files and changed code paths that required structure repair\n- do not create another generic truth doc\n- README.md files are indexes, not Truth Sync targets\n- must not append behavior details to a README.md index\n- write engineering truth under ${config.truthmark.paths.engineeringTruthRoot}; product truth updates under ${config.truthmark.paths.productTruthRoot} are allowed only for explicit current product behavior changes\nOptional validation tooling:\n- you may run truthmark check when local tooling is available\n- you may validate the final report with \\`truthmark validate sync-report <report-file> --json\\` when 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 only in product truth and Engineering Decisions only in engineering truth when evidence supports the lane-specific decision change\n${renderHierarchySummary(config)}\nParent post-sync verification:\n- verify only truth docs and leased truth routing files changed during sync\n- stop on any unrelated diff caused by the sync step\n- stop if functional code changed during sync\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 reviewed checkout evidence, changed-code impact, or a recorded stale-truth correction made within the sync write lease\n- verify the final report records ownership review, structure requirement, split, restructure, or manual handoff reason when the ownership review applies\n- manual handoff outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files`;\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 engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n const workflow = getTruthmarkWorkflow(\"truthmark-sync\");\n return `---\nname: truthmark-sync\ndescription: ${workflow.description}\nargument-hint: Optional changed-code area, truth-doc area, or sync focus\nuser-invocable: true\n---\n\n${renderTruthSyncProcedureBody(config, options)}\nReport completion in this shape:\n${renderMarkdownExample(\n renderTruthSyncCompletedReport({\n changedCode: [\"src/auth/session.ts\"],\n syncIntent: {\n changedCodeReviewed: [\"src/auth/session.ts\"],\n affectedRouteOrTruthOwner: [\n `${config.truthmark.paths.routeAreasRoot}/authentication.md`,\n ],\n targetTruthDocs: [`${engineeringTruthRoot}/behaviors/session-timeout.md`],\n intendedUpdate: [\"Update session timeout behavior.\"],\n evidenceToVerify: [\n \"src/auth/session.ts:12\",\n `${config.truthmark.paths.routeAreasRoot}/authentication.md:11`,\n ],\n userProvidedDecisionRationale: [\n \"User rationale: session timeout behavior changed for internal implementation consistency\",\n ],\n noUpdateNeededRationale: [\"not applicable; mapped truth is stale\"],\n blockers: [\"none\"],\n },\n ownershipReviewed: [`${config.truthmark.paths.routeAreasRoot}/authentication.md`],\n truthDocsUpdated: [`${engineeringTruthRoot}/behaviors/session-timeout.md`],\n evidenceChecked: [\n {\n claim:\n \"Session timeout behavior is documented in the bounded authentication behavior truth doc.\",\n evidence: [\n \"src/auth/session.ts:12\",\n `${config.truthmark.paths.routeAreasRoot}/authentication.md:11`,\n ],\n result: \"supported\",\n },\n ],\n decisionRationaleCaptured: [\n \"Placed user rationale in the bounded authentication behavior truth doc under Engineering Decisions/Rationale.\",\n ],\n notes: [\"Updated session timeout behavior.\"],\n }),\n)}\nBlocked report example:\n${renderMarkdownExample(\n renderTruthSyncBlockedReport({\n reason: \"Changed code maps only to the provisional bootstrap route.\",\n manualReviewFiles: [\n \"src/auth/**\",\n `${config.truthmark.paths.routeAreasRoot}/${config.truthmark.routes.defaultArea}.md`,\n ],\n nextAction: \"Run Truth Structure for src/auth/** before updating behavior truth.\",\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 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\ntype 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\ntype 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 renderCopilotCustomAgentModeSection,\n renderHierarchySummary,\n renderOpenCodeSubagentModeSection,\n renderTruthDocOwnershipGateSection,\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"../agents/shared.js\";\nimport {\n renderTruthCheckProcedureBody,\n renderTruthCheckReportExample,\n renderTruthCheckSkillBody,\n} from \"../agents/truth-check.js\";\nimport {\n renderTruthDocumentProcedureBody,\n renderTruthDocumentReportExample,\n renderTruthDocumentSkillBody,\n} from \"../agents/truth-document.js\";\nimport {\n renderTruthmarkPortalProcedureBody,\n renderTruthmarkPortalSkillBody,\n} from \"../agents/truthmark-portal.js\";\nimport {\n renderTruthStructureProcedureBody,\n renderTruthStructureReportExample,\n renderTruthStructureSkillBody,\n} from \"../agents/truth-structure.js\";\nimport {\n renderTruthSyncProcedureBody,\n renderTruthSyncSkillBody,\n} from \"../agents/truth-sync.js\";\nimport {\n renderTruthSyncBlockedReport,\n renderTruthSyncCompletedReport,\n} from \"../sync/report.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\";\n\nexport const TRUTHMARK_STRUCTURE_SKILL_PATH =\n \".agents/skills/truthmark-structure/SKILL.md\";\n\nexport const TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-structure/agents/openai.yaml\";\n\nexport const TRUTHMARK_DOCUMENT_SKILL_PATH =\n \".agents/skills/truthmark-document/SKILL.md\";\n\nexport const TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-document/agents/openai.yaml\";\n\nexport const TRUTHMARK_SYNC_SKILL_PATH =\n \".agents/skills/truthmark-sync/SKILL.md\";\n\nexport const TRUTHMARK_SYNC_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-sync/agents/openai.yaml\";\n\nexport const TRUTHMARK_REALIZE_SKILL_PATH =\n \".agents/skills/truthmark-realize/SKILL.md\";\n\nexport const TRUTHMARK_REALIZE_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-realize/agents/openai.yaml\";\n\nexport const TRUTHMARK_CHECK_SKILL_PATH =\n \".agents/skills/truthmark-check/SKILL.md\";\n\nexport const TRUTHMARK_CHECK_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-check/agents/openai.yaml\";\n\nexport const TRUTHMARK_PORTAL_SKILL_PATH =\n \".agents/skills/truthmark-portal/SKILL.md\";\n\nexport const TRUTHMARK_PORTAL_SKILL_METADATA_PATH =\n \".agents/skills/truthmark-portal/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_ANTIGRAVITY_STRUCTURE_RULE_PATH =\n \".antigravity/rules/truthmark-structure.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_DOCUMENT_RULE_PATH =\n \".antigravity/rules/truthmark-document.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_SYNC_RULE_PATH =\n \".antigravity/rules/truthmark-sync.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_REALIZE_RULE_PATH =\n \".antigravity/rules/truthmark-realize.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_CHECK_RULE_PATH =\n \".antigravity/rules/truthmark-check.md\";\n\nexport const TRUTHMARK_ANTIGRAVITY_PORTAL_RULE_PATH =\n \".antigravity/rules/truthmark-portal.md\";\n\nexport const TRUTHMARK_CURSOR_STRUCTURE_SKILL_PATH =\n \".cursor/skills/truthmark-structure/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_DOCUMENT_SKILL_PATH =\n \".cursor/skills/truthmark-document/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_SYNC_SKILL_PATH =\n \".cursor/skills/truthmark-sync/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_REALIZE_SKILL_PATH =\n \".cursor/skills/truthmark-realize/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_CHECK_SKILL_PATH =\n \".cursor/skills/truthmark-check/SKILL.md\";\n\nexport const TRUTHMARK_CURSOR_PORTAL_SKILL_PATH =\n \".cursor/skills/truthmark-portal/SKILL.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_PORTAL_PROMPT_PATH =\n \".github/prompts/truthmark-portal.prompt.md\";\n\nexport const TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH =\n \".github/agents/truth-route-auditor.md\";\n\nexport const TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH =\n \".github/agents/truth-claim-verifier.md\";\n\nexport const TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH =\n \".github/agents/truth-doc-reviewer.md\";\nexport const TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH =\n \".github/agents/truth-doc-writer.md\";\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 workflowSupportFiles = (workflowId: TruthmarkWorkflowId): string[] => {\n const workflow = getTruthmarkWorkflow(workflowId);\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const hasSubagentSupport =\n definition.parentRule !== undefined &&\n ((workflow.subagents?.length ?? 0) > 0 ||\n (workflow.writeSubagents?.length ?? 0) > 0);\n\n return [\n \"support/procedure.md\",\n \"support/report-template.md\",\n ...(hasSubagentSupport ? [\"support/subagents-and-leases.md\"] : []),\n ];\n};\n\nconst renderWorkflowCommandAdapterInstructions = (\n workflowId: TruthmarkWorkflowId,\n root: string,\n hostName: string,\n surfaceKind: \"command\" | \"prompt\",\n): string => {\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const canonicalFiles = [\"SKILL.md\", ...workflowSupportFiles(workflowId)]\n .map((supportFile) => `- ${root}/${supportFile}`)\n .join(\"\\n\");\n\n return `This ${surfaceKind} is the ${hostName} entrypoint for ${definition.title}.\n\nDo not invoke another Truthmark command from here.\n\nRead these host-local files in order only as needed:\n${canonicalFiles}\n\nIf skill entrypoints are unavailable, use the host's direct evidence-first manual fallback procedure.`;\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 | \"cursor\";\n\ntype TruthmarkSkillPackageFile = {\n path: string;\n content: string;\n};\n\ntype WorkflowPackageDefinition = {\n title: string;\n argumentHint: string;\n use: (config: TruthmarkConfig) => string;\n quickRules: (config: TruthmarkConfig) => string[];\n parentRule?: string;\n};\n\nconst routeFilesHint = (config: TruthmarkConfig): string =>\n `${config.truthmark.paths.routesIndex}; ${config.truthmark.paths.routeAreasRoot}/`;\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 use: () => \"Use this skill to design or repair Truthmark area structure.\",\n quickRules: (config) => [\n \"Follow repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n `Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then inspect 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 ],\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 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 repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n `Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then inspect 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 ],\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 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 repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n \"Skip docs-only, formatting-only, behavior-preserving renames with no truth impact, missing config, and no-code changes.\",\n `Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then inspect relevant canonical docs directly.`,\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 ],\n parentRule:\n \"Parent agent owns Truth Sync acceptance, lease validation, and final report\",\n },\n \"truthmark-realize\": {\n title: \"Truthmark Realize\",\n argumentHint:\n \"Optional truth doc path, area, or desired code behavior to realize\",\n use: () =>\n \"Use this skill only when the user explicitly asks to realize truth docs into code.\",\n quickRules: (config) => [\n \"Follow repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n `Read the source truth docs, inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist, then inspect 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 ],\n },\n \"truthmark-check\": {\n title: \"Truthmark Check\",\n argumentHint: \"Optional area, doc path, or audit focus\",\n use: () => \"Use this skill to audit repository truth health.\",\n quickRules: (config) => [\n \"Follow repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n `Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then inspect canonical docs and relevant implementation directly.`,\n \"Report issues and suggested fixes; do not silently rewrite unrelated files.\",\n ],\n parentRule: \"Parent agent owns the final Truth Check report\",\n },\n \"truthmark-portal\": {\n title: \"Truthmark Portal\",\n argumentHint: \"Optional portal generation focus\",\n use: () =>\n \"Use this skill only when the user explicitly asks to generate or refresh the committed static HTML Truthmark Portal.\",\n quickRules: (config) => [\n \"Follow repository instruction files that exist in this checkout; do not assume any optional policy path exists.\",\n \"Truthmark Portal is manual-only; never run it automatically at completion and never treat it as Truth Sync.\",\n \"Markdown remains canonical; generated HTML is non-canonical presentation only.\",\n \"Read Markdown directly; the workflow does not require the truthmark CLI or package.\",\n \"Generate committed, generated non-canonical static files for humans.\",\n `Write only under fixed Portal output ${config.truthmark.paths.portalOutput}.`,\n `Use determined Portal template ${config.truthmark.paths.portalTemplate} when present; no .truthmark/index.json dependency.`,\n \"Use no remote dependencies by default and include source provenance on every page.\",\n ],\n },\n};\n\nconst renderMarkdownExample = (content: string): string => {\n return [\"```md\", content, \"```\"].join(\"\\n\");\n};\n\nconst renderWorkflowReportTemplate = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(config);\n\n switch (workflowId) {\n case \"truthmark-structure\":\n return `Report completion in this shape:\\n${renderMarkdownExample(\n renderTruthStructureReportExample(config),\n )}`;\n case \"truthmark-document\":\n return `Report completion in this shape:\\n${renderMarkdownExample(\n renderTruthDocumentReportExample(config),\n )}`;\n case \"truthmark-sync\":\n return `Report completion in this shape:\\n${renderMarkdownExample(\n renderTruthSyncCompletedReport({\n changedCode: [\"src/auth/session.ts\"],\n syncIntent: {\n changedCodeReviewed: [\"src/auth/session.ts\"],\n affectedRouteOrTruthOwner: [\n `${config.truthmark.paths.routeAreasRoot}/authentication.md`,\n ],\n targetTruthDocs: [`${engineeringTruthRoot}/behaviors/session-timeout.md`],\n intendedUpdate: [\"Update session timeout behavior.\"],\n evidenceToVerify: [\n \"src/auth/session.ts:12\",\n `${config.truthmark.paths.routeAreasRoot}/authentication.md:11`,\n ],\n userProvidedDecisionRationale: [\n \"User rationale: session timeout behavior changed for internal implementation consistency\",\n ],\n noUpdateNeededRationale: [\"not applicable; mapped truth is stale\"],\n blockers: [\"none\"],\n },\n ownershipReviewed: [\n `${config.truthmark.paths.routeAreasRoot}/authentication.md`,\n ],\n truthDocsUpdated: [`${engineeringTruthRoot}/behaviors/session-timeout.md`],\n evidenceChecked: [\n {\n claim:\n \"Session timeout behavior is documented in the bounded authentication behavior truth doc.\",\n evidence: [\n \"src/auth/session.ts:12\",\n `${config.truthmark.paths.routeAreasRoot}/authentication.md:11`,\n ],\n result: \"supported\",\n },\n ],\n decisionRationaleCaptured: [\n \"Placed user rationale in the bounded authentication behavior truth doc under Engineering Decisions/Rationale.\",\n ],\n notes: [\"Updated session timeout behavior.\"],\n }),\n )}\\nBlocked report example:\\n${renderMarkdownExample(\n renderTruthSyncBlockedReport({\n reason: \"Changed code maps only to the provisional bootstrap route.\",\n manualReviewFiles: [\n \"src/auth/**\",\n `${config.truthmark.paths.routeAreasRoot}/${config.truthmark.routes.defaultArea}.md`,\n ],\n nextAction: \"Run Truth Structure for src/auth/** before updating behavior truth.\",\n }),\n )}`;\n case \"truthmark-realize\":\n return `Report completion in this shape:\\n\\n${renderMarkdownExample(`Truth Realize: completed\n\nTruth docs used:\n- ${productTruthRoot}/capabilities/authentication-session.md\n- ${engineeringTruthRoot}/behaviors/authentication-session.md\n\nCode updated:\n- src/auth/session.ts\n\nVerification:\n- npm test -- auth`)}`;\n case \"truthmark-check\":\n return `Report completion in this shape:\\n\\n${renderMarkdownExample(\n renderTruthCheckReportExample(config),\n )}`;\n case \"truthmark-portal\":\n return `Report completion in this shape:\\n\\n${renderMarkdownExample(`Truthmark Portal: completed\n\nOutput path:\n- ${config.truthmark.paths.portalOutput}\n\nPage count:\n- <count>\n\nDiagrams/assets:\n- <generated diagrams/assets or none>\n\nSource docs reviewed:\n- <source markdown paths>\n\nSkipped/ambiguous docs:\n- <paths and reason, or none>\n\nValidation:\n- <checks performed>\n\nMarkdown canonical statement:\n- Markdown remains canonical; generated Portal HTML is non-canonical presentation only.`)}`;\n }\n};\n\nconst renderWorkflowSupportParts = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n): { procedure: string; reportTemplate: string } => {\n return {\n procedure: renderWorkflowProcedure(workflowId, config),\n reportTemplate: renderWorkflowReportTemplate(workflowId, config),\n };\n};\n\nconst renderSkillSupportFile = (title: string, body: string): string => {\n return `# ${title}\n\nTruthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\n\n${body}\n`;\n};\n\nconst renderWorkflowProcedure = (\n workflowId: TruthmarkWorkflowId,\n config: TruthmarkConfig,\n): string => {\n switch (workflowId) {\n case \"truthmark-structure\":\n return renderTruthStructureProcedureBody(config);\n case \"truthmark-document\":\n return renderTruthDocumentProcedureBody(config);\n case \"truthmark-sync\":\n return renderTruthSyncProcedureBody(config);\n case \"truthmark-realize\":\n return renderTruthmarkRealizeProcedureBody(config);\n case \"truthmark-check\":\n return renderTruthCheckProcedureBody(config);\n case \"truthmark-portal\":\n return renderTruthmarkPortalProcedureBody(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 supportFileUsage = (supportFile: string): string => {\n if (supportFile === \"support/procedure.md\") {\n return \"read before edits or detailed auditing; contains core review questions\";\n }\n\n if (supportFile === \"support/report-template.md\") {\n return \"read before the final report\";\n }\n\n if (supportFile === \"support/subagents-and-leases.md\") {\n return \"read only when using subagents, leases, or accepting worker output\";\n }\n\n return \"available when relevant to the current step\";\n };\n const supportFileList = supportFiles\n .map((supportFile) => `- ${supportFile} — ${supportFileUsage(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 === \"cursor\"\n ? \"Use as a Cursor Agent Skill. Cursor discovers project skills under `.cursor/skills/`, selects them from the description when relevant, and supports manual `/` invocation.\"\n : undefined;\n\n return `---\nname: ${workflowId}\ndescription: ${workflow.description}\nargument-hint: ${definition.argumentHint}\nuser-invocable: true\n---\n\n# ${definition.title}\n\n${definition.use(config)}${hostUsage === undefined ? \"\" : `\\n\\n${hostUsage}`}\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 \"cursor\":\n return undefined;\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 } = renderWorkflowSupportParts(\n workflowId,\n 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, 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 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 truthDocRoots = Array.from(\n new Set([\n normalizeOpenCodePermissionPath(resolveProductTruthRoot(config)),\n normalizeOpenCodePermissionPath(resolveEngineeringTruthRoot(config)),\n ]),\n );\n const rootRouteIndex = normalizeOpenCodePermissionPath(\n config.truthmark.paths.routesIndex,\n );\n const areaFilesRoot = normalizeOpenCodePermissionPath(\n config.truthmark.paths.routeAreasRoot,\n );\n const allowedPatterns = [\n ...truthDocRoots.map((root) => appendOpenCodePermissionGlob(root, \"/**\")),\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, .github/copilot-instructions.md, .cursor/skills, .antigravity/rules, 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.\nInspect .truthmark/config.yml and route files only when they exist; then inspect mapped truth docs and relevant implementation files directly.\nUse a route-first bounded strategy: narrow audits inspect only the routed area and directly linked counterpart docs; root-wide health first builds a cheap route-map/index from route files, then inspects only mismatches and linked leaves.\nFind missing, stale, broad, overloaded, catch-all, mixed-owner, or unrouteable ownership.\nValidate route ownership against lane-specific roots and route kind:\n- confirm mapped truth docs resolve to the correct lane root (product or engineering) for their kind\n- flag mismatch between assigned route kind and resolved doc kind (for example, product-capability routed to engineering paths)\n- verify route-doc linkage for lane pairings via realized_by and realizes before recommending edits\n- inspect product counterparts for engineering docs only when route YAML claims a product relationship, or when the parent explicitly asks for user-visible product coverage\n- treat missing product links for user-visible engineering docs as a second-pass diagnostic, not a default full-document read.\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 compact frontmatter, required template sections, final Source References entries, Evidence checked entries, and lane-appropriate decision sections (Product Decisions in product truth, Engineering Decisions in engineering truth).\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 `# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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 `# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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# Truthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\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 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 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 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 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 refresh_command: \"truthmark init\"\n`;\n};\n\nconst renderTruthmarkRealizeProcedureBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return `# Truthmark Realize\n\nUse this skill only when the user explicitly asks to realize truth docs into code.\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 configured route files when present.\n2. Inspect .truthmark/config.yml and configured route files (${routeFilesHint(config)}) only when they exist; then read 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, stop 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};\n\nconst renderTruthmarkRealizeSkillBody = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n const productTruthRoot = resolveProductTruthRoot(config);\n const engineeringTruthRoot = resolveEngineeringTruthRoot(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\n---\n\n${renderTruthmarkRealizeProcedureBody(config)}\nReport completion in this shape:\n\n\\`\\`\\`md\nTruth Realize: completed\n\nTruth docs used:\n- ${productTruthRoot}/capabilities/authentication-session.md\n- ${engineeringTruthRoot}/behaviors/authentication-session.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 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 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 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 refresh_command: \"truthmark init\"\n`;\n};\n\nexport const renderTruthmarkPortalSkill = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n return renderTruthmarkPortalSkillBody(config);\n};\n\nexport const renderTruthmarkPortalSkillMetadata = (): string => {\n const workflow = getTruthmarkWorkflow(\"truthmark-portal\");\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 refresh_command: \"truthmark init\"\n`;\n};\n\nconst renderWorkflowRuleFile = ({\n workflowId,\n hostName,\n ruleName,\n config = defaultAgentConfig(),\n}: {\n workflowId: TruthmarkWorkflowId;\n hostName: string;\n ruleName: string;\n config?: TruthmarkConfig;\n}): string => {\n const workflow = getTruthmarkWorkflow(workflowId);\n const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId];\n const { procedure, reportTemplate } = renderWorkflowSupportParts(\n workflowId,\n config,\n );\n const body = `# ${definition.title}\n\nTruthmark-managed generated file. Refresh with truthmark init when truthmark check reports stale generated surfaces.\n\nThis rule is the ${hostName} entrypoint for ${definition.title}.\n\nDo not invoke another Truthmark command from here.\n\nManual invocation: @${ruleName}\n\nIf skill entrypoints are unavailable, use the host's direct evidence-first manual fallback procedure.\n\nDescription: ${workflow.description}\n\n## Procedure\n\n${procedure}\n\n## Report Template\n\n${reportTemplate}\n`;\n\n return body;\n};\n\nconst renderCopilotWorkflowPrompt = (\n workflowId: TruthmarkWorkflowId,\n root: string,\n): string => {\n const workflow = getTruthmarkWorkflow(workflowId);\n\n return renderCopilotPromptFile(\n workflow.description,\n renderWorkflowCommandAdapterInstructions(\n workflowId,\n root,\n \"GitHub Copilot\",\n \"prompt\",\n ),\n );\n};\n\nexport const renderTruthmarkAntigravityStructureRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-structure\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-structure\",\n config,\n });\n\nexport const renderTruthmarkAntigravityDocumentRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-document\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-document\",\n config,\n });\n\nexport const renderTruthmarkAntigravitySyncRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-sync\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-sync\",\n config,\n });\n\nexport const renderTruthmarkAntigravityRealizeRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-realize\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-realize\",\n config,\n });\n\nexport const renderTruthmarkAntigravityCheckRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-check\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-check\",\n config,\n });\n\nexport const renderTruthmarkAntigravityPortalRule = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string =>\n renderWorkflowRuleFile({\n workflowId: \"truthmark-portal\",\n hostName: \"Antigravity\",\n ruleName: \"truthmark-portal\",\n config,\n });\n\nexport const renderTruthmarkCopilotStructurePrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-structure\",\n \".github/skills/truthmark-structure\",\n );\n};\n\nexport const renderTruthmarkCopilotDocumentPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-document\",\n \".github/skills/truthmark-document\",\n );\n};\n\nexport const renderTruthmarkCopilotSyncPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-sync\",\n \".github/skills/truthmark-sync\",\n );\n};\n\nexport const renderTruthmarkCopilotRealizePrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-realize\",\n \".github/skills/truthmark-realize\",\n );\n};\n\nexport const renderTruthmarkCopilotCheckPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-check\",\n \".github/skills/truthmark-check\",\n );\n};\n\nexport const renderTruthmarkCopilotPortalPrompt = (\n config: TruthmarkConfig = defaultAgentConfig(),\n): string => {\n void config;\n return renderCopilotWorkflowPrompt(\n \"truthmark-portal\",\n \".github/skills/truthmark-portal\",\n );\n};\n","import {\n SUPPORTED_PLATFORMS,\n type TruthmarkConfig,\n type TruthmarkPlatform,\n} from \"../config/schema.js\";\nimport { renderAgentsBlock } from \"./agents-block.js\";\nimport {\n renderTruthmarkCopilotCheckPrompt,\n renderTruthmarkCopilotClaimVerifierAgent,\n renderTruthmarkCopilotDocumentPrompt,\n renderTruthmarkCopilotDocReviewerAgent,\n renderTruthmarkCopilotDocWriterAgent,\n renderTruthmarkCopilotPortalPrompt,\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 renderTruthmarkAntigravityCheckRule,\n renderTruthmarkAntigravityDocumentRule,\n renderTruthmarkAntigravityPortalRule,\n renderTruthmarkAntigravityRealizeRule,\n renderTruthmarkAntigravityStructureRule,\n renderTruthmarkAntigravitySyncRule,\n renderTruthmarkSkillPackage,\n renderTruthmarkCheckSkillMetadata,\n renderTruthmarkOpenCodeClaimVerifierAgent,\n renderTruthmarkOpenCodeDocReviewerAgent,\n renderTruthmarkOpenCodeDocWriterAgent,\n renderTruthmarkOpenCodeRouteAuditorAgent,\n renderTruthmarkPortalSkillMetadata,\n renderTruthmarkRealizeSkillMetadata,\n renderTruthmarkRouteAuditorAgent,\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_ANTIGRAVITY_CHECK_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_DOCUMENT_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_PORTAL_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_REALIZE_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_STRUCTURE_RULE_PATH,\n TRUTHMARK_ANTIGRAVITY_SYNC_RULE_PATH,\n TRUTHMARK_CURSOR_CHECK_SKILL_PATH,\n TRUTHMARK_CURSOR_DOCUMENT_SKILL_PATH,\n TRUTHMARK_CURSOR_PORTAL_SKILL_PATH,\n TRUTHMARK_CURSOR_REALIZE_SKILL_PATH,\n TRUTHMARK_CURSOR_STRUCTURE_SKILL_PATH,\n TRUTHMARK_CURSOR_SYNC_SKILL_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_PORTAL_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_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_PORTAL_SKILL_METADATA_PATH,\n TRUTHMARK_PORTAL_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\nexport type GeneratedSurfaceOwner =\n | {\n kind: \"platform\" | \"portal\";\n platform: TruthmarkPlatform;\n }\n | {\n kind: \"retired\";\n manualCleanupOnly: boolean;\n };\n\nexport type GeneratedSurfaceCatalogEntry = GeneratedSurface & {\n owners: GeneratedSurfaceOwner[];\n recognizedContents: string[];\n};\n\nexport const RETIRED_GENERATED_SURFACES = {\n exactPaths: [\n \"GEMINI.md\",\n \".github/prompts/truthmark-preview.prompt.md\",\n \".cursor/rules/truthmark-structure.mdc\",\n \".cursor/rules/truthmark-document.mdc\",\n \".cursor/rules/truthmark-sync.mdc\",\n \".cursor/rules/truthmark-realize.mdc\",\n \".cursor/rules/truthmark-check.mdc\",\n \".cursor/rules/truthmark-portal.mdc\",\n ],\n recursiveRoots: [\".gemini\"],\n skillRoots: [\n \".agents/skills\",\n \".opencode/skills\",\n \".claude/skills\",\n \".github/skills\",\n \".cursor/skills\",\n ],\n retiredPackages: [\"truthmark-preview\"],\n retiredPackageFiles: [\"helper-manifest.yml\", \"support/helper-policy.md\"],\n} as const;\n\nconst codexFiles = (\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n ...instructionBlockFiles([\"AGENTS.md\"], block),\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_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 if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_PORTAL_SKILL_PATH,\n workflowId: \"truthmark-portal\",\n host: \"codex\",\n config,\n }),\n {\n path: TRUTHMARK_PORTAL_SKILL_METADATA_PATH,\n content: renderTruthmarkPortalSkillMetadata(),\n },\n );\n }\n\n return files;\n};\n\nconst opencodeFiles = (\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n ...instructionBlockFiles([\"AGENTS.md\"], block),\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-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 if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: \".opencode/skills/truthmark-portal/SKILL.md\",\n workflowId: \"truthmark-portal\",\n host: \"opencode\",\n config,\n }),\n );\n }\n\n return files;\n};\n\nconst claudeFiles = (\n config: TruthmarkConfig,\n block: string,\n): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\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-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 if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: \".claude/skills/truthmark-portal/SKILL.md\",\n workflowId: \"truthmark-portal\",\n host: \"claude-code\",\n config,\n }),\n );\n }\n\n return files;\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-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_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 if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: \".github/skills/truthmark-portal/SKILL.md\",\n workflowId: \"truthmark-portal\",\n host: \"github-copilot\",\n config,\n }),\n {\n path: TRUTHMARK_COPILOT_PORTAL_PROMPT_PATH,\n content: renderTruthmarkCopilotPortalPrompt(config),\n },\n );\n }\n\n return files;\n};\n\nconst antigravityFiles = (config: TruthmarkConfig): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n {\n path: TRUTHMARK_ANTIGRAVITY_STRUCTURE_RULE_PATH,\n content: renderTruthmarkAntigravityStructureRule(config),\n },\n {\n path: TRUTHMARK_ANTIGRAVITY_DOCUMENT_RULE_PATH,\n content: renderTruthmarkAntigravityDocumentRule(config),\n },\n {\n path: TRUTHMARK_ANTIGRAVITY_SYNC_RULE_PATH,\n content: renderTruthmarkAntigravitySyncRule(config),\n },\n {\n path: TRUTHMARK_ANTIGRAVITY_CHECK_RULE_PATH,\n content: renderTruthmarkAntigravityCheckRule(config),\n },\n {\n path: TRUTHMARK_ANTIGRAVITY_REALIZE_RULE_PATH,\n content: renderTruthmarkAntigravityRealizeRule(config),\n },\n ];\n\n if (config.truthmark.generated.portal.enabled) {\n files.push({\n path: TRUTHMARK_ANTIGRAVITY_PORTAL_RULE_PATH,\n content: renderTruthmarkAntigravityPortalRule(config),\n });\n }\n\n return files;\n};\n\nconst cursorFiles = (config: TruthmarkConfig): GeneratedSurface[] => {\n const files: GeneratedSurface[] = [\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_STRUCTURE_SKILL_PATH,\n workflowId: \"truthmark-structure\",\n host: \"cursor\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_DOCUMENT_SKILL_PATH,\n workflowId: \"truthmark-document\",\n host: \"cursor\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_SYNC_SKILL_PATH,\n workflowId: \"truthmark-sync\",\n host: \"cursor\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_CHECK_SKILL_PATH,\n workflowId: \"truthmark-check\",\n host: \"cursor\",\n config,\n }),\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_REALIZE_SKILL_PATH,\n workflowId: \"truthmark-realize\",\n host: \"cursor\",\n config,\n }),\n ];\n\n if (config.truthmark.generated.portal.enabled) {\n files.push(\n ...renderTruthmarkSkillPackage({\n skillPath: TRUTHMARK_CURSOR_PORTAL_SKILL_PATH,\n workflowId: \"truthmark-portal\",\n host: \"cursor\",\n config,\n }),\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, block);\n case \"opencode\":\n return opencodeFiles(config, block);\n case \"claude-code\":\n return claudeFiles(config, block);\n case \"github-copilot\":\n return copilotFiles(config, block);\n case \"antigravity\":\n return antigravityFiles(config);\n case \"cursor\":\n return cursorFiles(config);\n }\n};\n\nexport const renderGeneratedSurfaces = (\n config: TruthmarkConfig,\n block = renderAgentsBlock(config),\n): GeneratedSurface[] => {\n const files = config.platforms.flatMap((platform) =>\n filesForPlatform(platform, config, block),\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\nexport const renderGeneratedSurfaceCatalog = (\n config: TruthmarkConfig,\n): GeneratedSurfaceCatalogEntry[] => {\n const catalog = new Map<string, GeneratedSurfaceCatalogEntry>();\n\n for (const platform of SUPPORTED_PLATFORMS) {\n const baseConfig = {\n ...config,\n platforms: [platform],\n truthmark: {\n ...config.truthmark,\n generated: { portal: { enabled: false } },\n },\n };\n const basePaths = new Set(\n renderGeneratedSurfaces(baseConfig).map(({ path }) => path),\n );\n\n for (const surface of renderGeneratedSurfaces({\n ...baseConfig,\n truthmark: {\n ...baseConfig.truthmark,\n generated: { portal: { enabled: true } },\n },\n })) {\n const owner: GeneratedSurfaceOwner = {\n kind: basePaths.has(surface.path) ? \"platform\" : \"portal\",\n platform,\n };\n const existing = catalog.get(surface.path);\n const recognizedContent = surface.content.endsWith(\"\\n\")\n ? surface.content\n : `${surface.content}\\n`;\n if (existing) {\n existing.owners.push(owner);\n if (!existing.recognizedContents.includes(recognizedContent)) {\n existing.recognizedContents.push(recognizedContent);\n }\n } else {\n catalog.set(surface.path, {\n ...surface,\n owners: [owner],\n recognizedContents: [recognizedContent],\n });\n }\n }\n }\n\n for (const retiredPath of RETIRED_GENERATED_SURFACES.exactPaths) {\n if (!catalog.has(retiredPath))\n catalog.set(retiredPath, {\n path: retiredPath,\n content: \"\",\n owners: [\n {\n kind: \"retired\",\n manualCleanupOnly:\n retiredPath === \"GEMINI.md\" || retiredPath.startsWith(\".gemini/\"),\n },\n ],\n recognizedContents: [],\n });\n }\n\n return [...catalog.values()].sort((left, right) =>\n left.path.localeCompare(right.path),\n );\n};\n","import fs from \"node:fs/promises\";\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { isSafeExactFile, resolveRepoPath } from \"../fs/paths.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { parseManagedBlock } from \"../managed-block.js\";\nimport {\n renderGeneratedSurfaceCatalog,\n renderGeneratedSurfaces,\n RETIRED_GENERATED_SURFACES,\n} from \"../templates/generated-surfaces.js\";\n\nexport type LifecycleAction =\n | \"remove-file\"\n | \"remove-managed-block\"\n | \"preserve\"\n | \"manual-review\";\n\nexport type LifecyclePlanEntry = {\n path: string;\n action: LifecycleAction;\n reason: string;\n};\n\nexport type LifecyclePlan = {\n schemaVersion: \"truthmark-lifecycle/v0\";\n mode: \"dry-run\" | \"apply\";\n entries: LifecyclePlanEntry[];\n diagnostics: Diagnostic[];\n applicable: boolean;\n applied: boolean;\n};\n\nconst plannedContents = new WeakMap<LifecyclePlan, Map<string, string>>();\nconst readFile = async (\n rootDir: string,\n filePath: string,\n): 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 throw error;\n }\n};\n\nconst listFiles = async (\n rootDir: string,\n directory: string,\n): Promise<string[]> => {\n const files: string[] = [];\n const stack = [directory];\n while (stack.length > 0) {\n const current = stack.pop()!;\n try {\n for (const entry of await fs.readdir(resolveRepoPath(rootDir, current), {\n withFileTypes: true,\n })) {\n const next = `${current}/${entry.name}`;\n if (entry.isDirectory()) stack.push(next);\n else if (entry.isFile() || entry.isSymbolicLink()) files.push(next);\n }\n } catch (error: unknown) {\n if (\n !(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")\n )\n throw error;\n }\n }\n return files;\n};\n\nconst findRetiredSurfaces = async (rootDir: string): Promise<string[]> => {\n const paths = new Set<string>();\n for (const filePath of RETIRED_GENERATED_SURFACES.exactPaths) {\n try {\n await fs.lstat(resolveRepoPath(rootDir, filePath));\n paths.add(filePath);\n } catch (error: unknown) {\n if (\n !(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")\n )\n throw error;\n }\n }\n for (const root of RETIRED_GENERATED_SURFACES.recursiveRoots)\n for (const filePath of await listFiles(rootDir, root)) paths.add(filePath);\n for (const skillRoot of RETIRED_GENERATED_SURFACES.skillRoots) {\n for (const packageName of RETIRED_GENERATED_SURFACES.retiredPackages)\n for (const filePath of await listFiles(\n rootDir,\n `${skillRoot}/${packageName}`,\n ))\n paths.add(filePath);\n let packages: string[] = [];\n try {\n packages = (\n await fs.readdir(resolveRepoPath(rootDir, skillRoot), {\n withFileTypes: true,\n })\n )\n .filter(\n (entry) => entry.isDirectory() && entry.name.startsWith(\"truthmark-\"),\n )\n .map((entry) => entry.name);\n } catch (error: unknown) {\n if (\n !(error instanceof Error && \"code\" in error && error.code === \"ENOENT\")\n )\n throw error;\n }\n for (const packageName of packages)\n for (const retiredFile of RETIRED_GENERATED_SURFACES.retiredPackageFiles) {\n const filePath = `${skillRoot}/${packageName}/${retiredFile}`;\n try {\n await fs.lstat(resolveRepoPath(rootDir, filePath));\n paths.add(filePath);\n } catch (error: unknown) {\n if (\n !(\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n )\n )\n throw error;\n }\n }\n }\n return [...paths];\n};\n\nexport const buildLifecyclePlan = async (\n rootDir: string,\n config: TruthmarkConfig,\n mode: \"dry-run\" | \"apply\",\n desired = renderGeneratedSurfaces(config),\n): Promise<LifecyclePlan> => {\n const desiredPaths = new Set(desired.map(({ path }) => path));\n const entries: LifecyclePlanEntry[] = [];\n const diagnostics: Diagnostic[] = [];\n let applicable = true;\n\n for (const surface of desired.filter(({ managedBlock }) => managedBlock)) {\n if (!(await isSafeExactFile(rootDir, surface.path, true))) {\n applicable = false;\n entries.push({\n path: surface.path,\n action: \"manual-review\",\n reason:\n \"Managed instruction destination is aliased or not a regular single-link file.\",\n });\n }\n }\n\n for (const surface of desired.filter(({ managedBlock }) => managedBlock)) {\n const content = await readFile(rootDir, surface.path);\n if (content !== null && parseManagedBlock(content).status === \"malformed\") {\n applicable = false;\n entries.push({\n path: surface.path,\n action: \"manual-review\",\n reason: \"Truthmark managed-block markers are malformed.\",\n });\n }\n }\n\n const catalog = renderGeneratedSurfaceCatalog(config);\n for (const retiredPath of await findRetiredSurfaces(rootDir)) {\n if (!catalog.some(({ path: catalogPath }) => catalogPath === retiredPath))\n catalog.push({\n path: retiredPath,\n content: \"\",\n owners: [\n {\n kind: \"retired\",\n manualCleanupOnly:\n retiredPath === \"GEMINI.md\" || retiredPath.startsWith(\".gemini/\"),\n },\n ],\n recognizedContents: [],\n });\n }\n\n for (const surface of catalog) {\n if (desiredPaths.has(surface.path)) continue;\n const content = await readFile(rootDir, surface.path);\n if (content === null) continue;\n if (!(await isSafeExactFile(rootDir, surface.path, false))) {\n applicable = false;\n entries.push({\n path: surface.path,\n action: \"manual-review\",\n reason: \"Path is not safely contained in the worktree.\",\n });\n continue;\n }\n if (surface.path === \"GEMINI.md\" || surface.path.startsWith(\".gemini/\")) {\n entries.push({\n path: surface.path,\n action: \"preserve\",\n reason: \"Gemini surfaces require manual cleanup.\",\n });\n } else if (surface.managedBlock) {\n const block = parseManagedBlock(content);\n if (block.status === \"malformed\") {\n applicable = false;\n entries.push({\n path: surface.path,\n action: \"manual-review\",\n reason: \"Truthmark managed-block markers are malformed.\",\n });\n } else if (block.status === \"valid\") {\n entries.push({\n path: surface.path,\n action: \"remove-managed-block\",\n reason: \"No configured platform owns this managed block.\",\n });\n }\n } else if (surface.recognizedContents.includes(content)) {\n entries.push({\n path: surface.path,\n action: \"remove-file\",\n reason: \"Generated file has no active platform owner.\",\n });\n } else {\n entries.push({\n path: surface.path,\n action: \"preserve\",\n reason: \"Generated path has diverged content and requires review.\",\n });\n diagnostics.push({\n category: \"generated-surface\",\n severity: \"review\",\n message: `Generated surface ${surface.path} has diverged content; preserved for manual review.`,\n file: surface.path,\n });\n }\n }\n\n entries.sort(\n (a, b) => a.path.localeCompare(b.path) || a.action.localeCompare(b.action),\n );\n if (!applicable)\n diagnostics.push({\n category: \"generated-surface\",\n severity: \"error\",\n message:\n \"Lifecycle changes were not applied because preflight found unsafe or malformed generated surfaces.\",\n });\n const plan: LifecyclePlan = {\n schemaVersion: \"truthmark-lifecycle/v0\",\n mode,\n entries,\n diagnostics,\n applicable,\n applied: false,\n };\n const contents = new Map<string, string>();\n for (const entry of entries) {\n if (\n entry.action === \"remove-file\" ||\n entry.action === \"remove-managed-block\"\n ) {\n const content = await readFile(rootDir, entry.path);\n if (content !== null) contents.set(entry.path, content);\n }\n }\n plannedContents.set(plan, contents);\n return plan;\n};\n\nexport const applyLifecyclePlan = async (\n rootDir: string,\n plan: LifecyclePlan,\n): Promise<LifecyclePlan> => {\n if (!plan.applicable || plan.mode !== \"apply\") return plan;\n const expected = plannedContents.get(plan);\n const failure = async (entry: LifecyclePlanEntry): Promise<string | null> => {\n if (\n entry.action !== \"remove-file\" &&\n entry.action !== \"remove-managed-block\"\n )\n return null;\n if (!(await isSafeExactFile(rootDir, entry.path, false)))\n return `Unsafe lifecycle target: ${entry.path}`;\n const content = await readFile(rootDir, entry.path);\n if (content === null || expected?.get(entry.path) !== content)\n return `Lifecycle target changed after planning: ${entry.path}`;\n if (\n entry.action === \"remove-managed-block\" &&\n parseManagedBlock(content).status !== \"valid\"\n )\n return `Managed block changed during removal: ${entry.path}`;\n return null;\n };\n for (const entry of plan.entries) {\n const message = await failure(entry);\n if (message)\n return {\n ...plan,\n applicable: false,\n applied: false,\n diagnostics: [\n ...plan.diagnostics,\n {\n category: \"generated-surface\",\n severity: \"error\",\n message,\n file: entry.path,\n },\n ],\n };\n }\n for (const entry of plan.entries) {\n const absolutePath = resolveRepoPath(rootDir, entry.path);\n if (entry.action === \"remove-file\") {\n const stat = await fs.lstat(absolutePath);\n if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)\n throw new Error(\n `Refusing unsafe generated file removal: ${entry.path}`,\n );\n await fs.rm(absolutePath);\n } else if (entry.action === \"remove-managed-block\") {\n const stat = await fs.lstat(absolutePath);\n if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1)\n throw new Error(`Refusing unsafe managed-block removal: ${entry.path}`);\n const content = await fs.readFile(absolutePath, \"utf8\");\n const block = parseManagedBlock(content);\n if (block.status !== \"valid\")\n throw new Error(`Managed block changed during removal: ${entry.path}`);\n const remaining = `${content.slice(0, block.start)}${content.slice(block.end)}`;\n if (remaining.trim().length === 0) await fs.rm(absolutePath);\n else await fs.writeFile(absolutePath, remaining, \"utf8\");\n }\n }\n return { ...plan, applied: true };\n};\n","import { loadConfig } from \"../config/load.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport type { CommandResult } from \"../output/diagnostic.js\";\nimport { applyLifecyclePlan, buildLifecyclePlan } from \"./lifecycle.js\";\n\nexport const runUninstall = async (\n cwd: string,\n mode: \"dry-run\" | \"apply\",\n): Promise<CommandResult> => {\n const repository = await getGitRepository(cwd);\n const loaded = await loadConfig(repository.worktreePath);\n if (!loaded.config) {\n const lifecyclePlan = {\n schemaVersion: \"truthmark-lifecycle/v0\" as const,\n mode,\n entries: [],\n diagnostics: loaded.diagnostics,\n applicable: false,\n applied: false,\n };\n return {\n command: \"uninstall\",\n summary:\n \"Truthmark uninstall requires a valid .truthmark/config.yml; no files were changed.\",\n diagnostics: loaded.diagnostics,\n data: { lifecyclePlan },\n };\n }\n const planned = await buildLifecyclePlan(\n repository.worktreePath,\n loaded.config,\n mode,\n [],\n );\n const plan = await applyLifecyclePlan(repository.worktreePath, planned);\n return {\n command: \"uninstall\",\n summary:\n mode === \"dry-run\"\n ? \"Truthmark uninstall dry run completed; no files were changed.\"\n : plan.applied\n ? \"Truthmark generated host surfaces were uninstalled; authored truth and config were preserved.\"\n : \"Truthmark uninstall was not applied.\",\n diagnostics: [...loaded.diagnostics, ...plan.diagnostics],\n data: { lifecyclePlan: plan },\n };\n};\n","import fs from \"node:fs/promises\";\n\nimport fg from \"fast-glob\";\n\nimport { loadConfig } from \"../config/load.js\";\nimport { createDefaultConfig } 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\nclass 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\nconst 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 defaultConfig = createDefaultConfig();\n const rootIndex = loadResult.config?.truthmark.paths.routesIndex ?? defaultConfig.truthmark.paths.routesIndex;\n const areaFilesRoot =\n loadResult.config?.truthmark.paths.routeAreasRoot ?? defaultConfig.truthmark.paths.routeAreasRoot;\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 checkControlledPaths = async (\n rootDir: string,\n controlledPaths: string[],\n): Promise<AuthorityCheckResult> => {\n const diagnostics: Diagnostic[] = [];\n const orderedPaths: string[] = [];\n const seenPaths = new Set<string>();\n\n for (const entry of controlledPaths) {\n if (looksLikeGlob(entry)) {\n try {\n resolveRepoPath(rootDir, entry);\n } catch {\n diagnostics.push({\n category: \"authority\",\n severity: \"error\",\n message: `Truthmark-controlled path ${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: `Truthmark-controlled 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: `Truthmark-controlled 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: `Truthmark-controlled path ${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 Truthmark-controlled 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\nexport const checkAuthority = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<AuthorityCheckResult> => {\n return checkControlledPaths(rootDir, config.truthmark.controlledPaths);\n};\n","import fs from \"node:fs/promises\";\n\nimport type { TruthmarkConfig } from \"../config/schema.js\";\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\nimport { parseFrontmatter } from \"../markdown/frontmatter.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n TRUTH_DOCUMENT_KINDS,\n laneForTruthDocumentKind,\n type TruthDocumentEntry,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\n\nconst isTruthDocumentKind = (value: string): value is TruthDocumentKind =>\n TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind);\n\nconst ROUTE_RELATIONSHIP_FRONTMATTER_FIELDS = [\n \"realized_by\",\n \"realizes\",\n \"depends_on\",\n];\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 parseFrontmatter(source, { throwOnInvalid: true });\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 const truthLane = document.frontmatter.truth_lane;\n const isTruthDocument =\n routedTruthDocument !== undefined || truthKind !== undefined;\n\n if (isTruthDocument) {\n for (const field of ROUTE_RELATIONSHIP_FRONTMATTER_FIELDS) {\n if (field in document.frontmatter) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Frontmatter field ${field} is not allowed on truth documents; author relationship metadata in fenced route YAML entries instead.`,\n file: markdownPath,\n });\n }\n }\n }\n\n if (\n truthLane !== undefined &&\n truthLane !== \"product\" &&\n truthLane !== \"engineering\"\n ) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: \"Frontmatter truth_lane must be product or engineering.\",\n file: markdownPath,\n });\n }\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 if (\n typeof truthKind === \"string\" &&\n isTruthDocumentKind(truthKind) &&\n truthLane !== undefined &&\n (truthLane === \"product\" || truthLane === \"engineering\") &&\n truthLane !== laneForTruthDocumentKind(truthKind)\n ) {\n diagnostics.push({\n category: \"frontmatter\",\n severity: \"error\",\n message: `Frontmatter truth_lane ${truthLane} must match truth_kind ${truthKind}.`,\n file: markdownPath,\n });\n }\n }\n }\n\n return diagnostics;\n};\n","import { parse } from \"yaml\";\n\nexport type ParsedFrontmatterDocument = {\n data: Record<string, unknown>;\n content: string;\n};\n\nexport type ParseFrontmatterOptions = {\n throwOnInvalid?: boolean;\n};\n\nconst openingDelimiterPattern = /^(?:\\uFEFF)?---[ \\t]*(?:\\r?\\n|$)/u;\nconst closingDelimiterPattern = /^---[ \\t]*(?:\\r?\\n|$)/mu;\n\nconst asRecord = (value: unknown): Record<string, unknown> => {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n return value as Record<string, unknown>;\n }\n\n return {};\n};\n\nexport const parseFrontmatter = (\n source: string,\n options: ParseFrontmatterOptions = {},\n): ParsedFrontmatterDocument => {\n const openingMatch = openingDelimiterPattern.exec(source);\n if (!openingMatch) {\n return {\n data: {},\n content: source.replace(/^\\uFEFF/u, \"\"),\n };\n }\n\n const bodyStart = openingMatch[0].length;\n const bodyAndContent = source.slice(bodyStart);\n const closingMatch = closingDelimiterPattern.exec(bodyAndContent);\n if (!closingMatch || typeof closingMatch.index !== \"number\") {\n return {\n data: {},\n content: source.replace(/^\\uFEFF/u, \"\"),\n };\n }\n\n const yamlSource = bodyAndContent.slice(0, closingMatch.index);\n const content = bodyAndContent.slice(closingMatch.index + closingMatch[0].length);\n let data: Record<string, unknown> = {};\n if (yamlSource.trim().length > 0) {\n try {\n data = asRecord(parse(yamlSource));\n } catch (error: unknown) {\n if (options.throwOnInvalid) {\n throw error;\n }\n data = {};\n }\n }\n\n return {\n data,\n content,\n };\n};\n","import { parseFrontmatter } from \"./frontmatter.js\";\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 = parseFrontmatter(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 { discoverRepositoryFilePaths } from \"../git/files.js\";\nimport { resolveAreaRouting } from \"../routing/area-resolver.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport {\n laneForTruthDocumentKind,\n mergeTruthDocumentEntryRelationships,\n type TruthDocumentEntry,\n} from \"../routing/areas.js\";\nimport { classifyPath, isTestPath } from \"../sync/classify.js\";\nimport {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} 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 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\nconst PRODUCT_LINK_REVIEW_KINDS = new Set([\n \"engineering-behavior\",\n \"engineering-workflow\",\n \"engineering-contract\",\n]);\n\nconst normalizeRoot = (value: string): string =>\n value.replaceAll(\"\\\\\", \"/\").replace(/\\/+$/u, \"\");\n\nconst validateLaneShape = (\n entry: TruthDocumentEntry,\n config: TruthmarkConfig,\n areaName: string,\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const productRoot = normalizeRoot(resolveProductTruthRoot(config));\n const engineeringRoot = normalizeRoot(resolveEngineeringTruthRoot(config));\n const normalizedPath = entry.path.replaceAll(\"\\\\\", \"/\");\n const expectedLane = laneForTruthDocumentKind(entry.kind);\n\n if (entry.lane !== expectedLane) {\n diagnostics.push({\n category: \"lane-shape\",\n severity: \"error\",\n message: `Truth document ${entry.path} declares ${entry.kind} in ${entry.lane} lane; ${entry.kind} belongs to the ${expectedLane} lane.`,\n area: areaName,\n file: entry.path,\n });\n }\n\n if (\n entry.lane === \"product\" &&\n !normalizedPath.startsWith(`${productRoot}/`)\n ) {\n diagnostics.push({\n category: \"lane-shape\",\n severity: \"error\",\n message: `Product truth document ${entry.path} must live under ${productRoot}.`,\n area: areaName,\n file: entry.path,\n });\n }\n\n if (\n entry.lane === \"engineering\" &&\n !normalizedPath.startsWith(`${engineeringRoot}/`)\n ) {\n diagnostics.push({\n category: \"lane-shape\",\n severity: \"error\",\n message: `Engineering truth document ${entry.path} must live under ${engineeringRoot}.`,\n area: areaName,\n file: entry.path,\n });\n }\n\n return diagnostics;\n};\n\nconst validateRelationshipTargets = (\n entries: TruthDocumentEntry[],\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const byPath = new Map(entries.map((entry) => [entry.path, entry]));\n\n for (const entry of entries) {\n for (const target of entry.realizedBy) {\n const targetEntry = byPath.get(target);\n if (!targetEntry) {\n diagnostics.push({\n category: \"traceability\",\n severity: \"error\",\n message: `Product truth document ${entry.path} declares missing engineering realization ${target}.`,\n file: entry.path,\n });\n } else if (targetEntry.lane !== \"engineering\") {\n diagnostics.push({\n category: \"traceability\",\n severity: \"error\",\n message: `Product truth document ${entry.path} realized_by target ${target} must point to engineering truth.`,\n file: entry.path,\n });\n }\n }\n\n for (const target of entry.realizes) {\n const targetEntry = byPath.get(target);\n if (!targetEntry) {\n diagnostics.push({\n category: \"traceability\",\n severity: \"error\",\n message: `Engineering truth document ${entry.path} declares missing product truth ${target}.`,\n file: entry.path,\n });\n } else if (targetEntry.lane !== \"product\") {\n diagnostics.push({\n category: \"traceability\",\n severity: \"error\",\n message: `Engineering truth document ${entry.path} realizes target ${target} must point to product truth.`,\n file: entry.path,\n });\n }\n }\n }\n\n return diagnostics;\n};\n\nconst validateMissingProductLinkReviews = (\n entries: TruthDocumentEntry[],\n reportedPaths: Set<string>,\n): Diagnostic[] => {\n const diagnostics: Diagnostic[] = [];\n const hasProductTruth = entries.some((entry) => entry.lane === \"product\");\n\n if (!hasProductTruth) {\n return diagnostics;\n }\n\n for (const entry of entries) {\n if (\n entry.lane === \"engineering\" &&\n PRODUCT_LINK_REVIEW_KINDS.has(entry.kind) &&\n entry.realizes.length === 0 &&\n !reportedPaths.has(entry.path)\n ) {\n reportedPaths.add(entry.path);\n diagnostics.push({\n category: \"traceability\",\n severity: \"review\",\n message: `User-visible engineering truth document ${entry.path} should link product truth with realizes when it implements a product capability.`,\n file: entry.path,\n });\n }\n }\n\n return diagnostics;\n};\n\nexport const checkAreas = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<AreasCheckResult> => {\n const routing = await resolveAreaRouting(rootDir, {\n rootIndex: config.truthmark.paths.routesIndex,\n areaFilesRoot: config.truthmark.paths.routeAreasRoot,\n productTruthRoot: resolveProductTruthRoot(config),\n engineeringTruthRoot: resolveEngineeringTruthRoot(config),\n });\n\n const discoveredCodeFiles = await discoverRepositoryFilePaths(\n rootDir,\n config.ignore,\n );\n const rawCodeFiles = discoveredCodeFiles.filter(\n (filePath) =>\n classifyPath(filePath, config.ignore) === \"functional-code\" &&\n !isTestPath(filePath),\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 reportedMissingProductLinkPaths = new Set<string>();\n const areaCoverage = routing.areas.map((area) => ({\n area,\n valid: true,\n patterns: [] as string[],\n }));\n const codeFiles = rawCodeFiles;\n\n const truthReferences = routing.truthDocumentReferences;\n\n for (const area of truthReferences) {\n let areaHasTruthDocumentErrors = false;\n const areaTruthDocumentEntries: TruthDocumentEntry[] = [];\n const registerTruthDocumentEntry = (\n truthDocumentEntry: TruthDocumentEntry,\n ): 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 && existingEntry.lane !== truthDocumentEntry.lane) {\n diagnostics.push({\n category: \"area-index\",\n severity: \"error\",\n message: `Truth document ${truthDocumentEntry.path} is routed with conflicting lanes ${existingEntry.lane} and ${truthDocumentEntry.lane}.`,\n area: area.name,\n file: truthDocumentEntry.path,\n });\n return false;\n }\n\n if (!existingEntry) {\n truthDocumentEntryMap.set(truthDocumentEntry.path, truthDocumentEntry);\n } else {\n truthDocumentEntryMap.set(\n truthDocumentEntry.path,\n mergeTruthDocumentEntryRelationships(\n existingEntry,\n truthDocumentEntry,\n ),\n );\n }\n\n areaTruthDocumentEntries.push(truthDocumentEntry);\n diagnostics.push(\n ...validateLaneShape(truthDocumentEntry, config, area.name),\n );\n\n return true;\n };\n\n for (const [\n truthDocumentIndex,\n truthDocument,\n ] of area.truthDocuments.entries()) {\n const routedEntry = area.truthDocumentEntries[truthDocumentIndex];\n\n if (looksLikeGlob(truthDocument)) {\n const matches = (\n await fg([truthDocument], { cwd: rootDir, onlyFiles: true })\n ).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 routedEntry &&\n !registerTruthDocumentEntry({\n ...routedEntry,\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 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) =>\n truthDocument === area.truthDocuments[index],\n ),\n );\n if (matchingArea) {\n matchingArea.valid = false;\n }\n }\n\n diagnostics.push(\n ...validateMissingProductLinkReviews(\n areaTruthDocumentEntries,\n reportedMissingProductLinkPaths,\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(\n rootDir,\n resolveRepoPath(rootDir, match),\n );\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 &&\n 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) =>\n diagnostic.category === \"area-index\" &&\n diagnostic.severity === \"review\",\n ).length;\n\n const truthDocumentEntries = [...truthDocumentEntryMap.values()];\n diagnostics.push(...validateRelationshipTargets(truthDocumentEntries));\n\n return {\n diagnostics,\n truthDocumentPaths,\n truthDocumentEntries,\n routePrecision: {\n leafAreaCount: routing.areas.length,\n broadAreaCount,\n },\n topologyPressureCount,\n };\n};\n","import fs from \"node:fs/promises\";\n\nimport { execa } from \"execa\";\nimport fg from \"fast-glob\";\nimport micromatch from \"micromatch\";\n\nimport { assertRepoContainment, resolveRepoPath } from \"../fs/paths.js\";\n\nconst defaultIgnore = [\".git/**\", \"node_modules/**\", \"dist/**\", \"build/**\"];\n\nconst normalizePath = (filePath: string): string =>\n filePath.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/u, \"\");\n\nconst isIgnoredPath = (filePath: string, ignorePatterns: string[]): boolean =>\n micromatch.isMatch(filePath, [...defaultIgnore, ...ignorePatterns]);\n\nconst gitDiscoverableFiles = async (\n rootDir: string,\n): Promise<string[] | null> => {\n try {\n const result = await execa(\n \"git\",\n [\n \"ls-files\",\n \"-z\",\n \"--cached\",\n \"--others\",\n \"--exclude-standard\",\n \"--deduplicate\",\n ],\n {\n cwd: rootDir,\n reject: false,\n stripFinalNewline: false,\n },\n );\n\n if ((result.exitCode ?? 1) !== 0) {\n return null;\n }\n\n return result.stdout\n .split(\"\\0\")\n .filter((filePath) => filePath.length > 0)\n .map(normalizePath);\n } catch {\n return null;\n }\n};\n\nconst isCurrentContainedFile = async (\n rootDir: string,\n relativePath: string,\n): Promise<boolean> => {\n try {\n const absolutePath = resolveRepoPath(rootDir, relativePath);\n await assertRepoContainment(rootDir, absolutePath);\n return (await fs.stat(absolutePath)).isFile();\n } catch {\n return false;\n }\n};\n\n/**\n * Enumerates current Git-visible regular files, with a local full-tree fallback\n * when Git enumeration is unavailable. Returned paths are normalized,\n * repository-relative, sorted, and deduplicated.\n */\nexport const discoverRepositoryFilePaths = async (\n rootDir: string,\n ignorePatterns: string[],\n): Promise<string[]> => {\n const discoveredPaths =\n (await gitDiscoverableFiles(rootDir)) ??\n (await fg([\"**/*\"], {\n cwd: rootDir,\n onlyFiles: true,\n dot: true,\n ignore: [...defaultIgnore, ...ignorePatterns],\n followSymbolicLinks: false,\n }));\n const paths = [...new Set(discoveredPaths.map(normalizePath))]\n .filter((filePath) => !isIgnoredPath(filePath, ignorePatterns))\n .sort();\n const currentPaths = await Promise.all(\n paths.map(async (filePath) => {\n return (await isCurrentContainedFile(rootDir, filePath))\n ? filePath\n : null;\n }),\n );\n\n return currentPaths.filter(\n (filePath): filePath is string => filePath !== null,\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 productTruthRoot?: string;\n engineeringTruthRoot?: string;\n};\n\ntype 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 productTruthRoot: config.productTruthRoot,\n engineeringTruthRoot: config.engineeringTruthRoot,\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 productTruthRoot: config.productTruthRoot,\n engineeringTruthRoot: config.engineeringTruthRoot,\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 path from \"node:path\";\n\nimport 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\nexport const 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 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(\".agents/skills/truthmark-\") ||\n normalizedPath.startsWith(\".claude/\") ||\n normalizedPath.startsWith(\".codex/\") ||\n normalizedPath.startsWith(\".opencode/\") ||\n normalizedPath.startsWith(\".antigravity/rules/truthmark-\") ||\n normalizedPath.startsWith(\".cursor/rules/truthmark-\") ||\n normalizedPath.startsWith(\".cursor/skills/truthmark-\") ||\n normalizedPath === \".github/copilot-instructions.md\" ||\n normalizedPath.startsWith(\".github/agents/truth-\") ||\n normalizedPath.startsWith(\".github/prompts/truthmark-\") ||\n normalizedPath.startsWith(\".github/skills/truthmark-\") ||\n normalizedPath === \"AGENTS.md\" ||\n normalizedPath === \"CLAUDE.md\"\n ) {\n return \"derived\";\n }\n\n if (\n ignorePatterns.length > 0 &&\n micromatch.isMatch(normalizedPath, ignorePatterns)\n ) {\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 laneForTruthDocumentKind,\n type TruthDocumentEntry,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\nimport {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"../truth/docs.js\";\n\nconst PRODUCT_CAPABILITY_REQUIRED_HEADINGS = [\n \"Capability Promise\",\n \"Users And Value\",\n \"Capability Scope\",\n \"Current Product Behavior\",\n \"Acceptance Criteria\",\n \"Product Decisions\",\n \"Engineering Realization Links\",\n \"Non-Goals\",\n];\nconst ENGINEERING_REQUIRED_HEADINGS = [\n \"Purpose\",\n \"Scope\",\n \"Current Implementation Behavior\",\n \"Source References\",\n \"Product Truth Links\",\n \"Maintenance Notes\",\n];\nconst FORBIDDEN_PRODUCT_HEADINGS = [\n \"Execution Flow\",\n \"Execution Model\",\n \"Generated File Inventory\",\n \"CLI Envelope Details\",\n \"Data And Control Flow\",\n];\nconst FORBIDDEN_ENGINEERING_HEADINGS = [\n \"Product Promise\",\n \"User / Stakeholder Value\",\n \"Product Decisions\",\n \"Product Rationale\",\n \"Business Boundary\",\n];\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(\n source,\n );\n};\n\nconst kindSpecificHeadingMessages = (\n source: string,\n kind: TruthDocumentKind | null,\n): string[] => {\n if (kind === null) {\n return [];\n }\n\n if (kind === \"engineering-behavior\") {\n return hasHeading(source, \"Current Implementation Behavior\")\n ? []\n : [\"Current Implementation Behavior\"];\n }\n\n if (kind === \"engineering-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 === \"engineering-architecture\") {\n return hasHeading(source, \"Boundaries\") || hasHeading(source, \"Components\")\n ? []\n : [\"Boundaries or Components\"];\n }\n\n if (kind === \"engineering-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 === \"engineering-operations\") {\n return hasHeading(source, \"Runtime Topology\") ||\n hasHeading(source, \"Configuration\")\n ? []\n : [\"Runtime Topology or Configuration\"];\n }\n\n if (kind === \"engineering-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(\n \"Fixtures And Data Model or Assertions And Invariants\",\n );\n }\n\n return missingMessages;\n }\n\n return [];\n};\n\nconst productRequiredHeadings = (kind: TruthDocumentKind | null): string[] => {\n if (kind === \"product-capability\") {\n return PRODUCT_CAPABILITY_REQUIRED_HEADINGS;\n }\n\n return PRODUCT_CAPABILITY_REQUIRED_HEADINGS;\n};\n\nconst decisionTruthGlobs = (config: TruthmarkConfig): string[] => {\n return [\n `${resolveProductTruthRoot(config)}/**/*.md`,\n `${resolveEngineeringTruthRoot(config)}/**/*.md`,\n ];\n};\n\nconst isDecisionTruthCandidate = (\n config: TruthmarkConfig,\n filePath: string,\n): boolean => {\n return (\n !filePath.endsWith(\"/README.md\") &&\n micromatch.isMatch(filePath, decisionTruthGlobs(config))\n );\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) ||\n isDecisionTruthCandidate(config, filePath),\n )\n .sort();\n\n for (const filePath of candidatePaths) {\n const source = await fs.readFile(\n resolveRepoPath(rootDir, filePath),\n \"utf8\",\n );\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\"\n ? null\n : routedTruthDocument?.kind;\n const truthKind =\n routedTruthKind ??\n (frontmatterTruthKind && isTruthDocumentKind(frontmatterTruthKind)\n ? frontmatterTruthKind\n : inferTruthDocumentKindFromPath(filePath));\n const lane =\n routedTruthDocument?.lane ??\n (truthKind\n ? laneForTruthDocumentKind(truthKind)\n : filePath.startsWith(resolveProductTruthRoot(config))\n ? \"product\"\n : \"engineering\");\n const requiredHeadings =\n lane === \"product\"\n ? productRequiredHeadings(truthKind)\n : ENGINEERING_REQUIRED_HEADINGS;\n const missingHeadings = requiredHeadings.filter(\n (heading) => !hasHeading(source, heading),\n );\n if (lane === \"engineering\") {\n missingHeadings.push(...kindSpecificHeadingMessages(source, truthKind));\n }\n const forbiddenHeadings = (\n lane === \"product\"\n ? FORBIDDEN_PRODUCT_HEADINGS\n : FORBIDDEN_ENGINEERING_HEADINGS\n ).filter((heading) => hasHeading(source, heading));\n\n if (missingHeadings.length === 0 && forbiddenHeadings.length === 0) {\n continue;\n }\n\n if (missingHeadings.length > 0) {\n diagnostics.push({\n category: \"doc-structure\",\n severity: \"review\",\n message: `Canonical ${lane} truth doc ${filePath} should include ${missingHeadings.join(\" and \")} section(s). Product truth says what must be true and why; engineering truth says how the repository currently realizes it.`,\n file: filePath,\n });\n }\n\n if (forbiddenHeadings.length > 0) {\n diagnostics.push({\n category: \"lane-drift\",\n severity: \"error\",\n message: `Canonical ${lane} truth doc ${filePath} contains wrong-lane section(s): ${forbiddenHeadings.join(\", \")}.`,\n file: filePath,\n });\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 { renderGeneratedSurfaces } from \"../templates/generated-surfaces.js\";\nimport { buildLifecyclePlan } from \"../init/lifecycle.js\";\nimport { extractManagedBlock } from \"../managed-block.js\";\n\nconst readOptionalFile = async (\n rootDir: string,\n filePath: string,\n): 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 normalizeGeneratedSurfaceContent = (\n content: string | null,\n): 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 isRetiredGeminiSurfacePath = (filePath: string): boolean =>\n filePath === \"GEMINI.md\" || filePath.startsWith(\".gemini/\");\n\nconst obsoleteGeneratedSurfaceMessage = (surfacePath: string): string => {\n if (isRetiredGeminiSurfacePath(surfacePath)) {\n return `Generated surface ${surfacePath} is obsolete; remove stale Gemini instructions manually if they are no longer wanted.`;\n }\n\n return `Generated surface ${surfacePath} is obsolete; rerun truthmark init.`;\n};\n\nexport const checkGeneratedSurfaces = async (\n rootDir: string,\n config: TruthmarkConfig,\n): Promise<Diagnostic[]> => {\n const diagnostics: Diagnostic[] = [];\n const renderedSurfaces = renderGeneratedSurfaces(config);\n\n for (const surface of renderedSurfaces) {\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\n const lifecyclePlan = await buildLifecyclePlan(\n rootDir,\n config,\n \"dry-run\",\n renderedSurfaces,\n );\n for (const entry of lifecyclePlan.entries) {\n diagnostics.push({\n category: \"generated-surface\",\n severity: entry.action === \"manual-review\" ? \"error\" : \"review\",\n message:\n entry.action === \"preserve\" &&\n (entry.path.includes(\"truthmark-preview\") ||\n entry.path.endsWith(\"helper-manifest.yml\") ||\n entry.path.endsWith(\"support/helper-policy.md\") ||\n isRetiredGeminiSurfacePath(entry.path))\n ? obsoleteGeneratedSurfaceMessage(entry.path)\n : entry.action === \"preserve\"\n ? `Generated surface ${entry.path} is inactive but was preserved: ${entry.reason}`\n : `Generated surface ${entry.path} is inactive; rerun truthmark init to reconcile it.`,\n file: entry.path,\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 type { RouteMapRoute } from \"../repo-index/types.js\";\nimport { classifyPath } from \"../sync/classify.js\";\nimport { getChangedFiles } from \"./git-diff.js\";\nimport type { ImpactOptions, ImpactRoute, ImpactSet } 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});\n\nconst changedFilePaths = (changedFile: { path: string; previousPath?: string }): string[] => {\n return [changedFile.path, ...(changedFile.previousPath ? [changedFile.previousPath] : [])];\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\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 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\n const uniqueAffectedTruthDocs = uniqueSorted(affectedTruthDocs);\n for (const test of repoIndex.tests) {\n const hintMatchesChangedFile = changedFiles.some((changedFile) =>\n changedFilePaths(changedFile).some((filePath) =>\n testHintMatchesChangedFile(test.targetHints, filePath),\n ),\n );\n\n if (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 diagnostics,\n };\n};\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { discoverRepositoryFilePaths } from \"../git/files.js\";\nimport { parseFrontmatter } from \"../markdown/frontmatter.js\";\nimport { parseMarkdownDocument } from \"../markdown/parse.js\";\nimport {\n TRUTH_DOCUMENT_KINDS,\n docTypeForTruthDocumentKind,\n laneForTruthDocumentKind,\n type TruthDocumentKind,\n} from \"../routing/areas.js\";\nimport { classifyPath, isTestPath } from \"../sync/classify.js\";\nimport { parseSourceReferences } from \"../truth/source-references.js\";\nimport type {\n RepoDocEntry,\n RepoFileEntry,\n RepoFileKind,\n RepoTestEntry,\n} 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 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\n .basename(filePath)\n .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(\n (segment) => segment === \"tests\" || segment === \"__tests__\",\n );\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 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 discoverRepoFiles = async (\n rootDir: string,\n ignore: string[],\n): Promise<{\n files: RepoFileEntry[];\n docs: RepoDocEntry[];\n tests: RepoTestEntry[];\n}> => {\n const discoveredFiles = await discoverRepositoryFilePaths(rootDir, ignore);\n const files: RepoFileEntry[] = [];\n const docs: RepoDocEntry[] = [];\n const tests: RepoTestEntry[] = [];\n\n for (const filePath of discoveredFiles) {\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 (\n error instanceof Error &&\n \"code\" in error &&\n error.code === \"ENOENT\"\n ) {\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 = parseFrontmatter(source);\n const markdown = parseMarkdownDocument(parsed.content);\n const title =\n markdown.headings.find((heading) => heading.depth === 1)?.text ?? null;\n const sourceOfTruth = parseSourceReferences(source, filePath);\n const truthKind =\n typeof parsed.data.truth_kind === \"string\"\n ? parsed.data.truth_kind\n : null;\n const derivedTruthKind = isTruthDocumentKind(truthKind)\n ? truthKind\n : null;\n\n docs.push({\n path: filePath,\n title,\n docType:\n typeof parsed.data.doc_type === \"string\"\n ? parsed.data.doc_type\n : derivedTruthKind\n ? docTypeForTruthDocumentKind(derivedTruthKind)\n : null,\n truthKind,\n truthLane:\n typeof parsed.data.truth_lane === \"string\"\n ? parsed.data.truth_lane\n : derivedTruthKind\n ? laneForTruthDocumentKind(derivedTruthKind)\n : null,\n sourceOfTruth: sourceOfTruth.sort(),\n realizedBy: [],\n realizes: [],\n dependsOn: [],\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 path from \"node:path\";\n\nimport { parseFrontmatter } from \"../markdown/frontmatter.js\";\n\nconst repoRootPrefixes = [\n \".codex/\",\n \".github/\",\n \".truthmark/\",\n \"docs/\",\n \"src/\",\n \"tests/\",\n];\nconst sourceReferencesHeadingPattern = /^##\\s+Source References\\s*$/imu;\nconst nextSecondLevelHeadingPattern = /^##\\s+/imu;\nconst bulletReferencePattern = /^\\s*[-*]\\s+(.+?)\\s*$/u;\nconst markdownLinkPattern = /^\\s*\\[[^\\]]+\\]\\(([^)]+)\\)\\s*$/u;\nconst backtickPathPattern = /^\\s*`([^`]+)`\\s*$/u;\n\nexport const normalizeSourceReferencePath = (\n truthDocPath: string,\n referencePath: string,\n): string => {\n const strippedPath = referencePath.split(\"#\")[0]?.trim() ?? \"\";\n const isRepoRelative = repoRootPrefixes.some((prefix) =>\n strippedPath.startsWith(prefix),\n );\n\n if (\n !isRepoRelative &&\n (strippedPath.startsWith(\".\") || !strippedPath.includes(\"/\"))\n ) {\n return path.posix.normalize(\n path.posix.join(path.posix.dirname(truthDocPath), strippedPath),\n );\n }\n\n return path.posix.normalize(strippedPath);\n};\n\nconst normalizeReferenceText = (value: string): string => {\n const trimmed = value.trim();\n const markdownLinkMatch = markdownLinkPattern.exec(trimmed);\n if (markdownLinkMatch) {\n return markdownLinkMatch[1]?.trim() ?? \"\";\n }\n\n const backtickMatch = backtickPathPattern.exec(trimmed);\n if (backtickMatch) {\n return backtickMatch[1]?.trim() ?? \"\";\n }\n\n return trimmed;\n};\n\nconst parseSourceReferencesSection = (content: string): string[] => {\n const headingMatch = sourceReferencesHeadingPattern.exec(content);\n if (!headingMatch || typeof headingMatch.index !== \"number\") {\n return [];\n }\n\n const sectionStart = headingMatch.index + headingMatch[0].length;\n const afterHeading = content.slice(sectionStart);\n const nextHeadingMatch = nextSecondLevelHeadingPattern.exec(afterHeading);\n const section = nextHeadingMatch\n ? afterHeading.slice(0, nextHeadingMatch.index)\n : afterHeading;\n const references: string[] = [];\n\n for (const line of section.split(\"\\n\")) {\n const bulletMatch = bulletReferencePattern.exec(line);\n if (!bulletMatch) {\n continue;\n }\n\n const reference = normalizeReferenceText(bulletMatch[1] ?? \"\");\n if (reference.length > 0 && !reference.startsWith(\"{{\")) {\n references.push(reference);\n }\n }\n\n return references;\n};\n\nexport const parseSourceReferences = (\n source: string,\n truthDocPath: string,\n): string[] => {\n const parsed = parseFrontmatter(source);\n const references = new Set<string>();\n const frontmatterSourceOfTruth = Array.isArray(parsed.data.source_of_truth)\n ? parsed.data.source_of_truth\n : [];\n\n for (const entry of frontmatterSourceOfTruth) {\n if (typeof entry === \"string\") {\n references.add(normalizeSourceReferencePath(truthDocPath, entry));\n }\n }\n\n for (const entry of parseSourceReferencesSection(parsed.content)) {\n references.add(normalizeSourceReferencePath(truthDocPath, entry));\n }\n\n return [...references].sort();\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 {\n mergeTruthDocumentEntryRelationships,\n type TruthDocumentEntry,\n} from \"../routing/areas.js\";\nimport {\n resolveEngineeringTruthRoot,\n resolveProductTruthRoot,\n} from \"../truth/docs.js\";\nimport type { RouteMap } from \"./types.js\";\n\nconst mergedEntryMap = (\n entries: TruthDocumentEntry[],\n): Map<string, TruthDocumentEntry> => {\n const byPath = new Map<string, TruthDocumentEntry>();\n\n for (const entry of entries) {\n const existingEntry = byPath.get(entry.path);\n if (\n existingEntry &&\n existingEntry.kind === entry.kind &&\n existingEntry.lane === entry.lane\n ) {\n byPath.set(\n entry.path,\n mergeTruthDocumentEntryRelationships(existingEntry, entry),\n );\n } else if (!existingEntry) {\n byPath.set(entry.path, entry);\n }\n }\n\n return byPath;\n};\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.truthmark.paths.routesIndex,\n areaFilesRoot: loadResult.config.truthmark.paths.routeAreasRoot,\n productTruthRoot: resolveProductTruthRoot(loadResult.config),\n engineeringTruthRoot: resolveEngineeringTruthRoot(loadResult.config),\n });\n\n const mergedTruthDocumentEntries = mergedEntryMap(\n routing.areas.flatMap((area) => area.truthDocumentEntries),\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 truthDocumentEntries: [\n ...new Map(\n area.truthDocumentEntries.map((entry) => [\n entry.path,\n mergedTruthDocumentEntries.get(entry.path) ?? entry,\n ]),\n ).values(),\n ].sort((left, right) => left.path.localeCompare(right.path)),\n updateTruthWhen: [...area.updateTruthWhen],\n }))\n .sort((left, right) => left.key.localeCompare(right.key)),\n diagnostics: routing.diagnostics,\n };\n};\n","import { loadConfig } from \"../config/load.js\";\nimport { getGitRepository } from \"../git/repository.js\";\nimport type { Diagnostic } from \"../output/diagnostic.js\";\nimport { discoverRepoFiles } from \"./file-tree.js\";\nimport { discoverPackageMetadata } from \"./package-metadata.js\";\nimport { buildRouteMap } from \"./route-map.js\";\nimport type { 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\n diagnostics.push(...routeMap.diagnostics);\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 routeMap,\n diagnostics,\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 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\";\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[] = [];\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 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 { 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: \"source-traceability\",\n severity: \"error\",\n message,\n file: reference.truthDocPath,\n data: {\n reference: reference.path,\n source: reference.source,\n },\n});\n\nconst parseDiagnosticFor = (truthDocPath: string, error: unknown): Diagnostic => ({\n category: \"source-traceability\",\n severity: \"error\",\n message: `Malformed evidence YAML block in ${truthDocPath}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n file: truthDocPath,\n data: {\n source: \"evidence-block\",\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 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 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 let references: EvidenceReference[];\n try {\n references = await parseEvidenceReferences(rootDir, truthDocPath);\n } catch (error) {\n diagnostics.push(parseDiagnosticFor(truthDocPath, error));\n continue;\n }\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 { parse } from \"yaml\";\n\nimport { parseFrontmatter } from \"../markdown/frontmatter.js\";\n\nimport type { EvidenceReference } from \"./types.js\";\nimport {\n normalizeSourceReferencePath,\n parseSourceReferences,\n} from \"../truth/source-references.js\";\n\nconst yamlFencePattern = /```ya?ml\\s*\\n([\\s\\S]*?)```/giu;\nconst topLevelEvidenceMarkerPattern = /^evidence\\s*:/imu;\n\nconst toEvidenceReference = (\n truthDocPath: string,\n raw: unknown,\n): EvidenceReference | null => {\n if (\n !raw ||\n typeof raw !== \"object\" ||\n !(\"path\" in raw) ||\n typeof raw.path !== \"string\"\n ) {\n return null;\n }\n\n return {\n truthDocPath,\n path: normalizeSourceReferencePath(truthDocPath, raw.path),\n symbol:\n \"symbol\" in raw && typeof raw.symbol === \"string\"\n ? raw.symbol\n : undefined,\n startLine:\n \"start_line\" in raw && typeof raw.start_line === \"number\"\n ? raw.start_line\n : undefined,\n endLine:\n \"end_line\" in raw && typeof raw.end_line === \"number\"\n ? raw.end_line\n : undefined,\n contentHash:\n \"content_hash\" in raw && typeof raw.content_hash === \"string\"\n ? raw.content_hash\n : 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 = parseFrontmatter(source);\n const references: EvidenceReference[] = [];\n\n for (const entry of parseSourceReferences(source, truthDocPath)) {\n references.push({\n truthDocPath,\n path: entry,\n source: \"source-references\",\n });\n }\n\n for (const match of parsed.content.matchAll(yamlFencePattern)) {\n const yamlBlock = match[1] ?? \"\";\n if (!topLevelEvidenceMarkerPattern.test(yamlBlock)) {\n continue;\n }\n\n const block = parse(yamlBlock) 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 { Diagnostic } from \"../output/diagnostic.js\";\n\nexport const TRUTH_HEALTH_SCORECARD_SCHEMA_VERSION = \"truthmark-scorecard/v0\" as const;\n\nexport const TRUTH_HEALTH_DIMENSION_IDS = [\n \"routing-coverage\",\n \"ownership-clarity\",\n \"source-traceability\",\n \"branch-freshness\",\n \"generated-surface-freshness\",\n \"truth-doc-structure\",\n \"decision-rationale-preservation\",\n] as const;\n\nexport type TruthHealthDimensionId = (typeof TRUTH_HEALTH_DIMENSION_IDS)[number];\n\nexport type TruthHealthDimensionStatus = \"pass\" | \"warn\" | \"fail\" | \"not-run\";\n\nexport type TruthHealthScorecardDimension = {\n id: TruthHealthDimensionId;\n status: TruthHealthDimensionStatus;\n diagnosticIndexes: number[];\n evidence?: string[];\n};\n\nexport type TruthHealthScorecard = {\n schemaVersion: typeof TRUTH_HEALTH_SCORECARD_SCHEMA_VERSION;\n dimensions: TruthHealthScorecardDimension[];\n};\n\nexport type TruthHealthScorecardContext = {\n branchFreshnessRan: boolean;\n branchFreshnessNotRunReason?: string;\n routingChecksRan?: boolean;\n ownershipChecksRan?: boolean;\n evidenceChecksRan?: boolean;\n generatedSurfaceChecksRan?: boolean;\n truthDocStructureChecksRan?: boolean;\n decisionRationaleChecksRan?: boolean;\n};\n\nconst EVIDENCE_LIMIT = 2;\n\nconst textIncludesAny = (text: string, needles: string[]): boolean => {\n const normalized = text.toLowerCase();\n return needles.some((needle) => normalized.includes(needle));\n};\n\nconst diagnosticText = (diagnostic: Diagnostic): string => {\n const dataText = diagnostic.data ? JSON.stringify(diagnostic.data) : \"\";\n return `${diagnostic.message} ${diagnostic.file ?? \"\"} ${diagnostic.area ?? \"\"} ${dataText}`;\n};\n\nconst isRouteAmbiguityDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"context-pack\" &&\n textIncludesAny(diagnosticText(diagnostic), [\n \"route\",\n \"routing\",\n \"ownership\",\n \"write boundary\",\n \"allowed write\",\n ]);\n\nconst isSourceTraceabilityDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"source-traceability\" ||\n (diagnostic.category === \"links\" &&\n textIncludesAny(diagnosticText(diagnostic), [\n \"source_of_truth\",\n \"source of truth\",\n \"source evidence\",\n \"evidence\",\n ]));\n\nconst isMarkdownShapeDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"authority\" &&\n textIncludesAny(diagnosticText(diagnostic), [\"markdown\", \"heading\", \"section\"]);\n\nconst isOwnershipFreshnessDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"freshness\" &&\n textIncludesAny(diagnosticText(diagnostic), [\n \"route\",\n \"routing\",\n \"ownership\",\n \"truth owner\",\n \"truth ownership\",\n \"affected truth document\",\n ]);\n\nconst isDecisionRationaleDiagnostic = (diagnostic: Diagnostic): boolean =>\n diagnostic.category === \"doc-structure\" &&\n textIncludesAny(diagnosticText(diagnostic), [\"product decisions\", \"rationale\"]);\n\nconst mapsToDimension = (\n diagnostic: Diagnostic,\n dimensionId: TruthHealthDimensionId,\n): boolean => {\n switch (dimensionId) {\n case \"routing-coverage\":\n return [\"config\", \"authority\", \"area-index\", \"coverage\", \"repo-index\"].includes(\n diagnostic.category,\n );\n case \"ownership-clarity\":\n return (\n [\"config\", \"area-index\", \"coverage\", \"impact\"].includes(diagnostic.category) ||\n isRouteAmbiguityDiagnostic(diagnostic) ||\n isOwnershipFreshnessDiagnostic(diagnostic)\n );\n case \"source-traceability\":\n return isSourceTraceabilityDiagnostic(diagnostic);\n case \"branch-freshness\":\n return diagnostic.category === \"freshness\";\n case \"generated-surface-freshness\":\n return diagnostic.category === \"config\" || diagnostic.category === \"generated-surface\";\n case \"truth-doc-structure\":\n return (\n diagnostic.category === \"config\" ||\n diagnostic.category === \"frontmatter\" ||\n diagnostic.category === \"links\" ||\n diagnostic.category === \"doc-structure\" ||\n isMarkdownShapeDiagnostic(diagnostic)\n );\n case \"decision-rationale-preservation\":\n return isDecisionRationaleDiagnostic(diagnostic);\n }\n};\n\nconst checkerRanForDimension = (\n dimensionId: TruthHealthDimensionId,\n context: TruthHealthScorecardContext,\n): boolean => {\n switch (dimensionId) {\n case \"routing-coverage\":\n return context.routingChecksRan ?? true;\n case \"ownership-clarity\":\n return context.ownershipChecksRan ?? true;\n case \"source-traceability\":\n return context.evidenceChecksRan ?? true;\n case \"branch-freshness\":\n return context.branchFreshnessRan;\n case \"generated-surface-freshness\":\n return context.generatedSurfaceChecksRan ?? true;\n case \"truth-doc-structure\":\n return context.truthDocStructureChecksRan ?? true;\n case \"decision-rationale-preservation\":\n return context.decisionRationaleChecksRan ?? true;\n }\n};\n\nconst statusForDiagnostics = (\n diagnostics: Diagnostic[],\n diagnosticIndexes: number[],\n checkerRan: boolean,\n): TruthHealthDimensionStatus => {\n if (diagnosticIndexes.length > 0) {\n return diagnosticIndexes.some((index) => diagnostics[index]?.severity === \"error\")\n ? \"fail\"\n : \"warn\";\n }\n\n return checkerRan ? \"pass\" : \"not-run\";\n};\n\nconst evidenceForDiagnostics = (\n diagnostics: Diagnostic[],\n diagnosticIndexes: number[],\n status: TruthHealthDimensionStatus,\n dimensionId: TruthHealthDimensionId,\n context: TruthHealthScorecardContext,\n): string[] | undefined => {\n if (status === \"pass\") {\n return undefined;\n }\n\n if (diagnosticIndexes.length === 0) {\n if (dimensionId === \"branch-freshness\") {\n return [context.branchFreshnessNotRunReason ?? \"base not supplied\"];\n }\n\n return [\"checker not run\"];\n }\n\n return diagnosticIndexes.slice(0, EVIDENCE_LIMIT).map((index) => {\n const diagnostic = diagnostics[index];\n const subject = diagnostic.file ?? diagnostic.area;\n return subject ? `${diagnostic.category}:${subject}` : diagnostic.category;\n });\n};\n\nexport const buildTruthHealthScorecard = (\n diagnostics: Diagnostic[],\n context: TruthHealthScorecardContext,\n): TruthHealthScorecard => ({\n schemaVersion: TRUTH_HEALTH_SCORECARD_SCHEMA_VERSION,\n dimensions: TRUTH_HEALTH_DIMENSION_IDS.map((dimensionId) => {\n const diagnosticIndexes = diagnostics.flatMap((diagnostic, index) =>\n mapsToDimension(diagnostic, dimensionId) ? [index] : [],\n );\n const status = statusForDiagnostics(\n diagnostics,\n diagnosticIndexes,\n checkerRanForDimension(dimensionId, context),\n );\n const evidence = evidenceForDiagnostics(\n diagnostics,\n diagnosticIndexes,\n status,\n dimensionId,\n context,\n );\n\n return {\n id: dimensionId,\n status,\n diagnosticIndexes,\n ...(evidence ? { evidence } : {}),\n };\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\";\nimport { validateEvidenceReferences } from \"../evidence/validate.js\";\nimport { buildTruthHealthScorecard } from \"./scorecard.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 const scorecard = buildTruthHealthScorecard(loadResult.diagnostics, {\n branchFreshnessRan: false,\n branchFreshnessNotRunReason: options.base ? \"config unavailable\" : \"base not supplied\",\n routingChecksRan: false,\n ownershipChecksRan: false,\n evidenceChecksRan: false,\n generatedSurfaceChecksRan: false,\n truthDocStructureChecksRan: false,\n decisionRationaleChecksRan: false,\n });\n\n return {\n command: \"check\",\n summary: summarizeDiagnostics(loadResult.diagnostics),\n diagnostics: loadResult.diagnostics,\n data: {\n branchScope,\n scorecard,\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 sourceTraceability = await validateEvidenceReferences(rootDir, areas.truthDocumentPaths);\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 ...sourceTraceability,\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 const scorecard = buildTruthHealthScorecard(diagnostics, {\n branchFreshnessRan: Boolean(freshness),\n branchFreshnessNotRunReason: options.base ? \"freshness checker skipped\" : \"base not supplied\",\n evidenceChecksRan: true,\n });\n\n return {\n command: \"check\",\n summary: summarizeDiagnostics(diagnostics),\n diagnostics,\n data: {\n branchScope,\n truthVisibility,\n scorecard,\n ...(freshness ? { impactSet: freshness.impactSet } : {}),\n },\n };\n};\n","import { execa } from \"execa\";\nimport micromatch from \"micromatch\";\n\nimport {\n TRUTHMARK_WORKFLOW_MANIFEST,\n type TruthmarkWorkflowManifestEntry,\n type TruthmarkWorkflowId,\n} from \"../agents/workflow-manifest.js\";\nimport { loadConfig } from \"../config/load.js\";\nimport { runCheck } from \"../checks/check.js\";\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 { RepoIndex } from \"../repo-index/types.js\";\nimport { buildWorkflowActionContext } from \"./action-context.js\";\nimport type {\n BuildWorkflowStateOptions,\n WorkflowApplicability,\n WorkflowActionContextData,\n WorkflowAdvisoryCard,\n WorkflowHelperValidationCommand,\n WorkflowState,\n} from \"./types.js\";\n\nconst helperCommandsFor = (\n workflow: TruthmarkWorkflowId,\n): WorkflowHelperValidationCommand[] =>\n (\n (TRUTHMARK_WORKFLOW_MANIFEST[workflow] as TruthmarkWorkflowManifestEntry)\n .helpers ?? []\n ).map((helper) => ({\n id: helper.id,\n runner: helper.runner,\n argv: [...helper.command.argv],\n optional: helper.optional,\n }));\n\nconst uniqueSorted = (values: string[]): string[] =>\n [...new Set(values.filter((value) => value.length > 0))].sort();\n\nconst isWriteCapable = (workflow: TruthmarkWorkflowId): boolean =>\n workflow !== \"truthmark-check\";\n\nconst DEFAULT_BASE_CANDIDATES = [\n \"@{upstream}\",\n \"origin/main\",\n \"main\",\n \"origin/master\",\n \"master\",\n];\n\nconst selectComparisonBase = async (\n rootDir: string,\n suppliedBase?: string,\n): Promise<string | null> => {\n if (suppliedBase) {\n return suppliedBase;\n }\n\n for (const candidate of DEFAULT_BASE_CANDIDATES) {\n const result = await execa(\n \"git\",\n [\"rev-parse\", \"--verify\", `${candidate}^{commit}`],\n {\n cwd: rootDir,\n reject: false,\n },\n );\n if ((result.exitCode ?? 1) === 0) {\n return candidate;\n }\n }\n\n return null;\n};\n\nconst routeFilesFor = (repoIndex: RepoIndex): string[] =>\n uniqueSorted(repoIndex.routeMap.routes.map((route) => route.sourcePath));\n\nconst candidateStaleTruthDocsFor = (\n repoIndex: RepoIndex,\n primaryTruthDocs: string[],\n impactSet: ImpactSet | null,\n diagnostics: Diagnostic[],\n): string[] => {\n const indexedTruthDocs = new Set(\n repoIndex.routeMap.routes.flatMap((route) => route.truthDocs),\n );\n const primary = new Set(primaryTruthDocs);\n const candidates = new Set<string>();\n const changedPaths = new Set(\n (impactSet?.changedFiles ?? []).flatMap((file) => [\n file.path,\n ...(file.previousPath ? [file.previousPath] : []),\n ]),\n );\n const docEntries = new Map(\n repoIndex.routeMap.routes\n .flatMap((route) => route.truthDocumentEntries)\n .map((entry) => [entry.path, entry]),\n );\n\n const addCandidate = (truthDoc: string): void => {\n if (indexedTruthDocs.has(truthDoc) && !primary.has(truthDoc)) {\n candidates.add(truthDoc);\n }\n };\n\n const linkedTruthDocs = (truthDoc: string): string[] => {\n const entry = docEntries.get(truthDoc);\n return uniqueSorted([\n ...(entry?.realizedBy ?? []),\n ...(entry?.realizes ?? []),\n ...(entry?.dependsOn ?? []),\n ...[...docEntries.values()]\n .filter(\n (candidate) =>\n candidate.realizedBy.includes(truthDoc) ||\n candidate.realizes.includes(truthDoc) ||\n candidate.dependsOn.includes(truthDoc),\n )\n .map((candidate) => candidate.path),\n ]);\n };\n\n for (const truthDoc of [...primary, ...changedPaths].filter((path) =>\n indexedTruthDocs.has(path),\n )) {\n for (const linkedTruthDoc of linkedTruthDocs(truthDoc)) {\n addCandidate(linkedTruthDoc);\n }\n }\n\n for (const diagnostic of diagnostics) {\n if (diagnostic.category === \"freshness\" && diagnostic.file) {\n addCandidate(diagnostic.file);\n }\n }\n\n for (const route of repoIndex.routeMap.routes) {\n if (changedPaths.has(route.sourcePath)) {\n route.truthDocs.forEach(addCandidate);\n }\n }\n\n for (const doc of repoIndex.docs) {\n if (!indexedTruthDocs.has(doc.path) || primary.has(doc.path)) {\n continue;\n }\n\n if (\n doc.sourceOfTruth.some((reference) =>\n [...changedPaths].some(\n (changedPath) =>\n reference === changedPath || micromatch.isMatch(changedPath, reference),\n ),\n )\n ) {\n candidates.add(doc.path);\n }\n }\n\n return uniqueSorted([...candidates]);\n};\n\nconst hasUnmappedFunctionalChange = (impactSet: ImpactSet | null): boolean =>\n impactSet?.diagnostics.some(\n (diagnostic) =>\n diagnostic.category === \"impact\" &&\n /not mapped to a Truthmark route|no affected truth document/u.test(\n diagnostic.message,\n ),\n ) ?? false;\n\nconst applicabilityFor = (\n workflow: TruthmarkWorkflowId,\n diagnostics: Diagnostic[],\n impactSet: ImpactSet | null,\n): WorkflowApplicability => {\n const reasons: string[] = [];\n\n if (\n diagnostics.some((diagnostic) =>\n diagnostic.message.includes(\"Missing .truthmark/config.yml\"),\n )\n ) {\n reasons.push(\"Missing .truthmark/config.yml.\");\n return {\n state: isWriteCapable(workflow)\n ? \"needs_manual_review\"\n : \"not_applicable\",\n reasons,\n };\n }\n\n if (workflow === \"truthmark-sync\" && !impactSet) {\n reasons.push(\n \"Choose a comparison base with --base <ref> when workflow status cannot infer one automatically.\",\n );\n return { state: \"needs_manual_review\", reasons };\n }\n\n if (workflow === \"truthmark-realize\" && !impactSet) {\n reasons.push(\n \"Choose a comparison base with --base <ref> so the helper can suggest bounded code-write paths.\",\n );\n return { state: \"needs_manual_review\", reasons };\n }\n\n if (hasUnmappedFunctionalChange(impactSet)) {\n reasons.push(\n \"Changed functional files need route ownership review before truth-doc suggestions are reliable.\",\n );\n return { state: \"needs_routing_review\", reasons };\n }\n\n if (diagnostics.some((diagnostic) => diagnostic.severity === \"error\")) {\n reasons.push(\n \"Existing diagnostics need manual review before using helper write suggestions.\",\n );\n return { state: \"needs_manual_review\", reasons };\n }\n\n return { state: \"ready\", reasons };\n};\n\nconst workflowCardFor = (\n workflow: TruthmarkWorkflowId,\n applicability: WorkflowApplicability,\n diagnostics: Diagnostic[],\n impactSet: ImpactSet | null,\n): WorkflowAdvisoryCard => {\n const helpers = helperCommandsFor(workflow);\n const diagnosticQuestions = diagnostics\n .filter((diagnostic) => diagnostic.severity === \"error\")\n .map((diagnostic) => diagnostic.message);\n\n return {\n affectedFiles: uniqueSorted(\n impactSet?.changedFiles.map((file) => file.path) ?? [],\n ),\n likelyRouteOwners: uniqueSorted(\n impactSet?.affectedRoutes.map((route) => route.sourcePath) ?? [],\n ),\n suggestedTruthDocs:\n applicability.state === \"needs_routing_review\"\n ? []\n : uniqueSorted(impactSet?.affectedTruthDocs ?? []),\n openQuestions: uniqueSorted([\n ...applicability.reasons,\n ...diagnosticQuestions,\n ]),\n skippedHelperStatus: helpers.map((helper) => ({\n helper: helper.id,\n status: \"skipped\" as const,\n reason:\n \"workflow status does not run optional helpers; inspect the checkout directly or run the helper manually when useful.\",\n })),\n };\n};\n\nconst contextDataFor = (\n workflow: TruthmarkWorkflowId,\n repoIndex: RepoIndex,\n config: Awaited<ReturnType<typeof loadConfig>>[\"config\"],\n impactSet: ImpactSet | null,\n diagnostics: Diagnostic[],\n): WorkflowActionContextData => {\n if (!config) {\n return {};\n }\n\n const routeFiles = routeFilesFor(repoIndex);\n const indexedTruthDocs = uniqueSorted(\n repoIndex.routeMap.routes.flatMap((route) => route.truthDocs),\n );\n const primaryTruthDocs = uniqueSorted(impactSet?.affectedTruthDocs ?? []);\n const candidateStaleTruthDocs =\n workflow === \"truthmark-sync\"\n ? candidateStaleTruthDocsFor(\n repoIndex,\n primaryTruthDocs,\n impactSet,\n diagnostics,\n )\n : [];\n const truthDocs =\n workflow === \"truthmark-sync\"\n ? uniqueSorted([...primaryTruthDocs, ...candidateStaleTruthDocs])\n : uniqueSorted(impactSet?.affectedTruthDocs ?? indexedTruthDocs);\n\n return {\n routeIndexPath: config.truthmark.paths.routesIndex,\n routeFiles,\n truthRoot: config.truthmark.paths.truthRoot,\n truthDocs,\n primaryTruthDocs:\n workflow === \"truthmark-sync\" ? primaryTruthDocs : truthDocs,\n candidateStaleTruthDocs,\n starterTruthDocs: workflow === \"truthmark-structure\" ? truthDocs : [],\n codeWritePaths:\n workflow === \"truthmark-realize\"\n ? uniqueSorted(\n impactSet?.affectedRoutes.flatMap((route) => route.codeSurface) ??\n [],\n )\n : [],\n portalEnabled: config.truthmark.generated.portal.enabled,\n portalOutputPath: config.truthmark.paths.portalOutput,\n routes: repoIndex.routeMap.routes,\n };\n};\n\nconst nextStepsFor = (\n workflow: TruthmarkWorkflowId,\n applicability: WorkflowApplicability,\n comparisonBase: string | null,\n): string[] => {\n if (applicability.state === \"needs_routing_review\") {\n return [\n \"Run Truth Structure or repair route ownership before writing truth docs.\",\n ];\n }\n\n if (\n (workflow === \"truthmark-sync\" || workflow === \"truthmark-realize\") &&\n applicability.state === \"needs_manual_review\" &&\n !comparisonBase\n ) {\n return [\n workflow === \"truthmark-sync\"\n ? \"Rerun with --base <ref> so the helper can suggest changed-file impact.\"\n : \"Rerun with --base <ref> so the helper can suggest bounded code-write paths.\",\n ];\n }\n\n return [];\n};\n\nexport const buildWorkflowState = async (\n cwd: string,\n options: BuildWorkflowStateOptions,\n): Promise<WorkflowState> => {\n const manifestEntry = TRUTHMARK_WORKFLOW_MANIFEST[options.workflow];\n if (!manifestEntry) {\n throw new Error(`Unknown Truthmark workflow: ${String(options.workflow)}`);\n }\n\n const repoIndex = await buildRepoIndex(cwd);\n const rootDir = repoIndex.repository.root;\n const loadResult = await loadConfig(rootDir);\n const comparisonBase = options.base\n ? options.base\n : options.workflow === \"truthmark-sync\"\n ? await selectComparisonBase(rootDir)\n : null;\n const impactSet = comparisonBase\n ? await buildImpactSet(rootDir, { base: comparisonBase })\n : null;\n const checkResult = await runCheck(\n cwd,\n comparisonBase ? { base: comparisonBase } : {},\n );\n const diagnostics = [\n ...loadResult.diagnostics,\n ...repoIndex.diagnostics,\n ...(impactSet?.diagnostics ?? []),\n ...checkResult.diagnostics,\n ];\n const applicability = applicabilityFor(\n options.workflow,\n diagnostics,\n impactSet,\n );\n const actionData =\n applicability.state === \"needs_manual_review\" ||\n applicability.state === \"needs_routing_review\"\n ? {}\n : contextDataFor(\n options.workflow,\n repoIndex,\n loadResult.config,\n impactSet,\n diagnostics,\n );\n\n return {\n schemaVersion: \"truthmark-workflow/v0\",\n workflow: options.workflow,\n applicability,\n actionContext: buildWorkflowActionContext(manifestEntry, actionData),\n workflowCard: workflowCardFor(\n options.workflow,\n applicability,\n diagnostics,\n impactSet,\n ),\n changedFiles: impactSet?.changedFiles ?? [],\n affectedRoutes: impactSet?.affectedRoutes ?? [],\n targetTruthDocs:\n applicability.state === \"needs_routing_review\"\n ? []\n : (impactSet?.affectedTruthDocs ?? []),\n diagnostics,\n checks: {\n reviewChecklist: [...manifestEntry.reviewQuestions],\n recommended: [...manifestEntry.positiveTriggers],\n helpers: helperCommandsFor(options.workflow),\n affectedTests: impactSet?.affectedTests ?? [],\n },\n nextSteps: nextStepsFor(options.workflow, applicability, comparisonBase),\n reportSections: [...manifestEntry.reportSections],\n };\n};\n","import type { TruthmarkWorkflowManifestEntry } from \"../agents/workflow-manifest.js\";\nimport type {\n WorkflowActionContext,\n WorkflowActionContextData,\n WorkflowActionMode,\n WorkflowHelperValidationCommand,\n} from \"./types.js\";\n\nconst uniqueSorted = (values: string[]): string[] =>\n [...new Set(values.filter((value) => value.length > 0))].sort();\n\nconst helperCommandsFor = (\n manifestEntry: TruthmarkWorkflowManifestEntry,\n): WorkflowHelperValidationCommand[] =>\n (manifestEntry.helpers ?? []).map((helper) => ({\n id: helper.id,\n runner: helper.runner,\n argv: [...helper.command.argv],\n optional: helper.optional,\n }));\n\nconst evidenceFor = (manifestEntry: TruthmarkWorkflowManifestEntry): string[] =>\n manifestEntry.reviewQuestions.filter((question) =>\n /evidence|ownership|containment/iu.test(question),\n );\n\nconst baseContext = (\n manifestEntry: TruthmarkWorkflowManifestEntry,\n mode: WorkflowActionMode,\n allowedWritePaths: string[],\n routeFiles: string[],\n primaryTruthDocs: string[],\n candidateStaleTruthDocs: string[],\n forbiddenWritePaths: string[],\n writeLeaseRequired: boolean,\n): WorkflowActionContext => ({\n mode,\n allowedWritePaths: uniqueSorted(allowedWritePaths),\n routeFiles: uniqueSorted(routeFiles),\n primaryTruthDocs: uniqueSorted(primaryTruthDocs),\n candidateStaleTruthDocs: uniqueSorted(candidateStaleTruthDocs),\n forbiddenWritePaths: uniqueSorted(forbiddenWritePaths),\n stopConditions: [\n ...manifestEntry.negativeTriggers,\n ...manifestEntry.forbiddenAdjacency,\n ],\n evidencePrompts: uniqueSorted([\n ...evidenceFor(manifestEntry),\n ...(candidateStaleTruthDocs.length > 0\n ? [\n \"Record checkout evidence and the reason before touching a candidate stale truth doc outside primaryTruthDocs.\",\n ]\n : []),\n ]),\n helperValidationCommands: helperCommandsFor(manifestEntry),\n writeLeaseRequired,\n});\n\nexport const buildWorkflowActionContext = (\n manifestEntry: TruthmarkWorkflowManifestEntry,\n data: WorkflowActionContextData = {},\n): WorkflowActionContext => {\n if (manifestEntry.id === \"truthmark-check\") {\n return baseContext(manifestEntry, \"read-only\", [], [], [], [], [], false);\n }\n\n if (\n manifestEntry.id === \"truthmark-sync\" ||\n manifestEntry.id === \"truthmark-document\"\n ) {\n const routeFiles = data.routeFiles ?? [];\n const primaryTruthDocs = data.primaryTruthDocs ?? data.truthDocs ?? [];\n const candidateStaleTruthDocs = data.candidateStaleTruthDocs ?? [];\n return baseContext(\n manifestEntry,\n \"truth-doc-write\",\n [\n ...(data.routeIndexPath ? [data.routeIndexPath] : []),\n ...routeFiles,\n ...primaryTruthDocs,\n ...candidateStaleTruthDocs,\n ],\n routeFiles,\n primaryTruthDocs,\n candidateStaleTruthDocs,\n [],\n true,\n );\n }\n\n if (manifestEntry.id === \"truthmark-structure\") {\n return baseContext(\n manifestEntry,\n \"route-write\",\n [\n ...(data.routeIndexPath ? [data.routeIndexPath] : []),\n ...(data.routeFiles ?? []),\n ...(data.starterTruthDocs ?? []),\n ],\n data.routeFiles ?? [],\n data.starterTruthDocs ?? [],\n [],\n [],\n true,\n );\n }\n\n if (manifestEntry.id === \"truthmark-realize\") {\n return baseContext(\n manifestEntry,\n \"code-write\",\n data.codeWritePaths ?? [],\n data.routeFiles ?? [],\n data.truthDocs ?? [],\n [],\n [\n ...(data.routeIndexPath ? [data.routeIndexPath] : []),\n ...(data.routeFiles ?? []),\n ...(data.truthRoot ? [`${data.truthRoot}/**/*.md`] : []),\n ...(data.truthDocs ?? []),\n ],\n false,\n );\n }\n\n return baseContext(\n manifestEntry,\n \"portal-write\",\n data.portalEnabled && data.portalOutputPath\n ? [`${data.portalOutputPath}/**`]\n : [],\n [],\n [],\n [],\n [],\n false,\n );\n};\n","import {\n runConfig as runRepositoryConfig,\n type ConfigCommandOptions,\n} from \"../config/command.js\";\nimport { runInit as runRepositoryInit } from \"../init/init.js\";\nimport { runUninstall as runRepositoryUninstall } from \"../init/uninstall.js\";\nimport { runCheck as runRepositoryCheck } from \"../checks/check.js\";\nimport type { CommandResult } from \"../output/diagnostic.js\";\nimport { buildImpactSet } from \"../impact/build.js\";\nimport {\n TRUTHMARK_WORKFLOW_IDS,\n type TruthmarkWorkflowId,\n} from \"../agents/workflow-manifest.js\";\nimport { buildWorkflowState } from \"../workflow-state/build.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 (\n options: ConfigCommandOptions,\n): 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 runUninstall = async (\n mode: \"dry-run\" | \"apply\",\n): Promise<CommandResult> => {\n return runRepositoryUninstall(process.cwd(), mode);\n};\n\nexport const runCheck = async (\n options: { base?: string } = {},\n): 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(\n (diagnostic) => diagnostic.severity === \"error\",\n ).length;\n const reviewCount = repoIndex.diagnostics.filter(\n (diagnostic) => diagnostic.severity === \"review\",\n ).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: {\n base?: string;\n}): 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(\n (diagnostic) => diagnostic.severity === \"error\",\n ).length;\n const reviewCount = impactSet.diagnostics.filter(\n (diagnostic) => diagnostic.severity === \"review\",\n ).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 isTruthmarkWorkflowId = (\n value: unknown,\n): value is TruthmarkWorkflowId => {\n return (\n typeof value === \"string\" &&\n TRUTHMARK_WORKFLOW_IDS.includes(value as TruthmarkWorkflowId)\n );\n};\n\nconst invalidWorkflowResult = (\n command: \"workflow status\",\n workflow: string | undefined,\n): CommandResult => ({\n command,\n summary: workflow\n ? `Truthmark workflow requires a supported full workflow ID; received ${workflow}.`\n : \"Truthmark workflow requires --workflow.\",\n diagnostics: [\n {\n category: \"workflow-state\",\n severity: \"error\",\n message: workflow\n ? `Unknown Truthmark workflow: ${workflow}. Use a canonical full manifest ID such as truthmark-sync or truthmark-check.`\n : `truthmark ${command} requires --workflow <workflow>.`,\n },\n ],\n data: {\n request: workflow ? { workflow } : {},\n },\n});\n\nconst readHelperFile = async (\n filePath: string,\n helper: string,\n): 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\"\n ? validateTruthDocumentReportText(text)\n : 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(\n changedFilesFile,\n \"validate-write-lease\",\n );\n if (typeof changedText !== \"string\") {\n return changedText;\n }\n\n return validateWriteLeaseText(leaseText, changedText);\n};\n\nexport const runWorkflowStatus = async (options: {\n workflow?: string;\n base?: string;\n}): Promise<CommandResult> => {\n if (!isTruthmarkWorkflowId(options.workflow)) {\n return invalidWorkflowResult(\"workflow status\", options.workflow);\n }\n\n const workflowState = await buildWorkflowState(process.cwd(), {\n workflow: options.workflow,\n ...(options.base ? { base: options.base } : {}),\n });\n\n return {\n command: \"workflow status\",\n summary: `Truthmark workflow status completed for ${options.workflow}.`,\n diagnostics: workflowState.diagnostics,\n data: {\n request: {\n workflow: options.workflow,\n ...(options.base ? { base: options.base } : {}),\n },\n workflowState,\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 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 && requiredHelpers.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 [\"Decision/rationale captured\", report.decisionRationaleCaptured],\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 const completedTargets = [\n ...report.truthDocsUpdated,\n ...(report.syncIntent?.targetTruthDocs ?? []),\n ];\n const bootstrapTargets = completedTargets.filter(isBootstrapRoutingDocPath);\n if (bootstrapTargets.length > 0) {\n errors.push(\n `bootstrap-routing.md is a provisional topology handoff, not a completed behavior-update target: ${bootstrapTargets.join(\", \")}`,\n );\n }\n\n if (report.syncIntent !== undefined) {\n checks.push(\"Sync Intent\");\n }\n\n validateHelperScriptEntries(report.helperScripts, [], errors, checks);\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 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, [], 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 isBootstrapRoutingDocPath = (value: string): boolean =>\n normalizePath(value).endsWith(\"/bootstrap-routing.md\");\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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;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,I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F;AAEF;AAAA,IACE,SACG,QAAQ,aAAa,EACrB,YAAY,oCAAoC,EAChD,SAAS,iBAAiB,wBAAwB;AAAA,EACvD,EAAE,OAAO,OAAO,YAAoB,YAA2B;AAC7D;AAAA,MACE;AAAA,MACA,MAAM,sBAAsB,UAAU;AAAA,MACtC;AAAA,IACF;AAAA,EACF,CAAC;AAED;AAAA,IACE,SACG,QAAQ,iBAAiB,EACzB,YAAY,wCAAwC,EACpD,SAAS,iBAAiB,4BAA4B;AAAA,EAC3D,EAAE,OAAO,OAAO,YAAoB,YAA2B;AAC7D;AAAA,MACE;AAAA,MACA,MAAM,0BAA0B,UAAU;AAAA,MAC1C;AAAA,IACF;AAAA,EACF,CAAC;AAED;AAAA,IACE,SACG,QAAQ,aAAa,EACrB;AAAA,MACC;AAAA,IACF,EACC,SAAS,0BAA0B,6BAA6B,EAChE,SAAS,wBAAwB,qCAAqC;AAAA,EAC3E,EAAE;AAAA,IACA,OACE,mBACA,kBACA,YACG;AACH;AAAA,QACE;AAAA,QACA,MAAM,sBAAsB,mBAAmB,gBAAgB;AAAA,QAC/D;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;;;A2D3QO,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","path","parse","path","CONFIG_PATH","fs","parse","truthRoot","fs","truthRoot","fs","path","path","fs","fs","path","path","fs","fs","fs","fs","fg","fs","fg","fs","parse","isTruthDocumentKind","fs","fs","path","pathExists","fs","path","fs","fg","micromatch","fs","execa","fg","micromatch","micromatch","execa","fs","fg","fs","fg","micromatch","micromatch","fs","fg","path","micromatch","normalizePath","looksLikeGlob","pathExists","fs","fg","micromatch","fs","micromatch","isTruthDocumentKind","micromatch","fs","fs","fs","path","micromatch","fs","path","path","path","path","isTruthDocumentKind","fs","fs","path","fg","execa","fs","path","execa","normalizePath","execa","pathExists","fs","path","normalizePath","execa","uniqueSorted","micromatch","pathSegments","path","fs","fg","fs","path","parse","fs","path","parse","pathExists","fs","fg","scorecard","execa","micromatch","uniqueSorted","helperCommandsFor","uniqueSorted","execa","path","micromatch","fs","parseYaml","normalizePath","parseYaml","runConfig","runInit","runUninstall","runCheck","fs","runConfig","runInit","runUninstall","runCheck"]}
|