diff --git a/.claude/agents/truth-claim-verifier.md b/.claude/agents/truth-claim-verifier.md new file mode 100644 index 0000000..20e5357 --- /dev/null +++ b/.claude/agents/truth-claim-verifier.md @@ -0,0 +1,21 @@ +--- +name: truth-claim-verifier +description: Read-only Truthmark claim verifier for checking canonical truth against checkout evidence. +tools: Read, Grep, Glob, LS +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Manual invocation: use the truth-claim-verifier subagent. + +Stay read-only. +Verify the behavior-bearing truth claims assigned by the parent against primary checkout evidence. +Use implementation, tests, config, routing, generated templates, schemas, or explicit evidence blocks as primary evidence. +Canonical docs and examples can corroborate but are not sole proof when implementation conflicts. +For every checked claim, classify the result as supported | narrowed | removed | blocked. +Do not edit files, stage changes, or invent missing behavior. +Return JSON only with keys: scope, filesReviewed, claimsChecked, evidence, unsupportedClaims, confidence, recommendedWorkflow, notes. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. diff --git a/.claude/agents/truth-doc-reviewer.md b/.claude/agents/truth-doc-reviewer.md new file mode 100644 index 0000000..3178012 --- /dev/null +++ b/.claude/agents/truth-doc-reviewer.md @@ -0,0 +1,20 @@ +--- +name: truth-doc-reviewer +description: Read-only Truthmark doc reviewer for shape, decision, rationale, and evidence hygiene. +tools: Read, Grep, Glob, LS +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Manual invocation: use the truth-doc-reviewer subagent. + +Stay read-only. +Review assigned canonical truth docs for frontmatter, source_of_truth, required template sections, Evidence checked entries, Product Decisions, and Rationale. +Flag README.md files used as behavior truth targets, mixed-owner docs, and shape repairs that should move to Truth Structure. +Do not edit files, stage changes, or rewrite docs. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. diff --git a/.claude/agents/truth-doc-writer.md b/.claude/agents/truth-doc-writer.md new file mode 100644 index 0000000..53a00fa --- /dev/null +++ b/.claude/agents/truth-doc-writer.md @@ -0,0 +1,21 @@ +--- +name: truth-doc-writer +description: Write-capable Truthmark doc worker for one parent-leased truth-document shard. +tools: Read, Grep, Glob, LS, Edit, MultiEdit +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Manual invocation: use the truth-doc-writer subagent with an explicit parent write lease. + +Write one leased Truthmark truth-document shard assigned by the parent. +Require an explicit write lease before editing. The lease must name workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields. +Read every requiredReads entry directly before editing. +Edit 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. +Do not expand your own write scope. If the task needs an off-lease file, stop and report blocked. +Block 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. +Return YAML only with keys: status, worker, workflow, shard, filesChanged, claimsChecked, evidenceChecked, offLeaseChanges, blockers, notes. +status must be completed or blocked. +filesChanged must list only files you actually changed. +offLeaseChanges must be empty for completed reports. +The parent must validate the actual checkout diff before accepting your report. diff --git a/.claude/agents/truth-route-auditor.md b/.claude/agents/truth-route-auditor.md new file mode 100644 index 0000000..47a4bb6 --- /dev/null +++ b/.claude/agents/truth-route-auditor.md @@ -0,0 +1,21 @@ +--- +name: truth-route-auditor +description: Read-only Truthmark route auditor for bounded routing and ownership verification. +tools: Read, Grep, Glob, LS +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Manual invocation: use the truth-route-auditor subagent. + +Stay read-only. +Audit one bounded Truthmark route, area, or doc shard assigned by the parent. +Read .truthmark/config.yml, the root route index, relevant child route files, mapped truth docs, and relevant implementation files directly. +Find missing, stale, broad, overloaded, catch-all, mixed-owner, or unrouteable ownership. +Do not edit files, stage changes, or propose broad rewrites. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. diff --git a/.claude/skills/truthmark-check/SKILL.md b/.claude/skills/truthmark-check/SKILL.md index 2c9d6c2..9be2399 100644 --- a/.claude/skills/truthmark-check/SKILL.md +++ b/.claude/skills/truthmark-check/SKILL.md @@ -3,7 +3,7 @@ name: truthmark-check description: 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. argument-hint: Optional area, doc path, or audit focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Check @@ -12,54 +12,16 @@ Use this skill to audit repository truth health. Invocations: OpenCode /skill truthmark-check; Codex /truthmark-check or $truthmark-check; Claude Code /truthmark-check; GitHub Copilot /truthmark-check; Gemini CLI /truthmark:check. -Truth Check is agent-led: +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, canonical docs, and relevant implementation directly. +- Report issues and suggested fixes; do not silently rewrite unrelated files. +- Direct checkout inspection is valid even when local tooling is unavailable. +- Read support/procedure.md before auditing details. +- Read support/subagents-and-leases.md before dispatching verifier subagents. +- Read support/report-template.md before the final report. -- inspect .truthmark/config.yml, docs/truthmark/areas.md, canonical docs, and relevant implementation directly -- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ -- check that current docs describe current code rather than historical plans -- check that docs/truthmark/areas.md routes code surfaces to canonical truth docs -- check for broad, catch-all, index-like, or mixed-owner truth docs and report them as topology issues requiring Truth Structure -- check that canonical behavior docs keep active Product Decisions and Rationale sections -- optionally run truthmark check when local tooling is available -- must not require the truthmark binary; direct inspection is always valid -- report issues and suggested fixes without silently rewriting unrelated files -- if follow-up docs edits are needed for mixed-owner docs, run or recommend Truth Structure before editing -Evidence Gate: -- support each finding and suggested fix with evidence from config, route files, canonical docs, implementation, templates, or tests -- canonical docs are context, not sole proof when implementation conflicts -- remove unsupported findings or mark open questions; validate changed claims if you edit docs - -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. - -Report completion in this shape: - -```md -Truth Check: completed - -Files reviewed: -- docs/truthmark/areas.md - -Issues found: -- none - -Fixes suggested: -- none - -Evidence checked: -- Finding: The root route index is present and maps repository truth owners. - Evidence: .truthmark/config.yml:1 / docs/truthmark/areas.md:1 - Suggested fix: none - Confidence: high - -Validation: -- truthmark check -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.claude/skills/truthmark-check/support/procedure.md b/.claude/skills/truthmark-check/support/procedure.md new file mode 100644 index 0000000..0c0ae26 --- /dev/null +++ b/.claude/skills/truthmark-check/support/procedure.md @@ -0,0 +1,37 @@ +# Truthmark Check Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +# Truthmark Check + +Use this skill to audit repository truth health. + +Invocations: OpenCode /skill truthmark-check; Codex /truthmark-check or $truthmark-check; Claude Code /truthmark-check; GitHub Copilot /truthmark-check; Gemini CLI /truthmark:check. + +Truth Check is agent-led: + +- inspect .truthmark/config.yml, docs/truthmark/areas.md, canonical docs, and relevant implementation directly +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ +- check that current docs describe current code rather than historical plans +- check that docs/truthmark/areas.md routes code surfaces to canonical truth docs +- check for broad, catch-all, index-like, or mixed-owner truth docs and report them as topology issues requiring Truth Structure +- check that canonical behavior docs keep active Product Decisions and Rationale sections +- optionally run truthmark check when local tooling is available +- must not require the truthmark binary; direct inspection is always valid +- report issues and suggested fixes without silently rewriting unrelated files +- if follow-up docs edits are needed for mixed-owner docs, run or recommend Truth Structure before editing +Evidence Gate: +- support each finding and suggested fix with evidence from config, route files, canonical docs, implementation, templates, or tests +- canonical docs are context, not sole proof when implementation conflicts +- remove unsupported findings or mark open questions; validate changed claims if you edit docs + +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. diff --git a/.claude/skills/truthmark-check/support/report-template.md b/.claude/skills/truthmark-check/support/report-template.md new file mode 100644 index 0000000..df79cea --- /dev/null +++ b/.claude/skills/truthmark-check/support/report-template.md @@ -0,0 +1,27 @@ +# Truthmark Check Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: + +```md +Truth Check: completed + +Files reviewed: +- docs/truthmark/areas.md + +Issues found: +- none + +Fixes suggested: +- none + +Evidence checked: +- Finding: The root route index is present and maps repository truth owners. + Evidence: .truthmark/config.yml:1 / docs/truthmark/areas.md:1 + Suggested fix: none + Confidence: high + +Validation: +- truthmark check +``` diff --git a/.claude/skills/truthmark-check/support/subagents-and-leases.md b/.claude/skills/truthmark-check/support/subagents-and-leases.md new file mode 100644 index 0000000..bea7aa9 --- /dev/null +++ b/.claude/skills/truthmark-check/support/subagents-and-leases.md @@ -0,0 +1,10 @@ +# Truthmark Check Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Claude Code subagent mode: +- use automatically when this workflow runs in Claude Code and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents only: truth-route-auditor subagent, truth-claim-verifier subagent, truth-doc-reviewer subagent +- subagents inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; subagents must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns the final Truth Check report diff --git a/.claude/skills/truthmark-document/SKILL.md b/.claude/skills/truthmark-document/SKILL.md index c123523..0031fc3 100644 --- a/.claude/skills/truthmark-document/SKILL.md +++ b/.claude/skills/truthmark-document/SKILL.md @@ -3,98 +3,25 @@ name: truthmark-document description: 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. argument-hint: Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Document Use this skill to document existing implemented behavior when no functional-code changes are required for the task. + Invocations: OpenCode /skill truthmark-document; Codex /truthmark-document or $truthmark-document; Claude Code /truthmark-document; GitHub Copilot /truthmark-document; Gemini CLI /truthmark:document. -Truth Document is manual and implementation-first: +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, existing canonical docs, implementation code, and tests directly. +- Document current implemented behavior; do not invent future behavior. +- May write canonical truth docs and truth routing files only; must not write functional code. +- Read support/procedure.md before editing truth docs. +- Read support/subagents-and-leases.md before dispatching or accepting worker output. +- Read support/report-template.md before the final report. -- 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 -- inspect .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, existing canonical docs, implementation code, and tests directly -- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -- document current implemented behavior; do not invent future behavior or planned endpoints -- may write canonical truth docs and docs/truthmark/areas.md or relevant child route files only -- must not write functional code -- 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 -- block and recommend Truth Structure when routing repair is unsafe, ambiguous, or outside the task boundary -- keep feature README.md files as indexes rather than truth-document targets -- create or update bounded leaf truth docs when behavior does not fit an existing leaf doc -- keep behavior truth docs behavior-oriented, not endpoint-oriented, unless the endpoint itself is the behavior boundary -- keep API endpoint details in the nearest contract truth doc when such a doc owns the API contract -- preserve unrelated authored content -Truth-doc ownership gate: -- before editing or relying on the implemented behavior and candidate truth docs, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if the target doc is broad, mixed-owner, index-like, or the documented behavior spans independent owners, run Truth Structure first when safe and in scope; otherwise block and recommend Truth Structure -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -Product Decisions/Rationale preservation gate: -- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc -- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index -- 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 -- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing -- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked -Evidence Gate: -- route-first: map the documented behavior to bounded route owners and primary canonical docs -- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale -- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions -- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts -- remove, narrow, or block unsupported claims -- if no truth doc changed, report why current truth was already sufficient or why documentation was blocked -Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. -They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. -If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. -When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. -Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. -Align existing docs to that template while preserving accurate authored content. -If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. -Teams may edit the template files under docs/templates/ to define their local truth-doc standards. -Truth-doc shape repair gate: -- Truth Document may restructure only truth docs for the implemented behavior being documented. -- repair shape in place only after the ownership gate confirms the doc is the right bounded owner -- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work -- 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 -- preserve supported claims; remove, narrow, or block unsupported or stale claims -- report docs restructured and why a narrow edit was not sufficient -Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. -Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. - -Report completion in this shape: -```md -Truth Document: completed - -Implementation reviewed: -- src/routing/area-resolver.ts - -Truth docs created: -- docs/truth/contracts.md - -Truth docs updated: -- docs/truth/check-diagnostics.md - -Truth docs restructured: -- docs/truth/check-diagnostics.md - -Routing updated: -- docs/truthmark/areas.md - -Evidence checked: -- Claim: Route resolution behavior is documented in the contracts truth doc. - Evidence: src/routing/area-resolver.ts:14 / docs/truthmark/areas.md:9 - Result: supported - -Notes: -- Documented routing and behavior from route handlers and tests. -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.claude/skills/truthmark-document/support/procedure.md b/.claude/skills/truthmark-document/support/procedure.md new file mode 100644 index 0000000..5b6e4a8 --- /dev/null +++ b/.claude/skills/truthmark-document/support/procedure.md @@ -0,0 +1,73 @@ +# Truthmark Document Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +# Truthmark Document + +Use this skill to document existing implemented behavior when no functional-code changes are required for the task. +Invocations: OpenCode /skill truthmark-document; Codex /truthmark-document or $truthmark-document; Claude Code /truthmark-document; GitHub Copilot /truthmark-document; Gemini CLI /truthmark:document. + +Truth Document is manual and implementation-first: + +- 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 +- inspect .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, existing canonical docs, implementation code, and tests directly +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +- document current implemented behavior; do not invent future behavior or planned endpoints +- may write canonical truth docs and docs/truthmark/areas.md or relevant child route files only +- must not write functional code +- 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 +- block and recommend Truth Structure when routing repair is unsafe, ambiguous, or outside the task boundary +- keep feature README.md files as indexes rather than truth-document targets +- create or update bounded leaf truth docs when behavior does not fit an existing leaf doc +- keep behavior truth docs behavior-oriented, not endpoint-oriented, unless the endpoint itself is the behavior boundary +- keep API endpoint details in the nearest contract truth doc when such a doc owns the API contract +- preserve unrelated authored content +Truth-doc ownership gate: +- before editing or relying on the implemented behavior and candidate truth docs, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if the target doc is broad, mixed-owner, index-like, or the documented behavior spans independent owners, run Truth Structure first when safe and in scope; otherwise block and recommend Truth Structure +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +Product Decisions/Rationale preservation gate: +- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc +- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index +- 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 +- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing +- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked +Evidence Gate: +- route-first: map the documented behavior to bounded route owners and primary canonical docs +- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale +- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions +- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts +- remove, narrow, or block unsupported claims +- if no truth doc changed, report why current truth was already sufficient or why documentation was blocked +Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. +They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. +If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. +When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. +Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. +Align existing docs to that template while preserving accurate authored content. +If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. +Teams may edit the template files under docs/templates/ to define their local truth-doc standards. +Truth-doc shape repair gate: +- Truth Document may restructure only truth docs for the implemented behavior being documented. +- repair shape in place only after the ownership gate confirms the doc is the right bounded owner +- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work +- 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 +- preserve supported claims; remove, narrow, or block unsupported or stale claims +- report docs restructured and why a narrow edit was not sufficient +Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. +Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. +Parent post-document verification: +- verify only truth docs and leased truth routing files changed during document work +- block on functional code, generated host surfaces, or unrelated diffs caused by document work +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it +- verify the final report records ownership review, structure requirement, restructure, routing update, or blocked reason when applicable diff --git a/.claude/skills/truthmark-document/support/report-template.md b/.claude/skills/truthmark-document/support/report-template.md new file mode 100644 index 0000000..19d5454 --- /dev/null +++ b/.claude/skills/truthmark-document/support/report-template.md @@ -0,0 +1,31 @@ +# Truthmark Document Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Document: completed + +Implementation reviewed: +- src/routing/area-resolver.ts + +Truth docs created: +- docs/truth/contracts.md + +Truth docs updated: +- docs/truth/check-diagnostics.md + +Truth docs restructured: +- docs/truth/check-diagnostics.md + +Routing updated: +- docs/truthmark/areas.md + +Evidence checked: +- Claim: Route resolution behavior is documented in the contracts truth doc. + Evidence: src/routing/area-resolver.ts:14 / docs/truthmark/areas.md:9 + Result: supported + +Notes: +- Documented routing and behavior from route handlers and tests. +``` diff --git a/.claude/skills/truthmark-document/support/subagents-and-leases.md b/.claude/skills/truthmark-document/support/subagents-and-leases.md new file mode 100644 index 0000000..271f648 --- /dev/null +++ b/.claude/skills/truthmark-document/support/subagents-and-leases.md @@ -0,0 +1,14 @@ +# Truthmark Document Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Claude Code subagent mode: +- use automatically when this workflow runs in Claude Code and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents for verification: truth-route-auditor subagent, truth-claim-verifier subagent +- read-only subagents inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; read-only subagents must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- dispatch write-capable project subagents only with explicit write leases: truth-doc-writer subagent +- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields +- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes +- parent must inspect the actual checkout diff against each lease before accepting a worker report +- Parent agent owns Truth Document acceptance, lease validation, and final report diff --git a/.claude/skills/truthmark-preview/SKILL.md b/.claude/skills/truthmark-preview/SKILL.md new file mode 100644 index 0000000..9a5ed1d --- /dev/null +++ b/.claude/skills/truthmark-preview/SKILL.md @@ -0,0 +1,26 @@ +--- +name: truthmark-preview +description: Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check. +argument-hint: Optional requested outcome, code area, doc path, or routing question +user-invocable: true +truthmark-version: 1.4.0 +--- + +# Truthmark Preview + +Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits. + +Invocations: OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview. + +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and only the truth docs or implementation files needed to preview ownership. +- Truth Preview is read-only; this report is intended, not authorized. +- must not edit files and must not issue write leases; do not run Truth Sync automatically, replace Truth Check, claim final correctness, or mutate code. +- Use optional read-only route-auditor evidence only when it reduces context or clarifies ownership. +- Hand off to the selected workflow after user approval. + +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.claude/skills/truthmark-preview/support/procedure.md b/.claude/skills/truthmark-preview/support/procedure.md new file mode 100644 index 0000000..dd3f146 --- /dev/null +++ b/.claude/skills/truthmark-preview/support/procedure.md @@ -0,0 +1,43 @@ +# Truthmark Preview Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits. + +Invocations: OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview. + +Truth Preview is read-only. Its report is intended, not authorized. + +Purpose: +- preview the likely Truthmark workflow, route owner, target files, expected write classes, suggested subagent use, and blocking ambiguity before edits happen +- hand off to the selected workflow after user approval +- keep the selector thin so agents can avoid loading or acting through heavier workflows prematurely + +Read: +- .truthmark/config.yml +- docs/truthmark/areas.md +- relevant child route files under docs/truthmark/areas/ +- relevant truth docs and implementation files needed to preview ownership +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. + +Do not: +- must not edit files +- must not create truth docs +- must not update routing +- must not run Truth Sync automatically +- must not replace Truth Check +- must not claim final correctness +- must not issue write leases +- must not mutate code + +Suggested subagent use: +- optional read-only verifier: truth_route_auditor +- write workers: none +- leases needed: none + +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md diff --git a/.claude/skills/truthmark-preview/support/report-template.md b/.claude/skills/truthmark-preview/support/report-template.md new file mode 100644 index 0000000..7c3c08b --- /dev/null +++ b/.claude/skills/truthmark-preview/support/report-template.md @@ -0,0 +1,41 @@ +# Truthmark Preview Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Preview: completed + +Requested outcome: +- preview likely Truthmark workflow routing before edits + +Likely workflow: +- truthmark-document + +Why this workflow: +- positive trigger: document existing implemented behavior +- negative triggers considered: functional-code change, doc-first implementation, topology repair, truth audit +- forbidden adjacency considered: must not edit functional code + +Likely route owner: +- route file: docs/truthmark/areas.md +- truth doc: docs/truth/example.md +- confidence: medium + +Expected write classes: +- truth docs + +Expected target files: +- docs/truth/example.md + +Suggested subagent use: +- read-only verifiers: truth_route_auditor +- write workers: none in Preview +- leases needed: none in Preview + +Blocking ambiguity: +- none identified in preview + +Handoff: +- Run the selected Truthmark workflow after user approval. +``` diff --git a/.claude/skills/truthmark-preview/support/subagents-and-leases.md b/.claude/skills/truthmark-preview/support/subagents-and-leases.md new file mode 100644 index 0000000..c691430 --- /dev/null +++ b/.claude/skills/truthmark-preview/support/subagents-and-leases.md @@ -0,0 +1,10 @@ +# Truthmark Preview Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Claude Code subagent mode: +- use automatically when this workflow runs in Claude Code and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents only: truth-route-auditor subagent +- subagents inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; subagents must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns the final Truth Preview report diff --git a/.claude/skills/truthmark-realize/SKILL.md b/.claude/skills/truthmark-realize/SKILL.md index 5f34ff2..a5a0de8 100644 --- a/.claude/skills/truthmark-realize/SKILL.md +++ b/.claude/skills/truthmark-realize/SKILL.md @@ -3,7 +3,7 @@ name: truthmark-realize description: 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. argument-hint: Optional truth doc path, area, or desired code behavior to realize user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Realize @@ -12,50 +12,14 @@ Use this skill only when the user explicitly asks to realize truth docs into cod Invocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize. -Truth Realize is doc-first: +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read the source truth docs, .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files, tests, and relevant functional code directly. +- Truth docs lead; code follows. +- may write functional code only; must not edit truth docs or truth routing while realizing those docs. +- Read support/procedure.md before changing code. +- Read support/report-template.md before the final report. -- truth docs lead -- code follows -- Truth Realize never edits the truth docs it is realizing - -Workflow: - -1. Read the updated truth docs named by the user, or infer the relevant docs from docs/truthmark/areas.md. -2. Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files, tests, and the relevant functional code. -3. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -Truth-doc ownership gate: -- before editing or relying on source truth docs before writing code, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -4. Update functional code only so implementation matches bounded, current truth claims from the source docs. -5. Do not edit truth docs or truth routing while realizing those docs. -6. Run relevant tests for the changed code. -7. Report changed code files and verification steps. -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md - -Read and write boundaries: - -- may read truth docs, routing docs, and relevant functional code -- may write functional code only -- must not edit truth docs or truth routing while realizing those docs - -Report completion in this shape: - -```md -Truth Realize: completed - -Truth docs used: -- docs/truth/authentication/session-timeout.md - -Code updated: -- src/auth/session.ts - -Verification: -- npm test -- auth -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md diff --git a/.claude/skills/truthmark-realize/support/procedure.md b/.claude/skills/truthmark-realize/support/procedure.md new file mode 100644 index 0000000..3a657a6 --- /dev/null +++ b/.claude/skills/truthmark-realize/support/procedure.md @@ -0,0 +1,42 @@ +# Truthmark Realize Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +# Truthmark Realize + +Use this skill only when the user explicitly asks to realize truth docs into code. + +Invocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize. + +Truth Realize is doc-first: + +- truth docs lead +- code follows +- Truth Realize never edits the truth docs it is realizing + +Workflow: + +1. Read the updated truth docs named by the user, or infer the relevant docs from docs/truthmark/areas.md. +2. Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files, tests, and the relevant functional code. +3. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +Truth-doc ownership gate: +- before editing or relying on source truth docs before writing code, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +4. Update functional code only so implementation matches bounded, current truth claims from the source docs. +5. Do not edit truth docs or truth routing while realizing those docs. +6. Run relevant tests for the changed code. +7. Report changed code files and verification steps. +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md + +Read and write boundaries: + +- may read truth docs, routing docs, and relevant functional code +- may write functional code only +- must not edit truth docs or truth routing while realizing those docs diff --git a/.claude/skills/truthmark-realize/support/report-template.md b/.claude/skills/truthmark-realize/support/report-template.md new file mode 100644 index 0000000..0f77d6a --- /dev/null +++ b/.claude/skills/truthmark-realize/support/report-template.md @@ -0,0 +1,18 @@ +# Truthmark Realize Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: + +```md +Truth Realize: completed + +Truth docs used: +- docs/truth/authentication/session-timeout.md + +Code updated: +- src/auth/session.ts + +Verification: +- npm test -- auth +``` diff --git a/.claude/skills/truthmark-structure/SKILL.md b/.claude/skills/truthmark-structure/SKILL.md index 339d87f..2aef662 100644 --- a/.claude/skills/truthmark-structure/SKILL.md +++ b/.claude/skills/truthmark-structure/SKILL.md @@ -1,123 +1,26 @@ --- name: truthmark-structure -description: Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, or needs split/repair. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code. +description: 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. argument-hint: Optional area, directory, or routing concern user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- +# Truthmark Structure + Use this skill to design or repair Truthmark area structure. + Invocations: OpenCode /skill truthmark-structure; Codex /truthmark-structure or $truthmark-structure; Claude Code /truthmark-structure; GitHub Copilot /truthmark-structure; Gemini CLI /truthmark:structure. -Truth Structure is agent-native: -- inspect repository layout, current docs, .truthmark/config.yml, docs/truthmark/areas.md, and relevant code directly -- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ -- define areas by product or behavior ownership, not by mechanical directory mirroring -- create or repair docs/truthmark/areas.md -- create starter truth docs when useful and when they belong in the canonical current-truth surface -- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter. -- Starter truth docs must include ## Product Decisions and ## Rationale sections. -When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. -Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. -Align existing docs to that template while preserving accurate authored content. -If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. -Teams may edit the template files under docs/templates/ to define their local truth-doc standards. -- use docs/truth/**, docs/architecture/**, or docs/standards/** for current truth destinations -- use only canonical current-truth destinations for starter truth docs -- keep active Product Decisions and Rationale in the canonical doc that owns the behavior -- preserve unrelated authored content -## Topology Governance -Truth Structure owns documentation topology. Do not depend on humans to manually organize docs/truth. Treat the configured truth root as a managed semantic root. -Inspect 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. -When topology pressure exists, repair structure before creating or extending truth docs. -Truth-doc ownership gate: -- before editing or relying on candidate route owners and current truth docs, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if a truth doc mixes independent owners, route ownership is broad, or a split is required for bounded ownership, split and reroute into bounded truth docs when safe; otherwise block with manual-review files -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -Product Decisions/Rationale preservation gate: -- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc -- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index -- 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 -- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing -- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked -Topology pressure signals: -- one area maps broad code such as src/**, app/**, server/**, services/**, or packages/** -- one area maps multiple unrelated controllers, route groups, services, or bounded contexts -- one truth doc owns unrelated behaviors or unrelated endpoint families -- the configured truth root has many direct non-index docs -- a changed controller, route, or service cannot map to a specific behavior doc -- Truth Sync would need to create a new generic truth doc because routing is too broad -- endpoint or controller names reveal domains missing from docs/truthmark/areas/** -Use these review thresholds as guidance: -- more than 10 direct truth docs in one folder -- more than 15 leaf areas in one child route file -- more than 8 truth docs mapped to one area -- more than 5 controllers mapped through one catch-all area -Repair rules: -- split broad, overloaded, or catch-all areas into behavior-owned child route files -- split mixed-owner truth docs into bounded owner docs before adding new behavior claims -- create route files under docs/truthmark/areas/ when a product/domain boundary is clear -- create behavior truth docs under the configured truth root only when behavior lacks a current doc -- README.md files are indexes, not Truth Sync targets -- prefer bounded leaf truth docs at //.md -- keep behavior truth docs behavior-oriented, not endpoint-oriented -- keep API endpoint details in the nearest contract truth doc when such a doc exists -- update routing so future Truth Sync can target small docs -- preserve existing authored docs; move or rewrite only when needed to remove ambiguity -- report Truth docs split when one broad or mixed-owner truth doc becomes multiple bounded docs -Truth-doc shape repair gate: -- Truth Structure may restructure broader routed docs when topology, ownership, or doc-shape repair is already in scope. -- repair shape in place only after the ownership gate confirms the doc is the right bounded owner -- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work -- 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 -- preserve supported claims; remove, narrow, or block unsupported or stale claims -- report docs restructured and why a narrow edit was not sufficient -Evidence Gate: -- apply the Evidence Gate before finishing when Truth Structure writes routed docs, ownership claims, Product Decisions, or Rationale -- support ownership/behavior claims with topology or primary checkout evidence from layout, implementation boundaries, docs, config, route files, tests, templates, schemas, or contracts -- tests/examples/canonical docs corroborate; remove, narrow, or block unsupported claims -Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. -Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. -- Do not finish topology repair with routed canonical current-truth docs missing Product Decisions or Rationale sections. -- If an existing canonical doc lacks either section, add the missing heading beside Current Behavior with a concise current-state placeholder or active decision. -Portable fallback: -- If this skill surface is unavailable, perform the same workflow directly from committed repository files. -- Do not require the truthmark CLI. -- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, canonical docs, and representative implementation code. -- Use a subagent only when the host supports that pattern; otherwise perform the topology repair inline. -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. -Report completion in this shape: -```md -Truth Structure: completed -Topology reviewed: -- controllers: src/auth/** -- docs root: docs/truth -- route files: docs/truthmark/areas.md -Areas reviewed: -- src/auth/** -Routing updated: -- docs/truthmark/areas.md -Truth docs created: -- docs/truth/authentication/session.md -Truth docs split: -- docs/truth/authentication/README.md -> docs/truth/authentication/session.md -Truth docs restructured: -- docs/truth/authentication/README.md -Evidence checked: -- Claim: Session behavior belongs to a dedicated Authentication truth owner. - Evidence: src/auth/** / docs/truthmark/areas.md:7 - Result: supported -Topology decisions: -- Added an Authentication area because session behavior has a distinct code surface and truth owner. -Notes: -- Added an Authentication area for session behavior. -``` + +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, current docs, and relevant code directly. +- Define areas by product or behavior ownership, not by mechanical directory mirroring. +- Do not edit functional code. +- Read support/procedure.md before writing route or starter truth-doc changes. +- Read support/report-template.md before the final report. + +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.claude/skills/truthmark-structure/support/procedure.md b/.claude/skills/truthmark-structure/support/procedure.md new file mode 100644 index 0000000..5eabbf7 --- /dev/null +++ b/.claude/skills/truthmark-structure/support/procedure.md @@ -0,0 +1,109 @@ +# Truthmark Structure Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Use this skill to design or repair Truthmark area structure. +Invocations: OpenCode /skill truthmark-structure; Codex /truthmark-structure or $truthmark-structure; Claude Code /truthmark-structure; GitHub Copilot /truthmark-structure; Gemini CLI /truthmark:structure. +Truth Structure is agent-native: +- inspect repository layout, current docs, .truthmark/config.yml, docs/truthmark/areas.md, and relevant code directly +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ +- define areas by product or behavior ownership, not by mechanical directory mirroring +- create or repair docs/truthmark/areas.md +- create starter truth docs when useful and when they belong in the canonical current-truth surface +- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter. +- Starter truth docs must include ## Product Decisions and ## Rationale sections. + +When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. +Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. +Align existing docs to that template while preserving accurate authored content. +If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. +Teams may edit the template files under docs/templates/ to define their local truth-doc standards. +- use docs/truth/**, docs/architecture/**, or docs/standards/** for current truth destinations +- use only canonical current-truth destinations for starter truth docs +- keep active Product Decisions and Rationale in the canonical doc that owns the behavior +- preserve unrelated authored content +## New area setup +Use 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. +Do: +- inspect the named code area +- infer bounded product or behavior ownership +- choose the owning route when ownership is clear; otherwise propose the route and block for review +- create or update the child route entry or file +- create starter truth docs only where current truth is missing +- report the initial truth boundary +Do not: +- do not edit functional code +- do not perform full behavior documentation unless evidence is inspected and the task explicitly asks for it +- do not patch broad or mixed-owner docs in place +- do not create generic catch-all docs +- do not treat README files as Sync targets +## Topology Governance +Truth Structure owns documentation topology. Do not depend on humans to manually organize docs/truth. Treat the configured truth root as a managed semantic root. +Inspect 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. +When topology pressure exists, repair structure before creating or extending truth docs. +Truth-doc ownership gate: +- before editing or relying on candidate route owners and current truth docs, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if a truth doc mixes independent owners, route ownership is broad, or a split is required for bounded ownership, split and reroute into bounded truth docs when safe; otherwise block with manual-review files +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +Product Decisions/Rationale preservation gate: +- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc +- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index +- 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 +- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing +- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked +Topology pressure signals: +- one area maps broad code such as src/**, app/**, server/**, services/**, or packages/** +- one area maps multiple unrelated controllers, route groups, services, or bounded contexts +- one truth doc owns unrelated behaviors or unrelated endpoint families +- the configured truth root has many direct non-index docs +- a changed controller, route, or service cannot map to a specific behavior doc +- Truth Sync would need to create a new generic truth doc because routing is too broad +- endpoint or controller names reveal domains missing from docs/truthmark/areas/** +Use these review thresholds as guidance: +- more than 10 direct truth docs in one folder +- more than 15 leaf areas in one child route file +- more than 8 truth docs mapped to one area +- more than 5 controllers mapped through one catch-all area +Repair rules: +- split broad, overloaded, or catch-all areas into behavior-owned child route files +- split mixed-owner truth docs into bounded owner docs before adding new behavior claims +- create route files under docs/truthmark/areas/ when a product/domain boundary is clear +- create behavior truth docs under the configured truth root only when behavior lacks a current doc +- README.md files are indexes, not Truth Sync targets +- prefer bounded leaf truth docs at //.md +- keep behavior truth docs behavior-oriented, not endpoint-oriented +- keep API endpoint details in the nearest contract truth doc when such a doc exists +- update routing so future Truth Sync can target small docs +- preserve existing authored docs; move or rewrite only when needed to remove ambiguity +- report Truth docs split when one broad or mixed-owner truth doc becomes multiple bounded docs +Truth-doc shape repair gate: +- Truth Structure may restructure broader routed docs when topology, ownership, or doc-shape repair is already in scope. +- repair shape in place only after the ownership gate confirms the doc is the right bounded owner +- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work +- 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 +- preserve supported claims; remove, narrow, or block unsupported or stale claims +- report docs restructured and why a narrow edit was not sufficient +Evidence Gate: +- apply the Evidence Gate before finishing when Truth Structure writes routed docs, ownership claims, Product Decisions, or Rationale +- support ownership/behavior claims with topology or primary checkout evidence from layout, implementation boundaries, docs, config, route files, tests, templates, schemas, or contracts +- tests/examples/canonical docs corroborate; remove, narrow, or block unsupported claims +Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. +Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. +- Do not finish topology repair with routed canonical current-truth docs missing Product Decisions or Rationale sections. +- If an existing canonical doc lacks either section, add the missing heading beside Current Behavior with a concise current-state placeholder or active decision. +Portable fallback: +- If this skill surface is unavailable, perform the same workflow directly from committed repository files. +- Do not require the truthmark CLI. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, canonical docs, and representative implementation code. +- Use a subagent only when the host supports that pattern; otherwise perform the topology repair inline. +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. diff --git a/.claude/skills/truthmark-structure/support/report-template.md b/.claude/skills/truthmark-structure/support/report-template.md new file mode 100644 index 0000000..f8cfa0d --- /dev/null +++ b/.claude/skills/truthmark-structure/support/report-template.md @@ -0,0 +1,35 @@ +# Truthmark Structure Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Structure: completed +Topology reviewed: +- controllers: src/auth/** +- docs root: docs/truth +- route files: docs/truthmark/areas.md +Areas reviewed: +- src/auth/** +Routing updated: +- docs/truthmark/areas.md +Initial truth boundary: +- Area: Authentication +- Code: src/auth/** +- Truth owner: docs/truth/authentication/session.md +- Scope: session behavior only +Truth docs created: +- docs/truth/authentication/session.md +Truth docs split: +- docs/truth/authentication/README.md -> docs/truth/authentication/session.md +Truth docs restructured: +- docs/truth/authentication/README.md +Evidence checked: +- Claim: Session behavior belongs to a dedicated Authentication truth owner. + Evidence: src/auth/** / docs/truthmark/areas.md:7 + Result: supported +Topology decisions: +- Added an Authentication area because session behavior has a distinct code surface and truth owner. +Notes: +- Added an Authentication area for session behavior. +``` diff --git a/.claude/skills/truthmark-structure/support/subagents-and-leases.md b/.claude/skills/truthmark-structure/support/subagents-and-leases.md new file mode 100644 index 0000000..4474180 --- /dev/null +++ b/.claude/skills/truthmark-structure/support/subagents-and-leases.md @@ -0,0 +1,10 @@ +# Truthmark Structure Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Claude Code subagent mode: +- use automatically when this workflow runs in Claude Code and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents only: truth-route-auditor subagent +- subagents inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; subagents must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns all Truth Structure writes and final topology decisions diff --git a/.claude/skills/truthmark-sync/SKILL.md b/.claude/skills/truthmark-sync/SKILL.md index 4227894..c3d5a91 100644 --- a/.claude/skills/truthmark-sync/SKILL.md +++ b/.claude/skills/truthmark-sync/SKILL.md @@ -3,135 +3,26 @@ name: truthmark-sync description: 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. argument-hint: Optional changed-code area, truth-doc area, or sync focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- +# Truthmark Sync + 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. + Invocations: OpenCode /skill truthmark-sync; Codex /truthmark-sync or $truthmark-sync; Claude Code /truthmark-sync; GitHub Copilot /truthmark-sync; Gemini CLI /truthmark:sync. -Explicit invocation runs immediately. Later functional-code changes reopen the finish-time requirement, and an earlier explicit run satisfies the finish gate only if no later functional-code changes occur. -Skip 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. -Parent workflow: -1. Inspect git status, staged changes, unstaged changes, and untracked files directly. -2. Read .truthmark/config.yml, the configured root route index at docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and relevant canonical docs. -3. Identify functional-code changes and the nearest truth docs or routing repairs. -4. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run. -6. Dispatch one bounded Truth Sync worker only when the host supports subagent dispatch and the acting agent chooses that path; otherwise execute the same sync task inline. -Topology quality gate: -- before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner -- if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc -- run Truth Structure before syncing when topology repair is safe and in scope -- block and recommend Truth Structure when topology repair is unsafe, ambiguous, or outside the current task boundary -- report the route files and changed code paths that require structure repair -- README.md files are indexes, not Truth Sync targets -- must not append behavior details to a README.md index -- create or update a bounded leaf truth doc when behavior changes do not fit an existing leaf doc -Truth-doc ownership gate: -- before editing or relying on changed functional files and impacted truth docs, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if an impacted doc is broad, mixed-owner, index-like, or the update spans independent behavior owners, run Truth Structure before syncing when safe and in scope; otherwise block and recommend Truth Structure -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -Product Decisions/Rationale preservation gate: -- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc -- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index -- 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 -- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing -- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked -When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. -Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. -Align existing docs to that template while preserving accurate authored content. -If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. -Teams may edit the template files under docs/templates/ to define their local truth-doc standards. -Truth-doc shape repair gate: -- Truth Sync may restructure only truth docs impacted by the current functional-code change. -- repair shape in place only after the ownership gate confirms the doc is the right bounded owner -- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work -- 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 -- preserve supported claims; remove, narrow, or block unsupported or stale claims -- report docs restructured and why a narrow edit was not sufficient -Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. -Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. -Evidence Gate: -- route-first: map changed functional files to bounded route owners and primary canonical docs -- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale -- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions -- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts -- remove, narrow, or block unsupported claims -- if no impacted doc changed, report why truth was already current or why sync was skipped -Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. -They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. -If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. -Optional validation tooling: -- you may run truthmark check when local tooling is available -- do not require the truthmark binary; direct checkout inspection is the canonical path -- optional validation must not replace agent judgment about docs and routing -- update Product Decisions and Rationale when a behavior change comes from a decision change -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. -### Truth Sync Worker -The parent provides the task focus and any repository context already gathered. -Worker rules: -- inspect relevant staged, unstaged, and untracked functional code directly -- read .truthmark/config.yml, docs/truthmark/areas.md, and canonical truth docs directly -- Code verification is parent-owned; report what was run or why it was not run -- may write truth docs and docs/truthmark/areas.md only for Truth Sync alignment -- must not rewrite functional code -Return result in this shape: -- status: completed | blocked -- changedCodeReviewed: string[] -- ownershipReviewed: string[] -- structureRequired?: string[] -- truthDocsUpdated: string[] -- routingDocsUpdated: string[] -- truthDocsSplit?: string[] -- evidenceChecked: { claim: string; evidence: string[]; result: supported | narrowed | removed | blocked }[] -- notes: string[] -- blockedReason?: string -- manualReviewFiles?: string[] -Parent post-sync verification: -- verify only truth docs and docs/truthmark/areas.md changed during sync -- block on any unrelated diff caused by the sync step -- block if functional code changed during sync -- verify the worker report matches the required headings and sections -- validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked -- verify the updated docs correspond to the reviewed changed-code surface -- verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired -- blocked outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files -Report completion in this shape: -```md -Truth Sync: completed -Changed code reviewed: -- src/auth/session.ts +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Skip docs-only, formatting-only, behavior-preserving renames with no truth impact, missing config, and no-code changes. +- Read .truthmark/config.yml, the configured root route index at docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and relevant canonical docs. +- direct checkout inspection is the canonical path; do not require the truthmark binary. +- May write canonical truth docs and truth routing files only; must not rewrite functional code. +- Read support/procedure.md before editing truth docs. +- Read support/subagents-and-leases.md before dispatching or accepting worker output. +- Read support/report-template.md before the final report. -Truth docs updated: -- docs/truth/repository/overview.md - -Evidence checked: -- Claim: Session timeout behavior is documented in the mapped repository truth doc. - Evidence: src/auth/session.ts:12 / docs/truthmark/areas.md:11 - Result: supported - -Notes: -- Updated session timeout behavior. -``` -Blocked report example: -```md -Truth Sync: blocked - -Reason: -- routing repair is not allowed - -Files requiring manual review: -- docs/truthmark/areas.md - -Next action: -- update routing metadata and rerun Truth Sync -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.claude/skills/truthmark-sync/support/procedure.md b/.claude/skills/truthmark-sync/support/procedure.md new file mode 100644 index 0000000..e213b0e --- /dev/null +++ b/.claude/skills/truthmark-sync/support/procedure.md @@ -0,0 +1,82 @@ +# Truthmark Sync Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +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. +Invocations: OpenCode /skill truthmark-sync; Codex /truthmark-sync or $truthmark-sync; Claude Code /truthmark-sync; GitHub Copilot /truthmark-sync; Gemini CLI /truthmark:sync. +Explicit invocation runs immediately. Later functional-code changes reopen the finish-time requirement, and an earlier explicit run satisfies the finish gate only if no later functional-code changes occur. +Skip 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. +Parent workflow: +1. Inspect git status, staged changes, unstaged changes, and untracked files directly. +2. Read .truthmark/config.yml, the configured root route index at docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and relevant canonical docs. +3. Identify functional-code changes and the nearest truth docs or routing repairs. +4. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run. +6. 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. +Topology quality gate: +- before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner +- if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc +- run Truth Structure before syncing when topology repair is safe and in scope +- block and recommend Truth Structure when topology repair is unsafe, ambiguous, or outside the current task boundary +- report the route files and changed code paths that require structure repair +- README.md files are indexes, not Truth Sync targets +- must not append behavior details to a README.md index +- create or update a bounded leaf truth doc when behavior changes do not fit an existing leaf doc +Truth-doc ownership gate: +- before editing or relying on changed functional files and impacted truth docs, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if an impacted doc is broad, mixed-owner, index-like, or the update spans independent behavior owners, run Truth Structure before syncing when safe and in scope; otherwise block and recommend Truth Structure +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +Product Decisions/Rationale preservation gate: +- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc +- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index +- 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 +- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing +- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked +When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. +Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. +Align existing docs to that template while preserving accurate authored content. +If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. +Teams may edit the template files under docs/templates/ to define their local truth-doc standards. +Truth-doc shape repair gate: +- Truth Sync may restructure only truth docs impacted by the current functional-code change. +- repair shape in place only after the ownership gate confirms the doc is the right bounded owner +- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work +- 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 +- preserve supported claims; remove, narrow, or block unsupported or stale claims +- report docs restructured and why a narrow edit was not sufficient +Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. +Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. +Evidence Gate: +- route-first: map changed functional files to bounded route owners and primary canonical docs +- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale +- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions +- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts +- remove, narrow, or block unsupported claims +- if no impacted doc changed, report why truth was already current or why sync was skipped +Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. +They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. +If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. +Optional validation tooling: +- you may run truthmark check when local tooling is available +- do not require the truthmark binary; direct checkout inspection is the canonical path +- optional validation must not replace agent judgment about docs and routing +- update Product Decisions and Rationale when a behavior change comes from a decision change +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. +Parent post-sync verification: +- verify only truth docs and leased truth routing files changed during sync +- block on any unrelated diff caused by the sync step +- block if functional code changed during sync +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it +- validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked +- verify the updated docs correspond to the reviewed changed-code surface +- verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired +- blocked outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files diff --git a/.claude/skills/truthmark-sync/support/report-template.md b/.claude/skills/truthmark-sync/support/report-template.md new file mode 100644 index 0000000..ccbadff --- /dev/null +++ b/.claude/skills/truthmark-sync/support/report-template.md @@ -0,0 +1,35 @@ +# Truthmark Sync Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Sync: completed + +Changed code reviewed: +- src/auth/session.ts + +Truth docs updated: +- docs/truth/repository/overview.md + +Evidence checked: +- Claim: Session timeout behavior is documented in the mapped repository truth doc. + Evidence: src/auth/session.ts:12 / docs/truthmark/areas.md:11 + Result: supported + +Notes: +- Updated session timeout behavior. +``` +Blocked report example: +```md +Truth Sync: blocked + +Reason: +- routing repair is not allowed + +Files requiring manual review: +- docs/truthmark/areas.md + +Next action: +- update routing metadata and rerun Truth Sync +``` diff --git a/.claude/skills/truthmark-sync/support/subagents-and-leases.md b/.claude/skills/truthmark-sync/support/subagents-and-leases.md new file mode 100644 index 0000000..8e6b414 --- /dev/null +++ b/.claude/skills/truthmark-sync/support/subagents-and-leases.md @@ -0,0 +1,14 @@ +# Truthmark Sync Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Claude Code subagent mode: +- use automatically when this workflow runs in Claude Code and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents for verification: truth-route-auditor subagent, truth-claim-verifier subagent +- read-only subagents inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; read-only subagents must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- dispatch write-capable project subagents only with explicit write leases: truth-doc-writer subagent +- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields +- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes +- parent must inspect the actual checkout diff against each lease before accepting a worker report +- Parent agent owns Truth Sync acceptance, lease validation, and final report diff --git a/.codex/agents/truth-claim-verifier.toml b/.codex/agents/truth-claim-verifier.toml new file mode 100644 index 0000000..f8ebcc5 --- /dev/null +++ b/.codex/agents/truth-claim-verifier.toml @@ -0,0 +1,18 @@ +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. +name = "truth_claim_verifier" +description = "Read-only Truthmark claim verifier for checking canonical truth against checkout evidence." +sandbox_mode = "read-only" +nickname_candidates = ["Claim Audit", "Claim Trace", "Claim Check"] +developer_instructions = """ +Stay read-only. +Verify the behavior-bearing truth claims assigned by the parent against primary checkout evidence. +Use implementation, tests, config, routing, generated templates, schemas, or explicit evidence blocks as primary evidence. +Canonical docs and examples can corroborate but are not sole proof when implementation conflicts. +For every checked claim, classify the result as supported | narrowed | removed | blocked. +Do not edit files, stage changes, or invent missing behavior. +Return JSON only with keys: scope, filesReviewed, claimsChecked, evidence, unsupportedClaims, confidence, recommendedWorkflow, notes. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. +""" diff --git a/.codex/agents/truth-doc-reviewer.toml b/.codex/agents/truth-doc-reviewer.toml new file mode 100644 index 0000000..d3c7fc1 --- /dev/null +++ b/.codex/agents/truth-doc-reviewer.toml @@ -0,0 +1,17 @@ +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. +name = "truth_doc_reviewer" +description = "Read-only Truthmark doc reviewer for shape, decision, rationale, and evidence hygiene." +sandbox_mode = "read-only" +nickname_candidates = ["Doc Audit", "Doc Shape", "Doc Check"] +developer_instructions = """ +Stay read-only. +Review assigned canonical truth docs for frontmatter, source_of_truth, required template sections, Evidence checked entries, Product Decisions, and Rationale. +Flag README.md files used as behavior truth targets, mixed-owner docs, and shape repairs that should move to Truth Structure. +Do not edit files, stage changes, or rewrite docs. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. +""" diff --git a/.codex/agents/truth-doc-writer.toml b/.codex/agents/truth-doc-writer.toml new file mode 100644 index 0000000..32f4be6 --- /dev/null +++ b/.codex/agents/truth-doc-writer.toml @@ -0,0 +1,18 @@ +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. +name = "truth_doc_writer" +description = "Write-capable Truthmark doc worker for one parent-leased truth-document shard." +sandbox_mode = "workspace-write" +nickname_candidates = ["Doc Writer", "Truth Writer", "Doc Sync"] +developer_instructions = """ +Write one leased Truthmark truth-document shard assigned by the parent. +Require an explicit write lease before editing. The lease must name workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields. +Read every requiredReads entry directly before editing. +Edit 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. +Do not expand your own write scope. If the task needs an off-lease file, stop and report blocked. +Block 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. +Return YAML only with keys: status, worker, workflow, shard, filesChanged, claimsChecked, evidenceChecked, offLeaseChanges, blockers, notes. +status must be completed or blocked. +filesChanged must list only files you actually changed. +offLeaseChanges must be empty for completed reports. +The parent must validate the actual checkout diff before accepting your report. +""" diff --git a/.codex/agents/truth-route-auditor.toml b/.codex/agents/truth-route-auditor.toml new file mode 100644 index 0000000..74add1a --- /dev/null +++ b/.codex/agents/truth-route-auditor.toml @@ -0,0 +1,18 @@ +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. +name = "truth_route_auditor" +description = "Read-only Truthmark route auditor for bounded routing and ownership verification." +sandbox_mode = "read-only" +nickname_candidates = ["Route Audit", "Route Trace", "Route Check"] +developer_instructions = """ +Stay read-only. +Audit one bounded Truthmark route, area, or doc shard assigned by the parent. +Read .truthmark/config.yml, the root route index, relevant child route files, mapped truth docs, and relevant implementation files directly. +Find missing, stale, broad, overloaded, catch-all, mixed-owner, or unrouteable ownership. +Do not edit files, stage changes, or propose broad rewrites. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. +""" diff --git a/.codex/skills/truthmark-check/SKILL.md b/.codex/skills/truthmark-check/SKILL.md index 2c9d6c2..9be2399 100644 --- a/.codex/skills/truthmark-check/SKILL.md +++ b/.codex/skills/truthmark-check/SKILL.md @@ -3,7 +3,7 @@ name: truthmark-check description: 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. argument-hint: Optional area, doc path, or audit focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Check @@ -12,54 +12,16 @@ Use this skill to audit repository truth health. Invocations: OpenCode /skill truthmark-check; Codex /truthmark-check or $truthmark-check; Claude Code /truthmark-check; GitHub Copilot /truthmark-check; Gemini CLI /truthmark:check. -Truth Check is agent-led: +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, canonical docs, and relevant implementation directly. +- Report issues and suggested fixes; do not silently rewrite unrelated files. +- Direct checkout inspection is valid even when local tooling is unavailable. +- Read support/procedure.md before auditing details. +- Read support/subagents-and-leases.md before dispatching verifier subagents. +- Read support/report-template.md before the final report. -- inspect .truthmark/config.yml, docs/truthmark/areas.md, canonical docs, and relevant implementation directly -- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ -- check that current docs describe current code rather than historical plans -- check that docs/truthmark/areas.md routes code surfaces to canonical truth docs -- check for broad, catch-all, index-like, or mixed-owner truth docs and report them as topology issues requiring Truth Structure -- check that canonical behavior docs keep active Product Decisions and Rationale sections -- optionally run truthmark check when local tooling is available -- must not require the truthmark binary; direct inspection is always valid -- report issues and suggested fixes without silently rewriting unrelated files -- if follow-up docs edits are needed for mixed-owner docs, run or recommend Truth Structure before editing -Evidence Gate: -- support each finding and suggested fix with evidence from config, route files, canonical docs, implementation, templates, or tests -- canonical docs are context, not sole proof when implementation conflicts -- remove unsupported findings or mark open questions; validate changed claims if you edit docs - -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. - -Report completion in this shape: - -```md -Truth Check: completed - -Files reviewed: -- docs/truthmark/areas.md - -Issues found: -- none - -Fixes suggested: -- none - -Evidence checked: -- Finding: The root route index is present and maps repository truth owners. - Evidence: .truthmark/config.yml:1 / docs/truthmark/areas.md:1 - Suggested fix: none - Confidence: high - -Validation: -- truthmark check -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.codex/skills/truthmark-check/agents/openai.yaml b/.codex/skills/truthmark-check/agents/openai.yaml index bf63c58..19bd282 100644 --- a/.codex/skills/truthmark-check/agents/openai.yaml +++ b/.codex/skills/truthmark-check/agents/openai.yaml @@ -7,5 +7,5 @@ policy: allow_implicit_invocation: false truthmark: - version: "1.3.0" + version: "1.4.0" refresh_command: "truthmark init" diff --git a/.codex/skills/truthmark-check/support/procedure.md b/.codex/skills/truthmark-check/support/procedure.md new file mode 100644 index 0000000..0c0ae26 --- /dev/null +++ b/.codex/skills/truthmark-check/support/procedure.md @@ -0,0 +1,37 @@ +# Truthmark Check Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +# Truthmark Check + +Use this skill to audit repository truth health. + +Invocations: OpenCode /skill truthmark-check; Codex /truthmark-check or $truthmark-check; Claude Code /truthmark-check; GitHub Copilot /truthmark-check; Gemini CLI /truthmark:check. + +Truth Check is agent-led: + +- inspect .truthmark/config.yml, docs/truthmark/areas.md, canonical docs, and relevant implementation directly +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ +- check that current docs describe current code rather than historical plans +- check that docs/truthmark/areas.md routes code surfaces to canonical truth docs +- check for broad, catch-all, index-like, or mixed-owner truth docs and report them as topology issues requiring Truth Structure +- check that canonical behavior docs keep active Product Decisions and Rationale sections +- optionally run truthmark check when local tooling is available +- must not require the truthmark binary; direct inspection is always valid +- report issues and suggested fixes without silently rewriting unrelated files +- if follow-up docs edits are needed for mixed-owner docs, run or recommend Truth Structure before editing +Evidence Gate: +- support each finding and suggested fix with evidence from config, route files, canonical docs, implementation, templates, or tests +- canonical docs are context, not sole proof when implementation conflicts +- remove unsupported findings or mark open questions; validate changed claims if you edit docs + +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. diff --git a/.codex/skills/truthmark-check/support/report-template.md b/.codex/skills/truthmark-check/support/report-template.md new file mode 100644 index 0000000..df79cea --- /dev/null +++ b/.codex/skills/truthmark-check/support/report-template.md @@ -0,0 +1,27 @@ +# Truthmark Check Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: + +```md +Truth Check: completed + +Files reviewed: +- docs/truthmark/areas.md + +Issues found: +- none + +Fixes suggested: +- none + +Evidence checked: +- Finding: The root route index is present and maps repository truth owners. + Evidence: .truthmark/config.yml:1 / docs/truthmark/areas.md:1 + Suggested fix: none + Confidence: high + +Validation: +- truthmark check +``` diff --git a/.codex/skills/truthmark-check/support/subagents-and-leases.md b/.codex/skills/truthmark-check/support/subagents-and-leases.md new file mode 100644 index 0000000..54377b9 --- /dev/null +++ b/.codex/skills/truthmark-check/support/subagents-and-leases.md @@ -0,0 +1,10 @@ +# Truthmark Check Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Codex subagent mode: +- use automatically when this workflow runs in Codex and the parent agent chooses bounded subagent fan-out +- dispatch read-only project agents only: truth_route_auditor, truth_claim_verifier, truth_doc_reviewer +- workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns the final Truth Check report diff --git a/.codex/skills/truthmark-document/SKILL.md b/.codex/skills/truthmark-document/SKILL.md index c123523..0031fc3 100644 --- a/.codex/skills/truthmark-document/SKILL.md +++ b/.codex/skills/truthmark-document/SKILL.md @@ -3,98 +3,25 @@ name: truthmark-document description: 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. argument-hint: Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Document Use this skill to document existing implemented behavior when no functional-code changes are required for the task. + Invocations: OpenCode /skill truthmark-document; Codex /truthmark-document or $truthmark-document; Claude Code /truthmark-document; GitHub Copilot /truthmark-document; Gemini CLI /truthmark:document. -Truth Document is manual and implementation-first: +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, existing canonical docs, implementation code, and tests directly. +- Document current implemented behavior; do not invent future behavior. +- May write canonical truth docs and truth routing files only; must not write functional code. +- Read support/procedure.md before editing truth docs. +- Read support/subagents-and-leases.md before dispatching or accepting worker output. +- Read support/report-template.md before the final report. -- 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 -- inspect .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, existing canonical docs, implementation code, and tests directly -- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -- document current implemented behavior; do not invent future behavior or planned endpoints -- may write canonical truth docs and docs/truthmark/areas.md or relevant child route files only -- must not write functional code -- 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 -- block and recommend Truth Structure when routing repair is unsafe, ambiguous, or outside the task boundary -- keep feature README.md files as indexes rather than truth-document targets -- create or update bounded leaf truth docs when behavior does not fit an existing leaf doc -- keep behavior truth docs behavior-oriented, not endpoint-oriented, unless the endpoint itself is the behavior boundary -- keep API endpoint details in the nearest contract truth doc when such a doc owns the API contract -- preserve unrelated authored content -Truth-doc ownership gate: -- before editing or relying on the implemented behavior and candidate truth docs, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if the target doc is broad, mixed-owner, index-like, or the documented behavior spans independent owners, run Truth Structure first when safe and in scope; otherwise block and recommend Truth Structure -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -Product Decisions/Rationale preservation gate: -- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc -- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index -- 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 -- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing -- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked -Evidence Gate: -- route-first: map the documented behavior to bounded route owners and primary canonical docs -- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale -- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions -- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts -- remove, narrow, or block unsupported claims -- if no truth doc changed, report why current truth was already sufficient or why documentation was blocked -Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. -They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. -If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. -When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. -Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. -Align existing docs to that template while preserving accurate authored content. -If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. -Teams may edit the template files under docs/templates/ to define their local truth-doc standards. -Truth-doc shape repair gate: -- Truth Document may restructure only truth docs for the implemented behavior being documented. -- repair shape in place only after the ownership gate confirms the doc is the right bounded owner -- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work -- 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 -- preserve supported claims; remove, narrow, or block unsupported or stale claims -- report docs restructured and why a narrow edit was not sufficient -Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. -Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. - -Report completion in this shape: -```md -Truth Document: completed - -Implementation reviewed: -- src/routing/area-resolver.ts - -Truth docs created: -- docs/truth/contracts.md - -Truth docs updated: -- docs/truth/check-diagnostics.md - -Truth docs restructured: -- docs/truth/check-diagnostics.md - -Routing updated: -- docs/truthmark/areas.md - -Evidence checked: -- Claim: Route resolution behavior is documented in the contracts truth doc. - Evidence: src/routing/area-resolver.ts:14 / docs/truthmark/areas.md:9 - Result: supported - -Notes: -- Documented routing and behavior from route handlers and tests. -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.codex/skills/truthmark-document/agents/openai.yaml b/.codex/skills/truthmark-document/agents/openai.yaml index 1aeb4fc..9021cf5 100644 --- a/.codex/skills/truthmark-document/agents/openai.yaml +++ b/.codex/skills/truthmark-document/agents/openai.yaml @@ -7,5 +7,5 @@ policy: allow_implicit_invocation: false truthmark: - version: "1.3.0" + version: "1.4.0" refresh_command: "truthmark init" diff --git a/.codex/skills/truthmark-document/support/procedure.md b/.codex/skills/truthmark-document/support/procedure.md new file mode 100644 index 0000000..5b6e4a8 --- /dev/null +++ b/.codex/skills/truthmark-document/support/procedure.md @@ -0,0 +1,73 @@ +# Truthmark Document Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +# Truthmark Document + +Use this skill to document existing implemented behavior when no functional-code changes are required for the task. +Invocations: OpenCode /skill truthmark-document; Codex /truthmark-document or $truthmark-document; Claude Code /truthmark-document; GitHub Copilot /truthmark-document; Gemini CLI /truthmark:document. + +Truth Document is manual and implementation-first: + +- 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 +- inspect .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, existing canonical docs, implementation code, and tests directly +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +- document current implemented behavior; do not invent future behavior or planned endpoints +- may write canonical truth docs and docs/truthmark/areas.md or relevant child route files only +- must not write functional code +- 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 +- block and recommend Truth Structure when routing repair is unsafe, ambiguous, or outside the task boundary +- keep feature README.md files as indexes rather than truth-document targets +- create or update bounded leaf truth docs when behavior does not fit an existing leaf doc +- keep behavior truth docs behavior-oriented, not endpoint-oriented, unless the endpoint itself is the behavior boundary +- keep API endpoint details in the nearest contract truth doc when such a doc owns the API contract +- preserve unrelated authored content +Truth-doc ownership gate: +- before editing or relying on the implemented behavior and candidate truth docs, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if the target doc is broad, mixed-owner, index-like, or the documented behavior spans independent owners, run Truth Structure first when safe and in scope; otherwise block and recommend Truth Structure +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +Product Decisions/Rationale preservation gate: +- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc +- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index +- 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 +- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing +- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked +Evidence Gate: +- route-first: map the documented behavior to bounded route owners and primary canonical docs +- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale +- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions +- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts +- remove, narrow, or block unsupported claims +- if no truth doc changed, report why current truth was already sufficient or why documentation was blocked +Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. +They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. +If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. +When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. +Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. +Align existing docs to that template while preserving accurate authored content. +If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. +Teams may edit the template files under docs/templates/ to define their local truth-doc standards. +Truth-doc shape repair gate: +- Truth Document may restructure only truth docs for the implemented behavior being documented. +- repair shape in place only after the ownership gate confirms the doc is the right bounded owner +- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work +- 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 +- preserve supported claims; remove, narrow, or block unsupported or stale claims +- report docs restructured and why a narrow edit was not sufficient +Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. +Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. +Parent post-document verification: +- verify only truth docs and leased truth routing files changed during document work +- block on functional code, generated host surfaces, or unrelated diffs caused by document work +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it +- verify the final report records ownership review, structure requirement, restructure, routing update, or blocked reason when applicable diff --git a/.codex/skills/truthmark-document/support/report-template.md b/.codex/skills/truthmark-document/support/report-template.md new file mode 100644 index 0000000..19d5454 --- /dev/null +++ b/.codex/skills/truthmark-document/support/report-template.md @@ -0,0 +1,31 @@ +# Truthmark Document Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Document: completed + +Implementation reviewed: +- src/routing/area-resolver.ts + +Truth docs created: +- docs/truth/contracts.md + +Truth docs updated: +- docs/truth/check-diagnostics.md + +Truth docs restructured: +- docs/truth/check-diagnostics.md + +Routing updated: +- docs/truthmark/areas.md + +Evidence checked: +- Claim: Route resolution behavior is documented in the contracts truth doc. + Evidence: src/routing/area-resolver.ts:14 / docs/truthmark/areas.md:9 + Result: supported + +Notes: +- Documented routing and behavior from route handlers and tests. +``` diff --git a/.codex/skills/truthmark-document/support/subagents-and-leases.md b/.codex/skills/truthmark-document/support/subagents-and-leases.md new file mode 100644 index 0000000..8e97104 --- /dev/null +++ b/.codex/skills/truthmark-document/support/subagents-and-leases.md @@ -0,0 +1,14 @@ +# Truthmark Document Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Codex subagent mode: +- use automatically when this workflow runs in Codex and the parent agent chooses bounded subagent fan-out +- dispatch read-only project agents for verification: truth_route_auditor, truth_claim_verifier +- read-only workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; read-only workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- dispatch write-capable project agents only with explicit write leases: truth_doc_writer +- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields +- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes +- parent must inspect the actual checkout diff against each lease before accepting a worker report +- Parent agent owns Truth Document acceptance, lease validation, and final report diff --git a/.codex/skills/truthmark-preview/SKILL.md b/.codex/skills/truthmark-preview/SKILL.md new file mode 100644 index 0000000..9a5ed1d --- /dev/null +++ b/.codex/skills/truthmark-preview/SKILL.md @@ -0,0 +1,26 @@ +--- +name: truthmark-preview +description: Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check. +argument-hint: Optional requested outcome, code area, doc path, or routing question +user-invocable: true +truthmark-version: 1.4.0 +--- + +# Truthmark Preview + +Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits. + +Invocations: OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview. + +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and only the truth docs or implementation files needed to preview ownership. +- Truth Preview is read-only; this report is intended, not authorized. +- must not edit files and must not issue write leases; do not run Truth Sync automatically, replace Truth Check, claim final correctness, or mutate code. +- Use optional read-only route-auditor evidence only when it reduces context or clarifies ownership. +- Hand off to the selected workflow after user approval. + +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.codex/skills/truthmark-preview/agents/openai.yaml b/.codex/skills/truthmark-preview/agents/openai.yaml new file mode 100644 index 0000000..0d5f40e --- /dev/null +++ b/.codex/skills/truthmark-preview/agents/openai.yaml @@ -0,0 +1,11 @@ +interface: + display_name: "Truthmark Preview" + short_description: "Preview likely workflow routing before edits; read-only and explicit" + default_prompt: "Use $truthmark-preview to preview likely Truthmark routing before edits." + +policy: + allow_implicit_invocation: false + +truthmark: + version: "1.4.0" + refresh_command: "truthmark init" diff --git a/.codex/skills/truthmark-preview/support/procedure.md b/.codex/skills/truthmark-preview/support/procedure.md new file mode 100644 index 0000000..dd3f146 --- /dev/null +++ b/.codex/skills/truthmark-preview/support/procedure.md @@ -0,0 +1,43 @@ +# Truthmark Preview Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits. + +Invocations: OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview. + +Truth Preview is read-only. Its report is intended, not authorized. + +Purpose: +- preview the likely Truthmark workflow, route owner, target files, expected write classes, suggested subagent use, and blocking ambiguity before edits happen +- hand off to the selected workflow after user approval +- keep the selector thin so agents can avoid loading or acting through heavier workflows prematurely + +Read: +- .truthmark/config.yml +- docs/truthmark/areas.md +- relevant child route files under docs/truthmark/areas/ +- relevant truth docs and implementation files needed to preview ownership +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. + +Do not: +- must not edit files +- must not create truth docs +- must not update routing +- must not run Truth Sync automatically +- must not replace Truth Check +- must not claim final correctness +- must not issue write leases +- must not mutate code + +Suggested subagent use: +- optional read-only verifier: truth_route_auditor +- write workers: none +- leases needed: none + +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md diff --git a/.codex/skills/truthmark-preview/support/report-template.md b/.codex/skills/truthmark-preview/support/report-template.md new file mode 100644 index 0000000..7c3c08b --- /dev/null +++ b/.codex/skills/truthmark-preview/support/report-template.md @@ -0,0 +1,41 @@ +# Truthmark Preview Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Preview: completed + +Requested outcome: +- preview likely Truthmark workflow routing before edits + +Likely workflow: +- truthmark-document + +Why this workflow: +- positive trigger: document existing implemented behavior +- negative triggers considered: functional-code change, doc-first implementation, topology repair, truth audit +- forbidden adjacency considered: must not edit functional code + +Likely route owner: +- route file: docs/truthmark/areas.md +- truth doc: docs/truth/example.md +- confidence: medium + +Expected write classes: +- truth docs + +Expected target files: +- docs/truth/example.md + +Suggested subagent use: +- read-only verifiers: truth_route_auditor +- write workers: none in Preview +- leases needed: none in Preview + +Blocking ambiguity: +- none identified in preview + +Handoff: +- Run the selected Truthmark workflow after user approval. +``` diff --git a/.codex/skills/truthmark-preview/support/subagents-and-leases.md b/.codex/skills/truthmark-preview/support/subagents-and-leases.md new file mode 100644 index 0000000..6002ff2 --- /dev/null +++ b/.codex/skills/truthmark-preview/support/subagents-and-leases.md @@ -0,0 +1,10 @@ +# Truthmark Preview Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Codex subagent mode: +- use automatically when this workflow runs in Codex and the parent agent chooses bounded subagent fan-out +- dispatch read-only project agents only: truth_route_auditor +- workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns the final Truth Preview report diff --git a/.codex/skills/truthmark-realize/SKILL.md b/.codex/skills/truthmark-realize/SKILL.md index 5f34ff2..a5a0de8 100644 --- a/.codex/skills/truthmark-realize/SKILL.md +++ b/.codex/skills/truthmark-realize/SKILL.md @@ -3,7 +3,7 @@ name: truthmark-realize description: 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. argument-hint: Optional truth doc path, area, or desired code behavior to realize user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Realize @@ -12,50 +12,14 @@ Use this skill only when the user explicitly asks to realize truth docs into cod Invocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize. -Truth Realize is doc-first: +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read the source truth docs, .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files, tests, and relevant functional code directly. +- Truth docs lead; code follows. +- may write functional code only; must not edit truth docs or truth routing while realizing those docs. +- Read support/procedure.md before changing code. +- Read support/report-template.md before the final report. -- truth docs lead -- code follows -- Truth Realize never edits the truth docs it is realizing - -Workflow: - -1. Read the updated truth docs named by the user, or infer the relevant docs from docs/truthmark/areas.md. -2. Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files, tests, and the relevant functional code. -3. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -Truth-doc ownership gate: -- before editing or relying on source truth docs before writing code, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -4. Update functional code only so implementation matches bounded, current truth claims from the source docs. -5. Do not edit truth docs or truth routing while realizing those docs. -6. Run relevant tests for the changed code. -7. Report changed code files and verification steps. -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md - -Read and write boundaries: - -- may read truth docs, routing docs, and relevant functional code -- may write functional code only -- must not edit truth docs or truth routing while realizing those docs - -Report completion in this shape: - -```md -Truth Realize: completed - -Truth docs used: -- docs/truth/authentication/session-timeout.md - -Code updated: -- src/auth/session.ts - -Verification: -- npm test -- auth -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md diff --git a/.codex/skills/truthmark-realize/agents/openai.yaml b/.codex/skills/truthmark-realize/agents/openai.yaml index 812ba8d..a8e7b2e 100644 --- a/.codex/skills/truthmark-realize/agents/openai.yaml +++ b/.codex/skills/truthmark-realize/agents/openai.yaml @@ -7,5 +7,5 @@ policy: allow_implicit_invocation: false truthmark: - version: "1.3.0" + version: "1.4.0" refresh_command: "truthmark init" diff --git a/.codex/skills/truthmark-realize/support/procedure.md b/.codex/skills/truthmark-realize/support/procedure.md new file mode 100644 index 0000000..3a657a6 --- /dev/null +++ b/.codex/skills/truthmark-realize/support/procedure.md @@ -0,0 +1,42 @@ +# Truthmark Realize Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +# Truthmark Realize + +Use this skill only when the user explicitly asks to realize truth docs into code. + +Invocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize. + +Truth Realize is doc-first: + +- truth docs lead +- code follows +- Truth Realize never edits the truth docs it is realizing + +Workflow: + +1. Read the updated truth docs named by the user, or infer the relevant docs from docs/truthmark/areas.md. +2. Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files, tests, and the relevant functional code. +3. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +Truth-doc ownership gate: +- before editing or relying on source truth docs before writing code, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +4. Update functional code only so implementation matches bounded, current truth claims from the source docs. +5. Do not edit truth docs or truth routing while realizing those docs. +6. Run relevant tests for the changed code. +7. Report changed code files and verification steps. +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md + +Read and write boundaries: + +- may read truth docs, routing docs, and relevant functional code +- may write functional code only +- must not edit truth docs or truth routing while realizing those docs diff --git a/.codex/skills/truthmark-realize/support/report-template.md b/.codex/skills/truthmark-realize/support/report-template.md new file mode 100644 index 0000000..0f77d6a --- /dev/null +++ b/.codex/skills/truthmark-realize/support/report-template.md @@ -0,0 +1,18 @@ +# Truthmark Realize Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: + +```md +Truth Realize: completed + +Truth docs used: +- docs/truth/authentication/session-timeout.md + +Code updated: +- src/auth/session.ts + +Verification: +- npm test -- auth +``` diff --git a/.codex/skills/truthmark-structure/SKILL.md b/.codex/skills/truthmark-structure/SKILL.md index 339d87f..2aef662 100644 --- a/.codex/skills/truthmark-structure/SKILL.md +++ b/.codex/skills/truthmark-structure/SKILL.md @@ -1,123 +1,26 @@ --- name: truthmark-structure -description: Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, or needs split/repair. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code. +description: 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. argument-hint: Optional area, directory, or routing concern user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- +# Truthmark Structure + Use this skill to design or repair Truthmark area structure. + Invocations: OpenCode /skill truthmark-structure; Codex /truthmark-structure or $truthmark-structure; Claude Code /truthmark-structure; GitHub Copilot /truthmark-structure; Gemini CLI /truthmark:structure. -Truth Structure is agent-native: -- inspect repository layout, current docs, .truthmark/config.yml, docs/truthmark/areas.md, and relevant code directly -- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ -- define areas by product or behavior ownership, not by mechanical directory mirroring -- create or repair docs/truthmark/areas.md -- create starter truth docs when useful and when they belong in the canonical current-truth surface -- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter. -- Starter truth docs must include ## Product Decisions and ## Rationale sections. -When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. -Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. -Align existing docs to that template while preserving accurate authored content. -If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. -Teams may edit the template files under docs/templates/ to define their local truth-doc standards. -- use docs/truth/**, docs/architecture/**, or docs/standards/** for current truth destinations -- use only canonical current-truth destinations for starter truth docs -- keep active Product Decisions and Rationale in the canonical doc that owns the behavior -- preserve unrelated authored content -## Topology Governance -Truth Structure owns documentation topology. Do not depend on humans to manually organize docs/truth. Treat the configured truth root as a managed semantic root. -Inspect 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. -When topology pressure exists, repair structure before creating or extending truth docs. -Truth-doc ownership gate: -- before editing or relying on candidate route owners and current truth docs, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if a truth doc mixes independent owners, route ownership is broad, or a split is required for bounded ownership, split and reroute into bounded truth docs when safe; otherwise block with manual-review files -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -Product Decisions/Rationale preservation gate: -- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc -- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index -- 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 -- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing -- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked -Topology pressure signals: -- one area maps broad code such as src/**, app/**, server/**, services/**, or packages/** -- one area maps multiple unrelated controllers, route groups, services, or bounded contexts -- one truth doc owns unrelated behaviors or unrelated endpoint families -- the configured truth root has many direct non-index docs -- a changed controller, route, or service cannot map to a specific behavior doc -- Truth Sync would need to create a new generic truth doc because routing is too broad -- endpoint or controller names reveal domains missing from docs/truthmark/areas/** -Use these review thresholds as guidance: -- more than 10 direct truth docs in one folder -- more than 15 leaf areas in one child route file -- more than 8 truth docs mapped to one area -- more than 5 controllers mapped through one catch-all area -Repair rules: -- split broad, overloaded, or catch-all areas into behavior-owned child route files -- split mixed-owner truth docs into bounded owner docs before adding new behavior claims -- create route files under docs/truthmark/areas/ when a product/domain boundary is clear -- create behavior truth docs under the configured truth root only when behavior lacks a current doc -- README.md files are indexes, not Truth Sync targets -- prefer bounded leaf truth docs at //.md -- keep behavior truth docs behavior-oriented, not endpoint-oriented -- keep API endpoint details in the nearest contract truth doc when such a doc exists -- update routing so future Truth Sync can target small docs -- preserve existing authored docs; move or rewrite only when needed to remove ambiguity -- report Truth docs split when one broad or mixed-owner truth doc becomes multiple bounded docs -Truth-doc shape repair gate: -- Truth Structure may restructure broader routed docs when topology, ownership, or doc-shape repair is already in scope. -- repair shape in place only after the ownership gate confirms the doc is the right bounded owner -- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work -- 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 -- preserve supported claims; remove, narrow, or block unsupported or stale claims -- report docs restructured and why a narrow edit was not sufficient -Evidence Gate: -- apply the Evidence Gate before finishing when Truth Structure writes routed docs, ownership claims, Product Decisions, or Rationale -- support ownership/behavior claims with topology or primary checkout evidence from layout, implementation boundaries, docs, config, route files, tests, templates, schemas, or contracts -- tests/examples/canonical docs corroborate; remove, narrow, or block unsupported claims -Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. -Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. -- Do not finish topology repair with routed canonical current-truth docs missing Product Decisions or Rationale sections. -- If an existing canonical doc lacks either section, add the missing heading beside Current Behavior with a concise current-state placeholder or active decision. -Portable fallback: -- If this skill surface is unavailable, perform the same workflow directly from committed repository files. -- Do not require the truthmark CLI. -- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, canonical docs, and representative implementation code. -- Use a subagent only when the host supports that pattern; otherwise perform the topology repair inline. -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. -Report completion in this shape: -```md -Truth Structure: completed -Topology reviewed: -- controllers: src/auth/** -- docs root: docs/truth -- route files: docs/truthmark/areas.md -Areas reviewed: -- src/auth/** -Routing updated: -- docs/truthmark/areas.md -Truth docs created: -- docs/truth/authentication/session.md -Truth docs split: -- docs/truth/authentication/README.md -> docs/truth/authentication/session.md -Truth docs restructured: -- docs/truth/authentication/README.md -Evidence checked: -- Claim: Session behavior belongs to a dedicated Authentication truth owner. - Evidence: src/auth/** / docs/truthmark/areas.md:7 - Result: supported -Topology decisions: -- Added an Authentication area because session behavior has a distinct code surface and truth owner. -Notes: -- Added an Authentication area for session behavior. -``` + +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, current docs, and relevant code directly. +- Define areas by product or behavior ownership, not by mechanical directory mirroring. +- Do not edit functional code. +- Read support/procedure.md before writing route or starter truth-doc changes. +- Read support/report-template.md before the final report. + +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.codex/skills/truthmark-structure/agents/openai.yaml b/.codex/skills/truthmark-structure/agents/openai.yaml index 2931879..7af8e48 100644 --- a/.codex/skills/truthmark-structure/agents/openai.yaml +++ b/.codex/skills/truthmark-structure/agents/openai.yaml @@ -1,11 +1,11 @@ interface: display_name: "Truthmark Structure" - short_description: "Design or repair Truthmark area routing" - default_prompt: "Use $truthmark-structure to design or repair Truthmark area routing." + short_description: "Design, repair, or set up Truthmark area routing" + default_prompt: "Use $truthmark-structure to design, repair, or set up Truthmark area routing." policy: allow_implicit_invocation: false truthmark: - version: "1.3.0" + version: "1.4.0" refresh_command: "truthmark init" diff --git a/.codex/skills/truthmark-structure/support/procedure.md b/.codex/skills/truthmark-structure/support/procedure.md new file mode 100644 index 0000000..5eabbf7 --- /dev/null +++ b/.codex/skills/truthmark-structure/support/procedure.md @@ -0,0 +1,109 @@ +# Truthmark Structure Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Use this skill to design or repair Truthmark area structure. +Invocations: OpenCode /skill truthmark-structure; Codex /truthmark-structure or $truthmark-structure; Claude Code /truthmark-structure; GitHub Copilot /truthmark-structure; Gemini CLI /truthmark:structure. +Truth Structure is agent-native: +- inspect repository layout, current docs, .truthmark/config.yml, docs/truthmark/areas.md, and relevant code directly +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ +- define areas by product or behavior ownership, not by mechanical directory mirroring +- create or repair docs/truthmark/areas.md +- create starter truth docs when useful and when they belong in the canonical current-truth surface +- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter. +- Starter truth docs must include ## Product Decisions and ## Rationale sections. + +When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. +Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. +Align existing docs to that template while preserving accurate authored content. +If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. +Teams may edit the template files under docs/templates/ to define their local truth-doc standards. +- use docs/truth/**, docs/architecture/**, or docs/standards/** for current truth destinations +- use only canonical current-truth destinations for starter truth docs +- keep active Product Decisions and Rationale in the canonical doc that owns the behavior +- preserve unrelated authored content +## New area setup +Use 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. +Do: +- inspect the named code area +- infer bounded product or behavior ownership +- choose the owning route when ownership is clear; otherwise propose the route and block for review +- create or update the child route entry or file +- create starter truth docs only where current truth is missing +- report the initial truth boundary +Do not: +- do not edit functional code +- do not perform full behavior documentation unless evidence is inspected and the task explicitly asks for it +- do not patch broad or mixed-owner docs in place +- do not create generic catch-all docs +- do not treat README files as Sync targets +## Topology Governance +Truth Structure owns documentation topology. Do not depend on humans to manually organize docs/truth. Treat the configured truth root as a managed semantic root. +Inspect 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. +When topology pressure exists, repair structure before creating or extending truth docs. +Truth-doc ownership gate: +- before editing or relying on candidate route owners and current truth docs, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if a truth doc mixes independent owners, route ownership is broad, or a split is required for bounded ownership, split and reroute into bounded truth docs when safe; otherwise block with manual-review files +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +Product Decisions/Rationale preservation gate: +- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc +- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index +- 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 +- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing +- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked +Topology pressure signals: +- one area maps broad code such as src/**, app/**, server/**, services/**, or packages/** +- one area maps multiple unrelated controllers, route groups, services, or bounded contexts +- one truth doc owns unrelated behaviors or unrelated endpoint families +- the configured truth root has many direct non-index docs +- a changed controller, route, or service cannot map to a specific behavior doc +- Truth Sync would need to create a new generic truth doc because routing is too broad +- endpoint or controller names reveal domains missing from docs/truthmark/areas/** +Use these review thresholds as guidance: +- more than 10 direct truth docs in one folder +- more than 15 leaf areas in one child route file +- more than 8 truth docs mapped to one area +- more than 5 controllers mapped through one catch-all area +Repair rules: +- split broad, overloaded, or catch-all areas into behavior-owned child route files +- split mixed-owner truth docs into bounded owner docs before adding new behavior claims +- create route files under docs/truthmark/areas/ when a product/domain boundary is clear +- create behavior truth docs under the configured truth root only when behavior lacks a current doc +- README.md files are indexes, not Truth Sync targets +- prefer bounded leaf truth docs at //.md +- keep behavior truth docs behavior-oriented, not endpoint-oriented +- keep API endpoint details in the nearest contract truth doc when such a doc exists +- update routing so future Truth Sync can target small docs +- preserve existing authored docs; move or rewrite only when needed to remove ambiguity +- report Truth docs split when one broad or mixed-owner truth doc becomes multiple bounded docs +Truth-doc shape repair gate: +- Truth Structure may restructure broader routed docs when topology, ownership, or doc-shape repair is already in scope. +- repair shape in place only after the ownership gate confirms the doc is the right bounded owner +- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work +- 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 +- preserve supported claims; remove, narrow, or block unsupported or stale claims +- report docs restructured and why a narrow edit was not sufficient +Evidence Gate: +- apply the Evidence Gate before finishing when Truth Structure writes routed docs, ownership claims, Product Decisions, or Rationale +- support ownership/behavior claims with topology or primary checkout evidence from layout, implementation boundaries, docs, config, route files, tests, templates, schemas, or contracts +- tests/examples/canonical docs corroborate; remove, narrow, or block unsupported claims +Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. +Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. +- Do not finish topology repair with routed canonical current-truth docs missing Product Decisions or Rationale sections. +- If an existing canonical doc lacks either section, add the missing heading beside Current Behavior with a concise current-state placeholder or active decision. +Portable fallback: +- If this skill surface is unavailable, perform the same workflow directly from committed repository files. +- Do not require the truthmark CLI. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, canonical docs, and representative implementation code. +- Use a subagent only when the host supports that pattern; otherwise perform the topology repair inline. +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. diff --git a/.codex/skills/truthmark-structure/support/report-template.md b/.codex/skills/truthmark-structure/support/report-template.md new file mode 100644 index 0000000..f8cfa0d --- /dev/null +++ b/.codex/skills/truthmark-structure/support/report-template.md @@ -0,0 +1,35 @@ +# Truthmark Structure Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Structure: completed +Topology reviewed: +- controllers: src/auth/** +- docs root: docs/truth +- route files: docs/truthmark/areas.md +Areas reviewed: +- src/auth/** +Routing updated: +- docs/truthmark/areas.md +Initial truth boundary: +- Area: Authentication +- Code: src/auth/** +- Truth owner: docs/truth/authentication/session.md +- Scope: session behavior only +Truth docs created: +- docs/truth/authentication/session.md +Truth docs split: +- docs/truth/authentication/README.md -> docs/truth/authentication/session.md +Truth docs restructured: +- docs/truth/authentication/README.md +Evidence checked: +- Claim: Session behavior belongs to a dedicated Authentication truth owner. + Evidence: src/auth/** / docs/truthmark/areas.md:7 + Result: supported +Topology decisions: +- Added an Authentication area because session behavior has a distinct code surface and truth owner. +Notes: +- Added an Authentication area for session behavior. +``` diff --git a/.codex/skills/truthmark-structure/support/subagents-and-leases.md b/.codex/skills/truthmark-structure/support/subagents-and-leases.md new file mode 100644 index 0000000..0cdc369 --- /dev/null +++ b/.codex/skills/truthmark-structure/support/subagents-and-leases.md @@ -0,0 +1,10 @@ +# Truthmark Structure Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Codex subagent mode: +- use automatically when this workflow runs in Codex and the parent agent chooses bounded subagent fan-out +- dispatch read-only project agents only: truth_route_auditor +- workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns all Truth Structure writes and final topology decisions diff --git a/.codex/skills/truthmark-sync/SKILL.md b/.codex/skills/truthmark-sync/SKILL.md index 4227894..c3d5a91 100644 --- a/.codex/skills/truthmark-sync/SKILL.md +++ b/.codex/skills/truthmark-sync/SKILL.md @@ -3,135 +3,26 @@ name: truthmark-sync description: 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. argument-hint: Optional changed-code area, truth-doc area, or sync focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- +# Truthmark Sync + 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. + Invocations: OpenCode /skill truthmark-sync; Codex /truthmark-sync or $truthmark-sync; Claude Code /truthmark-sync; GitHub Copilot /truthmark-sync; Gemini CLI /truthmark:sync. -Explicit invocation runs immediately. Later functional-code changes reopen the finish-time requirement, and an earlier explicit run satisfies the finish gate only if no later functional-code changes occur. -Skip 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. -Parent workflow: -1. Inspect git status, staged changes, unstaged changes, and untracked files directly. -2. Read .truthmark/config.yml, the configured root route index at docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and relevant canonical docs. -3. Identify functional-code changes and the nearest truth docs or routing repairs. -4. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run. -6. Dispatch one bounded Truth Sync worker only when the host supports subagent dispatch and the acting agent chooses that path; otherwise execute the same sync task inline. -Topology quality gate: -- before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner -- if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc -- run Truth Structure before syncing when topology repair is safe and in scope -- block and recommend Truth Structure when topology repair is unsafe, ambiguous, or outside the current task boundary -- report the route files and changed code paths that require structure repair -- README.md files are indexes, not Truth Sync targets -- must not append behavior details to a README.md index -- create or update a bounded leaf truth doc when behavior changes do not fit an existing leaf doc -Truth-doc ownership gate: -- before editing or relying on changed functional files and impacted truth docs, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if an impacted doc is broad, mixed-owner, index-like, or the update spans independent behavior owners, run Truth Structure before syncing when safe and in scope; otherwise block and recommend Truth Structure -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -Product Decisions/Rationale preservation gate: -- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc -- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index -- 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 -- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing -- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked -When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. -Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. -Align existing docs to that template while preserving accurate authored content. -If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. -Teams may edit the template files under docs/templates/ to define their local truth-doc standards. -Truth-doc shape repair gate: -- Truth Sync may restructure only truth docs impacted by the current functional-code change. -- repair shape in place only after the ownership gate confirms the doc is the right bounded owner -- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work -- 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 -- preserve supported claims; remove, narrow, or block unsupported or stale claims -- report docs restructured and why a narrow edit was not sufficient -Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. -Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. -Evidence Gate: -- route-first: map changed functional files to bounded route owners and primary canonical docs -- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale -- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions -- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts -- remove, narrow, or block unsupported claims -- if no impacted doc changed, report why truth was already current or why sync was skipped -Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. -They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. -If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. -Optional validation tooling: -- you may run truthmark check when local tooling is available -- do not require the truthmark binary; direct checkout inspection is the canonical path -- optional validation must not replace agent judgment about docs and routing -- update Product Decisions and Rationale when a behavior change comes from a decision change -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. -### Truth Sync Worker -The parent provides the task focus and any repository context already gathered. -Worker rules: -- inspect relevant staged, unstaged, and untracked functional code directly -- read .truthmark/config.yml, docs/truthmark/areas.md, and canonical truth docs directly -- Code verification is parent-owned; report what was run or why it was not run -- may write truth docs and docs/truthmark/areas.md only for Truth Sync alignment -- must not rewrite functional code -Return result in this shape: -- status: completed | blocked -- changedCodeReviewed: string[] -- ownershipReviewed: string[] -- structureRequired?: string[] -- truthDocsUpdated: string[] -- routingDocsUpdated: string[] -- truthDocsSplit?: string[] -- evidenceChecked: { claim: string; evidence: string[]; result: supported | narrowed | removed | blocked }[] -- notes: string[] -- blockedReason?: string -- manualReviewFiles?: string[] -Parent post-sync verification: -- verify only truth docs and docs/truthmark/areas.md changed during sync -- block on any unrelated diff caused by the sync step -- block if functional code changed during sync -- verify the worker report matches the required headings and sections -- validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked -- verify the updated docs correspond to the reviewed changed-code surface -- verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired -- blocked outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files -Report completion in this shape: -```md -Truth Sync: completed -Changed code reviewed: -- src/auth/session.ts +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Skip docs-only, formatting-only, behavior-preserving renames with no truth impact, missing config, and no-code changes. +- Read .truthmark/config.yml, the configured root route index at docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and relevant canonical docs. +- direct checkout inspection is the canonical path; do not require the truthmark binary. +- May write canonical truth docs and truth routing files only; must not rewrite functional code. +- Read support/procedure.md before editing truth docs. +- Read support/subagents-and-leases.md before dispatching or accepting worker output. +- Read support/report-template.md before the final report. -Truth docs updated: -- docs/truth/repository/overview.md - -Evidence checked: -- Claim: Session timeout behavior is documented in the mapped repository truth doc. - Evidence: src/auth/session.ts:12 / docs/truthmark/areas.md:11 - Result: supported - -Notes: -- Updated session timeout behavior. -``` -Blocked report example: -```md -Truth Sync: blocked - -Reason: -- routing repair is not allowed - -Files requiring manual review: -- docs/truthmark/areas.md - -Next action: -- update routing metadata and rerun Truth Sync -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.codex/skills/truthmark-sync/agents/openai.yaml b/.codex/skills/truthmark-sync/agents/openai.yaml index 54eeff8..8cac47e 100644 --- a/.codex/skills/truthmark-sync/agents/openai.yaml +++ b/.codex/skills/truthmark-sync/agents/openai.yaml @@ -7,5 +7,5 @@ policy: allow_implicit_invocation: true truthmark: - version: "1.3.0" + version: "1.4.0" refresh_command: "truthmark init" diff --git a/.codex/skills/truthmark-sync/support/procedure.md b/.codex/skills/truthmark-sync/support/procedure.md new file mode 100644 index 0000000..e213b0e --- /dev/null +++ b/.codex/skills/truthmark-sync/support/procedure.md @@ -0,0 +1,82 @@ +# Truthmark Sync Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +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. +Invocations: OpenCode /skill truthmark-sync; Codex /truthmark-sync or $truthmark-sync; Claude Code /truthmark-sync; GitHub Copilot /truthmark-sync; Gemini CLI /truthmark:sync. +Explicit invocation runs immediately. Later functional-code changes reopen the finish-time requirement, and an earlier explicit run satisfies the finish gate only if no later functional-code changes occur. +Skip 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. +Parent workflow: +1. Inspect git status, staged changes, unstaged changes, and untracked files directly. +2. Read .truthmark/config.yml, the configured root route index at docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and relevant canonical docs. +3. Identify functional-code changes and the nearest truth docs or routing repairs. +4. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run. +6. 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. +Topology quality gate: +- before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner +- if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc +- run Truth Structure before syncing when topology repair is safe and in scope +- block and recommend Truth Structure when topology repair is unsafe, ambiguous, or outside the current task boundary +- report the route files and changed code paths that require structure repair +- README.md files are indexes, not Truth Sync targets +- must not append behavior details to a README.md index +- create or update a bounded leaf truth doc when behavior changes do not fit an existing leaf doc +Truth-doc ownership gate: +- before editing or relying on changed functional files and impacted truth docs, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if an impacted doc is broad, mixed-owner, index-like, or the update spans independent behavior owners, run Truth Structure before syncing when safe and in scope; otherwise block and recommend Truth Structure +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +Product Decisions/Rationale preservation gate: +- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc +- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index +- 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 +- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing +- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked +When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. +Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. +Align existing docs to that template while preserving accurate authored content. +If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. +Teams may edit the template files under docs/templates/ to define their local truth-doc standards. +Truth-doc shape repair gate: +- Truth Sync may restructure only truth docs impacted by the current functional-code change. +- repair shape in place only after the ownership gate confirms the doc is the right bounded owner +- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work +- 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 +- preserve supported claims; remove, narrow, or block unsupported or stale claims +- report docs restructured and why a narrow edit was not sufficient +Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. +Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. +Evidence Gate: +- route-first: map changed functional files to bounded route owners and primary canonical docs +- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale +- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions +- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts +- remove, narrow, or block unsupported claims +- if no impacted doc changed, report why truth was already current or why sync was skipped +Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. +They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. +If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. +Optional validation tooling: +- you may run truthmark check when local tooling is available +- do not require the truthmark binary; direct checkout inspection is the canonical path +- optional validation must not replace agent judgment about docs and routing +- update Product Decisions and Rationale when a behavior change comes from a decision change +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. +Parent post-sync verification: +- verify only truth docs and leased truth routing files changed during sync +- block on any unrelated diff caused by the sync step +- block if functional code changed during sync +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it +- validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked +- verify the updated docs correspond to the reviewed changed-code surface +- verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired +- blocked outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files diff --git a/.codex/skills/truthmark-sync/support/report-template.md b/.codex/skills/truthmark-sync/support/report-template.md new file mode 100644 index 0000000..ccbadff --- /dev/null +++ b/.codex/skills/truthmark-sync/support/report-template.md @@ -0,0 +1,35 @@ +# Truthmark Sync Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Sync: completed + +Changed code reviewed: +- src/auth/session.ts + +Truth docs updated: +- docs/truth/repository/overview.md + +Evidence checked: +- Claim: Session timeout behavior is documented in the mapped repository truth doc. + Evidence: src/auth/session.ts:12 / docs/truthmark/areas.md:11 + Result: supported + +Notes: +- Updated session timeout behavior. +``` +Blocked report example: +```md +Truth Sync: blocked + +Reason: +- routing repair is not allowed + +Files requiring manual review: +- docs/truthmark/areas.md + +Next action: +- update routing metadata and rerun Truth Sync +``` diff --git a/.codex/skills/truthmark-sync/support/subagents-and-leases.md b/.codex/skills/truthmark-sync/support/subagents-and-leases.md new file mode 100644 index 0000000..a969f89 --- /dev/null +++ b/.codex/skills/truthmark-sync/support/subagents-and-leases.md @@ -0,0 +1,14 @@ +# Truthmark Sync Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Codex subagent mode: +- use automatically when this workflow runs in Codex and the parent agent chooses bounded subagent fan-out +- dispatch read-only project agents for verification: truth_route_auditor, truth_claim_verifier +- read-only workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; read-only workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- dispatch write-capable project agents only with explicit write leases: truth_doc_writer +- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields +- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes +- parent must inspect the actual checkout diff against each lease before accepting a worker report +- Parent agent owns Truth Sync acceptance, lease validation, and final report diff --git a/.gemini/commands/truthmark/check.toml b/.gemini/commands/truthmark/check.toml index fff52ea..523f02e 100644 --- a/.gemini/commands/truthmark/check.toml +++ b/.gemini/commands/truthmark/check.toml @@ -5,7 +5,7 @@ name: truthmark-check description: 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. argument-hint: Optional area, doc path, or audit focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Check diff --git a/.gemini/commands/truthmark/document.toml b/.gemini/commands/truthmark/document.toml index 1c80c47..df143d0 100644 --- a/.gemini/commands/truthmark/document.toml +++ b/.gemini/commands/truthmark/document.toml @@ -5,7 +5,7 @@ name: truthmark-document description: 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. argument-hint: Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Document @@ -72,6 +72,11 @@ Truthmark hierarchy: Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. Update Product Decisions and Rationale when a decision changes behavior. +Parent post-document verification: +- verify only truth docs and leased truth routing files changed during document work +- block on functional code, generated host surfaces, or unrelated diffs caused by document work +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it +- verify the final report records ownership review, structure requirement, restructure, routing update, or blocked reason when applicable Report completion in this shape: ```md diff --git a/.gemini/commands/truthmark/preview.toml b/.gemini/commands/truthmark/preview.toml new file mode 100644 index 0000000..9258be1 --- /dev/null +++ b/.gemini/commands/truthmark/preview.toml @@ -0,0 +1,88 @@ +description = "Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check." +prompt = ''' +--- +name: truthmark-preview +description: Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check. +argument-hint: Optional requested outcome, code area, doc path, or routing question +user-invocable: true +truthmark-version: 1.4.0 +--- + +Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits. + +Invocations: OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview. + +Truth Preview is read-only. Its report is intended, not authorized. + +Purpose: +- preview the likely Truthmark workflow, route owner, target files, expected write classes, suggested subagent use, and blocking ambiguity before edits happen +- hand off to the selected workflow after user approval +- keep the selector thin so agents can avoid loading or acting through heavier workflows prematurely + +Read: +- .truthmark/config.yml +- docs/truthmark/areas.md +- relevant child route files under docs/truthmark/areas/ +- relevant truth docs and implementation files needed to preview ownership +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. + +Do not: +- must not edit files +- must not create truth docs +- must not update routing +- must not run Truth Sync automatically +- must not replace Truth Check +- must not claim final correctness +- must not issue write leases +- must not mutate code + +Suggested subagent use: +- optional read-only verifier: truth_route_auditor +- write workers: none +- leases needed: none + +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md + +Report completion in this shape: +```md +Truth Preview: completed + +Requested outcome: +- preview likely Truthmark workflow routing before edits + +Likely workflow: +- truthmark-document + +Why this workflow: +- positive trigger: document existing implemented behavior +- negative triggers considered: functional-code change, doc-first implementation, topology repair, truth audit +- forbidden adjacency considered: must not edit functional code + +Likely route owner: +- route file: docs/truthmark/areas.md +- truth doc: docs/truth/example.md +- confidence: medium + +Expected write classes: +- truth docs + +Expected target files: +- docs/truth/example.md + +Suggested subagent use: +- read-only verifiers: truth_route_auditor +- write workers: none in Preview +- leases needed: none in Preview + +Blocking ambiguity: +- none identified in preview + +Handoff: +- Run the selected Truthmark workflow after user approval. +``` +''' diff --git a/.gemini/commands/truthmark/realize.toml b/.gemini/commands/truthmark/realize.toml index 8a53599..eff73da 100644 --- a/.gemini/commands/truthmark/realize.toml +++ b/.gemini/commands/truthmark/realize.toml @@ -5,7 +5,7 @@ name: truthmark-realize description: 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. argument-hint: Optional truth doc path, area, or desired code behavior to realize user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Realize diff --git a/.gemini/commands/truthmark/structure.toml b/.gemini/commands/truthmark/structure.toml index 910a13e..f249fd0 100644 --- a/.gemini/commands/truthmark/structure.toml +++ b/.gemini/commands/truthmark/structure.toml @@ -1,11 +1,11 @@ -description = "Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, or needs split/repair. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code." +description = "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." prompt = ''' --- name: truthmark-structure -description: Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, or needs split/repair. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code. +description: 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. argument-hint: Optional area, directory, or routing concern user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- Use this skill to design or repair Truthmark area structure. @@ -20,6 +20,7 @@ Implementation code and canonical truth docs are inspected evidence for current - create starter truth docs when useful and when they belong in the canonical current-truth surface - Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter. - Starter truth docs must include ## Product Decisions and ## Rationale sections. + When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. Align existing docs to that template while preserving accurate authored content. @@ -29,6 +30,21 @@ Teams may edit the template files under docs/templates/ to define their local tr - use only canonical current-truth destinations for starter truth docs - keep active Product Decisions and Rationale in the canonical doc that owns the behavior - preserve unrelated authored content +## New area setup +Use 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. +Do: +- inspect the named code area +- infer bounded product or behavior ownership +- choose the owning route when ownership is clear; otherwise propose the route and block for review +- create or update the child route entry or file +- create starter truth docs only where current truth is missing +- report the initial truth boundary +Do not: +- do not edit functional code +- do not perform full behavior documentation unless evidence is inspected and the task explicitly asks for it +- do not patch broad or mixed-owner docs in place +- do not create generic catch-all docs +- do not treat README files as Sync targets ## Topology Governance Truth Structure owns documentation topology. Do not depend on humans to manually organize docs/truth. Treat the configured truth root as a managed semantic root. Inspect 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. @@ -108,6 +124,11 @@ Areas reviewed: - src/auth/** Routing updated: - docs/truthmark/areas.md +Initial truth boundary: +- Area: Authentication +- Code: src/auth/** +- Truth owner: docs/truth/authentication/session.md +- Scope: session behavior only Truth docs created: - docs/truth/authentication/session.md Truth docs split: diff --git a/.gemini/commands/truthmark/sync.toml b/.gemini/commands/truthmark/sync.toml index 6832403..892aa6e 100644 --- a/.gemini/commands/truthmark/sync.toml +++ b/.gemini/commands/truthmark/sync.toml @@ -5,7 +5,7 @@ name: truthmark-sync description: 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. argument-hint: Optional changed-code area, truth-doc area, or sync focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- 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. @@ -19,7 +19,7 @@ Parent workflow: 4. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. 5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run. -6. Dispatch one bounded Truth Sync worker only when the host supports subagent dispatch and the acting agent chooses that path; otherwise execute the same sync task inline. +6. 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. Topology quality gate: - before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner - if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc @@ -77,31 +77,11 @@ Truthmark hierarchy: Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. Update Product Decisions and Rationale when a decision changes behavior. -### Truth Sync Worker -The parent provides the task focus and any repository context already gathered. -Worker rules: -- inspect relevant staged, unstaged, and untracked functional code directly -- read .truthmark/config.yml, docs/truthmark/areas.md, and canonical truth docs directly -- Code verification is parent-owned; report what was run or why it was not run -- may write truth docs and docs/truthmark/areas.md only for Truth Sync alignment -- must not rewrite functional code -Return result in this shape: -- status: completed | blocked -- changedCodeReviewed: string[] -- ownershipReviewed: string[] -- structureRequired?: string[] -- truthDocsUpdated: string[] -- routingDocsUpdated: string[] -- truthDocsSplit?: string[] -- evidenceChecked: { claim: string; evidence: string[]; result: supported | narrowed | removed | blocked }[] -- notes: string[] -- blockedReason?: string -- manualReviewFiles?: string[] Parent post-sync verification: -- verify only truth docs and docs/truthmark/areas.md changed during sync +- verify only truth docs and leased truth routing files changed during sync - block on any unrelated diff caused by the sync step - block if functional code changed during sync -- verify the worker report matches the required headings and sections +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it - validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked - verify the updated docs correspond to the reviewed changed-code surface - verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired diff --git a/.github/agents/truth-claim-verifier.agent.md b/.github/agents/truth-claim-verifier.agent.md new file mode 100644 index 0000000..54dbf59 --- /dev/null +++ b/.github/agents/truth-claim-verifier.agent.md @@ -0,0 +1,19 @@ +--- +name: truth-claim-verifier +description: Read-only Truthmark claim verifier for checking canonical truth against checkout evidence. +tools: [read, search] +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Stay read-only. +Verify the behavior-bearing truth claims assigned by the parent against primary checkout evidence. +Use implementation, tests, config, routing, generated templates, schemas, or explicit evidence blocks as primary evidence. +Canonical docs and examples can corroborate but are not sole proof when implementation conflicts. +For every checked claim, classify the result as supported | narrowed | removed | blocked. +Do not edit files, stage changes, or invent missing behavior. +Return JSON only with keys: scope, filesReviewed, claimsChecked, evidence, unsupportedClaims, confidence, recommendedWorkflow, notes. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. diff --git a/.github/agents/truth-doc-reviewer.agent.md b/.github/agents/truth-doc-reviewer.agent.md new file mode 100644 index 0000000..0933fd6 --- /dev/null +++ b/.github/agents/truth-doc-reviewer.agent.md @@ -0,0 +1,18 @@ +--- +name: truth-doc-reviewer +description: Read-only Truthmark doc reviewer for shape, decision, rationale, and evidence hygiene. +tools: [read, search] +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Stay read-only. +Review assigned canonical truth docs for frontmatter, source_of_truth, required template sections, Evidence checked entries, Product Decisions, and Rationale. +Flag README.md files used as behavior truth targets, mixed-owner docs, and shape repairs that should move to Truth Structure. +Do not edit files, stage changes, or rewrite docs. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. diff --git a/.github/agents/truth-doc-writer.agent.md b/.github/agents/truth-doc-writer.agent.md new file mode 100644 index 0000000..d259bc6 --- /dev/null +++ b/.github/agents/truth-doc-writer.agent.md @@ -0,0 +1,19 @@ +--- +name: truth-doc-writer +description: Write-capable Truthmark doc worker for one parent-leased truth-document shard. +tools: [read, search, edit] +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Write one leased Truthmark truth-document shard assigned by the parent. +Require an explicit write lease before editing. The lease must name workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields. +Read every requiredReads entry directly before editing. +Edit 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. +Do not expand your own write scope. If the task needs an off-lease file, stop and report blocked. +Block 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. +Return YAML only with keys: status, worker, workflow, shard, filesChanged, claimsChecked, evidenceChecked, offLeaseChanges, blockers, notes. +status must be completed or blocked. +filesChanged must list only files you actually changed. +offLeaseChanges must be empty for completed reports. +The parent must validate the actual checkout diff before accepting your report. diff --git a/.github/agents/truth-route-auditor.agent.md b/.github/agents/truth-route-auditor.agent.md new file mode 100644 index 0000000..f05b5b4 --- /dev/null +++ b/.github/agents/truth-route-auditor.agent.md @@ -0,0 +1,19 @@ +--- +name: truth-route-auditor +description: Read-only Truthmark route auditor for bounded routing and ownership verification. +tools: [read, search] +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Stay read-only. +Audit one bounded Truthmark route, area, or doc shard assigned by the parent. +Read .truthmark/config.yml, the root route index, relevant child route files, mapped truth docs, and relevant implementation files directly. +Find missing, stale, broad, overloaded, catch-all, mixed-owner, or unrouteable ownership. +Do not edit files, stage changes, or propose broad rewrites. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index bea23c3..9357698 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,14 +1,22 @@ +Follow `docs/ai/repo-rules.md`. + +Use that file as the primary repository instruction source for this agent. + +Agent-specific: +- Read `docs/README.md` only when choosing or updating canonical docs. +- Use `docs/ai/agent-onboarding.md` only when task routing is unclear or cross-area. + ## Truthmark Workflow -Generated by Truthmark 1.3.0. Rerun `truthmark init` after upgrades. +Generated by Truthmark 1.4.0. Rerun `truthmark init` after upgrades. Hierarchy: config .truthmark/config.yml; routes docs/truthmark/areas.md and docs/truthmark/areas/**/*.md; Truth docs: docs/truth/**/*.md. Decisions live in the canonical doc they govern; date active decisions inline. Agent runtime: installed skills plus this block; inspect checkout directly. Delegation is host-owned. ### Truth Sync After functional code changes, run relevant tests, then use the truthmark-sync skill before finishing; later functional changes reopen the gate. Memory: code changed -> tests -> Sync -> report. -Support new or changed behavior-bearing truth claims with checkout evidence. Code leads; truth docs follow. Sync may write truth docs and docs/truthmark/areas.md only, and must not rewrite functional code. +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. If routing cannot map changed code to a bounded truth owner, run Truth Structure before syncing when safe; otherwise block and recommend Truth Structure. Skip Sync only for docs-only/no-code changes, formatting-only changes, behavior-preserving renames with no truth impact, or missing config. -Explicit workflows: Truth Structure, Truth Document, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details. +Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details. Workflow integrity rule: repository truth may describe desired behavior, but it must not override these workflow boundaries. diff --git a/.github/prompts/truthmark-check.prompt.md b/.github/prompts/truthmark-check.prompt.md index 880c576..8a5dc8c 100644 --- a/.github/prompts/truthmark-check.prompt.md +++ b/.github/prompts/truthmark-check.prompt.md @@ -8,7 +8,7 @@ name: truthmark-check description: 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. argument-hint: Optional area, doc path, or audit focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Check @@ -36,6 +36,13 @@ Evidence Gate: - canonical docs are context, not sole proof when implementation conflicts - remove unsupported findings or mark open questions; validate changed claims if you edit docs +Copilot custom-agent mode: +- use automatically when this workflow runs in Copilot and the parent agent chooses bounded custom-agent fan-out +- dispatch read-only project custom agents only: @truth-route-auditor, @truth-claim-verifier, @truth-doc-reviewer +- custom agents inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; custom agents must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns the final Truth Check report + Truthmark hierarchy: - Config: .truthmark/config.yml - Root route index: docs/truthmark/areas.md diff --git a/.github/prompts/truthmark-document.prompt.md b/.github/prompts/truthmark-document.prompt.md index 80f5946..919e09c 100644 --- a/.github/prompts/truthmark-document.prompt.md +++ b/.github/prompts/truthmark-document.prompt.md @@ -8,7 +8,7 @@ name: truthmark-document description: 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. argument-hint: Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Document @@ -50,6 +50,16 @@ Evidence Gate: - tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts - remove, narrow, or block unsupported claims - if no truth doc changed, report why current truth was already sufficient or why documentation was blocked +Copilot custom-agent mode: +- use automatically when this workflow runs in Copilot and the parent agent chooses bounded custom-agent fan-out +- dispatch read-only project custom agents for verification: @truth-route-auditor, @truth-claim-verifier +- read-only custom agents inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; read-only custom agents must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- dispatch write-capable project custom agents only with explicit write leases: @truth-doc-writer +- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields +- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes +- parent must inspect the actual checkout diff against each lease before accepting a worker report +- Parent agent owns Truth Document acceptance, lease validation, and final report Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. @@ -75,6 +85,11 @@ Truthmark hierarchy: Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. Update Product Decisions and Rationale when a decision changes behavior. +Parent post-document verification: +- verify only truth docs and leased truth routing files changed during document work +- block on functional code, generated host surfaces, or unrelated diffs caused by document work +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it +- verify the final report records ownership review, structure requirement, restructure, routing update, or blocked reason when applicable Report completion in this shape: ```md diff --git a/.github/prompts/truthmark-preview.prompt.md b/.github/prompts/truthmark-preview.prompt.md new file mode 100644 index 0000000..75168ad --- /dev/null +++ b/.github/prompts/truthmark-preview.prompt.md @@ -0,0 +1,90 @@ +--- +agent: 'agent' +description: 'Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check.' +--- + +--- +name: truthmark-preview +description: Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check. +argument-hint: Optional requested outcome, code area, doc path, or routing question +user-invocable: true +truthmark-version: 1.4.0 +--- + +Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits. + +Invocations: OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview. + +Truth Preview is read-only. Its report is intended, not authorized. + +Purpose: +- preview the likely Truthmark workflow, route owner, target files, expected write classes, suggested subagent use, and blocking ambiguity before edits happen +- hand off to the selected workflow after user approval +- keep the selector thin so agents can avoid loading or acting through heavier workflows prematurely + +Read: +- .truthmark/config.yml +- docs/truthmark/areas.md +- relevant child route files under docs/truthmark/areas/ +- relevant truth docs and implementation files needed to preview ownership +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. + +Do not: +- must not edit files +- must not create truth docs +- must not update routing +- must not run Truth Sync automatically +- must not replace Truth Check +- must not claim final correctness +- must not issue write leases +- must not mutate code + +Suggested subagent use: +- optional read-only verifier: truth_route_auditor +- write workers: none +- leases needed: none + +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md + +Report completion in this shape: +```md +Truth Preview: completed + +Requested outcome: +- preview likely Truthmark workflow routing before edits + +Likely workflow: +- truthmark-document + +Why this workflow: +- positive trigger: document existing implemented behavior +- negative triggers considered: functional-code change, doc-first implementation, topology repair, truth audit +- forbidden adjacency considered: must not edit functional code + +Likely route owner: +- route file: docs/truthmark/areas.md +- truth doc: docs/truth/example.md +- confidence: medium + +Expected write classes: +- truth docs + +Expected target files: +- docs/truth/example.md + +Suggested subagent use: +- read-only verifiers: truth_route_auditor +- write workers: none in Preview +- leases needed: none in Preview + +Blocking ambiguity: +- none identified in preview + +Handoff: +- Run the selected Truthmark workflow after user approval. +``` diff --git a/.github/prompts/truthmark-realize.prompt.md b/.github/prompts/truthmark-realize.prompt.md index 268625e..b5c38c6 100644 --- a/.github/prompts/truthmark-realize.prompt.md +++ b/.github/prompts/truthmark-realize.prompt.md @@ -8,7 +8,7 @@ name: truthmark-realize description: 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. argument-hint: Optional truth doc path, area, or desired code behavior to realize user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Realize diff --git a/.github/prompts/truthmark-structure.prompt.md b/.github/prompts/truthmark-structure.prompt.md index 4fffc87..9dd8068 100644 --- a/.github/prompts/truthmark-structure.prompt.md +++ b/.github/prompts/truthmark-structure.prompt.md @@ -1,14 +1,14 @@ --- agent: 'agent' -description: 'Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, or needs split/repair. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code.' +description: '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.' --- --- name: truthmark-structure -description: Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, or needs split/repair. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code. +description: 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. argument-hint: Optional area, directory, or routing concern user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- Use this skill to design or repair Truthmark area structure. @@ -23,6 +23,13 @@ Implementation code and canonical truth docs are inspected evidence for current - create starter truth docs when useful and when they belong in the canonical current-truth surface - Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter. - Starter truth docs must include ## Product Decisions and ## Rationale sections. +Copilot custom-agent mode: +- use automatically when this workflow runs in Copilot and the parent agent chooses bounded custom-agent fan-out +- dispatch read-only project custom agents only: @truth-route-auditor +- custom agents inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; custom agents must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns all Truth Structure writes and final topology decisions + When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. Align existing docs to that template while preserving accurate authored content. @@ -32,6 +39,21 @@ Teams may edit the template files under docs/templates/ to define their local tr - use only canonical current-truth destinations for starter truth docs - keep active Product Decisions and Rationale in the canonical doc that owns the behavior - preserve unrelated authored content +## New area setup +Use 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. +Do: +- inspect the named code area +- infer bounded product or behavior ownership +- choose the owning route when ownership is clear; otherwise propose the route and block for review +- create or update the child route entry or file +- create starter truth docs only where current truth is missing +- report the initial truth boundary +Do not: +- do not edit functional code +- do not perform full behavior documentation unless evidence is inspected and the task explicitly asks for it +- do not patch broad or mixed-owner docs in place +- do not create generic catch-all docs +- do not treat README files as Sync targets ## Topology Governance Truth Structure owns documentation topology. Do not depend on humans to manually organize docs/truth. Treat the configured truth root as a managed semantic root. Inspect 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. @@ -111,6 +133,11 @@ Areas reviewed: - src/auth/** Routing updated: - docs/truthmark/areas.md +Initial truth boundary: +- Area: Authentication +- Code: src/auth/** +- Truth owner: docs/truth/authentication/session.md +- Scope: session behavior only Truth docs created: - docs/truth/authentication/session.md Truth docs split: diff --git a/.github/prompts/truthmark-sync.prompt.md b/.github/prompts/truthmark-sync.prompt.md index 6e20d07..f48aad6 100644 --- a/.github/prompts/truthmark-sync.prompt.md +++ b/.github/prompts/truthmark-sync.prompt.md @@ -8,7 +8,7 @@ name: truthmark-sync description: 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. argument-hint: Optional changed-code area, truth-doc area, or sync focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- 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. @@ -22,7 +22,17 @@ Parent workflow: 4. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. 5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run. -6. Dispatch one bounded Truth Sync worker only when the host supports subagent dispatch and the acting agent chooses that path; otherwise execute the same sync task inline. +6. 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. +Copilot custom-agent mode: +- use automatically when this workflow runs in Copilot and the parent agent chooses bounded custom-agent fan-out +- dispatch read-only project custom agents for verification: @truth-route-auditor, @truth-claim-verifier +- read-only custom agents inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; read-only custom agents must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- dispatch write-capable project custom agents only with explicit write leases: @truth-doc-writer +- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields +- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes +- parent must inspect the actual checkout diff against each lease before accepting a worker report +- Parent agent owns Truth Sync acceptance, lease validation, and final report Topology quality gate: - before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner - if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc @@ -80,31 +90,11 @@ Truthmark hierarchy: Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. Update Product Decisions and Rationale when a decision changes behavior. -### Truth Sync Worker -The parent provides the task focus and any repository context already gathered. -Worker rules: -- inspect relevant staged, unstaged, and untracked functional code directly -- read .truthmark/config.yml, docs/truthmark/areas.md, and canonical truth docs directly -- Code verification is parent-owned; report what was run or why it was not run -- may write truth docs and docs/truthmark/areas.md only for Truth Sync alignment -- must not rewrite functional code -Return result in this shape: -- status: completed | blocked -- changedCodeReviewed: string[] -- ownershipReviewed: string[] -- structureRequired?: string[] -- truthDocsUpdated: string[] -- routingDocsUpdated: string[] -- truthDocsSplit?: string[] -- evidenceChecked: { claim: string; evidence: string[]; result: supported | narrowed | removed | blocked }[] -- notes: string[] -- blockedReason?: string -- manualReviewFiles?: string[] Parent post-sync verification: -- verify only truth docs and docs/truthmark/areas.md changed during sync +- verify only truth docs and leased truth routing files changed during sync - block on any unrelated diff caused by the sync step - block if functional code changed during sync -- verify the worker report matches the required headings and sections +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it - validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked - verify the updated docs correspond to the reviewed changed-code surface - verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired diff --git a/.opencode/agents/truth-claim-verifier.md b/.opencode/agents/truth-claim-verifier.md new file mode 100644 index 0000000..3ec3937 --- /dev/null +++ b/.opencode/agents/truth-claim-verifier.md @@ -0,0 +1,33 @@ +--- +description: Read-only Truthmark claim verifier for checking canonical truth against checkout evidence. +mode: subagent +permission: + edit: deny + task: deny + webfetch: deny + websearch: deny + external_directory: deny + bash: + "*": ask + "git status*": allow + "git diff*": allow + "git log*": allow + "rg *": allow + "grep *": allow +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Manual invocation: @truth-claim-verifier + +Stay read-only. +Verify the behavior-bearing truth claims assigned by the parent against primary checkout evidence. +Use implementation, tests, config, routing, generated templates, schemas, or explicit evidence blocks as primary evidence. +Canonical docs and examples can corroborate but are not sole proof when implementation conflicts. +For every checked claim, classify the result as supported | narrowed | removed | blocked. +Do not edit files, stage changes, or invent missing behavior. +Return JSON only with keys: scope, filesReviewed, claimsChecked, evidence, unsupportedClaims, confidence, recommendedWorkflow, notes. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. diff --git a/.opencode/agents/truth-doc-reviewer.md b/.opencode/agents/truth-doc-reviewer.md new file mode 100644 index 0000000..beea2de --- /dev/null +++ b/.opencode/agents/truth-doc-reviewer.md @@ -0,0 +1,32 @@ +--- +description: Read-only Truthmark doc reviewer for shape, decision, rationale, and evidence hygiene. +mode: subagent +permission: + edit: deny + task: deny + webfetch: deny + websearch: deny + external_directory: deny + bash: + "*": ask + "git status*": allow + "git diff*": allow + "git log*": allow + "rg *": allow + "grep *": allow +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Manual invocation: @truth-doc-reviewer + +Stay read-only. +Review assigned canonical truth docs for frontmatter, source_of_truth, required template sections, Evidence checked entries, Product Decisions, and Rationale. +Flag README.md files used as behavior truth targets, mixed-owner docs, and shape repairs that should move to Truth Structure. +Do not edit files, stage changes, or rewrite docs. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. diff --git a/.opencode/agents/truth-doc-writer.md b/.opencode/agents/truth-doc-writer.md new file mode 100644 index 0000000..b25fbb6 --- /dev/null +++ b/.opencode/agents/truth-doc-writer.md @@ -0,0 +1,38 @@ +--- +description: Write-capable Truthmark doc worker for one parent-leased truth-document shard. +mode: subagent +permission: + read: allow + list: allow + grep: allow + glob: allow + edit: + "*": deny + "docs/truth/**": allow + "docs/truthmark/areas.md": allow + "docs/truthmark/areas/**/*.md": allow + task: deny + webfetch: deny + websearch: deny + external_directory: deny + bash: + "*": ask + "git status*": allow + "git diff*": allow +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Manual invocation: @truth-doc-writer + +Write one leased Truthmark truth-document shard assigned by the parent. +Require an explicit write lease before editing. The lease must name workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields. +Read every requiredReads entry directly before editing. +Edit 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. +Do not expand your own write scope. If the task needs an off-lease file, stop and report blocked. +Block 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. +Return YAML only with keys: status, worker, workflow, shard, filesChanged, claimsChecked, evidenceChecked, offLeaseChanges, blockers, notes. +status must be completed or blocked. +filesChanged must list only files you actually changed. +offLeaseChanges must be empty for completed reports. +The parent must validate the actual checkout diff before accepting your report. diff --git a/.opencode/agents/truth-route-auditor.md b/.opencode/agents/truth-route-auditor.md new file mode 100644 index 0000000..25a14ac --- /dev/null +++ b/.opencode/agents/truth-route-auditor.md @@ -0,0 +1,33 @@ +--- +description: Read-only Truthmark route auditor for bounded routing and ownership verification. +mode: subagent +permission: + edit: deny + task: deny + webfetch: deny + websearch: deny + external_directory: deny + bash: + "*": ask + "git status*": allow + "git diff*": allow + "git log*": allow + "rg *": allow + "grep *": allow +--- + +# Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Manual invocation: @truth-route-auditor + +Stay read-only. +Audit one bounded Truthmark route, area, or doc shard assigned by the parent. +Read .truthmark/config.yml, the root route index, relevant child route files, mapped truth docs, and relevant implementation files directly. +Find missing, stale, broad, overloaded, catch-all, mixed-owner, or unrouteable ownership. +Do not edit files, stage changes, or propose broad rewrites. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure. +Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes. diff --git a/.opencode/skills/truthmark-check/SKILL.md b/.opencode/skills/truthmark-check/SKILL.md index 2c9d6c2..9be2399 100644 --- a/.opencode/skills/truthmark-check/SKILL.md +++ b/.opencode/skills/truthmark-check/SKILL.md @@ -3,7 +3,7 @@ name: truthmark-check description: 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. argument-hint: Optional area, doc path, or audit focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Check @@ -12,54 +12,16 @@ Use this skill to audit repository truth health. Invocations: OpenCode /skill truthmark-check; Codex /truthmark-check or $truthmark-check; Claude Code /truthmark-check; GitHub Copilot /truthmark-check; Gemini CLI /truthmark:check. -Truth Check is agent-led: +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, canonical docs, and relevant implementation directly. +- Report issues and suggested fixes; do not silently rewrite unrelated files. +- Direct checkout inspection is valid even when local tooling is unavailable. +- Read support/procedure.md before auditing details. +- Read support/subagents-and-leases.md before dispatching verifier subagents. +- Read support/report-template.md before the final report. -- inspect .truthmark/config.yml, docs/truthmark/areas.md, canonical docs, and relevant implementation directly -- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ -- check that current docs describe current code rather than historical plans -- check that docs/truthmark/areas.md routes code surfaces to canonical truth docs -- check for broad, catch-all, index-like, or mixed-owner truth docs and report them as topology issues requiring Truth Structure -- check that canonical behavior docs keep active Product Decisions and Rationale sections -- optionally run truthmark check when local tooling is available -- must not require the truthmark binary; direct inspection is always valid -- report issues and suggested fixes without silently rewriting unrelated files -- if follow-up docs edits are needed for mixed-owner docs, run or recommend Truth Structure before editing -Evidence Gate: -- support each finding and suggested fix with evidence from config, route files, canonical docs, implementation, templates, or tests -- canonical docs are context, not sole proof when implementation conflicts -- remove unsupported findings or mark open questions; validate changed claims if you edit docs - -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. - -Report completion in this shape: - -```md -Truth Check: completed - -Files reviewed: -- docs/truthmark/areas.md - -Issues found: -- none - -Fixes suggested: -- none - -Evidence checked: -- Finding: The root route index is present and maps repository truth owners. - Evidence: .truthmark/config.yml:1 / docs/truthmark/areas.md:1 - Suggested fix: none - Confidence: high - -Validation: -- truthmark check -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.opencode/skills/truthmark-check/support/procedure.md b/.opencode/skills/truthmark-check/support/procedure.md new file mode 100644 index 0000000..0c0ae26 --- /dev/null +++ b/.opencode/skills/truthmark-check/support/procedure.md @@ -0,0 +1,37 @@ +# Truthmark Check Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +# Truthmark Check + +Use this skill to audit repository truth health. + +Invocations: OpenCode /skill truthmark-check; Codex /truthmark-check or $truthmark-check; Claude Code /truthmark-check; GitHub Copilot /truthmark-check; Gemini CLI /truthmark:check. + +Truth Check is agent-led: + +- inspect .truthmark/config.yml, docs/truthmark/areas.md, canonical docs, and relevant implementation directly +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ +- check that current docs describe current code rather than historical plans +- check that docs/truthmark/areas.md routes code surfaces to canonical truth docs +- check for broad, catch-all, index-like, or mixed-owner truth docs and report them as topology issues requiring Truth Structure +- check that canonical behavior docs keep active Product Decisions and Rationale sections +- optionally run truthmark check when local tooling is available +- must not require the truthmark binary; direct inspection is always valid +- report issues and suggested fixes without silently rewriting unrelated files +- if follow-up docs edits are needed for mixed-owner docs, run or recommend Truth Structure before editing +Evidence Gate: +- support each finding and suggested fix with evidence from config, route files, canonical docs, implementation, templates, or tests +- canonical docs are context, not sole proof when implementation conflicts +- remove unsupported findings or mark open questions; validate changed claims if you edit docs + +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. diff --git a/.opencode/skills/truthmark-check/support/report-template.md b/.opencode/skills/truthmark-check/support/report-template.md new file mode 100644 index 0000000..df79cea --- /dev/null +++ b/.opencode/skills/truthmark-check/support/report-template.md @@ -0,0 +1,27 @@ +# Truthmark Check Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: + +```md +Truth Check: completed + +Files reviewed: +- docs/truthmark/areas.md + +Issues found: +- none + +Fixes suggested: +- none + +Evidence checked: +- Finding: The root route index is present and maps repository truth owners. + Evidence: .truthmark/config.yml:1 / docs/truthmark/areas.md:1 + Suggested fix: none + Confidence: high + +Validation: +- truthmark check +``` diff --git a/.opencode/skills/truthmark-check/support/subagents-and-leases.md b/.opencode/skills/truthmark-check/support/subagents-and-leases.md new file mode 100644 index 0000000..3edcd02 --- /dev/null +++ b/.opencode/skills/truthmark-check/support/subagents-and-leases.md @@ -0,0 +1,10 @@ +# Truthmark Check Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +OpenCode subagent mode: +- use automatically when this workflow runs in OpenCode and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents only: @truth-route-auditor, @truth-claim-verifier, @truth-doc-reviewer +- workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns the final Truth Check report diff --git a/.opencode/skills/truthmark-document/SKILL.md b/.opencode/skills/truthmark-document/SKILL.md index c123523..0031fc3 100644 --- a/.opencode/skills/truthmark-document/SKILL.md +++ b/.opencode/skills/truthmark-document/SKILL.md @@ -3,98 +3,25 @@ name: truthmark-document description: 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. argument-hint: Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Document Use this skill to document existing implemented behavior when no functional-code changes are required for the task. + Invocations: OpenCode /skill truthmark-document; Codex /truthmark-document or $truthmark-document; Claude Code /truthmark-document; GitHub Copilot /truthmark-document; Gemini CLI /truthmark:document. -Truth Document is manual and implementation-first: +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, existing canonical docs, implementation code, and tests directly. +- Document current implemented behavior; do not invent future behavior. +- May write canonical truth docs and truth routing files only; must not write functional code. +- Read support/procedure.md before editing truth docs. +- Read support/subagents-and-leases.md before dispatching or accepting worker output. +- Read support/report-template.md before the final report. -- 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 -- inspect .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, existing canonical docs, implementation code, and tests directly -- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -- document current implemented behavior; do not invent future behavior or planned endpoints -- may write canonical truth docs and docs/truthmark/areas.md or relevant child route files only -- must not write functional code -- 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 -- block and recommend Truth Structure when routing repair is unsafe, ambiguous, or outside the task boundary -- keep feature README.md files as indexes rather than truth-document targets -- create or update bounded leaf truth docs when behavior does not fit an existing leaf doc -- keep behavior truth docs behavior-oriented, not endpoint-oriented, unless the endpoint itself is the behavior boundary -- keep API endpoint details in the nearest contract truth doc when such a doc owns the API contract -- preserve unrelated authored content -Truth-doc ownership gate: -- before editing or relying on the implemented behavior and candidate truth docs, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if the target doc is broad, mixed-owner, index-like, or the documented behavior spans independent owners, run Truth Structure first when safe and in scope; otherwise block and recommend Truth Structure -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -Product Decisions/Rationale preservation gate: -- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc -- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index -- 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 -- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing -- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked -Evidence Gate: -- route-first: map the documented behavior to bounded route owners and primary canonical docs -- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale -- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions -- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts -- remove, narrow, or block unsupported claims -- if no truth doc changed, report why current truth was already sufficient or why documentation was blocked -Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. -They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. -If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. -When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. -Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. -Align existing docs to that template while preserving accurate authored content. -If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. -Teams may edit the template files under docs/templates/ to define their local truth-doc standards. -Truth-doc shape repair gate: -- Truth Document may restructure only truth docs for the implemented behavior being documented. -- repair shape in place only after the ownership gate confirms the doc is the right bounded owner -- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work -- 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 -- preserve supported claims; remove, narrow, or block unsupported or stale claims -- report docs restructured and why a narrow edit was not sufficient -Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. -Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. - -Report completion in this shape: -```md -Truth Document: completed - -Implementation reviewed: -- src/routing/area-resolver.ts - -Truth docs created: -- docs/truth/contracts.md - -Truth docs updated: -- docs/truth/check-diagnostics.md - -Truth docs restructured: -- docs/truth/check-diagnostics.md - -Routing updated: -- docs/truthmark/areas.md - -Evidence checked: -- Claim: Route resolution behavior is documented in the contracts truth doc. - Evidence: src/routing/area-resolver.ts:14 / docs/truthmark/areas.md:9 - Result: supported - -Notes: -- Documented routing and behavior from route handlers and tests. -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.opencode/skills/truthmark-document/support/procedure.md b/.opencode/skills/truthmark-document/support/procedure.md new file mode 100644 index 0000000..5b6e4a8 --- /dev/null +++ b/.opencode/skills/truthmark-document/support/procedure.md @@ -0,0 +1,73 @@ +# Truthmark Document Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +# Truthmark Document + +Use this skill to document existing implemented behavior when no functional-code changes are required for the task. +Invocations: OpenCode /skill truthmark-document; Codex /truthmark-document or $truthmark-document; Claude Code /truthmark-document; GitHub Copilot /truthmark-document; Gemini CLI /truthmark:document. + +Truth Document is manual and implementation-first: + +- 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 +- inspect .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, existing canonical docs, implementation code, and tests directly +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +- document current implemented behavior; do not invent future behavior or planned endpoints +- may write canonical truth docs and docs/truthmark/areas.md or relevant child route files only +- must not write functional code +- 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 +- block and recommend Truth Structure when routing repair is unsafe, ambiguous, or outside the task boundary +- keep feature README.md files as indexes rather than truth-document targets +- create or update bounded leaf truth docs when behavior does not fit an existing leaf doc +- keep behavior truth docs behavior-oriented, not endpoint-oriented, unless the endpoint itself is the behavior boundary +- keep API endpoint details in the nearest contract truth doc when such a doc owns the API contract +- preserve unrelated authored content +Truth-doc ownership gate: +- before editing or relying on the implemented behavior and candidate truth docs, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if the target doc is broad, mixed-owner, index-like, or the documented behavior spans independent owners, run Truth Structure first when safe and in scope; otherwise block and recommend Truth Structure +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +Product Decisions/Rationale preservation gate: +- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc +- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index +- 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 +- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing +- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked +Evidence Gate: +- route-first: map the documented behavior to bounded route owners and primary canonical docs +- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale +- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions +- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts +- remove, narrow, or block unsupported claims +- if no truth doc changed, report why current truth was already sufficient or why documentation was blocked +Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. +They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. +If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. +When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. +Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. +Align existing docs to that template while preserving accurate authored content. +If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. +Teams may edit the template files under docs/templates/ to define their local truth-doc standards. +Truth-doc shape repair gate: +- Truth Document may restructure only truth docs for the implemented behavior being documented. +- repair shape in place only after the ownership gate confirms the doc is the right bounded owner +- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work +- 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 +- preserve supported claims; remove, narrow, or block unsupported or stale claims +- report docs restructured and why a narrow edit was not sufficient +Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. +Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. +Parent post-document verification: +- verify only truth docs and leased truth routing files changed during document work +- block on functional code, generated host surfaces, or unrelated diffs caused by document work +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it +- verify the final report records ownership review, structure requirement, restructure, routing update, or blocked reason when applicable diff --git a/.opencode/skills/truthmark-document/support/report-template.md b/.opencode/skills/truthmark-document/support/report-template.md new file mode 100644 index 0000000..19d5454 --- /dev/null +++ b/.opencode/skills/truthmark-document/support/report-template.md @@ -0,0 +1,31 @@ +# Truthmark Document Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Document: completed + +Implementation reviewed: +- src/routing/area-resolver.ts + +Truth docs created: +- docs/truth/contracts.md + +Truth docs updated: +- docs/truth/check-diagnostics.md + +Truth docs restructured: +- docs/truth/check-diagnostics.md + +Routing updated: +- docs/truthmark/areas.md + +Evidence checked: +- Claim: Route resolution behavior is documented in the contracts truth doc. + Evidence: src/routing/area-resolver.ts:14 / docs/truthmark/areas.md:9 + Result: supported + +Notes: +- Documented routing and behavior from route handlers and tests. +``` diff --git a/.opencode/skills/truthmark-document/support/subagents-and-leases.md b/.opencode/skills/truthmark-document/support/subagents-and-leases.md new file mode 100644 index 0000000..b2ef6cb --- /dev/null +++ b/.opencode/skills/truthmark-document/support/subagents-and-leases.md @@ -0,0 +1,14 @@ +# Truthmark Document Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +OpenCode subagent mode: +- use automatically when this workflow runs in OpenCode and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents for verification: @truth-route-auditor, @truth-claim-verifier +- read-only workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; read-only workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- dispatch write-capable project subagents only with explicit write leases: @truth-doc-writer +- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields +- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes +- parent must inspect the actual checkout diff against each lease before accepting a worker report +- Parent agent owns Truth Document acceptance, lease validation, and final report diff --git a/.opencode/skills/truthmark-preview/SKILL.md b/.opencode/skills/truthmark-preview/SKILL.md new file mode 100644 index 0000000..9a5ed1d --- /dev/null +++ b/.opencode/skills/truthmark-preview/SKILL.md @@ -0,0 +1,26 @@ +--- +name: truthmark-preview +description: Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check. +argument-hint: Optional requested outcome, code area, doc path, or routing question +user-invocable: true +truthmark-version: 1.4.0 +--- + +# Truthmark Preview + +Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits. + +Invocations: OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview. + +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and only the truth docs or implementation files needed to preview ownership. +- Truth Preview is read-only; this report is intended, not authorized. +- must not edit files and must not issue write leases; do not run Truth Sync automatically, replace Truth Check, claim final correctness, or mutate code. +- Use optional read-only route-auditor evidence only when it reduces context or clarifies ownership. +- Hand off to the selected workflow after user approval. + +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.opencode/skills/truthmark-preview/support/procedure.md b/.opencode/skills/truthmark-preview/support/procedure.md new file mode 100644 index 0000000..dd3f146 --- /dev/null +++ b/.opencode/skills/truthmark-preview/support/procedure.md @@ -0,0 +1,43 @@ +# Truthmark Preview Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits. + +Invocations: OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview. + +Truth Preview is read-only. Its report is intended, not authorized. + +Purpose: +- preview the likely Truthmark workflow, route owner, target files, expected write classes, suggested subagent use, and blocking ambiguity before edits happen +- hand off to the selected workflow after user approval +- keep the selector thin so agents can avoid loading or acting through heavier workflows prematurely + +Read: +- .truthmark/config.yml +- docs/truthmark/areas.md +- relevant child route files under docs/truthmark/areas/ +- relevant truth docs and implementation files needed to preview ownership +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. + +Do not: +- must not edit files +- must not create truth docs +- must not update routing +- must not run Truth Sync automatically +- must not replace Truth Check +- must not claim final correctness +- must not issue write leases +- must not mutate code + +Suggested subagent use: +- optional read-only verifier: truth_route_auditor +- write workers: none +- leases needed: none + +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md diff --git a/.opencode/skills/truthmark-preview/support/report-template.md b/.opencode/skills/truthmark-preview/support/report-template.md new file mode 100644 index 0000000..7c3c08b --- /dev/null +++ b/.opencode/skills/truthmark-preview/support/report-template.md @@ -0,0 +1,41 @@ +# Truthmark Preview Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Preview: completed + +Requested outcome: +- preview likely Truthmark workflow routing before edits + +Likely workflow: +- truthmark-document + +Why this workflow: +- positive trigger: document existing implemented behavior +- negative triggers considered: functional-code change, doc-first implementation, topology repair, truth audit +- forbidden adjacency considered: must not edit functional code + +Likely route owner: +- route file: docs/truthmark/areas.md +- truth doc: docs/truth/example.md +- confidence: medium + +Expected write classes: +- truth docs + +Expected target files: +- docs/truth/example.md + +Suggested subagent use: +- read-only verifiers: truth_route_auditor +- write workers: none in Preview +- leases needed: none in Preview + +Blocking ambiguity: +- none identified in preview + +Handoff: +- Run the selected Truthmark workflow after user approval. +``` diff --git a/.opencode/skills/truthmark-preview/support/subagents-and-leases.md b/.opencode/skills/truthmark-preview/support/subagents-and-leases.md new file mode 100644 index 0000000..62a4e79 --- /dev/null +++ b/.opencode/skills/truthmark-preview/support/subagents-and-leases.md @@ -0,0 +1,10 @@ +# Truthmark Preview Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +OpenCode subagent mode: +- use automatically when this workflow runs in OpenCode and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents only: @truth-route-auditor +- workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns the final Truth Preview report diff --git a/.opencode/skills/truthmark-realize/SKILL.md b/.opencode/skills/truthmark-realize/SKILL.md index 5f34ff2..a5a0de8 100644 --- a/.opencode/skills/truthmark-realize/SKILL.md +++ b/.opencode/skills/truthmark-realize/SKILL.md @@ -3,7 +3,7 @@ name: truthmark-realize description: 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. argument-hint: Optional truth doc path, area, or desired code behavior to realize user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- # Truthmark Realize @@ -12,50 +12,14 @@ Use this skill only when the user explicitly asks to realize truth docs into cod Invocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize. -Truth Realize is doc-first: +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read the source truth docs, .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files, tests, and relevant functional code directly. +- Truth docs lead; code follows. +- may write functional code only; must not edit truth docs or truth routing while realizing those docs. +- Read support/procedure.md before changing code. +- Read support/report-template.md before the final report. -- truth docs lead -- code follows -- Truth Realize never edits the truth docs it is realizing - -Workflow: - -1. Read the updated truth docs named by the user, or infer the relevant docs from docs/truthmark/areas.md. -2. Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files, tests, and the relevant functional code. -3. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -Truth-doc ownership gate: -- before editing or relying on source truth docs before writing code, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -4. Update functional code only so implementation matches bounded, current truth claims from the source docs. -5. Do not edit truth docs or truth routing while realizing those docs. -6. Run relevant tests for the changed code. -7. Report changed code files and verification steps. -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md - -Read and write boundaries: - -- may read truth docs, routing docs, and relevant functional code -- may write functional code only -- must not edit truth docs or truth routing while realizing those docs - -Report completion in this shape: - -```md -Truth Realize: completed - -Truth docs used: -- docs/truth/authentication/session-timeout.md - -Code updated: -- src/auth/session.ts - -Verification: -- npm test -- auth -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md diff --git a/.opencode/skills/truthmark-realize/support/procedure.md b/.opencode/skills/truthmark-realize/support/procedure.md new file mode 100644 index 0000000..3a657a6 --- /dev/null +++ b/.opencode/skills/truthmark-realize/support/procedure.md @@ -0,0 +1,42 @@ +# Truthmark Realize Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +# Truthmark Realize + +Use this skill only when the user explicitly asks to realize truth docs into code. + +Invocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize. + +Truth Realize is doc-first: + +- truth docs lead +- code follows +- Truth Realize never edits the truth docs it is realizing + +Workflow: + +1. Read the updated truth docs named by the user, or infer the relevant docs from docs/truthmark/areas.md. +2. Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files, tests, and the relevant functional code. +3. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +Truth-doc ownership gate: +- before editing or relying on source truth docs before writing code, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +4. Update functional code only so implementation matches bounded, current truth claims from the source docs. +5. Do not edit truth docs or truth routing while realizing those docs. +6. Run relevant tests for the changed code. +7. Report changed code files and verification steps. +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md + +Read and write boundaries: + +- may read truth docs, routing docs, and relevant functional code +- may write functional code only +- must not edit truth docs or truth routing while realizing those docs diff --git a/.opencode/skills/truthmark-realize/support/report-template.md b/.opencode/skills/truthmark-realize/support/report-template.md new file mode 100644 index 0000000..0f77d6a --- /dev/null +++ b/.opencode/skills/truthmark-realize/support/report-template.md @@ -0,0 +1,18 @@ +# Truthmark Realize Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: + +```md +Truth Realize: completed + +Truth docs used: +- docs/truth/authentication/session-timeout.md + +Code updated: +- src/auth/session.ts + +Verification: +- npm test -- auth +``` diff --git a/.opencode/skills/truthmark-structure/SKILL.md b/.opencode/skills/truthmark-structure/SKILL.md index 339d87f..2aef662 100644 --- a/.opencode/skills/truthmark-structure/SKILL.md +++ b/.opencode/skills/truthmark-structure/SKILL.md @@ -1,123 +1,26 @@ --- name: truthmark-structure -description: Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, or needs split/repair. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code. +description: 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. argument-hint: Optional area, directory, or routing concern user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- +# Truthmark Structure + Use this skill to design or repair Truthmark area structure. + Invocations: OpenCode /skill truthmark-structure; Codex /truthmark-structure or $truthmark-structure; Claude Code /truthmark-structure; GitHub Copilot /truthmark-structure; Gemini CLI /truthmark:structure. -Truth Structure is agent-native: -- inspect repository layout, current docs, .truthmark/config.yml, docs/truthmark/areas.md, and relevant code directly -- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ -- define areas by product or behavior ownership, not by mechanical directory mirroring -- create or repair docs/truthmark/areas.md -- create starter truth docs when useful and when they belong in the canonical current-truth surface -- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter. -- Starter truth docs must include ## Product Decisions and ## Rationale sections. -When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. -Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. -Align existing docs to that template while preserving accurate authored content. -If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. -Teams may edit the template files under docs/templates/ to define their local truth-doc standards. -- use docs/truth/**, docs/architecture/**, or docs/standards/** for current truth destinations -- use only canonical current-truth destinations for starter truth docs -- keep active Product Decisions and Rationale in the canonical doc that owns the behavior -- preserve unrelated authored content -## Topology Governance -Truth Structure owns documentation topology. Do not depend on humans to manually organize docs/truth. Treat the configured truth root as a managed semantic root. -Inspect 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. -When topology pressure exists, repair structure before creating or extending truth docs. -Truth-doc ownership gate: -- before editing or relying on candidate route owners and current truth docs, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if a truth doc mixes independent owners, route ownership is broad, or a split is required for bounded ownership, split and reroute into bounded truth docs when safe; otherwise block with manual-review files -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -Product Decisions/Rationale preservation gate: -- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc -- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index -- 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 -- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing -- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked -Topology pressure signals: -- one area maps broad code such as src/**, app/**, server/**, services/**, or packages/** -- one area maps multiple unrelated controllers, route groups, services, or bounded contexts -- one truth doc owns unrelated behaviors or unrelated endpoint families -- the configured truth root has many direct non-index docs -- a changed controller, route, or service cannot map to a specific behavior doc -- Truth Sync would need to create a new generic truth doc because routing is too broad -- endpoint or controller names reveal domains missing from docs/truthmark/areas/** -Use these review thresholds as guidance: -- more than 10 direct truth docs in one folder -- more than 15 leaf areas in one child route file -- more than 8 truth docs mapped to one area -- more than 5 controllers mapped through one catch-all area -Repair rules: -- split broad, overloaded, or catch-all areas into behavior-owned child route files -- split mixed-owner truth docs into bounded owner docs before adding new behavior claims -- create route files under docs/truthmark/areas/ when a product/domain boundary is clear -- create behavior truth docs under the configured truth root only when behavior lacks a current doc -- README.md files are indexes, not Truth Sync targets -- prefer bounded leaf truth docs at //.md -- keep behavior truth docs behavior-oriented, not endpoint-oriented -- keep API endpoint details in the nearest contract truth doc when such a doc exists -- update routing so future Truth Sync can target small docs -- preserve existing authored docs; move or rewrite only when needed to remove ambiguity -- report Truth docs split when one broad or mixed-owner truth doc becomes multiple bounded docs -Truth-doc shape repair gate: -- Truth Structure may restructure broader routed docs when topology, ownership, or doc-shape repair is already in scope. -- repair shape in place only after the ownership gate confirms the doc is the right bounded owner -- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work -- 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 -- preserve supported claims; remove, narrow, or block unsupported or stale claims -- report docs restructured and why a narrow edit was not sufficient -Evidence Gate: -- apply the Evidence Gate before finishing when Truth Structure writes routed docs, ownership claims, Product Decisions, or Rationale -- support ownership/behavior claims with topology or primary checkout evidence from layout, implementation boundaries, docs, config, route files, tests, templates, schemas, or contracts -- tests/examples/canonical docs corroborate; remove, narrow, or block unsupported claims -Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. -Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. -- Do not finish topology repair with routed canonical current-truth docs missing Product Decisions or Rationale sections. -- If an existing canonical doc lacks either section, add the missing heading beside Current Behavior with a concise current-state placeholder or active decision. -Portable fallback: -- If this skill surface is unavailable, perform the same workflow directly from committed repository files. -- Do not require the truthmark CLI. -- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, canonical docs, and representative implementation code. -- Use a subagent only when the host supports that pattern; otherwise perform the topology repair inline. -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. -Report completion in this shape: -```md -Truth Structure: completed -Topology reviewed: -- controllers: src/auth/** -- docs root: docs/truth -- route files: docs/truthmark/areas.md -Areas reviewed: -- src/auth/** -Routing updated: -- docs/truthmark/areas.md -Truth docs created: -- docs/truth/authentication/session.md -Truth docs split: -- docs/truth/authentication/README.md -> docs/truth/authentication/session.md -Truth docs restructured: -- docs/truth/authentication/README.md -Evidence checked: -- Claim: Session behavior belongs to a dedicated Authentication truth owner. - Evidence: src/auth/** / docs/truthmark/areas.md:7 - Result: supported -Topology decisions: -- Added an Authentication area because session behavior has a distinct code surface and truth owner. -Notes: -- Added an Authentication area for session behavior. -``` + +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, current docs, and relevant code directly. +- Define areas by product or behavior ownership, not by mechanical directory mirroring. +- Do not edit functional code. +- Read support/procedure.md before writing route or starter truth-doc changes. +- Read support/report-template.md before the final report. + +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.opencode/skills/truthmark-structure/support/procedure.md b/.opencode/skills/truthmark-structure/support/procedure.md new file mode 100644 index 0000000..5eabbf7 --- /dev/null +++ b/.opencode/skills/truthmark-structure/support/procedure.md @@ -0,0 +1,109 @@ +# Truthmark Structure Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Use this skill to design or repair Truthmark area structure. +Invocations: OpenCode /skill truthmark-structure; Codex /truthmark-structure or $truthmark-structure; Claude Code /truthmark-structure; GitHub Copilot /truthmark-structure; Gemini CLI /truthmark:structure. +Truth Structure is agent-native: +- inspect repository layout, current docs, .truthmark/config.yml, docs/truthmark/areas.md, and relevant code directly +- Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +- inspect the configured root route index at docs/truthmark/areas.md and relevant child route files under docs/truthmark/areas/ +- define areas by product or behavior ownership, not by mechanical directory mirroring +- create or repair docs/truthmark/areas.md +- create starter truth docs when useful and when they belong in the canonical current-truth surface +- Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter. +- Starter truth docs must include ## Product Decisions and ## Rationale sections. + +When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. +Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. +Align existing docs to that template while preserving accurate authored content. +If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. +Teams may edit the template files under docs/templates/ to define their local truth-doc standards. +- use docs/truth/**, docs/architecture/**, or docs/standards/** for current truth destinations +- use only canonical current-truth destinations for starter truth docs +- keep active Product Decisions and Rationale in the canonical doc that owns the behavior +- preserve unrelated authored content +## New area setup +Use 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. +Do: +- inspect the named code area +- infer bounded product or behavior ownership +- choose the owning route when ownership is clear; otherwise propose the route and block for review +- create or update the child route entry or file +- create starter truth docs only where current truth is missing +- report the initial truth boundary +Do not: +- do not edit functional code +- do not perform full behavior documentation unless evidence is inspected and the task explicitly asks for it +- do not patch broad or mixed-owner docs in place +- do not create generic catch-all docs +- do not treat README files as Sync targets +## Topology Governance +Truth Structure owns documentation topology. Do not depend on humans to manually organize docs/truth. Treat the configured truth root as a managed semantic root. +Inspect 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. +When topology pressure exists, repair structure before creating or extending truth docs. +Truth-doc ownership gate: +- before editing or relying on candidate route owners and current truth docs, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if a truth doc mixes independent owners, route ownership is broad, or a split is required for bounded ownership, split and reroute into bounded truth docs when safe; otherwise block with manual-review files +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +Product Decisions/Rationale preservation gate: +- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc +- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index +- 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 +- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing +- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked +Topology pressure signals: +- one area maps broad code such as src/**, app/**, server/**, services/**, or packages/** +- one area maps multiple unrelated controllers, route groups, services, or bounded contexts +- one truth doc owns unrelated behaviors or unrelated endpoint families +- the configured truth root has many direct non-index docs +- a changed controller, route, or service cannot map to a specific behavior doc +- Truth Sync would need to create a new generic truth doc because routing is too broad +- endpoint or controller names reveal domains missing from docs/truthmark/areas/** +Use these review thresholds as guidance: +- more than 10 direct truth docs in one folder +- more than 15 leaf areas in one child route file +- more than 8 truth docs mapped to one area +- more than 5 controllers mapped through one catch-all area +Repair rules: +- split broad, overloaded, or catch-all areas into behavior-owned child route files +- split mixed-owner truth docs into bounded owner docs before adding new behavior claims +- create route files under docs/truthmark/areas/ when a product/domain boundary is clear +- create behavior truth docs under the configured truth root only when behavior lacks a current doc +- README.md files are indexes, not Truth Sync targets +- prefer bounded leaf truth docs at //.md +- keep behavior truth docs behavior-oriented, not endpoint-oriented +- keep API endpoint details in the nearest contract truth doc when such a doc exists +- update routing so future Truth Sync can target small docs +- preserve existing authored docs; move or rewrite only when needed to remove ambiguity +- report Truth docs split when one broad or mixed-owner truth doc becomes multiple bounded docs +Truth-doc shape repair gate: +- Truth Structure may restructure broader routed docs when topology, ownership, or doc-shape repair is already in scope. +- repair shape in place only after the ownership gate confirms the doc is the right bounded owner +- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work +- 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 +- preserve supported claims; remove, narrow, or block unsupported or stale claims +- report docs restructured and why a narrow edit was not sufficient +Evidence Gate: +- apply the Evidence Gate before finishing when Truth Structure writes routed docs, ownership claims, Product Decisions, or Rationale +- support ownership/behavior claims with topology or primary checkout evidence from layout, implementation boundaries, docs, config, route files, tests, templates, schemas, or contracts +- tests/examples/canonical docs corroborate; remove, narrow, or block unsupported claims +Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. +Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. +- Do not finish topology repair with routed canonical current-truth docs missing Product Decisions or Rationale sections. +- If an existing canonical doc lacks either section, add the missing heading beside Current Behavior with a concise current-state placeholder or active decision. +Portable fallback: +- If this skill surface is unavailable, perform the same workflow directly from committed repository files. +- Do not require the truthmark CLI. +- Read .truthmark/config.yml, docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, canonical docs, and representative implementation code. +- Use a subagent only when the host supports that pattern; otherwise perform the topology repair inline. +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. diff --git a/.opencode/skills/truthmark-structure/support/report-template.md b/.opencode/skills/truthmark-structure/support/report-template.md new file mode 100644 index 0000000..f8cfa0d --- /dev/null +++ b/.opencode/skills/truthmark-structure/support/report-template.md @@ -0,0 +1,35 @@ +# Truthmark Structure Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Structure: completed +Topology reviewed: +- controllers: src/auth/** +- docs root: docs/truth +- route files: docs/truthmark/areas.md +Areas reviewed: +- src/auth/** +Routing updated: +- docs/truthmark/areas.md +Initial truth boundary: +- Area: Authentication +- Code: src/auth/** +- Truth owner: docs/truth/authentication/session.md +- Scope: session behavior only +Truth docs created: +- docs/truth/authentication/session.md +Truth docs split: +- docs/truth/authentication/README.md -> docs/truth/authentication/session.md +Truth docs restructured: +- docs/truth/authentication/README.md +Evidence checked: +- Claim: Session behavior belongs to a dedicated Authentication truth owner. + Evidence: src/auth/** / docs/truthmark/areas.md:7 + Result: supported +Topology decisions: +- Added an Authentication area because session behavior has a distinct code surface and truth owner. +Notes: +- Added an Authentication area for session behavior. +``` diff --git a/.opencode/skills/truthmark-structure/support/subagents-and-leases.md b/.opencode/skills/truthmark-structure/support/subagents-and-leases.md new file mode 100644 index 0000000..97f0bf3 --- /dev/null +++ b/.opencode/skills/truthmark-structure/support/subagents-and-leases.md @@ -0,0 +1,10 @@ +# Truthmark Structure Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +OpenCode subagent mode: +- use automatically when this workflow runs in OpenCode and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents only: @truth-route-auditor +- workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- Parent agent owns all Truth Structure writes and final topology decisions diff --git a/.opencode/skills/truthmark-sync/SKILL.md b/.opencode/skills/truthmark-sync/SKILL.md index 4227894..c3d5a91 100644 --- a/.opencode/skills/truthmark-sync/SKILL.md +++ b/.opencode/skills/truthmark-sync/SKILL.md @@ -3,135 +3,26 @@ name: truthmark-sync description: 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. argument-hint: Optional changed-code area, truth-doc area, or sync focus user-invocable: true -truthmark-version: 1.3.0 +truthmark-version: 1.4.0 --- +# Truthmark Sync + 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. + Invocations: OpenCode /skill truthmark-sync; Codex /truthmark-sync or $truthmark-sync; Claude Code /truthmark-sync; GitHub Copilot /truthmark-sync; Gemini CLI /truthmark:sync. -Explicit invocation runs immediately. Later functional-code changes reopen the finish-time requirement, and an earlier explicit run satisfies the finish gate only if no later functional-code changes occur. -Skip 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. -Parent workflow: -1. Inspect git status, staged changes, unstaged changes, and untracked files directly. -2. Read .truthmark/config.yml, the configured root route index at docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and relevant canonical docs. -3. Identify functional-code changes and the nearest truth docs or routing repairs. -4. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. -Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. -5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run. -6. Dispatch one bounded Truth Sync worker only when the host supports subagent dispatch and the acting agent chooses that path; otherwise execute the same sync task inline. -Topology quality gate: -- before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner -- if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc -- run Truth Structure before syncing when topology repair is safe and in scope -- block and recommend Truth Structure when topology repair is unsafe, ambiguous, or outside the current task boundary -- report the route files and changed code paths that require structure repair -- README.md files are indexes, not Truth Sync targets -- must not append behavior details to a README.md index -- create or update a bounded leaf truth doc when behavior changes do not fit an existing leaf doc -Truth-doc ownership gate: -- before editing or relying on changed functional files and impacted truth docs, verify each target/source truth doc is a bounded owner for the behavior -- 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 -- if an impacted doc is broad, mixed-owner, index-like, or the update spans independent behavior owners, run Truth Structure before syncing when safe and in scope; otherwise block and recommend Truth Structure -- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable -Product Decisions/Rationale preservation gate: -- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc -- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index -- 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 -- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing -- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked -When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. -Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. -Align existing docs to that template while preserving accurate authored content. -If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. -Teams may edit the template files under docs/templates/ to define their local truth-doc standards. -Truth-doc shape repair gate: -- Truth Sync may restructure only truth docs impacted by the current functional-code change. -- repair shape in place only after the ownership gate confirms the doc is the right bounded owner -- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work -- 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 -- preserve supported claims; remove, narrow, or block unsupported or stale claims -- report docs restructured and why a narrow edit was not sufficient -Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. -Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. -Evidence Gate: -- route-first: map changed functional files to bounded route owners and primary canonical docs -- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale -- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions -- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts -- remove, narrow, or block unsupported claims -- if no impacted doc changed, report why truth was already current or why sync was skipped -Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. -They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. -If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. -Optional validation tooling: -- you may run truthmark check when local tooling is available -- do not require the truthmark binary; direct checkout inspection is the canonical path -- optional validation must not replace agent judgment about docs and routing -- update Product Decisions and Rationale when a behavior change comes from a decision change -Truthmark hierarchy: -- Config: .truthmark/config.yml -- Root route index: docs/truthmark/areas.md -- Area route files: docs/truthmark/areas/**/*.md -- Truth docs: docs/truth/**/*.md -Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. -Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. -Update Product Decisions and Rationale when a decision changes behavior. -### Truth Sync Worker -The parent provides the task focus and any repository context already gathered. -Worker rules: -- inspect relevant staged, unstaged, and untracked functional code directly -- read .truthmark/config.yml, docs/truthmark/areas.md, and canonical truth docs directly -- Code verification is parent-owned; report what was run or why it was not run -- may write truth docs and docs/truthmark/areas.md only for Truth Sync alignment -- must not rewrite functional code -Return result in this shape: -- status: completed | blocked -- changedCodeReviewed: string[] -- ownershipReviewed: string[] -- structureRequired?: string[] -- truthDocsUpdated: string[] -- routingDocsUpdated: string[] -- truthDocsSplit?: string[] -- evidenceChecked: { claim: string; evidence: string[]; result: supported | narrowed | removed | blocked }[] -- notes: string[] -- blockedReason?: string -- manualReviewFiles?: string[] -Parent post-sync verification: -- verify only truth docs and docs/truthmark/areas.md changed during sync -- block on any unrelated diff caused by the sync step -- block if functional code changed during sync -- verify the worker report matches the required headings and sections -- validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked -- verify the updated docs correspond to the reviewed changed-code surface -- verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired -- blocked outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files -Report completion in this shape: -```md -Truth Sync: completed -Changed code reviewed: -- src/auth/session.ts +Quick procedure: +- Follow docs/ai/repo-rules.md as the repository instruction authority. +- Skip docs-only, formatting-only, behavior-preserving renames with no truth impact, missing config, and no-code changes. +- Read .truthmark/config.yml, the configured root route index at docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and relevant canonical docs. +- direct checkout inspection is the canonical path; do not require the truthmark binary. +- May write canonical truth docs and truth routing files only; must not rewrite functional code. +- Read support/procedure.md before editing truth docs. +- Read support/subagents-and-leases.md before dispatching or accepting worker output. +- Read support/report-template.md before the final report. -Truth docs updated: -- docs/truth/repository/overview.md - -Evidence checked: -- Claim: Session timeout behavior is documented in the mapped repository truth doc. - Evidence: src/auth/session.ts:12 / docs/truthmark/areas.md:11 - Result: supported - -Notes: -- Updated session timeout behavior. -``` -Blocked report example: -```md -Truth Sync: blocked - -Reason: -- routing repair is not allowed - -Files requiring manual review: -- docs/truthmark/areas.md - -Next action: -- update routing metadata and rerun Truth Sync -``` +Progressive disclosure: +- support/procedure.md +- support/report-template.md +- support/subagents-and-leases.md diff --git a/.opencode/skills/truthmark-sync/support/procedure.md b/.opencode/skills/truthmark-sync/support/procedure.md new file mode 100644 index 0000000..e213b0e --- /dev/null +++ b/.opencode/skills/truthmark-sync/support/procedure.md @@ -0,0 +1,82 @@ +# Truthmark Sync Procedure + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +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. +Invocations: OpenCode /skill truthmark-sync; Codex /truthmark-sync or $truthmark-sync; Claude Code /truthmark-sync; GitHub Copilot /truthmark-sync; Gemini CLI /truthmark:sync. +Explicit invocation runs immediately. Later functional-code changes reopen the finish-time requirement, and an earlier explicit run satisfies the finish gate only if no later functional-code changes occur. +Skip 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. +Parent workflow: +1. Inspect git status, staged changes, unstaged changes, and untracked files directly. +2. Read .truthmark/config.yml, the configured root route index at docs/truthmark/areas.md, relevant child route files under docs/truthmark/areas/, and relevant canonical docs. +3. Identify functional-code changes and the nearest truth docs or routing repairs. +4. Repository instruction docs such as docs/ai/repo-rules.md remain instruction authority. +Implementation code and canonical truth docs are inspected evidence for current behavior; they do not silently override workflow write boundaries. +5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run. +6. 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. +Topology quality gate: +- before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner +- if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc +- run Truth Structure before syncing when topology repair is safe and in scope +- block and recommend Truth Structure when topology repair is unsafe, ambiguous, or outside the current task boundary +- report the route files and changed code paths that require structure repair +- README.md files are indexes, not Truth Sync targets +- must not append behavior details to a README.md index +- create or update a bounded leaf truth doc when behavior changes do not fit an existing leaf doc +Truth-doc ownership gate: +- before editing or relying on changed functional files and impacted truth docs, verify each target/source truth doc is a bounded owner for the behavior +- 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 +- if an impacted doc is broad, mixed-owner, index-like, or the update spans independent behavior owners, run Truth Structure before syncing when safe and in scope; otherwise block and recommend Truth Structure +- report Ownership reviewed, Structure required, Truth docs split, Truth docs restructured, or Blocked reason as applicable +Product Decisions/Rationale preservation gate: +- before any truth-doc split, restructure, or shape repair, inventory existing Product Decisions and Rationale sections in every source or touched truth doc +- preserve each current decision and rationale in the bounded owner doc it governs; when splitting, move it to the new owner doc rather than deleting it or leaving it in an index +- 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 +- if ownership of a decision or rationale is unclear, block with manual-review files instead of deleting it or guessing +- after the edit, verify every touched truth doc still has Product Decisions and Rationale sections and every pre-existing entry is preserved, moved, narrowed, removed with evidence, or blocked +When creating or updating a truth doc, inspect the routed truth kind and use the matching `docs/templates/-doc.md` template. +Supported kinds: behavior, contract, architecture, workflow, operations, and test-behavior. +Align existing docs to that template while preserving accurate authored content. +If the template is missing, use Scope, Product Decisions, Rationale, and the kind-specific current-truth section. +Teams may edit the template files under docs/templates/ to define their local truth-doc standards. +Truth-doc shape repair gate: +- Truth Sync may restructure only truth docs impacted by the current functional-code change. +- repair shape in place only after the ownership gate confirms the doc is the right bounded owner +- use Truth Structure for ownership splits; do not treat broad or mixed-owner docs as in-place repair work +- 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 +- preserve supported claims; remove, narrow, or block unsupported or stale claims +- report docs restructured and why a narrow edit was not sufficient +Maintain architecture docs only for structure-level changes: system structure, module boundaries, runtime topology, persistence boundaries, cross-cutting contracts, or generated-surface ownership. +Keep ordinary behavior, endpoints, UI copy, validation rules, and bug fixes in behavior or contract docs unless they change those boundaries. +Evidence Gate: +- route-first: map changed functional files to bounded route owners and primary canonical docs +- review new or changed behavior-bearing claims only in touched docs, route ownership, Product Decisions, and Rationale +- support claims with primary checkout evidence: implementation, config, routing, generated templates, schemas, or contract definitions +- tests/examples/canonical docs corroborate; they are not sole proof when implementation conflicts +- remove, narrow, or block unsupported claims +- if no impacted doc changed, report why truth was already current or why sync was skipped +Repository intelligence artifacts are optional derived context: RepoIndex, RouteMap, ImpactSet, and ContextPack may guide routing, context selection, and verification planning when available. +They do not override checkout evidence, canonical truth docs, route files, or workflow write boundaries. +If unavailable, inspect .truthmark/config.yml, route files, source files, truth docs, and tests directly, then report that repository-intelligence artifacts were not generated. +Optional validation tooling: +- you may run truthmark check when local tooling is available +- do not require the truthmark binary; direct checkout inspection is the canonical path +- optional validation must not replace agent judgment about docs and routing +- update Product Decisions and Rationale when a behavior change comes from a decision change +Truthmark hierarchy: +- Config: .truthmark/config.yml +- Root route index: docs/truthmark/areas.md +- Area route files: docs/truthmark/areas/**/*.md +- Truth docs: docs/truth/**/*.md +Decision truth lives in the canonical doc it governs; date active decisions inline when added or changed. +Do not create separate active-decision ADR/planning logs; replace the active decision and let Git history carry the audit trail. +Update Product Decisions and Rationale when a decision changes behavior. +Parent post-sync verification: +- verify only truth docs and leased truth routing files changed during sync +- block on any unrelated diff caused by the sync step +- block if functional code changed during sync +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it +- validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked +- verify the updated docs correspond to the reviewed changed-code surface +- verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired +- blocked outcomes must preserve the working tree as-is: no rollback, no post-block cleanup edits, and manual-review reporting of any remaining files diff --git a/.opencode/skills/truthmark-sync/support/report-template.md b/.opencode/skills/truthmark-sync/support/report-template.md new file mode 100644 index 0000000..ccbadff --- /dev/null +++ b/.opencode/skills/truthmark-sync/support/report-template.md @@ -0,0 +1,35 @@ +# Truthmark Sync Report Template + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +Report completion in this shape: +```md +Truth Sync: completed + +Changed code reviewed: +- src/auth/session.ts + +Truth docs updated: +- docs/truth/repository/overview.md + +Evidence checked: +- Claim: Session timeout behavior is documented in the mapped repository truth doc. + Evidence: src/auth/session.ts:12 / docs/truthmark/areas.md:11 + Result: supported + +Notes: +- Updated session timeout behavior. +``` +Blocked report example: +```md +Truth Sync: blocked + +Reason: +- routing repair is not allowed + +Files requiring manual review: +- docs/truthmark/areas.md + +Next action: +- update routing metadata and rerun Truth Sync +``` diff --git a/.opencode/skills/truthmark-sync/support/subagents-and-leases.md b/.opencode/skills/truthmark-sync/support/subagents-and-leases.md new file mode 100644 index 0000000..472da8b --- /dev/null +++ b/.opencode/skills/truthmark-sync/support/subagents-and-leases.md @@ -0,0 +1,14 @@ +# Truthmark Sync Subagents And Leases + +Generated by Truthmark 1.4.0. Rerun truthmark init after upgrades. + +OpenCode subagent mode: +- use automatically when this workflow runs in OpenCode and the parent agent chooses bounded subagent fan-out +- dispatch read-only project subagents for verification: @truth-route-auditor, @truth-claim-verifier +- read-only workers inspect checkout evidence directly, return structured findings, and must not edit files +- parent supplies bounded evidence shards; read-only workers must not preload host instruction files or repo-wide policy docs unless assigned as evidence +- dispatch write-capable project subagents only with explicit write leases: @truth-doc-writer +- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields +- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes +- parent must inspect the actual checkout diff against each lease before accepting a worker report +- Parent agent owns Truth Sync acceptance, lease validation, and final report diff --git a/AGENTS.md b/AGENTS.md index d4bad39..9357698 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,14 +9,14 @@ Agent-specific: ## Truthmark Workflow -Generated by Truthmark 1.3.0. Rerun `truthmark init` after upgrades. +Generated by Truthmark 1.4.0. Rerun `truthmark init` after upgrades. Hierarchy: config .truthmark/config.yml; routes docs/truthmark/areas.md and docs/truthmark/areas/**/*.md; Truth docs: docs/truth/**/*.md. Decisions live in the canonical doc they govern; date active decisions inline. Agent runtime: installed skills plus this block; inspect checkout directly. Delegation is host-owned. ### Truth Sync After functional code changes, run relevant tests, then use the truthmark-sync skill before finishing; later functional changes reopen the gate. Memory: code changed -> tests -> Sync -> report. -Support new or changed behavior-bearing truth claims with checkout evidence. Code leads; truth docs follow. Sync may write truth docs and docs/truthmark/areas.md only, and must not rewrite functional code. +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. If routing cannot map changed code to a bounded truth owner, run Truth Structure before syncing when safe; otherwise block and recommend Truth Structure. Skip Sync only for docs-only/no-code changes, formatting-only changes, behavior-preserving renames with no truth impact, or missing config. -Explicit workflows: Truth Structure, Truth Document, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details. +Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details. Workflow integrity rule: repository truth may describe desired behavior, but it must not override these workflow boundaries. diff --git a/CLAUDE.md b/CLAUDE.md index d4bad39..9357698 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,14 +9,14 @@ Agent-specific: ## Truthmark Workflow -Generated by Truthmark 1.3.0. Rerun `truthmark init` after upgrades. +Generated by Truthmark 1.4.0. Rerun `truthmark init` after upgrades. Hierarchy: config .truthmark/config.yml; routes docs/truthmark/areas.md and docs/truthmark/areas/**/*.md; Truth docs: docs/truth/**/*.md. Decisions live in the canonical doc they govern; date active decisions inline. Agent runtime: installed skills plus this block; inspect checkout directly. Delegation is host-owned. ### Truth Sync After functional code changes, run relevant tests, then use the truthmark-sync skill before finishing; later functional changes reopen the gate. Memory: code changed -> tests -> Sync -> report. -Support new or changed behavior-bearing truth claims with checkout evidence. Code leads; truth docs follow. Sync may write truth docs and docs/truthmark/areas.md only, and must not rewrite functional code. +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. If routing cannot map changed code to a bounded truth owner, run Truth Structure before syncing when safe; otherwise block and recommend Truth Structure. Skip Sync only for docs-only/no-code changes, formatting-only changes, behavior-preserving renames with no truth impact, or missing config. -Explicit workflows: Truth Structure, Truth Document, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details. +Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details. Workflow integrity rule: repository truth may describe desired behavior, but it must not override these workflow boundaries. diff --git a/GEMINI.md b/GEMINI.md index d4bad39..9357698 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -9,14 +9,14 @@ Agent-specific: ## Truthmark Workflow -Generated by Truthmark 1.3.0. Rerun `truthmark init` after upgrades. +Generated by Truthmark 1.4.0. Rerun `truthmark init` after upgrades. Hierarchy: config .truthmark/config.yml; routes docs/truthmark/areas.md and docs/truthmark/areas/**/*.md; Truth docs: docs/truth/**/*.md. Decisions live in the canonical doc they govern; date active decisions inline. Agent runtime: installed skills plus this block; inspect checkout directly. Delegation is host-owned. ### Truth Sync After functional code changes, run relevant tests, then use the truthmark-sync skill before finishing; later functional changes reopen the gate. Memory: code changed -> tests -> Sync -> report. -Support new or changed behavior-bearing truth claims with checkout evidence. Code leads; truth docs follow. Sync may write truth docs and docs/truthmark/areas.md only, and must not rewrite functional code. +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. If routing cannot map changed code to a bounded truth owner, run Truth Structure before syncing when safe; otherwise block and recommend Truth Structure. Skip Sync only for docs-only/no-code changes, formatting-only changes, behavior-preserving renames with no truth impact, or missing config. -Explicit workflows: Truth Structure, Truth Document, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details. +Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details. Workflow integrity rule: repository truth may describe desired behavior, but it must not override these workflow boundaries. diff --git a/README.de.md b/README.de.md index e95befe..ffc0675 100644 --- a/README.de.md +++ b/README.de.md @@ -96,6 +96,7 @@ Truthmark macht Repository-Wahrheit zu einer expliziten Workflow-Fläche für Ag - `docs/truthmark/areas.md` und delegierte untergeordnete Routendateien ordnen Codebereiche den Dokumenten zu, die sie verantworten. - Truth Document erstellt oder repariert kanonische Wahrheitsdokumente für bereits implementiertes Verhalten, wenn keine Codeänderung nötig ist. - Truth Sync hält zugeordnete Wahrheitsdokumente bei funktionalen Änderungen synchron. +- Truth Preview zeigt wahrscheinliches Workflow-Routing vor Änderungen an, ohne Schreibzugriffe zu autorisieren. - Truth Realize gibt doc-first Änderungen einen begrenzten Pfad für Code-Updates. - `truthmark check` validiert die daraus entstehenden Wahrheitsartefakte. - Das gesamte Modell bleibt local-first und Git-nativ. @@ -213,18 +214,25 @@ Codex, Claude Code und unterstützte Copilot-IDEs können es mit `/truthmark-rea Truthmark hält die dauerhafte Workflow-Fläche klein und repository-nativ. Nach `truthmark init` trägt das Repository selbst Routing, Regeln und installierte Workflow-Flächen, sodass Teams nicht nur auf die lokale Konfiguration einer einzelnen Person angewiesen sind. +Truthmark installiert zwei getrennte Oberflächen: + +- menschenorientierte CLI-Befehle, die Menschen oder CI ausführen, um das Repository zu konfigurieren, installierte Dateien zu aktualisieren, Truth-Artefakte zu validieren und optional abgeleiteten Review-Kontext zu erzeugen +- Agenten-Workflow-Flächen, die Coding-Agenten oder Agenten-Hosts während Implementierungsworkflows aufrufen; sie sind keine zusätzlichen täglichen Terminalbefehle für Menschen + - `.truthmark/config.yml` für den maschinenlesbaren, festgeschriebenen Hierarchievertrag - `docs/truthmark/areas.md` für den Root-Routenindex - `docs/truthmark/areas/**/*.md` für delegierte untergeordnete Routendateien - `docs/templates/behavior-doc.md` sowie die weiteren typspezifischen Vorlagen unter `docs/templates/` für die editierbaren Truth-Doc-Standards der generierten Workflows - verwaltete Instruktionsblöcke für konfigurierte Plattformen wie `AGENTS.md`, `CLAUDE.md`, Copilot-Anweisungen und `GEMINI.md` -- host-native Skills, Prompts oder Commands für Truth Structure, Truth Document, Truth Sync, Truth Realize und Truth Check +- host-native Skills, Prompts oder Commands für Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize und Truth Check +- projektbezogene schreibgeschützte Codex-, Claude-Code-, GitHub-Copilot- und OpenCode-Prüfer plus geleaste `truth-doc-writer`-Agenten, wo Hosts Agenten unterstützen, unter `.codex/agents/`, `.claude/agents/`, `.github/agents/` und `.opencode/agents/` für workflow-eigene Audits und vom Parent geleaste Dokument-Shards Die installierten Workflow-Flächen sind die Runtime: - Truth Structure erstellt oder repariert Area-Routing und erste Wahrheitsdokumente. - Truth Document erstellt oder repariert Wahrheitsdokumente für bereits implementiertes Verhalten. - Truth Sync hält zugeordnete Wahrheitsdokumente bei funktionalen Änderungen synchron. +- Truth Preview zeigt wahrscheinliches Workflow-Routing vor Änderungen an, ohne Dateien zu schreiben. - Truth Realize aktualisiert Code so, dass er zu den Wahrheitsdokumenten passt. - Truth Check auditiert die Gesundheit der Repository-Wahrheit. @@ -234,38 +242,30 @@ Generierte Flächen werden von Truthmark verwaltet, enthalten einen Versionsmark ## Befehle -Truthmark V1 hält die CLI fokussiert, weil der laufende Workflow in den installierten Agenten-Flächen leben soll und nicht in einer langen Liste täglicher manueller Befehle. In nachgelagerten Repositories erzeugt `truthmark config` den in Git festgeschriebenen Hierarchievertrag, `truthmark init` installiert und aktualisiert Workflow-Flächen aus dieser geprüften Konfiguration, `truthmark check` validiert Wahrheitsartefakte für manuelle Audits, CI oder Fehlersuche, und die Repository-Intelligence-Befehle erzeugen abgeleitete Prüfarbeitsstände, wenn lokale Werkzeuge verfügbar sind. +Truthmark V1 hält die Terminal-CLI fokussiert. Die meisten menschlichen Nutzer brauchen nur Einrichtung, Aktualisierung und Validierung: -```bash -truthmark config -truthmark init -truthmark check -truthmark index -truthmark impact --base main -truthmark context --workflow truth-sync --base main -truthmark config --json -truthmark check --json -truthmark index --json -truthmark impact --base main --json -truthmark context --workflow truth-sync --base main --json -``` +| Menschenorientierter CLI-Befehl | Zweck | +| -------------------------------- | ----- | +| `truthmark config` | Erstellt `.truthmark/config.yml`; schreibt nur diese Datei, außer `--stdout` wird verwendet. | +| `truthmark init` | Installiert oder aktualisiert lokale Workflow-Dateien aus der geprüften Konfiguration. | +| `truthmark check` | Validiert Konfiguration, Autorität, Routing, entscheidungstragende Dokumente, Frontmatter, interne Links, Branch-Scope und Coverage-Diagnostik. | -`config` schreibt nur `.truthmark/config.yml`, außer `--stdout` wird verwendet. +Die übrigen CLI-Befehle sind optionale Repository-Intelligence-Helfer. Sie erzeugen abgeleiteten Review-Kontext für den aktiven Checkout; sie sind keine Quellen der Wahrheit: -`init` benötigt `.truthmark/config.yml` und installiert oder aktualisiert anschließend die lokalen Workflow-Dateien. +| Optionaler CLI-Befehl | Zweck | +| --------------------- | ----- | +| `truthmark index` | Baut RepoIndex- und RouteMap-JSON für den aktiven Checkout. | +| `truthmark impact --base ` | Ordnet geänderte Dateien den gerouteten Truth-Dokumenten, zuständigen Routen, nahen Tests und öffentlichen Symbolen zu. | +| `truthmark context --workflow [--base ]` | Erzeugt ein begrenztes ContextPack für Truth Sync, Truth Document oder Truth Realize. `--format markdown` rendert eine menschenlesbare Fassung. | -`check` validiert Konfiguration, Autorität, Routing, entscheidungstragende Dokumente, Frontmatter, interne Links, Branch-Scope und Coverage-Diagnostik. +Alle oben genannten CLI-Befehle unterstützen `--json`, wenn strukturierte Ausgabe für Automatisierung nützlich ist. -`index` baut RepoIndex- und RouteMap-JSON für den aktiven Checkout. - -`impact --base ` ordnet geänderte Dateien den gerouteten Truth-Dokumenten, Routen, nahen Tests und öffentlichen Symbolen zu. - -`context --workflow [--base ]` erzeugt ein begrenztes ContextPack für Truth Sync, Truth Document oder Truth Realize. `--format markdown` rendert eine menschenlesbare Fassung. - -Truth Structure, Truth Document, Truth Sync, Truth Realize und Truth Check sind installierte Agenten-Workflows, keine täglichen Top-Level-CLI-Befehle. +Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize und Truth Check sind installierte Agenten-Workflows, keine täglichen Top-Level-CLI-Befehle. Sie laufen über die konfigurierten Agenten-Host-Flächen, zum Beispiel Codex/Claude/Copilot `/truthmark-*`, OpenCode `/skill truthmark-*` oder Gemini `/truthmark:*`. +Diese Aufrufe wirken befehlsartig, weil Agenten-Hosts Skills über Slash-Commands bereitstellen. Behandle sie als Anweisungen an einen Agenten, nicht als Terminalbefehle, die Menschen ausführen sollen. + ```text /truthmark-check routing und truth-abdeckung vor der review prüfen ``` @@ -297,7 +297,7 @@ V1 bietet derzeit: - `truthmark impact` - `truthmark context` - verwaltete `AGENTS.md`-Workflow-Anweisungen -- generierte Truth Structure-, Truth Document-, Truth Sync-, Truth Realize- und Truth Check-Skill-Flächen für konfigurierte Agenten-Hosts +- generierte Truth Structure-, Truth Document-, Truth Sync-, Truth Preview-, Truth Realize- und Truth Check-Skill-Flächen für konfigurierte Agenten-Hosts - Branch-Scope-Metadaten - Diagnostik für Konfiguration, Autorität, Routing, Entscheidungsstruktur, Frontmatter, Links, Freshness und polyglotte Abdeckung - abgeleitete RepoIndex-, RouteMap-, ImpactSet- und ContextPack-Artefakte für schnellere lokale Prüfung, wenn die CLI verfügbar ist diff --git a/README.es.md b/README.es.md index 6f7d857..39dd4b3 100644 --- a/README.es.md +++ b/README.es.md @@ -96,6 +96,7 @@ Truthmark convierte la verdad del repositorio en una superficie explícita de fl - `docs/truthmark/areas.md` y los archivos de rutas secundarias delegadas asignan áreas de código a los documentos que las gobiernan. - Truth Document genera o repara documentos de verdad canónica para comportamiento ya implementado cuando no hace falta cambiar código. - Truth Sync mantiene alineados los documentos de verdad asignados cuando hay cambios funcionales. +- Truth Preview previsualiza el enrutamiento de flujo probable antes de editar, sin autorizar escrituras. - Truth Realize ofrece a los cambios que empiezan en documentación una ruta acotada para actualizar código. - `truthmark check` valida los artefactos de verdad resultantes. - Todo el modelo se mantiene local-first y nativo de Git. @@ -213,18 +214,25 @@ Codex, Claude Code y los IDEs de Copilot compatibles pueden invocarlo con `/trut Truthmark mantiene pequeña y nativa del repositorio la superficie duradera de flujo de trabajo. Después de `truthmark init`, el propio repositorio lleva el enrutamiento, las reglas y las superficies instaladas, así que el equipo no depende solo de la configuración local de una persona. +Truthmark instala dos superficies distintas: + +- comandos CLI orientados a personas, ejecutados por personas o CI para configurar el repositorio, refrescar archivos instalados, validar artefactos de verdad y generar opcionalmente contexto derivado para revisión +- superficies de flujo de trabajo para agentes, invocadas por agentes de código u hosts de agentes durante flujos de implementación; no son comandos de terminal diarios adicionales para personas + - `.truthmark/config.yml` para el contrato de jerarquía confirmado y legible por máquina - `docs/truthmark/areas.md` para el índice raíz de rutas - `docs/truthmark/areas/**/*.md` para archivos de rutas secundarias delegadas - `docs/templates/behavior-doc.md` y las demás plantillas específicas por tipo bajo `docs/templates/` para los estándares editables de truth docs usados por los flujos generados - bloques de instrucciones administrados para plataformas configuradas como `AGENTS.md`, `CLAUDE.md`, instrucciones de Copilot y `GEMINI.md` -- skills, prompts o comandos nativos del host para Truth Structure, Truth Document, Truth Sync, Truth Realize y Truth Check +- skills, prompts o comandos nativos del host para Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize y Truth Check +- verificadores de solo lectura de Codex, Claude Code, GitHub Copilot y OpenCode con alcance de proyecto, más agentes `truth-doc-writer` con lease donde el host admite agentes, bajo `.codex/agents/`, `.claude/agents/`, `.github/agents/` y `.opencode/agents/` para auditorías propias del flujo y shards de documentación concedidos por el padre Las superficies de flujo de trabajo instaladas son el entorno de ejecución: - Truth Structure crea o repara el enrutamiento de áreas y documentos de verdad iniciales. - Truth Document crea o repara documentos de verdad para comportamiento ya implementado. - Truth Sync mantiene alineados los documentos de verdad asignados con los cambios funcionales. +- Truth Preview previsualiza el enrutamiento de flujo probable antes de editar sin escribir archivos. - Truth Realize actualiza el código para que coincida con los documentos de verdad. - Truth Check audita la salud de la verdad del repositorio. @@ -234,38 +242,30 @@ Las superficies generadas son administradas por Truthmark, incluyen un marcador ## Comandos -Truthmark V1 mantiene la CLI pequeña a propósito porque el flujo continuo debe vivir en las superficies instaladas del agente, no en una lista larga de comandos manuales de uso diario. En repositorios derivados, `truthmark config` crea el contrato de jerarquía confirmado en Git, `truthmark init` instala y refresca superficies de flujo de trabajo a partir de esa configuración revisada, `truthmark check` valida los artefactos de verdad para auditorías manuales, CI o depuración, y los comandos de inteligencia del repositorio generan artefactos derivados de revisión cuando hay herramientas locales disponibles. +Truthmark V1 mantiene enfocada la CLI de terminal. La mayoría de los usuarios humanos solo necesita configuración, actualización y validación: -```bash -truthmark config -truthmark init -truthmark check -truthmark index -truthmark impact --base main -truthmark context --workflow truth-sync --base main -truthmark config --json -truthmark check --json -truthmark index --json -truthmark impact --base main --json -truthmark context --workflow truth-sync --base main --json -``` +| CLI orientada a personas | Uso | +| ------------------------ | --- | +| `truthmark config` | Crea `.truthmark/config.yml`; solo escribe ese archivo, salvo que se use `--stdout`. | +| `truthmark init` | Instala o refresca los archivos locales de flujo de trabajo desde la configuración revisada. | +| `truthmark check` | Valida configuración, autoridad, enrutamiento, documentos que contienen decisiones, frontmatter, enlaces internos, alcance de rama y diagnósticos de cobertura. | -`config` solo escribe `.truthmark/config.yml`, salvo que se use `--stdout`. +Los demás comandos CLI son ayudantes opcionales de inteligencia del repositorio. Generan contexto derivado para revisión sobre el checkout activo; no son fuentes de verdad: -`init` requiere `.truthmark/config.yml` y luego instala o refresca los archivos locales de flujo de trabajo. +| CLI opcional | Uso | +| ------------ | --- | +| `truthmark index` | Construye JSON de RepoIndex y RouteMap para el checkout activo. | +| `truthmark impact --base ` | Mapea los archivos cambiados a truth docs enrutados, rutas propietarias, pruebas cercanas y símbolos públicos. | +| `truthmark context --workflow [--base ]` | Genera un ContextPack acotado para Truth Sync, Truth Document o Truth Realize. `--format markdown` lo renderiza en un formato legible para personas. | -`check` valida configuración, autoridad, enrutamiento, documentos que contienen decisiones, frontmatter, enlaces internos, alcance de rama y diagnósticos de cobertura. +Todos los comandos CLI anteriores admiten `--json` cuando la salida estructurada es útil para automatización. -`index` construye JSON de RepoIndex y RouteMap para el checkout activo. - -`impact --base ` mapea los archivos cambiados a los truth docs enrutados, rutas propietarias, pruebas cercanas y símbolos públicos. - -`context --workflow [--base ]` genera un ContextPack acotado para Truth Sync, Truth Document o Truth Realize. `--format markdown` lo renderiza en un formato legible para personas. - -Truth Structure, Truth Document, Truth Sync, Truth Realize y Truth Check son flujos de trabajo instalados para agentes, no comandos CLI principales de uso diario. +Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize y Truth Check son flujos de trabajo instalados para agentes, no comandos CLI principales de uso diario. Se ejecutan a través de las superficies configuradas del host agente, por ejemplo Codex/Claude/Copilot `/truthmark-*`, OpenCode `/skill truthmark-*` o Gemini `/truthmark:*`. +Estas invocaciones parecen comandos porque los hosts de agentes exponen skills mediante slash commands. Trátalas como instrucciones para un agente, no como comandos de terminal que una persona deba ejecutar. + ```text /truthmark-check audita el enrutamiento y la cobertura de verdad antes de la revisión ``` @@ -297,7 +297,7 @@ V1 actualmente ofrece: - `truthmark impact` - `truthmark context` - instrucciones de flujo de trabajo administradas en `AGENTS.md` -- superficies de skill generadas para Truth Structure, Truth Document, Truth Sync, Truth Realize y Truth Check en los anfitriones de agentes configurados +- superficies de skill generadas para Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize y Truth Check en los anfitriones de agentes configurados - metadatos de alcance de rama - diagnósticos de configuración, autoridad, enrutamiento, estructura de decisiones, frontmatter, enlaces y cobertura políglota - artefactos derivados de RepoIndex, RouteMap, ImpactSet y ContextPack para una revisión local más rápida cuando la CLI está disponible diff --git a/README.md b/README.md index 6de4e8e..2294e05 100644 --- a/README.md +++ b/README.md @@ -96,6 +96,7 @@ Truthmark turns repository truth into an explicit workflow surface for agents: - `docs/truthmark/areas.md` and delegated child route files map code areas to the docs that own them. - Truth Document generates or repairs canonical truth docs for existing implemented behavior when no code change is needed. - Truth Sync keeps mapped truth docs aligned with functional changes. +- Truth Preview previews likely workflow routing before edits without authorizing writes. - Truth Realize gives doc-first changes a bounded code-update path. - `truthmark check` validates the resulting truth artifacts. - The whole model stays local-first and Git-native. @@ -219,18 +220,25 @@ Codex, Claude Code, and supported Copilot IDEs can invoke it with `/truthmark-re Truthmark keeps the durable workflow surface small and repository-native. After `truthmark init`, the repo itself carries the routing, rules, and installed workflow surfaces, so teams are not relying only on one operator's local setup. +Truthmark installs two distinct surfaces: + +- human-facing CLI commands, run by people or CI to configure the repo, refresh installed files, validate truth artifacts, and optionally generate derived review context +- agent workflow surfaces, invoked by coding agents or agent hosts during implementation workflows; they are not extra daily terminal commands for humans + - `.truthmark/config.yml` for the machine-readable committed hierarchy contract - `docs/truthmark/areas.md` for the root route index - `docs/truthmark/areas/**/*.md` for delegated child route files - `docs/templates/behavior-doc.md` plus the other kind-specific templates under `docs/templates/` for the editable truth-doc standards used by generated workflows - managed instruction blocks for configured platforms such as `AGENTS.md`, `CLAUDE.md`, Copilot instructions, and `GEMINI.md` -- host-native skills, prompts, or commands for Truth Structure, Truth Document, Truth Sync, Truth Realize, and Truth Check +- host-native skills, prompts, or commands for Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, and Truth Check +- Codex, Claude Code, GitHub Copilot, and OpenCode project-scoped read-only verifiers plus leased `truth-doc-writer` agents where hosts support agents, under `.codex/agents/`, `.claude/agents/`, `.github/agents/`, and `.opencode/agents/` for workflow-owned audits and parent-leased doc shards The installed workflow surfaces are the runtime: - Truth Structure creates or repairs area routing and starter truth docs. - Truth Document creates or repairs truth docs for existing implemented behavior. - Truth Sync keeps mapped truth docs aligned with functional changes. +- Truth Preview previews likely workflow routing before edits without writing files. - Truth Realize updates code to match truth docs. - Truth Check audits repository truth health. @@ -240,38 +248,30 @@ Generated surfaces are managed by Truthmark, include a version marker, and may b ## Commands -Truthmark V1 keeps the CLI focused because the ongoing workflow is meant to live in the installed agent surfaces, not in a long list of daily manual commands. In downstream repositories, `truthmark config` creates the committed hierarchy contract, `truthmark init` installs and refreshes workflow surfaces from that reviewed config, `truthmark check` validates truth artifacts for manual audits, CI, or troubleshooting, and the repository-intelligence commands generate derived review artifacts when local tooling is available. +Truthmark V1 keeps the terminal CLI focused. Most human users only need setup, refresh, and validation: -```bash -truthmark config -truthmark init -truthmark check -truthmark index -truthmark impact --base main -truthmark context --workflow truth-sync --base main -truthmark config --json -truthmark check --json -truthmark index --json -truthmark impact --base main --json -truthmark context --workflow truth-sync --base main --json -``` +| Human-facing CLI | Use | +| ---------------- | --- | +| `truthmark config` | Create `.truthmark/config.yml`; writes only that file unless `--stdout` is used. | +| `truthmark init` | Install or refresh local workflow files from the reviewed config. | +| `truthmark check` | Validate configuration, authority, routing, decision-bearing docs, frontmatter, internal links, branch scope, and coverage diagnostics. | -`config` writes only `.truthmark/config.yml` unless `--stdout` is used. +The remaining CLI commands are optional repository-intelligence helpers. They generate derived review context for the active checkout; they are not sources of truth: -`init` requires `.truthmark/config.yml`, then installs or refreshes the local workflow files. +| Optional CLI | Use | +| ------------ | --- | +| `truthmark index` | Build RepoIndex and RouteMap JSON for the active checkout. | +| `truthmark impact --base ` | Map changed files to routed truth docs, owning routes, nearby tests, and public symbols. | +| `truthmark context --workflow [--base ]` | Generate a bounded ContextPack for Truth Sync, Truth Document, or Truth Realize. `--format markdown` renders a human-readable pack. | -`check` validates configuration, authority, routing, decision-bearing docs, frontmatter, internal links, branch scope, and coverage diagnostics. +All CLI commands above support `--json` where structured output is useful for automation. -`index` builds RepoIndex and RouteMap JSON for the active checkout. - -`impact --base ` maps changed files to routed truth docs, owning routes, nearby tests, and public symbols. - -`context --workflow [--base ]` generates a bounded ContextPack for Truth Sync, Truth Document, or Truth Realize. `--format markdown` renders a human-readable pack. - -Truth Structure, Truth Document, Truth Sync, Truth Realize, and Truth Check are installed agent workflows, not top-level daily CLI commands. +Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, and Truth Check are installed agent workflows, not top-level daily CLI commands. They run through the configured agent host surfaces, for example Codex/Claude/Copilot `/truthmark-*`, OpenCode `/skill truthmark-*`, or Gemini `/truthmark:*`. +These invocations look command-like because agent hosts expose skills through slash commands. Treat them as instructions to an agent, not as terminal commands a human is expected to run. + ```text /truthmark-check audit routing and truth coverage before review ``` @@ -304,7 +304,7 @@ V1 currently provides: - `truthmark impact` - `truthmark context` - managed `AGENTS.md` workflow instructions -- generated Truth Structure, Truth Document, Truth Sync, Truth Realize, and Truth Check skill surfaces for configured agent hosts +- generated Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, and Truth Check skill surfaces for configured agent hosts - branch-scope metadata - config, authority, routing, decision-structure, frontmatter, link, freshness, and polyglot coverage diagnostics - derived RepoIndex, RouteMap, ImpactSet, and ContextPack artifacts for faster local review when the CLI is available diff --git a/README.ru.md b/README.ru.md index 18a3d25..6c49828 100644 --- a/README.ru.md +++ b/README.ru.md @@ -96,6 +96,7 @@ Truthmark превращает истину репозитория в явную - `docs/truthmark/areas.md` и делегированные дочерние файлы маршрутов сопоставляют области кода с документами, которые за них отвечают. - Truth Document создает или исправляет канонические документы истины для уже реализованного поведения, когда изменение кода не нужно. - Truth Sync поддерживает синхронизацию сопоставленных документов истины при функциональных изменениях. +- Truth Preview предварительно показывает вероятную маршрутизацию рабочего процесса до правок, не авторизуя записи. - Truth Realize дает изменениям, начинающимся с документации, ограниченный путь для обновления кода. - `truthmark check` валидирует получившиеся артефакты истины. - Вся модель остается local-first и Git-native. @@ -213,18 +214,25 @@ Codex, Claude Code и поддерживаемые IDE Copilot могут выз Truthmark держит постоянную рабочую поверхность маленькой и встроенной в репозиторий. После `truthmark init` сам репозиторий несет маршрутизацию, правила и установленные рабочие поверхности, поэтому команда не зависит только от локальной настройки одного человека. +Truthmark устанавливает два разных интерфейса: + +- CLI-команды для людей, которые запускают люди или CI, чтобы настроить репозиторий, обновить установленные файлы, проверить артефакты истины и при необходимости создать производный контекст для ревью +- агентские рабочие поверхности, которые вызывают coding agents или агентские хосты во время реализации; это не дополнительные ежедневные терминальные команды для людей + - `.truthmark/config.yml` для машиночитаемого зафиксированного контракта иерархии - `docs/truthmark/areas.md` для корневого индекса маршрутов - `docs/truthmark/areas/**/*.md` для делегированных дочерних файлов маршрутов - `docs/templates/behavior-doc.md` и другие шаблоны по видам под `docs/templates/` для редактируемых стандартов truth docs, используемых сгенерированными рабочими процессами - управляемые блоки инструкций для настроенных платформ, таких как `AGENTS.md`, `CLAUDE.md`, инструкции Copilot и `GEMINI.md` -- нативные для хоста skills, prompts или commands для Truth Structure, Truth Document, Truth Sync, Truth Realize и Truth Check +- нативные для хоста skills, prompts или commands для Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize и Truth Check +- проектные проверяющие агенты Codex, Claude Code, GitHub Copilot и OpenCode в режиме только чтения, а также leased-агенты `truth-doc-writer` там, где хост поддерживает агентов, под `.codex/agents/`, `.claude/agents/`, `.github/agents/` и `.opencode/agents/` для аудитов, которыми владеет рабочий процесс, и для документных шардов, выданных родительским агентом Установленные рабочие поверхности и есть среда выполнения: - Truth Structure создает или исправляет маршрутизацию областей и стартовые документы истины. - Truth Document создает или исправляет документы истины для уже реализованного поведения. - Truth Sync поддерживает синхронизацию сопоставленных документов истины с функциональными изменениями. +- Truth Preview предварительно показывает вероятную маршрутизацию рабочего процесса до правок без записи файлов. - Truth Realize обновляет код так, чтобы он соответствовал документам истины. - Truth Check аудитирует здоровье истины репозитория. @@ -234,38 +242,30 @@ Truthmark держит постоянную рабочую поверхност ## Команды -Truthmark V1 намеренно держит CLI небольшим, потому что постоянный рабочий процесс должен жить в установленных агентских поверхностях, а не в длинном списке ежедневных ручных команд. В нижестоящих репозиториях `truthmark config` создает зафиксированный контракт иерархии, `truthmark init` устанавливает и обновляет рабочие поверхности на основе этой проверенной конфигурации, `truthmark check` валидирует артефакты истины для ручных аудитов, CI или отладки, а команды репозиторной аналитики создают производные артефакты для проверки, когда доступны локальные инструменты. +Truthmark V1 держит терминальный CLI сфокусированным. Большинству людей нужны только настройка, обновление и проверка: -```bash -truthmark config -truthmark init -truthmark check -truthmark index -truthmark impact --base main -truthmark context --workflow truth-sync --base main -truthmark config --json -truthmark check --json -truthmark index --json -truthmark impact --base main --json -truthmark context --workflow truth-sync --base main --json -``` +| CLI-команда для людей | Назначение | +| --------------------- | ---------- | +| `truthmark config` | Создает `.truthmark/config.yml`; пишет только этот файл, если не используется `--stdout`. | +| `truthmark init` | Устанавливает или обновляет локальные файлы рабочих процессов из проверенной конфигурации. | +| `truthmark check` | Валидирует конфигурацию, полномочия, маршрутизацию, документы с решениями, frontmatter, внутренние ссылки, область действия ветки и диагностику покрытия. | -`config` пишет только `.truthmark/config.yml`, если не используется `--stdout`. +Остальные CLI-команды - необязательные помощники репозиторной аналитики. Они создают производный контекст для ревью активного checkout; они не являются источниками истины: -`init` требует `.truthmark/config.yml`, а затем устанавливает или обновляет локальные файлы рабочих процессов. +| Необязательная CLI-команда | Назначение | +| -------------------------- | ---------- | +| `truthmark index` | Строит JSON RepoIndex и RouteMap для активного checkout. | +| `truthmark impact --base ` | Сопоставляет измененные файлы с routed truth docs, owning routes, nearby tests и public symbols. | +| `truthmark context --workflow [--base ]` | Генерирует ограниченный ContextPack для Truth Sync, Truth Document или Truth Realize. `--format markdown` рендерит его в читаемый человеком вид. | -`check` валидирует конфигурацию, полномочия, маршрутизацию, документы с решениями, frontmatter, внутренние ссылки, область действия ветки и диагностику покрытия. +Все CLI-команды выше поддерживают `--json`, когда структурированный вывод полезен для автоматизации. -`index` строит JSON RepoIndex и RouteMap для активного checkout. - -`impact --base ` сопоставляет измененные файлы с routed truth docs, owning routes, nearby tests и public symbols. - -`context --workflow [--base ]` генерирует ограниченный ContextPack для Truth Sync, Truth Document или Truth Realize. `--format markdown` рендерит его в читаемый человеком вид. - -Truth Structure, Truth Document, Truth Sync, Truth Realize и Truth Check это установленные агентские рабочие процессы, а не повседневные CLI-команды верхнего уровня. +Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize и Truth Check это установленные агентские рабочие процессы, а не повседневные CLI-команды верхнего уровня. Они запускаются через настроенные поверхности хоста агента, например Codex/Claude/Copilot `/truthmark-*`, OpenCode `/skill truthmark-*` или Gemini `/truthmark:*`. +Эти вызовы выглядят как команды, потому что агентские хосты предоставляют skills через slash-команды. Относитесь к ним как к инструкциям для агента, а не как к терминальным командам, которые должен запускать человек. + ```text /truthmark-check проверь маршрутизацию и покрытие truth перед review ``` @@ -297,7 +297,7 @@ V1 сейчас предоставляет: - `truthmark impact` - `truthmark context` - управляемые инструкции рабочих процессов в `AGENTS.md` -- сгенерированные skill-поверхности Truth Structure, Truth Document, Truth Sync, Truth Realize и Truth Check для настроенных агентских хостов +- сгенерированные skill-поверхности Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize и Truth Check для настроенных агентских хостов - метаданные области ветки - диагностика конфигурации, полномочий, маршрутизации, структуры решений, frontmatter, ссылок и полиглотного покрытия - производные артефакты RepoIndex, RouteMap, ImpactSet и ContextPack для более быстрой локальной проверки, когда CLI доступен diff --git a/README.zh.md b/README.zh.md index 5992f86..a3f1aae 100644 --- a/README.zh.md +++ b/README.zh.md @@ -96,6 +96,7 @@ Truthmark 把仓库事实变成代理可见的显式工作流载体: - `docs/truthmark/areas.md` 和委托的子路由文件把代码区域映射到负责它们的文档。 - Truth Document 在无需修改代码时,为已实现行为生成或修复规范事实文档。 - Truth Sync 在功能性变更发生时,让已映射的事实文档保持同步。 +- Truth Preview 在编辑前预览可能的工作流路由,但不授权写入。 - Truth Realize 为文档优先的变更提供有边界的代码更新路径。 - `truthmark check` 验证最终形成的事实产物。 - 整个模型保持本地优先和 Git 原生。 @@ -213,18 +214,25 @@ Codex、Claude Code 和支持的 Copilot IDE 可以用 `/truthmark-realize` 调 Truthmark 把持久化的工作流载体保持得很小,而且是仓库原生的。运行 `truthmark init` 之后,仓库本身就携带路由、规则和已安装的工作流载体,因此团队不再只依赖某个人的本地配置。 +Truthmark 会安装两类不同入口: + +- 面向人的 CLI 命令,由人或 CI 运行,用来配置仓库、刷新已安装文件、验证 truth artifacts,并可选生成派生的审查上下文 +- 面向代理的工作流载体,由编码代理或代理宿主在实现工作流中调用;它们不是给人每天在终端里额外运行的命令 + - `.truthmark/config.yml`,用于机器可读的已提交层级契约 - `docs/truthmark/areas.md`,用于根路由索引 - `docs/truthmark/areas/**/*.md`,用于委托的子路由文件 - `docs/templates/behavior-doc.md` 以及 `docs/templates/` 下其他按类型划分的模板,用作生成工作流采用的可编辑 truth doc 标准 - 面向已配置平台的受管说明块,例如 `AGENTS.md`、`CLAUDE.md`、Copilot 指令和 `GEMINI.md` -- 面向 Truth Structure、Truth Document、Truth Sync、Truth Realize 和 Truth Check 的宿主原生技能、提示或命令 +- 面向 Truth Structure、Truth Document、Truth Sync、Truth Preview、Truth Realize 和 Truth Check 的宿主原生技能、提示或命令 +- `.codex/agents/`、`.claude/agents/`、`.github/agents/` 和 `.opencode/agents/` 下项目级 Codex、Claude Code、GitHub Copilot 与 OpenCode 只读验证器,以及在宿主支持代理时使用的租约式 `truth-doc-writer` 代理,用于工作流自有审计和父代理租约授权的文档分片 安装后的工作流载体就是运行时: - Truth Structure 创建或修复区域路由和起始事实文档。 - Truth Document 为已实现行为创建或修复事实文档。 - Truth Sync 在功能性变更发生时,让已映射的事实文档保持同步。 +- Truth Preview 在编辑前预览可能的工作流路由,但不写入文件。 - Truth Realize 更新代码,使其符合事实文档。 - Truth Check 审计仓库事实的健康状况。 @@ -234,38 +242,30 @@ Truthmark 把持久化的工作流载体保持得很小,而且是仓库原生 ## 命令 -Truthmark V1 有意保持 CLI 很小,因为持续运行的工作流应该活在已安装的代理载体里,而不是一长串日常手动命令里。在下游仓库中,`truthmark config` 创建已提交的层级契约,`truthmark init` 根据这份已审查的配置安装和刷新工作流载体,`truthmark check` 则为人工审计、CI 或问题排查验证事实产物,而仓库情报命令会在有本地工具时生成派生审查产物。 +Truthmark V1 会保持终端 CLI 聚焦。大多数人类用户只需要设置、刷新和验证: -```bash -truthmark config -truthmark init -truthmark check -truthmark index -truthmark impact --base main -truthmark context --workflow truth-sync --base main -truthmark config --json -truthmark check --json -truthmark index --json -truthmark impact --base main --json -truthmark context --workflow truth-sync --base main --json -``` +| 面向人的 CLI | 用途 | +| ------------ | ---- | +| `truthmark config` | 创建 `.truthmark/config.yml`;除非使用 `--stdout`,否则只写入这个文件。 | +| `truthmark init` | 根据已审查配置安装或刷新本地工作流文件。 | +| `truthmark check` | 验证配置、权限边界、路由、承载决策的文档、frontmatter、内部链接、分支范围和覆盖率诊断。 | -`config` 只写入 `.truthmark/config.yml`,除非使用 `--stdout`。 +其余 CLI 命令是可选的仓库情报辅助工具。它们为当前 checkout 生成派生审查上下文;它们不是事实来源: -`init` 需要 `.truthmark/config.yml`,然后安装或刷新本地工作流文件。 +| 可选 CLI | 用途 | +| -------- | ---- | +| `truthmark index` | 为当前 checkout 构建 RepoIndex 和 RouteMap JSON。 | +| `truthmark impact --base ` | 把变更文件映射到已路由的 truth docs、所属路由、附近测试和 public symbols。 | +| `truthmark context --workflow [--base ]` | 为 Truth Sync、Truth Document 或 Truth Realize 生成受限的 ContextPack。`--format markdown` 会把它渲染成可读文本。 | -`check` 验证配置、权限边界、路由、承载决策的文档、frontmatter、内部链接、分支范围和覆盖率诊断。 +上面所有 CLI 命令在需要结构化输出用于自动化时都支持 `--json`。 -`index` 为当前 checkout 构建 RepoIndex 和 RouteMap JSON。 - -`impact --base ` 会把变更文件映射到已路由的 truth docs、所属路由、附近测试和 public symbols。 - -`context --workflow [--base ]` 会为 Truth Sync、Truth Document 或 Truth Realize 生成一个受限的 ContextPack。`--format markdown` 会把它渲染成可读文本。 - -Truth Structure、Truth Document、Truth Sync、Truth Realize 和 Truth Check 是已安装的代理工作流,不是日常使用的顶层 CLI 命令。 +Truth Structure、Truth Document、Truth Sync、Truth Preview、Truth Realize 和 Truth Check 是已安装的代理工作流,不是日常使用的顶层 CLI 命令。 它们通过已配置的代理宿主表面运行,例如 Codex/Claude/Copilot 的 `/truthmark-*`、OpenCode 的 `/skill truthmark-*`,或者 Gemini 的 `/truthmark:*`。 +这些调用看起来像命令,是因为代理宿主会通过 slash commands 暴露技能。应把它们当作给代理的指令,而不是人类需要在终端中运行的 Truthmark CLI 命令。 + ```text /truthmark-check 在 review 前审计路由和 truth 覆盖 ``` @@ -297,7 +297,7 @@ V1 目前提供: - `truthmark impact` - `truthmark context` - 受管的 `AGENTS.md` 工作流说明 -- 为已配置代理宿主生成的 Truth Structure、Truth Document、Truth Sync、Truth Realize 和 Truth Check 技能载体 +- 为已配置代理宿主生成的 Truth Structure、Truth Document、Truth Sync、Truth Preview、Truth Realize 和 Truth Check 技能载体 - 分支范围元数据 - 配置、权限边界、路由、决策结构、frontmatter、链接和多语言覆盖率诊断 - RepoIndex、RouteMap、ImpactSet 和 ContextPack 派生产物,可在 CLI 可用时加快本地检查 diff --git a/changes/2026-05-16-version-140.md b/changes/2026-05-16-version-140.md new file mode 100644 index 0000000..b9e80a4 --- /dev/null +++ b/changes/2026-05-16-version-140.md @@ -0,0 +1,27 @@ +# Workflow Verifier And Writer Agents + +Previous version: 1.3.0 +New version: 1.4.0 +Diff basis: release/1.3.0..HEAD plus working tree +Version action: minor +SemVer rationale: The pending payload adds generated read-only verifier-agent workflow surfaces, leased `truth-doc-writer` workflow surfaces where hosts support agents, and workflow subagent guidance, which are backward-compatible generated-surface and shipped-workflow capabilities. + +Release payload: +- Added project-scoped read-only verifiers plus leased `truth-doc-writer` agents for Codex, Claude Code, GitHub Copilot, and OpenCode where hosts support agents. +- Added workflow skill and prompt guidance for bounded subagent dispatch while keeping parent workflows responsible for final reports, write leases, and diff validation. +- Added deterministic write-worker acceptance validation so parent workflows can parse worker reports and compare actual worker diffs against leases before accepting completed work. +- Updated init, classification, markdown discovery, generated-surface tests, workflow truth docs, root README variants, and routing docs for the new verifier and leased writer agent surfaces. +- Moved the external agent-skills workflow review out of `docs/ai/` into non-canonical `research/`. +- Renamed the host-neutral workflow renderer from `src/templates/codex-skills.ts` to `src/templates/workflow-surfaces.ts`. +- Tightened versioning and change-note standards so requested package versions must be checked against the full pending release payload. + +User-facing release text: +- Truthmark now installs read-only verifiers plus leased `truth-doc-writer` agents where hosts support agents, so workflows can delegate bounded evidence checks and parent-leased doc shards without giving up parent-owned write control. +- Package version bumps now require release notes that describe the actual release payload since the previous version, not just the version-number edit. + +Verification: +- `npm test -- tests/package-files.test.ts` +- `npm run check` +- `npm run release:check` +- `npm run dev -- init --json` +- `npm run dev -- check --json` diff --git a/docs/ai/agent-onboarding.md b/docs/ai/agent-onboarding.md index 796085a..e891718 100644 --- a/docs/ai/agent-onboarding.md +++ b/docs/ai/agent-onboarding.md @@ -1,7 +1,7 @@ --- status: active doc_type: agent-guide -last_reviewed: 2026-05-13 +last_reviewed: 2026-05-16 source_of_truth: - repo-rules.md - ../README.md @@ -47,7 +47,7 @@ Read: 1. [.truthmark/config.yml](../../.truthmark/config.yml) 2. [docs/truth/workflows/overview.md](../truth/workflows/overview.md) and the relevant workflow leaf doc under `docs/truth/workflows/` 3. [docs/standards/maintaining-repository-truth.md](../standards/maintaining-repository-truth.md) -4. [docs/ai/agent-skills-workflow-review.md](agent-skills-workflow-review.md) +4. The manifest, renderer, generated surfaces, and focused tests named by the workflow truth docs ### Package version changes diff --git a/docs/ai/repo-rules.md b/docs/ai/repo-rules.md index 1ee4133..283b8b3 100644 --- a/docs/ai/repo-rules.md +++ b/docs/ai/repo-rules.md @@ -1,7 +1,7 @@ --- status: active doc_type: agent-rules -last_reviewed: 2026-05-15 +last_reviewed: 2026-05-16 source_of_truth: - ../../AGENTS.md - ../README.md @@ -28,7 +28,7 @@ Code is the implementation. On code/doc conflict, inspect code, decide whether c ## Product Boundary -Truthmark public CLI commands are `config`, `init`, `check`, `index`, `impact`, and `context`. Truth Structure, Truth Document, Truth Sync, Truth Realize, and Truth Check are installed workflow surfaces, not CLI commands. +Truthmark public CLI commands are `config`, `init`, `check`, `index`, `impact`, and `context`. Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, and Truth Check are installed workflow surfaces, not CLI commands. Agents inspect the active checkout directly. There is no daemon, database, remote service, or V1 MCP server. @@ -49,6 +49,14 @@ Agents inspect the active checkout directly. There is no daemon, database, remot 13. Verify the text and file contracts that changed with the narrowest evidence that can falsify them: generated diffs, structured parsers, snapshots, fixture round-trips, build/package/check commands, or focused tests. Do not run broad tests as ceremony when they add no evidence; state skipped checks. 14. Work surgically and fail visibly: surface assumptions, conflicts, skipped files, blocked ownership, and unverified claims; touch only request-traceable lines, match existing style, checkpoint long workflow or skill edits, and report unrelated issues instead of editing them. +## Instruction Surface Boundary + +In `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`, and `.github/copilot-instructions.md`, only text between `` and `` is the generated Truthmark workflow surface. Repo-local preamble outside those markers should delegate to this file and conditional routing docs, not duplicate completion policy. Do not put this repository's internal policy, completion gates, or maintainer-only standards inside marker-delimited blocks, package templates, installed workflow skills, prompts, or downstream scaffold output. + +## Completion Gate + +Before declaring changed repository work complete, apply [docs/standards/pre-completion-checklist.md](../standards/pre-completion-checklist.md) and [docs/standards/testing-and-verification.md](../standards/testing-and-verification.md). Skip this gate only for read-only or no-file-change sessions, and state the skip reason when completion or verification would otherwise be expected. + ## Routing Fast task routing lives in [agent-onboarding.md](agent-onboarding.md). Read only the docs that govern the slice you are changing. diff --git a/docs/architecture/module-map.md b/docs/architecture/module-map.md index 62b2c99..e10596e 100644 --- a/docs/architecture/module-map.md +++ b/docs/architecture/module-map.md @@ -39,7 +39,7 @@ This doc covers the current module grouping of the Truthmark codebase and the pr | `src/truth/` | Neutral helpers for truth root resolution and evidence report formatting shared by scaffold, checks, sync, and agent renderers | | `src/git/` | Git repository and worktree resolution plus change listing | | `src/sync/` | Truth Sync policy and completed, skipped, or blocked report rendering | -| `src/agents/` | Installed Truth Structure, Truth Document, Truth Sync, Truth Realize, and Truth Check instruction text plus shared worker and skill contract fragments | +| `src/agents/` | Installed Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, and Truth Check instruction text plus shared worker and skill contract fragments | | `src/realize/` | Truth Realize report rendering | | `src/output/` | Diagnostic types plus human and JSON rendering shared by CLI and check flows | | `src/types/` | Local type shims | diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md index b675838..ab45979 100644 --- a/docs/architecture/overview.md +++ b/docs/architecture/overview.md @@ -1,7 +1,7 @@ --- status: active doc_type: architecture -last_reviewed: 2026-05-13 +last_reviewed: 2026-05-16 source_of_truth: - ../../.truthmark/config.yml - ../truth/contracts.md @@ -36,7 +36,7 @@ The durable surfaces are ordinary repository files: - [docs/truthmark/areas.md](../truthmark/areas.md) - canonical docs under `docs/` - the managed Truthmark block inside [AGENTS.md](../../AGENTS.md) -- generated Truth Structure, Truth Document, Truth Sync, Truth Realize, and Truth Check surfaces under `.codex/skills/`, `.opencode/skills/`, `.claude/skills/`, `.github/prompts/`, and `.gemini/commands/truthmark/` +- generated Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, and Truth Check surfaces under `.codex/skills/`, `.opencode/skills/`, `.claude/skills/`, `.github/prompts/`, and `.gemini/commands/truthmark/` - Codex workflow metadata under `.codex/skills/truthmark-*/agents/openai.yaml` - configured platform instruction files such as [AGENTS.md](../../AGENTS.md), `CLAUDE.md`, `.github/copilot-instructions.md`, and `GEMINI.md` @@ -77,16 +77,16 @@ Key implementation surfaces: ### Installed workflow support -Truthmark also contains support primitives for the installed Truth Structure, Truth Document, Truth Sync, Truth Realize, and Truth Check workflows: +Truthmark also contains support primitives for the installed Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, and Truth Check workflows: - `src/templates/agents-block.ts` renders compact managed instruction blocks - `src/agents/*` renders detailed workflow and skill text for explicit workflow invocation -- `src/templates/codex-skills.ts` renders generated skill, prompt, command, and metadata content for configured platforms +- `src/templates/workflow-surfaces.ts` renders generated skill, prompt, command, and metadata content for configured platforms - `src/templates/generated-surfaces.ts` assembles configured platform surfaces from the renderers - `src/sync/*` classifies functional-code paths and renders Truth Sync reports - `src/realize/report.ts` renders the Truth Realize completion report shape -These modules support the installed workflow contract even though V1 does not expose dedicated CLI entrypoints for the installed Truth Structure, Truth Document, Truth Sync, Truth Realize, or Truth Check workflows. +These modules support the installed workflow contract even though V1 does not expose dedicated CLI entrypoints for the installed Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, or Truth Check workflows. ## Architecture Doc Boundary @@ -120,7 +120,7 @@ Current automatic coverage discovery scans common roots such as `src/`, `api/`, - `src/checks/areas.ts` - `src/sync/surfaces.ts` - `src/agents/instructions.ts` -- `src/templates/codex-skills.ts` +- `src/templates/workflow-surfaces.ts` - `src/templates/generated-surfaces.ts` - `src/templates/agents-block.ts` diff --git a/docs/standards/change-notes.md b/docs/standards/change-notes.md index 27dbf4d..fa7c5a4 100644 --- a/docs/standards/change-notes.md +++ b/docs/standards/change-notes.md @@ -38,12 +38,12 @@ Use dates from the current local session date. Keep slugs short, lowercase, and ## Required Shape -Each change note must use this structure: +Each change note must use this structure when `Version action` is `none`: ```markdown # Short Change Title -Version action: none|patch|minor|major +Version action: none ## PR Summary @@ -58,11 +58,35 @@ Version action: none|patch|minor|major - Command run, or skipped check with reason. ``` +Each change note must use this structure when `Version action` is `patch`, `minor`, or `major`: + +```markdown +# Short Change Title + +Previous version: MAJOR.MINOR.PATCH +New version: MAJOR.MINOR.PATCH +Diff basis: release/MAJOR.MINOR.PATCH..HEAD plus working tree +Version action: patch|minor|major +SemVer rationale: One sentence explaining why the pending release payload requires this bump. + +Release payload: +- Concise maintainer-facing summary of an actual release-worthy change. + +User-facing release text: +- User-visible release note. + +Verification: +- Command run, or skipped check with reason. +``` + ## Rules - `Version action` must match [versioning.md](versioning.md). - If `Version action` is `patch`, `minor`, or `major`, the package version must change in the same working change. -- If the package version changes, a matching change note is required because Truthmark releases whenever the package version changes. +- If the package version changes, a matching change note for the new version is required because Truthmark releases whenever the package version changes. +- Versioned change notes must describe all release-worthy pending changes since the previous release tag, not only the package metadata edit or generated version-marker refresh. +- Versioned change notes must name the previous version, new version, diff basis, SemVer rationale, release payload, user-facing release text, and verification. +- Verification entries should report final useful checks only; do not include red-test scaffolding, agent mistakes, or process chatter in release-facing change notes. - Internal-only repository standards may use `Version action: none`. - Release notes describe published package behavior, not private repo maintenance. - Keep notes compact; they are source material for PR and release descriptions, not canonical product truth. diff --git a/docs/standards/versioning.md b/docs/standards/versioning.md index 201bae0..8309bf5 100644 --- a/docs/standards/versioning.md +++ b/docs/standards/versioning.md @@ -64,10 +64,17 @@ Treat these as published package behavior: ## Version Change Procedure +Before changing a version number: + +1. Identify the previous released version from the latest lower `release/` tag. +2. Inspect all pending release payload since that previous version: committed branch diff plus staged, unstaged, and untracked files that will ship. +3. Classify the payload with the decision table above before editing `package.json`. +4. If the requested new version is lower than the required bump, block the edit and report the required version. Do not accept a patch request for a minor or major payload. + When changing a version number: -1. Decide the bump class before editing the version and state the rationale in the handoff, PR, or release note. -2. Create or update the matching `changes/` note from [change-notes.md](change-notes.md). +1. State the previous version, requested version, required bump class, and SemVer rationale in the handoff, PR, or release note. +2. Create or update the matching `changes/` note from [change-notes.md](change-notes.md), covering the full release payload since the previous version. 3. Update `package.json` and the root package entries in `package-lock.json` together. 4. Rerun `truthmark init` only when the package version actually changes, then inspect generated version-marker diffs. 5. Run the focused verification required by [testing-and-verification.md](testing-and-verification.md). For release-sensitive package version changes, `npm run release:check` is the default final gate. @@ -78,6 +85,7 @@ When reporting a package version decision, state only: - chosen version action - one-line SemVer rationale +- whether the requested version matched the required bump - files changed or intentionally left unchanged - matching change note path when a version changes - verification run or explicitly skipped diff --git a/docs/truth/check-diagnostics.md b/docs/truth/check-diagnostics.md index 54ea867..2a90c9c 100644 --- a/docs/truth/check-diagnostics.md +++ b/docs/truth/check-diagnostics.md @@ -24,7 +24,7 @@ This document describes the current behavior of `truthmark check`. ## Current Behavior -`truthmark check` is validation tooling. It is not the runtime for Truth Sync, Truth Realize, Truth Structure, or Truth Check skills, and it is not a CI-style merge gate by default. +`truthmark check` is validation tooling. It is not the runtime for Truth Sync, Truth Preview, Truth Realize, Truth Structure, or Truth Check skills, and it is not a CI-style merge gate by default. The command: diff --git a/docs/truth/contracts.md b/docs/truth/contracts.md index 9b5686f..75f710a 100644 --- a/docs/truth/contracts.md +++ b/docs/truth/contracts.md @@ -70,6 +70,8 @@ Route files may express `Truth documents` in either of these forms: New scaffolded child route files use the fenced YAML form so routed truth kind is explicit from the first generated route. The legacy list form remains a compatibility input for existing repositories. +Markdown list values normalize Prettier-escaped glob stars before route matching, so formatted entries such as `src/example/\*\*` are treated as `src/example/**`. + Supported routed truth kinds are: - `behavior` @@ -163,7 +165,7 @@ The command emits `action` diagnostics describing whether each scaffolded file w `truthmark init` requires an existing valid `.truthmark/config.yml`. It does not create config; `truthmark config` is the required first step in a new repository. Configured `instruction_targets` are generated or refreshed independently of platform-specific surfaces, so `AGENTS.md` remains managed even when `claude-code` is not in `platforms`. -Generated Truth Structure, Truth Document, Truth Sync, and Truth Check surfaces and the managed `AGENTS.md` block use the `truth-sync` diagnostic category. +Generated Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Check, Codex, Claude Code, GitHub Copilot, and OpenCode verifier or leased doc-writer agent surfaces, and the managed `AGENTS.md` block use the `truth-sync` diagnostic category. Current agent-native scaffold targets include: @@ -177,16 +179,41 @@ Current agent-native scaffold targets include: - `.codex/skills/truthmark-realize/agents/openai.yaml` - `.codex/skills/truthmark-check/SKILL.md` - `.codex/skills/truthmark-check/agents/openai.yaml` +- `.codex/skills/truthmark-preview/SKILL.md` +- `.codex/skills/truthmark-preview/agents/openai.yaml` +- `.codex/skills/truthmark-*/support/procedure.md` +- `.codex/skills/truthmark-*/support/report-template.md` +- `.codex/skills/truthmark-*/support/subagents-and-leases.md` when the workflow has generated subagent guidance +- `.codex/agents/truth-route-auditor.toml` +- `.codex/agents/truth-claim-verifier.toml` +- `.codex/agents/truth-doc-reviewer.toml` +- `.codex/agents/truth-doc-writer.toml` - `.claude/skills/truthmark-structure/SKILL.md` - `.claude/skills/truthmark-document/SKILL.md` - `.claude/skills/truthmark-sync/SKILL.md` - `.claude/skills/truthmark-realize/SKILL.md` - `.claude/skills/truthmark-check/SKILL.md` +- `.claude/skills/truthmark-preview/SKILL.md` +- `.claude/skills/truthmark-*/support/procedure.md` +- `.claude/skills/truthmark-*/support/report-template.md` +- `.claude/skills/truthmark-*/support/subagents-and-leases.md` when the workflow has generated subagent guidance +- `.claude/agents/truth-route-auditor.md` +- `.claude/agents/truth-claim-verifier.md` +- `.claude/agents/truth-doc-reviewer.md` +- `.claude/agents/truth-doc-writer.md` - `.opencode/skills/truthmark-structure/SKILL.md` - `.opencode/skills/truthmark-document/SKILL.md` - `.opencode/skills/truthmark-sync/SKILL.md` - `.opencode/skills/truthmark-realize/SKILL.md` - `.opencode/skills/truthmark-check/SKILL.md` +- `.opencode/skills/truthmark-preview/SKILL.md` +- `.opencode/skills/truthmark-*/support/procedure.md` +- `.opencode/skills/truthmark-*/support/report-template.md` +- `.opencode/skills/truthmark-*/support/subagents-and-leases.md` when the workflow has generated subagent guidance +- `.opencode/agents/truth-route-auditor.md` +- `.opencode/agents/truth-claim-verifier.md` +- `.opencode/agents/truth-doc-reviewer.md` +- `.opencode/agents/truth-doc-writer.md` - `AGENTS.md` - `CLAUDE.md` - `.github/copilot-instructions.md` @@ -195,14 +222,22 @@ Current agent-native scaffold targets include: - `.github/prompts/truthmark-sync.prompt.md` - `.github/prompts/truthmark-realize.prompt.md` - `.github/prompts/truthmark-check.prompt.md` +- `.github/prompts/truthmark-preview.prompt.md` +- `.github/agents/truth-route-auditor.agent.md` +- `.github/agents/truth-claim-verifier.agent.md` +- `.github/agents/truth-doc-reviewer.agent.md` +- `.github/agents/truth-doc-writer.agent.md` - `GEMINI.md` - `.gemini/commands/truthmark/structure.toml` - `.gemini/commands/truthmark/document.toml` - `.gemini/commands/truthmark/sync.toml` - `.gemini/commands/truthmark/realize.toml` - `.gemini/commands/truthmark/check.toml` +- `.gemini/commands/truthmark/preview.toml` -Generated `SKILL.md` files use closed YAML frontmatter with `name`, `description`, `argument-hint`, `user-invocable`, and `truthmark-version` fields so Codex-style, Claude Code, and OpenCode-style skill indexers can parse every generated workflow surface. Generated Copilot prompt files use `.github/prompts/*.prompt.md` files with `agent` and `description` frontmatter so supported Copilot IDEs can expose `/truthmark-*` prompts. Generated Codex metadata includes a `truthmark.version` marker plus `truthmark.refresh_command: "truthmark init"`. Managed instruction blocks also render the Truthmark package version, and `package.json` is the single maintained version source for those markers. Generated Gemini command files use project-scoped TOML custom commands so `truthmark init` can install `/truthmark:structure`, `/truthmark:document`, `/truthmark:sync`, `/truthmark:realize`, and `/truthmark:check` alongside `GEMINI.md`. Re-running `truthmark init` after a package upgrade refreshes configured committed surfaces and exposes staleness through ordinary Git diffs. Removing a platform from config stops future refreshes for that platform; it does not delete previously generated files. +Generated `SKILL.md` files use closed YAML frontmatter with `name`, `description`, `argument-hint`, `user-invocable`, and `truthmark-version` fields so Codex-style, Claude Code, and OpenCode-style skill indexers can parse every generated workflow surface. For those skill-package hosts, `SKILL.md` is the compact routing and quick-procedure entrypoint; detailed procedure text, report templates, and subagent or lease reference material live in generated sibling `support/*.md` files. Generated Copilot prompt files use `.github/prompts/*.prompt.md` files with `agent` and `description` frontmatter so supported Copilot IDEs can expose `/truthmark-*` prompts. Generated verifier agents are read-only and context-bounded to parent-assigned shards, while generated `truth-doc-writer` agents are write-capable only through parent-provided leases and parent diff validation. Generated Codex metadata includes a `truthmark.version` marker plus `truthmark.refresh_command: "truthmark init"`. Managed instruction blocks also render the Truthmark package version, and `package.json` is the single maintained version source for those markers. Generated Gemini command files use project-scoped TOML custom commands so `truthmark init` can install `/truthmark:structure`, `/truthmark:document`, `/truthmark:sync`, `/truthmark:preview`, `/truthmark:realize`, and `/truthmark:check` alongside `GEMINI.md`. Re-running `truthmark init` after a package upgrade refreshes configured committed surfaces and exposes staleness through ordinary Git diffs. Removing a platform from config stops future refreshes for that platform; it does not delete previously generated files. + +The OpenCode `truth-doc-writer` edit allow-list is rendered from the active `docs.roots.truth`, `docs.routing.root_index`, and `docs.routing.area_files_root` config paths so valid leases remain writable in non-default documentation layouts. ## Check Result Data diff --git a/docs/truth/init-and-scaffold.md b/docs/truth/init-and-scaffold.md index ff7f5f5..43def03 100644 --- a/docs/truth/init-and-scaffold.md +++ b/docs/truth/init-and-scaffold.md @@ -2,7 +2,7 @@ status: active doc_type: behavior truth_kind: behavior -last_reviewed: 2026-05-14 +last_reviewed: 2026-05-16 source_of_truth: - ../../src/config/defaults.ts - ../../src/fs/paths.ts @@ -10,7 +10,7 @@ source_of_truth: - ../../src/init/hierarchy.ts - ../../src/templates/init-files.ts - ../../src/templates/agents-block.ts - - ../../src/templates/codex-skills.ts + - ../../src/templates/workflow-surfaces.ts - ../../src/templates/generated-surfaces.ts --- @@ -67,35 +67,59 @@ Current scaffold targets: - `.codex/skills/truthmark-realize/agents/openai.yaml` - `.codex/skills/truthmark-check/SKILL.md` - `.codex/skills/truthmark-check/agents/openai.yaml` +- `.codex/skills/truthmark-preview/SKILL.md` +- `.codex/skills/truthmark-preview/agents/openai.yaml` +- `.codex/skills/truthmark-*/support/procedure.md` +- `.codex/skills/truthmark-*/support/report-template.md` +- `.codex/skills/truthmark-*/support/subagents-and-leases.md` when the workflow has generated subagent guidance +- `.codex/agents/truth-route-auditor.toml` +- `.codex/agents/truth-claim-verifier.toml` +- `.codex/agents/truth-doc-reviewer.toml` - `.opencode/skills/truthmark-structure/SKILL.md` - `.opencode/skills/truthmark-document/SKILL.md` - `.opencode/skills/truthmark-sync/SKILL.md` - `.opencode/skills/truthmark-realize/SKILL.md` - `.opencode/skills/truthmark-check/SKILL.md` +- `.opencode/skills/truthmark-preview/SKILL.md` +- `.opencode/skills/truthmark-*/support/procedure.md` +- `.opencode/skills/truthmark-*/support/report-template.md` +- `.opencode/skills/truthmark-*/support/subagents-and-leases.md` when the workflow has generated subagent guidance +- `.opencode/agents/truth-route-auditor.md` +- `.opencode/agents/truth-claim-verifier.md` +- `.opencode/agents/truth-doc-reviewer.md` - `.claude/skills/truthmark-structure/SKILL.md` - `.claude/skills/truthmark-document/SKILL.md` - `.claude/skills/truthmark-sync/SKILL.md` - `.claude/skills/truthmark-realize/SKILL.md` - `.claude/skills/truthmark-check/SKILL.md` +- `.claude/skills/truthmark-preview/SKILL.md` +- `.claude/skills/truthmark-*/support/procedure.md` +- `.claude/skills/truthmark-*/support/report-template.md` +- `.claude/skills/truthmark-*/support/subagents-and-leases.md` when the workflow has generated subagent guidance - `.github/copilot-instructions.md` - `.github/prompts/truthmark-structure.prompt.md` - `.github/prompts/truthmark-document.prompt.md` - `.github/prompts/truthmark-sync.prompt.md` - `.github/prompts/truthmark-realize.prompt.md` - `.github/prompts/truthmark-check.prompt.md` +- `.github/prompts/truthmark-preview.prompt.md` +- `.github/agents/truth-route-auditor.agent.md` +- `.github/agents/truth-claim-verifier.agent.md` +- `.github/agents/truth-doc-reviewer.agent.md` - `GEMINI.md` - `.gemini/commands/truthmark/structure.toml` - `.gemini/commands/truthmark/document.toml` - `.gemini/commands/truthmark/sync.toml` - `.gemini/commands/truthmark/realize.toml` - `.gemini/commands/truthmark/check.toml` +- `.gemini/commands/truthmark/preview.toml` `instruction_targets` controls shared managed-instruction files such as `AGENTS.md`. These targets are written or refreshed whenever `truthmark init` runs with a valid config, independent of the configured platform list. -`platforms` controls which platform-specific surfaces are written or refreshed. Defaults include all supported platforms: `codex`, `opencode`, `claude-code`, `github-copilot`, and `gemini-cli`. Teams should remove unused platforms from `.truthmark/config.yml` before rerunning `truthmark init`. Claude Code installs both `CLAUDE.md` and project skills under `.claude/skills/`, which surface as `/truthmark-structure`, `/truthmark-document`, `/truthmark-sync`, `/truthmark-realize`, and `/truthmark-check`. GitHub Copilot installs both `.github/copilot-instructions.md` and prompt files under `.github/prompts/`, which surface as `/truthmark-structure`, `/truthmark-document`, `/truthmark-sync`, `/truthmark-realize`, and `/truthmark-check` in supported Copilot IDEs. Gemini installs both `GEMINI.md` and project-scoped TOML commands under `.gemini/commands/truthmark/`, which surface as `/truthmark:structure`, `/truthmark:document`, `/truthmark:sync`, `/truthmark:realize`, and `/truthmark:check` in Gemini CLI. Unknown platform names are config errors. Removing a platform stops future refreshes for that platform, but `init` does not delete previously generated files. +`platforms` controls which platform-specific surfaces are written or refreshed. Defaults include all supported platforms: `codex`, `opencode`, `claude-code`, `github-copilot`, and `gemini-cli`. Teams should remove unused platforms from `.truthmark/config.yml` before rerunning `truthmark init`. Claude Code installs `CLAUDE.md`, project skills under `.claude/skills/`, and verifier plus leased doc-writer subagents under `.claude/agents/`; skills surface as `/truthmark-structure`, `/truthmark-document`, `/truthmark-sync`, `/truthmark-preview`, `/truthmark-realize`, and `/truthmark-check`, while the generated project subagents provide bounded evidence checks and parent-leased truth-doc writes. GitHub Copilot installs `.github/copilot-instructions.md`, prompt files under `.github/prompts/`, and verifier plus leased doc-writer custom agents under `.github/agents/`; prompts surface as `/truthmark-structure`, `/truthmark-document`, `/truthmark-sync`, `/truthmark-preview`, `/truthmark-realize`, and `/truthmark-check` in supported Copilot IDEs, while Copilot CLI can dispatch the generated `@truth-*` custom agents for bounded evidence checks or parent-leased doc shards. Gemini installs both `GEMINI.md` and project-scoped TOML commands under `.gemini/commands/truthmark/`, which surface as `/truthmark:structure`, `/truthmark:document`, `/truthmark:sync`, `/truthmark:preview`, `/truthmark:realize`, and `/truthmark:check` in Gemini CLI. Unknown platform names are config errors. Removing a platform stops future refreshes for that platform, but `init` does not delete previously generated files. `ensureRepoFile` is intentionally conservative: existing non-empty files are left alone. The AGENTS managed block is the exception because Truthmark owns that block and may refresh it to match current template behavior. -The generated Truth Structure, Truth Document, Truth Sync, Truth Realize, and Truth Check explicit surfaces are also managed by Truthmark and may be refreshed on rerun so the Codex skills, metadata, Claude Code project skills, GitHub Copilot prompt files, and OpenCode skills keep matching the installed workflow contract. Generated skills, Codex metadata, Copilot prompt files, and managed instruction blocks include the Truthmark package version that rendered them; `package.json` is the single maintained version source. After upgrading Truthmark, rerun `truthmark init` and review generated workflow diffs. +The generated Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, and Truth Check explicit surfaces are also managed by Truthmark and may be refreshed on rerun so the Codex skills, metadata, Claude Code project skills, GitHub Copilot prompt and custom-agent files, and OpenCode skills keep matching the installed workflow contract. Generated skill packages keep `SKILL.md` compact and write heavy procedure, report-template, and subagent or lease reference material into sibling `support/*.md` files. Generated skills, support files, Codex metadata, Copilot prompt files, Copilot custom-agent files, and managed instruction blocks include the Truthmark package version that rendered them; `package.json` is the single maintained version source. After upgrading Truthmark, rerun `truthmark init` and review generated workflow diffs. ## AGENTS Management Rules @@ -108,7 +132,7 @@ The current managed-instruction update behavior is: - normalize legacy unconditional docs-map and onboarding preamble lines to conditional reads so normal sessions do not load routing docs before they are needed - append the managed block when no block exists - keep the generated workflow block as a compact automatic-Sync trigger and boundary index so it does not consume unnecessary model context in long legacy instruction files -- keep detailed report examples, platform-specific invocation strings, and long workflow procedure in explicit generated skill files instead of host instruction blocks +- keep detailed report examples, platform-specific invocation strings, and long workflow procedure in explicit generated skill support files or standalone prompt and command files instead of host instruction blocks - preserve repository instruction authority while clarifying that implementation code and canonical truth docs are behavior evidence, not a way to override workflow write boundaries Repository-specific instructions should therefore live outside the managed block. @@ -140,10 +164,10 @@ Important current defaults: - default truth scaffolding creates an index at `/README.md`, an index at `//README.md`, six editable templates under `docs/templates/*.md`, and a bounded leaf truth doc at `//overview.md` routed through explicit `{ path, kind }` metadata - default platforms are `codex`, `opencode`, `claude-code`, `github-copilot`, and `gemini-cli` - shared instruction targets are refreshed independently of platform-specific surfaces -- explicit Truth Structure, Truth Document, Truth Sync, Truth Realize, and Truth Check surfaces are installed only for configured platforms +- explicit Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, and Truth Check surfaces are installed only for configured platforms - installed workflows are agent-native; generated skills tell agents to inspect the checkout directly -- generated workflow surfaces leave Truth Sync subagent selection to the acting agent and host environment -- managed instruction blocks include only compact hierarchy, decision-truth, automatic-Sync trigger, boundary reminders, and a pointer to explicit workflows; generated skills carry invocation strings and detailed workflow bodies +- Codex platform generation includes `.codex/agents/*.toml`, Claude Code platform generation includes `.claude/agents/*.md`, GitHub Copilot platform generation includes `.github/agents/*.agent.md`, and OpenCode platform generation includes `.opencode/agents/*.md` read-only verifier agents plus `truth-doc-writer` for parent-leased Truth Sync and Truth Document shards; the acting parent agent may use them automatically when the host supports subagent dispatch, and read-only verifier agents are context-bounded so they do not preload repo-wide instruction or policy docs unless assigned as evidence +- managed instruction blocks include only compact hierarchy, decision-truth, automatic-Sync trigger, boundary reminders, and a pointer to explicit workflows; generated skill entrypoints carry invocation strings and link to support files for detailed workflow bodies - generated workflow surfaces must not demote repository instruction docs such as [docs/ai/repo-rules.md](../ai/repo-rules.md) when warning agents that product truth cannot override workflow write boundaries - scaffolded default standards include AI-native topology repair guidance and an architecture-vs-behavior boundary so new repositories do not rely on human folder discipline - Truth Sync is the only generated skill with implicit invocation enabled because it is the automatic finish-time workflow @@ -155,7 +179,7 @@ Important current defaults: Current init JSON reporting uses: -- `truth-sync` for the managed `AGENTS.md` block and generated Truth Structure, Truth Document, Truth Sync, and Truth Check assets +- `truth-sync` for the managed `AGENTS.md` block and generated Truth Structure, Truth Document, Truth Sync, Truth Preview, and Truth Check assets - `realization` for generated Truth Realize assets - `authority` for [docs/truthmark/areas.md](../truthmark/areas.md) - `config` for the remaining scaffolded files @@ -173,7 +197,7 @@ Current init JSON reporting uses: - Hierarchical routing is the only scaffold model, and route ownership stays in Markdown route files rather than config. - Init reports migration risk instead of rewriting existing truth doc placement on the user's behalf. - V1 uses configured shared instruction targets such as `AGENTS.md` plus generated skill or command surfaces for host compatibility instead of creating host-specific top-level instruction files for every adapter. -- Managed instruction blocks are compact automatic-Sync indexes; generated skills and command files own explicit workflow procedure. +- Managed instruction blocks are compact automatic-Sync indexes; generated skill support files, prompt files, and command files own explicit workflow procedure. - Decision (2026-05-15): Repository instruction preambles make docs-map and onboarding reads conditional, and managed instruction blocks omit platform-specific workflow invocation strings so ordinary sessions load less context. - Decision (2026-05-13): `.truthmark/config.yml` and route files are the committed hierarchy contract, so init no longer creates a low-value top-level note. - Decision (2026-05-14): Truth-doc templates are kind-specific under `docs/templates/*.md`; `docs/templates/behavior-doc.md` is the default bounded behavior template and the other five typed templates carry kind-specific required sections. @@ -193,5 +217,5 @@ Keeping typed truth-doc templates in `docs/templates/` gives repository owners o - `src/init/init.ts` - `src/templates/init-files.ts` - `src/templates/agents-block.ts` -- `src/templates/codex-skills.ts` +- `src/templates/workflow-surfaces.ts` - `src/fs/paths.ts` diff --git a/docs/truth/workflows/overview.md b/docs/truth/workflows/overview.md index bd42ad8..53b5fa7 100644 --- a/docs/truth/workflows/overview.md +++ b/docs/truth/workflows/overview.md @@ -2,12 +2,12 @@ status: active doc_type: behavior truth_kind: workflow -last_reviewed: 2026-05-15 +last_reviewed: 2026-05-16 source_of_truth: - ../../../.truthmark/config.yml - ../../../src/agents/instructions.ts - ../../../src/agents/workflow-manifest.ts - - ../../../src/templates/codex-skills.ts + - ../../../src/templates/workflow-surfaces.ts - ../../../src/templates/generated-surfaces.ts --- @@ -26,6 +26,7 @@ This document owns the shared installed-workflow runtime model and generated hos - `truthmark init` refreshes managed instruction blocks and explicit workflow surfaces after configuration or renderer changes. - Explicit host invocations run manual workflows. - Truth Sync is the only automatic finish-time workflow trigger. +- Truth Preview is an explicit read-only selector for likely workflow routing before edits; it is intended, not authorized. ## Inputs @@ -43,38 +44,46 @@ Agents inspect the checkout directly, apply workflow boundaries from committed s The default platform list includes every supported platform. Teams should remove unused platforms from `.truthmark/config.yml` before rerunning `truthmark init`. -| Platform | Generated surface | Invocation shape | -| --- | --- | --- | -| `codex` | `.codex/skills/truthmark-*/SKILL.md` plus Codex metadata | `/truthmark-*` or `$truthmark-*` | -| `opencode` | `.opencode/skills/truthmark-*/SKILL.md` | `/skill truthmark-*` | -| `claude-code` | `.claude/skills/truthmark-*/SKILL.md` | `/truthmark-*` | -| `github-copilot` | `.github/prompts/truthmark-*.prompt.md` | `/truthmark-*` in supported Copilot IDEs | -| `gemini-cli` | `.gemini/commands/truthmark/*.toml` | `/truthmark:*` | +| Platform | Generated surface | Invocation shape | +| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| `codex` | `.codex/skills/truthmark-*/SKILL.md`, `.codex/skills/truthmark-*/support/*.md`, Codex metadata, and `.codex/agents/*.toml` verifier and leased doc-writer agents | `/truthmark-*` or `$truthmark-*` | +| `opencode` | `.opencode/skills/truthmark-*/SKILL.md`, `.opencode/skills/truthmark-*/support/*.md`, and `.opencode/agents/*.md` verifier and leased doc-writer subagents | `/skill truthmark-*` | +| `claude-code` | `.claude/skills/truthmark-*/SKILL.md`, `.claude/skills/truthmark-*/support/*.md`, and `.claude/agents/*.md` verifier and leased doc-writer subagents | `/truthmark-*`; named subagents such as `truth-route-auditor` | +| `github-copilot` | `.github/prompts/truthmark-*.prompt.md` and `.github/agents/*.agent.md` verifier and leased doc-writer agents | `/truthmark-*` in supported Copilot IDEs; `@truth-*` custom agents in Copilot CLI | +| `gemini-cli` | `.gemini/commands/truthmark/*.toml` | `/truthmark:*` | -Generated skill files, Gemini command files, Codex metadata, and managed instruction blocks include the package version from `package.json`. After upgrading Truthmark, rerun `truthmark init` and review generated workflow diffs. +Generated skill files, Gemini command files, Codex metadata, Codex custom-agent files, Claude Code subagent files, GitHub Copilot custom-agent files, OpenCode subagent files, and managed instruction blocks include the package version from `package.json`. After upgrading Truthmark, rerun `truthmark init` and review generated workflow diffs. -Generated workflow descriptions are routing triggers. They use short positive trigger language plus adjacent-workflow exclusions, and they leave detailed procedure, write boundaries, and report shape to the workflow body. +Codex, Claude Code, GitHub Copilot, and OpenCode platform generation include project-scoped read-only verifier agents for workflow-owned subagent dispatch plus a write-capable `truth-doc-writer` for parent-leased Truth Sync and Truth Document shards. Codex exposes `truth_route_auditor`, `truth_claim_verifier`, `truth_doc_reviewer`, and `truth_doc_writer`. Claude Code exposes `truth-route-auditor`, `truth-claim-verifier`, `truth-doc-reviewer`, and `truth-doc-writer` project subagents. GitHub Copilot and OpenCode expose `@truth-route-auditor`, `@truth-claim-verifier`, `@truth-doc-reviewer`, and `@truth-doc-writer`. The parent workflow may use them automatically when the host supports subagents and bounded fan-out is useful; read-only verifier agents keep context bounded by avoiding host instruction files and repo-wide policy docs unless assigned as evidence, write workers require explicit leases, and the parent workflow owns final reports, repo-policy interpretation, diff validation, and acceptance. +Read-only verifier agents include an explicit context boundary: they inspect only the parent-assigned shard plus required checkout evidence files and do not preload repo-wide instruction or policy docs unless the parent assigns those files as evidence. + +Generated workflow descriptions are routing triggers. They use short positive trigger language plus adjacent-workflow exclusions. Skill-package hosts keep `SKILL.md` as the compact routing and quick-procedure entrypoint, then put detailed procedure, report templates, and subagent or lease instructions in generated `support/*.md` files. Standalone prompt and command hosts keep the full workflow body inline because they do not load skill-package support files. The typed workflow manifest owns generated description text, Codex-facing short descriptions and default prompts, implicit-invocation policy, positive and negative routing examples, forbidden-adjacent cases, required gates, write boundaries, and report-section expectations. Generated host surfaces and deterministic routing tests should consume that manifest rather than duplicating workflow metadata in renderer code. Truthmark-owned workflow surfaces are generated under host-specific directories. Repo-root `skills/` files are not generated V1 workflow surfaces. -Managed instruction blocks are compact automatic-Sync trigger and boundary indexes. They intentionally omit platform-specific invocation strings, non-automatic workflow procedures, report examples, and long checklists. Detailed invocations and procedures live in generated skills, prompts, and command files. +Managed instruction blocks are compact automatic-Sync trigger and boundary indexes. They intentionally omit platform-specific invocation strings, non-automatic workflow procedures, report examples, and long checklists. Detailed invocations and procedures live in generated skills, skill support files, prompts, and command files. ## Product Decisions - Decision (2026-05-15): Installed skills, prompts, commands, and managed instruction blocks are the workflow runtime. The CLI installs and validates those surfaces but does not orchestrate Truth Sync or require helper payloads before agents can act. - Decision (2026-05-15): Managed instruction blocks stay compact enough for ordinary agent context. Non-automatic workflow procedure belongs in generated skills, prompts, and command files. - Decision (2026-05-15): Managed instruction blocks omit platform-specific invocation strings; host-specific generated workflow files remain the canonical place for invocation detail. -- Decision (2026-05-15): Truthmark follows current host discovery paths for generated workflow files: Codex uses `.codex/skills/`, Claude Code uses `.claude/skills/`, GitHub Copilot uses `.github/prompts/`, OpenCode uses `.opencode/skills/`, Gemini CLI uses `.gemini/commands/`, and repo-root `skills/` is not a generated V1 target. +- Decision (2026-05-15): Truthmark follows current host discovery paths for generated workflow files: Codex uses `.codex/skills/`, Claude Code uses `.claude/skills/` and `.claude/agents/`, GitHub Copilot uses `.github/prompts/` and `.github/agents/`, OpenCode uses `.opencode/skills/`, Gemini CLI uses `.gemini/commands/`, and repo-root `skills/` is not a generated V1 target. - Decision (2026-05-15): Workflow descriptions are routing triggers rather than workflow summaries; adjacent-workflow exclusions belong in metadata when they prevent wrong workflow loading. - Decision (2026-05-15): Workflow metadata and routing-eval expectations live in a typed manifest so generated descriptions, host metadata, and deterministic routing tests share one structural source. +- Decision (2026-05-16): Codex, Claude Code, GitHub Copilot, and OpenCode may install project-scoped read-only verifier agents plus a leased `truth-doc-writer`; parent workflows keep acceptance and diff validation ownership and do not require users to request subagents per task. +- Decision (2026-05-16): Read-only verifier agents do not preload host instruction files or repo-wide policy docs by default; parent workflows keep that policy context and pass only bounded evidence shards to verifier agents. +- Decision (2026-05-16): Coding and document-writing speed is not a priority over workflow simplicity and agent stability. Truthmark must not make document writing faster by adding project complexity, weaker leases, broader write authority, or less stable agent behavior. +- Decision (2026-05-16): Truth Preview is generated as an explicit read-only workflow surface, not an automatic gate, validator, or Truth Check replacement. +- Decision (2026-05-16): Generated skill packages use progressive disclosure: `SKILL.md` stays compact for routing and first-step execution, while heavy procedure detail, report examples, and subagent or lease reference material move to generated support files beside the skill. ## Rationale Keeping workflow execution agent-native makes installed repositories usable even when the Truthmark package is unavailable at execution time. Agents can read committed surfaces, inspect the checkout, and act without depending on a daemon, database, or mandatory generated payload. -Compact managed instruction blocks protect ordinary model context while explicit workflow surfaces remain available when the agent needs a full procedure. +Compact managed instruction blocks and compact skill entrypoints protect ordinary model context while explicit support files, prompt files, and command files remain available when the agent needs a full procedure. ## Non-Goals diff --git a/docs/truth/workflows/shared-gates.md b/docs/truth/workflows/shared-gates.md index 0632d6f..0e55460 100644 --- a/docs/truth/workflows/shared-gates.md +++ b/docs/truth/workflows/shared-gates.md @@ -21,7 +21,7 @@ This document owns shared ownership, evidence, shape-repair, architecture-bounda ## Triggers -The gates apply whenever Truth Structure, Truth Document, Truth Sync, Truth Realize, or Truth Check reads, writes, audits, or relies on canonical truth docs. +The gates apply whenever Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize, or Truth Check reads, writes, audits, or relies on canonical truth docs. ## Inputs diff --git a/docs/truth/workflows/truth-check.md b/docs/truth/workflows/truth-check.md index ad3305e..46e1298 100644 --- a/docs/truth/workflows/truth-check.md +++ b/docs/truth/workflows/truth-check.md @@ -2,11 +2,12 @@ status: active doc_type: behavior truth_kind: workflow -last_reviewed: 2026-05-15 +last_reviewed: 2026-05-16 source_of_truth: - ../../../src/agents/truth-check.ts - ../../../src/checks/** - ../../../src/agents/shared.ts + - ../../../src/templates/workflow-surfaces.ts --- # Truth Check Workflow @@ -33,7 +34,7 @@ Truth Check owns agent-led truth-health review. It reports issues and suggested ## Execution Model -Truth Check inspects the checkout directly and may optionally run `truthmark check` when local tooling is available. Installed workflows must not depend on the binary being present. +Truth Check inspects the checkout directly and may optionally run `truthmark check` when local tooling is available. Installed workflows must not depend on the binary being present. In Codex, Claude Code, GitHub Copilot, or OpenCode, Truth Check may automatically use generated read-only verifier subagents when the host supports subagent dispatch and the parent agent chooses bounded fan-out. ## Current Behavior @@ -43,12 +44,15 @@ Truth Check supports each finding and suggested fix with evidence from config, r If follow-up docs edits are needed for mixed-owner docs, Truth Check runs or recommends Truth Structure before editing. +When subagent mode is available, the parent agent may dispatch read-only route, claim, and doc-shape verifier workers across bounded shards. Codex exposes `truth_route_auditor`, `truth_claim_verifier`, and `truth_doc_reviewer`; Claude Code exposes `truth-route-auditor`, `truth-claim-verifier`, and `truth-doc-reviewer` project subagents; GitHub Copilot and OpenCode expose `@truth-route-auditor`, `@truth-claim-verifier`, and `@truth-doc-reviewer`. Workers return structured findings only and must not edit files. They inspect only the parent-assigned shard plus required checkout evidence files and do not preload repo-wide instruction or policy docs unless the parent assigns those files as evidence. The parent agent deduplicates findings, spot-checks evidence, optionally runs validation, and owns repo-policy interpretation and the final Truth Check report. + Completed reports include `Files reviewed`, `Issues found`, `Fixes suggested`, `Evidence checked`, and `Validation`. ## Product Decisions - Decision (2026-05-15): Truth Check is an audit workflow, not a substitute for lint, tests, typecheck, code review, or Truth Sync. - Decision (2026-05-15): Truth Check reports mixed-owner truth docs as topology issues and does not silently repair them outside the proper workflow. +- Decision (2026-05-16): Codex, Claude Code, GitHub Copilot, and OpenCode subagent mode is read-only, automatic when host-supported, parent-owned, and context-bounded; verifier agents may gather evidence but never write docs, preload repo-wide policy unless assigned, or replace the final audit report. ## Rationale diff --git a/docs/truth/workflows/truth-document.md b/docs/truth/workflows/truth-document.md index fb8c1f2..c698ea2 100644 --- a/docs/truth/workflows/truth-document.md +++ b/docs/truth/workflows/truth-document.md @@ -2,10 +2,12 @@ status: active doc_type: behavior truth_kind: workflow -last_reviewed: 2026-05-15 +last_reviewed: 2026-05-16 source_of_truth: - ../../../src/agents/truth-document.ts + - ../../../src/agents/write-lease.ts - ../../../src/agents/shared.ts + - ../../../src/templates/workflow-surfaces.ts --- # Truth Document Workflow @@ -32,7 +34,7 @@ Truth Document owns manual missing-truth generation for implemented behavior. It ## Execution Model -Truth Document is implementation-first and never writes functional code. It documents current implemented behavior only and does not invent future behavior or planned endpoints. +Truth Document is implementation-first and never writes functional code. It documents current implemented behavior only and does not invent future behavior or planned endpoints. In Codex, Claude Code, GitHub Copilot, or OpenCode, Truth Document may automatically use generated read-only verifier subagents and explicit-lease `truth-doc-writer` subagents when the host supports subagent dispatch and the parent agent chooses bounded fan-out. ## Current Behavior @@ -46,13 +48,17 @@ When Truth Document restructures a bounded truth doc or runs Structure first, it ContextPack may be used to gather bounded source context when available. It does not replace checkout inspection, does not create write permission, and cannot be cited as evidence unless it points to real checkout files, tests, route files, truth docs, schemas, or explicit evidence blocks. If ContextPack is unavailable, Truth Document proceeds manually and reports that repository-intelligence artifacts were not generated. +When subagent mode is available, the parent agent may dispatch read-only route and claim verifier workers to gather route and evidence findings. Codex exposes `truth_route_auditor` and `truth_claim_verifier`; Claude Code exposes `truth-route-auditor` and `truth-claim-verifier` project subagents; GitHub Copilot and OpenCode expose `@truth-route-auditor` and `@truth-claim-verifier`. Read-only verifier workers inspect only the parent-assigned shard plus required checkout evidence files and do not preload repo-wide instruction or policy docs unless the parent assigns those files as evidence. The same hosts expose `truth_doc_writer` or `@truth-doc-writer` for leased truth-doc shards. The parent agent creates each lease, requires allowedWrites and forbiddenWrites, validates the actual checkout diff against the lease, and owns repo-policy interpretation, final acceptance, routing decisions, shape repair scope, and the final report. + Completed reports include `Implementation reviewed`, `Ownership reviewed`, `Structure required` when applicable, `Truth docs created`, `Truth docs updated`, `Truth docs restructured`, `Routing updated`, `Evidence checked`, and `Notes`. +When write workers are used, each worker report must include `status`, `worker`, `workflow`, `shard`, `filesChanged`, `claimsChecked`, `evidenceChecked`, `offLeaseChanges`, `blockers`, and `notes`. The parent accepts a completed worker report only after validating the parsed report against the lease identity, required report fields, actual worker diff, `allowedWrites`, `forbiddenWrites`, reported `filesChanged`, reported `offLeaseChanges`, and reported `blockers`. Blocked worker reports remain blocked outcomes and must include blockers; off-lease or forbidden actual diffs are rejected rather than trusted from self-report. ## Product Decisions - Decision (2026-05-15): Truth Document exists because documenting existing implemented behavior without code changes is not a Truth Sync run. - Decision (2026-05-15): Truth Document must switch to Truth Structure rather than patching mixed-owner truth docs. - Decision (2026-05-15): Truth Document must not lose Product Decisions or Rationale during bounded shape repair or Structure handoff. +- Decision (2026-05-16): Codex, Claude Code, GitHub Copilot, and OpenCode subagents may gather bounded read-only evidence for Document without preloading repo-wide policy by default. Document may also dispatch `truth-doc-writer` only with an explicit write lease, while parent agents retain policy, acceptance, and diff-validation ownership. ## Rationale diff --git a/docs/truth/workflows/truth-preview.md b/docs/truth/workflows/truth-preview.md new file mode 100644 index 0000000..8c344aa --- /dev/null +++ b/docs/truth/workflows/truth-preview.md @@ -0,0 +1,62 @@ +--- +status: active +doc_type: behavior +truth_kind: workflow +last_reviewed: 2026-05-16 +source_of_truth: + - ../../../src/agents/truth-preview.ts + - ../../../src/agents/workflow-manifest.ts + - ../../../src/templates/workflow-surfaces.ts + - ../../../src/templates/generated-surfaces.ts +--- + +# Truth Preview + +## Scope + +Truth Preview previews likely Truthmark routing before edits. + +It is an explicit read-only planning surface. It is intended, not authorized, and hands off to the selected workflow after user approval. + +## Triggers + +- explicit user invocation through the installed host surface +- questions about likely workflow routing, route ownership, target files, write classes, or subagent use before edits + +## Execution Model + +Truth Preview reads only the context needed to preview ownership: + +- `.truthmark/config.yml` +- root and child route files +- relevant canonical docs +- relevant implementation files + +Truth Preview reports the likely Truthmark workflow, why that workflow was selected, likely route owner, expected write classes, expected target files, suggested subagent use, blocking ambiguity, and handoff. + +Truth Preview may suggest the read-only route auditor when bounded verifier input would reduce context or clarify route ownership. It does not use write workers and does not issue write leases. + +Truth Preview must not edit files, create truth docs, update routing, run Truth Sync automatically, replace Truth Check, claim final correctness, issue write leases, or mutate code. + +Completed reports include `Requested outcome`, `Likely workflow`, `Why this workflow`, `Likely route owner`, `Expected write classes`, `Expected target files`, `Suggested subagent use`, `Blocking ambiguity`, and `Handoff`. + +## Product Decisions + +- Decision (2026-05-16): Truth Preview is a first-class explicit workflow because routing transparency before mutation can prevent agents from loading or acting through the wrong heavier workflow. +- Decision (2026-05-16): Truth Preview is not automatic. Its value is a cheap selector for ambiguous routing or write-boundary questions, not a required gate before normal edits. +- Decision (2026-05-16): Truth Preview reports intended next steps only; it does not authorize writes or validate final correctness. + +## Rationale + +Preview improves agent performance only when it prevents unnecessary workflow loading, broad context gathering, or wrong-owner edits. Making it automatic would add ceremony and context to straightforward tasks. + +## Non-Goals + +- no automatic invocation +- no validation gate +- no Truth Check replacement +- no file mutation + +## Maintenance Notes + +Update this doc when Preview triggers, read boundaries, report shape, generated surfaces, or handoff behavior change. diff --git a/docs/truth/workflows/truth-realize.md b/docs/truth/workflows/truth-realize.md index bf710c5..0c10cce 100644 --- a/docs/truth/workflows/truth-realize.md +++ b/docs/truth/workflows/truth-realize.md @@ -2,10 +2,10 @@ status: active doc_type: behavior truth_kind: workflow -last_reviewed: 2026-05-15 +last_reviewed: 2026-05-16 source_of_truth: - ../../../src/agents/prompts.ts - - ../../../src/templates/codex-skills.ts + - ../../../src/templates/workflow-surfaces.ts - ../../../src/realize/report.ts --- diff --git a/docs/truth/workflows/truth-structure.md b/docs/truth/workflows/truth-structure.md index 6da14ea..b1de4f5 100644 --- a/docs/truth/workflows/truth-structure.md +++ b/docs/truth/workflows/truth-structure.md @@ -2,10 +2,11 @@ status: active doc_type: behavior truth_kind: workflow -last_reviewed: 2026-05-15 +last_reviewed: 2026-05-16 source_of_truth: - ../../../src/agents/truth-structure.ts - ../../../src/agents/shared.ts + - ../../../src/templates/workflow-surfaces.ts - ../../../src/routing/** --- @@ -18,6 +19,7 @@ Truth Structure designs or repairs repository truth topology. ## Scope Truth Structure owns area routing, child route-file structure, ownership splits, and starter truth-doc placement when topology is missing, stale, broad, overloaded, catch-all, unrouteable, or explicitly requested. +Truth Structure also owns new area setup when a user asks to onboard a new code area into Truthmark, a new package/controller/domain lacks bounded truth ownership, or a new product area needs routing and starter truth docs. ## Triggers @@ -36,6 +38,7 @@ Truth Structure owns area routing, child route-file structure, ownership splits, ## Execution Model Truth Structure inspects the checkout directly and defines areas by product or behavior ownership, not mechanical directory mirroring. +For new area setup, Truth Structure inspects the named code area, infers bounded product or behavior ownership, chooses the owning route when ownership is clear, and otherwise proposes the route and blocks for review. It creates or updates the child route entry or file, creates starter truth docs only where current truth is missing, and reports the initial truth boundary. ## Current Behavior @@ -45,17 +48,22 @@ Topology pressure includes broad code mappings, overloaded child route files, mu Truth Structure splits broad, overloaded, catch-all, or mixed-owner areas into behavior-owned route files and bounded leaf truth docs when safe. It updates routing so future Truth Sync can target small docs. If a split is unsafe or ambiguous, it blocks with manual-review files. +In Codex, Claude Code, GitHub Copilot, and OpenCode, Truth Structure surfaces may reference the generated read-only route auditor when the parent agent chooses bounded validation fan-out. Codex exposes `truth_route_auditor`; Claude Code exposes the `truth-route-auditor` project subagent; GitHub Copilot and OpenCode expose the generated `@truth-route-auditor` custom agent. The route auditor gathers topology and ownership findings only, inspects only the parent-assigned shard plus required checkout evidence files, and does not preload repo-wide instruction or policy docs unless the parent assigns those files as evidence. The parent workflow owns repo-policy interpretation, all route edits, starter truth-doc writes, topology decisions, and the final report. + Before splitting or restructuring truth docs, Truth Structure inventories Product Decisions and Rationale in every source doc. It moves each current entry into the bounded owner doc it governs, removes or narrows entries only with checkout evidence, and blocks with manual-review files when ownership is unclear. Starter truth docs use closed YAML frontmatter with `status`, `doc_type`, `last_reviewed`, and `source_of_truth`, and include `Product Decisions` and `Rationale` sections. +New area setup must not edit functional code, perform full behavior documentation unless evidence is inspected and the task explicitly asks for it, patch broad or mixed-owner docs in place, create generic catch-all docs, or treat README files as Sync targets. -Completed reports include `Topology reviewed`, `Areas reviewed`, `Routing updated`, `Truth docs created`, `Truth docs split`, `Truth docs restructured`, `Evidence checked`, `Topology decisions`, and `Notes`. +Completed reports include `Topology reviewed`, `Areas reviewed`, `Routing updated`, `Initial truth boundary`, `Truth docs created`, `Truth docs split`, `Truth docs restructured`, `Evidence checked`, `Topology decisions`, and `Notes`. ## Product Decisions - Decision (2026-05-15): Truth Structure owns ownership repair. Mixed-owner docs must be split/rerouted when safe, not repaired in place by Sync or Document. - Decision (2026-05-15): Truth Structure must satisfy canonical decision-section expectations for new starter docs and repaired routed docs. - Decision (2026-05-15): Truth Structure must preserve or explicitly account for Product Decisions and Rationale when splitting or restructuring truth docs. +- Decision (2026-05-16): Codex, Claude Code, GitHub Copilot, and OpenCode Truth Structure may use the generated read-only route auditor for bounded validation input without preloading repo-wide policy by default, while parent agents retain policy and topology write ownership. +- Decision (2026-05-16): New area setup is a Truth Structure scenario, not a separate workflow surface. It may add routing and starter truth docs, but detailed behavior documentation remains bounded by evidence and explicit task scope. ## Rationale @@ -65,7 +73,8 @@ Ownership repair needs a workflow that can change route topology and create boun - no mechanical directory mirroring when behavior ownership is clearer - no generic truth docs behind broad catch-all routing +- no full behavior documentation during new area setup unless evidence is inspected and the task explicitly asks for it ## Maintenance Notes -Update this doc when topology pressure signals, split behavior, starter-doc requirements, or Structure report shape changes. +Update this doc when topology pressure signals, split behavior, starter-doc requirements, Structure subagent behavior, or Structure report shape changes. diff --git a/docs/truth/workflows/truth-sync.md b/docs/truth/workflows/truth-sync.md index 9f1fab7..7232f3c 100644 --- a/docs/truth/workflows/truth-sync.md +++ b/docs/truth/workflows/truth-sync.md @@ -2,11 +2,13 @@ status: active doc_type: behavior truth_kind: workflow -last_reviewed: 2026-05-15 +last_reviewed: 2026-05-16 source_of_truth: - ../../../src/agents/truth-sync.ts + - ../../../src/agents/write-lease.ts - ../../../src/sync/report.ts - ../../../src/agents/shared.ts + - ../../../src/templates/workflow-surfaces.ts --- # Truth Sync Workflow @@ -33,7 +35,7 @@ Truth Sync is code-first. Code leads, truth docs follow, and functional code mus ## Execution Model -Truth Sync may update routed truth docs and routing when routing repair is needed. It may create missing canonical truth docs when routeable implementation would otherwise remain undocumented. +Truth Sync may update routed truth docs and routing when routing repair is needed. It may create missing canonical truth docs when routeable implementation would otherwise remain undocumented. In Codex, Claude Code, GitHub Copilot, or OpenCode, Truth Sync may automatically use generated read-only verifier subagents and explicit-lease `truth-doc-writer` subagents when the host supports subagent dispatch and the parent agent chooses bounded fan-out. ## Current Behavior @@ -50,6 +52,7 @@ Truth Sync updates architecture docs in the same sync when changed code alters a ContextPack may be used to accelerate Truth Sync when available. It does not replace checkout inspection, does not create write permission, and cannot be cited as evidence unless it points to real checkout files, tests, route files, truth docs, schemas, or explicit evidence blocks. If ContextPack or ImpactSet is unavailable, Truth Sync proceeds manually and reports that repository-intelligence artifacts were not generated. Completed reports include `Changed code reviewed`, `Ownership reviewed`, `Structure required` when applicable, `Truth docs updated`, `Truth docs split` when Structure is run inline, `Evidence checked`, and `Notes`. Skipped reports include `Reason`. Blocked reports include `Reason`, `Files requiring manual review`, and `Next action`. +When write workers are used, each worker report must include `status`, `worker`, `workflow`, `shard`, `filesChanged`, `claimsChecked`, `evidenceChecked`, `offLeaseChanges`, `blockers`, and `notes`. The parent accepts a completed worker report only after validating the parsed report against the lease identity, required report fields, actual worker diff, `allowedWrites`, `forbiddenWrites`, reported `filesChanged`, reported `offLeaseChanges`, and reported `blockers`. Blocked worker reports remain blocked outcomes and must include blockers; off-lease or forbidden actual diffs are rejected rather than trusted from self-report. Current skip reasons are: @@ -61,7 +64,7 @@ Current skip reasons are: Truth Sync's generated frontmatter description and Codex metadata carry those skip cases because skill metadata is the host-visible routing boundary before the full workflow body is loaded. -Truth Sync delegation is host-owned. Generated workflow surfaces may describe when delegation is allowed, but must not name a preferred subagent or project-local subagent preference file. +Truth Sync delegation is host-owned. Generated workflow surfaces may describe when delegation is allowed, but must not create unrestricted writable helpers or a project-local subagent preference file. Codex, Claude Code, GitHub Copilot, and OpenCode generated surfaces may name project-scoped read-only verifier agents for workflow-owned automatic verification and `truth-doc-writer` for leased truth-doc shards. Read-only verifier agents inspect only the parent-assigned shard plus required checkout evidence files and do not preload repo-wide instruction or policy docs unless the parent assigns those files as evidence. The parent workflow creates each lease, requires allowedWrites and forbiddenWrites, validates the actual checkout diff against the lease, and owns repo-policy interpretation and final acceptance. ## Product Decisions @@ -69,16 +72,18 @@ Truth Sync delegation is host-owned. Generated workflow surfaces may describe wh - Decision (2026-05-15): Truth Sync must not worsen weak topology by adding generic truth docs behind missing, stale, broad, overloaded, catch-all, or unrouteable routing. - Decision (2026-05-15): Truth Sync must switch to Truth Structure or block when impacted truth docs are mixed-owner or broad. - Decision (2026-05-15): Truth Sync must not lose Product Decisions or Rationale during bounded shape repair or inline Structure handoff. +- Decision (2026-05-16): Codex, Claude Code, GitHub Copilot, and OpenCode subagents may automatically gather bounded read-only route and claim evidence for Sync when host-supported without preloading repo-wide policy by default. Sync may also dispatch `truth-doc-writer` only with an explicit write lease, while parent agents retain policy, acceptance, and diff-validation ownership. +- Decision (2026-05-16): Truth Sync write authority is bounded by file class and route ownership, not by the root route index alone. It may write canonical truth docs and truth routing files, while functional code remains outside Sync authority. ## Rationale -Truth Sync is the finish-time bridge from code to truth, so it must protect route ownership before claim evidence. Otherwise it can accurately document behavior in the wrong place. +Truth Sync is the finish-time bridge from code to truth, so it must protect route ownership before claim evidence. Otherwise it can accurately document behavior in the wrong place. Routing repair can require child route-file edits as well as root index edits, so Sync's safe boundary is leased truth routing files rather than one hard-coded route file. ## Non-Goals - no functional-code rewrites during sync - no generic docs behind weak routing -- no preferred subagent baked into generated surfaces +- no unleased writable subagent ownership baked into generated surfaces ## Maintenance Notes diff --git a/docs/truthmark/areas.md b/docs/truthmark/areas.md index a9ca80b..b4259a9 100644 --- a/docs/truthmark/areas.md +++ b/docs/truthmark/areas.md @@ -1,7 +1,7 @@ --- status: active doc_type: routing -last_reviewed: 2026-05-14 +last_reviewed: 2026-05-16 source_of_truth: - ../README.md - ../ai/repo-rules.md @@ -75,7 +75,7 @@ Code surface: - src/realize/** - src/sync/** - src/templates/agents-block.ts -- src/templates/codex-skills.ts +- src/templates/workflow-surfaces.ts - src/templates/generated-surfaces.ts - src/truth/** - src/version.ts diff --git a/docs/truthmark/areas/installed-workflows.md b/docs/truthmark/areas/installed-workflows.md index d07a8b8..86943c9 100644 --- a/docs/truthmark/areas/installed-workflows.md +++ b/docs/truthmark/areas/installed-workflows.md @@ -1,7 +1,7 @@ --- status: active doc_type: routing -last_reviewed: 2026-05-15 +last_reviewed: 2026-05-16 source_of_truth: - ../areas.md - ../../README.md @@ -13,6 +13,7 @@ source_of_truth: ## Installed Workflows Truth documents: + ```yaml truth_documents: - path: docs/truth/contracts.md @@ -27,6 +28,8 @@ truth_documents: kind: workflow - path: docs/truth/workflows/truth-sync.md kind: workflow + - path: docs/truth/workflows/truth-preview.md + kind: workflow - path: docs/truth/workflows/truth-realize.md kind: workflow - path: docs/truth/workflows/truth-check.md @@ -36,17 +39,19 @@ truth_documents: ``` Code surface: -- src/agents/** -- src/generation/** -- src/realize/** -- src/sync/** + +- src/agents/\*\* +- src/generation/\*\* +- src/realize/\*\* +- src/sync/\*\* - src/templates/agents-block.ts -- src/templates/codex-skills.ts +- src/templates/workflow-surfaces.ts - src/templates/generated-surfaces.ts -- src/truth/** +- src/truth/\*\* - src/version.ts Update truth when: + - installed workflow boundaries or report shapes change - generated instruction block or skill content changes - workflow version markers or sync classification behavior changes diff --git a/package-lock.json b/package-lock.json index aea40fa..f6c5027 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "truthmark", - "version": "1.3.0", + "version": "1.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "truthmark", - "version": "1.3.0", + "version": "1.4.0", "license": "MIT", "dependencies": { "ajv": "^8.17.1", diff --git a/package.json b/package.json index 6484c6b..41103db 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "truthmark", - "version": "1.3.0", + "version": "1.4.0", "description": "Git-native, branch-scoped truth workflow installer for local AI coding agents.", "license": "MIT", "type": "module", diff --git a/docs/ai/agent-skills-workflow-review.md b/research/2026-05-15-agent-skills-workflow-review.md similarity index 77% rename from docs/ai/agent-skills-workflow-review.md rename to research/2026-05-15-agent-skills-workflow-review.md index 70183f6..1fb490e 100644 --- a/docs/ai/agent-skills-workflow-review.md +++ b/research/2026-05-15-agent-skills-workflow-review.md @@ -1,33 +1,39 @@ ---- -status: active -doc_type: agent-guide -last_reviewed: 2026-05-15 -source_of_truth: - - repo-rules.md - - ../truth/workflows/overview.md - - ../truth/workflows/shared-gates.md - - ../../src/agents/workflow-manifest.ts - - ../../.codex/skills/truthmark-sync/SKILL.md - - ../../.codex/skills/truthmark-structure/SKILL.md - - ../../.codex/skills/truthmark-document/SKILL.md - - ../../.codex/skills/truthmark-realize/SKILL.md - - ../../.codex/skills/truthmark-check/SKILL.md - - https://developers.openai.com/codex/skills - - https://developers.openai.com/blog/eval-skills - - https://developers.openai.com/blog/skills-shell-tips - - https://developers.openai.com/blog/skills-agents-sdk - - https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills - - https://resources.anthropic.com/hubfs/The-Complete-Guide-to-Building-Skill-for-Claude.pdf - - https://code.claude.com/docs/en/slash-commands - - https://agentskills.io/specification - - https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity ---- +# Agent Skills Workflow Review -This note summarizes external skill-authoring guidance reviewed on 2026-05-15 and applies it to Truthmark's installed project workflows. It is a reference for future workflow-surface changes, not a replacement for [workflow overview](../truth/workflows/overview.md) and the bounded workflow truth docs under `docs/truth/workflows/`. +Status: research reference +Date: 2026-05-15 +Audience: Truthmark maintainers + +This is a non-canonical research reference. It summarizes external skill-authoring guidance reviewed on 2026-05-15 and applies it to Truthmark's installed project workflows. It must not be treated as current Truthmark behavior unless the behavior-bearing parts are promoted into [workflow overview](../docs/truth/workflows/overview.md), the bounded workflow truth docs under `docs/truth/workflows/`, the workflow manifest, renderers, and tests. + +Checkout references: + +- [docs/ai/repo-rules.md](../docs/ai/repo-rules.md) +- [docs/truth/workflows/overview.md](../docs/truth/workflows/overview.md) +- [docs/truth/workflows/shared-gates.md](../docs/truth/workflows/shared-gates.md) +- [src/agents/workflow-manifest.ts](../src/agents/workflow-manifest.ts) +- [src/templates/workflow-surfaces.ts](../src/templates/workflow-surfaces.ts) +- [.codex/skills/truthmark-sync/SKILL.md](../.codex/skills/truthmark-sync/SKILL.md) +- [.codex/skills/truthmark-structure/SKILL.md](../.codex/skills/truthmark-structure/SKILL.md) +- [.codex/skills/truthmark-document/SKILL.md](../.codex/skills/truthmark-document/SKILL.md) +- [.codex/skills/truthmark-realize/SKILL.md](../.codex/skills/truthmark-realize/SKILL.md) +- [.codex/skills/truthmark-check/SKILL.md](../.codex/skills/truthmark-check/SKILL.md) + +External sources reviewed: + +- +- +- +- +- +- +- +- +- ## External Links Reviewed -All external links in `source_of_truth` resolved on 2026-05-15. The previous Anthropic Claude Code slash-command URL redirects to `https://code.claude.com/docs/en/slash-commands`; use the canonical redirected URL in this doc. +All external links above resolved on 2026-05-15. The previous Anthropic Claude Code slash-command URL redirects to `https://code.claude.com/docs/en/slash-commands`; use the canonical redirected URL in this doc. The Perplexity review adds a stricter standard than this doc previously stated: description metadata is routing logic, not a compact summary of the workflow. Expected outputs and success criteria belong in the body, report contract, or eval rubric. @@ -73,7 +79,7 @@ Truthmark currently installs five workflows across host-specific surfaces: | `truthmark-realize` | Realize truth docs into functional code | `allow_implicit_invocation: false` | | `truthmark-check` | Audit repository truth health | `allow_implicit_invocation: false` | -Generated runtime surfaces include `.codex/skills/`, `.claude/skills/`, `.opencode/skills/`, `.github/prompts/`, `.gemini/commands/truthmark/`, and compact managed instruction blocks in files such as `AGENTS.md`. +Generated runtime surfaces include `.codex/skills/`, `.codex/agents/`, `.claude/skills/`, `.opencode/skills/`, `.opencode/agents/`, `.github/prompts/`, `.github/agents/`, `.gemini/commands/truthmark/`, and compact managed instruction blocks in files such as `AGENTS.md`. Current strengths: @@ -82,6 +88,7 @@ Current strengths: - The runtime is agent-native. Skills tell agents to inspect the checkout directly and treat the CLI as optional validation rather than a required orchestration bridge. - The managed instruction block is compact while detailed procedures live in explicit workflow surfaces, preserving ordinary task context. - Codex metadata correctly makes only Sync implicitly invocable. Manual workflows remain explicit in Codex, reducing accidental Structure, Document, Realize, or Check runs. +- Codex, GitHub Copilot, and OpenCode custom agents are read-only verification helpers for workflow-owned subagent dispatch, not alternate workflow owners; parent workflows retain final reports and writes. - Generated-surface tests cover parseable frontmatter, required phrases, report headings, host paths, version markers, and stale-surface diagnostics. ## Current Findings diff --git a/research/2026-05-16-write-capable-opencode-subagents-design.md b/research/2026-05-16-write-capable-opencode-subagents-design.md new file mode 100644 index 0000000..2c41105 --- /dev/null +++ b/research/2026-05-16-write-capable-opencode-subagents-design.md @@ -0,0 +1,448 @@ +# Write-Capable OpenCode Subagents Design + +Status: proposed review draft +Date: 2026-05-16 +Scope: OpenCode-first workflow subagent expansion for Truthmark + +This is a research design, not canonical repository truth. If accepted, the +behavior-bearing parts should move into the owning truth docs, manifest, renderers, +and tests. + +## Summary + +Truthmark should support write-capable OpenCode subagents for bounded workflow +shards, but not as free-form helper agents. The parent workflow should remain the +orchestrator and final acceptor. Each write-capable subagent should receive a +task-specific write lease that names its objective, allowed reads, allowed writes, +forbidden writes, evidence requirements, and report shape. + +This gives us the context benefit the user called out: the parent can fan out +large Sync, Document, Structure, or Realize work without loading every file and +intermediate thought into the parent context. The tradeoff is that write fan-out +must be treated as a merge protocol, not just "let another agent edit files". + +## OpenCode Basis + +OpenCode supports project-local Markdown agents under `.opencode/agents/`, with +`mode: subagent`, descriptions for automatic routing, and manual invocation by +`@agent-name`. It also supports per-agent permissions, including `edit`, `bash`, +`read`, `grep`, `glob`, `list`, `task`, `skill`, and pattern-based permission +objects. Skills are discovered from `.opencode/skills/*/SKILL.md`. + +Relevant docs: + +- +- +- + +Implication: OpenCode can enforce coarse static boundaries for a worker agent, +but task-specific exact ownership still needs to live in the prompt/lease and be +validated by the parent after the child session returns. + +## Current Truthmark Baseline + +Current Truthmark workflow generation now has OpenCode read-only verifier +subagents: + +- `@truth-route-auditor` +- `@truth-claim-verifier` +- `@truth-doc-reviewer` + +The current canonical workflow model keeps writes parent-owned. That is correct +for the first subagent step because it avoids merge risk while proving that +OpenCode subagents can reduce verification context load. + +The next improvement should add write-capable workers behind stricter contracts, +not by relaxing the existing verifier agents. + +## Problem + +Large Truthmark workflows create context pressure in two places: + +- The parent agent must inspect implementation, routing, truth docs, generated + surfaces, test output, and report requirements. +- The parent agent often must perform repetitive localized writes after the + ownership decision is already clear. + +Read-only subagents help the first problem, but not the second. If all edits stay +in the parent, Sync and Document can still accumulate unnecessary context when +multiple truth docs or code areas need independent updates. + +Write-capable subagents can fix this, but only if they do not weaken Truthmark's +core invariants: + +- Workflow write boundaries remain enforceable. +- Canonical truth ownership remains explicit. +- Generated surfaces remain source-derived. +- Parent reports remain coherent and evidence-backed. +- Overlapping edits do not silently race. + +## Goals + +- Reduce parent context growth during large workflow runs. +- Allow bounded OpenCode worker sessions to write isolated shards. +- Preserve workflow-specific allowed write boundaries. +- Keep the parent workflow responsible for acceptance, validation, and final + reporting. +- Make worker failures visible and recoverable. +- Keep generated surfaces deterministic from the typed manifest and templates. + +## Non-Goals + +- Do not create unrestricted "developer" subagents for Truthmark workflows. +- Do not let workers expand their own write scope. +- Do not make OpenCode subagents a daemon, background queue, database, or + required runtime service. +- Do not let workers run `truthmark init` as part of ordinary shard edits. +- Do not make generated host surfaces the authority. +- Do not require cross-host parity before proving the OpenCode model. + +## Design Principle: Write Leases + +A write-capable subagent receives a write lease from the parent. The lease is the +unit of delegation and the unit of validation. + +The lease should contain: + +- `workflow`: the active Truthmark workflow. +- `worker`: the worker agent id. +- `shard`: a stable shard id for reporting. +- `objective`: the concrete edit outcome. +- `requiredReads`: files the worker must inspect before editing. +- `allowedReads`: optional broader read patterns. +- `allowedWrites`: exact files or narrow globs the worker may edit. +- `forbiddenWrites`: explicit deny list for adjacent surfaces. +- `evidenceRequired`: checkout evidence the worker must cite in its report. +- `verification`: focused command or inspection expected from the worker, if any. +- `report`: required report fields. + +If the task requires writing outside the lease, the worker must stop and report +`blocked`. It must not infer a wider scope. + +Example: + +```yaml +workflow: truthmark-sync +worker: truth-doc-writer +shard: workflows-sync-doc +objective: Update the routed Sync truth doc for the implemented OpenCode subagent behavior. +requiredReads: + - .truthmark/config.yml + - docs/truthmark/areas.md + - docs/truth/workflows/truth-sync.md + - src/agents/workflow-manifest.ts +allowedWrites: + - docs/truth/workflows/truth-sync.md +forbiddenWrites: + - src/** + - .opencode/** + - .codex/** +evidenceRequired: + - implemented source or generated surface proving each behavior claim +verification: + - inspect final diff for off-lease writes +report: + status: completed | blocked + filesChanged: [] + claimsChecked: [] + evidenceChecked: [] + blockers: [] +``` + +## Proposed Worker Agents + +### `truth-doc-writer` + +Purpose: write bounded canonical truth doc updates for Truth Sync and Truth +Document after ownership is already known. + +Static OpenCode permission shape: + +- `mode: subagent` +- allow reads/search/list +- allow edit only for `docs/truth/**` and the specific routing locations needed + by the workflow +- deny or ask for bash by default +- deny external directories + +Runtime lease: + +- usually one canonical truth doc per worker +- optional routing file only when parent already identified the owning route +- no functional code +- no generated host surfaces + +### `truth-route-structurer` + +Purpose: repair or split routing topology under Truth Structure. + +This should be introduced after `truth-doc-writer`, because topology edits have +more coupling. Parallelism should be conservative: + +- one worker per independent route subtree +- parent serializes root route index changes +- parent rejects overlapping route ownership claims + +Allowed writes: + +- `docs/truthmark/areas.md` +- `docs/truthmark/areas/**/*.md` +- starter canonical truth docs when the lease explicitly includes them + +Forbidden writes: + +- functional code +- generated host workflow surfaces +- unrelated truth docs + +### `truth-realize-writer` + +Purpose: implement a bounded code shard from accepted truth docs during Truth +Realize. + +This is valuable for context control but higher risk than doc writes. It should +arrive after lease validation exists. + +Runtime lease: + +- one implementation area or module per worker +- exact source/test paths where possible +- required source truth docs +- no truth docs +- no routing docs +- no generated host surfaces + +Parent responsibility: + +- run focused tests +- run Truth Sync afterward if functional behavior changed +- reject any truth doc edits from this worker + +### No Initial Generated-Surface Writer + +Do not create a worker that edits `.opencode/skills`, `.opencode/agents`, +`.codex/skills`, `.codex/agents`, Gemini commands, Copilot prompts, or generated +instruction blocks. Generated surfaces should remain parent/refreshed outputs of +source templates and `truthmark init`. + +## Workflow Mapping + +### Truth Sync + +Recommended flow: + +1. Parent inspects code diff and changed behavior. +2. Parent dispatches read-only route and claim verifier subagents as useful. +3. Parent maps changed behavior to owned truth docs. +4. Parent creates non-overlapping `truth-doc-writer` leases. +5. Workers edit only leased docs. +6. Parent checks actual diffs against leases. +7. Parent runs focused validation and `truthmark check` when appropriate. +8. Parent writes the final Sync report. + +Truth Sync should be the first workflow to use write workers because its write +boundary is narrow: canonical truth docs and routing only. + +### Truth Document + +Recommended flow: + +1. Parent establishes that behavior is already implemented. +2. Parent verifies route ownership. +3. Parent dispatches one doc writer per missing or stale canonical doc. +4. Parent accepts only docs/routing writes permitted by the workflow. + +Truth Document is the second-best rollout target. It has the same doc-writing +shape as Sync but is explicit rather than finish-time automatic. + +### Truth Structure + +Recommended flow: + +1. Parent uses read-only route auditing to find broad, stale, missing, or + mixed-owner routing. +2. Parent produces a topology plan. +3. Parent serializes or narrowly shards route writes. +4. Parent rejects write leases that overlap root ownership files unless there is + exactly one route structurer. + +Structure should not start with broad parallel writes. Routing topology is too +easy to corrupt with independent partial fixes. + +### Truth Realize + +Recommended flow: + +1. Parent reads accepted truth docs and identifies implementation shards. +2. Parent dispatches `truth-realize-writer` workers with exact source/test write + leases. +3. Workers return implementation diffs and focused verification notes. +4. Parent runs authoritative tests. +5. Parent invokes Truth Sync after functional code changes. + +Realize is where write fan-out may save the most context, but it must not be +allowed to edit truth docs. Code leads after realization; Sync follows. + +### Truth Check + +Truth Check should stay read-only by default. It may recommend Structure, +Document, Sync, or Realize, but it should not silently dispatch write workers. + +## Parent Orchestration Algorithm + +The parent workflow should follow a deterministic merge protocol: + +1. Inspect checkout, config, routing, manifest, and relevant docs. +2. Build a work-unit graph with expected write sets. +3. Reject or serialize overlapping write sets before dispatch. +4. Dispatch OpenCode workers with explicit write leases. +5. Require each worker to report status, changed files, evidence, and blockers. +6. Inspect actual diff after each worker returns. +7. Reject or flag any off-lease file changes. +8. Merge worker reports into the parent report. +9. Run focused validation, generated-surface refresh, or `truthmark check` as + required by the changed surface. +10. Keep final user-facing completion parent-owned. + +The parent should never trust a worker report without checking the actual diff. + +## Permission Model + +OpenCode permissions should provide coarse static fencing: + +```yaml +--- +description: Writes one leased Truthmark truth-document shard. Use only when a parent workflow provides an explicit write lease. +mode: subagent +permission: + read: allow + list: allow + grep: allow + glob: allow + edit: + "*": deny + "docs/truth/**": allow + "docs/truthmark/areas.md": allow + "docs/truthmark/areas/**/*.md": allow + bash: + "*": ask + "git diff*": allow + external_directory: deny +--- +``` + +This is necessary but not sufficient. Static permissions cannot express the exact +per-task file list. The lease and parent diff validation provide the precise +boundary. + +## Report Contract + +Each write worker should return a compact, machine-checkable report: + +```yaml +status: completed | blocked +worker: truth-doc-writer +workflow: truthmark-sync +shard: workflows-sync-doc +filesChanged: + - docs/truth/workflows/truth-sync.md +claimsChecked: + - claim: OpenCode installs read-only verifier subagents for workflow-owned verification. + evidence: + - src/templates/generated-surfaces.ts + - .opencode/agents/truth-route-auditor.md +evidenceChecked: + - docs/truthmark/areas.md mapped the doc owner before writing. +offLeaseChanges: [] +blockers: [] +``` + +The parent can parse this lightly, but the source of truth remains the actual +checkout diff. + +## Conflict Handling + +Workers must block when: + +- ownership is missing or ambiguous +- the required edit needs an off-lease file +- another worker changed the same leased file +- generated surfaces appear stale and require parent refresh +- evidence does not support the requested truth claim + +The parent should handle conflicts by: + +- serializing overlapping route/doc writes +- narrowing leases and retrying only when safe +- reporting blocked ownership rather than broadening scope +- preserving unrelated user changes +- refusing to accept off-lease edits as workflow output + +## Test Strategy + +The implementation should have tests before enabling write workers by default: + +- Manifest tests for worker metadata, write boundaries, and workflow mapping. +- Renderer tests for generated OpenCode worker agent files. +- Init tests proving `.opencode/agents/*.md` outputs are deterministic. +- Contract tests that worker prompts require leases and block on off-lease writes. +- Permission tests or snapshots for OpenCode `permission` frontmatter. +- Report parser tests for `completed`, `blocked`, `offLeaseChanges`, and + evidence fields. +- Integration fixture for two non-overlapping doc writers. +- Negative fixture for overlapping write leases rejected by the parent. + +## Rollout Plan + +### Phase 1: Lease Schema and Prompt Contract + +Add a source-level representation of write leases and tests for rendered worker +instructions. Do not enable write workers yet. + +### Phase 2: OpenCode `truth-doc-writer` + +Generate one OpenCode doc writer subagent. Wire Sync and Document instructions to +permit parent-dispatched doc write fan-out only after route ownership is known. + +### Phase 3: Parent Diff Acceptance + +Add deterministic parent guidance and tests for checking actual changed files +against the lease. This is the gate before any worker is considered successful. + +### Phase 4: Realize Code Worker + +Add `truth-realize-writer` only after doc writers prove the lease model. Require +tests and post-realization Sync. + +### Phase 5: Structure Worker + +Add `truth-route-structurer` with conservative serialization. Structure writes +should remain parent-planned because routing topology is coupled. + +### Phase 6: Cross-Host Parity + +Only after the OpenCode shape is stable, evaluate Codex and other host-specific +subagent equivalents. Do not force parity early if it weakens OpenCode quality. + +## Open Questions + +- Should write leases be only prompt text at first, or also generated as a + machine-readable payload? Recommendation: prompt text first, typed source model + next, sidecar payload only if the prompt contract proves insufficient. +- Should write workers run validation commands? Recommendation: allow focused + commands, but keep authoritative validation parent-owned. +- Should generated worker agents be installed by default? Recommendation: not + until lease validation and negative tests exist. +- Should route writes ever run in parallel? Recommendation: only by independent + route subtree, never against the root route index in parallel. + +## Recommendation + +Proceed with OpenCode write-capable subagents, but start with `truth-doc-writer` +and a strict write-lease protocol. This directly addresses parent context +explosion while preserving Truthmark's workflow boundaries. + +The important boundary is not "read-only versus write-capable". The boundary is +"parent-owned acceptance versus unreviewed child edits". Write-capable subagents +are safe enough for Truthmark only when the parent grants narrow leases, validates +actual diffs, and owns the final workflow report. diff --git a/research/prompt-skill-agent-workflow-literature-review-2026-05-16.md b/research/prompt-skill-agent-workflow-literature-review-2026-05-16.md new file mode 100644 index 0000000..1108602 --- /dev/null +++ b/research/prompt-skill-agent-workflow-literature-review-2026-05-16.md @@ -0,0 +1,858 @@ +# Prompt, Skill, Agent, and Workflow Literature Review + +## Status + +This document is a literature review and research reference. It is not canonical Truthmark behavior. It does not by itself change Truthmark workflows, generated surfaces, skills, agents, tests, repository rules, or implementation policy. + +The document collects and compares literature relevant to prompt standards, reusable skills, agents/subagents, and repository-native workflow implementation. Any later design decision for Truthmark would need to be promoted through the appropriate canonical files, source manifest, renderers, generated host surfaces, and tests. + +## Scope + +This review covers literature related to: + +- prompt standards +- persistent repository instructions +- reusable skills +- agents and subagents +- workflow implementation +- routing and invocation +- permissions and write boundaries +- evaluation +- security +- maintenance +- cross-host compatibility + +The review intentionally does not apply a strict year cutoff. Official, canonical, influential, or actively maintained sources are included even when they predate 2026. Source age, publication date, update date, or currentness signal is recorded where available. + +The primary research question is: + +> What does the best available literature say about world-class standards for prompts, skills, agents/subagents, and workflow implementation in modern AI coding-agent systems? + +The secondary questions are organized around prompt structure, reusable AI skills, agent/subagent delegation, repository-native workflows, routing triggers, negative triggers, permissions, verification, evaluation, cross-source agreement, cross-source disagreement, and relevance to Truthmark’s workflow/skill/agent architecture. + +## Truthmark Context + +This section summarizes the local repository context so that the external literature can be mapped later. It is descriptive, not evaluative. + +### Repository and product context + +Truthmark presents itself as a local-first, Git-native protocol for repository truth workflows. The README describes a normal workflow in which an agent changes functional code, runs tests, then uses Truth Sync to update mapped truth docs before finishing. It also describes the central repository files: `.truthmark/config.yml`, `docs/truthmark/areas.md`, generated workflow surfaces, and the truth docs under `docs/truth/**/*.md`. Source: [README.md](https://github.com/merlinhu1/truthmark/tree/subagent-improvement). + +`FutureVision.md` frames the project as a repository protocol rather than a server. It lists non-goals such as a memory server, session persistence, IDE-plugin centricity, and default merge gating. It emphasizes committed, branch-scoped, Git-reviewable truth. Source: [FutureVision.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/FutureVision.md). + +### Managed instruction blocks + +`AGENTS.md`, `CLAUDE.md`, and `GEMINI.md` contain managed Truthmark instruction blocks. These blocks describe the source hierarchy, the finish-time Truth Sync rule, skip cases, explicit workflows, and workflow-integrity requirements. They point agents toward canonical docs and generated surfaces rather than embedding all workflow details in root instructions. Sources: [AGENTS.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/AGENTS.md), [CLAUDE.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/CLAUDE.md), [GEMINI.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/GEMINI.md). + +### Current workflows + +The current workflow inventory is: + +- Truth Sync +- Truth Structure +- Truth Document +- Truth Realize +- Truth Check + +The workflow overview states that workflow surfaces define invocation rules, write boundaries, report shapes, and required reads. It also states that Truth Sync is the only automatic finish-time workflow. Structure, Document, Realize, and Check are explicit/manual unless invoked by another workflow under documented rules. Source: [docs/truth/workflows/overview.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/overview.md). + +### Shared workflow gates + +The shared gates document defines common workflow gates: + +- Ownership Gate +- Product Decisions/Rationale preservation gate +- Evidence Gate +- Shape Repair Gate + +It also states that the direct checkout is the ground truth and that optional repository intelligence may assist but may not override the checkout. Source: [docs/truth/workflows/shared-gates.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/shared-gates.md). + +### Truth docs and routing + +`docs/truthmark/areas.md` acts as the root route index. It maps installed workflow behavior to source areas such as `src/agents/**`, `src/generation/**`, `src/realize/**`, `src/sync/**`, template renderers, and truth docs. It also states when truth updates are required, including workflow boundary changes, report shape changes, generated content changes, version marker changes, and sync classification changes. Source: [docs/truthmark/areas.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truthmark/areas.md). + +### Workflow manifest + +`src/agents/workflow-manifest.ts` is the typed workflow manifest. It defines workflow ids, display names, descriptions, short descriptions, default prompts, implicit invocation policy, positive triggers, negative triggers, forbidden adjacency, required gates, allowed writes, report sections, read-only subagents, and write-capable subagents. Source: [src/agents/workflow-manifest.ts](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). + +The manifest currently distinguishes read-only subagents such as route auditor, claim verifier, and doc reviewer from the write-capable `truth-doc-writer`. Truth Sync and Truth Document include the write-capable doc writer. Truth Check uses read-only verifier agents. + +### Instruction rendering + +`src/agents/instructions.ts` renders compact managed instruction snippets. These rendered snippets include the automatic Truth Sync rule, the direct-checkout rule, the truth-doc write boundary, and skip reasons. Source: [src/agents/instructions.ts](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/instructions.ts). + +### Generated host surfaces + +`src/templates/workflow-surfaces.ts` defines host-surface templates for skills, prompts, commands, and agents. It includes read-only subagent context boundaries and the write-capable `truth-doc-writer` profile. The doc writer requires an explicit parent-issued write lease and returns a structured YAML report. It may edit only leased truth docs and routing paths unless explicitly leased otherwise; the parent validates actual Git diff before accepting the worker’s output. Source: [src/templates/workflow-surfaces.ts](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). + +`src/templates/generated-surfaces.ts` renders host outputs for Codex, OpenCode, Claude, GitHub Copilot, and Gemini. The workflow overview states that Codex, OpenCode, Claude, and GitHub Copilot include verifier and leased doc-writer agents. Gemini currently receives generated commands under `.gemini/commands/truthmark/*.toml`. Source: [src/templates/generated-surfaces.ts](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts). + +### Generated skills, prompts, commands, and agents + +The repository includes generated OpenCode skills such as `.opencode/skills/truthmark-sync/SKILL.md` and `.opencode/skills/truthmark-document/SKILL.md`. These files include routing descriptions, invocation rules, write boundaries, subagent mode, parent validation, gates, and report expectations. Sources: [.opencode/skills/truthmark-sync/SKILL.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/skills/truthmark-sync/SKILL.md), [.opencode/skills/truthmark-document/SKILL.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/skills/truthmark-document/SKILL.md). + +The generated OpenCode `truth-doc-writer` agent is a write-capable subagent with constrained permissions and a required lease. It denies task/web/external-directory access, asks for bash access, and limits edit permissions to truth-doc and route paths. Source: [.opencode/agents/truth-doc-writer.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/agents/truth-doc-writer.md). + +The generated OpenCode route auditor is a read-only verifier subagent. It is instructed to inspect only assigned routing evidence, return JSON, and avoid making edits or final workflow decisions. Source: [.opencode/agents/truth-route-auditor.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/agents/truth-route-auditor.md). + +Codex, Claude, and GitHub Copilot generated surfaces expose analogous skills/prompts and agents. Sources include [.codex/skills/truthmark-sync/SKILL.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.codex/skills/truthmark-sync/SKILL.md), [.codex/agents/truth-doc-writer.toml](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.codex/agents/truth-doc-writer.toml), [.claude/skills/truthmark-sync/SKILL.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.claude/skills/truthmark-sync/SKILL.md), [.claude/agents/truth-doc-writer.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.claude/agents/truth-doc-writer.md), [.github/prompts/truthmark-sync.prompt.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.github/prompts/truthmark-sync.prompt.md), and [.github/agents/truth-doc-writer.agent.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.github/agents/truth-doc-writer.agent.md). + +Gemini generated surfaces are command files such as `.gemini/commands/truthmark/sync.toml`. These command files contain prompt text and command descriptions but do not contain generated Gemini subagents in the inspected branch. Source: [.gemini/commands/truthmark/sync.toml](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.gemini/commands/truthmark/sync.toml). + +### Research folder + +The research folder contains non-canonical design references. The 2026-05-15 review describes skills as context packages, descriptions as routing logic, progressive disclosure, evals, and security considerations. It explicitly states that behavior-bearing findings must be promoted into truth docs, the manifest, renderers, generated surfaces, and tests before becoming behavior. Source: [research/2026-05-15-agent-skills-workflow-review.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-15-agent-skills-workflow-review.md). + +The 2026-05-16 write-capable OpenCode subagents design proposes parent-issued write leases, parent-owned final acceptance, and possible workers such as `truth-doc-writer`, `truth-route-structurer`, and `truth-realize-writer`. The research file is explicitly non-canonical. Source: [research/2026-05-16-write-capable-opencode-subagents-design.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-16-write-capable-opencode-subagents-design.md). + +## Literature Search Method + +Sources were found through the seed list, official documentation navigation, repository inspection, and targeted searches for current platform documentation and major agent-framework materials. Search terms are listed in Appendix C. + +Source quality was judged by: + +- officialness: whether the source is maintained by the platform or research organization; +- canonicality: whether the source defines current user-facing behavior or a published standard; +- influence: whether the source is widely adopted or cited in the coding-agent ecosystem; +- maintenance: whether the source is currently updated or attached to an active repository; +- concreteness: whether the source discusses prompts, skills, agents, workflows, routing, permissions, evaluation, or safety in implementable detail. + +There is no strict year cutoff. Older sources were included when they remain current, canonical, or influential. For example, Anthropic’s “Building effective agents” is from 2024 but is still widely referenced and directly addresses agent workflow patterns. The AGENTS.md open format is not a single vendor product page, but it is included because it is an active open format used across coding-agent systems. Currentness was judged from page metadata, visible update markers, active repository state, or whether the page is current official documentation. + +Official docs, standards/specifications, maintained repositories, engineering blogs, production case studies, and research papers were treated differently: + +- official docs were treated as evidence of current platform behavior; +- standards/specifications were treated as evidence of shared or portable formats; +- maintained repositories were treated as practical implementation examples; +- engineering blogs were treated as design rationale or product practice, not necessarily normative behavior; +- research papers were treated as empirical or conceptual evidence and were caveated when preprint or benchmark-specific; +- practitioner examples were treated as illustrative unless they contained concrete reusable structures. + +Access date for source review: 2026-05-16. + +## Included Source Ledger + +| Source | Organization / author | Date or currentness signal | Source type | Inclusion reason | Relevant areas | Notes | +|---|---|---:|---|---|---|---| +| [Prompt Engineering Guide](https://developers.openai.com/api/docs/guides/prompt-engineering) | OpenAI | Current official docs; references current GPT model family | Official documentation | Canonical OpenAI guidance for system/developer/user prompts, structure, examples, and coding prompts | Prompt, context placement, output contracts | Strong for prompt mechanics; less specific to repository workflows | +| [Codex AGENTS.md Guide](https://developers.openai.com/codex/guides/agents-md) | OpenAI | Current Codex docs | Official documentation | Defines how Codex discovers and applies AGENTS.md instructions | Persistent repository instructions, precedence, maintenance | Directly relevant to repository-native coding-agent instructions | +| [Codex Skills](https://developers.openai.com/codex/skills) | OpenAI | Current Codex docs | Official documentation | Defines Codex skill packages, `SKILL.md`, progressive disclosure, implicit/explicit invocation | Skill, routing, context budgeting | Relevant to SKILL.md-style packages | +| [Codex Subagents](https://developers.openai.com/codex/subagents) | OpenAI | Current Codex docs | Official documentation | Defines Codex subagents, custom agents, sandbox/approval inheritance, and narrow specialist design | Agents, subagents, permissions, orchestration | Relevant to Truthmark’s Codex surfaces | +| [Evals in agentic workflows: three skills](https://developers.openai.com/blog/eval-skills) | OpenAI | 2026-01-22 | Engineering blog | Concrete 2026 treatment of evals as agentic workflow skills | Evaluation, skill evals, routing evals | Blog, not formal spec; useful implementation detail | +| [Skills shell tips](https://developers.openai.com/blog/skills-shell-tips) | OpenAI | 2026-02-11 | Engineering blog | Discusses skill descriptions, shell workflows, deterministic helpers, and network risk | Skills, scripts, routing, security | Shell-oriented but highly relevant to skill execution | +| [Equip agents with skills using the Agents SDK and Codex](https://developers.openai.com/blog/skills-agents-sdk) | OpenAI | 2026-03-09 | Engineering blog | Discusses repo-local skills, AGENTS.md, GitHub Actions, and deterministic scripts | Skills, repo workflows, evals, maintenance | SDK-oriented; still relevant as platform practice | +| [Agent Evals Guide](https://developers.openai.com/api/docs/guides/agent-evals) | OpenAI | Current official docs | Official documentation | Describes traces, graders, datasets, eval runs, tools, handoffs, and safety checks | Evaluation, agents, routing, guardrails | General agent-eval guidance | +| [Improve agents with Codex](https://developers.openai.com/cookbook/examples/agents_sdk/agent_improvement_loop) | OpenAI Cookbook | 2026-05-12 | Cookbook / implementation guide | Describes traces, feedback, evals, harness updates, validation, and routing changes | Evaluation, maintenance, workflows | Cookbook pattern, not normative standard | +| [Prompt engineering overview](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview) | Anthropic | Current official docs | Official documentation | Establishes Anthropic prompting workflow, success criteria, evals, examples, and structure | Prompt, evals, prompt iteration | High-level overview | +| [Agent Skills overview](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview) | Anthropic | Current official docs | Official documentation | Defines skills as modular filesystem capabilities with progressive disclosure | Skills, metadata, security, cross-surface use | Directly relevant to SKILL.md packages | +| [Skill authoring best practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices) | Anthropic | Current official docs | Official documentation | Detailed guidance on skill descriptions, body size, progressive disclosure, evals, and maintenance | Skill, routing, bloat control, evals | Strong skill-quality source | +| [Claude Code subagents](https://code.claude.com/docs/en/sub-agents) | Anthropic | Current Claude Code docs | Official documentation | Defines subagents with separate context, prompts, tools, permissions, and descriptions | Subagents, delegation, permissions, reports | Directly relevant to generated `.claude/agents` | +| [Claude Code skills and commands](https://code.claude.com/docs/en/slash-commands) | Anthropic | Current Claude Code docs | Official documentation | Describes skills, supporting files, invocation controls, and command/skill boundary | Skills, commands, invocation, maintenance | The slash-command seed resolves into current skill guidance | +| [Building effective agents](https://www.anthropic.com/engineering/building-effective-agents) | Anthropic | 2024-12-19; still influential | Engineering essay | Defines workflow vs agent patterns: chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer | Agents, workflows, routing, evaluation, tool design | Older than 2026 but still canonical/influential | +| [OpenCode docs](https://opencode.ai/docs/) | OpenCode | Last updated 2026-05-16 | Official documentation | Current product overview; describes OpenCode as a terminal coding agent and project rules | Persistent instructions, host behavior | Useful for host context | +| [OpenCode agents](https://opencode.ai/docs/agents/) | OpenCode | Last updated 2026-05-16 | Official documentation | Defines primary agents, subagents, agent files, descriptions, prompts, modes, permissions | Agents, subagents, permissions | Directly relevant to `.opencode/agents` | +| [OpenCode skills](https://opencode.ai/docs/skills/) | OpenCode | Last updated 2026-05-16 | Official documentation | Defines OpenCode skills, recognized metadata, paths, loading behavior, and permissions | Skills, routing, permissions, cross-host compatibility | Directly relevant to `.opencode/skills` | +| [OpenCode permissions](https://opencode.ai/docs/permissions/) | OpenCode | Last updated 2026-05-16 | Official documentation | Defines allow/ask/deny permission categories and granular rules | Permissions, write boundaries, security | Directly relevant to host-specific write boundaries | +| [Agent Skills specification](https://agentskills.io/specification) | Agent Skills | Active specification; repository maintained | Standard/specification | Defines portable `SKILL.md` package structure, metadata, progressive disclosure, scripts, references, assets | Skill, compatibility, metadata | Useful for cross-host skill format comparison | +| [Agent Skills repository](https://github.com/agentskills/agentskills) | Agent Skills community | Active GitHub repository | Standard repository | Maintained reference for the Agent Skills standard | Skill, compatibility | Complements specification page | +| [AGENTS.md open format](https://agents.md/) | Agentic AI Foundation / community | Active open format | Open format / standard-like guidance | Defines AGENTS.md as a simple README-like instruction file for agents | Persistent repository instructions, precedence, maintenance | Relevant across Codex/OpenCode/GitHub and repository-native workflows | +| [GitHub Copilot customization cheat sheet](https://docs.github.com/en/copilot/reference/customization-cheat-sheet) | GitHub | Current GitHub Docs; 2026 copyright | Official documentation | Compares custom instructions, prompt files, custom agents, subagents, skills, and hooks | Persistent instructions, prompts, agents, skills, hooks | Strong cross-surface taxonomy | +| [Adding repository custom instructions for GitHub Copilot](https://docs.github.com/copilot/customizing-copilot/adding-custom-instructions-for-github-copilot) | GitHub | Current GitHub Docs; 2026 copyright | Official documentation | Defines repository custom instructions, path-specific instructions, AGENTS.md support, and instruction scope | Persistent repository instructions | Directly relevant to `.github` surfaces | +| [Gemini CLI custom commands](https://google-gemini.github.io/gemini-cli/docs/cli/custom-commands.html) | Google Gemini CLI | Active official docs; 2026 commit activity observed | Official documentation | Defines global/project custom commands, TOML fields, shell injection, and file injection | Commands, workflow surfaces, invocation | Relevant to `.gemini/commands/truthmark` | +| [Subagents have arrived in Gemini CLI](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/) | Google Developers Blog | 2026-04-15 | Engineering blog / product announcement | Describes Gemini CLI subagents, separate context, instructions, tools, routing, and project/global agent files | Subagents, delegation, context isolation | Announcement-level but official and current | +| [Agent Skills](https://learn.microsoft.com/en-us/agent-framework/agents/skills) | Microsoft Agent Framework | Last updated 2026-04-10 | Official documentation | Defines skills as portable instructions/scripts/resources; covers progressive disclosure, scripts, security, workflows distinction | Skills, workflow distinction, security | Strong source for skill-vs-workflow boundary | +| [Handoff orchestration](https://learn.microsoft.com/en-us/agent-framework/workflows/orchestrations/handoff) | Microsoft Agent Framework | Last updated 2026-05-09 | Official documentation | Defines handoff orchestration, specialist agents, handoff rules, tool approval, checkpointing | Agents, handoff, orchestration, permissions | Relevant to parent-child and specialist-agent comparisons | +| [Google ADK overview](https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/adk) | Google Cloud | Last updated 2026-05-15 | Official documentation | Describes ADK as a framework for build/run/evaluate/scale and dynamic or deterministic orchestration | Agents, workflows, evaluation | Framework-level context rather than coding-agent host surface | +| [Google ADK multi-agent systems](https://github.com/google/adk-docs/blob/main/docs/agents/multi-agents.md) | Google ADK | Active docs repository | Official framework docs | Defines multi-agent hierarchy, workflow agents, LLM-driven delegation, descriptions, and routing | Agents, subagents, workflows, routing | Useful for parent-child and workflow-agent comparison | +| [AWS Bedrock multi-agent collaboration](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-multi-agent-collaboration.html) | AWS | Current AWS docs | Official documentation | Defines supervisor/collaborator agents, roles, responsibilities, routing, and guardrails | Multi-agent orchestration, permissions, routing | Enterprise platform context; not coding-agent-specific | +| [LangGraph overview](https://docs.langchain.com/oss/python/langgraph/overview) | LangChain | Current docs | Maintained open-source framework docs | Describes durable, stateful, long-running agents, human-in-the-loop, memory, tracing, and evaluation | Workflows, agents, evaluation, state | Important contrasting architecture; not repository-surface-specific | +| [Model Context Protocol Security Best Practices](https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices) | Model Context Protocol | Current official docs | Security best practices | Discusses prompt injection, tool poisoning, least privilege, tool allowlists, and human confirmation | Security, permissions, tool risk | Relevant to external tools and permission boundaries | +| [Prompt injection is not SQL injection](https://www.ncsc.gov.uk/blog-post/prompt-injection-is-not-sql-injection) | UK NCSC | 2025-12-08 | Government security guidance | Explains prompt injection as instruction/data confusion and recommends deterministic safeguards and privilege reduction | Security, prompt injection, permissions | Strong safety framing; not coding-agent-specific | +| [OWASP Top 10 for LLM Applications 2025](https://genai.owasp.org/resource/owasp-top-10-for-llm-applications-2025/) | OWASP | 2024-11-17; active 2026 project resources | Security standard / community guidance | Defines common LLM application security risk categories | Security, tool misuse, supply-chain risk | Broad; useful background rather than workflow detail | +| [Designing, Refining, and Maintaining Agent Skills at Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity) | Perplexity Research | 2026-05-01 | Production engineering article | Detailed source on skill descriptions, progressive disclosure, evals, scripts, bloat, and maintenance | Skills, routing, evals, maintenance | Practitioner source with strong implementation detail | +| [Goalkeeper](https://github.com/itsuzef/goalkeeper) | Youssef / open source | Active 2026 repository | Practitioner repository | Demonstrates judge-gate pattern, explicit Definition of Done, validation, and fresh-context subagent review | Judge agents, verification, workflows | Illustrative; not a platform standard | +| [Matt Pocock skills](https://github.com/mattpocock/skills) | Matt Pocock | Active popular repository | Practitioner repository | Demonstrates compact skill examples, handoff skills, TDD skills, and skill-writing practices | Skills, prompt reuse, maintenance | Illustrative; useful for concrete skill style | + +## Rejected or Low-Relevance Source Ledger + +| Source | Reason rejected or downgraded | Historically relevant? | Replacement or better source | +|---|---|---:|---| +| Generic SEO prompt-engineering summaries found during discovery | Too shallow, not canonical, and usually restated official guidance without implementation detail | Limited | OpenAI and Anthropic official prompt docs | +| Third-party Gemini CLI tutorials | Often restated official command/subagent docs and lacked durable implementation detail | Limited | Gemini CLI official custom-command docs and Google Developers subagent announcement | +| Third-party “best AI agent framework” listicles | Broad, ranking-oriented, and not specific to prompts, skills, permissions, routing, or workflow surfaces | Limited | LangGraph, Google ADK, Microsoft Agent Framework, AWS Bedrock official docs | +| Microsoft AutoGen older docs | Historically important but superseded or de-emphasized relative to Microsoft Agent Framework for current skill/workflow documentation | Yes | Microsoft Agent Framework skills and handoff orchestration docs | +| Cursor documentation discovered during search | Relevant platform area, but not inspected deeply enough in this review to support source-centered claims | Yes | GitHub Copilot, Codex, OpenCode, Claude Code, and Gemini CLI docs | +| Vendor marketing pages about “autonomous agents” without concrete docs | Lacked concrete structure for prompts, skills, routing, permissions, or evals | Limited | Anthropic “Building effective agents,” Google ADK, Microsoft Agent Framework | +| Unmaintained toy agent repositories | Not current enough and not influential enough for standards comparison | Limited | Goalkeeper and Matt Pocock skills as maintained practitioner references | +| Blog posts about prompt injection without operational safeguards | Often alarmist or duplicative; lacked practical permission or boundary patterns | Some | NCSC prompt injection guidance, OWASP LLM Top 10, MCP security best practices | + +## Annotated Bibliography + +### OpenAI — Prompt Engineering Guide + +The OpenAI Prompt Engineering Guide is current official documentation for structuring prompts. It addresses how instructions are divided between system, developer, user, and assistant messages, and it treats developer messages as a place for rules and business logic that should apply across user requests. The guide discusses Markdown and XML-style structure for separating instructions from supporting context, and it includes coding-prompt examples that define role, tool use, tests, and output expectations. + +The source is strongest for prompt structure, instruction hierarchy, examples, output contracts, and coding-task prompt format. It is less specific about repository-native workflow generation or subagent delegation. For Truthmark, it provides background on how generated workflow prompts can structure instruction hierarchy and output contracts without claiming that Truthmark should adopt any particular OpenAI-only surface. + +### OpenAI — Codex AGENTS.md Guide + +The Codex AGENTS.md guide defines how Codex discovers and applies repository instruction files. It describes global and project-specific AGENTS.md files, discovery order, nested overrides, and a project instruction size limit. It treats AGENTS.md as the place for project setup, build, test, formatting, and repository expectations. + +The source addresses persistent repository instructions, instruction precedence, local overrides, and maintenance. Its relevance to Truthmark is direct because Truthmark uses managed repository instruction blocks and must coexist with host-specific instruction discovery. The limitation is that it describes Codex behavior specifically; other hosts may read different files or apply different precedence rules. + +### OpenAI — Codex Skills + +The Codex Skills documentation defines skills as packages containing instructions, resources, and scripts. It describes the `SKILL.md` entrypoint, name/description/path listing, progressive disclosure, explicit invocation, and implicit invocation through descriptions. It also discusses context budgeting for skill listings and loading. + +The source addresses reusable skills, metadata, descriptions, progressive disclosure, and context placement. It is directly relevant to Truthmark’s generated `.codex/skills` and to any comparison of SKILL.md-like packages across hosts. The limitation is host specificity: Codex skill invocation and context budgets do not automatically apply to Claude, OpenCode, GitHub Copilot, or Gemini. + +### OpenAI — Codex Subagents + +The Codex Subagents documentation describes subagents as specialized agents that can run in parallel and report back to a main agent. It describes custom agents in `.codex/agents`, fields such as name, description, and developer instructions, inherited sandbox/approval behavior, optional sandbox override, and a default depth cap to avoid recursive fan-out. It encourages narrow, opinionated custom agents. + +The source addresses delegation, specialist agents, context splitting, sandbox inheritance, and recursive-delegation risks. It is relevant to Truthmark’s generated Codex agents and to the broader question of parent-owned orchestration. Its limitation is that it describes a Codex-specific execution model and approval system. + +### OpenAI — Evals in agentic workflows: three skills + +This 2026 OpenAI engineering article treats evaluation work itself as a set of agentic skills. It frames evals as prompt, trace/artifact, check, and score pipelines. It distinguishes defining success before writing a skill, using name and description as selection signals, and designing trigger and negative-control evaluations. It includes examples of deterministic trace checks and compact eval sets. + +The source addresses prompt evals, skill evals, routing evals, negative controls, and evaluation-data management. It is relevant to Truthmark because workflows and generated surfaces depend on correct routing, invocation, and report behavior. The article is practical but not a formal standard. + +### OpenAI — Skills shell tips + +This article focuses on skills that guide shell-based agent work. It treats a skill as a reusable procedure that can include scripts, templates, examples, and explicit invocation patterns. It emphasizes writing descriptions as routing logic, including “use” and “don’t use” cases, and using explicit skill calls for deterministic workflows. It also discusses risks around network access, secrets, and tool use. + +The source addresses scripts, shell workflows, skill descriptions, deterministic helpers, and skill-security boundaries. It is relevant to Truthmark’s workflow skills because Truthmark’s generated surfaces direct agents through repeatable procedures. The limitation is that examples are shell-oriented and may not generalize to all workflow surfaces. + +### OpenAI — Equip agents with skills using the Agents SDK and Codex + +This 2026 OpenAI article discusses repository-local skills, AGENTS.md, GitHub Actions, and the division between mandatory workflows and optional skills. It presents AGENTS.md as a place for required workflows and high-level instructions, while skills carry on-demand procedures, scripts, and context. It also connects skills to CI and deterministic validation. + +The source addresses persistent repository instructions, skills, deterministic scripts, and repository workflows. It is relevant because Truthmark’s architecture similarly separates root managed blocks from generated workflow surfaces. The limitation is that it is tied to OpenAI’s Agents SDK and Codex examples, so its details are not automatically host-neutral. + +### OpenAI — Agent Evals Guide + +The Agent Evals Guide describes using traces, graders, datasets, and eval runs to assess agent behavior. It frames traces as containing model calls, tool calls, guardrails, handoffs, and other execution steps. It suggests evaluating whether the right tool was called, whether a handoff happened appropriately, whether an instruction or safety requirement was violated, and whether prompt or routing changes improved behavior. + +The source addresses agent evaluation, routing evaluation, tool-use evaluation, handoff evaluation, and guardrail checks. It is relevant to Truthmark’s interest in workflow routing, report contracts, subagent dispatch, and permission boundaries. The limitation is that it describes OpenAI’s evaluation infrastructure rather than a repository-native test harness. + +### OpenAI Cookbook — Improve agents with Codex + +The OpenAI Cookbook’s agent-improvement-loop example describes how traces, human feedback, evals, and harness changes can be used to improve agents. It treats an agent harness as containing instructions, tools, routing, output validation, and evaluation metadata. It describes a loop in which observed failures are converted into validation or harness changes. + +The source addresses maintenance, evaluation, routing, tool policy, and output validation. It is relevant to Truthmark as a model for treating workflow-surface changes as evaluated artifacts. It is a cookbook example rather than a normative platform specification. + +### Anthropic — Prompt engineering overview + +Anthropic’s prompt engineering overview frames prompt engineering around defining success criteria, establishing evals, and iterating through techniques such as clarity, examples, XML tags, role prompting, chain-of-thought controls, and prompt chaining. It places eval design before prompt iteration. + +The source addresses prompt structure, examples, uncertainty, and prompt evaluation. It is relevant to Truthmark because workflow prompts and generated surfaces can be evaluated as prompts rather than treated as static documentation. Its limitation is that it is a general model-use guide, not a repository-agent workflow standard. + +### Anthropic — Agent Skills overview + +Anthropic’s Agent Skills overview defines skills as modular capabilities stored as filesystem resources. It emphasizes that skills differ from one-off prompts because they are reusable packages with instructions and supporting materials. It describes progressive disclosure, `SKILL.md`, name and description fields, security considerations, and cross-surface availability limitations. + +The source addresses skill definition, metadata, progressive disclosure, and security. It is directly relevant to Truthmark’s generated `SKILL.md` surfaces. Its limitation is that Anthropic skill semantics may differ from Codex, OpenCode, and GitHub Copilot. + +### Anthropic — Skill authoring best practices + +Anthropic’s skill authoring best-practices document gives detailed guidance on naming, descriptions, progressive disclosure, body size, concrete examples, validation, and real-world usage. It states that skill descriptions are critical for selection among many skills and should describe when the skill should be used. It recommends keeping the body concise, moving large content into supporting files, avoiding time-sensitive information, and testing skills with real scenarios. + +The source addresses skill routing, context bloat, evals, examples, maintenance, and description quality. It is highly relevant to Truthmark’s workflow-skill descriptions and generated surfaces. Its limitation is that it focuses on Claude skill behavior and not every host supports the same frontmatter or invocation semantics. + +### Anthropic — Claude Code subagents + +Claude Code subagents are specialist assistants with their own context, prompt, tools, and permissions. The docs describe project-level and user-level subagents, frontmatter fields, tool selection, descriptions for delegation, subagent chaining, and hooks. They distinguish work that should stay in the main conversation from work that should be delegated to subagents. + +The source addresses context isolation, specialist agents, permission boundaries, delegation descriptions, and parent/subagent tradeoffs. It is directly relevant to Truthmark’s `.claude/agents` surfaces and to the wider question of verifier or worker subagents. Its limitation is host specificity. + +### Anthropic — Claude Code skills and commands + +Claude Code’s skills and commands documentation describes skills as prompt-based reusable capabilities with supporting files. It notes that skills are recommended over older custom commands for many repeated workflows. It describes description-based loading, manual-only or disabled model invocation modes, tool restrictions, supporting files, shell-execution policy, overrides, and troubleshooting for skills that trigger too often or not often enough. + +The source addresses skill invocation, command/skill boundaries, progressive disclosure, tool restrictions, and description tuning. It is relevant to Truthmark’s generated Claude skill surfaces and to the distinction between command files and skill packages. The limitation is that it describes Claude Code behavior specifically. + +### Anthropic — Building effective agents + +Anthropic’s “Building effective agents” distinguishes workflows from agents: workflows follow predefined code paths, while agents dynamically direct processes and tools. It describes prompt chaining with gates, routing, parallelization, orchestrator-workers, evaluator-optimizer loops, and autonomous agents. It warns that frameworks can obscure prompts and responses and recommends starting with simple, composable patterns. + +The source addresses agent workflow patterns, gates, routing, parallelism, evaluation, tool definition, and human checkpoints. It is relevant to Truthmark’s workflow architecture because Truthmark’s workflows resemble predefined workflow surfaces more than unconstrained autonomous agents. It predates 2026 but remains influential and canonical enough to include. + +### OpenCode — Docs overview + +OpenCode’s docs describe OpenCode as an open-source terminal-based AI coding agent. They describe project rules through `AGENTS.md` and recommend committing project instructions. The overview provides host context for the more specific agents, skills, and permissions pages. + +The source addresses persistent instructions and host behavior. It is relevant to Truthmark because Truthmark generates OpenCode surfaces. Its limitation is that the overview is less detailed than the agents, skills, and permissions docs. + +### OpenCode — Agents + +OpenCode’s agents docs define primary agents and subagents. Primary agents are main workflows such as Build or Plan; subagents can be invoked automatically or manually and run as child sessions. Agent configuration can be project-local in `.opencode/agents/`. Descriptions are required and should answer what the agent does and when to use it. Agents can have prompts, models, tools, modes, and permissions. + +The source addresses agent/subagent design, routing descriptions, modes, and permissions. It is directly relevant to Truthmark’s `.opencode/agents` surfaces. Its limitation is that OpenCode’s model of subagents and permissions is host-specific. + +### OpenCode — Skills + +OpenCode’s skills docs define skills as reusable instructions loaded on demand. It supports `.opencode/skills`, compatibility with Claude-style and Agent Skills-style locations, and recognized metadata. It states that available skills are shown to the model by name and description and that a skill loader fetches the body. It also describes per-skill and per-agent permission controls. + +The source addresses skills, descriptions, progressive loading, permissions, and cross-host compatibility. It is directly relevant to Truthmark’s `.opencode/skills` surfaces. The limitation is that OpenCode frontmatter support and permission merging do not necessarily apply to other hosts. + +### OpenCode — Permissions + +OpenCode’s permissions docs define allow, ask, and deny behaviors, granular tool rules, external-directory rules, and defaults. The available permission categories include read, edit, bash, web, task, grep, glob, list, and others. + +The source addresses tool permissions, least privilege, write boundaries, and host-level enforcement. It is directly relevant to Truthmark’s OpenCode agent surfaces. The limitation is that static host permissions cannot represent every runtime workflow constraint. + +### Agent Skills specification + +The Agent Skills specification defines a portable skill directory structure. It requires `SKILL.md` and supports frontmatter fields such as name, description, license, compatibility, metadata, and experimental allowed tools. It defines scripts, references, assets, progressive disclosure, and validation with a reference tool. + +The source addresses skill metadata, standard format, scripts, references, and compatibility. It is relevant to Truthmark’s cross-host skill comparisons because several vendors and repositories converge around `SKILL.md`-style packages. Its limitation is that host-specific platforms may support only subsets or extensions of the spec. + +### Agent Skills repository + +The Agent Skills repository is the maintained reference repository for the open Agent Skills format. It is relevant as a current implementation and maintenance signal for the specification. It complements the spec by showing active development and community stewardship. + +The source addresses compatibility and standard maintenance. It is less detailed than the specification itself, but it helps establish currentness and active maintenance. + +### AGENTS.md open format + +AGENTS.md defines itself as a simple open format for guiding coding agents, comparable to a README for agents. It suggests including project overview, build/test commands, style conventions, security considerations, and nested instruction files. It describes closest-file precedence and user prompts overriding file instructions. + +The source addresses persistent repository instructions, precedence, test instructions, and living documentation. It is directly relevant to Truthmark’s managed root blocks and repository-native instruction model. Its limitation is that it intentionally has no required fields and is format-light. + +### GitHub Copilot — Customization cheat sheet + +GitHub’s Copilot customization cheat sheet compares custom instructions, prompt files, custom agents, subagents, agent skills, hooks, and MCP. It distinguishes automatic and manual usage, which surfaces are supported in which environments, and what each customization type is meant to do. + +The source addresses cross-surface taxonomy, invocation modes, repository instructions, prompts, agents, skills, and hooks. It is relevant to Truthmark’s cross-host generated surfaces. Its limitation is that it is a product comparison table, not a deep implementation standard. + +### GitHub Copilot — Repository custom instructions + +GitHub’s custom-instructions docs describe repository-wide instructions, path-specific instructions, and agent instructions. They recommend using instructions to tell Copilot how to understand the project and build, test, and validate changes. They warn that instructions should be concise and not task-specific. + +The source addresses persistent repository instructions, scope, placement, and bloat control. It is directly relevant to Truthmark’s `.github` surfaces and managed instruction blocks. Its limitation is that it focuses on GitHub Copilot behavior. + +### Gemini CLI — Custom commands + +Gemini CLI custom commands are reusable prompt shortcuts stored globally or in a project under `.gemini/commands`. Commands are TOML files with a required `prompt` and optional one-line `description`. They can include arguments, shell command execution with user confirmation, and file or directory injection. + +The source addresses command surfaces, explicit invocation, prompt reuse, shell execution, and file injection. It is relevant to Truthmark’s generated `.gemini/commands/truthmark/*.toml` files. Its limitation is that commands are not equivalent to skills or subagents. + +### Gemini CLI — Subagents announcement + +The Gemini CLI subagents announcement describes subagents as separate-context workers with custom system instructions and curated tools. It describes the main session as orchestrator, mentions parallel work and context-rot avoidance, and shows project/global Markdown agent files with YAML frontmatter including name, description, tools, and model. + +The source addresses subagent isolation, routing descriptions, project-local agent definitions, and tool scoping. It is relevant as a comparison point because Truthmark currently generates Gemini commands but not generated Gemini agents. The limitation is that it is an announcement blog rather than full reference documentation. + +### Microsoft Agent Framework — Agent Skills + +Microsoft’s Agent Skills docs define skills as portable packages of instructions, scripts, and resources. They support `SKILL.md`, scripts, references, assets, metadata, compatibility, allowed tools, and progressive disclosure. The docs also distinguish skills from workflows: skills are selected by the AI, while workflows are deterministic, checkpointed, and often involve side effects or approvals. + +The source addresses skills, progressive disclosure, scripts, security, caching, skill approval, and workflow distinction. It is strongly relevant to Truthmark’s skill-vs-workflow architecture. The limitation is Microsoft Agent Framework specificity. + +### Microsoft Agent Framework — Handoff orchestration + +Microsoft’s handoff orchestration docs describe control transfer between specialist agents. They contrast handoff with agent-as-tools patterns in terms of control flow, task ownership, and context management. They describe handoff rules, human-in-the-loop approval, checkpointing, context synchronization, tool approval, and specialized executors. + +The source addresses parent-child orchestration, specialist agents, routing rules, and tool approval. It is relevant to Truthmark’s subagent delegation context, although Truthmark’s generated host surfaces are not Microsoft Agent Framework workflows. The limitation is that it belongs to a framework rather than a coding-agent host. + +### Google ADK — Overview + +Google ADK describes an open-source framework for building, running, evaluating, and scaling agent systems. It supports predictable pipelines and agent-coordinated dynamic routing, multi-agent architectures, tools, evaluation, and local/cloud execution. + +The source addresses agent framework architecture, workflows, evaluation, and dynamic routing. It is relevant as background for how major platforms frame agent orchestration. It is less directly relevant to repository-native generated AI-host surfaces. + +### Google ADK — Multi-agent systems + +Google ADK multi-agent docs describe multi-agent hierarchies, parent-child relationships, workflow agents such as Sequential, Parallel, and Loop agents, and LLM-driven delegation. They emphasize modularity, specialization, reusability, maintainability, and clear descriptions on subagents so the parent can route tasks. + +The source addresses subagent hierarchy, workflow agents, parallel agents, descriptions, and delegation. It is relevant to Truthmark’s read-only verifier and worker subagent context. Its limitation is framework-specific execution semantics. + +### AWS Bedrock — Multi-agent collaboration + +AWS Bedrock’s multi-agent collaboration docs describe a supervisor agent and collaborator agents with designated roles, responsibilities, tools, knowledge bases, and guardrails. The supervisor routes tasks and coordinates collaborators. + +The source addresses supervisor-worker orchestration, role separation, and guardrails. It is relevant as enterprise background for multi-agent coordination. It is not specific to coding agents, Git repositories, SKILL.md packages, or host-generated workflow surfaces. + +### LangGraph overview + +LangGraph describes a framework and runtime for long-running, stateful agents. It emphasizes durable execution, streaming, human-in-the-loop, memory, debugging, tracing, evaluation, and deployment. It positions itself as low-level orchestration infrastructure for agents. + +The source addresses workflow durability, state, traces, evaluation, and human oversight. It is relevant as a contrasting architecture to Truthmark’s repository-native generated surfaces. Its limitation is that it centers runtime orchestration, not Git-reviewable host-specific prompt surfaces. + +### Model Context Protocol — Security Best Practices + +MCP security guidance discusses prompt injection, tool poisoning, tool shadowing, least-privilege access, human confirmation, and tool allowlists. It treats external tools and data sources as attack surfaces and recommends constraining capability exposure. + +The source addresses permissions, prompt injection, tool risk, and security boundaries. It is relevant to Truthmark’s tool/agent permission context and external-resource boundaries. Its limitation is that it is MCP-specific and not solely about coding agents. + +### NCSC — Prompt injection is not SQL injection + +The NCSC article explains prompt injection as a consequence of mixing instructions and untrusted data in LLM context. It argues that LLMs lack a reliable data/instruction boundary and recommends reducing risk and impact through deterministic safeguards, privilege reduction, logging, monitoring, and avoiding designs that cannot tolerate residual risk. + +The source addresses prompt injection, deterministic safeguards, privilege reduction, and audit logging. It is relevant to any AI workflow that reads repository content and may write files or invoke tools. Its limitation is that it is general security guidance rather than a workflow-surface implementation manual. + +### OWASP Top 10 for LLM Applications + +OWASP’s Top 10 for LLM Applications is a community security reference for LLM application risks. It covers prompt injection, sensitive information disclosure, supply-chain risks, excessive agency, and related concerns. + +The source addresses security taxonomy and risk categories. It is relevant as background for permission, tool, and reviewable-artifact discussions. It is broad and does not directly define skill or workflow structure. + +### Perplexity — Designing, Refining, and Maintaining Agent Skills + +Perplexity’s 2026 article is a detailed practitioner guide for agent skills. It defines a skill as structured context for models and environments. It describes a hub-and-spoke skill directory with `SKILL.md`, scripts, references, assets, and config. It treats the description as a routing trigger, not internal documentation. It describes progressive disclosure, index cost, loaded body cost, runtime resources, eval-first skill writing, negative examples, neighbor confusion, deterministic scripts, maintenance, and bloat control. + +The source addresses skill structure, routing, evals, scripts, maintenance, and bloat. It is highly relevant to Truthmark’s workflow skills. It is practitioner literature, not an official platform standard, but it provides unusually concrete implementation detail. + +### Goalkeeper + +Goalkeeper is an open-source practitioner repository for contract-driven autonomous goal execution in Claude Code. It uses explicit contracts with objective, non-goals, Definition of Done, validators, checkpoint cadence, rejection limits, judge mode, and diff exclusions. It demonstrates a judge-gate pattern where a fresh-context subagent checks diffs and logs after validators pass, approving or returning a structured fix list. + +The source addresses judge agents, validation, workflow gates, explicit contracts, and human escalation. It is relevant to Truthmark’s interest in verifier agents and parent-owned acceptance. It is illustrative, not a general standard. + +### Matt Pocock skills + +Matt Pocock’s skills repository is a popular practitioner collection of reusable skills for coding agents. It emphasizes small, composable skills, shared language, handoff skills, TDD skills, and adapting skills to one’s own codebase. It also discusses common agent failure modes and the role of skills in reducing verbosity and improving agent navigation. + +The source addresses practical skill packaging, prompt reuse, maintenance, and coding-agent workflow habits. It is useful as a concrete practitioner reference. It is not a formal standard and should be distinguished from official docs. + +## Literature by Topic + +### Prompt Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Prompt roles and hierarchy matter | OpenAI distinguishes system, developer, user, and assistant messages, with developer messages carrying rules and business logic. Repository instructions are another persistent layer in coding-agent systems. | OpenAI Prompt Engineering Guide; OpenAI Codex AGENTS.md Guide; GitHub custom instructions; AGENTS.md open format | +| Prompts should be structured | Markdown, XML-like tags, sections, and explicit task framing help separate instructions, data, examples, and outputs. | OpenAI Prompt Engineering Guide; Anthropic prompt engineering overview; Anthropic skill docs | +| Success criteria and evals should precede iteration | Anthropic frames prompt engineering as starting with success criteria and evals. OpenAI’s eval sources similarly treat prompt and agent changes as measurable. | Anthropic prompt engineering overview; OpenAI Agent Evals Guide; OpenAI Eval Skills; OpenAI Cookbook | +| Examples are useful but should be scoped | Anthropic and OpenAI both discuss examples as a way to shape behavior. Perplexity cautions that examples in skills should target non-obvious cases and failure modes rather than duplicating obvious instructions. | Anthropic prompt engineering overview; OpenAI Prompt Engineering Guide; Perplexity skills guide | +| Output contracts reduce ambiguity | Coding prompts and agent eval sources emphasize structured output, trace checks, report fields, validation, and defined success. | OpenAI Prompt Engineering Guide; OpenAI Agent Evals Guide; Goalkeeper | +| Prompt chaining and gates are common workflow patterns | Anthropic describes prompt chaining with gates and evaluator-optimizer loops for controlled multi-step behavior. | Anthropic Building effective agents | +| Context placement is part of prompt design | Repository instructions, skill descriptions, loaded skill bodies, references, and supporting files occupy different context layers. | OpenAI Codex Skills; Anthropic Skills; Perplexity skills guide; Microsoft Agent Skills | +| Prompt evaluation includes positive and negative behavior | Eval literature treats trigger behavior, negative controls, tool calls, handoffs, and instruction violations as measurable. | OpenAI Eval Skills; OpenAI Agent Evals Guide; Perplexity skills guide | + +### Persistent Repository Instruction Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Repository instruction files guide coding agents | AGENTS.md is described as a README-like file for agents, containing project overview, build/test commands, conventions, and security considerations. | AGENTS.md open format; OpenAI Codex AGENTS.md Guide; OpenCode docs; GitHub custom instructions | +| Local and nested precedence exists | Codex and AGENTS.md describe nested instruction files and closest-file precedence. GitHub supports repository-wide and path-specific instructions. | OpenAI Codex AGENTS.md Guide; AGENTS.md open format; GitHub custom instructions | +| Repository instructions should be concise and stable | GitHub recommends repository instructions be about project understanding, build, test, and validation, not task-specific instructions. | GitHub custom instructions; AGENTS.md open format | +| Project-level instructions can be committed | OpenCode recommends committing project rules; AGENTS.md is designed for repository use. | OpenCode docs; AGENTS.md open format | +| Persistent instructions should not absorb all workflow detail | Skill literature treats repeated procedures and detailed workflows as better placed in skills or workflow surfaces. | Anthropic Claude Code skills; Microsoft Agent Skills; Perplexity skills guide | +| Host-specific instruction files differ | GitHub recognizes `.github/copilot-instructions.md`, `.github/instructions`, `AGENTS.md`, `CLAUDE.md`, and `GEMINI.md`. Codex and OpenCode have their own discovery behavior. | GitHub custom instructions; OpenAI Codex AGENTS.md Guide; OpenCode docs | + +### Skill Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Skills are reusable context packages | Skills package instructions, resources, scripts, examples, and assets for repeated tasks. | OpenAI Codex Skills; Anthropic Agent Skills; Microsoft Agent Skills; Agent Skills specification; Perplexity skills guide | +| `SKILL.md` is a common entrypoint | Multiple sources use a directory containing `SKILL.md` as the skill entrypoint. | OpenAI Codex Skills; Anthropic Agent Skills; Microsoft Agent Skills; Agent Skills specification; OpenCode Skills | +| Descriptions are routing signals | Skill descriptions tell the model when to load or use the skill. Perplexity explicitly says descriptions are routing triggers, not internal documentation. | Anthropic skill best practices; OpenAI Codex Skills; OpenCode Skills; Perplexity skills guide; Agent Skills specification | +| Progressive disclosure is central | Skill listings expose compact metadata; full bodies and supporting files are loaded only when needed. | OpenAI Codex Skills; Anthropic Agent Skills; Microsoft Agent Skills; Perplexity skills guide | +| Skills can include scripts | Scripts are used for deterministic work, setup, validation, or repeated operations, but require security review. | OpenAI Skills shell tips; Microsoft Agent Skills; Agent Skills specification; Perplexity skills guide | +| References/assets/examples belong outside the main body when large | Larger supporting materials should be stored separately and loaded conditionally. | Anthropic skill best practices; Microsoft Agent Skills; Agent Skills specification; Perplexity skills guide | +| Skill bloat is a recurring concern | Skills impose context cost. Perplexity emphasizes index cost and body cost; Anthropic and Microsoft recommend concise bodies. | Perplexity skills guide; Anthropic skill best practices; Microsoft Agent Skills | +| Skill evals should include routing behavior | Positive examples, negative examples, forbidden loads, and neighbor confusion are part of skill evaluation. | OpenAI Eval Skills; Perplexity skills guide; Anthropic skill best practices | + +### Agent and Subagent Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Subagents are specialist workers with separate context | Claude Code, Gemini CLI, Codex, OpenCode, Google ADK, and Microsoft all describe specialist or child agents with distinct context or task ownership. | Claude Code subagents; Gemini subagents; Codex Subagents; OpenCode Agents; Google ADK multi-agent docs; Microsoft handoff orchestration | +| Descriptions guide delegation | Subagent descriptions are used by parent agents or orchestrators to decide when to delegate. | Claude Code subagents; OpenCode Agents; Gemini subagents; Google ADK multi-agent docs | +| Agents should be narrow when custom-defined | Codex recommends narrow, opinionated custom agents; Claude and OpenCode similarly frame subagents as specialists. | Codex Subagents; Claude Code subagents; OpenCode Agents | +| Parent/orchestrator roles are common | Microsoft handoff, AWS supervisor agents, Gemini orchestrator framing, and Anthropic orchestrator-worker patterns all describe parent coordination. | Microsoft handoff orchestration; AWS Bedrock multi-agent collaboration; Gemini subagents; Anthropic Building effective agents | +| Read-only or verifier roles are common patterns | Codex custom-agent examples include read-only explorers and reviewers; Goalkeeper uses a judge agent; Anthropic discusses evaluator-optimizer workflows. | Codex Subagents; Goalkeeper; Anthropic Building effective agents | +| Tool and permission boundaries matter | Claude, OpenCode, Codex, Microsoft, and MCP security docs all address tool access, approval, or least privilege. | Claude Code subagents; OpenCode Permissions; Codex Subagents; Microsoft Agent Skills; MCP Security Best Practices | +| Subagents can increase cost and complexity | Codex notes subagents consume more tokens. Anthropic recommends starting with simple composable patterns and avoiding unnecessary complexity. | Codex Subagents; Anthropic Building effective agents | + +### Workflow Implementation Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Workflows differ from agents | Anthropic distinguishes predefined workflow paths from dynamically acting agents. Microsoft distinguishes skills from deterministic workflows. | Anthropic Building effective agents; Microsoft Agent Skills | +| Workflow patterns include chaining, routing, parallelization, orchestrator-workers, and evaluator-optimizer loops | These are recurring patterns in Anthropic’s agent workflow taxonomy and in ADK workflow agents. | Anthropic Building effective agents; Google ADK multi-agent docs | +| Commands are explicit workflow surfaces | Gemini custom commands and Claude command/skill docs show prompt shortcuts as explicit workflow entrypoints. | Gemini CLI custom commands; Claude Code skills/commands | +| Host-specific surfaces differ | GitHub separates custom instructions, prompts, agents, subagents, skills, and hooks. Gemini commands differ from OpenCode/Claude/Codex skills and agents. | GitHub customization cheat sheet; Gemini CLI custom commands; OpenCode Skills; Claude Code skills | +| Deterministic or checkpointed workflows may be more appropriate than AI-selected skills for side effects | Microsoft states workflows are suited to guaranteed steps, checkpoints, side effects, and approvals. | Microsoft Agent Skills | +| Durable runtime frameworks provide contrasting patterns | LangGraph emphasizes durable execution, memory, human-in-the-loop, tracing, and deployment. | LangGraph overview | + +### Routing and Invocation Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Descriptions are routing boundaries | Skill and subagent descriptions are repeatedly used to choose whether and when to invoke a capability. | OpenAI Codex Skills; Anthropic skill best practices; OpenCode Skills; OpenCode Agents; Perplexity skills guide; Gemini subagents | +| Positive and negative examples improve routing | Perplexity recommends positive and negative examples, forbidden loads, and neighbor-confusion evals. OpenAI evals include trigger and negative-control cases. | Perplexity skills guide; OpenAI Eval Skills | +| Explicit invocation exists alongside automatic routing | Codex skills support explicit and implicit invocation; Gemini commands are explicit shortcuts; OpenCode subagents can be automatic or manual. | OpenAI Codex Skills; Gemini CLI custom commands; OpenCode Agents | +| Ambiguity should be handled as a routing problem | Literature discusses tool boundaries, description specificity, and evals for cases where one capability is close to another. | Perplexity skills guide; Anthropic skill best practices; Anthropic Building effective agents | +| Manual-only controls exist for side-effectful or risky workflows | Claude skills can disable model invocation; GitHub differentiates manual prompt files and automatic instructions. | Claude Code skills/commands; GitHub customization cheat sheet | + +### Permission and Write-Boundary Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Tool permissions should be explicit | OpenCode, Claude Code, Codex, Microsoft Agent Framework, and MCP all describe tool access or approval controls. | OpenCode Permissions; Claude Code subagents; Codex Subagents; Microsoft Agent Skills; MCP Security Best Practices | +| Least privilege is a recurring security principle | MCP security and OpenCode permission categories both support narrowing capability exposure. | MCP Security Best Practices; OpenCode Permissions | +| Approval gates exist for risky actions | OpenCode uses ask/deny/allow. Microsoft discusses script approval and tool approval. Codex discusses approvals and sandbox behavior. | OpenCode Permissions; Microsoft Agent Skills; Microsoft handoff orchestration; Codex Subagents | +| File access and external directories are security boundaries | OpenCode treats external directories explicitly; Gemini commands respect `.gitignore` and `.geminiignore` during file injection. | OpenCode Permissions; Gemini CLI custom commands | +| Static permissions do not cover all runtime intent | Platform docs define static tool/file controls. Practitioner and workflow literature additionally emphasizes task contracts, validators, judge gates, or parent review. | OpenCode Permissions; Goalkeeper; OpenAI Agent Evals Guide; Anthropic Building effective agents | +| Prompt injection risk motivates deterministic safeguards | NCSC and MCP security guidance emphasize non-LLM safeguards, privilege drops, confirmation, and audit trails. | NCSC prompt injection guidance; MCP Security Best Practices; OWASP LLM Top 10 | + +### Evaluation Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Evals should be designed before prompt/skill changes | Anthropic prompts and OpenAI eval skills both put success criteria before iteration. | Anthropic prompt engineering overview; OpenAI Eval Skills | +| Agent evals can inspect traces | OpenAI’s agent evals guide treats traces as containing model calls, tool calls, guardrails, handoffs, and actions. | OpenAI Agent Evals Guide | +| Routing evals should include positive and negative cases | Perplexity and OpenAI both discuss trigger and negative-control evals. | Perplexity skills guide; OpenAI Eval Skills | +| Output contracts are evaluable | Structured reports, JSON/YAML outputs, trace checks, and Definition-of-Done gates support evaluation. | OpenAI Agent Evals Guide; Goalkeeper; OpenAI Cookbook | +| Human feedback and judge models appear in evaluation loops | OpenAI’s agent improvement loop includes human feedback and evals. Goalkeeper uses a judge subagent after validators pass. | OpenAI Cookbook; Goalkeeper | +| Frameworks increasingly include evaluation/tracing | Google ADK, LangGraph/LangSmith, and OpenAI evals all describe tracing, evaluation, or monitoring as part of agent systems. | Google ADK overview; LangGraph overview; OpenAI Agent Evals Guide | + +### Security and Safety Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Prompt injection is a structural risk | NCSC explains that LLMs lack reliable data/instruction separation and recommends reducing risk and impact. | NCSC prompt injection guidance | +| Tool exposure increases risk | MCP security guidance discusses tool poisoning, tool shadowing, least privilege, and human confirmation. | MCP Security Best Practices | +| Skills with scripts need review and sandboxing | Microsoft and OpenAI both discuss script execution risks; Microsoft includes sandboxing, input validation, logging, and source trust. | Microsoft Agent Skills; OpenAI Skills shell tips | +| Excessive agency is a security concern | OWASP classifies excessive agency and related risks among LLM application risks. | OWASP Top 10 for LLM Applications | +| Audit trails and logs help manage risk | NCSC, Goalkeeper, LangGraph, and OpenAI eval sources all reference traces, logs, or reviewable artifacts. | NCSC prompt injection guidance; Goalkeeper; LangGraph overview; OpenAI Agent Evals Guide | +| Human confirmation remains important for risky actions | Microsoft, MCP, OpenCode, and Codex all include approval or confirmation concepts. | Microsoft Agent Skills; MCP Security Best Practices; OpenCode Permissions; Codex Subagents | + +### Maintenance Standards + +| Pattern | What the literature says | Supporting sources | +|---|---|---| +| Keep instructions concise | GitHub custom instructions, Anthropic skill guidance, and Perplexity skill guidance all warn against instruction bloat. | GitHub custom instructions; Anthropic skill best practices; Perplexity skills guide | +| Update skills based on failures and evals | Perplexity describes a maintenance flywheel from real user queries and known failures to eval-backed changes. | Perplexity skills guide | +| Avoid duplicated instructions | Skill literature favors progressive disclosure and supporting files over repeated long instructions. | Anthropic skill best practices; Microsoft Agent Skills; Perplexity skills guide | +| Repository instructions can be living documentation | AGENTS.md describes agent instructions as living documentation for build/test and conventions. | AGENTS.md open format | +| Source-of-truth and generated-surface separation appears as a recurring engineering concern | Official docs often separate configuration, instructions, skills, and commands by surface. Truthmark itself uses a manifest and generated surfaces as repository context. | GitHub customization cheat sheet; OpenCode Skills; Truthmark repository evidence | +| Stale instruction risk is implicit in currentness and precedence guidance | Codex AGENTS.md guidance includes verifying loaded instructions. Skill docs caution against time-sensitive info inside skills. | OpenAI Codex AGENTS.md Guide; Anthropic skill best practices | + +## Cross-Source Comparison + +### Prompt Structure Comparison + +| Source family | Prompt surfaces discussed | Structure emphasized | Evaluation emphasized | Notes | +|---|---|---|---|---| +| OpenAI | System/developer/user messages, Codex prompts, AGENTS.md, skills | Role hierarchy, Markdown/XML structure, coding task setup, output contracts | Agent evals, traces, graders, datasets | Strong for message hierarchy and agent eval instrumentation | +| Anthropic | Prompt engineering docs, Claude skills, Claude subagents | Clear instructions, examples, XML tags, role prompting, prompt chaining | Success criteria and evals before iteration | Strong for prompt iteration and simple workflow patterns | +| GitHub Copilot | Custom instructions, prompt files, custom agents, subagents, skills, hooks | Surface taxonomy and scope boundaries | Less detailed in seed docs; product supports hooks and agent customization | Strong cross-surface comparison | +| Gemini CLI | Custom command prompts, file injection, shell commands | Explicit command prompt, TOML fields, dynamic shell/file injection | Not central in command docs | Strong for command-style workflow surfaces | +| OpenCode | AGENTS.md rules, skills, agents | Project rules, skill descriptions, agent descriptions, permissions | Not a deep eval source in inspected docs | Strong for host-native skills/agents/permissions | +| Practitioner sources | Perplexity skills, Goalkeeper contracts, Matt Pocock skills | Skill descriptions, contracts, Definition of Done, handoff prompts | Evals, validators, judge gates | Strong concrete patterns, lower formal authority | + +### Skill Structure Comparison + +| Source | Entry structure | Metadata | Description role | Progressive disclosure | Scripts/assets | Evaluation / maintenance | +|---|---|---|---|---|---|---| +| OpenAI Codex Skills | Skill directory with `SKILL.md` | Name, description, path; host-specific listing | Used for implicit skill selection | Yes | Instructions/resources/scripts | Eval-related guidance appears in OpenAI eval and skills articles | +| Anthropic Agent Skills | Skill directory with `SKILL.md` and supporting files | Name and description required | Critical for selection among skills | Yes | Supporting files and resources | Best-practice checklist and real-usage testing | +| Agent Skills spec | Directory with `SKILL.md`, scripts, references, assets | Name, description, license, compatibility, metadata, experimental allowed tools | What/when/key terms | Yes | Scripts/references/assets/examples | Validation with reference tooling | +| OpenCode Skills | `.opencode/skills` and compatible locations | Recognized fields vary by host | Name/description displayed to model | Yes, loaded on demand | Permissions can apply to skills | Host docs focus more on loading and permissions | +| Microsoft Agent Skills | Skill folder with `SKILL.md`, scripts, references, assets | Name, description, license, compatibility, metadata, allowed tools | Advertised to agent for selection | Yes | Scripts, references, assets, config | Script approval, sandboxing, caching; skill-vs-workflow distinction | +| Perplexity | Hub-and-spoke skill directory | `SKILL.md` name/description plus supporting files | Routing trigger, not documentation | Yes, with explicit context tiers | Scripts/references/assets/config | Eval-first, maintenance flywheel, bloat budget | +| Matt Pocock skills | Practical repository of concise skill files | Varies by skill | Practical “use when” framing | Usually compact | Examples and workflows | Practitioner maintenance by adaptation | + +### Agent/Subagent Comparison + +| Source | Agent/subagent model | Delegation mechanism | Context isolation | Permission model | Reporting / acceptance | +|---|---|---|---|---|---| +| OpenCode | Primary agents and subagents | Automatic/manual subagent invocation via descriptions | Child sessions | Per-agent permissions with allow/ask/deny | Host-specific; prompt can define report | +| Claude Code | Project/user subagents | Descriptions guide delegation; subagents can be called directly | Own context, prompt, tools | Per-agent tools/permissions, hooks | Subagent returns summary/findings; parent conversation continues | +| OpenAI Codex | Subagents and custom agents | Main agent spawns specialized agents; explicit ask; parallel tasks | Separate threads/context | Inherited sandbox/approvals with overrides | Results returned to main agent; recursion capped | +| Gemini CLI | Custom subagent Markdown files | Auto-selected by description or invoked by name | Separate context; main session orchestrates | Curated tools per subagent | Results consolidated into main response | +| Microsoft Agent Framework | Handoff orchestration and specialized agents | Handoff rules and task ownership transfer | Context synchronization rules | Tool approval and HITL approval | Handoff, checkpointing, and specialized executor behavior | +| Google ADK | Parent-child multi-agent hierarchy | Parent instruction and subagent descriptions | Agent hierarchy and workflow agents | Framework tools and orchestration | Framework-dependent | +| AWS Bedrock | Supervisor/collaborator agents | Supervisor routes tasks | Collaborator roles and tools | Guardrails, action groups, knowledge bases | Supervisor coordinates responses | +| Goalkeeper | Judge subagent pattern | Validator pass triggers judge | Fresh independent context | Claude Code environment-dependent | Judge approves/rejects against Definition of Done | + +### Workflow Surface Comparison + +| Surface family | Typical files/surfaces | Invocation mode | Strength | Limitation | +|---|---|---|---|---| +| OpenCode | `AGENTS.md`, `.opencode/skills`, `.opencode/agents` | Automatic or manual depending on skill/agent description | Rich skills/agents/permissions | Host-specific permission semantics | +| Claude Code | `CLAUDE.md`, `.claude/skills`, `.claude/agents`, commands/hooks | Automatic skill loading, direct subagent calls, hooks | Strong skill/subagent ecosystem | Claude-specific frontmatter and tools | +| Codex | `AGENTS.md`, `.codex/skills`, `.codex/agents` | AGENTS.md auto-read; skills explicit/implicit; subagents explicit | Strong repository instruction and skill model | Codex-specific sandbox/approval model | +| GitHub Copilot | Custom instructions, prompt files, custom agents, subagents, skills, hooks | Mixed automatic/manual | Clear taxonomy across customization surfaces | Feature availability varies by environment | +| Gemini CLI | `.gemini/commands`, `.gemini/agents` | Commands explicit; agents may be routed/invoked | Strong command/file injection and emerging subagents | Commands and agents are distinct; project support varies | +| Truthmark repository context | Managed root blocks, generated skills/prompts/commands/agents | Sync automatic; others explicit/manual | Manifest-owned generated surfaces | Host capability differences remain part of adapter problem | + +### Permission Model Comparison + +| Source | Tool permissions | File/write boundaries | Approval model | Security emphasis | +|---|---|---|---|---| +| OpenCode | Explicit allow/ask/deny categories | Granular edit/bash/external-directory permissions | Ask mode for selected tools/actions | Host-level least privilege | +| Claude Code | Tools and permissions per subagent; hooks | Tool selection and hooks can constrain behavior | Hooks and permission controls | Host-level controls plus subagent isolation | +| Codex | Sandbox/approval inheritance and overrides | Workspace sandbox options | Approval requests may surface from subagent activity | Sandbox and approval coordination | +| Gemini CLI commands | Shell command confirmation; file injection respects ignore rules | Command/file injection boundaries | User confirmation for shell execution | Explicit shell/file injection caution | +| Microsoft Agent Framework | Script approval, tool approval, sandboxing | Resource limits, input validation, audit logging | Approval callbacks/HITL | Production script and tool safety | +| MCP security | Tool descriptions, tool allowlists, least privilege | Tool/resource exposure constraints | Human confirmation recommended | Prompt injection/tool poisoning risks | +| Truthmark repository context | Generated host permissions plus runtime lease text | Truth docs/routing write boundaries and leased worker writes | Parent-owned diff validation in generated surfaces | Repository-reviewable write boundaries | + +### Evaluation Model Comparison + +| Source | Evaluation object | Mechanism | Positive/negative behavior | Notes | +|---|---|---|---|---| +| OpenAI Agent Evals | Agent traces, tools, handoffs, safety | Traces, graders, datasets, eval runs | Yes; wrong tool/handoff/instruction violations | Strong for trace-centered evals | +| OpenAI Eval Skills | Skills and skill-routing behavior | Prompt sets, trace checks, deterministic assertions | Yes; trigger and negative controls | Strong for skill-routing evals | +| OpenAI Cookbook | Agent harness changes | Feedback, traces, evals, validation | Yes; improvement loop | Implementation-oriented | +| Anthropic prompting | Prompts | Success criteria and eval iteration | Implied | Strong for prompt process | +| Perplexity skills | Skill loading and task performance | Positive/negative/forbidden evals, progressive loading checks | Explicit | Strong practitioner skill-eval detail | +| Goalkeeper | Autonomous workflow completion | Validator plus judge gate against Definition of Done | Reject/fix-list behavior | Illustrative judge-agent pattern | +| LangGraph/LangSmith | Agent execution | Tracing, evaluation, monitoring | Framework-dependent | Runtime-observability model | +| Microsoft Agent Framework | Skills/workflows | Script approval, caching, workflow checkpoints | Framework-dependent | Workflow-vs-skill distinction important | + +## Agreement Map + +| Pattern | Supporting sources | Area | Notes | +|---|---|---|---| +| Skills should have concise routing descriptions | OpenAI Codex Skills; Anthropic skill best practices; OpenCode Skills; Agent Skills spec; Perplexity | Skills, routing | Sources use different names but converge on description-driven selection | +| Reusable context should be separated from one-off task prompts | OpenAI skills; Anthropic skills; Microsoft Agent Skills; Perplexity | Skills, prompts | Repeated procedures become skills/resources, not ad hoc prompts | +| Persistent repository instructions should be stable and concise | AGENTS.md; OpenAI Codex AGENTS.md; GitHub custom instructions; OpenCode docs | Repository instructions | They carry project norms, build/test commands, and conventions | +| Progressive disclosure is a skill standard | OpenAI Codex Skills; Anthropic Agent Skills; Microsoft Agent Skills; Agent Skills spec; Perplexity | Skills, context management | Small metadata first, body/resources later | +| Subagents should have narrow responsibilities | Codex Subagents; Claude Code subagents; OpenCode Agents; Gemini subagents; Google ADK | Agents/subagents | Narrowness supports routing and reduces context contamination | +| Parent/orchestrator coordination is common | Anthropic orchestrator-workers; Microsoft handoff; AWS supervisor; Gemini main session; Google ADK parent agents | Workflows, agents | Sources differ on whether control transfers or remains centralized | +| Permissions should be explicit | OpenCode Permissions; Claude Code subagents; Codex Subagents; Microsoft Agent Skills; MCP security | Permissions/security | Permission models vary by host but least privilege recurs | +| Eval suites should include negative behavior | OpenAI Eval Skills; Perplexity; OpenAI Agent Evals | Evaluation, routing | Negative controls and forbidden invocations are repeated patterns | +| Tool and script execution are security-sensitive | Microsoft Agent Skills; OpenAI Skills shell tips; MCP security; NCSC | Security, skills | Scripted skills and tools require review, sandboxing, or confirmation | +| Workflow and skill are not identical concepts | Microsoft Agent Skills; Anthropic Building effective agents; GitHub customization cheat sheet | Workflow implementation | Skills are often agent-selected; workflows can be deterministic/checkpointed | +| Human review or confirmation remains relevant for risky actions | Microsoft, MCP, OpenCode, Codex, Goalkeeper | Permissions, evaluation, safety | Sources differ on how much is manual versus automated | +| Bloat is a real maintenance risk | Anthropic skill best practices; GitHub custom instructions; Perplexity | Maintenance | Context cost is treated as a design constraint | + +## Disagreement Map + +| Topic | Source positions | Why they differ | Relevance to Truthmark | +|---|---|---|---| +| Skill format | OpenAI, Anthropic, Microsoft, OpenCode, and Agent Skills all use `SKILL.md`-style packages, but supported metadata and paths differ | Hosts have different loaders, frontmatter fields, permission systems, and compatibility layers | Truthmark has host-specific generated skill surfaces | +| Commands versus skills | Gemini custom commands are explicit TOML prompt shortcuts; Claude docs increasingly frame repeated procedures as skills rather than commands | Command surfaces and skill loaders solve overlapping but different host problems | Truthmark uses Gemini commands and host skills/prompts elsewhere | +| Automatic versus manual invocation | Codex and OpenCode skills can be implicit or explicit; Gemini commands are explicit; GitHub surfaces differ by feature | Invocation depends on host capability and risk model | Truthmark distinguishes automatic Sync from explicit/manual workflows | +| Agent autonomy | Anthropic recommends simple workflows first; LangGraph supports long-running stateful agents; Microsoft supports handoff orchestration | Frameworks target different complexity and deployment settings | Truthmark’s repository-native surfaces are different from durable runtime agents | +| Parent-owned versus handoff ownership | Microsoft handoff transfers control; Gemini describes main session orchestration; Anthropic includes orchestrator-workers; Codex subagents report back | Multi-agent systems differ on whether task ownership moves or remains centralized | Truthmark’s generated surfaces describe parent-owned final acceptance | +| Static permissions versus runtime intent | OpenCode, Claude, Codex, and Microsoft define static or approval-based controls; practitioner systems use contracts/judges; Truthmark research uses leases | Static tools can constrain capability but cannot fully encode task-specific intent | Truthmark’s write lease pattern is a local design pattern adjacent to external permission literature | +| Prompt verbosity | Anthropic and GitHub emphasize concise instructions; Perplexity allows larger loaded skill bodies but warns about context tax; OpenAI discusses context budgeting | Different surfaces have different context budgets and loading semantics | Truthmark’s generated surfaces must balance route visibility and bloat | +| Cross-host parity | GitHub offers a broad taxonomy; OpenCode/Claude/Codex/Gemini implement different mechanics | Host ecosystems are not identical | Truthmark maps one protocol into multiple host surfaces | + +## Truthmark Relevance Map + +| Truthmark area | Relevant literature | What the literature discusses | Why it may matter | +|---|---|---|---| +| Truth Sync | OpenAI evals; Anthropic workflow gates; Microsoft workflow distinction; OpenCode/Codex/Claude skills | Automatic or implicit workflows, report contracts, gates, skill invocation, verification | Literature discusses how repeated side-effectful procedures can be structured, invoked, and evaluated | +| Truth Structure | Anthropic routing workflows; Perplexity neighbor-confusion evals; OpenAI skill routing evals | Routing, negative cases, adjacent workflow confusion, structure repair | Literature suggests topology/routing workflows are sensitive to boundary definitions | +| Truth Document | Skill descriptions; progressive disclosure; evidence and output contracts | Documentation workflows, skill bodies, evidence requirements, report outputs | Literature provides patterns for implementing documentation procedures as loaded context | +| Truth Realize | Workflow-vs-skill distinction; prompt chaining; coding-agent prompts | Doc-first implementation, code-writing prompts, verification loops | Literature discusses code-writing workflows and testing/validation patterns | +| Truth Check | Agent evals; judge agents; security review; workflow audits | Audit/check workflows, traces, judge gates, validation, report contracts | Literature provides adjacent patterns for review-only or verification workflows | +| Workflow manifest | Microsoft workflow distinction; Anthropic workflow patterns; Google ADK workflow agents | Source structures for workflows, routing, gates, and orchestration | Literature provides context for treating workflows as structured entities rather than ad hoc prompts | +| Generated workflow surfaces | GitHub customization taxonomy; OpenCode/Claude/Codex/Gemini surfaces | Host-specific instructions, skills, prompts, commands, agents | Literature shows that different hosts expose different but overlapping customization surfaces | +| Skills | OpenAI Codex Skills; Anthropic Skills; OpenCode Skills; Agent Skills spec; Microsoft Skills; Perplexity | `SKILL.md`, metadata, description routing, progressive disclosure, scripts, references | Directly maps to generated host skills and skill-like workflow packages | +| Read-only verifier agents | Codex read-only examples; Claude subagents; Goalkeeper judge; OpenAI evals | Specialist verifiers, reviewers, judge agents, fresh-context review | Literature discusses verifier/reviewer roles as a recurring subagent pattern | +| Proposed write-capable OpenCode subagents | OpenCode permissions; Microsoft script/tool approval; NCSC/MCP security; Goalkeeper contracts | Tool permissions, write boundaries, approval, contracts, validation, parent review | Literature provides adjacent evidence for permissioning and validating delegated writes | +| Cross-host adapters | GitHub taxonomy; OpenCode, Codex, Claude, Gemini docs | Platform differences in skills, agents, prompts, commands, permissions | Literature clarifies why host-specific adapters may not be mechanically identical | +| Tests | OpenAI evals; Perplexity evals; Anthropic prompt eval process; Goalkeeper validator/judge | Routing evals, negative controls, traces, validators, judge gates | Literature gives evaluation categories for later test design | + +## Candidate Implementation Patterns Found in the Literature + +This section lists implementation patterns found in the literature. It does not state whether Truthmark should adopt them. + +| Pattern | Source support | Description | Potential relevance to Truthmark | Caveats | +|---|---|---|---|---| +| Source-of-truth manifest rendered into host surfaces | Truthmark repository context; GitHub customization taxonomy; framework config patterns | A central structured definition generates host-specific instructions, prompts, commands, skills, and agents | Truthmark already uses a typed workflow manifest and renderers | External sources usually do not prescribe Truthmark’s exact manifest pattern | +| Narrow skill descriptions used as routing boundaries | OpenAI Codex Skills; Anthropic skill best practices; OpenCode Skills; Perplexity | Descriptions tell the model when to invoke a skill and when not to | Relevant to workflow-skill routing descriptions | Hosts differ on how descriptions are surfaced to the model | +| Progressive disclosure | OpenAI, Anthropic, Microsoft, Agent Skills spec, Perplexity | Skill metadata is shown first; full instructions and resources are loaded only when needed | Relevant to managing workflow-surface size | Some hosts have different loaders or no direct skill equivalent | +| Read-only verifier subagents | Codex examples; Claude subagents; Goalkeeper; Anthropic evaluator-optimizer | Specialist workers inspect evidence and return findings without writing | Relevant to route auditors, claim verifiers, and doc reviewers | “Read-only” may require both prompt instructions and host permissions | +| Judge-gate pattern | Goalkeeper; Anthropic evaluator-optimizer; OpenAI evals | A fresh-context reviewer checks completion against a contract after validators pass | Relevant to workflow check or acceptance research | Practitioner pattern; not a formal standard | +| Parent-owned final acceptance | Gemini orchestrator framing; Codex main-agent result collection; Microsoft orchestration; Truthmark repository context | Parent/orchestrator receives subagent results and coordinates final output | Relevant to parent/subagent workflow design | Microsoft handoff can transfer task ownership, so not universal | +| Leased write-capable worker | Truthmark research/context; OpenCode permissions; Microsoft approval; NCSC/MCP least privilege | A worker receives task-specific allowed writes and parent validates actual diff | Relevant to proposed and current write-capable Truthmark workers | “Write lease” is a Truthmark-local term, not a broad external standard | +| Positive and negative routing evals | OpenAI Eval Skills; Perplexity | Eval sets include prompts that should and should not trigger a skill or workflow | Relevant to workflow routing tests | Requires model-based or prompt-simulation harness design | +| Permission allowlists and denylists | OpenCode Permissions; MCP security; Microsoft Agent Skills | Tools, files, external directories, and scripts are constrained by explicit rules | Relevant to generated agent permissions | Static allowlists may not encode all workflow intent | +| Explicit command surfaces | Gemini custom commands; Claude commands/skills; GitHub prompt files | Commands or prompt files provide manual workflow entrypoints | Relevant to manual Truthmark workflows | Commands differ from skills and subagents | +| Workflow gates | Anthropic prompt chaining gates; Goalkeeper validators/judge; Truthmark gates | A workflow pauses, routes, or rejects based on intermediate checks | Relevant to Truthmark’s shared gates | Gate semantics vary by system | +| Trace-centered evaluation | OpenAI Agent Evals; LangGraph/LangSmith | Agent runs are evaluated through traces, tool calls, handoffs, and outcomes | Relevant to future workflow eval design | Truthmark’s local Git/test model may use different artifacts | + +## Open Questions for Future Truthmark Design + +The literature raises several questions that are not fully answered for this repository: + +1. How much cross-host parity is realistic when Codex, OpenCode, Claude, GitHub Copilot, and Gemini expose different instruction, skill, command, agent, and permission primitives? + +2. What belongs in a workflow surface versus a reusable skill when a host treats skills as model-selected context packages but Truthmark treats workflows as behavior-bearing protocol surfaces? + +3. How should workflow descriptions be tested as routing boundaries across hosts with different loaders and invocation semantics? + +4. What is the appropriate balance between deterministic tests, prompt-style evals, trace-based evals, and model-judge evals for repository-native workflows? + +5. Which workflow behaviors should be automatic, explicit, or conditionally invoked by a parent workflow? + +6. How should write-capable subagents be validated when host permissions are static but workflow intent is runtime-specific? + +7. Should write-capable subagents remain host-specific first, or should all generated hosts expose equivalent workers only when host capabilities match? + +8. How should parent workflows validate subagent edits: report schema, Git diff, file allowlist, semantic evidence, tests, or a combination? + +9. How should stale generated surfaces be detected when a manifest, renderer, README, truth docs, and host surfaces may drift? + +10. Which discovered failure modes should become examples, which should become manifest fields, which should become tests, and which should be left as operator judgment? + +11. How much context should be placed in root managed instructions versus generated workflow surfaces versus supporting files? + +12. How should security guidance from prompt injection, MCP tool safety, and LLM excessive-agency literature be adapted to local repository-writing agents? + +## Appendix A: Source Notes + +### OpenAI source notes + +- Prompt Engineering Guide: official OpenAI docs; useful for role hierarchy, structured prompts, coding prompt examples, output contracts, and context placement. +- Codex AGENTS.md Guide: official Codex docs; useful for repository instruction discovery, global/project/nested instruction precedence, and instruction size constraints. +- Codex Skills: official Codex docs; useful for skill directory structure, `SKILL.md`, progressive disclosure, implicit and explicit invocation. +- Codex Subagents: official Codex docs; useful for custom agents, narrow subagents, inherited sandbox/approvals, recursion limits, and parallel work. +- Eval Skills: 2026 OpenAI blog; useful for eval-first skills, trigger evals, negative controls, and deterministic trace checks. +- Skills Shell Tips: 2026 OpenAI blog; useful for description-as-routing, shell scripts, deterministic workflows, and tool/security cautions. +- Skills Agents SDK: 2026 OpenAI blog; useful for repository-local skills, AGENTS.md, deterministic scripts, and CI workflows. +- Agent Evals Guide: official docs; useful for traces, graders, datasets, tool-call checks, handoff checks, and safety checks. +- Agent Improvement Loop Cookbook: 2026 OpenAI cookbook; useful for harness-change loops using traces, feedback, evals, routing, and output validation. + +### Anthropic source notes + +- Prompt engineering overview: useful for success criteria, evals, clarity, examples, XML tags, and prompt chaining. +- Agent Skills overview: useful for skills as filesystem capabilities, progressive disclosure, `SKILL.md`, metadata, and security considerations. +- Skill authoring best practices: useful for description specificity, body-size guidance, examples, evals, and maintenance checklist. +- Claude Code subagents: useful for separate context, prompt, tools, permissions, description-based delegation, and parent/subagent boundaries. +- Claude Code skills/commands: useful for skill loading, supporting files, manual-only modes, tool restrictions, and troubleshooting over-triggering. +- Building effective agents: useful for workflow/agent distinction, prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer, and tool design. + +### OpenCode source notes + +- OpenCode docs overview: useful for project `AGENTS.md` and host context. +- Agents docs: useful for primary agents, subagents, automatic/manual invocation, child sessions, project-local agent files, descriptions, prompts, modes, and permissions. +- Skills docs: useful for skill paths, recognized metadata, name/description listing, loader behavior, and per-skill/per-agent permissions. +- Permissions docs: useful for allow/ask/deny behavior, granular rules, external directory handling, and permission categories. + +### Agent Skills and AGENTS.md source notes + +- Agent Skills specification: useful for portable `SKILL.md`, metadata, scripts, references, assets, examples, progressive disclosure, and validation. +- Agent Skills repository: useful as active reference implementation and currentness signal. +- AGENTS.md open format: useful for persistent repository instructions, build/test conventions, nested files, closest-file precedence, and living documentation. + +### GitHub source notes + +- Copilot customization cheat sheet: useful as a taxonomy across custom instructions, prompt files, custom agents, subagents, skills, hooks, and MCP. +- Repository custom instructions docs: useful for repository-wide, path-specific, and agent instructions, including what belongs in persistent instructions. + +### Google and Gemini source notes + +- Gemini CLI custom commands: useful for explicit command surfaces, TOML fields, project/global placement, arguments, shell confirmation, and file injection. +- Gemini CLI subagents announcement: useful for separate-context subagents, project/global Markdown agent files, descriptions, tools, models, and main-session orchestration. +- Google ADK overview: useful for agent framework design, predictable pipelines, dynamic routing, multi-agent systems, tools, and evaluation. +- Google ADK multi-agent systems: useful for parent-child hierarchy, workflow agents, parallel agents, and LLM-driven delegation. + +### Microsoft and AWS source notes + +- Microsoft Agent Skills: useful for skill package structure, metadata, progressive disclosure, script security, script approval, caching, and the distinction between skills and workflows. +- Microsoft handoff orchestration: useful for specialist agents, handoff rules, task ownership, context synchronization, approval, and checkpointing. +- AWS Bedrock multi-agent collaboration: useful for supervisor/collaborator roles, responsibilities, guardrails, and task routing. + +### Framework, security, and practitioner source notes + +- LangGraph overview: useful as a contrasting runtime-oriented architecture for durable, stateful agents with HITL, memory, tracing, and evaluation. +- MCP security best practices: useful for tool safety, tool poisoning, prompt injection, least privilege, and human confirmation. +- NCSC prompt injection guidance: useful for structural security framing and deterministic safeguards. +- OWASP Top 10 for LLM Applications: useful as broad security taxonomy. +- Perplexity skills guide: useful for skill descriptions, progressive disclosure, scripts, eval-first design, maintenance, bloat, and neighbor-confusion evals. +- Goalkeeper: useful for contract-driven workflow execution, validator-plus-judge gates, fresh-context review, and structured fix lists. +- Matt Pocock skills: useful as an illustrative skill repository with small reusable skills, handoff patterns, TDD patterns, and practical agent workflow examples. + +## Appendix B: Repository Evidence Notes + +### Files inspected + +- [README.md](https://github.com/merlinhu1/truthmark/tree/subagent-improvement) +- [AGENTS.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/AGENTS.md) +- [CLAUDE.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/CLAUDE.md) +- [GEMINI.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/GEMINI.md) +- [FutureVision.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/FutureVision.md) +- [research/2026-05-15-agent-skills-workflow-review.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-15-agent-skills-workflow-review.md) +- [research/2026-05-16-write-capable-opencode-subagents-design.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-16-write-capable-opencode-subagents-design.md) +- [docs/truth/workflows/overview.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/overview.md) +- [docs/truth/workflows/shared-gates.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/shared-gates.md) +- [docs/truthmark/areas.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truthmark/areas.md) +- [src/agents/workflow-manifest.ts](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts) +- [src/agents/instructions.ts](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/instructions.ts) +- [src/templates/workflow-surfaces.ts](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts) +- [src/templates/generated-surfaces.ts](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts) +- [.opencode/skills/truthmark-sync/SKILL.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/skills/truthmark-sync/SKILL.md) +- [.opencode/skills/truthmark-document/SKILL.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/skills/truthmark-document/SKILL.md) +- [.opencode/agents/truth-doc-writer.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/agents/truth-doc-writer.md) +- [.opencode/agents/truth-route-auditor.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/agents/truth-route-auditor.md) +- [.codex/skills/truthmark-sync/SKILL.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.codex/skills/truthmark-sync/SKILL.md) +- [.codex/agents/truth-doc-writer.toml](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.codex/agents/truth-doc-writer.toml) +- [.claude/skills/truthmark-sync/SKILL.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.claude/skills/truthmark-sync/SKILL.md) +- [.claude/agents/truth-doc-writer.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.claude/agents/truth-doc-writer.md) +- [.github/prompts/truthmark-sync.prompt.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.github/prompts/truthmark-sync.prompt.md) +- [.github/agents/truth-doc-writer.agent.md](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.github/agents/truth-doc-writer.agent.md) +- [.gemini/commands/truthmark/sync.toml](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.gemini/commands/truthmark/sync.toml) + +### Repository observations + +- Truthmark installs repository-native workflow surfaces for several AI hosts. +- The workflow inventory is Sync, Structure, Document, Realize, and Check. +- Truth Sync is described as the only automatic finish-time workflow. +- The typed workflow manifest is the central source of workflow metadata. +- Generated workflow descriptions are used as routing triggers. +- Detailed procedures, write boundaries, report contracts, and invocation rules live in generated surfaces. +- Host surfaces include skills, prompts, commands, managed instruction blocks, and agents depending on host. +- Current generated surfaces include read-only verifiers plus leased `truth-doc-writer` agents where hosts support agents. +- Gemini generated surfaces in the inspected branch are command files rather than generated Gemini subagents. +- The research folder contains non-canonical design references and should not be treated as behavior-bearing unless promoted. +- The write-capable OpenCode subagents research file proposes a broader write-worker design, while the current promoted worker in source/generated surfaces is the doc writer. + +## Appendix C: Search Queries Used + +- `OpenCode skills agents permissions docs` +- `OpenCode AGENTS.md project rules skills subagents permissions` +- `OpenAI Codex skills AGENTS.md subagents docs` +- `OpenAI agent evals traces graders handoffs` +- `OpenAI skills shell tips description routing` +- `Anthropic agent skills best practices description progressive disclosure` +- `Claude Code subagents tools permissions description` +- `Claude Code skills slash commands supporting files` +- `Anthropic building effective agents workflows routing parallelization` +- `Agent Skills specification SKILL.md scripts references assets` +- `AGENTS.md open format coding agents` +- `GitHub Copilot custom instructions prompt files custom agents skills hooks` +- `Gemini CLI custom commands file injection shell commands` +- `Gemini CLI subagents separate context tools description` +- `Microsoft Agent Framework skills workflows scripts security` +- `Microsoft Agent Framework handoff orchestration tool approval` +- `Google ADK multi-agent systems parent child workflow agents` +- `AWS Bedrock multi-agent collaboration supervisor collaborator` +- `LangGraph durable execution human in the loop tracing evaluation` +- `MCP security best practices prompt injection tool poisoning least privilege` +- `NCSC prompt injection is not SQL injection` +- `Perplexity designing refining maintaining agent skills` +- `Goalkeeper judge gate Claude Code subagent Definition of Done` +- `Matt Pocock skills AI agents repository` + +## Appendix D: Terminology + +| Term | Meaning in this review | +|---|---| +| Prompt | Instructions or context given to a model for a specific interaction, task, workflow, or capability. | +| System prompt | Highest-level model instruction layer in systems that expose system messages. | +| Developer instruction | Instruction layer used by some platforms for durable behavior, rules, tool policy, or application logic. | +| Repository instruction | A project-local instruction file such as `AGENTS.md`, `CLAUDE.md`, `GEMINI.md`, or Copilot custom instructions. | +| Skill | A reusable context package, often containing `SKILL.md`, metadata, instructions, scripts, references, assets, or examples. | +| Agent | A model-driven actor with instructions, tools, context, and possibly state or permissions. | +| Subagent | A specialized child or delegated agent, often with separate context, narrower tools, and a specific purpose. | +| Workflow | A repeatable process with invocation criteria, steps, gates, write boundaries, verification, and output/report expectations. | +| Command | A named prompt shortcut or explicit entrypoint, often host-specific, such as a Gemini CLI command. | +| Routing trigger | Text or metadata that helps a model or orchestrator decide when to invoke a prompt, skill, command, workflow, or subagent. | +| Negative trigger | A condition or example indicating when a capability should not be invoked. | +| Forbidden adjacency | A neighboring task or workflow that is easy to confuse with the current one and should be explicitly distinguished. | +| Permission | A host or framework control that constrains tools, files, commands, network access, or approvals. | +| Write boundary | A rule limiting what files, directories, or artifacts may be edited by a workflow or agent. | +| Eval | A test or assessment of model, prompt, skill, agent, routing, tool-use, report, or workflow behavior. | +| Generated surface | A host-specific file or prompt surface generated from a source definition, such as a skill, prompt, command, agent file, or managed instruction block. | +| Source of truth | The canonical repository file or structured definition from which behavior-bearing generated surfaces or documentation derive. | diff --git a/research/prompt-skill-agent-workflow-quality-uplift-review.md b/research/prompt-skill-agent-workflow-quality-uplift-review.md new file mode 100644 index 0000000..2cc1e5a --- /dev/null +++ b/research/prompt-skill-agent-workflow-quality-uplift-review.md @@ -0,0 +1,1180 @@ +# Truthmark Prompt, Skill, Agent, and Workflow Quality Uplift Review + +Intended commit path: `research/prompt-skill-agent-workflow-quality-uplift-review.md` + +## Status + +This document is a research and recommendation reference. It is not canonical Truthmark behavior. + +It does not by itself change Truthmark workflows, generated surfaces, skills, agents, tests, repository rules, or implementation policy. Any behavior-bearing recommendation must be promoted into canonical truth docs, the typed workflow manifest, renderers, generated host surfaces, and tests before it becomes Truthmark behavior. + +This review is based on: + +- the current repository branch: `subagent-improvement`; +- the current Truthmark research folder; +- the current generated host surfaces; +- the literature review corpus on prompt standards, skills, agents/subagents, workflow implementation, permissions, routing, evaluation, security, and maintenance. + +## Direct Confidence Answer + +### Can this review be 100% confident that Truthmark’s prompt, skill, subagent, and workflow quality are world-class? + +No. + +The repository shows a strong architecture: repository-native workflow surfaces, a typed workflow manifest, generated host adapters, compact managed instruction blocks, workflow write boundaries, read-only verifier subagents, and a leased write-capable `truth-doc-writer`. + +That is strong structural evidence. + +It is not enough for 100% confidence in world-class runtime behavior. World-class quality for agentic systems requires empirical evidence from routing evals, negative-trigger evals, report-contract evals, permission regression tests, cross-host conformance tests, stale-surface detection, and live or simulated model-behavior tests. The current repository has meaningful deterministic tests, but the inspected branch does not yet show a complete prompt-style evaluation suite for workflow routing, subagent delegation, off-lease behavior, report compliance, and cross-host behavior. + +### Is Truthmark following best practice or using the most practical solution for this project? + +Mostly yes at the architectural level. + +Truthmark’s most important design choices align with recurring best-practice patterns in the literature: + +- repository-native, Git-reviewable truth rather than private model memory; +- compact root instructions rather than bloated always-on prompts; +- source-of-truth manifest rendered into host-specific surfaces; +- descriptions treated as routing boundaries; +- explicit positive, negative, and forbidden-adjacent routing cases; +- only one automatic finish-time workflow; +- read-only verifier subagents; +- leased write-capable subagents with parent-owned final acceptance; +- generated host surfaces instead of hand-edited prompt sprawl. + +The practical solution is broadly appropriate for this project because Truthmark is a repository protocol, not a cloud orchestration platform or runtime agent framework. + +However, “following the right architecture” is different from “proved world-class.” The project still needs stronger empirical evidence, schema validation, cross-host conformance checks, prompt-style evals, and explicit delegation policy. + +### Can this review be 100% confident in subagent and workflow performance/reliability? + +No. + +The current subagent and workflow design is promising and unusually disciplined, but reliability cannot be claimed at 100% without measured behavior. Subagents are especially sensitive to routing, host-specific permission semantics, context isolation, report compliance, and parent validation. The literature consistently treats these as eval and guardrail problems, not as problems solved by prompt text alone. + +A more defensible confidence statement is: + +| Area | Structural confidence | Empirical runtime confidence | Reason | +|---|---:|---:|---| +| Root managed instructions | High | Medium | Compact and generated, but still need drift/stale-surface checks across docs and hosts. | +| Workflow manifest | High | Medium | Strong typed metadata and tests; behavior still depends on generated prompt interpretation. | +| Generated skills/prompts/commands | Medium-high | Medium-low | Strong boundaries; limited evidence of prompt-style routing evals across hosts/models. | +| Read-only verifier subagents | Medium-high | Medium | Narrow and constrained; need output-schema and delegation evals. | +| Write-capable `truth-doc-writer` | Medium-high design confidence | Medium-low empirical confidence | Lease pattern is strong; runtime reliability needs parent-diff validation evals and cross-host permission conformance. | +| Cross-host workflow parity | Medium | Low-medium | Protocol is generated across hosts, but host capabilities differ materially. | + +## Scope + +This document focuses on strengthening Truthmark’s first-class product surfaces: + +- prompts; +- persistent repository instructions; +- reusable skills; +- agents and subagents; +- generated workflow surfaces; +- workflow implementation; +- routing and invocation; +- permissions and write boundaries; +- evaluation; +- security; +- maintenance; +- cross-host compatibility. + +The objective is direct actionability for Truthmark. The review does not recommend background daemons, private memory servers, remote workflow state, or non-Git-reviewable truth state. Those are treated as rejected alternatives unless explicitly scoped as external background context. + +## Repository Baseline + +### Repository-native truth protocol + +Truthmark describes itself as a local-first, Git-native truth layer for AI coding agents. The README says the intended flow is: an agent changes functional code, runs tests, and then the installed Truth Sync workflow updates mapped truth docs before the agent finishes. The README also states that Truthmark is not an MCP memory server, not a daemon, and not a prompt-history artifact. Repository evidence: [`README.md`](https://github.com/merlinhu1/truthmark/tree/subagent-improvement). + +`FutureVision.md` reinforces this architecture by rejecting memory servers, session persistence, IDE-plugin centricity, and default merge gating. It describes Truthmark as branch-scoped, committed, reviewable repository truth. Repository evidence: [`FutureVision.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/FutureVision.md). + +### Managed root instructions + +`AGENTS.md`, `CLAUDE.md`, and `GEMINI.md` contain compact managed Truthmark instruction blocks. They describe the source hierarchy, automatic Truth Sync after functional code changes, skip cases, explicit workflows, and workflow-integrity constraints. They do not contain the full workflow bodies. Repository evidence: [`AGENTS.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/AGENTS.md), [`CLAUDE.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/CLAUDE.md), [`GEMINI.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/GEMINI.md). + +### Workflow inventory + +The current workflow inventory is: + +- Truth Sync +- Truth Structure +- Truth Document +- Truth Realize +- Truth Check + +The canonical workflow overview states that workflow surfaces define invocation rules, write boundaries, report shapes, and required reads. It also states that Truth Sync is the only automatic finish-time workflow. Repository evidence: [`docs/truth/workflows/overview.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/overview.md). + +### Shared gates + +The shared gates file defines: + +- Ownership Gate; +- Product Decisions/Rationale preservation gate; +- Evidence Gate; +- Shape Repair Gate. + +It states that direct checkout evidence is authoritative and optional repository-intelligence artifacts may assist but cannot override the checkout. Repository evidence: [`docs/truth/workflows/shared-gates.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/shared-gates.md). + +### Workflow manifest + +`src/agents/workflow-manifest.ts` is the typed workflow source of truth. It defines workflow metadata, descriptions, short descriptions, default prompts, implicit invocation policy, positive triggers, negative triggers, forbidden adjacency, required gates, allowed writes, report sections, read-only subagents, and write-capable subagents. Repository evidence: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). + +### Generated host surfaces + +`src/templates/workflow-surfaces.ts` renders workflow skill bodies, subagent profiles, host permission text, report structures, and the write-capable `truth-doc-writer` lease contract. Repository evidence: [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). + +`src/templates/generated-surfaces.ts` renders host outputs for Codex, OpenCode, Claude, GitHub Copilot, and Gemini. Codex, OpenCode, Claude, and GitHub Copilot receive workflow skills/prompts and generated agents. Gemini receives command TOML files under `.gemini/commands/truthmark/`. Repository evidence: [`src/templates/generated-surfaces.ts`](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts). + +### Current agents and subagents + +Truthmark has read-only verifier subagents including route auditor, claim verifier, and doc reviewer. These are constrained to assigned shards and return findings rather than making final decisions. + +Truthmark also has a write-capable `truth-doc-writer`. It requires a parent-issued write lease, may edit only leased truth docs and routing files, must block on off-lease ambiguity, and must return a structured YAML report. The parent workflow validates the actual diff before acceptance. Repository evidence: [`.opencode/agents/truth-doc-writer.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/agents/truth-doc-writer.md), [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). + +### Research folder + +The research folder contains non-canonical design references. + +`research/2026-05-15-agent-skills-workflow-review.md` describes skills as context packages, descriptions as routing logic, progressive disclosure, and eval needs. Repository evidence: [`research/2026-05-15-agent-skills-workflow-review.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-15-agent-skills-workflow-review.md). + +`research/2026-05-16-write-capable-opencode-subagents-design.md` proposes write-capable OpenCode subagents under explicit parent-issued leases. It is non-canonical. Current source has already promoted the `truth-doc-writer` pattern beyond OpenCode to several host surfaces; broader workers such as route structurer and realize writer remain research-only ideas. Repository evidence: [`research/2026-05-16-write-capable-opencode-subagents-design.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-16-write-capable-opencode-subagents-design.md). + +### Current tests + +The inspected tests already cover meaningful deterministic behavior: + +- workflow manifest description shape, positive triggers, negative triggers, forbidden adjacency, gates, writes, report sections, and subagent assignment; +- generated init surfaces, compact root blocks, host-specific files, workflow metadata, OpenCode permissions, and no repo-root generated skill pollution; +- write-lease path acceptance/rejection; +- prompt surface boundaries for Truth Realize and related workflow behavior. + +Repository evidence: [`tests/agents/workflow-manifest.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/workflow-manifest.test.ts), [`tests/agents/write-lease.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/write-lease.test.ts), [`tests/agents/prompts.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/prompts.test.ts), [`tests/init/init.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/init/init.test.ts). + +## Literature-Derived Quality Criteria + +This section extracts standards from the reviewed literature. It is used as the comparison basis for the gap analysis. + +### Prompt quality criteria + +A high-quality coding-agent or workflow-agent prompt should: + +1. separate stable instructions from task-specific context; +2. state scope, evidence, allowed writes, forbidden writes, and output format; +3. use clear structure such as sections, Markdown, or XML-style delimiters where useful; +4. include examples when they reduce ambiguity; +5. define success criteria before iteration; +6. be evaluated against both expected and unexpected behavior; +7. avoid overloading always-on context with rarely used procedure details. + +External evidence: + +- OpenAI’s prompt engineering guide distinguishes instruction hierarchy and recommends structured prompt formats such as Markdown/XML sections and examples. Source: [OpenAI Prompt Engineering Guide](https://developers.openai.com/api/docs/guides/prompt-engineering). +- Anthropic’s prompt engineering overview says prompt work should start with clear success criteria and empirical tests. Source: [Anthropic Prompt Engineering Overview](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview). +- OpenAI’s agent evals guidance treats traces, tool calls, handoffs, and safety violations as evaluation targets. Source: [OpenAI Agent Evals Guide](https://developers.openai.com/api/docs/guides/agent-evals). + +### Persistent repository instruction quality criteria + +High-quality repository instructions should: + +1. be stable and repository-wide; +2. include build/test/validation commands and project conventions; +3. be concise; +4. avoid task-specific workflow bodies; +5. preserve local precedence and host-specific behavior; +6. point to deeper workflow surfaces instead of duplicating them. + +External evidence: + +- GitHub says repository custom instructions should help Copilot understand how to build, test, and validate the project and should not be task-specific. Source: [GitHub Copilot custom instructions](https://docs.github.com/copilot/customizing-copilot/adding-custom-instructions-for-github-copilot). +- OpenCode says project `AGENTS.md` should be committed and should cover build, lint, test, architecture, and project-specific conventions. Source: [OpenCode Rules](https://opencode.ai/docs/rules/). +- The AGENTS.md open format frames AGENTS.md as a README-like file for agents with project overview, build/test commands, code style, testing, and security notes. Source: [AGENTS.md open format](https://agents.md/). + +### Skill quality criteria + +A high-quality AI skill should: + +1. be a reusable context package, not a human manual; +2. have a concise routing description; +3. use `SKILL.md` or equivalent as a small entrypoint; +4. use progressive disclosure for references, scripts, examples, and assets; +5. keep the main body short enough to avoid context bloat; +6. include deterministic scripts only when they improve reliability; +7. treat scripts and external resources as security-sensitive; +8. include explicit trigger and non-trigger behavior; +9. be evaluated with positive, negative, forbidden-adjacent, and regression cases; +10. be maintained from observed failure modes, not by accumulating prose. + +External evidence: + +- OpenAI Codex Skills defines skills as packages of instructions/resources/scripts and says descriptions drive implicit invocation; descriptions should explain exactly when a skill should and should not trigger. Source: [OpenAI Codex Skills](https://developers.openai.com/codex/skills). +- Anthropic’s skill best practices say descriptions are critical to selection, should be specific, and skill bodies should use progressive disclosure and stay concise. Source: [Anthropic Skill Authoring Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices). +- OpenCode Skills says name and description are shown to the model and the body is loaded by a skill tool; it also supports per-skill permissions. Source: [OpenCode Skills](https://opencode.ai/docs/skills/). +- Microsoft Agent Skills defines skills as portable instructions, scripts, and resources, with progressive disclosure and script-security guidance. Source: [Microsoft Agent Skills](https://learn.microsoft.com/en-us/agent-framework/agents/skills). +- Perplexity’s skill-maintenance article treats descriptions as routing triggers, says every skill is a context tax, and recommends evals before skill changes. Source: [Perplexity, Designing, Refining, and Maintaining Agent Skills](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity). + +### Agent/subagent quality criteria + +A high-quality agent or subagent should: + +1. have one narrow responsibility; +2. have a description that functions as delegation/routing logic; +3. run with the least necessary tools; +4. isolate context where isolation improves quality; +5. return structured findings or reports; +6. avoid taking over final acceptance unless explicitly designed as a handoff system; +7. avoid write access unless the task and file boundaries are constrained; +8. avoid recursive fan-out or over-delegation without evidence; +9. preserve parent-owned orchestration when the parent must interpret policy or validate diffs. + +External evidence: + +- Claude Code subagents have separate context, prompts, tools, and permissions, and are delegated by description. Source: [Claude Code subagents](https://code.claude.com/docs/en/sub-agents). +- OpenCode agents require descriptions that say what the agent does and when to use it, and expose permissions for tools and actions. Source: [OpenCode Agents](https://opencode.ai/docs/agents/). +- OpenAI Codex subagents are specialized agents whose results are collected by the main agent; custom agents should be narrow and opinionated. Source: [OpenAI Codex Subagents](https://developers.openai.com/codex/subagents). +- Gemini CLI subagents use separate context, custom instructions, curated tools, and main-session orchestration; Google cautions that heavy code-edit subagents can conflict or overwrite each other. Source: [Google Developers Blog, Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/). +- Anthropic’s “Building effective agents” recommends simple composable patterns first, adding complexity only when measurement shows improvement. Source: [Anthropic, Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents). + +### Workflow implementation quality criteria + +A high-quality repository-native workflow should: + +1. have explicit invocation criteria; +2. have positive triggers, negative triggers, and skip cases; +3. have forbidden adjacency for easily confused workflows; +4. define allowed and forbidden writes; +5. define required reads or evidence; +6. define gates and escalation behavior; +7. define report contracts; +8. be rendered deterministically into host surfaces; +9. support stale-surface detection; +10. be tested both deterministically and with prompt-style evals. + +External evidence: + +- Anthropic distinguishes predefined workflows from dynamic agents and describes workflow patterns such as prompt chaining, routing, parallelization, orchestrator-workers, and evaluator-optimizer loops. Source: [Anthropic, Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents). +- Microsoft distinguishes skills from workflows: skills are selected by AI, while workflows are explicit deterministic paths better suited for side effects, approvals, and predictable behavior. Source: [Microsoft Agent Skills](https://learn.microsoft.com/en-us/agent-framework/agents/skills). +- GitHub’s Copilot customization cheat sheet distinguishes always-on instructions, manual prompts, custom agents, subagents, skills, hooks, and MCP by trigger mode and use case. Source: [GitHub Copilot customization cheat sheet](https://docs.github.com/en/copilot/reference/customization-cheat-sheet). + +### Permission and write-boundary quality criteria + +High-quality permission and write-boundary design should: + +1. use least privilege; +2. separate static tool permissions from runtime task intent; +3. use read-only roles when writes are not needed; +4. constrain write-capable agents by file allowlists and denylists; +5. require explicit approval or confirmation for risky actions; +6. validate actual changes against the task boundary; +7. use deterministic safeguards because prompt injection cannot be fully eliminated. + +External evidence: + +- OpenCode Permissions defines allow/ask/deny behavior and granular permission rules. Source: [OpenCode Permissions](https://opencode.ai/docs/permissions/). +- Microsoft Agent Skills recommends sandboxing, resource limits, input validation, allowlisting, and logging for scripts. Source: [Microsoft Agent Skills](https://learn.microsoft.com/en-us/agent-framework/agents/skills). +- MCP security guidance recommends least privilege, consent before execution, exact command visibility, sandboxing, and avoiding broad scopes. Source: [MCP Security Best Practices](https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices). +- NCSC explains that prompt injection does not have a reliable data/instruction boundary and recommends deterministic safeguards and privilege reduction. Source: [NCSC, Prompt injection is not SQL injection](https://www.ncsc.gov.uk/blog-post/prompt-injection-is-not-sql-injection). + +### Evaluation quality criteria + +High-quality evaluation should cover: + +1. prompt behavior; +2. skill routing; +3. positive triggers; +4. negative triggers; +5. forbidden adjacency; +6. tool use; +7. handoffs; +8. report contracts; +9. permission boundaries; +10. regression cases from real failures; +11. deterministic and model-based checks where appropriate; +12. cross-host behavior where multiple hosts are supported. + +External evidence: + +- OpenAI’s agent evals guidance uses traces, graders, datasets, and eval runs to check tools, handoffs, instructions, safety requirements, prompts, routing, and guardrails. Source: [OpenAI Agent Evals Guide](https://developers.openai.com/api/docs/guides/agent-evals). +- OpenAI’s eval-skills article recommends explicit, implicit, contextual, and negative-control eval prompts, deterministic graders, repo cleanliness checks, sandbox/permission checks, and real-failure-driven coverage. Source: [OpenAI, Evals in agentic workflows](https://developers.openai.com/blog/eval-skills). +- Perplexity recommends evals before skill creation, with positive examples, negative examples, forbidden loads, neighbor confusion, progressive-loading checks, end-to-end behavior, LLM-judge cases, and cross-model testing. Source: [Perplexity skill-maintenance article](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity). + +## Truthmark Gap Analysis + +Severity levels: + +- Critical: unsafe or invalid behavior would be likely if shipped or expanded without mitigation. +- High: likely to reduce workflow correctness, reliability, or safety in normal use. +- Medium: important quality improvement; current behavior may be acceptable but not world-class or fully proven. +- Low: useful refinement, mostly maintainability or clarity. +- Already strong: current repository aligns well with the literature. + +### Gap analysis table + +| Severity | Area | Finding | Repository evidence | External source evidence | Why it matters | +|---|---|---|---|---|---| +| Already strong | Product architecture | Truthmark is repository-native, branch-scoped, Git-reviewable, and explicitly not a private memory or daemon system. | README describes Git-native truth and explicitly says Truthmark is not an MCP memory server, daemon, or prompt-history artifact. `FutureVision.md` rejects memory servers and session persistence. Sources: [`README.md`](https://github.com/merlinhu1/truthmark/tree/subagent-improvement), [`FutureVision.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/FutureVision.md). | AGENTS.md, GitHub, and OpenCode all treat repository instruction files as committed project context. Sources: [AGENTS.md open format](https://agents.md/), [GitHub custom instructions](https://docs.github.com/copilot/customizing-copilot/adding-custom-instructions-for-github-copilot), [OpenCode Rules](https://opencode.ai/docs/rules/). | This is an appropriate foundation for a repository truth protocol and avoids hidden state. | +| Already strong | Root instruction placement | Root managed blocks are compact and route to workflow surfaces rather than embedding full procedures. | `AGENTS.md`, `CLAUDE.md`, and tests show compact managed blocks and workflow references. Sources: [`AGENTS.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/AGENTS.md), [`CLAUDE.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/CLAUDE.md), [`tests/init/init.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/init/init.test.ts). | GitHub says repository instructions should not be task-specific; Claude/OpenAI/Microsoft skill docs place detailed repeatable procedures in skills. Sources: [GitHub custom instructions](https://docs.github.com/copilot/customizing-copilot/adding-custom-instructions-for-github-copilot), [Claude Code skills](https://code.claude.com/docs/en/slash-commands), [OpenAI Codex Skills](https://developers.openai.com/codex/skills), [Microsoft Agent Skills](https://learn.microsoft.com/en-us/agent-framework/agents/skills). | Reduces always-on prompt bloat and keeps stable policy separate from workflow bodies. | +| Already strong | Manifest-owned workflow metadata | The typed manifest owns workflow ids, descriptions, triggers, negative triggers, forbidden adjacency, gates, writes, reports, and subagent assignments. | `src/agents/workflow-manifest.ts` defines these fields; manifest tests require them. Sources: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts), [`tests/agents/workflow-manifest.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/workflow-manifest.test.ts). | Skill and workflow literature repeatedly emphasizes explicit descriptions, routing, scope, and structured outputs. Sources: [OpenAI Codex Skills](https://developers.openai.com/codex/skills), [Perplexity skill-maintenance article](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity), [Anthropic Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents). | A typed manifest prevents hand-edited prompt drift and makes workflow protocol testable. | +| Already strong | Routing descriptions | Generated descriptions are explicitly treated as routing triggers, not summaries. | Workflow overview says descriptions are routing triggers; manifest tests forbid summary-like descriptions and require trigger language. Sources: [`docs/truth/workflows/overview.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/overview.md), [`tests/agents/workflow-manifest.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/workflow-manifest.test.ts). | Perplexity says skill descriptions are routing triggers; OpenAI, Anthropic, and OpenCode say descriptions drive skill/agent selection. Sources: [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity), [OpenAI Codex Skills](https://developers.openai.com/codex/skills), [Anthropic Skill Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices), [OpenCode Skills](https://opencode.ai/docs/skills/). | This is one of the most important design choices for workflow correctness. | +| Already strong | Sync-only automatic workflow | Truth Sync is the only automatic finish-time workflow; Structure, Document, Realize, and Check are explicit/manual. | Workflow overview, manifest, root blocks, and generated surfaces all state this. Sources: [`docs/truth/workflows/overview.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/overview.md), [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts), [`AGENTS.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/AGENTS.md). | Microsoft distinguishes AI-selected skills from deterministic workflows for side effects/approvals; Claude supports manual-only skill modes; GitHub distinguishes automatic and manual surfaces. Sources: [Microsoft Agent Skills](https://learn.microsoft.com/en-us/agent-framework/agents/skills), [Claude Code skills](https://code.claude.com/docs/en/slash-commands), [GitHub customization cheat sheet](https://docs.github.com/en/copilot/reference/customization-cheat-sheet). | Automatic side-effecting workflows should be narrowly scoped. Truthmark’s current automatic behavior is conservative. | +| Already strong | Read-only verifier subagents | Route auditor, claim verifier, and doc reviewer are scoped as read-only verifier agents with parent-owned decisions. | `workflow-surfaces.ts` defines read-only context boundaries and JSON report expectations. Generated host agents reflect this. Source: [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). | Claude, Codex, OpenCode, and Gemini describe subagents as specialists with separate context and tool scopes. Sources: [Claude Code subagents](https://code.claude.com/docs/en/sub-agents), [OpenAI Codex Subagents](https://developers.openai.com/codex/subagents), [OpenCode Agents](https://opencode.ai/docs/agents/), [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/). | Verifier agents are a low-risk, high-fit subagent pattern for Truthmark. | +| Already strong | Write lease concept | `truth-doc-writer` requires a parent-issued lease and parent diff validation. | `workflow-surfaces.ts`, generated doc-writer agents, and write-lease tests encode lease fields, off-lease behavior, and path validation. Sources: [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts), [`.opencode/agents/truth-doc-writer.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/agents/truth-doc-writer.md), [`tests/agents/write-lease.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/write-lease.test.ts). | OpenCode supports least-privilege permissions, Microsoft and MCP stress sandbox/allowlist controls, and NCSC stresses deterministic safeguards because prompt injection cannot be fully eliminated. Sources: [OpenCode Permissions](https://opencode.ai/docs/permissions/), [Microsoft Agent Skills](https://learn.microsoft.com/en-us/agent-framework/agents/skills), [MCP Security Best Practices](https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices), [NCSC prompt injection guidance](https://www.ncsc.gov.uk/blog-post/prompt-injection-is-not-sql-injection). | The lease model is a practical bridge between static host permissions and runtime workflow intent. | +| Critical | Future write-worker expansion | Adding `truth-route-structurer`, `truth-realize-writer`, or other write-capable workers before complete leases, conflict policy, diff validation, report schemas, and evals would be a critical risk. | The research file proposes additional write-capable workers but labels itself non-canonical. Current source promotes only `truth-doc-writer`. Sources: [`research/2026-05-16-write-capable-opencode-subagents-design.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-16-write-capable-opencode-subagents-design.md), [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). | Gemini cautions that heavy code-edit subagents can conflict or overwrite each other; Anthropic recommends adding complexity only when measurement shows improvement; NCSC recommends deterministic safeguards and privilege reduction. Sources: [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/), [Anthropic Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents), [NCSC prompt injection guidance](https://www.ncsc.gov.uk/blog-post/prompt-injection-is-not-sql-injection). | Code-writing or route-rewriting workers can create overlapping edits, hidden policy drift, and false acceptance if not strictly controlled. | +| High | Empirical prompt/workflow eval coverage | The repo has strong deterministic shape tests, but inspected evidence does not show a complete prompt-style eval suite for real workflow routing, negative prompts, forbidden adjacency, report compliance, and delegation behavior. | Tests enforce manifest shape and generated surfaces; they do not appear to exercise a broad model-facing prompt corpus. Sources: [`tests/agents/workflow-manifest.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/workflow-manifest.test.ts), [`tests/init/init.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/init/init.test.ts), [`tests/agents/prompts.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/prompts.test.ts). | OpenAI recommends explicit, implicit, contextual, and negative-control eval prompts; Perplexity recommends evals before skill changes and neighbor-confusion tests; Anthropic says prompt engineering should begin from success criteria and empirical tests. Sources: [OpenAI Eval Skills](https://developers.openai.com/blog/eval-skills), [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity), [Anthropic Prompt Engineering Overview](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview). | Without behavioral evals, prompt and routing quality cannot be claimed as world-class. | +| High | Delegation policy not fully first-class | The manifest lists subagents but does not appear to own detailed `delegateWhen`, `inlineWhen`, conflict policy, parallelism policy, or host fallback policy. | `workflow-manifest.ts` has read-only and write subagent assignment but no structured delegation-policy fields. Source: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). | Claude distinguishes when to use subagents versus the main conversation; Codex notes subagents consume more tokens; Gemini cautions about parallel code-edit conflicts; Anthropic recommends simple workflows and measured complexity. Sources: [Claude Code subagents](https://code.claude.com/docs/en/sub-agents), [OpenAI Codex Subagents](https://developers.openai.com/codex/subagents), [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/), [Anthropic Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents). | Subagent dispatch is a product behavior, not a documentation detail. It should be manifest-owned and testable. | +| High | Cross-host permission equivalence cannot be assumed | The same logical doc writer exists across several hosts, but host permission systems differ; Gemini currently has commands only. | Generated surfaces include doc writers for Codex, OpenCode, Claude, and GitHub Copilot, while Gemini receives commands. OpenCode has explicit granular permissions. Sources: [`src/templates/generated-surfaces.ts`](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts), [`.gemini/commands/truthmark/sync.toml`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.gemini/commands/truthmark/sync.toml), [`.opencode/agents/truth-doc-writer.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/agents/truth-doc-writer.md). | GitHub docs show feature support varies across surfaces; Claude states skill `allowed-tools` grants permission but does not necessarily restrict other tools; OpenCode permissions are granular but host-specific; Gemini subagents are separate from command files. Sources: [GitHub customization cheat sheet](https://docs.github.com/en/copilot/reference/customization-cheat-sheet), [Claude Code skills](https://code.claude.com/docs/en/slash-commands), [OpenCode Permissions](https://opencode.ai/docs/permissions/), [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/). | Protocol parity and permission parity are different. Truthmark should not imply identical safety across hosts without conformance evidence. | +| High | Parent diff validation is not yet proven end-to-end | The lease pattern and path validator are strong, but inspected tests do not show complete parent-orchestration simulations that compare worker reports, actual diffs, workflow status, and final acceptance. | `write-lease.test.ts` validates allowed/off-lease paths; generated prompts instruct parent diff validation. Sources: [`tests/agents/write-lease.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/write-lease.test.ts), [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). | OpenAI agent evals evaluate traces, handoffs, and violations; Goalkeeper’s judge gate inspects diff/log against a Definition of Done after validators pass. Sources: [OpenAI Agent Evals Guide](https://developers.openai.com/api/docs/guides/agent-evals), [Goalkeeper](https://github.com/itsuzef/goalkeeper). | The most important safety property for write-capable workers is acceptance based on actual diff, not self-report. | +| High | Report contracts are not fully schema-owned across all surfaces | The manifest includes report sections and generated surfaces contain report instructions, but inspected evidence does not show a complete schema validator for every workflow report and every worker report across hosts. | Manifest has `reportSections`; write worker returns YAML; Sync has structured parser references; tests check some report sections. Sources: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts), [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts), [`tests/agents/prompts.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/prompts.test.ts). | OpenAI evals and Goalkeeper both treat structured outputs and checkable definitions of done as evaluation artifacts. Sources: [OpenAI Eval Skills](https://developers.openai.com/blog/eval-skills), [OpenAI Agent Evals Guide](https://developers.openai.com/api/docs/guides/agent-evals), [Goalkeeper](https://github.com/itsuzef/goalkeeper). | Report shape is part of workflow reliability and should be machine-checkable where possible. | +| High | Stale research/canonical drift risk | The write-capable subagent research doc describes a proposed OpenCode-first direction, but current source has already promoted `truth-doc-writer` across several hosts. | Research file is non-canonical and proposes broader workers; canonical source/generated surfaces include doc writer across Codex/OpenCode/Claude/GitHub. Sources: [`research/2026-05-16-write-capable-opencode-subagents-design.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-16-write-capable-opencode-subagents-design.md), [`src/templates/generated-surfaces.ts`](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts). | Anthropic cautions against time-sensitive stale skill content; Perplexity says skill descriptions and changes need maintenance/evals because small wording changes affect routing. Sources: [Anthropic Skill Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices), [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity). | Agents may treat research as current behavior unless the canonical boundary is repeatedly clear. | +| Medium | Skill body bloat and progressive disclosure | Generated workflow skills are necessarily procedural, but the repository does not yet appear to enforce broad body-size or duplication budgets across all generated host surfaces. | Existing tests enforce compact root blocks and description length, but inspected tests do not appear to enforce skill body budget or duplicated-procedure budget across every generated skill. Sources: [`tests/init/init.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/init/init.test.ts), [`tests/agents/workflow-manifest.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/workflow-manifest.test.ts). | Anthropic recommends keeping `SKILL.md` concise and splitting details; Perplexity says every skill is a context tax; Agent Skills spec recommends progressive disclosure. Sources: [Anthropic Skill Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices), [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity), [Agent Skills Specification](https://agentskills.io/specification). | Workflow skills can become too large to route well or too expensive to load. | +| Medium | Positive/negative routing examples are manifest data but not enough by themselves | The manifest has positive, negative, and forbidden-adjacent examples, but model-facing prompt behavior needs an eval corpus. | Manifest includes these arrays and tests require them. Source: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). | OpenAI and Perplexity both recommend explicit prompt sets, negative controls, and neighbor-confusion evals. Sources: [OpenAI Eval Skills](https://developers.openai.com/blog/eval-skills), [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity). | Metadata can be correct while actual model routing still fails. | +| Medium | Gemini capability gap | Truthmark currently generates Gemini commands, while 2026 Gemini CLI also supports subagents. This is not necessarily wrong, but it is a capability difference that should remain explicit. | Gemini generated surfaces are command TOMLs under `.gemini/commands/truthmark`. Source: [`.gemini/commands/truthmark/sync.toml`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.gemini/commands/truthmark/sync.toml). | Gemini CLI supports project/global subagents under `.gemini/agents` with descriptions, tools, and separate context; Google cautions about heavy code-edit conflicts. Source: [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/). | Users may assume all hosts have the same generated subagent behavior. | +| Medium | Security standard for future scripts/assets is not yet central | Current Truthmark workflow skills appear mostly prompt-based, but literature treats future skill scripts/assets as security-sensitive. | Generated surfaces and skills exist, but the current repository does not appear to have a central skill-script security policy because scripts are not the main current pattern. Source: [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). | Microsoft recommends sandboxing, input validation, allowlisting, and audit logging for scripts; MCP and NCSC recommend least privilege and deterministic safeguards. Sources: [Microsoft Agent Skills](https://learn.microsoft.com/en-us/agent-framework/agents/skills), [MCP Security Best Practices](https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices), [NCSC prompt injection guidance](https://www.ncsc.gov.uk/blog-post/prompt-injection-is-not-sql-injection). | If future skills add scripts or assets, security rules should be explicit before expansion. | +| Medium | Cross-host conformance tests need protocol-level checks | Tests assert many generated files exist, but protocol parity across hosts should be tracked as a matrix, not only snapshots. | `init.test.ts` verifies files, metadata, and selected contents across hosts. Source: [`tests/init/init.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/init/init.test.ts). | GitHub shows host surfaces differ in automatic/manual triggers and feature support; OpenCode, Claude, Codex, and Gemini all expose different skill/agent/command semantics. Sources: [GitHub customization cheat sheet](https://docs.github.com/en/copilot/reference/customization-cheat-sheet), [OpenCode Skills](https://opencode.ai/docs/skills/), [Claude Code skills](https://code.claude.com/docs/en/slash-commands), [OpenAI Codex Skills](https://developers.openai.com/codex/skills), [Gemini custom commands](https://google-gemini.github.io/gemini-cli/docs/cli/custom-commands.html). | Host-specific differences are a first-class risk area for a cross-host protocol. | +| Low | Root managed blocks may be too compressed for human scanning | Compactness is good, but extremely compressed root blocks can be harder for humans to audit. | Root blocks are compact and tests enforce compactness. Sources: [`AGENTS.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/AGENTS.md), [`tests/init/init.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/init/init.test.ts). | GitHub recommends instructions no longer than about two pages but readable; AGENTS.md says precise agent guidance is useful. Sources: [GitHub custom instructions](https://docs.github.com/copilot/customizing-copilot/adding-custom-instructions-for-github-copilot), [AGENTS.md open format](https://agents.md/). | A small readability pass may help maintainers without increasing model context meaningfully. | +| Low | Host metadata compatibility should stay explicit | Hosts support different metadata fields and may ignore unknown fields. | Generated surfaces target different host paths and formats. Source: [`src/templates/generated-surfaces.ts`](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts). | OpenCode ignores unknown metadata fields; Agent Skills spec defines portable fields; Claude/Codex have host-specific semantics. Sources: [OpenCode Skills](https://opencode.ai/docs/skills/), [Agent Skills Specification](https://agentskills.io/specification), [Claude Code skills](https://code.claude.com/docs/en/slash-commands), [OpenAI Codex Skills](https://developers.openai.com/codex/skills). | Metadata drift is likely as host standards evolve. | + +## Workflow-by-Workflow Quality Assessment + +This section maps the literature and gap analysis to each Truthmark workflow. It is intentionally practical, because workflows are first-class product architecture in Truthmark. + +### Truth Sync + +Current role: automatic finish-time workflow after functional code/config/behavior changes. + +Repository evidence: Truth Sync is the only automatic finish-time workflow and may write canonical truth docs and routing files. Sources: [`docs/truth/workflows/overview.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/overview.md), [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). + +Literature fit: + +- Aligns with repository-native instruction patterns from AGENTS.md, GitHub, Codex, and OpenCode. +- Aligns with workflow-gate patterns from Anthropic. +- Aligns with evaluation needs from OpenAI and Perplexity. + +Quality assessment: + +| Dimension | Assessment | +|---|---| +| Routing description | Strong structurally; should be prompt-eval tested against finish-time, docs-only, and mixed changes. | +| Negative triggers | Strong in manifest; needs model-facing evals. | +| Forbidden adjacency | Strong conceptually; especially important against Structure/Document/Realize confusion. | +| Write boundary | Strong: truth docs/routing only. | +| Report contract | Present; should become schema-checked across hosts. | +| Subagent dispatch | Appropriate for route/claim verification and leased doc writing; needs manifest-owned delegation criteria. | +| Automatic/manual status | Correctly automatic only at finish time; should remain narrowly scoped. | +| Reliability confidence | Medium without behavioral evals. | + +### Truth Structure + +Current role: explicit/manual route topology and truth-doc structure repair. + +Repository evidence: Manifest defines Structure for missing/broad/misowned/stale routing and shape repair; it is not automatic. Source: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). + +Literature fit: + +- Aligns with routing/workflow boundary literature. +- Particularly sensitive to neighbor-confusion evals. + +Quality assessment: + +| Dimension | Assessment | +|---|---| +| Routing description | Strong but should be tested against Document and Sync confusion. | +| Negative triggers | Present. | +| Forbidden adjacency | Present. | +| Write boundary | Routing and starter truth docs, not functional code. | +| Report contract | Present; should be schema-checked. | +| Subagent dispatch | Route auditor is useful; write-capable route structurer should remain research-only until strict leases/evals exist. | +| Automatic/manual status | Correctly manual. | +| Reliability confidence | Medium without routing evals. | + +### Truth Document + +Current role: explicit/manual documentation of existing implemented behavior. + +Repository evidence: Manifest and generated skills distinguish Document from Sync and Realize. Source: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts), [`.opencode/skills/truthmark-document/SKILL.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/skills/truthmark-document/SKILL.md). + +Literature fit: + +- Aligns well with skill-as-context-package literature. +- Benefits from evidence-gate and claim-verifier subagents. + +Quality assessment: + +| Dimension | Assessment | +|---|---| +| Routing description | Strong, but needs prompt evals for “document existing behavior” versus “implement from docs.” | +| Negative triggers | Present. | +| Forbidden adjacency | Present. | +| Write boundary | Truth docs/routing only. | +| Report contract | Present; should be schema-checked. | +| Subagent dispatch | `truth-doc-writer` can help when leases are precise. | +| Automatic/manual status | Correctly manual. | +| Reliability confidence | Medium without prompt/e2e evals. | + +### Truth Realize + +Current role: explicit/manual implementation from truth docs into functional code. + +Repository evidence: Generated Realize surface states it is doc-first, code-only, and must not update truth docs or routing. Source: [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). + +Literature fit: + +- Aligns with prompt-chaining and workflow-vs-agent distinction. +- Highest risk if converted into write-capable worker because it edits functional code. + +Quality assessment: + +| Dimension | Assessment | +|---|---| +| Routing description | Strong; must stay distinct from Sync and Document. | +| Negative triggers | Present. | +| Forbidden adjacency | Present. | +| Write boundary | Functional code only; no truth docs/routing. | +| Report contract | Present; should be schema-checked. | +| Subagent dispatch | No write worker currently; this is conservative and appropriate. | +| Automatic/manual status | Correctly manual. | +| Reliability confidence | Medium for prompt surface; lower for any future code-writing subagent without further evals. | + +### Truth Check + +Current role: explicit/manual truth health audit. + +Repository evidence: Manifest defines Truth Check as audit/read-only and not a general code review or finish-time rewrite. Source: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). + +Literature fit: + +- Aligns with verifier/judge/eval patterns. +- Should avoid becoming a generic code-review workflow. + +Quality assessment: + +| Dimension | Assessment | +|---|---| +| Routing description | Strong; needs negative evals against general lint/code review. | +| Negative triggers | Present. | +| Forbidden adjacency | Present. | +| Write boundary | Read-only by default. | +| Report contract | Present; should be schema-checked. | +| Subagent dispatch | Read-only verifiers fit well. | +| Automatic/manual status | Correctly manual. | +| Reliability confidence | Medium without audit prompt evals and structured report validation. | + +## Recommendations + +Every recommendation below is traceable to both repository evidence and reviewed literature. + +### Ship now + +These are small, low-risk changes that improve workflow quality immediately. + +#### 1. Add this research document under `research/` + +Change: + +- Add `research/prompt-skill-agent-workflow-quality-uplift-review.md`. + +Repository evidence: + +- The research folder already contains non-canonical design references and explicitly separates research from canonical behavior. Source: [`research/2026-05-15-agent-skills-workflow-review.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-15-agent-skills-workflow-review.md). + +External evidence: + +- Perplexity and Anthropic both emphasize maintaining skill and prompt systems through observed failures, explicit evals, and current documentation. Sources: [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity), [Anthropic Skill Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices). + +Rationale: + +- This creates a traceable research artifact without changing canonical behavior. + +#### 2. Add a non-canonical-status note to the write-capable subagent research file + +Change: + +- Add a short note near the top of `research/2026-05-16-write-capable-opencode-subagents-design.md`: + - `truth-doc-writer` has been promoted into source/generated surfaces for several hosts. + - Additional workers such as `truth-route-structurer` and `truth-realize-writer` remain research-only. + - Behavior-bearing rules live in source/generated surfaces/tests, not this research file. + +Repository evidence: + +- The research file proposes write-capable OpenCode subagents, while current source/generated surfaces include `truth-doc-writer` across more hosts. Sources: [`research/2026-05-16-write-capable-opencode-subagents-design.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-16-write-capable-opencode-subagents-design.md), [`src/templates/generated-surfaces.ts`](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts). + +External evidence: + +- Anthropic cautions against stale or time-sensitive skill information; Perplexity emphasizes that skill description and behavior changes require maintenance and eval discipline. Sources: [Anthropic Skill Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices), [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity). + +#### 3. Add snapshot tests for the `truth-doc-writer` lease language across all generated agent hosts + +Change: + +- Extend init/generated-surface tests to assert that every generated `truth-doc-writer` surface includes: + - explicit parent-issued lease requirement; + - allowed write paths; + - forbidden write classes; + - off-lease block/report behavior; + - YAML report fields; + - parent actual-diff validation language. + +Repository evidence: + +- `truth-doc-writer` already has this behavior in templates and OpenCode generated surface; write-lease tests validate allowed/off-lease paths. Sources: [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts), [`.opencode/agents/truth-doc-writer.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/agents/truth-doc-writer.md), [`tests/agents/write-lease.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/write-lease.test.ts). + +External evidence: + +- OpenCode supports granular permissions; MCP and NCSC recommend least privilege and deterministic safeguards; OpenAI evals recommend permission regression checks. Sources: [OpenCode Permissions](https://opencode.ai/docs/permissions/), [MCP Security Best Practices](https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices), [NCSC prompt injection guidance](https://www.ncsc.gov.uk/blog-post/prompt-injection-is-not-sql-injection), [OpenAI Eval Skills](https://developers.openai.com/blog/eval-skills). + +#### 4. Add explicit Gemini capability language + +Change: + +- In generated Gemini commands and workflow overview, state: + - Gemini surfaces in this Truthmark version are command-only. + - They do not install generated Gemini subagents. + - The same workflow gates, write boundaries, and report expectations still apply inline. + +Repository evidence: + +- Gemini generated surfaces are TOML commands, while other hosts receive generated agents. Sources: [`.gemini/commands/truthmark/sync.toml`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.gemini/commands/truthmark/sync.toml), [`src/templates/generated-surfaces.ts`](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts). + +External evidence: + +- Gemini CLI supports both commands and subagents, but they are different surfaces. Sources: [Gemini custom commands](https://google-gemini.github.io/gemini-cli/docs/cli/custom-commands.html), [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/). + +#### 5. Add a generated-surface bloat smoke test + +Change: + +- Add deterministic limits for generated workflow descriptions, root managed blocks, and skill body size. +- Start with warnings or generous thresholds to avoid blocking useful detail too early. + +Repository evidence: + +- Current tests already enforce compact root blocks and description shape. Sources: [`tests/init/init.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/init/init.test.ts), [`tests/agents/workflow-manifest.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/workflow-manifest.test.ts). + +External evidence: + +- Anthropic recommends keeping `SKILL.md` concise; Perplexity says every skill is a context tax; Agent Skills spec recommends keeping main bodies concise and using progressive disclosure. Sources: [Anthropic Skill Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices), [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity), [Agent Skills Specification](https://agentskills.io/specification). + +#### 6. Add a deterministic check that canonical docs and generated surfaces agree on subagent inventory + +Change: + +- Add a test or `truthmark check` diagnostic comparing: + - manifest subagent assignments; + - generated host surfaces; + - workflow overview summary; + - README installed-surface summary. + +Repository evidence: + +- The repository has a source manifest, generated surfaces, and human docs that can drift. Sources: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts), [`docs/truth/workflows/overview.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/docs/truth/workflows/overview.md), [`README.md`](https://github.com/merlinhu1/truthmark/tree/subagent-improvement). + +External evidence: + +- Perplexity emphasizes skill maintenance because small text changes affect routing; OpenAI evals recommend repo cleanliness and regression checks. Sources: [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity), [OpenAI Eval Skills](https://developers.openai.com/blog/eval-skills). + +### Build next + +These are medium-sized changes requiring source, renderer, generated-surface, and test updates. + +#### 1. Add a prompt-style workflow routing eval suite + +Change: + +- Add fixtures for each workflow: + - positive explicit invocation; + - positive implicit invocation where applicable; + - contextual invocation; + - negative trigger; + - forbidden adjacency; + - skip case; + - ambiguous mixed case. + +Suggested file pattern: + +- `tests/evals/workflow-routing-cases.ts` +- `tests/evals/workflow-routing.test.ts` + +Suggested fixture shape: + +```ts +type WorkflowRoutingEvalCase = { + id: string; + userPrompt: string; + changedFiles?: string[]; + expectedWorkflow: WorkflowId | "none" | "block"; + expectedReason: string; + forbiddenWorkflows?: WorkflowId[]; + source: "manifest-positive" | "manifest-negative" | "forbidden-adjacent" | "real-failure" | "synthetic"; +}; +``` + +Repository evidence: + +- Manifest already contains positive triggers, negative triggers, and forbidden adjacency. Source: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). + +External evidence: + +- OpenAI recommends explicit, implicit, contextual, and negative-control eval prompts; Perplexity recommends positive/negative/forbidden and neighbor-confusion evals; Anthropic starts prompt engineering with success criteria/evals. Sources: [OpenAI Eval Skills](https://developers.openai.com/blog/eval-skills), [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity), [Anthropic Prompt Engineering Overview](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/overview). + +#### 2. Promote delegation policy into the workflow manifest + +Change: + +- Extend `WorkflowManifestEntry` with a structured delegation policy. + +Suggested pseudocode: + +```ts +delegationPolicy: { + delegateReadOnlyWhen: string[]; + delegateWriteWhen: string[]; + keepInlineWhen: string[]; + maxParallelReadOnlySubagents?: number; + maxParallelWriteLeases?: number; + conflictPolicy: "serialize" | "block" | "parent-only"; + parentValidationRequired: string[]; + hostFallback: { + whenSubagentsUnavailable: "inline" | "block"; + note: string; + }; +} +``` + +Repository evidence: + +- The manifest owns subagent assignments but not detailed delegation policy. Source: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). + +External evidence: + +- Claude distinguishes main-conversation versus subagent use; Codex warns subagents cost more tokens; Gemini warns about code-edit conflicts; Anthropic recommends adding complexity only when measured. Sources: [Claude Code subagents](https://code.claude.com/docs/en/sub-agents), [OpenAI Codex Subagents](https://developers.openai.com/codex/subagents), [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/), [Anthropic Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents). + +#### 3. Add workflow and worker report schemas + +Change: + +- Convert report sections into schema-like definitions for each workflow. +- Add a reusable worker YAML schema for `truth-doc-writer`. +- Add validators or snapshot tests for generated report contracts. + +Suggested pseudocode: + +```ts +type ReportField = { + key: string; + required: boolean; + type: "string" | "string[]" | "object[]" | "enum"; + enumValues?: string[]; +}; + +type WorkflowReportContract = { + workflow: WorkflowId; + requiredHeadings: string[]; + requiredFields: ReportField[]; +}; +``` + +Repository evidence: + +- Manifest has report sections and generated surfaces include report instructions. Source: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). + +External evidence: + +- OpenAI agent evals evaluate output and trace structure; Goalkeeper uses a structured Definition of Done, validator output, judge result, and fix-list. Sources: [OpenAI Agent Evals Guide](https://developers.openai.com/api/docs/guides/agent-evals), [Goalkeeper](https://github.com/itsuzef/goalkeeper). + +#### 4. Add parent/subagent orchestration tests + +Change: + +- Add deterministic simulations for: + - parent issues valid lease; + - worker returns completed YAML; + - actual diff matches lease; + - actual diff violates lease; + - worker report omits required fields; + - worker blocks on ambiguous ownership; + - parent rejects off-lease edit even if worker reports success; + - overlapping write leases are blocked or serialized. + +Repository evidence: + +- Current write-lease tests validate allowed/off-lease paths; generated surfaces state parent validation. Sources: [`tests/agents/write-lease.test.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/tests/agents/write-lease.test.ts), [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). + +External evidence: + +- OpenAI agent evals check handoffs, tools, safety violations, and routing; Goalkeeper’s judge pattern validates diff/log against an explicit contract after validators pass. Sources: [OpenAI Agent Evals Guide](https://developers.openai.com/api/docs/guides/agent-evals), [Goalkeeper](https://github.com/itsuzef/goalkeeper). + +#### 5. Add cross-host protocol conformance matrix + +Change: + +- Add a generated or tested matrix asserting for each host: + - workflow ids present; + - invocation policy present; + - routing description present; + - gates present; + - write boundaries present; + - report contract present; + - read-only agents present or explicit fallback; + - write-capable agent present or explicit fallback; + - host capability limitations documented. + +Suggested test target: + +```ts +expectHostProtocolParity({ + host: "gemini", + workflow: "truth-sync", + supportsGeneratedSubagents: false, + requiredFallbackNote: true, +}); +``` + +Repository evidence: + +- `generated-surfaces.ts` emits different host surfaces; Gemini currently receives commands only. Source: [`src/templates/generated-surfaces.ts`](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts). + +External evidence: + +- GitHub, Gemini, OpenCode, Claude, and Codex expose different customization primitives. Sources: [GitHub customization cheat sheet](https://docs.github.com/en/copilot/reference/customization-cheat-sheet), [Gemini custom commands](https://google-gemini.github.io/gemini-cli/docs/cli/custom-commands.html), [OpenCode Skills](https://opencode.ai/docs/skills/), [Claude Code skills](https://code.claude.com/docs/en/slash-commands), [OpenAI Codex Skills](https://developers.openai.com/codex/skills). + +#### 6. Add stale-surface diagnostics to `truthmark check` + +Change: + +- Extend `truthmark check` to detect: + - generated surface version mismatch; + - workflow list mismatch; + - subagent inventory mismatch; + - report section mismatch; + - generated file missing for configured host; + - manual edit to generated managed block; + - canonical docs mentioning a workflow or agent not in the manifest. + +Repository evidence: + +- `FutureVision.md` identifies stale generated surfaces and conformance tests as important V2 directions; current source has generated surfaces and version markers. Source: [`FutureVision.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/FutureVision.md). + +External evidence: + +- OpenAI eval skills recommend repo cleanliness and regression checks; Perplexity emphasizes skill maintenance and change sensitivity. Sources: [OpenAI Eval Skills](https://developers.openai.com/blog/eval-skills), [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity). + +#### 7. Add a Truthmark skill/security policy for future scripts and assets + +Change: + +- Add a canonical or generated standard stating: + - default generated skills should not include executable scripts unless needed; + - scripts must be deterministic; + - scripts must be reviewed like code; + - scripts must declare dependencies; + - scripts must not access secrets or network unless explicitly allowed; + - generated surfaces must not instruct agents to run unreviewed scripts. + +Repository evidence: + +- Current generated skills are prompt-heavy, but source templates are the natural place to enforce future skill format rules. Source: [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). + +External evidence: + +- Microsoft recommends sandboxing, input validation, allowlisting, logging, and source trust for scripts; Anthropic says skills from untrusted sources can introduce tool misuse or data exposure; MCP security emphasizes command visibility and least privilege. Sources: [Microsoft Agent Skills](https://learn.microsoft.com/en-us/agent-framework/agents/skills), [Anthropic Agent Skills Overview](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview), [MCP Security Best Practices](https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices). + +### Research further + +These ideas need examples, evals, or host-parity checks before adoption. + +#### 1. Gemini generated subagents + +Research question: + +- Should Truthmark generate `.gemini/agents/*.md` surfaces in addition to `.gemini/commands/truthmark/*.toml`? + +Repository evidence: + +- Current Gemini generated surfaces are command files. Source: [`.gemini/commands/truthmark/sync.toml`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.gemini/commands/truthmark/sync.toml). + +External evidence: + +- Gemini CLI supports subagents with project/global Markdown files, descriptions, tools, and separate context. It also cautions about conflict risk in heavy code-editing tasks. Source: [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/). + +Research criteria: + +- host permission support; +- command/agent interaction model; +- support for read-only verifiers; +- support for leased doc writer; +- generated-surface parity; +- stale-surface tests; +- conflict behavior. + +#### 2. `truth-route-structurer` + +Research question: + +- Can route/topology repair be safely delegated to a write-capable worker? + +Repository evidence: + +- The research file proposes broader write-capable workers, but source currently promotes only `truth-doc-writer`. Source: [`research/2026-05-16-write-capable-opencode-subagents-design.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/research/2026-05-16-write-capable-opencode-subagents-design.md). + +External evidence: + +- Subagent sources support specialist workers, but also emphasize narrow roles, tool restrictions, and conflict management. Sources: [Claude Code subagents](https://code.claude.com/docs/en/sub-agents), [OpenAI Codex Subagents](https://developers.openai.com/codex/subagents), [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/). + +Research criteria: + +- route-write lease; +- ownership conflict policy; +- split/merge operation schema; +- route-map report contract; +- parent validation against actual diff; +- negative evals for over-structuring. + +#### 3. `truth-realize-writer` + +Research question: + +- Can functional code realization be delegated safely, or should it remain parent-only? + +Repository evidence: + +- Truth Realize is currently explicit/manual and code-only, with no write subagent assignment. Source: [`src/agents/workflow-manifest.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/agents/workflow-manifest.ts). + +External evidence: + +- Gemini warns that heavy code-edit subagents can conflict or overwrite each other; Anthropic recommends extensive sandbox testing and guardrails for autonomous agents. Sources: [Gemini CLI subagents](https://developers.googleblog.com/subagents-have-arrived-in-gemini-cli/), [Anthropic Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents). + +Research criteria: + +- code-write lease; +- test contract; +- no truth-doc writes; +- conflict detection; +- rollback strategy; +- parent acceptance; +- stronger evals than doc writing. + +#### 4. Judge-agent or reviewer-agent acceptance patterns + +Research question: + +- Should Truthmark add a judge-style verifier for parent workflow acceptance or Truth Check? + +Repository evidence: + +- Current read-only verifier agents already exist; Truth Check is read-only/audit-oriented. Source: [`src/templates/workflow-surfaces.ts`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/src/templates/workflow-surfaces.ts). + +External evidence: + +- Goalkeeper uses a fresh-context judge after validators pass; Anthropic describes evaluator-optimizer loops; OpenAI agent evals evaluate traces and outputs. Sources: [Goalkeeper](https://github.com/itsuzef/goalkeeper), [Anthropic Building Effective Agents](https://www.anthropic.com/engineering/building-effective-agents), [OpenAI Agent Evals Guide](https://developers.openai.com/api/docs/guides/agent-evals). + +Research criteria: + +- judge input contract; +- judge output schema; +- false-positive/false-negative evals; +- whether judge is always-on, manual, or only for high-risk workflows; +- interaction with human review. + +#### 5. Cross-model and cross-host routing evals + +Research question: + +- How stable are generated workflow descriptions across Codex, Claude, OpenCode, Copilot, and Gemini? + +Repository evidence: + +- Truthmark renders host-specific surfaces from one source. Source: [`src/templates/generated-surfaces.ts`](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts). + +External evidence: + +- Perplexity recommends cross-model evals; GitHub shows host feature support varies; Anthropic says test with the models planned for use. Sources: [Perplexity](https://research.perplexity.ai/articles/designing-refining-and-maintaining-agent-skills-at-perplexity), [GitHub customization cheat sheet](https://docs.github.com/en/copilot/reference/customization-cheat-sheet), [Anthropic Skill Best Practices](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/best-practices). + +Research criteria: + +- same prompt corpus; +- same expected routing; +- host-specific output capture; +- report-shape scoring; +- model/version tracking. + +#### 6. Open Agent Skills compatibility + +Research question: + +- Should Truthmark render a host-neutral `.agents/skills` package in addition to host-specific skills? + +Repository evidence: + +- Truthmark already renders host-specific skills/prompts/commands/agents. Source: [`src/templates/generated-surfaces.ts`](https://github.com/merlinhu1/truthmark/blob/subagent-improvement/src/templates/generated-surfaces.ts). + +External evidence: + +- Agent Skills defines a portable `SKILL.md` package structure; OpenCode can read `.agents/skills`; OpenAI Codex Skills build on open Agent Skills concepts. Sources: [Agent Skills Specification](https://agentskills.io/specification), [OpenCode Skills](https://opencode.ai/docs/skills/), [OpenAI Codex Skills](https://developers.openai.com/codex/skills). + +Research criteria: + +- does it reduce duplication or add confusion; +- how host-specific metadata is represented; +- whether generated `.agents/skills` would be canonical or adapter; +- permission semantics. + +## Proposed Quality Rubric for Truthmark + +This rubric can be used to decide whether prompt, skill, agent, and workflow surfaces are approaching world-class quality. + +### Prompt quality rubric + +| Criterion | Minimum bar | World-class bar | +|---|---|---| +| Scope | States task and boundaries | States task, positive triggers, negative triggers, forbidden adjacency, and skip cases | +| Evidence | Mentions evidence | Requires source evidence and blocks/report when missing | +| Writes | Mentions allowed writes | Explicit allowed/forbidden writes with validation path | +| Output | Has report instructions | Schema-checkable report contract | +| Context placement | Uses root instructions | Places stable, workflow, skill, and reference context in separate layers | +| Evaluation | Manual review | Positive, negative, ambiguity, and regression prompt evals | + +### Skill quality rubric + +| Criterion | Minimum bar | World-class bar | +|---|---|---| +| Description | Says what skill does | Functions as routing boundary with when/not-when language | +| Body | Contains procedure | Concise body with progressive disclosure | +| Examples | Some examples | High-signal examples and negative cases only | +| Scripts | Optional scripts | Deterministic, reviewed, sandboxed scripts only | +| Maintenance | Updated ad hoc | Updated from observed failures and eval results | +| Tests | Snapshot only | Routing, load, report, and regression evals | + +### Agent/subagent quality rubric + +| Criterion | Minimum bar | World-class bar | +|---|---|---| +| Purpose | Named role | One narrow responsibility and explicit non-goals | +| Tools | Some limits | Least-privilege host permissions plus runtime constraints | +| Context | Separate prompt | Clear context boundary and assigned shard | +| Output | Text summary | Structured report with required fields | +| Writes | Prompt instruction | Static permissions plus runtime lease and parent diff validation | +| Delegation | Parent may use | Manifest-owned delegation criteria and conflict policy | + +### Workflow quality rubric + +| Criterion | Minimum bar | World-class bar | +|---|---|---| +| Invocation | User can run it | Explicit/manual/automatic policy with skip cases | +| Routing | Description exists | Positive/negative/forbidden-adjacent cases tested by evals | +| Gates | Some procedural steps | Shared gates with deterministic validation where possible | +| Writes | Described | Allowed/forbidden write contract and actual-diff checks | +| Reports | Human-readable | Schema-checkable and snapshot-tested | +| Surfaces | Generated | Cross-host protocol conformance and stale-surface diagnostics | + +## Proposed Evaluation Matrix + +| Evaluation category | Deterministic test | Prompt-style eval | Source support | +|---|---|---|---| +| Positive routing | Manifest has positive triggers; generated description includes use case | User prompt should select correct workflow | OpenAI Eval Skills; Perplexity | +| Negative routing | Manifest has negative triggers | User prompt should not trigger workflow | OpenAI Eval Skills; Perplexity | +| Forbidden adjacency | Manifest declares adjacent workflows | Mixed prompt should block or select correct workflow | Perplexity neighbor-confusion evals | +| Implicit invocation | Only Sync allows implicit invocation | Functional code change should trigger Sync at finish | GitHub/Claude/Microsoft invocation distinctions | +| Explicit invocation | Manual workflows have direct prompts | Explicit `/truthmark-*` request selects exact workflow | Gemini commands; GitHub prompt files | +| Read-only subagent dispatch | Generated agents are read-only and deny edits | Parent dispatches verifier for isolated shard | Claude/Codex/OpenCode subagents | +| Write lease acceptance | Allowed paths accepted | Worker edits leased docs only | OpenCode permissions; MCP least privilege | +| Off-lease rejection | Off-lease paths rejected | Worker self-reports success but diff violates lease | NCSC deterministic safeguards; Goalkeeper judge | +| Report compliance | Report schema validator passes/fails | Agent omits required report fields | OpenAI Agent Evals; Goalkeeper | +| Cross-host parity | Protocol matrix per host | Same scenario behaves equivalently by protocol | GitHub taxonomy; host docs | +| Stale-surface detection | Version/inventory checks | N/A | OpenAI repo cleanliness; Perplexity maintenance | +| Security checks | Permissions snapshot | Prompt injection tries to induce unauthorized write | MCP security; NCSC; OWASP | + +## Proposed OpenCode Write-Capable Subagent Standard + +This standard is intentionally stricter for OpenCode because OpenCode exposes granular permissions and is a strong proving ground for write-capable workers. + +### Allowed only when + +A write-capable OpenCode subagent is allowed only when: + +1. the active workflow permits that worker; +2. the parent can issue an exact lease; +3. the lease names exact allowed writes; +4. the lease names explicit forbidden writes; +5. the worker can complete without interpreting global policy beyond the lease; +6. the parent will inspect actual Git diff; +7. there are no overlapping write leases; +8. host permissions constrain the worker as much as the host allows. + +Repository evidence: + +- `truth-doc-writer` already follows a lease pattern. Source: [`.opencode/agents/truth-doc-writer.md`](https://raw.githubusercontent.com/merlinhu1/truthmark/subagent-improvement/.opencode/agents/truth-doc-writer.md). + +External evidence: + +- OpenCode supports granular allow/ask/deny permissions; MCP and NCSC support least privilege and deterministic safeguards. Sources: [OpenCode Permissions](https://opencode.ai/docs/permissions/), [MCP Security Best Practices](https://modelcontextprotocol.io/docs/tutorials/security/security_best_practices), [NCSC prompt injection guidance](https://www.ncsc.gov.uk/blog-post/prompt-injection-is-not-sql-injection). + +### Forbidden when + +A write-capable worker is forbidden when: + +1. ownership is ambiguous; +2. allowed writes cannot be named precisely; +3. the task requires broad functional code edits; +4. the worker would edit generated surfaces, templates, tests, package config, or repo policy without explicit lease; +5. two write leases overlap; +6. the parent cannot inspect actual diff; +7. the host cannot provide enough tool or file constraints and no deterministic fallback exists. + +### Required lease fields + +```yaml +workflow: truth-sync | truth-document | truth-structure | truth-realize | truth-check +worker: truth-doc-writer +shard: string +objective: string +requiredReads: + - path-or-glob +allowedWrites: + - path-or-glob +forbiddenWrites: + - path-or-glob +evidenceRequired: + - implementation-or-routing-evidence +verification: + - parent-validation-step +reportFields: + - status + - worker + - workflow + - shard + - filesChanged + - claimsChecked + - evidenceChecked + - offLeaseChanges + - blockers + - notes +``` + +### Required parent validation + +The parent must: + +1. read worker report; +2. inspect actual diff; +3. compare changed files against lease; +4. reject off-lease edits; +5. reject missing required report fields; +6. reject unsupported claims; +7. run applicable validation; +8. include worker result in parent-owned workflow report. + +### Required tests before additional write workers + +Before any new write-capable worker is enabled: + +- lease schema test; +- static permission snapshot; +- off-lease rejection test; +- overlapping lease test; +- worker report schema test; +- parent actual-diff validation test; +- routing/delegation prompt eval; +- cross-host fallback test; +- stale-surface check. + +## Rejected or Avoided Directions + +The following directions are attractive in some agent systems but conflict with Truthmark’s repository-native architecture or the reviewed safety literature. + +| Direction | Why to avoid | Repository evidence | Literature evidence | +|---|---|---|---| +| Background daemon orchestration | Would shift truth from Git-reviewable surfaces into hidden runtime state. | `FutureVision.md` rejects daemon/server architecture. | AGENTS.md/GitHub/OpenCode emphasize repository instruction files; NCSC recommends deterministic safeguards and auditability. | +| Private model memory as truth source | Not branch-scoped, not reviewable, and not portable across agents. | README and FutureVision reject private memory/server truth. | AGENTS.md and GitHub instructions use committed repo context. | +| Unrestricted write-capable subagents | Host permissions and prompt text are insufficient for safe writes. | Truthmark’s doc writer requires leases and parent diff validation. | OpenCode permissions, MCP, NCSC, and Microsoft all emphasize least privilege and approval/sandboxing. | +| Forced cross-host parity | Hosts expose different instruction, skill, command, and agent primitives. | Gemini currently has commands only; other hosts have agents. | GitHub taxonomy and Gemini/OpenCode/Claude/Codex docs show different capabilities. | +| Root prompt bloat | Always-on prompt context becomes expensive and harder to maintain. | Root managed blocks are compact and tested. | GitHub, Anthropic, and Perplexity all warn against bloated instructions/skills. | +| Treating research docs as behavior | Blurs non-canonical references with active protocol. | Research files state non-canonical status. | Skill-maintenance literature emphasizes stale guidance and currentness. | + +## File-Level Implementation Handoff + +Likely files to change for the “Ship now” and “Build next” items: + +### Research files + +- `research/prompt-skill-agent-workflow-quality-uplift-review.md` +- `research/2026-05-16-write-capable-opencode-subagents-design.md` + +### Canonical truth docs + +- `docs/truth/workflows/overview.md` +- `docs/truth/workflows/shared-gates.md` +- `docs/truthmark/areas.md` + +### Source + +- `src/agents/workflow-manifest.ts` +- `src/agents/instructions.ts` +- `src/templates/workflow-surfaces.ts` +- `src/templates/generated-surfaces.ts` + +### Generated OpenCode surfaces + +- `.opencode/skills/*/SKILL.md` +- `.opencode/agents/*.md` + +### Generated Codex surfaces + +- `.codex/skills/*/SKILL.md` +- `.codex/agents/*` + +### Generated Claude surfaces + +- `.claude/skills/*/SKILL.md` +- `.claude/agents/*` + +### Generated GitHub Copilot surfaces + +- `.github/prompts/*` +- `.github/agents/*` + +### Generated Gemini surfaces + +- `.gemini/commands/truthmark/*` + +### Tests + +- `tests/agents/workflow-manifest.test.ts` +- `tests/agents/write-lease.test.ts` +- `tests/agents/prompts.test.ts` +- `tests/init/init.test.ts` +- new: `tests/evals/workflow-routing-cases.ts` +- new: `tests/evals/workflow-routing.test.ts` +- new: `tests/agents/report-contract.test.ts` +- new: `tests/agents/subagent-delegation.test.ts` +- new: `tests/init/cross-host-conformance.test.ts` +- new or extended: stale-surface diagnostics under the `truthmark check` test area + +## Final Assessment + +Truthmark’s architecture is stronger than typical prompt-only or ad hoc agent-workflow projects. The project already aligns with many of the best patterns in the literature: + +- repository-native truth; +- compact managed root instructions; +- manifest-owned workflow metadata; +- generated host surfaces; +- descriptions as routing boundaries; +- explicit negative triggers and forbidden adjacency; +- Sync-only automatic workflow; +- read-only verifier subagents; +- leased write-capable doc writer; +- parent-owned acceptance. + +The evidence does not support 100% confidence in world-class quality or runtime reliability yet. + +The highest-leverage next step is not more prompt prose. It is evaluation and conformance infrastructure: + +1. prompt-style workflow routing evals; +2. manifest-owned delegation policy; +3. worker/report schemas; +4. parent-diff validation tests; +5. cross-host protocol conformance; +6. stale-surface diagnostics. + +Those additions would turn the current strong architecture into a more defensible world-class implementation. diff --git a/src/agents/shared.ts b/src/agents/shared.ts index 2573997..bc43ebf 100644 --- a/src/agents/shared.ts +++ b/src/agents/shared.ts @@ -111,6 +111,128 @@ export const renderAuditEvidenceGateSection = (): string => { ].join("\n"); }; +export const renderCodexSubagentModeSection = ( + agents: string[], + parentRule: string, + writeAgents: string[] = [], +): string => { + const writeAgentLines = + writeAgents.length > 0 + ? [ + `- dispatch write-capable project agents only with explicit write leases: ${writeAgents.join(", ")}`, + "- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields", + "- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes", + "- parent must inspect the actual checkout diff against each lease before accepting a worker report", + ] + : []; + const readOnlyScope = writeAgents.length > 0 ? "for verification" : "only"; + const readOnlyWorkerLabel = writeAgents.length > 0 ? "read-only workers" : "workers"; + + return [ + "Codex subagent mode:", + "- use automatically when this workflow runs in Codex and the parent agent chooses bounded subagent fan-out", + `- dispatch read-only project agents ${readOnlyScope}: ${agents.join(", ")}`, + `- ${readOnlyWorkerLabel} inspect checkout evidence directly, return structured findings, and must not edit files`, + `- parent supplies bounded evidence shards; ${readOnlyWorkerLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`, + ...writeAgentLines, + `- ${parentRule}`, + ].join("\n"); +}; + +export const renderOpenCodeSubagentModeSection = ( + agents: string[], + parentRule: string, + writeAgents: string[] = [], +): string => { + const mentions = agents.map((agent) => `@${agent.replace(/_/gu, "-")}`); + const writeMentions = writeAgents.map((agent) => `@${agent.replace(/_/gu, "-")}`); + const writeAgentLines = + writeMentions.length > 0 + ? [ + `- dispatch write-capable project subagents only with explicit write leases: ${writeMentions.join(", ")}`, + "- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields", + "- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes", + "- parent must inspect the actual checkout diff against each lease before accepting a worker report", + ] + : []; + const readOnlyScope = writeAgents.length > 0 ? "for verification" : "only"; + const readOnlyWorkerLabel = writeAgents.length > 0 ? "read-only workers" : "workers"; + + return [ + "OpenCode subagent mode:", + "- use automatically when this workflow runs in OpenCode and the parent agent chooses bounded subagent fan-out", + `- dispatch read-only project subagents ${readOnlyScope}: ${mentions.join(", ")}`, + `- ${readOnlyWorkerLabel} inspect checkout evidence directly, return structured findings, and must not edit files`, + `- parent supplies bounded evidence shards; ${readOnlyWorkerLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`, + ...writeAgentLines, + `- ${parentRule}`, + ].join("\n"); +}; + +export const renderClaudeSubagentModeSection = ( + agents: string[], + parentRule: string, + writeAgents: string[] = [], +): string => { + const mentions = agents.map((agent) => `${agent.replace(/_/gu, "-")} subagent`); + const writeMentions = writeAgents.map( + (agent) => `${agent.replace(/_/gu, "-")} subagent`, + ); + const writeAgentLines = + writeMentions.length > 0 + ? [ + `- dispatch write-capable project subagents only with explicit write leases: ${writeMentions.join(", ")}`, + "- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields", + "- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes", + "- parent must inspect the actual checkout diff against each lease before accepting a worker report", + ] + : []; + const readOnlyScope = writeAgents.length > 0 ? "for verification" : "only"; + const readOnlySubagentLabel = + writeAgents.length > 0 ? "read-only subagents" : "subagents"; + + return [ + "Claude Code subagent mode:", + "- use automatically when this workflow runs in Claude Code and the parent agent chooses bounded subagent fan-out", + `- dispatch read-only project subagents ${readOnlyScope}: ${mentions.join(", ")}`, + `- ${readOnlySubagentLabel} inspect checkout evidence directly, return structured findings, and must not edit files`, + `- parent supplies bounded evidence shards; ${readOnlySubagentLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`, + ...writeAgentLines, + `- ${parentRule}`, + ].join("\n"); +}; + +export const renderCopilotCustomAgentModeSection = ( + agents: string[], + parentRule: string, + writeAgents: string[] = [], +): string => { + const mentions = agents.map((agent) => `@${agent.replace(/_/gu, "-")}`); + const writeMentions = writeAgents.map((agent) => `@${agent.replace(/_/gu, "-")}`); + const writeAgentLines = + writeMentions.length > 0 + ? [ + `- dispatch write-capable project custom agents only with explicit write leases: ${writeMentions.join(", ")}`, + "- each write lease must name objective, required reads, allowed writes, forbidden writes, evidence, verification, and report fields", + "- write workers must stop when a required edit is off-lease and report status, filesChanged, evidence, offLeaseChanges, blockers, and notes", + "- parent must inspect the actual checkout diff against each lease before accepting a worker report", + ] + : []; + const readOnlyScope = writeAgents.length > 0 ? "for verification" : "only"; + const readOnlyCustomAgentLabel = + writeAgents.length > 0 ? "read-only custom agents" : "custom agents"; + + return [ + "Copilot custom-agent mode:", + "- use automatically when this workflow runs in Copilot and the parent agent chooses bounded custom-agent fan-out", + `- dispatch read-only project custom agents ${readOnlyScope}: ${mentions.join(", ")}`, + `- ${readOnlyCustomAgentLabel} inspect checkout evidence directly, return structured findings, and must not edit files`, + `- parent supplies bounded evidence shards; ${readOnlyCustomAgentLabel} must not preload host instruction files or repo-wide policy docs unless assigned as evidence`, + ...writeAgentLines, + `- ${parentRule}`, + ].join("\n"); +}; + export const defaultAgentConfig = (): TruthmarkConfig => { return createDefaultConfig(); }; diff --git a/src/agents/truth-check.ts b/src/agents/truth-check.ts index bfa5019..8b083e1 100644 --- a/src/agents/truth-check.ts +++ b/src/agents/truth-check.ts @@ -2,6 +2,10 @@ import type { TruthmarkConfig } from "../config/schema.js"; import { renderAuditEvidenceCheckedSection, renderAuditEvidenceGateSection, + renderClaudeSubagentModeSection, + renderCodexSubagentModeSection, + renderCopilotCustomAgentModeSection, + renderOpenCodeSubagentModeSection, DECISION_TRUTH_INSTRUCTIONS, EVIDENCE_AUTHORITY_INSTRUCTIONS, defaultAgentConfig, @@ -47,8 +51,39 @@ Validation: export const renderTruthCheckSkillBody = ( config: TruthmarkConfig = defaultAgentConfig(), + options: { + includeClaudeSubagentMode?: boolean; + includeCodexSubagentMode?: boolean; + includeCopilotCustomAgentMode?: boolean; + includeOpenCodeSubagentMode?: boolean; + } = {}, ): string => { const workflow = getTruthmarkWorkflow("truthmark-check"); + const claudeSubagentMode = options.includeClaudeSubagentMode + ? `${renderClaudeSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns the final Truth Check report", + )}\n\n` + : ""; + const codexSubagentMode = options.includeCodexSubagentMode + ? `${renderCodexSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns the final Truth Check report", + )}\n\n` + : ""; + const copilotCustomAgentMode = options.includeCopilotCustomAgentMode + ? `${renderCopilotCustomAgentModeSection( + workflow.subagents ?? [], + "Parent agent owns the final Truth Check report", + )}\n\n` + : ""; + const openCodeSubagentMode = options.includeOpenCodeSubagentMode + ? `${renderOpenCodeSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns the final Truth Check report", + )}\n\n` + : ""; + const subagentMode = `${claudeSubagentMode}${codexSubagentMode}${copilotCustomAgentMode}${openCodeSubagentMode}`; return `--- name: truthmark-check @@ -79,7 +114,7 @@ Truth Check is agent-led: - if follow-up docs edits are needed for mixed-owner docs, run or recommend Truth Structure before editing ${renderAuditEvidenceGateSection()} -${renderHierarchySummary(config)} +${subagentMode}${renderHierarchySummary(config)} ${DECISION_TRUTH_INSTRUCTIONS} Report completion in this shape: diff --git a/src/agents/truth-document.ts b/src/agents/truth-document.ts index 915d164..75b651b 100644 --- a/src/agents/truth-document.ts +++ b/src/agents/truth-document.ts @@ -7,6 +7,10 @@ import { REPOSITORY_INTELLIGENCE_INSTRUCTIONS, TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS, defaultAgentConfig, + renderClaudeSubagentModeSection, + renderCodexSubagentModeSection, + renderCopilotCustomAgentModeSection, + renderOpenCodeSubagentModeSection, renderClaimEvidenceCheckedSection, renderRouteFirstEvidenceGateSection, renderHierarchySummary, @@ -63,8 +67,43 @@ Notes: export const renderTruthDocumentSkillBody = ( config: TruthmarkConfig = defaultAgentConfig(), + options: { + includeClaudeSubagentMode?: boolean; + includeCodexSubagentMode?: boolean; + includeCopilotCustomAgentMode?: boolean; + includeOpenCodeSubagentMode?: boolean; + } = {}, ): string => { const workflow = getTruthmarkWorkflow("truthmark-document"); + const claudeSubagentMode = options.includeClaudeSubagentMode + ? `${renderClaudeSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns Truth Document acceptance, lease validation, and final report", + workflow.writeSubagents ?? [], + )}\n` + : ""; + const codexSubagentMode = options.includeCodexSubagentMode + ? `${renderCodexSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns Truth Document acceptance, lease validation, and final report", + workflow.writeSubagents ?? [], + )}\n` + : ""; + const copilotCustomAgentMode = options.includeCopilotCustomAgentMode + ? `${renderCopilotCustomAgentModeSection( + workflow.subagents ?? [], + "Parent agent owns Truth Document acceptance, lease validation, and final report", + workflow.writeSubagents ?? [], + )}\n` + : ""; + const openCodeSubagentMode = options.includeOpenCodeSubagentMode + ? `${renderOpenCodeSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns Truth Document acceptance, lease validation, and final report", + workflow.writeSubagents ?? [], + )}\n` + : ""; + const subagentMode = `${claudeSubagentMode}${codexSubagentMode}${copilotCustomAgentMode}${openCodeSubagentMode}`; return `--- name: truthmark-document @@ -103,7 +142,7 @@ ${renderRouteFirstEvidenceGateSection( "the documented behavior", "if no truth doc changed, report why current truth was already sufficient or why documentation was blocked", )} -${REPOSITORY_INTELLIGENCE_INSTRUCTIONS} +${subagentMode}${REPOSITORY_INTELLIGENCE_INSTRUCTIONS} ${FEATURE_DOC_TEMPLATE_INSTRUCTIONS} ${renderTruthDocRestructureGateSection( "Truth Document may restructure only truth docs for the implemented behavior being documented.", @@ -111,6 +150,11 @@ ${renderTruthDocRestructureGateSection( ${ARCHITECTURE_DOC_BOUNDARY_INSTRUCTIONS} ${renderHierarchySummary(config)} ${DECISION_TRUTH_INSTRUCTIONS} +Parent post-document verification: +- verify only truth docs and leased truth routing files changed during document work +- block on functional code, generated host surfaces, or unrelated diffs caused by document work +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it +- verify the final report records ownership review, structure requirement, restructure, routing update, or blocked reason when applicable Report completion in this shape: ${renderMarkdownExample(renderTruthDocumentReportExample(config))}`; diff --git a/src/agents/truth-preview.ts b/src/agents/truth-preview.ts new file mode 100644 index 0000000..519e15f --- /dev/null +++ b/src/agents/truth-preview.ts @@ -0,0 +1,109 @@ +import type { TruthmarkConfig } from "../config/schema.js"; +import { + EVIDENCE_AUTHORITY_INSTRUCTIONS, + defaultAgentConfig, + renderHierarchySummary, + resolveTruthDocsRoot, +} from "./shared.js"; +import { TRUTHMARK_VERSION } from "../version.js"; +import { getTruthmarkWorkflow } from "./workflow-manifest.js"; + +const renderMarkdownExample = (content: string): string => { + return ["```md", content, "```"].join("\n"); +}; + +export const TRUTH_PREVIEW_EXPLICIT_INVOCATIONS = + "OpenCode /skill truthmark-preview; Codex /truthmark-preview or $truthmark-preview; Claude Code /truthmark-preview; GitHub Copilot /truthmark-preview; Gemini CLI /truthmark:preview."; + +export const renderTruthPreviewReportExample = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const truthDocsRoot = resolveTruthDocsRoot(config); + + return `Truth Preview: completed + +Requested outcome: +- preview likely Truthmark workflow routing before edits + +Likely workflow: +- truthmark-document + +Why this workflow: +- positive trigger: document existing implemented behavior +- negative triggers considered: functional-code change, doc-first implementation, topology repair, truth audit +- forbidden adjacency considered: must not edit functional code + +Likely route owner: +- route file: ${config.docs.routing.rootIndex} +- truth doc: ${truthDocsRoot}/example.md +- confidence: medium + +Expected write classes: +- truth docs + +Expected target files: +- ${truthDocsRoot}/example.md + +Suggested subagent use: +- read-only verifiers: truth_route_auditor +- write workers: none in Preview +- leases needed: none in Preview + +Blocking ambiguity: +- none identified in preview + +Handoff: +- Run the selected Truthmark workflow after user approval.`; +}; + +export const renderTruthPreviewSkillBody = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-preview"); + + return `--- +name: truthmark-preview +description: ${workflow.description} +argument-hint: Optional requested outcome, code area, doc path, or routing question +user-invocable: true +truthmark-version: ${TRUTHMARK_VERSION} +--- + +Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits. + +Invocations: ${TRUTH_PREVIEW_EXPLICIT_INVOCATIONS} + +Truth Preview is read-only. Its report is intended, not authorized. + +Purpose: +- preview the likely Truthmark workflow, route owner, target files, expected write classes, suggested subagent use, and blocking ambiguity before edits happen +- hand off to the selected workflow after user approval +- keep the selector thin so agents can avoid loading or acting through heavier workflows prematurely + +Read: +- .truthmark/config.yml +- ${config.docs.routing.rootIndex} +- relevant child route files under ${config.docs.routing.areaFilesRoot}/ +- relevant truth docs and implementation files needed to preview ownership +- ${EVIDENCE_AUTHORITY_INSTRUCTIONS} + +Do not: +- must not edit files +- must not create truth docs +- must not update routing +- must not run Truth Sync automatically +- must not replace Truth Check +- must not claim final correctness +- must not issue write leases +- must not mutate code + +Suggested subagent use: +- optional read-only verifier: truth_route_auditor +- write workers: none +- leases needed: none + +${renderHierarchySummary(config)} + +Report completion in this shape: +${renderMarkdownExample(renderTruthPreviewReportExample(config))}`; +}; diff --git a/src/agents/truth-structure.ts b/src/agents/truth-structure.ts index eaa46da..aa1de2c 100644 --- a/src/agents/truth-structure.ts +++ b/src/agents/truth-structure.ts @@ -6,7 +6,9 @@ import { FEATURE_DOC_TEMPLATE_INSTRUCTIONS, TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS, defaultAgentConfig, + renderClaudeSubagentModeSection, renderClaimEvidenceCheckedSection, + renderCopilotCustomAgentModeSection, renderHierarchySummary, renderTopologyEvidenceGateSection, renderTruthDocOwnershipGateSection, @@ -37,6 +39,11 @@ Areas reviewed: - src/auth/** Routing updated: - ${config.docs.routing.rootIndex} +Initial truth boundary: +- Area: Authentication +- Code: src/auth/** +- Truth owner: ${truthDocsRoot}/authentication/session.md +- Scope: session behavior only Truth docs created: - ${truthDocsRoot}/authentication/session.md Truth docs split: @@ -58,11 +65,28 @@ Notes: export const renderTruthStructureSkillBody = ( config: TruthmarkConfig = defaultAgentConfig(), + options: { + includeClaudeSubagentMode?: boolean; + includeCopilotCustomAgentMode?: boolean; + } = {}, ): string => { const truthDocsRoot = resolveTruthDocsRoot(config); const workflow = getTruthmarkWorkflow("truthmark-structure"); + const claudeSubagentMode = options.includeClaudeSubagentMode + ? `${renderClaudeSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns all Truth Structure writes and final topology decisions", + )}\n` + : ""; + const copilotCustomAgentMode = options.includeCopilotCustomAgentMode + ? `${renderCopilotCustomAgentModeSection( + workflow.subagents ?? [], + "Parent agent owns all Truth Structure writes and final topology decisions", + )}\n` + : ""; + const subagentMode = `${claudeSubagentMode}${copilotCustomAgentMode}`; -return `--- + return `--- name: truthmark-structure description: ${workflow.description} argument-hint: Optional area, directory, or routing concern @@ -81,11 +105,27 @@ Truth Structure is agent-native: - create starter truth docs when useful and when they belong in the canonical current-truth surface - Starter truth docs must use closed YAML frontmatter bounded by opening and closing --- lines; include status, doc_type, last_reviewed, and source_of_truth inside that frontmatter. - Starter truth docs must include ## Product Decisions and ## Rationale sections. +${subagentMode} ${FEATURE_DOC_TEMPLATE_INSTRUCTIONS} - use ${truthDocsRoot}/**, docs/architecture/**, or docs/standards/** for current truth destinations - use only canonical current-truth destinations for starter truth docs - keep active Product Decisions and Rationale in the canonical doc that owns the behavior - preserve unrelated authored content +## New area setup +Use 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. +Do: +- inspect the named code area +- infer bounded product or behavior ownership +- choose the owning route when ownership is clear; otherwise propose the route and block for review +- create or update the child route entry or file +- create starter truth docs only where current truth is missing +- report the initial truth boundary +Do not: +- do not edit functional code +- do not perform full behavior documentation unless evidence is inspected and the task explicitly asks for it +- do not patch broad or mixed-owner docs in place +- do not create generic catch-all docs +- do not treat README files as Sync targets ## Topology Governance Truth Structure owns documentation topology. Do not depend on humans to manually organize ${truthDocsRoot}. Treat the configured truth root as a managed semantic root. Inspect 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. diff --git a/src/agents/truth-sync.ts b/src/agents/truth-sync.ts index 5e95834..8c75988 100644 --- a/src/agents/truth-sync.ts +++ b/src/agents/truth-sync.ts @@ -7,6 +7,10 @@ import { REPOSITORY_INTELLIGENCE_INSTRUCTIONS, TRUTH_DOC_DECISION_RATIONALE_PRESERVATION_INSTRUCTIONS, defaultAgentConfig, + renderClaudeSubagentModeSection, + renderCodexSubagentModeSection, + renderCopilotCustomAgentModeSection, + renderOpenCodeSubagentModeSection, renderRouteFirstEvidenceGateSection, renderHierarchySummary, renderTruthDocOwnershipGateSection, @@ -31,15 +35,20 @@ export const renderTruthSyncWorkerPrompt = ( config: TruthmarkConfig = defaultAgentConfig(), ): string => { return `### Truth Sync Worker -The parent provides the task focus and any repository context already gathered. +The parent provides the task focus, explicit write lease, and any repository context already gathered. Worker rules: +- require a write lease with workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields before editing - inspect relevant staged, unstaged, and untracked functional code directly - read .truthmark/config.yml, ${config.docs.routing.rootIndex}, and canonical truth docs directly - Code verification is parent-owned; report what was run or why it was not run -- may write truth docs and ${config.docs.routing.rootIndex} only for Truth Sync alignment -- must not rewrite functional code +- may write only leased truth docs and leased truth routing files for Truth Sync alignment +- must not rewrite functional code or generated host surfaces +- stop and report blocked when the required edit needs an off-lease file Return result in this shape: - status: completed | blocked +- worker: string +- shard: string +- filesChanged: string[] - changedCodeReviewed: string[] - ownershipReviewed: string[] - structureRequired?: string[] @@ -47,6 +56,7 @@ Return result in this shape: - routingDocsUpdated: string[] - truthDocsSplit?: string[] - evidenceChecked: { claim: string; evidence: string[]; result: supported | narrowed | removed | blocked }[] +- offLeaseChanges: string[] - notes: string[] - blockedReason?: string - manualReviewFiles?: string[]`; @@ -54,9 +64,44 @@ Return result in this shape: export const renderTruthSyncSkillBody = ( config: TruthmarkConfig = defaultAgentConfig(), + options: { + includeClaudeSubagentMode?: boolean; + includeCodexSubagentMode?: boolean; + includeCopilotCustomAgentMode?: boolean; + includeOpenCodeSubagentMode?: boolean; + } = {}, ): string => { const truthDocsRoot = resolveTruthDocsRoot(config); const workflow = getTruthmarkWorkflow("truthmark-sync"); + const claudeSubagentMode = options.includeClaudeSubagentMode + ? `${renderClaudeSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns Truth Sync acceptance, lease validation, and final report", + workflow.writeSubagents ?? [], + )}\n` + : ""; + const codexSubagentMode = options.includeCodexSubagentMode + ? `${renderCodexSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns Truth Sync acceptance, lease validation, and final report", + workflow.writeSubagents ?? [], + )}\n` + : ""; + const copilotCustomAgentMode = options.includeCopilotCustomAgentMode + ? `${renderCopilotCustomAgentModeSection( + workflow.subagents ?? [], + "Parent agent owns Truth Sync acceptance, lease validation, and final report", + workflow.writeSubagents ?? [], + )}\n` + : ""; + const openCodeSubagentMode = options.includeOpenCodeSubagentMode + ? `${renderOpenCodeSubagentModeSection( + workflow.subagents ?? [], + "Parent agent owns Truth Sync acceptance, lease validation, and final report", + workflow.writeSubagents ?? [], + )}\n` + : ""; + const subagentMode = `${claudeSubagentMode}${codexSubagentMode}${copilotCustomAgentMode}${openCodeSubagentMode}`; return `--- name: truthmark-sync @@ -76,8 +121,8 @@ Parent workflow: 3. Identify functional-code changes and the nearest truth docs or routing repairs. 4. ${EVIDENCE_AUTHORITY_INSTRUCTIONS} 5. Code verification is parent-owned: follow repository instructions and task context, and report what ran or why it did not run. -6. Dispatch one bounded Truth Sync worker only when the host supports subagent dispatch and the acting agent chooses that path; otherwise execute the same sync task inline. -Topology quality gate: +6. 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. +${subagentMode}Topology quality gate: - before updating truth docs, verify the changed code resolves to a specific behavior-owned area and bounded truth owner - if routing is missing, stale, broad, overloaded, catch-all route only, or cannot map changed code to a bounded truth owner, do not create another generic truth doc - run Truth Structure before syncing when topology repair is safe and in scope @@ -108,12 +153,11 @@ Optional validation tooling: - update Product Decisions and Rationale when a behavior change comes from a decision change ${renderHierarchySummary(config)} ${DECISION_TRUTH_INSTRUCTIONS} -${renderTruthSyncWorkerPrompt(config)} Parent post-sync verification: -- verify only truth docs and ${config.docs.routing.rootIndex} changed during sync +- verify only truth docs and leased truth routing files changed during sync - block on any unrelated diff caused by the sync step - block if functional code changed during sync -- verify the worker report matches the required headings and sections +- for each write lease, validate the worker report against the actual worker diff, allowedWrites, forbiddenWrites, identity fields, filesChanged, offLeaseChanges, blockers, and required report fields before accepting it - validate the final report against the structured Truth Sync report contract, including Claim, Evidence, and Result entries under Evidence checked - verify the updated docs correspond to the reviewed changed-code surface - verify the final report records ownership review, structure requirement, split, restructure, or blocked reason when the ownership gate fired diff --git a/src/agents/workflow-manifest.ts b/src/agents/workflow-manifest.ts index e4b386c..4ff622e 100644 --- a/src/agents/workflow-manifest.ts +++ b/src/agents/workflow-manifest.ts @@ -2,9 +2,19 @@ export type TruthmarkWorkflowId = | "truthmark-sync" | "truthmark-structure" | "truthmark-document" + | "truthmark-preview" | "truthmark-realize" | "truthmark-check"; +export type TruthmarkReadOnlySubagentId = + | "truth_route_auditor" + | "truth_claim_verifier" + | "truth_doc_reviewer"; +export type TruthmarkWriteSubagentId = "truth_doc_writer"; +export type TruthmarkSubagentId = + | TruthmarkReadOnlySubagentId + | TruthmarkWriteSubagentId; + export type TruthmarkWorkflowManifestEntry = { id: TruthmarkWorkflowId; displayName: string; @@ -18,6 +28,8 @@ export type TruthmarkWorkflowManifestEntry = { requiredGates: string[]; allowedWrites: string[]; reportSections: string[]; + subagents?: TruthmarkReadOnlySubagentId[]; + writeSubagents?: TruthmarkWriteSubagentId[]; }; export const TRUTHMARK_WORKFLOW_MANIFEST = { @@ -63,19 +75,23 @@ export const TRUTHMARK_WORKFLOW_MANIFEST = { "Evidence checked", "Notes", ], + subagents: ["truth_route_auditor", "truth_claim_verifier"], + writeSubagents: ["truth_doc_writer"], }, "truthmark-structure": { id: "truthmark-structure", displayName: "Truthmark Structure", description: - "Use when routing or truth ownership is missing, stale, broad, overloaded, catch-all, unrouteable, mixed-owner, or needs split/repair. Not for documenting implemented behavior, syncing a code diff, or realizing docs into code.", - shortDescription: "Design or repair Truthmark area routing", + "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.", + shortDescription: "Design, repair, or set up Truthmark area routing", defaultPrompt: - "Use $truthmark-structure to design or repair Truthmark area routing.", + "Use $truthmark-structure to design, repair, or set up Truthmark area routing.", allowImplicitInvocation: false, positiveTriggers: [ "split broad repository routing into bounded areas", "repair missing, stale, catch-all, unrouteable, or mixed-owner truth ownership", + "onboard a new code area into Truthmark routing", + "new package, controller, domain, or product area lacks bounded truth ownership", ], negativeTriggers: [ "document existing implemented behavior", @@ -97,6 +113,7 @@ export const TRUTHMARK_WORKFLOW_MANIFEST = { "Topology reviewed", "Areas reviewed", "Routing updated", + "Initial truth boundary", "Truth docs created", "Truth docs split", "Truth docs restructured", @@ -104,6 +121,7 @@ export const TRUTHMARK_WORKFLOW_MANIFEST = { "Topology decisions", "Notes", ], + subagents: ["truth_route_auditor"], }, "truthmark-document": { id: "truthmark-document", @@ -145,6 +163,8 @@ export const TRUTHMARK_WORKFLOW_MANIFEST = { "Evidence checked", "Notes", ], + subagents: ["truth_route_auditor", "truth_claim_verifier"], + writeSubagents: ["truth_doc_writer"], }, "truthmark-realize": { id: "truthmark-realize", @@ -169,6 +189,49 @@ export const TRUTHMARK_WORKFLOW_MANIFEST = { allowedWrites: ["functional code"], reportSections: ["Truth docs used", "Code updated", "Verification"], }, + "truthmark-preview": { + id: "truthmark-preview", + displayName: "Truthmark Preview", + description: + "Use when the user explicitly asks to preview likely workflow routing, target files, writes, or subagent use before edits. Not for validation, automatic gates, final correctness, or replacing Truth Check.", + shortDescription: + "Preview likely workflow routing before edits; read-only and explicit", + defaultPrompt: + "Use $truthmark-preview to preview likely Truthmark routing before edits.", + allowImplicitInvocation: false, + positiveTriggers: [ + "explicit request to preview Truthmark workflow routing before edits", + "explicit request for likely route owner, target docs, expected writes, or subagent plan", + ], + negativeTriggers: [ + "normal validation or final correctness audit", + "automatic preflight or finish-time gate", + "request to mutate truth docs, routing, or code", + ], + forbiddenAdjacency: [ + "must not replace Truth Check", + "must not run Truth Sync automatically", + "must not authorize later edits or issue write leases", + ], + requiredGates: [ + "read-only boundary", + "intended-not-authorized handoff", + "blocking ambiguity disclosure", + ], + allowedWrites: ["none by default"], + reportSections: [ + "Requested outcome", + "Likely workflow", + "Why this workflow", + "Likely route owner", + "Expected write classes", + "Expected target files", + "Suggested subagent use", + "Blocking ambiguity", + "Handoff", + ], + subagents: ["truth_route_auditor"], + }, "truthmark-check": { id: "truthmark-check", displayName: "Truthmark Check", @@ -199,6 +262,11 @@ export const TRUTHMARK_WORKFLOW_MANIFEST = { "Evidence checked", "Validation", ], + subagents: [ + "truth_route_auditor", + "truth_claim_verifier", + "truth_doc_reviewer", + ], }, } satisfies Record; diff --git a/src/agents/write-lease.ts b/src/agents/write-lease.ts new file mode 100644 index 0000000..ec7d1d3 --- /dev/null +++ b/src/agents/write-lease.ts @@ -0,0 +1,307 @@ +import micromatch from "micromatch"; +import { parse as parseYaml } from "yaml"; + +import type { + TruthmarkWorkflowId, + TruthmarkWriteSubagentId, +} from "./workflow-manifest.js"; + +export const TRUTHMARK_WRITE_WORKER_REPORT_FIELDS = [ + "status", + "worker", + "workflow", + "shard", + "filesChanged", + "claimsChecked", + "evidenceChecked", + "offLeaseChanges", + "blockers", + "notes", +] as const; + +export type TruthmarkWriteWorkerReportField = + (typeof TRUTHMARK_WRITE_WORKER_REPORT_FIELDS)[number]; + +export type TruthmarkWriteLease = { + workflow: TruthmarkWorkflowId; + worker: TruthmarkWriteSubagentId; + shard: string; + objective: string; + requiredReads: string[]; + allowedReads?: string[]; + allowedWrites: string[]; + forbiddenWrites: string[]; + evidenceRequired: string[]; + verification?: string[]; + reportFields: string[]; +}; + +export type TruthmarkWriteLeaseChangeValidation = { + allowedChanges: string[]; + forbiddenChanges: string[]; + offLeaseChanges: string[]; +}; + +export type TruthmarkWriteWorkerReport = Record; + +export type TruthmarkWriteWorkerAcceptanceReasonCode = + | "missing-report-field" + | "invalid-report-field" + | "invalid-report-status" + | "identity-mismatch" + | "forbidden-actual-diff" + | "off-lease-actual-diff" + | "reported-files-mismatch" + | "completed-with-reported-off-lease-changes" + | "completed-with-blockers" + | "blocked-without-blockers"; + +export type TruthmarkWriteWorkerAcceptanceReason = { + code: TruthmarkWriteWorkerAcceptanceReasonCode; + message: string; + field?: string; + files?: string[]; + expected?: string; + actual?: string; +}; + +export type TruthmarkWriteWorkerAcceptanceValidation = { + status: "accepted" | "blocked" | "rejected"; + reasons: TruthmarkWriteWorkerAcceptanceReason[]; + changeValidation: TruthmarkWriteLeaseChangeValidation; + actualChangedFiles: string[]; + reportedFilesChanged: string[]; +}; + +const normalizePath = (filePath: string): string => { + return filePath.replaceAll("\\", "/").replace(/^\.\/+/u, ""); +}; + +const matchesAny = (filePath: string, patterns: string[]): boolean => { + if (patterns.length === 0) { + return false; + } + + return micromatch.isMatch(normalizePath(filePath), patterns); +}; + +const uniqueSorted = (values: string[]): string[] => { + return Array.from(new Set(values)).sort((left, right) => left.localeCompare(right)); +}; + +const isRecord = (value: unknown): value is Record => { + return typeof value === "object" && value !== null && !Array.isArray(value); +}; + +const hasOwn = (record: Record, key: string): boolean => { + return Object.prototype.hasOwnProperty.call(record, key); +}; + +const readStringArrayField = ( + report: TruthmarkWriteWorkerReport, + field: string, +): string[] | undefined => { + const value = report[field]; + if (!Array.isArray(value) || !value.every((item) => typeof item === "string")) { + return undefined; + } + return uniqueSorted(value.map(normalizePath)); +}; + +const equalStringArrays = (left: string[], right: string[]): boolean => { + return left.length === right.length && left.every((value, index) => value === right[index]); +}; + +export const parseTruthmarkWriteWorkerReport = ( + source: string, +): TruthmarkWriteWorkerReport => { + const parsed = parseYaml(source); + if (!isRecord(parsed)) { + throw new Error("Truthmark write worker report must be a YAML object."); + } + return parsed; +}; + +export const validateTruthmarkWriteLeaseChanges = ( + lease: TruthmarkWriteLease, + changedFiles: string[], +): TruthmarkWriteLeaseChangeValidation => { + const normalizedFiles = uniqueSorted(changedFiles.map(normalizePath)); + const forbiddenChanges = normalizedFiles.filter((filePath) => + matchesAny(filePath, lease.forbiddenWrites), + ); + const outsideAllowedWrites = normalizedFiles.filter( + (filePath) => !matchesAny(filePath, lease.allowedWrites), + ); + const offLeaseChanges = uniqueSorted([ + ...forbiddenChanges, + ...outsideAllowedWrites, + ]); + + return { + allowedChanges: normalizedFiles.filter( + (filePath) => !offLeaseChanges.includes(filePath), + ), + forbiddenChanges, + offLeaseChanges, + }; +}; + +export const validateTruthmarkWriteWorkerAcceptance = ({ + lease, + workerReport, + actualChangedFiles, +}: { + lease: TruthmarkWriteLease; + workerReport: TruthmarkWriteWorkerReport; + actualChangedFiles: string[]; +}): TruthmarkWriteWorkerAcceptanceValidation => { + const reasons: TruthmarkWriteWorkerAcceptanceReason[] = []; + const normalizedActualChangedFiles = uniqueSorted(actualChangedFiles.map(normalizePath)); + const requiredReportFields = uniqueSorted([ + ...lease.reportFields, + ...(lease.worker === "truth_doc_writer" ? TRUTHMARK_WRITE_WORKER_REPORT_FIELDS : []), + ]); + + for (const field of requiredReportFields) { + if (!hasOwn(workerReport, field)) { + reasons.push({ + code: "missing-report-field", + field, + message: `Worker report is missing required field ${field}.`, + }); + } + } + + const reportStatus = workerReport.status; + if ( + hasOwn(workerReport, "status") && + reportStatus !== "completed" && + reportStatus !== "blocked" + ) { + reasons.push({ + code: "invalid-report-status", + field: "status", + message: "Worker report status must be completed or blocked.", + }); + } + + for (const field of ["worker", "workflow", "shard"] as const) { + const actual = workerReport[field]; + const expected = lease[field]; + if (hasOwn(workerReport, field) && typeof actual !== "string") { + reasons.push({ + code: "invalid-report-field", + field, + message: `Worker report field ${field} must be a string.`, + }); + } else if (typeof actual === "string" && actual !== expected) { + reasons.push({ + code: "identity-mismatch", + field, + expected, + actual, + message: `Worker report ${field} does not match the lease.`, + }); + } + } + + for (const field of [ + "filesChanged", + "claimsChecked", + "evidenceChecked", + "offLeaseChanges", + "blockers", + "notes", + ]) { + if (hasOwn(workerReport, field) && readStringArrayField(workerReport, field) === undefined) { + reasons.push({ + code: "invalid-report-field", + field, + message: `Worker report field ${field} must be a string array.`, + }); + } + } + + const reportedFilesChanged = readStringArrayField(workerReport, "filesChanged") ?? []; + const reportedOffLeaseChanges = readStringArrayField(workerReport, "offLeaseChanges") ?? []; + const reportedBlockers = readStringArrayField(workerReport, "blockers") ?? []; + const changeValidation = validateTruthmarkWriteLeaseChanges( + lease, + normalizedActualChangedFiles, + ); + + if (changeValidation.forbiddenChanges.length > 0) { + reasons.push({ + code: "forbidden-actual-diff", + files: changeValidation.forbiddenChanges, + message: "Actual worker diff includes forbidden lease paths.", + }); + } + + if (changeValidation.offLeaseChanges.length > 0) { + reasons.push({ + code: "off-lease-actual-diff", + files: changeValidation.offLeaseChanges, + message: "Actual worker diff includes paths outside allowedWrites.", + }); + } + + if (!equalStringArrays(reportedFilesChanged, normalizedActualChangedFiles)) { + reasons.push({ + code: "reported-files-mismatch", + files: reportedFilesChanged, + message: "Worker report filesChanged does not match the actual worker diff.", + }); + } + + if (reportStatus === "completed" && reportedOffLeaseChanges.length > 0) { + reasons.push({ + code: "completed-with-reported-off-lease-changes", + files: reportedOffLeaseChanges, + message: "Completed worker reports must not include offLeaseChanges.", + }); + } + + if (reportStatus === "completed" && reportedBlockers.length > 0) { + reasons.push({ + code: "completed-with-blockers", + message: "Completed worker reports must not include blockers.", + }); + } + + if (reportStatus === "blocked" && reportedBlockers.length === 0) { + reasons.push({ + code: "blocked-without-blockers", + message: "Blocked worker reports must include at least one blocker.", + }); + } + + if (reasons.length === 0 && reportStatus === "completed") { + return { + status: "accepted", + reasons, + changeValidation, + actualChangedFiles: normalizedActualChangedFiles, + reportedFilesChanged, + }; + } + + if (reasons.length === 0 && reportStatus === "blocked") { + return { + status: "blocked", + reasons, + changeValidation, + actualChangedFiles: normalizedActualChangedFiles, + reportedFilesChanged, + }; + } + + return { + status: "rejected", + reasons, + changeValidation, + actualChangedFiles: normalizedActualChangedFiles, + reportedFilesChanged, + }; +}; diff --git a/src/init/init.ts b/src/init/init.ts index f1f1433..06cabdc 100644 --- a/src/init/init.ts +++ b/src/init/init.ts @@ -188,8 +188,12 @@ const diagnosticCategoryForPath = ( filePath === "GEMINI.md" || filePath === ".github/copilot-instructions.md" || filePath.startsWith(".github/prompts/truthmark-") || + filePath.startsWith(".github/agents/truth-") || + filePath.startsWith(".claude/agents/truth-") || filePath.startsWith(".claude/skills/truthmark-") || - filePath.startsWith(".opencode/skills/truthmark-") + filePath.startsWith(".opencode/skills/truthmark-") || + filePath.startsWith(".opencode/agents/") || + filePath.startsWith(".codex/agents/") ) { return "truth-sync"; } @@ -206,6 +210,10 @@ const diagnosticCategoryForPath = ( return "truth-sync"; } + if (filePath.startsWith(".codex/skills/truthmark-preview/")) { + return "truth-sync"; + } + if (filePath.startsWith(".codex/skills/truthmark-realize/")) { return "realization"; } diff --git a/src/markdown/discovery.ts b/src/markdown/discovery.ts index db9d6ba..57ffeae 100644 --- a/src/markdown/discovery.ts +++ b/src/markdown/discovery.ts @@ -13,6 +13,7 @@ export type DiscoveredMarkdownDocument = { const DISCOVERY_IGNORES = [ "**/.git/**", + "**/.github/agents/**", "**/.github/instructions/**", "**/.github/prompts/**", "**/.claude/**", diff --git a/src/routing/areas.ts b/src/routing/areas.ts index ee629c8..ea7ba0b 100644 --- a/src/routing/areas.ts +++ b/src/routing/areas.ts @@ -82,12 +82,15 @@ const parseListSection = (sectionLines: string[]): string[] => { return sectionLines .map((line) => line.trim()) .filter((line) => line.startsWith("- ")) - .map((line) => line.slice(2).trim()) + .map((line) => line.slice(2).trim().replaceAll("\\*", "*")) .filter((line) => line.length > 0); }; const isTruthDocumentKind = (value: unknown): value is TruthDocumentKind => { - return typeof value === "string" && TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind); + return ( + typeof value === "string" && + TRUTH_DOCUMENT_KINDS.includes(value as TruthDocumentKind) + ); }; export const inferTruthDocumentKindFromPath = ( @@ -95,7 +98,9 @@ export const inferTruthDocumentKindFromPath = ( options: ParseAreasMarkdownOptions = {}, ): TruthDocumentKind | null => { const normalizedPath = documentPath.replaceAll("\\", "/"); - const truthDocsRoot = options.truthDocsRoot?.replaceAll("\\", "/").replace(/\/+$/u, ""); + const truthDocsRoot = options.truthDocsRoot + ?.replaceAll("\\", "/") + .replace(/\/+$/u, ""); if ( (truthDocsRoot && normalizedPath.startsWith(`${truthDocsRoot}/`)) || @@ -116,15 +121,24 @@ export const inferTruthDocumentKindFromPath = ( return "architecture"; } - if (normalizedPath.startsWith("docs/workflows/") || normalizedPath.startsWith("docs/workflow/")) { + if ( + normalizedPath.startsWith("docs/workflows/") || + normalizedPath.startsWith("docs/workflow/") + ) { return "workflow"; } - if (normalizedPath.startsWith("docs/operations/") || normalizedPath.startsWith("docs/platform/")) { + if ( + normalizedPath.startsWith("docs/operations/") || + normalizedPath.startsWith("docs/platform/") + ) { return "operations"; } - if (normalizedPath.startsWith("docs/testing/") || normalizedPath.startsWith("docs/tests/")) { + if ( + normalizedPath.startsWith("docs/testing/") || + normalizedPath.startsWith("docs/tests/") + ) { return "test-behavior"; } @@ -146,7 +160,9 @@ const findTruthDocumentsYamlFenceRange = ( sectionLines: string[], ): TruthDocumentsYamlFenceRange | null => { const trimmedLines = sectionLines.map((line) => line.trim()); - const openingFenceIndex = trimmedLines.findIndex((line) => /^```(?:yaml|yml)?$/u.test(line)); + const openingFenceIndex = trimmedLines.findIndex((line) => + /^```(?:yaml|yml)?$/u.test(line), + ); if (openingFenceIndex === -1) { return null; @@ -228,7 +244,10 @@ const parseTruthDocumentsFromYaml = ( try { parsedBlock = parse( sectionLines - .slice(yamlFenceRange.openingFenceIndex + 1, yamlFenceRange.closingFenceIndex) + .slice( + yamlFenceRange.openingFenceIndex + 1, + yamlFenceRange.closingFenceIndex, + ) .join("\n"), ); } catch (error: unknown) { @@ -245,7 +264,9 @@ const parseTruthDocumentsFromYaml = ( } const rawEntries = - parsedBlock && typeof parsedBlock === "object" && "truth_documents" in parsedBlock + parsedBlock && + typeof parsedBlock === "object" && + "truth_documents" in parsedBlock ? (parsedBlock as { truth_documents?: unknown }).truth_documents : null; @@ -275,7 +296,11 @@ const parseTruthDocumentsFromYaml = ( ? (rawEntry as { kind?: unknown }).kind : null; - if (typeof path !== "string" || path.trim().length === 0 || !isTruthDocumentKind(kind)) { + if ( + typeof path !== "string" || + path.trim().length === 0 || + !isTruthDocumentKind(kind) + ) { diagnostics.push( createAreaDiagnostic( `Area ${areaName} truth_documents entries must include non-empty path and valid kind fields.`, @@ -312,7 +337,10 @@ const parseTruthDocumentsSection = ( const yamlResult = parseTruthDocumentsFromYaml(sectionLines, areaName); - if (yamlResult.diagnostics.length > 0 || yamlFenceRange.closingFenceIndex === null) { + if ( + yamlResult.diagnostics.length > 0 || + yamlFenceRange.closingFenceIndex === null + ) { return yamlResult; } @@ -346,8 +374,12 @@ export const parseAreasMarkdown = ( ); const { truthDocuments, truthDocumentEntries } = truthDocumentResult; const areaFiles = parseListSection(currentSections.get("Area files") ?? []); - const codeSurface = parseListSection(currentSections.get("Code surface") ?? []); - const updateTruthWhen = parseListSection(currentSections.get("Update truth when") ?? []); + const codeSurface = parseListSection( + currentSections.get("Code surface") ?? [], + ); + const updateTruthWhen = parseListSection( + currentSections.get("Update truth when") ?? [], + ); const areaKey = slugify(currentAreaName); const areaId = areaKey.length > 0 ? areaKey : `area-${areaIndex}`; const hasTruthDocuments = truthDocuments.length > 0; @@ -366,7 +398,11 @@ export const parseAreasMarkdown = ( }); } - if (hasTruthDocuments === hasAreaFiles || codeSurface.length === 0 || updateTruthWhen.length === 0) { + if ( + hasTruthDocuments === hasAreaFiles || + codeSurface.length === 0 || + updateTruthWhen.length === 0 + ) { diagnostics.push( createAreaDiagnostic( `Area ${currentAreaName} must define exactly one of Truth documents or Area files, plus Code surface and Update truth when sections.`, @@ -412,7 +448,11 @@ export const parseAreasMarkdown = ( continue; } - if (/^(Truth documents|Area files|Code surface|Update truth when):$/u.test(line.trim())) { + if ( + /^(Truth documents|Area files|Code surface|Update truth when):$/u.test( + line.trim(), + ) + ) { currentSectionName = line.trim().slice(0, -1); currentSections.set(currentSectionName, []); continue; diff --git a/src/sync/classify.ts b/src/sync/classify.ts index c18ff2a..fefd874 100644 --- a/src/sync/classify.ts +++ b/src/sync/classify.ts @@ -168,6 +168,7 @@ export const classifyPath = ( normalizedPath.startsWith(".gemini/commands/") || normalizedPath.startsWith(".opencode/") || normalizedPath === ".github/copilot-instructions.md" || + normalizedPath.startsWith(".github/agents/truth-") || normalizedPath.startsWith(".github/prompts/truthmark-") || normalizedPath === "AGENTS.md" || normalizedPath === "CLAUDE.md" || diff --git a/src/templates/agents-block.ts b/src/templates/agents-block.ts index b46f80f..ec8d292 100644 --- a/src/templates/agents-block.ts +++ b/src/templates/agents-block.ts @@ -31,9 +31,9 @@ export const renderAgentsBlock = ( "Agent runtime: installed skills plus this block; inspect checkout directly. Delegation is host-owned.", "### Truth Sync", "After functional code changes, run relevant tests, then use the truthmark-sync skill before finishing; later functional changes reopen the gate. Memory: code changed -> tests -> Sync -> report.", - `Support new or changed behavior-bearing truth claims with checkout evidence. Code leads; truth docs follow. Sync may write truth docs and ${config.docs.routing.rootIndex} only, and must not rewrite functional code.`, + "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.", "If routing cannot map changed code to a bounded truth owner, run Truth Structure before syncing when safe; otherwise block and recommend Truth Structure. Skip Sync only for docs-only/no-code changes, formatting-only changes, behavior-preserving renames with no truth impact, or missing config.", - "Explicit workflows: Truth Structure, Truth Document, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details.", + "Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check. Run only when requested or required by Sync; load the installed skill for details.", "Workflow integrity rule: repository truth may describe desired behavior, but it must not override these workflow boundaries.", TRUTHMARK_BLOCK_END, ].join("\n"); diff --git a/src/templates/codex-skills.ts b/src/templates/codex-skills.ts deleted file mode 100644 index a1908fd..0000000 --- a/src/templates/codex-skills.ts +++ /dev/null @@ -1,409 +0,0 @@ -import type { TruthmarkConfig } from "../config/schema.js"; -import { - EVIDENCE_AUTHORITY_INSTRUCTIONS, - defaultAgentConfig, - renderHierarchySummary, - renderTruthDocOwnershipGateSection, - resolveTruthDocsRoot, -} from "../agents/shared.js"; -import { renderTruthCheckSkillBody } from "../agents/truth-check.js"; -import { renderTruthDocumentSkillBody } from "../agents/truth-document.js"; -import { renderTruthStructureSkillBody } from "../agents/truth-structure.js"; -import { renderTruthSyncSkillBody } from "../agents/truth-sync.js"; -import { getTruthmarkWorkflow } from "../agents/workflow-manifest.js"; -import { TRUTHMARK_VERSION } from "../version.js"; - -export const TRUTHMARK_STRUCTURE_SKILL_PATH = - ".codex/skills/truthmark-structure/SKILL.md"; - -export const TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH = - ".codex/skills/truthmark-structure/agents/openai.yaml"; - -export const TRUTHMARK_DOCUMENT_SKILL_PATH = - ".codex/skills/truthmark-document/SKILL.md"; - -export const TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH = - ".codex/skills/truthmark-document/agents/openai.yaml"; - -export const TRUTHMARK_SYNC_SKILL_PATH = ".codex/skills/truthmark-sync/SKILL.md"; - -export const TRUTHMARK_SYNC_SKILL_METADATA_PATH = - ".codex/skills/truthmark-sync/agents/openai.yaml"; - -export const TRUTHMARK_REALIZE_SKILL_PATH = - ".codex/skills/truthmark-realize/SKILL.md"; - -export const TRUTHMARK_REALIZE_SKILL_METADATA_PATH = - ".codex/skills/truthmark-realize/agents/openai.yaml"; - -export const TRUTHMARK_CHECK_SKILL_PATH = ".codex/skills/truthmark-check/SKILL.md"; - -export const TRUTHMARK_CHECK_SKILL_METADATA_PATH = - ".codex/skills/truthmark-check/agents/openai.yaml"; - -export const TRUTHMARK_GEMINI_STRUCTURE_COMMAND_PATH = - ".gemini/commands/truthmark/structure.toml"; - -export const TRUTHMARK_GEMINI_DOCUMENT_COMMAND_PATH = - ".gemini/commands/truthmark/document.toml"; - -export const TRUTHMARK_GEMINI_SYNC_COMMAND_PATH = - ".gemini/commands/truthmark/sync.toml"; - -export const TRUTHMARK_GEMINI_REALIZE_COMMAND_PATH = - ".gemini/commands/truthmark/realize.toml"; - -export const TRUTHMARK_GEMINI_CHECK_COMMAND_PATH = - ".gemini/commands/truthmark/check.toml"; - -export const TRUTHMARK_COPILOT_STRUCTURE_PROMPT_PATH = - ".github/prompts/truthmark-structure.prompt.md"; - -export const TRUTHMARK_COPILOT_DOCUMENT_PROMPT_PATH = - ".github/prompts/truthmark-document.prompt.md"; - -export const TRUTHMARK_COPILOT_SYNC_PROMPT_PATH = - ".github/prompts/truthmark-sync.prompt.md"; - -export const TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH = - ".github/prompts/truthmark-realize.prompt.md"; - -export const TRUTHMARK_COPILOT_CHECK_PROMPT_PATH = - ".github/prompts/truthmark-check.prompt.md"; - -const renderGeminiCommand = (description: string, prompt: string): string => { - return `description = "${description}" -prompt = ''' -${prompt} -''' -`; -}; - -const renderCopilotPromptFile = (description: string, prompt: string): string => { - return `--- -agent: 'agent' -description: '${description}' ---- - -${prompt} -`; -}; - -export const renderTruthmarkStructureSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthStructureSkillBody(config); -}; - -export const renderTruthmarkStructureLocalSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthStructureSkillBody(config); -}; - -export const renderTruthmarkStructureSkillMetadata = (): string => { - const workflow = getTruthmarkWorkflow("truthmark-structure"); - - return `interface: - display_name: "${workflow.displayName}" - short_description: "${workflow.shortDescription}" - default_prompt: "${workflow.defaultPrompt}" - -policy: - allow_implicit_invocation: ${workflow.allowImplicitInvocation} - -truthmark: - version: "${TRUTHMARK_VERSION}" - refresh_command: "truthmark init" -`; -}; - -export const renderTruthmarkDocumentSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthDocumentSkillBody(config); -}; - -export const renderTruthmarkDocumentLocalSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthDocumentSkillBody(config); -}; - -export const renderTruthmarkDocumentSkillMetadata = (): string => { - const workflow = getTruthmarkWorkflow("truthmark-document"); - - return `interface: - display_name: "${workflow.displayName}" - short_description: "${workflow.shortDescription}" - default_prompt: "${workflow.defaultPrompt}" - -policy: - allow_implicit_invocation: ${workflow.allowImplicitInvocation} - -truthmark: - version: "${TRUTHMARK_VERSION}" - refresh_command: "truthmark init" -`; -}; - -export const renderTruthmarkSyncSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthSyncSkillBody(config); -}; - -export const renderTruthmarkSyncLocalSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthSyncSkillBody(config); -}; - -export const renderTruthmarkSyncSkillMetadata = (): string => { - const workflow = getTruthmarkWorkflow("truthmark-sync"); - - return `interface: - display_name: "${workflow.displayName}" - short_description: "${workflow.shortDescription}" - default_prompt: "${workflow.defaultPrompt}" - -policy: - allow_implicit_invocation: ${workflow.allowImplicitInvocation} - -truthmark: - version: "${TRUTHMARK_VERSION}" - refresh_command: "truthmark init" -`; -}; - -const renderTruthmarkRealizeSkillBody = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const truthDocsRoot = resolveTruthDocsRoot(config); - const workflow = getTruthmarkWorkflow("truthmark-realize"); - - return `--- -name: truthmark-realize -description: ${workflow.description} -argument-hint: Optional truth doc path, area, or desired code behavior to realize -user-invocable: true -truthmark-version: ${TRUTHMARK_VERSION} ---- - -# Truthmark Realize - -Use this skill only when the user explicitly asks to realize truth docs into code. - -Invocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize. - -Truth Realize is doc-first: - -- truth docs lead -- code follows -- Truth Realize never edits the truth docs it is realizing - -Workflow: - -1. Read the updated truth docs named by the user, or infer the relevant docs from ${config.docs.routing.rootIndex}. -2. Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files, tests, and the relevant functional code. -3. ${EVIDENCE_AUTHORITY_INSTRUCTIONS} -${renderTruthDocOwnershipGateSection( - "source truth docs before writing code", - "if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document", - )} -4. Update functional code only so implementation matches bounded, current truth claims from the source docs. -5. Do not edit truth docs or truth routing while realizing those docs. -6. Run relevant tests for the changed code. -7. Report changed code files and verification steps. -${renderHierarchySummary(config)} - -Read and write boundaries: - -- may read truth docs, routing docs, and relevant functional code -- may write functional code only -- must not edit truth docs or truth routing while realizing those docs - -Report completion in this shape: - -\`\`\`md -Truth Realize: completed - -Truth docs used: -- ${truthDocsRoot}/authentication/session-timeout.md - -Code updated: -- src/auth/session.ts - -Verification: -- npm test -- auth -\`\`\` -`; -}; - -export const renderTruthmarkRealizeSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthmarkRealizeSkillBody(config); -}; - -export const renderTruthmarkRealizeLocalSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthmarkRealizeSkillBody(config); -}; - -export const renderTruthmarkRealizeSkillMetadata = (): string => { - const workflow = getTruthmarkWorkflow("truthmark-realize"); - - return `interface: - display_name: "${workflow.displayName}" - short_description: "${workflow.shortDescription}" - default_prompt: "${workflow.defaultPrompt}" - -policy: - allow_implicit_invocation: ${workflow.allowImplicitInvocation} - -truthmark: - version: "${TRUTHMARK_VERSION}" - refresh_command: "truthmark init" -`; -}; - -export const renderTruthmarkCheckSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthCheckSkillBody(config); -}; - -export const renderTruthmarkCheckLocalSkill = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - return renderTruthCheckSkillBody(config); -}; - -export const renderTruthmarkCheckSkillMetadata = (): string => { - const workflow = getTruthmarkWorkflow("truthmark-check"); - - return `interface: - display_name: "${workflow.displayName}" - short_description: "${workflow.shortDescription}" - default_prompt: "${workflow.defaultPrompt}" - -policy: - allow_implicit_invocation: ${workflow.allowImplicitInvocation} - -truthmark: - version: "${TRUTHMARK_VERSION}" - refresh_command: "truthmark init" -`; -}; - -export const renderTruthmarkGeminiStructureCommand = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-structure"); - - return renderGeminiCommand( - workflow.description, - renderTruthStructureSkillBody(config), - ); -}; - -export const renderTruthmarkGeminiDocumentCommand = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-document"); - - return renderGeminiCommand( - workflow.description, - renderTruthDocumentSkillBody(config), - ); -}; - -export const renderTruthmarkGeminiSyncCommand = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-sync"); - - return renderGeminiCommand( - workflow.description, - renderTruthSyncSkillBody(config), - ); -}; - -export const renderTruthmarkGeminiRealizeCommand = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-realize"); - - return renderGeminiCommand( - workflow.description, - renderTruthmarkRealizeSkillBody(config), - ); -}; - -export const renderTruthmarkGeminiCheckCommand = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-check"); - - return renderGeminiCommand( - workflow.description, - renderTruthCheckSkillBody(config), - ); -}; - -export const renderTruthmarkCopilotStructurePrompt = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-structure"); - - return renderCopilotPromptFile( - workflow.description, - renderTruthStructureSkillBody(config), - ); -}; - -export const renderTruthmarkCopilotDocumentPrompt = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-document"); - - return renderCopilotPromptFile( - workflow.description, - renderTruthDocumentSkillBody(config), - ); -}; - -export const renderTruthmarkCopilotSyncPrompt = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-sync"); - - return renderCopilotPromptFile( - workflow.description, - renderTruthSyncSkillBody(config), - ); -}; - -export const renderTruthmarkCopilotRealizePrompt = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-realize"); - - return renderCopilotPromptFile( - workflow.description, - renderTruthmarkRealizeSkillBody(config), - ); -}; - -export const renderTruthmarkCopilotCheckPrompt = ( - config: TruthmarkConfig = defaultAgentConfig(), -): string => { - const workflow = getTruthmarkWorkflow("truthmark-check"); - - return renderCopilotPromptFile( - workflow.description, - renderTruthCheckSkillBody(config), - ); -}; diff --git a/src/templates/generated-surfaces.ts b/src/templates/generated-surfaces.ts index 04999f3..b4d13d1 100644 --- a/src/templates/generated-surfaces.ts +++ b/src/templates/generated-surfaces.ts @@ -2,51 +2,81 @@ import type { TruthmarkConfig, TruthmarkPlatform } from "../config/schema.js"; import { renderAgentsBlock } from "./agents-block.js"; import { renderTruthmarkCopilotCheckPrompt, + renderTruthmarkCopilotClaimVerifierAgent, renderTruthmarkCopilotDocumentPrompt, + renderTruthmarkCopilotDocReviewerAgent, + renderTruthmarkCopilotDocWriterAgent, + renderTruthmarkCopilotPreviewPrompt, renderTruthmarkCopilotRealizePrompt, + renderTruthmarkCopilotRouteAuditorAgent, renderTruthmarkCopilotStructurePrompt, renderTruthmarkCopilotSyncPrompt, - renderTruthmarkCheckLocalSkill, - renderTruthmarkDocumentLocalSkill, - renderTruthmarkDocumentSkill, + renderTruthmarkClaudeClaimVerifierAgent, + renderTruthmarkClaudeDocReviewerAgent, + renderTruthmarkClaudeDocWriterAgent, + renderTruthmarkClaudeRouteAuditorAgent, + renderTruthmarkClaimVerifierAgent, renderTruthmarkDocumentSkillMetadata, + renderTruthmarkDocReviewerAgent, + renderTruthmarkDocWriterAgent, renderTruthmarkGeminiCheckCommand, renderTruthmarkGeminiDocumentCommand, + renderTruthmarkGeminiPreviewCommand, renderTruthmarkGeminiRealizeCommand, renderTruthmarkGeminiStructureCommand, renderTruthmarkGeminiSyncCommand, - renderTruthmarkCheckSkill, renderTruthmarkCheckSkillMetadata, - renderTruthmarkRealizeLocalSkill, - renderTruthmarkRealizeSkill, + renderTruthmarkOpenCodeClaimVerifierAgent, + renderTruthmarkOpenCodeDocReviewerAgent, + renderTruthmarkOpenCodeDocWriterAgent, + renderTruthmarkOpenCodeRouteAuditorAgent, + renderTruthmarkPreviewSkillMetadata, renderTruthmarkRealizeSkillMetadata, - renderTruthmarkStructureLocalSkill, - renderTruthmarkStructureSkill, + renderTruthmarkRouteAuditorAgent, + renderTruthmarkSkillPackage, renderTruthmarkStructureSkillMetadata, - renderTruthmarkSyncLocalSkill, - renderTruthmarkSyncSkill, renderTruthmarkSyncSkillMetadata, TRUTHMARK_CHECK_SKILL_METADATA_PATH, TRUTHMARK_CHECK_SKILL_PATH, + TRUTHMARK_CLAUDE_CLAIM_VERIFIER_AGENT_PATH, + TRUTHMARK_CLAUDE_DOC_REVIEWER_AGENT_PATH, + TRUTHMARK_CLAUDE_DOC_WRITER_AGENT_PATH, + TRUTHMARK_CLAUDE_ROUTE_AUDITOR_AGENT_PATH, + TRUTHMARK_CLAIM_VERIFIER_AGENT_PATH, + TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH, TRUTHMARK_COPILOT_CHECK_PROMPT_PATH, TRUTHMARK_COPILOT_DOCUMENT_PROMPT_PATH, + TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH, + TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH, + TRUTHMARK_COPILOT_PREVIEW_PROMPT_PATH, TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH, + TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH, TRUTHMARK_COPILOT_STRUCTURE_PROMPT_PATH, TRUTHMARK_COPILOT_SYNC_PROMPT_PATH, TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH, TRUTHMARK_DOCUMENT_SKILL_PATH, + TRUTHMARK_DOC_REVIEWER_AGENT_PATH, + TRUTHMARK_DOC_WRITER_AGENT_PATH, TRUTHMARK_GEMINI_CHECK_COMMAND_PATH, TRUTHMARK_GEMINI_DOCUMENT_COMMAND_PATH, + TRUTHMARK_GEMINI_PREVIEW_COMMAND_PATH, TRUTHMARK_GEMINI_REALIZE_COMMAND_PATH, TRUTHMARK_GEMINI_STRUCTURE_COMMAND_PATH, TRUTHMARK_GEMINI_SYNC_COMMAND_PATH, + TRUTHMARK_OPENCODE_CLAIM_VERIFIER_AGENT_PATH, + TRUTHMARK_OPENCODE_DOC_REVIEWER_AGENT_PATH, + TRUTHMARK_OPENCODE_DOC_WRITER_AGENT_PATH, + TRUTHMARK_OPENCODE_ROUTE_AUDITOR_AGENT_PATH, + TRUTHMARK_PREVIEW_SKILL_METADATA_PATH, + TRUTHMARK_PREVIEW_SKILL_PATH, TRUTHMARK_REALIZE_SKILL_METADATA_PATH, TRUTHMARK_REALIZE_SKILL_PATH, + TRUTHMARK_ROUTE_AUDITOR_AGENT_PATH, TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH, TRUTHMARK_STRUCTURE_SKILL_PATH, TRUTHMARK_SYNC_SKILL_METADATA_PATH, TRUTHMARK_SYNC_SKILL_PATH, -} from "./codex-skills.js"; +} from "./workflow-surfaces.js"; export type GeneratedSurface = { path: string; @@ -54,84 +84,211 @@ export type GeneratedSurface = { managedBlock?: boolean; }; -const workflowSkillFiles = ( - basePath: string, - config: TruthmarkConfig, -): GeneratedSurface[] => { - const files: GeneratedSurface[] = [ - { - path: `${basePath}/truthmark-structure/SKILL.md`, - content: renderTruthmarkStructureLocalSkill(config), - }, - { - path: `${basePath}/truthmark-document/SKILL.md`, - content: renderTruthmarkDocumentLocalSkill(config), - }, - { - path: `${basePath}/truthmark-sync/SKILL.md`, - content: renderTruthmarkSyncLocalSkill(config), - }, - { - path: `${basePath}/truthmark-check/SKILL.md`, - content: renderTruthmarkCheckLocalSkill(config), - }, - { - path: `${basePath}/truthmark-realize/SKILL.md`, - content: renderTruthmarkRealizeLocalSkill(config), - }, - ]; - - return files; -}; - const codexFiles = (config: TruthmarkConfig): GeneratedSurface[] => { const files: GeneratedSurface[] = [ - { - path: TRUTHMARK_STRUCTURE_SKILL_PATH, - content: renderTruthmarkStructureSkill(config), - }, + ...renderTruthmarkSkillPackage({ + skillPath: TRUTHMARK_STRUCTURE_SKILL_PATH, + workflowId: "truthmark-structure", + host: "codex", + config, + }), { path: TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH, content: renderTruthmarkStructureSkillMetadata(), }, - { - path: TRUTHMARK_DOCUMENT_SKILL_PATH, - content: renderTruthmarkDocumentSkill(config), - }, + ...renderTruthmarkSkillPackage({ + skillPath: TRUTHMARK_DOCUMENT_SKILL_PATH, + workflowId: "truthmark-document", + host: "codex", + config, + }), { path: TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH, content: renderTruthmarkDocumentSkillMetadata(), }, - { - path: TRUTHMARK_SYNC_SKILL_PATH, - content: renderTruthmarkSyncSkill(config), - }, + ...renderTruthmarkSkillPackage({ + skillPath: TRUTHMARK_SYNC_SKILL_PATH, + workflowId: "truthmark-sync", + host: "codex", + config, + }), { path: TRUTHMARK_SYNC_SKILL_METADATA_PATH, content: renderTruthmarkSyncSkillMetadata(), }, + ...renderTruthmarkSkillPackage({ + skillPath: TRUTHMARK_PREVIEW_SKILL_PATH, + workflowId: "truthmark-preview", + host: "codex", + config, + }), { - path: TRUTHMARK_CHECK_SKILL_PATH, - content: renderTruthmarkCheckSkill(config), + path: TRUTHMARK_PREVIEW_SKILL_METADATA_PATH, + content: renderTruthmarkPreviewSkillMetadata(), }, + ...renderTruthmarkSkillPackage({ + skillPath: TRUTHMARK_CHECK_SKILL_PATH, + workflowId: "truthmark-check", + host: "codex", + config, + }), { path: TRUTHMARK_CHECK_SKILL_METADATA_PATH, content: renderTruthmarkCheckSkillMetadata(), }, - { - path: TRUTHMARK_REALIZE_SKILL_PATH, - content: renderTruthmarkRealizeSkill(config), - }, + ...renderTruthmarkSkillPackage({ + skillPath: TRUTHMARK_REALIZE_SKILL_PATH, + workflowId: "truthmark-realize", + host: "codex", + config, + }), { path: TRUTHMARK_REALIZE_SKILL_METADATA_PATH, content: renderTruthmarkRealizeSkillMetadata(), }, + { + path: TRUTHMARK_ROUTE_AUDITOR_AGENT_PATH, + content: renderTruthmarkRouteAuditorAgent(), + }, + { + path: TRUTHMARK_CLAIM_VERIFIER_AGENT_PATH, + content: renderTruthmarkClaimVerifierAgent(), + }, + { + path: TRUTHMARK_DOC_REVIEWER_AGENT_PATH, + content: renderTruthmarkDocReviewerAgent(), + }, + { + path: TRUTHMARK_DOC_WRITER_AGENT_PATH, + content: renderTruthmarkDocWriterAgent(), + }, ]; return files; }; -const copilotFiles = (config: TruthmarkConfig, block: string): GeneratedSurface[] => { +const opencodeFiles = (config: TruthmarkConfig): GeneratedSurface[] => { + return [ + ...renderTruthmarkSkillPackage({ + skillPath: ".opencode/skills/truthmark-structure/SKILL.md", + workflowId: "truthmark-structure", + host: "opencode", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".opencode/skills/truthmark-document/SKILL.md", + workflowId: "truthmark-document", + host: "opencode", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".opencode/skills/truthmark-sync/SKILL.md", + workflowId: "truthmark-sync", + host: "opencode", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".opencode/skills/truthmark-preview/SKILL.md", + workflowId: "truthmark-preview", + host: "opencode", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".opencode/skills/truthmark-check/SKILL.md", + workflowId: "truthmark-check", + host: "opencode", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".opencode/skills/truthmark-realize/SKILL.md", + workflowId: "truthmark-realize", + host: "opencode", + config, + }), + { + path: TRUTHMARK_OPENCODE_ROUTE_AUDITOR_AGENT_PATH, + content: renderTruthmarkOpenCodeRouteAuditorAgent(), + }, + { + path: TRUTHMARK_OPENCODE_CLAIM_VERIFIER_AGENT_PATH, + content: renderTruthmarkOpenCodeClaimVerifierAgent(), + }, + { + path: TRUTHMARK_OPENCODE_DOC_REVIEWER_AGENT_PATH, + content: renderTruthmarkOpenCodeDocReviewerAgent(), + }, + { + path: TRUTHMARK_OPENCODE_DOC_WRITER_AGENT_PATH, + content: renderTruthmarkOpenCodeDocWriterAgent(config), + }, + ]; +}; + +const claudeFiles = ( + config: TruthmarkConfig, + block: string, +): GeneratedSurface[] => { + return [ + ...instructionBlockFiles(["CLAUDE.md"], block), + ...renderTruthmarkSkillPackage({ + skillPath: ".claude/skills/truthmark-structure/SKILL.md", + workflowId: "truthmark-structure", + host: "claude-code", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".claude/skills/truthmark-document/SKILL.md", + workflowId: "truthmark-document", + host: "claude-code", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".claude/skills/truthmark-sync/SKILL.md", + workflowId: "truthmark-sync", + host: "claude-code", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".claude/skills/truthmark-preview/SKILL.md", + workflowId: "truthmark-preview", + host: "claude-code", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".claude/skills/truthmark-check/SKILL.md", + workflowId: "truthmark-check", + host: "claude-code", + config, + }), + ...renderTruthmarkSkillPackage({ + skillPath: ".claude/skills/truthmark-realize/SKILL.md", + workflowId: "truthmark-realize", + host: "claude-code", + config, + }), + { + path: TRUTHMARK_CLAUDE_ROUTE_AUDITOR_AGENT_PATH, + content: renderTruthmarkClaudeRouteAuditorAgent(), + }, + { + path: TRUTHMARK_CLAUDE_CLAIM_VERIFIER_AGENT_PATH, + content: renderTruthmarkClaudeClaimVerifierAgent(), + }, + { + path: TRUTHMARK_CLAUDE_DOC_REVIEWER_AGENT_PATH, + content: renderTruthmarkClaudeDocReviewerAgent(), + }, + { + path: TRUTHMARK_CLAUDE_DOC_WRITER_AGENT_PATH, + content: renderTruthmarkClaudeDocWriterAgent(), + }, + ]; +}; + +const copilotFiles = ( + config: TruthmarkConfig, + block: string, +): GeneratedSurface[] => { const files: GeneratedSurface[] = [ ...instructionBlockFiles([".github/copilot-instructions.md"], block), { @@ -146,6 +303,10 @@ const copilotFiles = (config: TruthmarkConfig, block: string): GeneratedSurface[ path: TRUTHMARK_COPILOT_SYNC_PROMPT_PATH, content: renderTruthmarkCopilotSyncPrompt(config), }, + { + path: TRUTHMARK_COPILOT_PREVIEW_PROMPT_PATH, + content: renderTruthmarkCopilotPreviewPrompt(config), + }, { path: TRUTHMARK_COPILOT_CHECK_PROMPT_PATH, content: renderTruthmarkCopilotCheckPrompt(config), @@ -154,12 +315,31 @@ const copilotFiles = (config: TruthmarkConfig, block: string): GeneratedSurface[ path: TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH, content: renderTruthmarkCopilotRealizePrompt(config), }, + { + path: TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH, + content: renderTruthmarkCopilotRouteAuditorAgent(), + }, + { + path: TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH, + content: renderTruthmarkCopilotClaimVerifierAgent(), + }, + { + path: TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH, + content: renderTruthmarkCopilotDocReviewerAgent(), + }, + { + path: TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH, + content: renderTruthmarkCopilotDocWriterAgent(), + }, ]; return files; }; -const instructionBlockFiles = (paths: string[], block: string): GeneratedSurface[] => { +const instructionBlockFiles = ( + paths: string[], + block: string, +): GeneratedSurface[] => { return paths.map((path) => ({ path, content: block, @@ -176,12 +356,9 @@ const filesForPlatform = ( case "codex": return codexFiles(config); case "opencode": - return workflowSkillFiles(".opencode/skills", config); + return opencodeFiles(config); case "claude-code": - return [ - ...instructionBlockFiles(["CLAUDE.md"], block), - ...workflowSkillFiles(".claude/skills", config), - ]; + return claudeFiles(config, block); case "github-copilot": return copilotFiles(config, block); case "gemini-cli": @@ -199,6 +376,10 @@ const filesForPlatform = ( path: TRUTHMARK_GEMINI_SYNC_COMMAND_PATH, content: renderTruthmarkGeminiSyncCommand(config), }, + { + path: TRUTHMARK_GEMINI_PREVIEW_COMMAND_PATH, + content: renderTruthmarkGeminiPreviewCommand(config), + }, { path: TRUTHMARK_GEMINI_CHECK_COMMAND_PATH, content: renderTruthmarkGeminiCheckCommand(config), @@ -217,10 +398,12 @@ export const renderGeneratedSurfaces = ( ): GeneratedSurface[] => { const files = [ ...instructionBlockFiles(config.instructionTargets, block), - ...config.platforms.flatMap((platform) => filesForPlatform(platform, config, block)), + ...config.platforms.flatMap((platform) => + filesForPlatform(platform, config, block), + ), ]; - return Array.from(new Map(files.map((file) => [file.path, file])).values()).sort((left, right) => - left.path.localeCompare(right.path), - ); + return Array.from( + new Map(files.map((file) => [file.path, file])).values(), + ).sort((left, right) => left.path.localeCompare(right.path)); }; diff --git a/src/templates/workflow-surfaces.ts b/src/templates/workflow-surfaces.ts new file mode 100644 index 0000000..82040e0 --- /dev/null +++ b/src/templates/workflow-surfaces.ts @@ -0,0 +1,1398 @@ +import type { TruthmarkConfig } from "../config/schema.js"; +import { + EVIDENCE_AUTHORITY_INSTRUCTIONS, + defaultAgentConfig, + renderClaudeSubagentModeSection, + renderCodexSubagentModeSection, + renderHierarchySummary, + renderOpenCodeSubagentModeSection, + renderTruthDocOwnershipGateSection, + resolveTruthDocsRoot, +} from "../agents/shared.js"; +import { + TRUTH_CHECK_EXPLICIT_INVOCATIONS, + renderTruthCheckSkillBody, +} from "../agents/truth-check.js"; +import { + TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS, + renderTruthDocumentSkillBody, +} from "../agents/truth-document.js"; +import { + TRUTH_PREVIEW_EXPLICIT_INVOCATIONS, + renderTruthPreviewSkillBody, +} from "../agents/truth-preview.js"; +import { + TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS, + renderTruthStructureSkillBody, +} from "../agents/truth-structure.js"; +import { + TRUTH_SYNC_EXPLICIT_INVOCATIONS, + renderTruthSyncSkillBody, +} from "../agents/truth-sync.js"; +import { TRUTHMARK_WRITE_WORKER_REPORT_FIELDS } from "../agents/write-lease.js"; +import { + getTruthmarkWorkflow, + type TruthmarkWorkflowId, + type TruthmarkReadOnlySubagentId, + type TruthmarkWriteSubagentId, +} from "../agents/workflow-manifest.js"; +import { TRUTHMARK_VERSION } from "../version.js"; + +export const TRUTHMARK_STRUCTURE_SKILL_PATH = + ".codex/skills/truthmark-structure/SKILL.md"; + +export const TRUTHMARK_STRUCTURE_SKILL_METADATA_PATH = + ".codex/skills/truthmark-structure/agents/openai.yaml"; + +export const TRUTHMARK_DOCUMENT_SKILL_PATH = + ".codex/skills/truthmark-document/SKILL.md"; + +export const TRUTHMARK_DOCUMENT_SKILL_METADATA_PATH = + ".codex/skills/truthmark-document/agents/openai.yaml"; + +export const TRUTHMARK_SYNC_SKILL_PATH = + ".codex/skills/truthmark-sync/SKILL.md"; + +export const TRUTHMARK_SYNC_SKILL_METADATA_PATH = + ".codex/skills/truthmark-sync/agents/openai.yaml"; + +export const TRUTHMARK_REALIZE_SKILL_PATH = + ".codex/skills/truthmark-realize/SKILL.md"; + +export const TRUTHMARK_REALIZE_SKILL_METADATA_PATH = + ".codex/skills/truthmark-realize/agents/openai.yaml"; + +export const TRUTHMARK_CHECK_SKILL_PATH = + ".codex/skills/truthmark-check/SKILL.md"; + +export const TRUTHMARK_CHECK_SKILL_METADATA_PATH = + ".codex/skills/truthmark-check/agents/openai.yaml"; + +export const TRUTHMARK_PREVIEW_SKILL_PATH = + ".codex/skills/truthmark-preview/SKILL.md"; + +export const TRUTHMARK_PREVIEW_SKILL_METADATA_PATH = + ".codex/skills/truthmark-preview/agents/openai.yaml"; + +export const TRUTHMARK_ROUTE_AUDITOR_AGENT_PATH = + ".codex/agents/truth-route-auditor.toml"; + +export const TRUTHMARK_CLAIM_VERIFIER_AGENT_PATH = + ".codex/agents/truth-claim-verifier.toml"; + +export const TRUTHMARK_DOC_REVIEWER_AGENT_PATH = + ".codex/agents/truth-doc-reviewer.toml"; +export const TRUTHMARK_DOC_WRITER_AGENT_PATH = + ".codex/agents/truth-doc-writer.toml"; + +export const TRUTHMARK_OPENCODE_ROUTE_AUDITOR_AGENT_PATH = + ".opencode/agents/truth-route-auditor.md"; + +export const TRUTHMARK_OPENCODE_CLAIM_VERIFIER_AGENT_PATH = + ".opencode/agents/truth-claim-verifier.md"; + +export const TRUTHMARK_OPENCODE_DOC_REVIEWER_AGENT_PATH = + ".opencode/agents/truth-doc-reviewer.md"; +export const TRUTHMARK_OPENCODE_DOC_WRITER_AGENT_PATH = + ".opencode/agents/truth-doc-writer.md"; + +export const TRUTHMARK_CLAUDE_ROUTE_AUDITOR_AGENT_PATH = + ".claude/agents/truth-route-auditor.md"; + +export const TRUTHMARK_CLAUDE_CLAIM_VERIFIER_AGENT_PATH = + ".claude/agents/truth-claim-verifier.md"; + +export const TRUTHMARK_CLAUDE_DOC_REVIEWER_AGENT_PATH = + ".claude/agents/truth-doc-reviewer.md"; +export const TRUTHMARK_CLAUDE_DOC_WRITER_AGENT_PATH = + ".claude/agents/truth-doc-writer.md"; + +export const TRUTHMARK_GEMINI_STRUCTURE_COMMAND_PATH = + ".gemini/commands/truthmark/structure.toml"; + +export const TRUTHMARK_GEMINI_DOCUMENT_COMMAND_PATH = + ".gemini/commands/truthmark/document.toml"; + +export const TRUTHMARK_GEMINI_SYNC_COMMAND_PATH = + ".gemini/commands/truthmark/sync.toml"; + +export const TRUTHMARK_GEMINI_REALIZE_COMMAND_PATH = + ".gemini/commands/truthmark/realize.toml"; + +export const TRUTHMARK_GEMINI_CHECK_COMMAND_PATH = + ".gemini/commands/truthmark/check.toml"; + +export const TRUTHMARK_GEMINI_PREVIEW_COMMAND_PATH = + ".gemini/commands/truthmark/preview.toml"; + +export const TRUTHMARK_COPILOT_STRUCTURE_PROMPT_PATH = + ".github/prompts/truthmark-structure.prompt.md"; + +export const TRUTHMARK_COPILOT_DOCUMENT_PROMPT_PATH = + ".github/prompts/truthmark-document.prompt.md"; + +export const TRUTHMARK_COPILOT_SYNC_PROMPT_PATH = + ".github/prompts/truthmark-sync.prompt.md"; + +export const TRUTHMARK_COPILOT_REALIZE_PROMPT_PATH = + ".github/prompts/truthmark-realize.prompt.md"; + +export const TRUTHMARK_COPILOT_CHECK_PROMPT_PATH = + ".github/prompts/truthmark-check.prompt.md"; + +export const TRUTHMARK_COPILOT_PREVIEW_PROMPT_PATH = + ".github/prompts/truthmark-preview.prompt.md"; + +export const TRUTHMARK_COPILOT_ROUTE_AUDITOR_AGENT_PATH = + ".github/agents/truth-route-auditor.agent.md"; + +export const TRUTHMARK_COPILOT_CLAIM_VERIFIER_AGENT_PATH = + ".github/agents/truth-claim-verifier.agent.md"; + +export const TRUTHMARK_COPILOT_DOC_REVIEWER_AGENT_PATH = + ".github/agents/truth-doc-reviewer.agent.md"; +export const TRUTHMARK_COPILOT_DOC_WRITER_AGENT_PATH = + ".github/agents/truth-doc-writer.agent.md"; + +const renderGeminiCommand = (description: string, prompt: string): string => { + return `description = "${description}" +prompt = ''' +${prompt} +''' +`; +}; + +const renderCopilotPromptFile = ( + description: string, + prompt: string, +): string => { + return `--- +agent: 'agent' +description: '${description}' +--- + +${prompt} +`; +}; + +const renderTomlString = (value: string): string => { + return `"${value.replace(/\\/gu, "\\\\").replace(/"/gu, '\\"')}"`; +}; + +const renderTomlStringArray = (values: string[]): string => { + return `[${values.map(renderTomlString).join(", ")}]`; +}; + +type TruthmarkSkillPackageHost = "codex" | "opencode" | "claude-code"; + +type TruthmarkSkillPackageFile = { + path: string; + content: string; +}; + +type WorkflowPackageDefinition = { + title: string; + argumentHint: string; + invocations: string; + use: (config: TruthmarkConfig) => string; + quickRules: (config: TruthmarkConfig) => string[]; + parentRule?: string; +}; + +const TRUTH_REALIZE_EXPLICIT_INVOCATIONS = + "OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize."; + +const WORKFLOW_PACKAGE_DEFINITIONS: Record< + TruthmarkWorkflowId, + WorkflowPackageDefinition +> = { + "truthmark-structure": { + title: "Truthmark Structure", + argumentHint: "Optional area, directory, or routing concern", + invocations: TRUTH_STRUCTURE_EXPLICIT_INVOCATIONS, + use: () => "Use this skill to design or repair Truthmark area structure.", + quickRules: (config) => [ + "Follow docs/ai/repo-rules.md as the repository instruction authority.", + `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, current docs, and relevant code directly.`, + "Define areas by product or behavior ownership, not by mechanical directory mirroring.", + "Do not edit functional code.", + "Read support/procedure.md before writing route or starter truth-doc changes.", + "Read support/report-template.md before the final report.", + ], + parentRule: + "Parent agent owns all Truth Structure writes and final topology decisions", + }, + "truthmark-document": { + title: "Truthmark Document", + argumentHint: + "Optional implemented behavior, API endpoint, route, controller, package, or truth-doc area to document", + invocations: TRUTH_DOCUMENT_EXPLICIT_INVOCATIONS, + use: () => + "Use this skill to document existing implemented behavior when no functional-code changes are required for the task.", + quickRules: (config) => [ + "Follow docs/ai/repo-rules.md as the repository instruction authority.", + `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, existing canonical docs, implementation code, and tests directly.`, + "Document current implemented behavior; do not invent future behavior.", + "May write canonical truth docs and truth routing files only; must not write functional code.", + "Read support/procedure.md before editing truth docs.", + "Read support/subagents-and-leases.md before dispatching or accepting worker output.", + "Read support/report-template.md before the final report.", + ], + parentRule: + "Parent agent owns Truth Document acceptance, lease validation, and final report", + }, + "truthmark-sync": { + title: "Truthmark Sync", + argumentHint: "Optional changed-code area, truth-doc area, or sync focus", + invocations: TRUTH_SYNC_EXPLICIT_INVOCATIONS, + use: () => + "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.", + quickRules: (config) => [ + "Follow docs/ai/repo-rules.md as the repository instruction authority.", + "Skip docs-only, formatting-only, behavior-preserving renames with no truth impact, missing config, and no-code changes.", + `Read .truthmark/config.yml, the configured root route index at ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, and relevant canonical docs.`, + "direct checkout inspection is the canonical path; do not require the truthmark binary.", + "May write canonical truth docs and truth routing files only; must not rewrite functional code.", + "Read support/procedure.md before editing truth docs.", + "Read support/subagents-and-leases.md before dispatching or accepting worker output.", + "Read support/report-template.md before the final report.", + ], + parentRule: + "Parent agent owns Truth Sync acceptance, lease validation, and final report", + }, + "truthmark-preview": { + title: "Truthmark Preview", + argumentHint: + "Optional requested outcome, code area, doc path, or routing question", + invocations: TRUTH_PREVIEW_EXPLICIT_INVOCATIONS, + use: () => + "Use this skill only when the user explicitly asks to preview Truthmark routing or workflow choice before edits.", + quickRules: (config) => [ + "Follow docs/ai/repo-rules.md as the repository instruction authority.", + `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, and only the truth docs or implementation files needed to preview ownership.`, + "Truth Preview is read-only; this report is intended, not authorized.", + "must not edit files and must not issue write leases; do not run Truth Sync automatically, replace Truth Check, claim final correctness, or mutate code.", + "Use optional read-only route-auditor evidence only when it reduces context or clarifies ownership.", + "Hand off to the selected workflow after user approval.", + ], + parentRule: "Parent agent owns the final Truth Preview report", + }, + "truthmark-realize": { + title: "Truthmark Realize", + argumentHint: + "Optional truth doc path, area, or desired code behavior to realize", + invocations: TRUTH_REALIZE_EXPLICIT_INVOCATIONS, + use: () => + "Use this skill only when the user explicitly asks to realize truth docs into code.", + quickRules: (config) => [ + "Follow docs/ai/repo-rules.md as the repository instruction authority.", + `Read the source truth docs, .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files, tests, and relevant functional code directly.`, + "Truth docs lead; code follows.", + "may write functional code only; must not edit truth docs or truth routing while realizing those docs.", + "Read support/procedure.md before changing code.", + "Read support/report-template.md before the final report.", + ], + }, + "truthmark-check": { + title: "Truthmark Check", + argumentHint: "Optional area, doc path, or audit focus", + invocations: TRUTH_CHECK_EXPLICIT_INVOCATIONS, + use: () => "Use this skill to audit repository truth health.", + quickRules: (config) => [ + "Follow docs/ai/repo-rules.md as the repository instruction authority.", + `Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files under ${config.docs.routing.areaFilesRoot}/, canonical docs, and relevant implementation directly.`, + "Report issues and suggested fixes; do not silently rewrite unrelated files.", + "Direct checkout inspection is valid even when local tooling is unavailable.", + "Read support/procedure.md before auditing details.", + "Read support/subagents-and-leases.md before dispatching verifier subagents.", + "Read support/report-template.md before the final report.", + ], + parentRule: "Parent agent owns the final Truth Check report", + }, +}; + +const stripWorkflowSkillFrontmatter = (body: string): string => { + return body.replace(/^---\n[\s\S]*?\n---\n\n?/u, "").trim(); +}; + +const splitWorkflowSupport = ( + body: string, +): { procedure: string; reportTemplate: string } => { + const stripped = stripWorkflowSkillFrontmatter(body); + const marker = "Report completion in this shape:"; + const markerIndex = stripped.indexOf(marker); + + if (markerIndex === -1) { + return { + procedure: stripped, + reportTemplate: "Report completion in the workflow-specific shape.", + }; + } + + return { + procedure: stripped.slice(0, markerIndex).trim(), + reportTemplate: stripped.slice(markerIndex).trim(), + }; +}; + +const renderSkillSupportFile = (title: string, body: string): string => { + return `# ${title} + +Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades. + +${body} +`; +}; + +const renderStandaloneWorkflowSkillBody = ( + workflowId: TruthmarkWorkflowId, + config: TruthmarkConfig, +): string => { + switch (workflowId) { + case "truthmark-structure": + return renderTruthStructureSkillBody(config); + case "truthmark-document": + return renderTruthDocumentSkillBody(config); + case "truthmark-sync": + return renderTruthSyncSkillBody(config); + case "truthmark-preview": + return renderTruthPreviewSkillBody(config); + case "truthmark-realize": + return renderTruthmarkRealizeSkillBody(config); + case "truthmark-check": + return renderTruthCheckSkillBody(config); + } +}; + +const renderWorkflowEntrypoint = ( + workflowId: TruthmarkWorkflowId, + config: TruthmarkConfig, + supportFiles: string[], +): string => { + const workflow = getTruthmarkWorkflow(workflowId); + const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId]; + const supportFileList = supportFiles + .map((supportFile) => `- ${supportFile}`) + .join("\n"); + + return `--- +name: ${workflowId} +description: ${workflow.description} +argument-hint: ${definition.argumentHint} +user-invocable: true +truthmark-version: ${TRUTHMARK_VERSION} +--- + +# ${definition.title} + +${definition.use(config)} + +Invocations: ${definition.invocations} + +Quick procedure: +${definition + .quickRules(config) + .map((rule) => `- ${rule}`) + .join("\n")} + +Progressive disclosure: +${supportFileList} +`; +}; + +const renderWorkflowSubagentSupport = ( + workflowId: TruthmarkWorkflowId, + host: TruthmarkSkillPackageHost, +): string | undefined => { + const workflow = getTruthmarkWorkflow(workflowId); + const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId]; + const readAgents = workflow.subagents ?? []; + const writeAgents = workflow.writeSubagents ?? []; + + if (readAgents.length === 0 && writeAgents.length === 0) { + return undefined; + } + + if (definition.parentRule === undefined) { + return undefined; + } + + switch (host) { + case "codex": + return renderCodexSubagentModeSection( + readAgents, + definition.parentRule, + writeAgents, + ); + case "opencode": + return renderOpenCodeSubagentModeSection( + readAgents, + definition.parentRule, + writeAgents, + ); + case "claude-code": + return renderClaudeSubagentModeSection( + readAgents, + definition.parentRule, + writeAgents, + ); + } +}; + +export const renderTruthmarkSkillPackage = ({ + skillPath, + workflowId, + host, + config = defaultAgentConfig(), +}: { + skillPath: string; + workflowId: TruthmarkWorkflowId; + host: TruthmarkSkillPackageHost; + config?: TruthmarkConfig; +}): TruthmarkSkillPackageFile[] => { + const skillDirectory = skillPath.replace(/\/SKILL\.md$/u, ""); + const supportDirectory = `${skillDirectory}/support`; + const { procedure, reportTemplate } = splitWorkflowSupport( + renderStandaloneWorkflowSkillBody(workflowId, config), + ); + const subagents = renderWorkflowSubagentSupport(workflowId, host); + const supportFiles = [ + "support/procedure.md", + "support/report-template.md", + ...(subagents === undefined ? [] : ["support/subagents-and-leases.md"]), + ]; + const definition = WORKFLOW_PACKAGE_DEFINITIONS[workflowId]; + const files: TruthmarkSkillPackageFile[] = [ + { + path: skillPath, + content: renderWorkflowEntrypoint(workflowId, config, supportFiles), + }, + { + path: `${supportDirectory}/procedure.md`, + content: renderSkillSupportFile( + `${definition.title} Procedure`, + procedure, + ), + }, + { + path: `${supportDirectory}/report-template.md`, + content: renderSkillSupportFile( + `${definition.title} Report Template`, + reportTemplate, + ), + }, + ]; + + if (subagents !== undefined) { + files.push({ + path: `${supportDirectory}/subagents-and-leases.md`, + content: renderSkillSupportFile( + `${definition.title} Subagents And Leases`, + subagents, + ), + }); + } + + return files; +}; + +const normalizeOpenCodePermissionPath = (path: string): string => { + const normalized = path + .replace(/\\/gu, "/") + .replace(/^\.\//u, "") + .replace(/\/+$/u, ""); + + return normalized === "" ? "." : normalized; +}; + +const appendOpenCodePermissionGlob = (root: string, glob: string): string => { + return root === "." ? glob.replace(/^\//u, "") : `${root}${glob}`; +}; + +const renderOpenCodeWriterEditAllowRules = ( + config: TruthmarkConfig, +): string => { + const truthDocsRoot = normalizeOpenCodePermissionPath( + resolveTruthDocsRoot(config), + ); + const rootRouteIndex = normalizeOpenCodePermissionPath( + config.docs.routing.rootIndex, + ); + const areaFilesRoot = normalizeOpenCodePermissionPath( + config.docs.routing.areaFilesRoot, + ); + const allowedPatterns = [ + appendOpenCodePermissionGlob(truthDocsRoot, "/**"), + rootRouteIndex, + appendOpenCodePermissionGlob(areaFilesRoot, "/**/*.md"), + ]; + + return [...new Set(allowedPatterns)] + .map((pattern) => ` ${JSON.stringify(pattern)}: allow`) + .join("\n"); +}; + +type TruthmarkSubagentProfile = { + codexName: string; + copilotName: string; + description: string; + nicknameCandidates: string[]; + instructions: string; +}; + +const READ_ONLY_SUBAGENT_CONTEXT_BOUNDARY = `Context boundary: +Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence. +Use only the parent-assigned shard plus required checkout evidence files. +Return findings only; the parent workflow owns repository-policy interpretation, final decisions, and all writes.`; + +const renderReadOnlySubagentInstructions = (instructions: string): string => { + return `${instructions} +${READ_ONLY_SUBAGENT_CONTEXT_BOUNDARY}`; +}; + +const TRUTHMARK_SUBAGENT_PROFILES = { + truth_route_auditor: { + codexName: "truth_route_auditor", + copilotName: "truth-route-auditor", + description: + "Read-only Truthmark route auditor for bounded routing and ownership verification.", + nicknameCandidates: ["Route Audit", "Route Trace", "Route Check"], + instructions: `Stay read-only. +Audit one bounded Truthmark route, area, or doc shard assigned by the parent. +Read .truthmark/config.yml, the root route index, relevant child route files, mapped truth docs, and relevant implementation files directly. +Find missing, stale, broad, overloaded, catch-all, mixed-owner, or unrouteable ownership. +Do not edit files, stage changes, or propose broad rewrites. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure.`, + }, + truth_claim_verifier: { + codexName: "truth_claim_verifier", + copilotName: "truth-claim-verifier", + description: + "Read-only Truthmark claim verifier for checking canonical truth against checkout evidence.", + nicknameCandidates: ["Claim Audit", "Claim Trace", "Claim Check"], + instructions: `Stay read-only. +Verify the behavior-bearing truth claims assigned by the parent against primary checkout evidence. +Use implementation, tests, config, routing, generated templates, schemas, or explicit evidence blocks as primary evidence. +Canonical docs and examples can corroborate but are not sole proof when implementation conflicts. +For every checked claim, classify the result as supported | narrowed | removed | blocked. +Do not edit files, stage changes, or invent missing behavior. +Return JSON only with keys: scope, filesReviewed, claimsChecked, evidence, unsupportedClaims, confidence, recommendedWorkflow, notes.`, + }, + truth_doc_reviewer: { + codexName: "truth_doc_reviewer", + copilotName: "truth-doc-reviewer", + description: + "Read-only Truthmark doc reviewer for shape, decision, rationale, and evidence hygiene.", + nicknameCandidates: ["Doc Audit", "Doc Shape", "Doc Check"], + instructions: `Stay read-only. +Review assigned canonical truth docs for frontmatter, source_of_truth, required template sections, Evidence checked entries, Product Decisions, and Rationale. +Flag README.md files used as behavior truth targets, mixed-owner docs, and shape repairs that should move to Truth Structure. +Do not edit files, stage changes, or rewrite docs. +Return JSON only with keys: scope, filesReviewed, findings, evidence, confidence, recommendedWorkflow, notes. +recommendedWorkflow must be one of: none, truthmark-document, truthmark-structure.`, + }, +} satisfies Record; +type TruthmarkWriteSubagentProfile = { + codexName: string; + copilotName: string; + description: string; + nicknameCandidates: string[]; + instructions: string; +}; +const TRUTHMARK_WRITE_SUBAGENT_PROFILES = { + truth_doc_writer: { + codexName: "truth_doc_writer", + copilotName: "truth-doc-writer", + description: + "Write-capable Truthmark doc worker for one parent-leased truth-document shard.", + nicknameCandidates: ["Doc Writer", "Truth Writer", "Doc Sync"], + instructions: `Write one leased Truthmark truth-document shard assigned by the parent. +Require an explicit write lease before editing. The lease must name workflow, worker, shard, objective, requiredReads, allowedWrites, forbiddenWrites, evidenceRequired, verification, and reportFields. +Read every requiredReads entry directly before editing. +Edit 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. +Do not expand your own write scope. If the task needs an off-lease file, stop and report blocked. +Block 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. +Return YAML only with keys: ${TRUTHMARK_WRITE_WORKER_REPORT_FIELDS.join(", ")}. +status must be completed or blocked. +filesChanged must list only files you actually changed. +offLeaseChanges must be empty for completed reports. +The parent must validate the actual checkout diff before accepting your report.`, + }, +} satisfies Record; + +const renderCodexReadOnlyAgent = ({ + name, + description, + nicknameCandidates, + developerInstructions, +}: { + name: string; + description: string; + nicknameCandidates: string[]; + developerInstructions: string; +}): string => { + return `# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades. +name = ${renderTomlString(name)} +description = ${renderTomlString(description)} +sandbox_mode = "read-only" +nickname_candidates = ${renderTomlStringArray(nicknameCandidates)} +developer_instructions = """ +${developerInstructions} +""" +`; +}; +const renderCodexWriteAgent = ({ + name, + description, + nicknameCandidates, + developerInstructions, +}: { + name: string; + description: string; + nicknameCandidates: string[]; + developerInstructions: string; +}): string => { + return `# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades. +name = ${renderTomlString(name)} +description = ${renderTomlString(description)} +sandbox_mode = "workspace-write" +nickname_candidates = ${renderTomlStringArray(nicknameCandidates)} +developer_instructions = """ +${developerInstructions} +""" +`; +}; + +const renderCopilotReadOnlyAgent = ({ + copilotName, + description, + instructions, +}: TruthmarkSubagentProfile): string => { + const agentInstructions = renderReadOnlySubagentInstructions(instructions); + + return `--- +name: ${copilotName} +description: ${description} +tools: [read, search] +--- + +# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades. + +${agentInstructions} +`; +}; +const renderCopilotWriteAgent = ({ + copilotName, + description, + instructions, +}: TruthmarkWriteSubagentProfile): string => { + return `--- +name: ${copilotName} +description: ${description} +tools: [read, search, edit] +--- + +# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades. + +${instructions} +`; +}; + +const renderClaudeReadOnlyAgent = ({ + copilotName, + description, + instructions, +}: TruthmarkSubagentProfile): string => { + const agentInstructions = renderReadOnlySubagentInstructions(instructions); + + return `--- +name: ${copilotName} +description: ${description} +tools: Read, Grep, Glob, LS +--- + +# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades. + +Manual invocation: use the ${copilotName} subagent. + +${agentInstructions} +`; +}; +const renderClaudeWriteAgent = ({ + copilotName, + description, + instructions, +}: TruthmarkWriteSubagentProfile): string => { + return `--- +name: ${copilotName} +description: ${description} +tools: Read, Grep, Glob, LS, Edit, MultiEdit +--- + +# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades. + +Manual invocation: use the ${copilotName} subagent with an explicit parent write lease. + +${instructions} +`; +}; + +export const renderTruthmarkRouteAuditorAgent = (): string => { + const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor; + + return renderCodexReadOnlyAgent({ + name: profile.codexName, + description: profile.description, + nicknameCandidates: profile.nicknameCandidates, + developerInstructions: renderReadOnlySubagentInstructions( + profile.instructions, + ), + }); +}; + +export const renderTruthmarkClaimVerifierAgent = (): string => { + const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier; + + return renderCodexReadOnlyAgent({ + name: profile.codexName, + description: profile.description, + nicknameCandidates: profile.nicknameCandidates, + developerInstructions: renderReadOnlySubagentInstructions( + profile.instructions, + ), + }); +}; + +export const renderTruthmarkDocReviewerAgent = (): string => { + const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer; + + return renderCodexReadOnlyAgent({ + name: profile.codexName, + description: profile.description, + nicknameCandidates: profile.nicknameCandidates, + developerInstructions: renderReadOnlySubagentInstructions( + profile.instructions, + ), + }); +}; +export const renderTruthmarkDocWriterAgent = (): string => { + const profile = TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer; + + return renderCodexWriteAgent({ + name: profile.codexName, + description: profile.description, + nicknameCandidates: profile.nicknameCandidates, + developerInstructions: profile.instructions, + }); +}; + +export const renderTruthmarkCopilotRouteAuditorAgent = (): string => { + return renderCopilotReadOnlyAgent( + TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor, + ); +}; + +export const renderTruthmarkCopilotClaimVerifierAgent = (): string => { + return renderCopilotReadOnlyAgent( + TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier, + ); +}; + +export const renderTruthmarkCopilotDocReviewerAgent = (): string => { + return renderCopilotReadOnlyAgent( + TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer, + ); +}; +export const renderTruthmarkCopilotDocWriterAgent = (): string => { + return renderCopilotWriteAgent( + TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer, + ); +}; + +export const renderTruthmarkClaudeRouteAuditorAgent = (): string => { + return renderClaudeReadOnlyAgent( + TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor, + ); +}; + +export const renderTruthmarkClaudeClaimVerifierAgent = (): string => { + return renderClaudeReadOnlyAgent( + TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier, + ); +}; + +export const renderTruthmarkClaudeDocReviewerAgent = (): string => { + return renderClaudeReadOnlyAgent( + TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer, + ); +}; +export const renderTruthmarkClaudeDocWriterAgent = (): string => { + return renderClaudeWriteAgent( + TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer, + ); +}; + +const renderOpenCodeReadOnlyAgent = ({ + invocation, + description, + instructions, +}: { + invocation: string; + description: string; + instructions: string; +}): string => { + const agentInstructions = renderReadOnlySubagentInstructions(instructions); + + return `--- +description: ${description} +mode: subagent +permission: + edit: deny + task: deny + webfetch: deny + websearch: deny + external_directory: deny + bash: + "*": ask + "git status*": allow + "git diff*": allow + "git log*": allow + "rg *": allow + "grep *": allow +--- + +# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades. + +Manual invocation: @${invocation} + +${agentInstructions} +`; +}; +const renderOpenCodeWriteAgent = ({ + invocation, + description, + instructions, + config, +}: { + invocation: string; + description: string; + instructions: string; + config: TruthmarkConfig; +}): string => { + const editAllowRules = renderOpenCodeWriterEditAllowRules(config); + + return `--- +description: ${description} +mode: subagent +permission: + read: allow + list: allow + grep: allow + glob: allow + edit: + "*": deny +${editAllowRules} + task: deny + webfetch: deny + websearch: deny + external_directory: deny + bash: + "*": ask + "git status*": allow + "git diff*": allow +--- + +# Generated by Truthmark ${TRUTHMARK_VERSION}. Rerun truthmark init after upgrades. + +Manual invocation: @${invocation} + +${instructions} +`; +}; + +export const renderTruthmarkOpenCodeRouteAuditorAgent = (): string => { + const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_route_auditor; + + return renderOpenCodeReadOnlyAgent({ + invocation: profile.copilotName, + description: profile.description, + instructions: profile.instructions, + }); +}; + +export const renderTruthmarkOpenCodeClaimVerifierAgent = (): string => { + const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_claim_verifier; + + return renderOpenCodeReadOnlyAgent({ + invocation: profile.copilotName, + description: profile.description, + instructions: profile.instructions, + }); +}; + +export const renderTruthmarkOpenCodeDocReviewerAgent = (): string => { + const profile = TRUTHMARK_SUBAGENT_PROFILES.truth_doc_reviewer; + + return renderOpenCodeReadOnlyAgent({ + invocation: profile.copilotName, + description: profile.description, + instructions: profile.instructions, + }); +}; +export const renderTruthmarkOpenCodeDocWriterAgent = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const profile = TRUTHMARK_WRITE_SUBAGENT_PROFILES.truth_doc_writer; + + return renderOpenCodeWriteAgent({ + invocation: profile.copilotName, + description: profile.description, + instructions: profile.instructions, + config, + }); +}; + +export const renderTruthmarkStructureSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthStructureSkillBody(config); +}; + +export const renderTruthmarkStructureLocalSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthStructureSkillBody(config); +}; + +export const renderTruthmarkStructureClaudeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthStructureSkillBody(config, { + includeClaudeSubagentMode: true, + }); +}; + +export const renderTruthmarkStructureSkillMetadata = (): string => { + const workflow = getTruthmarkWorkflow("truthmark-structure"); + + return `interface: + display_name: "${workflow.displayName}" + short_description: "${workflow.shortDescription}" + default_prompt: "${workflow.defaultPrompt}" + +policy: + allow_implicit_invocation: ${workflow.allowImplicitInvocation} + +truthmark: + version: "${TRUTHMARK_VERSION}" + refresh_command: "truthmark init" +`; +}; + +export const renderTruthmarkDocumentSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthDocumentSkillBody(config, { + includeCodexSubagentMode: true, + }); +}; + +export const renderTruthmarkDocumentLocalSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthDocumentSkillBody(config); +}; + +export const renderTruthmarkDocumentClaudeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthDocumentSkillBody(config, { + includeClaudeSubagentMode: true, + }); +}; + +export const renderTruthmarkDocumentOpenCodeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthDocumentSkillBody(config, { + includeOpenCodeSubagentMode: true, + }); +}; + +export const renderTruthmarkDocumentSkillMetadata = (): string => { + const workflow = getTruthmarkWorkflow("truthmark-document"); + + return `interface: + display_name: "${workflow.displayName}" + short_description: "${workflow.shortDescription}" + default_prompt: "${workflow.defaultPrompt}" + +policy: + allow_implicit_invocation: ${workflow.allowImplicitInvocation} + +truthmark: + version: "${TRUTHMARK_VERSION}" + refresh_command: "truthmark init" +`; +}; + +export const renderTruthmarkSyncSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthSyncSkillBody(config, { includeCodexSubagentMode: true }); +}; + +export const renderTruthmarkSyncLocalSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthSyncSkillBody(config); +}; + +export const renderTruthmarkSyncClaudeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthSyncSkillBody(config, { includeClaudeSubagentMode: true }); +}; + +export const renderTruthmarkSyncOpenCodeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthSyncSkillBody(config, { + includeOpenCodeSubagentMode: true, + }); +}; + +export const renderTruthmarkSyncSkillMetadata = (): string => { + const workflow = getTruthmarkWorkflow("truthmark-sync"); + + return `interface: + display_name: "${workflow.displayName}" + short_description: "${workflow.shortDescription}" + default_prompt: "${workflow.defaultPrompt}" + +policy: + allow_implicit_invocation: ${workflow.allowImplicitInvocation} + +truthmark: + version: "${TRUTHMARK_VERSION}" + refresh_command: "truthmark init" +`; +}; + +const renderTruthmarkRealizeSkillBody = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const truthDocsRoot = resolveTruthDocsRoot(config); + const workflow = getTruthmarkWorkflow("truthmark-realize"); + + return `--- +name: truthmark-realize +description: ${workflow.description} +argument-hint: Optional truth doc path, area, or desired code behavior to realize +user-invocable: true +truthmark-version: ${TRUTHMARK_VERSION} +--- + +# Truthmark Realize + +Use this skill only when the user explicitly asks to realize truth docs into code. + +Invocations: OpenCode /skill truthmark-realize; Codex /truthmark-realize or $truthmark-realize; Claude Code /truthmark-realize; GitHub Copilot /truthmark-realize; Gemini CLI /truthmark:realize. + +Truth Realize is doc-first: + +- truth docs lead +- code follows +- Truth Realize never edits the truth docs it is realizing + +Workflow: + +1. Read the updated truth docs named by the user, or infer the relevant docs from ${config.docs.routing.rootIndex}. +2. Read .truthmark/config.yml, ${config.docs.routing.rootIndex}, relevant child route files, tests, and the relevant functional code. +3. ${EVIDENCE_AUTHORITY_INSTRUCTIONS} +${renderTruthDocOwnershipGateSection( + "source truth docs before writing code", + "if a source truth doc is broad, mixed-owner, index-like, unrouteable, stale, or conflicts with implementation evidence, block before writing code and recommend Truth Structure or Truth Document", +)} +4. Update functional code only so implementation matches bounded, current truth claims from the source docs. +5. Do not edit truth docs or truth routing while realizing those docs. +6. Run relevant tests for the changed code. +7. Report changed code files and verification steps. +${renderHierarchySummary(config)} + +Read and write boundaries: + +- may read truth docs, routing docs, and relevant functional code +- may write functional code only +- must not edit truth docs or truth routing while realizing those docs + +Report completion in this shape: + +\`\`\`md +Truth Realize: completed + +Truth docs used: +- ${truthDocsRoot}/authentication/session-timeout.md + +Code updated: +- src/auth/session.ts + +Verification: +- npm test -- auth +\`\`\` +`; +}; + +export const renderTruthmarkRealizeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthmarkRealizeSkillBody(config); +}; + +export const renderTruthmarkRealizeLocalSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthmarkRealizeSkillBody(config); +}; + +export const renderTruthmarkRealizeSkillMetadata = (): string => { + const workflow = getTruthmarkWorkflow("truthmark-realize"); + + return `interface: + display_name: "${workflow.displayName}" + short_description: "${workflow.shortDescription}" + default_prompt: "${workflow.defaultPrompt}" + +policy: + allow_implicit_invocation: ${workflow.allowImplicitInvocation} + +truthmark: + version: "${TRUTHMARK_VERSION}" + refresh_command: "truthmark init" +`; +}; + +export const renderTruthmarkPreviewSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthPreviewSkillBody(config); +}; + +export const renderTruthmarkPreviewLocalSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthPreviewSkillBody(config); +}; + +export const renderTruthmarkPreviewClaudeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthPreviewSkillBody(config); +}; + +export const renderTruthmarkPreviewOpenCodeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthPreviewSkillBody(config); +}; + +export const renderTruthmarkPreviewSkillMetadata = (): string => { + const workflow = getTruthmarkWorkflow("truthmark-preview"); + + return `interface: + display_name: "${workflow.displayName}" + short_description: "${workflow.shortDescription}" + default_prompt: "${workflow.defaultPrompt}" + +policy: + allow_implicit_invocation: ${workflow.allowImplicitInvocation} + +truthmark: + version: "${TRUTHMARK_VERSION}" + refresh_command: "truthmark init" +`; +}; + +export const renderTruthmarkCheckSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthCheckSkillBody(config, { includeCodexSubagentMode: true }); +}; + +export const renderTruthmarkCheckLocalSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthCheckSkillBody(config); +}; + +export const renderTruthmarkCheckClaudeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthCheckSkillBody(config, { includeClaudeSubagentMode: true }); +}; + +export const renderTruthmarkCheckOpenCodeSkill = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + return renderTruthCheckSkillBody(config, { + includeOpenCodeSubagentMode: true, + }); +}; + +export const renderTruthmarkCheckSkillMetadata = (): string => { + const workflow = getTruthmarkWorkflow("truthmark-check"); + + return `interface: + display_name: "${workflow.displayName}" + short_description: "${workflow.shortDescription}" + default_prompt: "${workflow.defaultPrompt}" + +policy: + allow_implicit_invocation: ${workflow.allowImplicitInvocation} + +truthmark: + version: "${TRUTHMARK_VERSION}" + refresh_command: "truthmark init" +`; +}; + +export const renderTruthmarkGeminiStructureCommand = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-structure"); + + return renderGeminiCommand( + workflow.description, + renderTruthStructureSkillBody(config), + ); +}; + +export const renderTruthmarkGeminiDocumentCommand = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-document"); + + return renderGeminiCommand( + workflow.description, + renderTruthDocumentSkillBody(config), + ); +}; + +export const renderTruthmarkGeminiSyncCommand = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-sync"); + + return renderGeminiCommand( + workflow.description, + renderTruthSyncSkillBody(config), + ); +}; + +export const renderTruthmarkGeminiRealizeCommand = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-realize"); + + return renderGeminiCommand( + workflow.description, + renderTruthmarkRealizeSkillBody(config), + ); +}; + +export const renderTruthmarkGeminiCheckCommand = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-check"); + + return renderGeminiCommand( + workflow.description, + renderTruthCheckSkillBody(config), + ); +}; + +export const renderTruthmarkGeminiPreviewCommand = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-preview"); + + return renderGeminiCommand( + workflow.description, + renderTruthPreviewSkillBody(config), + ); +}; + +export const renderTruthmarkCopilotStructurePrompt = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-structure"); + + return renderCopilotPromptFile( + workflow.description, + renderTruthStructureSkillBody(config, { + includeCopilotCustomAgentMode: true, + }), + ); +}; + +export const renderTruthmarkCopilotDocumentPrompt = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-document"); + + return renderCopilotPromptFile( + workflow.description, + renderTruthDocumentSkillBody(config, { + includeCopilotCustomAgentMode: true, + }), + ); +}; + +export const renderTruthmarkCopilotSyncPrompt = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-sync"); + + return renderCopilotPromptFile( + workflow.description, + renderTruthSyncSkillBody(config, { + includeCopilotCustomAgentMode: true, + }), + ); +}; + +export const renderTruthmarkCopilotRealizePrompt = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-realize"); + + return renderCopilotPromptFile( + workflow.description, + renderTruthmarkRealizeSkillBody(config), + ); +}; + +export const renderTruthmarkCopilotCheckPrompt = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-check"); + + return renderCopilotPromptFile( + workflow.description, + renderTruthCheckSkillBody(config, { + includeCopilotCustomAgentMode: true, + }), + ); +}; + +export const renderTruthmarkCopilotPreviewPrompt = ( + config: TruthmarkConfig = defaultAgentConfig(), +): string => { + const workflow = getTruthmarkWorkflow("truthmark-preview"); + + return renderCopilotPromptFile( + workflow.description, + renderTruthPreviewSkillBody(config), + ); +}; diff --git a/tests/agents/prompts.test.ts b/tests/agents/prompts.test.ts index d6ab83c..8001c9e 100644 --- a/tests/agents/prompts.test.ts +++ b/tests/agents/prompts.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { createDefaultConfig } from "../../src/config/defaults.js"; import { renderTruthRealizePrompt } from "../../src/agents/prompts.js"; -import { renderTruthmarkRealizeSkill } from "../../src/templates/codex-skills.js"; +import { renderTruthmarkRealizeSkill } from "../../src/templates/workflow-surfaces.js"; describe("renderTruthRealizePrompt", () => { it("renders manual doc-first realization guidance without a dedicated CLI command", () => { diff --git a/tests/agents/truth-check.test.ts b/tests/agents/truth-check.test.ts index fa93c36..5da36e7 100644 --- a/tests/agents/truth-check.test.ts +++ b/tests/agents/truth-check.test.ts @@ -4,11 +4,29 @@ import { TRUTH_CHECK_EXPLICIT_INVOCATIONS, renderTruthCheckSkillBody, } from "../../src/agents/truth-check.js"; +import { createDefaultConfig } from "../../src/config/defaults.js"; import { + renderTruthmarkClaimVerifierAgent, renderTruthmarkCheckLocalSkill, + renderTruthmarkCheckClaudeSkill, renderTruthmarkCheckSkill, renderTruthmarkCheckSkillMetadata, -} from "../../src/templates/codex-skills.js"; + renderTruthmarkClaudeClaimVerifierAgent, + renderTruthmarkClaudeDocReviewerAgent, + renderTruthmarkClaudeDocWriterAgent, + renderTruthmarkClaudeRouteAuditorAgent, + renderTruthmarkCopilotClaimVerifierAgent, + renderTruthmarkCopilotDocReviewerAgent, + renderTruthmarkDocReviewerAgent, + renderTruthmarkDocWriterAgent, + renderTruthmarkOpenCodeClaimVerifierAgent, + renderTruthmarkOpenCodeDocReviewerAgent, + renderTruthmarkOpenCodeDocWriterAgent, + renderTruthmarkOpenCodeRouteAuditorAgent, + renderTruthmarkCopilotDocWriterAgent, + renderTruthmarkCopilotRouteAuditorAgent, + renderTruthmarkRouteAuditorAgent, +} from "../../src/templates/workflow-surfaces.js"; import { TRUTHMARK_VERSION } from "../../src/version.js"; describe("renderTruthCheckSkillBody", () => { @@ -56,11 +74,37 @@ describe("renderTruthCheckSkillBody", () => { }); describe("Truth Check generated surfaces", () => { + const readOnlyContextBoundary = + "Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence."; + it("renders Codex metadata and OpenCode skill content", () => { expect(renderTruthmarkCheckSkill()).toContain("name: truthmark-check"); + expect(renderTruthmarkCheckSkill()).toContain("Codex subagent mode:"); + expect(renderTruthmarkCheckSkill()).toContain( + "use automatically when this workflow runs in Codex", + ); + expect(renderTruthmarkCheckSkill()).toContain("truth_route_auditor"); + expect(renderTruthmarkCheckSkill()).toContain("truth_claim_verifier"); + expect(renderTruthmarkCheckSkill()).toContain("truth_doc_reviewer"); + expect(renderTruthmarkCheckSkill()).toContain( + "Parent agent owns the final Truth Check report", + ); expect(renderTruthmarkCheckLocalSkill()).toContain( "/skill truthmark-check", ); + expect(renderTruthmarkCheckLocalSkill()).not.toContain("Codex subagent mode:"); + expect(renderTruthmarkCheckClaudeSkill()).toContain( + "Claude Code subagent mode:", + ); + expect(renderTruthmarkCheckClaudeSkill()).toContain( + "truth-route-auditor subagent", + ); + expect(renderTruthmarkCheckClaudeSkill()).toContain( + "truth-claim-verifier subagent", + ); + expect(renderTruthmarkCheckClaudeSkill()).toContain( + "truth-doc-reviewer subagent", + ); expect(renderTruthmarkCheckLocalSkill()).toContain("/truthmark:check"); expect(renderTruthmarkCheckSkillMetadata()).toContain( 'display_name: "Truthmark Check"', @@ -72,4 +116,135 @@ describe("Truth Check generated surfaces", () => { `version: "${TRUTHMARK_VERSION}"`, ); }); + + it("renders read-only Codex verifier agents for truth audits", () => { + const routeAuditor = renderTruthmarkRouteAuditorAgent(); + const claimVerifier = renderTruthmarkClaimVerifierAgent(); + const docReviewer = renderTruthmarkDocReviewerAgent(); + + expect(routeAuditor).toContain('name = "truth_route_auditor"'); + expect(routeAuditor).toContain('sandbox_mode = "read-only"'); + expect(routeAuditor).toContain(readOnlyContextBoundary); + expect(routeAuditor).toContain("Return JSON only"); + expect(routeAuditor).toContain("recommendedWorkflow"); + expect(routeAuditor).not.toContain("write truth docs"); + + expect(claimVerifier).toContain('name = "truth_claim_verifier"'); + expect(claimVerifier).toContain('sandbox_mode = "read-only"'); + expect(claimVerifier).toContain(readOnlyContextBoundary); + expect(claimVerifier).toContain("supported | narrowed | removed | blocked"); + expect(claimVerifier).toContain("Do not edit files"); + + expect(docReviewer).toContain('name = "truth_doc_reviewer"'); + expect(docReviewer).toContain('sandbox_mode = "read-only"'); + expect(docReviewer).toContain(readOnlyContextBoundary); + expect(docReviewer).toContain("Product Decisions"); + expect(docReviewer).toContain("Rationale"); + }); + it("renders read-only Claude Code verifier subagents for truth audits", () => { + const routeAuditor = renderTruthmarkClaudeRouteAuditorAgent(); + const claimVerifier = renderTruthmarkClaudeClaimVerifierAgent(); + const docReviewer = renderTruthmarkClaudeDocReviewerAgent(); + expect(routeAuditor).toContain("name: truth-route-auditor"); + expect(routeAuditor).toContain("tools: Read, Grep, Glob, LS"); + expect(routeAuditor).toContain("Manual invocation: use the truth-route-auditor subagent"); + expect(routeAuditor).toContain(readOnlyContextBoundary); + expect(routeAuditor).toContain("Do not edit files"); + expect(routeAuditor).toContain("Return JSON only"); + expect(claimVerifier).toContain("name: truth-claim-verifier"); + expect(claimVerifier).toContain("tools: Read, Grep, Glob, LS"); + expect(claimVerifier).toContain(readOnlyContextBoundary); + expect(claimVerifier).toContain("supported | narrowed | removed | blocked"); + expect(claimVerifier).toContain("Do not edit files"); + expect(docReviewer).toContain("name: truth-doc-reviewer"); + expect(docReviewer).toContain("tools: Read, Grep, Glob, LS"); + expect(docReviewer).toContain(readOnlyContextBoundary); + expect(docReviewer).toContain("Product Decisions"); + expect(docReviewer).toContain("Rationale"); + }); + it("renders read-only OpenCode verifier subagents for truth audits", () => { + const routeAuditor = renderTruthmarkOpenCodeRouteAuditorAgent(); + const claimVerifier = renderTruthmarkOpenCodeClaimVerifierAgent(); + const docReviewer = renderTruthmarkOpenCodeDocReviewerAgent(); + expect(routeAuditor).toContain("mode: subagent"); + expect(routeAuditor).toContain("edit: deny"); + expect(routeAuditor).toContain("task: deny"); + expect(routeAuditor).toContain("@truth-route-auditor"); + expect(routeAuditor).toContain(readOnlyContextBoundary); + expect(routeAuditor).toContain("Return JSON only"); + expect(routeAuditor).toContain("recommendedWorkflow"); + expect(claimVerifier).toContain("mode: subagent"); + expect(claimVerifier).toContain("edit: deny"); + expect(claimVerifier).toContain(readOnlyContextBoundary); + expect(claimVerifier).toContain("supported | narrowed | removed | blocked"); + expect(claimVerifier).toContain("Do not edit files"); + expect(docReviewer).toContain("mode: subagent"); + expect(docReviewer).toContain("edit: deny"); + expect(docReviewer).toContain(readOnlyContextBoundary); + expect(docReviewer).toContain("Product Decisions"); + expect(docReviewer).toContain("Rationale"); + }); + + it("renders read-only Copilot verifier agents with bounded context", () => { + const routeAuditor = renderTruthmarkCopilotRouteAuditorAgent(); + const claimVerifier = renderTruthmarkCopilotClaimVerifierAgent(); + const docReviewer = renderTruthmarkCopilotDocReviewerAgent(); + + expect(routeAuditor).toContain("name: truth-route-auditor"); + expect(routeAuditor).toContain("tools: [read, search]"); + expect(routeAuditor).toContain(readOnlyContextBoundary); + expect(routeAuditor).toContain("Return JSON only"); + expect(claimVerifier).toContain("name: truth-claim-verifier"); + expect(claimVerifier).toContain(readOnlyContextBoundary); + expect(claimVerifier).toContain("supported | narrowed | removed | blocked"); + expect(docReviewer).toContain("name: truth-doc-reviewer"); + expect(docReviewer).toContain(readOnlyContextBoundary); + expect(docReviewer).toContain("Rationale"); + }); + + it("renders write-capable doc writer agents behind explicit leases", () => { + const codexWriter = renderTruthmarkDocWriterAgent(); + const openCodeWriter = renderTruthmarkOpenCodeDocWriterAgent(); + const claudeWriter = renderTruthmarkClaudeDocWriterAgent(); + const copilotWriter = renderTruthmarkCopilotDocWriterAgent(); + const defaultConfig = createDefaultConfig(); + const customOpenCodeWriter = renderTruthmarkOpenCodeDocWriterAgent({ + ...defaultConfig, + docs: { + ...defaultConfig.docs, + roots: { + ...defaultConfig.docs.roots, + truth: "product/truth", + }, + routing: { + ...defaultConfig.docs.routing, + rootIndex: "product/routes/index.md", + areaFilesRoot: "product/routes/areas", + }, + }, + }); + + expect(codexWriter).toContain('name = "truth_doc_writer"'); + expect(codexWriter).toContain('sandbox_mode = "workspace-write"'); + expect(codexWriter).toContain("Require an explicit write lease"); + expect(codexWriter).not.toContain(readOnlyContextBoundary); + expect(codexWriter).toContain("Return YAML only"); + expect(openCodeWriter).toContain("mode: subagent"); + expect(openCodeWriter).toContain('"docs/truth/**": allow'); + expect(openCodeWriter).toContain('"docs/truthmark/areas.md": allow'); + expect(openCodeWriter).toContain("@truth-doc-writer"); + expect(customOpenCodeWriter).toContain('"product/truth/**": allow'); + expect(customOpenCodeWriter).toContain( + '"product/routes/index.md": allow', + ); + expect(customOpenCodeWriter).toContain( + '"product/routes/areas/**/*.md": allow', + ); + expect(customOpenCodeWriter).not.toContain('"docs/truth/**": allow'); + expect(claudeWriter).toContain("name: truth-doc-writer"); + expect(claudeWriter).toContain("tools: Read, Grep, Glob, LS, Edit, MultiEdit"); + expect(copilotWriter).toContain("name: truth-doc-writer"); + expect(copilotWriter).toContain("tools: [read, search, edit]"); + expect(copilotWriter).toContain("offLeaseChanges"); + }); }); diff --git a/tests/agents/truth-document.test.ts b/tests/agents/truth-document.test.ts index 98502bf..41cd735 100644 --- a/tests/agents/truth-document.test.ts +++ b/tests/agents/truth-document.test.ts @@ -8,10 +8,11 @@ import { renderTruthDocumentSkillBody, } from "../../src/agents/truth-document.js"; import { + renderTruthmarkDocumentClaudeSkill, renderTruthmarkDocumentLocalSkill, renderTruthmarkDocumentSkill, renderTruthmarkDocumentSkillMetadata, -} from "../../src/templates/codex-skills.js"; +} from "../../src/templates/workflow-surfaces.js"; import { TRUTHMARK_VERSION } from "../../src/version.js"; describe("renderTruthDocumentSkillBody", () => { @@ -148,9 +149,46 @@ describe("renderTruthDocumentSkillBody", () => { describe("Truth Document generated surfaces", () => { it("renders Codex metadata and OpenCode skill content", () => { expect(renderTruthmarkDocumentSkill()).toContain("name: truthmark-document"); + expect(renderTruthmarkDocumentSkill()).toContain("Codex subagent mode:"); + expect(renderTruthmarkDocumentSkill()).toContain( + "use automatically when this workflow runs in Codex", + ); + expect(renderTruthmarkDocumentSkill()).toContain("truth_route_auditor"); + expect(renderTruthmarkDocumentSkill()).toContain("truth_claim_verifier"); + expect(renderTruthmarkDocumentSkill()).toContain("truth_doc_writer"); + expect(renderTruthmarkDocumentSkill()).toContain( + "Parent agent owns Truth Document acceptance, lease validation, and final report", + ); + expect(renderTruthmarkDocumentSkill()).toContain( + "validate the worker report against the actual worker diff", + ); + expect(renderTruthmarkDocumentClaudeSkill()).toContain( + "Claude Code subagent mode:", + ); + expect(renderTruthmarkDocumentClaudeSkill()).toContain( + "use automatically when this workflow runs in Claude Code", + ); + expect(renderTruthmarkDocumentClaudeSkill()).toContain( + "truth-route-auditor subagent", + ); + expect(renderTruthmarkDocumentClaudeSkill()).toContain( + "truth-claim-verifier subagent", + ); + expect(renderTruthmarkDocumentClaudeSkill()).toContain( + "truth-doc-writer subagent", + ); + expect(renderTruthmarkDocumentClaudeSkill()).toContain( + "Parent agent owns Truth Document acceptance, lease validation, and final report", + ); expect(renderTruthmarkDocumentLocalSkill()).toContain( "/skill truthmark-document", ); + expect(renderTruthmarkDocumentLocalSkill()).not.toContain( + "Codex subagent mode:", + ); + expect(renderTruthmarkDocumentLocalSkill()).not.toContain( + "Claude Code subagent mode:", + ); expect(renderTruthmarkDocumentLocalSkill()).toContain("/truthmark:document"); expect(renderTruthmarkDocumentSkillMetadata()).toContain( 'display_name: "Truthmark Document"', diff --git a/tests/agents/truth-preview.test.ts b/tests/agents/truth-preview.test.ts new file mode 100644 index 0000000..42815f5 --- /dev/null +++ b/tests/agents/truth-preview.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vitest"; +import { + TRUTH_PREVIEW_EXPLICIT_INVOCATIONS, + renderTruthPreviewSkillBody, +} from "../../src/agents/truth-preview.js"; +import { + renderTruthmarkPreviewLocalSkill, + renderTruthmarkPreviewSkill, + renderTruthmarkPreviewSkillMetadata, +} from "../../src/templates/workflow-surfaces.js"; +import { TRUTHMARK_VERSION } from "../../src/version.js"; + +describe("renderTruthPreviewSkillBody", () => { + it("renders a thin explicit read-only preview workflow", () => { + const skill = renderTruthPreviewSkillBody(); + + expect(TRUTH_PREVIEW_EXPLICIT_INVOCATIONS).toContain("/truthmark:preview"); + expect(skill).toContain("name: truthmark-preview"); + expect(skill).toContain(`truthmark-version: ${TRUTHMARK_VERSION}`); + expect(skill).toContain("Truth Preview is read-only"); + expect(skill).toContain("intended, not authorized"); + expect(skill).toContain("must not edit files"); + expect(skill).toContain("must not create truth docs"); + expect(skill).toContain("must not update routing"); + expect(skill).toContain("must not run Truth Sync automatically"); + expect(skill).toContain("must not replace Truth Check"); + expect(skill).toContain("must not claim final correctness"); + expect(skill).toContain("must not issue write leases"); + expect(skill).toContain("must not mutate code"); + expect(skill).toContain("Likely workflow"); + expect(skill).toContain("Likely route owner"); + expect(skill).toContain("Expected write classes"); + expect(skill).toContain("Suggested subagent use"); + expect(skill).toContain("Blocking ambiguity"); + expect(skill).toContain("Handoff:"); + expect(skill).toContain("truth_route_auditor"); + expect(skill).not.toContain("truth_doc_writer"); + }); +}); + +describe("Truth Preview generated surfaces", () => { + it("renders Codex skill and metadata without implicit invocation", () => { + expect(renderTruthmarkPreviewSkill()).toContain("name: truthmark-preview"); + expect(renderTruthmarkPreviewSkill()).toContain("Truth Preview: completed"); + expect(renderTruthmarkPreviewLocalSkill()).toContain("/skill truthmark-preview"); + expect(renderTruthmarkPreviewSkillMetadata()).toContain( + 'display_name: "Truthmark Preview"', + ); + expect(renderTruthmarkPreviewSkillMetadata()).toContain( + "allow_implicit_invocation: false", + ); + }); +}); diff --git a/tests/agents/truth-structure.test.ts b/tests/agents/truth-structure.test.ts index 1a6fb88..af74b87 100644 --- a/tests/agents/truth-structure.test.ts +++ b/tests/agents/truth-structure.test.ts @@ -8,10 +8,11 @@ import { renderTruthStructureSkillBody, } from "../../src/agents/truth-structure.js"; import { + renderTruthmarkStructureClaudeSkill, renderTruthmarkStructureLocalSkill, renderTruthmarkStructureSkill, renderTruthmarkStructureSkillMetadata, -} from "../../src/templates/codex-skills.js"; +} from "../../src/templates/workflow-surfaces.js"; import { TRUTHMARK_VERSION } from "../../src/version.js"; describe("renderTruthStructureSkillBody", () => { @@ -131,6 +132,29 @@ describe("renderTruthStructureSkillBody", () => { expect(skill).toContain( "README.md files are indexes, not Truth Sync targets", ); + expect(skill).toContain("## New area setup"); + expect(skill).toContain( + "Use when a user asks to onboard a new code area into Truthmark", + ); + expect(skill).toContain( + "a new package, controller, domain, or product area lacks bounded truth ownership", + ); + expect(skill).toContain("inspect the named code area"); + expect(skill).toContain( + "infer bounded product or behavior ownership", + ); + expect(skill).toContain( + "choose the owning route when ownership is clear; otherwise propose the route and block for review", + ); + expect(skill).toContain( + "create starter truth docs only where current truth is missing", + ); + expect(skill).toContain("report the initial truth boundary"); + expect(skill).toContain("do not edit functional code"); + expect(skill).toContain( + "do not perform full behavior documentation unless evidence is inspected and the task explicitly asks for it", + ); + expect(skill).toContain("do not create generic catch-all docs"); expect(skill).toContain( "split mixed-owner truth docs into bounded owner docs before adding new behavior claims", ); @@ -144,6 +168,7 @@ describe("renderTruthStructureSkillBody", () => { expect(skill).toContain("Truth Structure: completed"); expect(skill).toContain("Areas reviewed"); expect(skill).toContain("Routing updated"); + expect(skill).toContain("Initial truth boundary"); expect(skill).toContain("Truth docs created"); expect(skill).toContain("Truth docs restructured"); expect(skill).toContain("Evidence checked"); @@ -204,6 +229,21 @@ describe("Truth Structure generated surfaces", () => { expect(renderTruthmarkStructureLocalSkill()).toContain( "/truthmark:structure", ); + expect(renderTruthmarkStructureClaudeSkill()).toContain( + "Claude Code subagent mode:", + ); + expect(renderTruthmarkStructureClaudeSkill()).toContain( + "use automatically when this workflow runs in Claude Code", + ); + expect(renderTruthmarkStructureClaudeSkill()).toContain( + "truth-route-auditor subagent", + ); + expect(renderTruthmarkStructureClaudeSkill()).toContain( + "Parent agent owns all Truth Structure writes and final topology decisions", + ); + expect(renderTruthmarkStructureLocalSkill()).not.toContain( + "Claude Code subagent mode:", + ); expect(renderTruthmarkStructureSkillMetadata()).toContain( 'display_name: "Truthmark Structure"', ); diff --git a/tests/agents/truth-sync.test.ts b/tests/agents/truth-sync.test.ts index e60a9ce..a6d1865 100644 --- a/tests/agents/truth-sync.test.ts +++ b/tests/agents/truth-sync.test.ts @@ -10,8 +10,11 @@ import { import { renderTruthmarkCopilotSyncPrompt, renderTruthmarkGeminiSyncCommand, + renderTruthmarkSyncClaudeSkill, + renderTruthmarkSyncLocalSkill, + renderTruthmarkSyncSkill, renderTruthmarkSyncSkillMetadata, -} from "../../src/templates/codex-skills.js"; +} from "../../src/templates/workflow-surfaces.js"; import { TRUTHMARK_VERSION } from "../../src/version.js"; describe("renderTruthSyncWorkerPrompt", () => { @@ -20,6 +23,7 @@ describe("renderTruthSyncWorkerPrompt", () => { expect(TRUTH_SYNC_EXPLICIT_INVOCATIONS).toContain("/truthmark:sync"); expect(prompt).toContain("parent provides the task focus"); + expect(prompt).toContain("explicit write lease"); expect(prompt).toContain( "staged, unstaged, and untracked functional code directly", ); @@ -27,9 +31,11 @@ describe("renderTruthSyncWorkerPrompt", () => { expect(prompt).toContain("Code verification is parent-owned"); expect(prompt).toContain("docs/truthmark/areas.md"); expect(prompt).toContain("status: completed | blocked"); + expect(prompt).toContain("filesChanged"); expect(prompt).toContain("changedCodeReviewed"); expect(prompt).toContain("truthDocsUpdated"); expect(prompt).toContain("routingDocsUpdated"); + expect(prompt).toContain("offLeaseChanges"); expect(prompt).toContain("notes"); expect(prompt).toContain("blockedReason"); expect(prompt).toContain("manualReviewFiles"); @@ -76,7 +82,7 @@ describe("renderTruthSyncSkillBody", () => { "truthmark check --json --workflow truth-sync", ); expect(skillBody).toContain( - "verify only truth docs and docs/truthmark/areas.md changed", + "verify only truth docs and leased truth routing files changed", ); expect(skillBody).toContain( "Read .truthmark/config.yml, the configured root route index", @@ -161,8 +167,10 @@ describe("renderTruthSyncSkillBody", () => { expect(skillBody).toContain("Claim:"); expect(skillBody).toContain("Result: supported"); expect(skillBody).toContain("structured Truth Sync report contract"); - expect(skillBody).toContain("ownershipReviewed: string[]"); - expect(skillBody).toContain("truthDocsSplit?: string[]"); + expect(skillBody).not.toContain("### Truth Sync Worker"); + expect(skillBody).not.toContain( + "may write truth docs and docs/truthmark/areas.md only for Truth Sync alignment", + ); expect(skillBody).toContain( "verify the final report records ownership review, structure requirement, split, restructure, or blocked reason", ); @@ -191,7 +199,9 @@ describe("renderTruthSyncSkillBody", () => { expect(skillBody).toContain("docs/truth/repository/overview.md"); expect(skillBody).toContain("docs/routes/index.md:11"); - expect(skillBody).toContain("verify only truth docs and docs/routes/index.md changed"); + expect(skillBody).toContain( + "verify only truth docs and leased truth routing files changed", + ); }); }); @@ -210,4 +220,44 @@ describe("Truth Sync generated metadata", () => { "description: 'Use automatically at finish-time after functional code changes", ); }); + + it("adds host-specific subagent guidance without changing generic surfaces", () => { + expect(renderTruthmarkSyncSkill()).toContain("Codex subagent mode:"); + expect(renderTruthmarkSyncSkill()).toContain( + "use automatically when this workflow runs in Codex", + ); + expect(renderTruthmarkSyncSkill()).toContain("truth_route_auditor"); + expect(renderTruthmarkSyncSkill()).toContain("truth_claim_verifier"); + expect(renderTruthmarkSyncSkill()).toContain("truth_doc_writer"); + expect(renderTruthmarkSyncSkill()).toContain( + "Parent agent owns Truth Sync acceptance, lease validation, and final report", + ); + expect(renderTruthmarkSyncSkill()).toContain( + "validate the worker report against the actual worker diff", + ); + expect(renderTruthmarkSyncClaudeSkill()).toContain( + "Claude Code subagent mode:", + ); + expect(renderTruthmarkSyncClaudeSkill()).toContain( + "use automatically when this workflow runs in Claude Code", + ); + expect(renderTruthmarkSyncClaudeSkill()).toContain( + "truth-route-auditor subagent", + ); + expect(renderTruthmarkSyncClaudeSkill()).toContain( + "truth-claim-verifier subagent", + ); + expect(renderTruthmarkSyncClaudeSkill()).toContain( + "truth-doc-writer subagent", + ); + expect(renderTruthmarkSyncClaudeSkill()).toContain( + "Parent agent owns Truth Sync acceptance, lease validation, and final report", + ); + expect(renderTruthmarkSyncLocalSkill()).not.toContain("Codex subagent mode:"); + expect(renderTruthmarkSyncLocalSkill()).not.toContain( + "Claude Code subagent mode:", + ); + expect(renderTruthmarkGeminiSyncCommand()).not.toContain("Codex subagent mode:"); + expect(renderTruthmarkCopilotSyncPrompt()).not.toContain("Codex subagent mode:"); + }); }); diff --git a/tests/agents/workflow-manifest.test.ts b/tests/agents/workflow-manifest.test.ts index 0c7576a..5434b96 100644 --- a/tests/agents/workflow-manifest.test.ts +++ b/tests/agents/workflow-manifest.test.ts @@ -8,9 +8,10 @@ import { } from "../../src/agents/workflow-manifest.js"; import { renderTruthCheckSkillBody } from "../../src/agents/truth-check.js"; import { renderTruthDocumentSkillBody } from "../../src/agents/truth-document.js"; +import { renderTruthPreviewSkillBody } from "../../src/agents/truth-preview.js"; import { renderTruthStructureSkillBody } from "../../src/agents/truth-structure.js"; import { renderTruthSyncSkillBody } from "../../src/agents/truth-sync.js"; -import { renderTruthmarkRealizeSkill } from "../../src/templates/codex-skills.js"; +import { renderTruthmarkRealizeSkill } from "../../src/templates/workflow-surfaces.js"; const renderWorkflowSkill = (id: (typeof TRUTHMARK_WORKFLOW_IDS)[number]) => { switch (id) { @@ -20,6 +21,8 @@ const renderWorkflowSkill = (id: (typeof TRUTHMARK_WORKFLOW_IDS)[number]) => { return renderTruthStructureSkillBody(); case "truthmark-document": return renderTruthDocumentSkillBody(); + case "truthmark-preview": + return renderTruthPreviewSkillBody(); case "truthmark-realize": return renderTruthmarkRealizeSkill(); case "truthmark-check": @@ -33,7 +36,9 @@ describe("Truthmark workflow manifest", () => { const parsed = matter(renderWorkflowSkill(id)); expect(parsed.data.name).toBe(id); - expect(parsed.data.description).toBe(getTruthmarkWorkflow(id).description); + expect(parsed.data.description).toBe( + getTruthmarkWorkflow(id).description, + ); } }); @@ -50,6 +55,66 @@ describe("Truthmark workflow manifest", () => { } }); + it("defines read-only and write-capable subagent recommendations by workflow", () => { + expect(TRUTHMARK_WORKFLOW_MANIFEST["truthmark-preview"].subagents).toEqual([ + "truth_route_auditor", + ]); + expect( + getTruthmarkWorkflow("truthmark-preview").writeSubagents, + ).toBeUndefined(); + expect(TRUTHMARK_WORKFLOW_MANIFEST["truthmark-check"].subagents).toEqual([ + "truth_route_auditor", + "truth_claim_verifier", + "truth_doc_reviewer", + ]); + expect( + getTruthmarkWorkflow("truthmark-check").writeSubagents, + ).toBeUndefined(); + expect(TRUTHMARK_WORKFLOW_MANIFEST["truthmark-document"].subagents).toEqual( + ["truth_route_auditor", "truth_claim_verifier"], + ); + expect( + TRUTHMARK_WORKFLOW_MANIFEST["truthmark-document"].writeSubagents, + ).toEqual(["truth_doc_writer"]); + expect(TRUTHMARK_WORKFLOW_MANIFEST["truthmark-sync"].subagents).toEqual([ + "truth_route_auditor", + "truth_claim_verifier", + ]); + expect( + TRUTHMARK_WORKFLOW_MANIFEST["truthmark-sync"].writeSubagents, + ).toEqual(["truth_doc_writer"]); + expect( + TRUTHMARK_WORKFLOW_MANIFEST["truthmark-structure"].subagents, + ).toEqual(["truth_route_auditor"]); + expect( + getTruthmarkWorkflow("truthmark-structure").writeSubagents, + ).toBeUndefined(); + expect(getTruthmarkWorkflow("truthmark-realize").subagents).toBeUndefined(); + expect( + getTruthmarkWorkflow("truthmark-realize").writeSubagents, + ).toBeUndefined(); + }); + it("defines Truth Preview as an explicit read-only planning surface", () => { + const workflow = getTruthmarkWorkflow( + "truthmark-preview" as (typeof TRUTHMARK_WORKFLOW_IDS)[number], + ); + + expect(workflow.displayName).toBe("Truthmark Preview"); + expect(workflow.allowImplicitInvocation).toBe(false); + expect(workflow.allowedWrites).toEqual(["none by default"]); + expect(workflow.reportSections).toEqual([ + "Requested outcome", + "Likely workflow", + "Why this workflow", + "Likely route owner", + "Expected write classes", + "Expected target files", + "Suggested subagent use", + "Blocking ambiguity", + "Handoff", + ]); + }); + it("keeps routing descriptions focused on trigger selection", () => { for (const id of TRUTHMARK_WORKFLOW_IDS) { const { description } = getTruthmarkWorkflow(id); diff --git a/tests/agents/write-lease.test.ts b/tests/agents/write-lease.test.ts new file mode 100644 index 0000000..810dd80 --- /dev/null +++ b/tests/agents/write-lease.test.ts @@ -0,0 +1,241 @@ +import { describe, expect, it } from "vitest"; + +import { + TRUTHMARK_WRITE_WORKER_REPORT_FIELDS, + parseTruthmarkWriteWorkerReport, + type TruthmarkWriteLease, + validateTruthmarkWriteWorkerAcceptance, + validateTruthmarkWriteLeaseChanges, +} from "../../src/agents/write-lease.js"; + +const lease: TruthmarkWriteLease = { + workflow: "truthmark-sync", + worker: "truth_doc_writer", + shard: "workflow-sync-doc", + objective: "Update one routed workflow truth doc.", + requiredReads: [ + ".truthmark/config.yml", + "docs/truthmark/areas.md", + "docs/truth/workflows/truth-sync.md", + ], + allowedWrites: [ + "docs/truth/workflows/truth-sync.md", + "docs/truthmark/areas/**/*.md", + ], + forbiddenWrites: ["src/**", ".codex/**", ".opencode/**"], + evidenceRequired: ["implemented source or generated surface for each claim"], + reportFields: [...TRUTHMARK_WRITE_WORKER_REPORT_FIELDS], +}; + +const completedReport = ` +status: completed +worker: truth_doc_writer +workflow: truthmark-sync +shard: workflow-sync-doc +filesChanged: + - docs/truth/workflows/truth-sync.md +claimsChecked: + - Sync parent validation claim +evidenceChecked: + - src/agents/write-lease.ts +offLeaseChanges: [] +blockers: [] +notes: + - Updated leased doc only. +`; + +describe("validateTruthmarkWriteLeaseChanges", () => { + it("accepts only files covered by allowed writes", () => { + expect( + validateTruthmarkWriteLeaseChanges(lease, [ + "docs/truth/workflows/truth-sync.md", + "./docs/truthmark/areas/workflows.md", + ]), + ).toEqual({ + allowedChanges: [ + "docs/truth/workflows/truth-sync.md", + "docs/truthmark/areas/workflows.md", + ], + forbiddenChanges: [], + offLeaseChanges: [], + }); + }); + + it("reports off-lease and explicitly forbidden changes", () => { + expect( + validateTruthmarkWriteLeaseChanges(lease, [ + "docs/truth/workflows/truth-sync.md", + "src/agents/truth-sync.ts", + ".opencode/agents/truth-doc-writer.md", + "docs/truth/workflows/truth-document.md", + ]), + ).toEqual({ + allowedChanges: ["docs/truth/workflows/truth-sync.md"], + forbiddenChanges: [ + ".opencode/agents/truth-doc-writer.md", + "src/agents/truth-sync.ts", + ], + offLeaseChanges: [ + ".opencode/agents/truth-doc-writer.md", + "docs/truth/workflows/truth-document.md", + "src/agents/truth-sync.ts", + ], + }); + }); +}); + +describe("validateTruthmarkWriteWorkerAcceptance", () => { + it("accepts a completed worker report only when the actual diff matches the lease", () => { + expect( + validateTruthmarkWriteWorkerAcceptance({ + lease, + workerReport: parseTruthmarkWriteWorkerReport(completedReport), + actualChangedFiles: ["docs/truth/workflows/truth-sync.md"], + }), + ).toMatchObject({ + status: "accepted", + reasons: [], + changeValidation: { + allowedChanges: ["docs/truth/workflows/truth-sync.md"], + forbiddenChanges: [], + offLeaseChanges: [], + }, + }); + }); + + it("rejects worker success when the actual diff includes off-lease changes", () => { + expect( + validateTruthmarkWriteWorkerAcceptance({ + lease, + workerReport: parseTruthmarkWriteWorkerReport(completedReport), + actualChangedFiles: [ + "docs/truth/workflows/truth-sync.md", + "docs/truth/workflows/truth-document.md", + ], + }).reasons.map((reason) => reason.code), + ).toEqual(["off-lease-actual-diff", "reported-files-mismatch"]); + }); + + it("rejects worker success when the actual diff includes forbidden changes", () => { + expect( + validateTruthmarkWriteWorkerAcceptance({ + lease, + workerReport: parseTruthmarkWriteWorkerReport(completedReport), + actualChangedFiles: [ + "docs/truth/workflows/truth-sync.md", + "src/agents/truth-sync.ts", + ], + }).reasons.map((reason) => reason.code), + ).toEqual([ + "forbidden-actual-diff", + "off-lease-actual-diff", + "reported-files-mismatch", + ]); + }); + + it("rejects reports that omit required fields", () => { + const report = parseTruthmarkWriteWorkerReport(` +status: completed +worker: truth_doc_writer +workflow: truthmark-sync +shard: workflow-sync-doc +filesChanged: + - docs/truth/workflows/truth-sync.md +claimsChecked: [] +evidenceChecked: [] +offLeaseChanges: [] +blockers: [] +`); + + expect( + validateTruthmarkWriteWorkerAcceptance({ + lease, + workerReport: report, + actualChangedFiles: ["docs/truth/workflows/truth-sync.md"], + }).reasons.map((reason) => reason.code), + ).toEqual(["missing-report-field"]); + }); + + it("rejects reports with invalid identity field types", () => { + const report = parseTruthmarkWriteWorkerReport(` +status: completed +worker: 7 +workflow: truthmark-sync +shard: workflow-sync-doc +filesChanged: + - docs/truth/workflows/truth-sync.md +claimsChecked: [] +evidenceChecked: [] +offLeaseChanges: [] +blockers: [] +notes: [] +`); + + expect( + validateTruthmarkWriteWorkerAcceptance({ + lease, + workerReport: report, + actualChangedFiles: ["docs/truth/workflows/truth-sync.md"], + }).reasons.map((reason) => reason.code), + ).toEqual(["invalid-report-field"]); + }); + + it("rejects completed reports that self-report off-lease changes or blockers", () => { + const report = parseTruthmarkWriteWorkerReport(` +status: completed +worker: truth_doc_writer +workflow: truthmark-sync +shard: workflow-sync-doc +filesChanged: + - docs/truth/workflows/truth-sync.md +claimsChecked: + - Sync parent validation claim +evidenceChecked: + - src/agents/write-lease.ts +offLeaseChanges: + - docs/truth/workflows/truth-document.md +blockers: + - ownership ambiguous +notes: + - Parent review required. +`); + + expect( + validateTruthmarkWriteWorkerAcceptance({ + lease, + workerReport: report, + actualChangedFiles: ["docs/truth/workflows/truth-sync.md"], + }).reasons.map((reason) => reason.code), + ).toEqual([ + "completed-with-reported-off-lease-changes", + "completed-with-blockers", + ]); + }); + + it("blocks, rather than accepts, blocked worker reports with blockers", () => { + const report = parseTruthmarkWriteWorkerReport(` +status: blocked +worker: truth_doc_writer +workflow: truthmark-sync +shard: workflow-sync-doc +filesChanged: [] +claimsChecked: + - Sync parent validation claim +evidenceChecked: + - src/agents/write-lease.ts +offLeaseChanges: [] +blockers: + - ownership ambiguous +notes: + - Parent review required. +`); + + expect( + validateTruthmarkWriteWorkerAcceptance({ + lease, + workerReport: report, + actualChangedFiles: [], + }).status, + ).toBe("blocked"); + }); +}); diff --git a/tests/evals/workflow-routing-cases.ts b/tests/evals/workflow-routing-cases.ts new file mode 100644 index 0000000..3aa2541 --- /dev/null +++ b/tests/evals/workflow-routing-cases.ts @@ -0,0 +1,172 @@ +import type { TruthmarkWorkflowId } from "../../src/agents/workflow-manifest.js"; + +export type WorkflowRoutingEvalCase = { + id: string; + userPrompt: string; + changedFiles?: string[]; + expectedWorkflow: TruthmarkWorkflowId | "none" | "block"; + expectedReason: string; + expectedManifestSignals: string[]; + forbiddenWorkflows?: TruthmarkWorkflowId[]; + source: + | "manifest-positive" + | "manifest-negative" + | "forbidden-adjacent" + | "synthetic"; +}; + +export const WORKFLOW_ROUTING_EVAL_CASES: WorkflowRoutingEvalCase[] = [ + { + id: "sync-implicit-after-functional-code-change", + userPrompt: + "I changed src/auth/session.ts. Before finishing, sync the truth docs from that code change.", + changedFiles: ["src/auth/session.ts"], + expectedWorkflow: "truthmark-sync", + expectedReason: "functional code changed since last successful Truth Sync", + expectedManifestSignals: [ + "Use automatically at finish-time after functional code changes", + "functional code changed since last successful Truth Sync", + ], + forbiddenWorkflows: ["truthmark-realize", "truthmark-structure"], + source: "manifest-positive", + }, + { + id: "sync-explicit-invocation", + userPrompt: + "Use /truthmark-sync for the changed authentication code before we finish.", + changedFiles: ["src/auth/session.ts"], + expectedWorkflow: "truthmark-sync", + expectedReason: + "explicit /truthmark-sync, $truthmark-sync, or /truthmark:sync", + expectedManifestSignals: [ + "explicit /truthmark-sync, $truthmark-sync, or /truthmark:sync", + ], + forbiddenWorkflows: ["truthmark-realize"], + source: "manifest-positive", + }, + { + id: "sync-skip-docs-only", + userPrompt: + "I only edited documentation prose and no functional code changed; do not run finish-time Sync.", + changedFiles: ["docs/truth/repository/overview.md"], + expectedWorkflow: "none", + expectedReason: "documentation-only change", + expectedManifestSignals: [ + "documentation-only change", + "no functional code changes", + ], + forbiddenWorkflows: ["truthmark-sync"], + source: "manifest-negative", + }, + { + id: "structure-broad-routing-repair", + userPrompt: + "The repository route is a broad src/** catch-all and needs to be split into bounded Truthmark areas.", + changedFiles: ["docs/truthmark/areas.md"], + expectedWorkflow: "truthmark-structure", + expectedReason: "split broad repository routing into bounded areas", + expectedManifestSignals: [ + "routing or truth ownership is missing, stale, broad, overloaded, catch-all", + "split broad repository routing into bounded areas", + ], + forbiddenWorkflows: ["truthmark-sync", "truthmark-document"], + source: "manifest-positive", + }, + { + id: "structure-new-area-setup", + userPrompt: + "Onboard the new billing controller area into Truthmark with routing and starter truth docs.", + changedFiles: ["src/billing/controllers/invoices.ts"], + expectedWorkflow: "truthmark-structure", + expectedReason: "onboard a new code area into Truthmark routing", + expectedManifestSignals: [ + "onboard a new code area into Truthmark routing", + "new package, controller, domain, or product area lacks bounded truth ownership", + ], + forbiddenWorkflows: ["truthmark-sync", "truthmark-document"], + source: "manifest-positive", + }, + { + id: "document-existing-implemented-behavior", + userPrompt: + "Document the existing implemented session-timeout behavior from the code without changing functional code.", + changedFiles: ["src/auth/session.ts"], + expectedWorkflow: "truthmark-document", + expectedReason: "document existing implemented behavior", + expectedManifestSignals: [ + "document existing implemented behavior", + "Not for functional-code changes", + ], + forbiddenWorkflows: ["truthmark-realize", "truthmark-structure"], + source: "manifest-positive", + }, + { + id: "realize-explicit-doc-first", + userPrompt: + "Use $truthmark-realize to realize docs/truth/authentication/session-timeout.md into code.", + changedFiles: ["docs/truth/authentication/session-timeout.md"], + expectedWorkflow: "truthmark-realize", + expectedReason: "explicitly realize truth docs into functional code", + expectedManifestSignals: [ + "explicitly realize truth docs into functional code", + "Not for syncing docs after code changes", + ], + forbiddenWorkflows: ["truthmark-sync", "truthmark-document"], + source: "manifest-positive", + }, + { + id: "check-truth-health-audit", + userPrompt: + "Audit repository truth health and routing ownership, but do not rewrite docs.", + expectedWorkflow: "truthmark-check", + expectedReason: "audit repository truth health", + expectedManifestSignals: [ + "audit repository truth health", + "Not for normal lint/test/typecheck/code-review verification", + ], + forbiddenWorkflows: ["truthmark-sync", "truthmark-document"], + source: "manifest-positive", + }, + { + id: "preview-routing-before-edits", + userPrompt: + "Before we edit anything, preview which Truthmark workflow and route owner would apply to src/auth/session.ts.", + changedFiles: ["src/auth/session.ts"], + expectedWorkflow: "truthmark-preview", + expectedReason: "preview likely workflow routing before edits", + expectedManifestSignals: [ + "preview likely workflow routing", + "Not for validation", + ], + forbiddenWorkflows: ["truthmark-sync", "truthmark-check"], + source: "manifest-positive", + }, + { + id: "adjacent-sync-not-realize", + userPrompt: + "I changed functional code and need the docs synced afterward, not a doc-first realization.", + changedFiles: ["src/auth/session.ts"], + expectedWorkflow: "truthmark-sync", + expectedReason: "doc-first implementation belongs to Truth Realize", + expectedManifestSignals: [ + "functional code changed since last successful Truth Sync", + "doc-first implementation belongs to Truth Realize", + ], + forbiddenWorkflows: ["truthmark-realize"], + source: "forbidden-adjacent", + }, + { + id: "mixed-owner-sync-block", + userPrompt: + "Sync this code diff, but the mapped truth doc is mixed-owner and the route cannot identify a bounded truth owner.", + changedFiles: ["src/auth/session.ts"], + expectedWorkflow: "block", + expectedReason: + "routing repair is required before Truth Sync can select a bounded owner", + expectedManifestSignals: [ + "manual topology design belongs to Truth Structure", + ], + forbiddenWorkflows: ["truthmark-sync"], + source: "synthetic", + }, +]; diff --git a/tests/evals/workflow-routing.test.ts b/tests/evals/workflow-routing.test.ts new file mode 100644 index 0000000..e7e9945 --- /dev/null +++ b/tests/evals/workflow-routing.test.ts @@ -0,0 +1,236 @@ +import { describe, expect, it } from "vitest"; +import { createDefaultConfig } from "../../src/config/defaults.js"; +import { renderGeneratedSurfaces } from "../../src/templates/generated-surfaces.js"; +import { + TRUTHMARK_WORKFLOW_IDS, + TRUTHMARK_WORKFLOW_MANIFEST, + getTruthmarkWorkflow, + type TruthmarkWorkflowId, +} from "../../src/agents/workflow-manifest.js"; +import { WORKFLOW_ROUTING_EVAL_CASES } from "./workflow-routing-cases.js"; + +const WORKFLOW_COMMAND_PATHS: Record = { + "truthmark-sync": ".gemini/commands/truthmark/sync.toml", + "truthmark-structure": ".gemini/commands/truthmark/structure.toml", + "truthmark-document": ".gemini/commands/truthmark/document.toml", + "truthmark-preview": ".gemini/commands/truthmark/preview.toml", + "truthmark-realize": ".gemini/commands/truthmark/realize.toml", + "truthmark-check": ".gemini/commands/truthmark/check.toml", +}; + +const WORKFLOW_SURFACE_PATHS = (id: TruthmarkWorkflowId): readonly string[] => [ + `.codex/skills/${id}/SKILL.md`, + `.opencode/skills/${id}/SKILL.md`, + `.claude/skills/${id}/SKILL.md`, + `.github/prompts/${id}.prompt.md`, + WORKFLOW_COMMAND_PATHS[id], +]; + +const CODEX_METADATA_PATHS = (id: TruthmarkWorkflowId): string => + `.codex/skills/${id}/agents/openai.yaml`; + +const WORKFLOW_SKILL_PACKAGE_PATHS = ( + hostSkillRoot: string, + id: TruthmarkWorkflowId, +): readonly string[] => { + const workflow = TRUTHMARK_WORKFLOW_MANIFEST[id]; + const hasSubagentSupport = + ("subagents" in workflow ? workflow.subagents.length : 0) > 0 || + ("writeSubagents" in workflow ? workflow.writeSubagents.length : 0) > 0; + + return [ + `${hostSkillRoot}/${id}/SKILL.md`, + `${hostSkillRoot}/${id}/support/procedure.md`, + `${hostSkillRoot}/${id}/support/report-template.md`, + ...(hasSubagentSupport + ? [`${hostSkillRoot}/${id}/support/subagents-and-leases.md`] + : []), + ]; +}; + +const WORKFLOW_CONTRACT_PATH_GROUPS = ( + id: TruthmarkWorkflowId, +): readonly (readonly string[])[] => [ + WORKFLOW_SKILL_PACKAGE_PATHS(".codex/skills", id), + WORKFLOW_SKILL_PACKAGE_PATHS(".opencode/skills", id), + WORKFLOW_SKILL_PACKAGE_PATHS(".claude/skills", id), + [`.github/prompts/${id}.prompt.md`], + [WORKFLOW_COMMAND_PATHS[id]], +]; + +const SURFACE_CONTRACT_TERMS: Record = { + "truthmark-sync": [ + "Skip when changes are documentation-only", + "block and recommend Truth Structure", + "verify only truth docs and leased truth routing files changed", + "Report completion in this shape:", + "Changed code reviewed:", + "Evidence checked:", + ], + "truthmark-structure": [ + "New area setup", + "report the initial truth boundary", + "create or repair", + "starter truth docs", + "Do not require the truthmark CLI", + "Report completion in this shape:", + "Topology reviewed:", + "Initial truth boundary:", + "Evidence checked:", + ], + "truthmark-document": [ + "document existing implemented behavior", + "may write canonical truth docs", + "must not write functional code", + "Report completion in this shape:", + "Implementation reviewed:", + "Evidence checked:", + ], + "truthmark-preview": [ + "preview Truthmark routing", + "Truth Preview is read-only", + "Report completion in this shape:", + "Truth Preview: completed", + "Handoff:", + ], + "truthmark-realize": [ + "Use this skill only when the user explicitly asks", + "may write functional code only", + "must not edit truth docs or truth routing", + "Report completion in this shape:", + "Truth docs used:", + "Verification:", + ], + "truthmark-check": [ + "audit repository truth health", + "report issues and suggested fixes without silently rewriting unrelated files", + "Report completion in this shape:", + "Files reviewed:", + "Validation:", + ], +}; + +const manifestRoutingText = (id: TruthmarkWorkflowId): string => { + const workflow = getTruthmarkWorkflow(id); + + return [ + workflow.description, + workflow.defaultPrompt, + ...workflow.positiveTriggers, + ...workflow.negativeTriggers, + ...workflow.forbiddenAdjacency, + ].join("\n"); +}; + +const candidateManifestText = ( + expectedWorkflow: TruthmarkWorkflowId | "none" | "block", + forbiddenWorkflows: readonly TruthmarkWorkflowId[] = [], +): string => { + const workflowIds = + expectedWorkflow === "none" || expectedWorkflow === "block" + ? forbiddenWorkflows + : [expectedWorkflow, ...forbiddenWorkflows]; + + return workflowIds.map((id) => manifestRoutingText(id)).join("\n"); +}; + +const buildGeneratedSurfaceMap = (): Map => { + const config = createDefaultConfig(); + return new Map( + renderGeneratedSurfaces(config).map((surface) => [ + surface.path, + surface.content, + ]), + ); +}; + +describe("workflow routing eval corpus", () => { + it("covers positive, negative, adjacent, none, and blocked routing outcomes", () => { + expect(WORKFLOW_ROUTING_EVAL_CASES).toEqual( + expect.arrayContaining([ + expect.objectContaining({ source: "manifest-positive" }), + expect.objectContaining({ source: "manifest-negative" }), + expect.objectContaining({ source: "forbidden-adjacent" }), + expect.objectContaining({ expectedWorkflow: "none" }), + expect.objectContaining({ expectedWorkflow: "block" }), + ]), + ); + + for (const id of TRUTHMARK_WORKFLOW_IDS) { + expect(WORKFLOW_ROUTING_EVAL_CASES).toEqual( + expect.arrayContaining([ + expect.objectContaining({ expectedWorkflow: id }), + ]), + ); + } + }); + + it.each(WORKFLOW_ROUTING_EVAL_CASES)( + "anchors $id to manifest routing signals", + (testCase) => { + const routingText = candidateManifestText( + testCase.expectedWorkflow, + testCase.forbiddenWorkflows, + ); + + for (const signal of testCase.expectedManifestSignals) { + expect(routingText).toContain(signal); + } + }, + ); +}); + +describe("generated workflow surface conformance", () => { + const surfaces = buildGeneratedSurfaceMap(); + + it("renders every workflow routing surface from the manifest description", () => { + for (const id of TRUTHMARK_WORKFLOW_IDS) { + const workflow = TRUTHMARK_WORKFLOW_MANIFEST[id]; + + for (const path of WORKFLOW_SURFACE_PATHS(id)) { + const content = surfaces.get(path); + + expect(content, `${path} is generated`).toBeDefined(); + expect(content).toContain(workflow.description); + expect(content).toContain(workflow.description.split("Not for ")[1]); + } + } + }); + + it("keeps Codex metadata aligned with manifest selection policy", () => { + for (const id of TRUTHMARK_WORKFLOW_IDS) { + const workflow = TRUTHMARK_WORKFLOW_MANIFEST[id]; + const path = CODEX_METADATA_PATHS(id); + const content = surfaces.get(path); + + expect(content, `${path} is generated`).toBeDefined(); + expect(content).toContain(`display_name: "${workflow.displayName}"`); + expect(content).toContain( + `short_description: "${workflow.shortDescription}"`, + ); + expect(content).toContain(`default_prompt: "${workflow.defaultPrompt}"`); + expect(content).toContain( + `allow_implicit_invocation: ${workflow.allowImplicitInvocation}`, + ); + } + }); + + it("keeps generated skill, prompt, and command bodies on the same write and report contract", () => { + for (const id of TRUTHMARK_WORKFLOW_IDS) { + for (const paths of WORKFLOW_CONTRACT_PATH_GROUPS(id)) { + const content = paths + .map((path) => { + const surface = surfaces.get(path); + + expect(surface, `${path} is generated`).toBeDefined(); + return surface; + }) + .join("\n"); + + for (const term of SURFACE_CONTRACT_TERMS[id]) { + expect(content).toContain(term); + } + } + } + }); +}); diff --git a/tests/git/changes.test.ts b/tests/git/changes.test.ts index ccda973..21195ad 100644 --- a/tests/git/changes.test.ts +++ b/tests/git/changes.test.ts @@ -109,6 +109,9 @@ describe("classifyPath", () => { expect(classifyPath(".github/prompts/truthmark-sync.prompt.md", [])).toBe( "derived", ); + expect(classifyPath(".github/agents/truth-route-auditor.agent.md", [])).toBe( + "derived", + ); expect(classifyPath("CLAUDE.md", [])).toBe("derived"); expect(classifyPath("GEMINI.md", [])).toBe("derived"); expect(classifyPath(".gemini/commands/truthmark/sync.toml", [])).toBe("derived"); diff --git a/tests/init/init-instructions.test.ts b/tests/init/init-instructions.test.ts index e93c781..a4052fb 100644 --- a/tests/init/init-instructions.test.ts +++ b/tests/init/init-instructions.test.ts @@ -28,7 +28,7 @@ describe("runInit instruction integration", () => { expect(agents).toContain("code changed -> tests -> Sync -> report"); expect(agents).toContain("Delegation is host-owned"); expect(agents).toContain( - "Explicit workflows: Truth Structure, Truth Document, Truth Realize, Truth Check", + "Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check", ); expect(agents).toContain("load the installed skill for details"); expect(agents).not.toContain("/skill truthmark-structure"); diff --git a/tests/init/init.test.ts b/tests/init/init.test.ts index 38f8e12..e02a5c9 100644 --- a/tests/init/init.test.ts +++ b/tests/init/init.test.ts @@ -11,6 +11,9 @@ import { runInit } from "../../src/init/init.js"; import { TRUTHMARK_VERSION } from "../../src/version.js"; import { createTempRepo } from "../helpers/temp-repo.js"; +const READ_ONLY_CONTEXT_BOUNDARY = + "Do not preload AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, or repo-wide policy docs unless the parent explicitly assigns them as evidence."; + describe("runInit", () => { it("does not initialize agent surfaces before config exists", async () => { const repo = await createTempRepo(); @@ -113,12 +116,12 @@ describe("runInit", () => { expect(await repo.readFile("docs/templates/behavior-doc.md")).toContain( "Split into another leaf doc when content introduces", ); - expect( - await repo.readFile("docs/truth/repository/README.md"), - ).toContain("Repository Truth Docs"); - expect( - await repo.readFile("docs/truth/repository/README.md"), - ).toContain("index"); + expect(await repo.readFile("docs/truth/repository/README.md")).toContain( + "Repository Truth Docs", + ); + expect(await repo.readFile("docs/truth/repository/README.md")).toContain( + "index", + ); expect( await repo.readFile("docs/truth/repository/overview.md"), ).toContain("# Repository Overview"); @@ -158,6 +161,9 @@ describe("runInit", () => { const structureSkill = await repo.readFile( ".codex/skills/truthmark-structure/SKILL.md", ); + const structureReportTemplate = await repo.readFile( + ".codex/skills/truthmark-structure/support/report-template.md", + ); const structureSkillMetadata = await repo.readFile( ".codex/skills/truthmark-structure/agents/openai.yaml", ); @@ -167,6 +173,12 @@ describe("runInit", () => { const documentSkill = await repo.readFile( ".codex/skills/truthmark-document/SKILL.md", ); + const documentSubagents = await repo.readFile( + ".codex/skills/truthmark-document/support/subagents-and-leases.md", + ); + const documentReportTemplate = await repo.readFile( + ".codex/skills/truthmark-document/support/report-template.md", + ); const documentSkillMetadata = await repo.readFile( ".codex/skills/truthmark-document/agents/openai.yaml", ); @@ -176,12 +188,27 @@ describe("runInit", () => { const syncSkill = await repo.readFile( ".codex/skills/truthmark-sync/SKILL.md", ); + const syncProcedure = await repo.readFile( + ".codex/skills/truthmark-sync/support/procedure.md", + ); + const syncSubagents = await repo.readFile( + ".codex/skills/truthmark-sync/support/subagents-and-leases.md", + ); + const syncReportTemplate = await repo.readFile( + ".codex/skills/truthmark-sync/support/report-template.md", + ); const syncSkillMetadata = await repo.readFile( ".codex/skills/truthmark-sync/agents/openai.yaml", ); const syncOpenCodeSkill = await repo.readFile( ".opencode/skills/truthmark-sync/SKILL.md", ); + const syncOpenCodeSubagents = await repo.readFile( + ".opencode/skills/truthmark-sync/support/subagents-and-leases.md", + ); + const syncCopilotPrompt = await repo.readFile( + ".github/prompts/truthmark-sync.prompt.md", + ); const realizeSkill = await repo.readFile( ".codex/skills/truthmark-realize/SKILL.md", ); @@ -191,6 +218,30 @@ describe("runInit", () => { const realizeOpenCodeSkill = await repo.readFile( ".opencode/skills/truthmark-realize/SKILL.md", ); + const previewSkill = await repo.readFile( + ".codex/skills/truthmark-preview/SKILL.md", + ); + const previewSubagents = await repo.readFile( + ".codex/skills/truthmark-preview/support/subagents-and-leases.md", + ); + const previewReportTemplate = await repo.readFile( + ".codex/skills/truthmark-preview/support/report-template.md", + ); + const previewSkillMetadata = await repo.readFile( + ".codex/skills/truthmark-preview/agents/openai.yaml", + ); + const previewOpenCodeSkill = await repo.readFile( + ".opencode/skills/truthmark-preview/SKILL.md", + ); + const previewClaudeSkill = await repo.readFile( + ".claude/skills/truthmark-preview/SKILL.md", + ); + const previewCopilotPrompt = await repo.readFile( + ".github/prompts/truthmark-preview.prompt.md", + ); + const previewGeminiCommand = await repo.readFile( + ".gemini/commands/truthmark/preview.toml", + ); const checkSkill = await repo.readFile( ".codex/skills/truthmark-check/SKILL.md", ); @@ -200,10 +251,61 @@ describe("runInit", () => { const checkOpenCodeSkill = await repo.readFile( ".opencode/skills/truthmark-check/SKILL.md", ); + const routeAuditorAgent = await repo.readFile( + ".codex/agents/truth-route-auditor.toml", + ); + const claimVerifierAgent = await repo.readFile( + ".codex/agents/truth-claim-verifier.toml", + ); + const docReviewerAgent = await repo.readFile( + ".codex/agents/truth-doc-reviewer.toml", + ); + const docWriterAgent = await repo.readFile( + ".codex/agents/truth-doc-writer.toml", + ); + const openCodeRouteAuditorAgent = await repo.readFile( + ".opencode/agents/truth-route-auditor.md", + ); + const openCodeClaimVerifierAgent = await repo.readFile( + ".opencode/agents/truth-claim-verifier.md", + ); + const openCodeDocReviewerAgent = await repo.readFile( + ".opencode/agents/truth-doc-reviewer.md", + ); + const openCodeDocWriterAgent = await repo.readFile( + ".opencode/agents/truth-doc-writer.md", + ); + const copilotRouteAuditorAgent = await repo.readFile( + ".github/agents/truth-route-auditor.agent.md", + ); + const copilotClaimVerifierAgent = await repo.readFile( + ".github/agents/truth-claim-verifier.agent.md", + ); + const copilotDocReviewerAgent = await repo.readFile( + ".github/agents/truth-doc-reviewer.agent.md", + ); + const copilotDocWriterAgent = await repo.readFile( + ".github/agents/truth-doc-writer.agent.md", + ); + const claudeRouteAuditorAgent = await repo.readFile( + ".claude/agents/truth-route-auditor.md", + ); + const claudeClaimVerifierAgent = await repo.readFile( + ".claude/agents/truth-claim-verifier.md", + ); + const claudeDocReviewerAgent = await repo.readFile( + ".claude/agents/truth-doc-reviewer.md", + ); + const claudeDocWriterAgent = await repo.readFile( + ".claude/agents/truth-doc-writer.md", + ); const claudeInstructions = await repo.readFile("CLAUDE.md"); const syncClaudeSkill = await repo.readFile( ".claude/skills/truthmark-sync/SKILL.md", ); + const syncClaudeSubagents = await repo.readFile( + ".claude/skills/truthmark-sync/support/subagents-and-leases.md", + ); expect(agents.match(//g)).toHaveLength(1); expect(claudeInstructions).toContain("Truthmark Workflow"); @@ -217,14 +319,12 @@ describe("runInit", () => { expect(agents).not.toContain("/skill truthmark-structure"); expect(agents).not.toContain("/skill truthmark-check"); expect(agents).toContain( - "Explicit workflows: Truth Structure, Truth Document, Truth Realize, Truth Check", + "Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check", ); expect(agents).toContain("load the installed skill for details"); expect(agents).toContain("Hierarchy: config .truthmark/config.yml"); expect(agents).toContain("routes docs/truthmark/areas.md"); - expect(agents).toContain( - "docs/truthmark/areas/**/*.md", - ); + expect(agents).toContain("docs/truthmark/areas/**/*.md"); expect(agents).toContain("Truth docs: docs/truth/**/*.md"); expect(agents).toContain( "Decisions live in the canonical doc they govern", @@ -245,19 +345,37 @@ describe("runInit", () => { expect(agents.match(/Hierarchy: config/g)).toHaveLength(1); expect(agents.match(/Decisions live/g)).toHaveLength(1); expect(structureSkill).toContain("name: truthmark-structure"); - expect(structureSkill).toContain("Truth Structure: completed"); + expect(structureSkill).toContain("support/procedure.md"); + expect(structureSkill).toContain("support/report-template.md"); + expect(structureSkill).not.toContain("Truth Structure: completed"); + expect(structureSkill.split("\n").length).toBeLessThanOrEqual(55); + expect(structureReportTemplate).toContain("Truth Structure: completed"); expect(structureSkillMetadata).toContain( 'display_name: "Truthmark Structure"', ); expect(structureOpenCodeSkill).toContain("name: truthmark-structure"); expect(documentSkill).toContain("name: truthmark-document"); - expect(documentSkill).toContain("Truth Document: completed"); + expect(documentSkill).toContain("support/procedure.md"); + expect(documentSkill).toContain("support/report-template.md"); + expect(documentSkill).toContain("support/subagents-and-leases.md"); + expect(documentSkill).not.toContain("Truth Document: completed"); expect(documentSkill).toContain("must not write functional code"); + expect(documentSkill).not.toContain("truth_doc_writer"); + expect(documentSkill.split("\n").length).toBeLessThanOrEqual(55); + expect(documentSubagents).toContain("truth_doc_writer"); + expect(documentSubagents).toContain("write lease"); + expect(documentReportTemplate).toContain("Truth Document: completed"); expect(documentSkillMetadata).toContain( 'display_name: "Truthmark Document"', ); - expect(documentSkillMetadata).toContain("allow_implicit_invocation: false"); + expect(documentSkillMetadata).toContain( + "allow_implicit_invocation: false", + ); expect(documentOpenCodeSkill).toContain("name: truthmark-document"); + expect(documentOpenCodeSkill).toContain( + "support/subagents-and-leases.md", + ); + expect(documentOpenCodeSkill).not.toContain("OpenCode subagent mode:"); expect(syncSkill).toContain("name: truthmark-sync"); expect(syncSkill).toContain("user-invocable: true"); expect(syncSkill).toContain(`truthmark-version: ${TRUTHMARK_VERSION}`); @@ -267,7 +385,18 @@ describe("runInit", () => { expect(syncSkill).toContain( "direct checkout inspection is the canonical path", ); - expect(syncSkill).toContain("host supports subagent dispatch"); + expect(syncSkill).toContain("support/procedure.md"); + expect(syncSkill).toContain("support/report-template.md"); + expect(syncSkill).toContain("support/subagents-and-leases.md"); + expect(syncSkill).not.toContain("host supports subagent dispatch"); + expect(syncSkill).not.toContain("truth_doc_writer"); + expect(syncSkill).not.toContain("Truth Sync: completed"); + expect(syncSkill.split("\n").length).toBeLessThanOrEqual(55); + expect(syncProcedure).toContain("host supports subagent dispatch"); + expect(syncSubagents).toContain("truth_doc_writer"); + expect(syncSubagents).toContain("write lease"); + expect(syncReportTemplate).toContain("Truth Sync: completed"); + expect(syncReportTemplate).toContain("Truth Sync: blocked"); expect(syncSkill).toContain( "Read .truthmark/config.yml, the configured root route index", ); @@ -285,14 +414,32 @@ describe("runInit", () => { expect(syncOpenCodeSkill).toContain( "Use this skill automatically before finishing", ); + expect(syncOpenCodeSkill).toContain("support/subagents-and-leases.md"); + expect(syncOpenCodeSkill).not.toContain("OpenCode subagent mode:"); + expect(syncOpenCodeSubagents).toContain("OpenCode subagent mode:"); + expect(syncOpenCodeSubagents).toContain("@truth-route-auditor"); + expect(syncOpenCodeSubagents).toContain("@truth-claim-verifier"); + expect(syncOpenCodeSubagents).toContain("@truth-doc-writer"); + expect(syncCopilotPrompt).toContain("Copilot custom-agent mode:"); + expect(syncCopilotPrompt).toContain("@truth-route-auditor"); + expect(syncCopilotPrompt).toContain("@truth-claim-verifier"); + expect(syncCopilotPrompt).toContain("@truth-doc-writer"); expect(syncClaudeSkill).toContain("name: truthmark-sync"); expect(syncClaudeSkill).toContain( "Use this skill automatically before finishing", ); + expect(syncClaudeSkill).toContain("support/subagents-and-leases.md"); + expect(syncClaudeSkill).not.toContain("Claude Code subagent mode:"); + expect(syncClaudeSubagents).toContain("Claude Code subagent mode:"); + expect(syncClaudeSubagents).toContain("truth-route-auditor subagent"); + expect(syncClaudeSubagents).toContain("truth-claim-verifier subagent"); + expect(syncClaudeSubagents).toContain("truth-doc-writer subagent"); expect(realizeSkill).toContain("name: truthmark-realize"); expect(realizeSkill).toContain("user-invocable: true"); expect(realizeSkill).toContain("may write functional code only"); - expect(realizeSkill).toContain("Truth Realize: completed"); + expect(realizeSkill).toContain("support/procedure.md"); + expect(realizeSkill).toContain("support/report-template.md"); + expect(realizeSkill).not.toContain("Truth Realize: completed"); expect(realizeSkillMetadata).toContain( 'display_name: "Truthmark Realize"', ); @@ -303,10 +450,101 @@ describe("runInit", () => { expect(realizeOpenCodeSkill).toContain( "Use this skill only when the user explicitly asks to realize truth docs into code.", ); + expect(previewSkill).toContain("name: truthmark-preview"); + expect(previewSkill).toContain("Truth Preview is read-only"); + expect(previewSkill).toContain("intended, not authorized"); + expect(previewSkill).toContain("must not edit files"); + expect(previewSkill).toContain("must not issue write leases"); + expect(previewSkill).toContain("support/procedure.md"); + expect(previewSkill).toContain("support/report-template.md"); + expect(previewSkill).toContain("support/subagents-and-leases.md"); + expect(previewSkill).not.toContain("Truth Preview: completed"); + expect(previewSkill).not.toContain("truth_route_auditor"); + expect(previewReportTemplate).toContain("Truth Preview: completed"); + expect(previewReportTemplate).toContain("Handoff:"); + expect(previewSubagents).toContain("truth_route_auditor"); + expect(previewSkill).not.toContain("truth_doc_writer"); + expect(previewSkillMetadata).toContain( + 'display_name: "Truthmark Preview"', + ); + expect(previewSkillMetadata).toContain( + "allow_implicit_invocation: false", + ); + expect(previewOpenCodeSkill).toContain("name: truthmark-preview"); + expect(previewClaudeSkill).toContain("name: truthmark-preview"); + expect(previewCopilotPrompt).toContain("Truth Preview: completed"); + expect(previewGeminiCommand).toContain("/truthmark:preview"); expect(checkSkill).toContain("name: truthmark-check"); - expect(checkSkill).toContain("Truth Check: completed"); + expect(checkSkill).toContain("support/procedure.md"); + expect(checkSkill).toContain("support/report-template.md"); + expect(checkSkill).toContain("support/subagents-and-leases.md"); + expect(checkSkill).not.toContain("Truth Check: completed"); + expect(checkSkill).not.toContain("Codex subagent mode:"); expect(checkSkillMetadata).toContain('display_name: "Truthmark Check"'); expect(checkOpenCodeSkill).toContain("name: truthmark-check"); + expect(checkOpenCodeSkill).toContain("support/subagents-and-leases.md"); + expect(checkOpenCodeSkill).not.toContain("OpenCode subagent mode:"); + expect(routeAuditorAgent).toContain('name = "truth_route_auditor"'); + expect(routeAuditorAgent).toContain('sandbox_mode = "read-only"'); + expect(routeAuditorAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(claimVerifierAgent).toContain('name = "truth_claim_verifier"'); + expect(claimVerifierAgent).toContain('sandbox_mode = "read-only"'); + expect(claimVerifierAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(docReviewerAgent).toContain('name = "truth_doc_reviewer"'); + expect(docReviewerAgent).toContain('sandbox_mode = "read-only"'); + expect(docReviewerAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(docWriterAgent).toContain('name = "truth_doc_writer"'); + expect(docWriterAgent).toContain('sandbox_mode = "workspace-write"'); + expect(docWriterAgent).toContain("Require an explicit write lease"); + expect(docWriterAgent).not.toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(openCodeRouteAuditorAgent).toContain("mode: subagent"); + expect(openCodeRouteAuditorAgent).toContain("edit: deny"); + expect(openCodeRouteAuditorAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(openCodeClaimVerifierAgent).toContain("mode: subagent"); + expect(openCodeClaimVerifierAgent).toContain("edit: deny"); + expect(openCodeClaimVerifierAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(openCodeDocReviewerAgent).toContain("mode: subagent"); + expect(openCodeDocReviewerAgent).toContain("edit: deny"); + expect(openCodeDocReviewerAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(openCodeDocWriterAgent).toContain("mode: subagent"); + expect(openCodeDocWriterAgent).toContain('"docs/truth/**": allow'); + expect(openCodeDocWriterAgent).toContain("@truth-doc-writer"); + expect(openCodeDocWriterAgent).not.toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(copilotRouteAuditorAgent).toContain("name: truth-route-auditor"); + expect(copilotRouteAuditorAgent).toContain("tools: [read, search]"); + expect(copilotRouteAuditorAgent).toContain("Stay read-only."); + expect(copilotRouteAuditorAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(copilotClaimVerifierAgent).toContain("name: truth-claim-verifier"); + expect(copilotClaimVerifierAgent).toContain("unsupportedClaims"); + expect(copilotClaimVerifierAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(copilotDocReviewerAgent).toContain("name: truth-doc-reviewer"); + expect(copilotDocReviewerAgent).toContain("recommendedWorkflow"); + expect(copilotDocReviewerAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(copilotDocWriterAgent).toContain("name: truth-doc-writer"); + expect(copilotDocWriterAgent).toContain("tools: [read, search, edit]"); + expect(copilotDocWriterAgent).toContain("offLeaseChanges"); + expect(copilotDocWriterAgent).not.toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(claudeRouteAuditorAgent).toContain("name: truth-route-auditor"); + expect(claudeRouteAuditorAgent).toContain("tools: Read, Grep, Glob, LS"); + expect(claudeRouteAuditorAgent).toContain( + "Manual invocation: use the truth-route-auditor subagent", + ); + expect(claudeRouteAuditorAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(claudeRouteAuditorAgent).toContain("Do not edit files"); + expect(claudeClaimVerifierAgent).toContain("name: truth-claim-verifier"); + expect(claudeClaimVerifierAgent).toContain("tools: Read, Grep, Glob, LS"); + expect(claudeClaimVerifierAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(claudeClaimVerifierAgent).toContain("Do not edit files"); + expect(claudeDocReviewerAgent).toContain("name: truth-doc-reviewer"); + expect(claudeDocReviewerAgent).toContain("tools: Read, Grep, Glob, LS"); + expect(claudeDocReviewerAgent).toContain(READ_ONLY_CONTEXT_BOUNDARY); + expect(claudeDocReviewerAgent).toContain("Rationale"); + expect(claudeDocWriterAgent).toContain("name: truth-doc-writer"); + expect(claudeDocWriterAgent).toContain( + "tools: Read, Grep, Glob, LS, Edit, MultiEdit", + ); + expect(claudeDocWriterAgent).toContain("explicit parent write lease"); + expect(claudeDocWriterAgent).not.toContain(READ_ONLY_CONTEXT_BOUNDARY); await expect( fs.stat(`${repo.rootDir}/skills/truthmark-structure/SKILL.md`), ).rejects.toThrow(); @@ -344,6 +582,13 @@ describe("runInit", () => { diagnostic.file === ".claude/skills/truthmark-sync/SKILL.md", ), ).toBe(true); + expect( + result.diagnostics.some( + (diagnostic) => + diagnostic.category === "truth-sync" && + diagnostic.file === ".claude/agents/truth-route-auditor.md", + ), + ).toBe(true); expect( result.diagnostics.some( (diagnostic) => @@ -365,6 +610,13 @@ describe("runInit", () => { diagnostic.file === ".codex/skills/truthmark-check/SKILL.md", ), ).toBe(true); + expect( + result.diagnostics.some( + (diagnostic) => + diagnostic.category === "truth-sync" && + diagnostic.file === ".opencode/agents/truth-route-auditor.md", + ), + ).toBe(true); expect( result.diagnostics.some((diagnostic) => diagnostic.message.includes("Created"), @@ -389,7 +641,9 @@ describe("runInit", () => { }; expect(config.docs.roots.truth).toBe("docs/truth"); - expect(await repo.readFile("docs/truth/README.md")).toContain("Truth Docs"); + expect(await repo.readFile("docs/truth/README.md")).toContain( + "Truth Docs", + ); expect(await repo.readFile("docs/truth/repository/README.md")).toContain( "Repository Truth Docs", ); @@ -405,28 +659,32 @@ describe("runInit", () => { expect(await repo.readFile("docs/templates/contract-doc.md")).toContain( "{{contract_surface}}", ); - expect(await repo.readFile("docs/templates/architecture-doc.md")).toContain( - "## Boundaries", - ); + expect( + await repo.readFile("docs/templates/architecture-doc.md"), + ).toContain("## Boundaries"); expect(await repo.readFile("docs/templates/workflow-doc.md")).toContain( "## Execution Model", ); expect(await repo.readFile("docs/templates/operations-doc.md")).toContain( "## Runtime Topology", ); - expect(await repo.readFile("docs/templates/test-behavior-doc.md")).toContain( - "## Assertions And Invariants", - ); - expect(await repo.readFile("docs/truth/repository/overview.md")).toContain( - "doc_type: behavior", - ); - expect(await repo.readFile("docs/truth/repository/overview.md")).toContain( - "truth_kind: behavior", - ); - expect(await repo.readFile("docs/truth/repository/overview.md")).toContain( + expect( + await repo.readFile("docs/templates/test-behavior-doc.md"), + ).toContain("## Assertions And Invariants"); + expect( + await repo.readFile("docs/truth/repository/overview.md"), + ).toContain("doc_type: behavior"); + expect( + await repo.readFile("docs/truth/repository/overview.md"), + ).toContain("truth_kind: behavior"); + expect( + await repo.readFile("docs/truth/repository/overview.md"), + ).toContain( "Truth README files are indexes; behavior truth belongs in bounded leaf docs.", ); - expect(await repo.readFile("docs/truth/repository/overview.md")).toContain( + expect( + await repo.readFile("docs/truth/repository/overview.md"), + ).toContain( "This doc was created from the editable behavior-doc template at docs/templates/behavior-doc.md.", ); } finally { @@ -578,6 +836,20 @@ ignore: [] expect( await repo.readFile(".claude/skills/truthmark-document/SKILL.md"), ).toContain("Claude Code /truthmark-document"); + expect( + await repo.readFile( + ".claude/skills/truthmark-document/support/subagents-and-leases.md", + ), + ).toContain("Claude Code subagent mode:"); + expect( + await repo.readFile(".claude/agents/truth-route-auditor.md"), + ).toContain("name: truth-route-auditor"); + expect( + await repo.readFile(".claude/agents/truth-claim-verifier.md"), + ).toContain("tools: Read, Grep, Glob, LS"); + expect( + await repo.readFile(".claude/agents/truth-doc-reviewer.md"), + ).toContain("recommendedWorkflow"); expect( await repo.readFile(".claude/skills/truthmark-check/SKILL.md"), ).toContain("name: truthmark-check"); @@ -620,9 +892,18 @@ ignore: [] expect( await repo.readFile(".github/prompts/truthmark-sync.prompt.md"), ).toContain("GitHub Copilot /truthmark-sync"); + expect( + await repo.readFile(".github/agents/truth-route-auditor.agent.md"), + ).toContain("tools: [read, search]"); + expect( + await repo.readFile(".github/agents/truth-claim-verifier.agent.md"), + ).toContain("unsupportedClaims"); expect( await repo.readFile(".github/prompts/truthmark-structure.prompt.md"), ).toContain("name: truthmark-structure"); + expect( + await repo.readFile(".github/prompts/truthmark-structure.prompt.md"), + ).toContain("@truth-route-auditor"); expect( await repo.readFile(".github/prompts/truthmark-document.prompt.md"), ).toContain("GitHub Copilot /truthmark-document"); @@ -632,6 +913,9 @@ ignore: [] expect( await repo.readFile(".github/prompts/truthmark-realize.prompt.md"), ).toContain("GitHub Copilot /truthmark-realize"); + expect( + await repo.readFile(".github/agents/truth-doc-reviewer.agent.md"), + ).toContain("recommendedWorkflow"); await expect( fs.stat(`${repo.rootDir}/.codex/skills/truthmark-sync/SKILL.md`), ).rejects.toThrow(); @@ -847,7 +1131,9 @@ authority: ]), ); expect( - await repo.readFile(".codex/skills/truthmark-realize/SKILL.md"), + await repo.readFile( + ".codex/skills/truthmark-realize/support/report-template.md", + ), ).toContain("docs/product/authentication/session-timeout.md"); expect(await repo.readFile("docs/truth/README.md")).toContain( "Truth Docs", @@ -882,7 +1168,9 @@ authority: await runInit(repo.rootDir); - const childRoute = await repo.readFile("docs/truthmark/areas/repository.md"); + const childRoute = await repo.readFile( + "docs/truthmark/areas/repository.md", + ); expect(childRoute).toContain("```yaml"); expect(childRoute).toContain("path: docs/product/repository/overview.md"); expect(childRoute).toContain("kind: behavior"); @@ -902,6 +1190,52 @@ authority: } }); + it("renders OpenCode doc-writer edit permissions from configured truth and routing paths", async () => { + const repo = await createTempRepo(); + + try { + await repo.writeFile( + ".truthmark/config.yml", + `version: 1 +platforms: + - opencode +docs: + layout: hierarchical + roots: + truth: product/truth + routing: + root_index: product/routes/index.md + area_files_root: product/routes/areas + default_area: repository + max_delegation_depth: 1 +authority: + - product/routes/index.md + - product/routes/areas/**/*.md + - product/truth/**/*.md +`, + ); + + await runInit(repo.rootDir); + + const openCodeDocWriterAgent = await repo.readFile( + ".opencode/agents/truth-doc-writer.md", + ); + expect(openCodeDocWriterAgent).toContain('"product/truth/**": allow'); + expect(openCodeDocWriterAgent).toContain( + '"product/routes/index.md": allow', + ); + expect(openCodeDocWriterAgent).toContain( + '"product/routes/areas/**/*.md": allow', + ); + expect(openCodeDocWriterAgent).not.toContain('"docs/truth/**": allow'); + expect(openCodeDocWriterAgent).not.toContain( + '"docs/truthmark/areas.md": allow', + ); + } finally { + await repo.cleanup(); + } + }); + it("does not overwrite authored config and routing files on rerun", async () => { const repo = await createTempRepo(); @@ -952,7 +1286,9 @@ Update truth when: - local behavior changes `, ); - await fs.rm(path.join(repo.rootDir, "docs/truthmark/areas/repository.md")); + await fs.rm( + path.join(repo.rootDir, "docs/truthmark/areas/repository.md"), + ); await runInit(repo.rootDir); @@ -990,8 +1326,12 @@ authority: await runInit(repo.rootDir); - expect(await repo.readFile("docs/truth/README.md")).toContain("Truth Docs"); - expect(await repo.readFile("AGENTS.md")).toContain("Truth docs: docs/truth/**/*.md"); + expect(await repo.readFile("docs/truth/README.md")).toContain( + "Truth Docs", + ); + expect(await repo.readFile("AGENTS.md")).toContain( + "Truth docs: docs/truth/**/*.md", + ); } finally { await repo.cleanup(); } diff --git a/tests/integration/agent-workflow-contract.test.ts b/tests/integration/agent-workflow-contract.test.ts index e926759..48fdaaf 100644 --- a/tests/integration/agent-workflow-contract.test.ts +++ b/tests/integration/agent-workflow-contract.test.ts @@ -41,9 +41,21 @@ describe("installed workflow contract", () => { const realizeOpenCodeSkill = await repo.readFile( ".opencode/skills/truthmark-realize/SKILL.md", ); + const previewSkill = await repo.readFile( + ".codex/skills/truthmark-preview/SKILL.md", + ); const checkSkill = await repo.readFile( ".codex/skills/truthmark-check/SKILL.md", ); + const routeAuditorAgent = await repo.readFile( + ".codex/agents/truth-route-auditor.toml", + ); + const openCodeRouteAuditorAgent = await repo.readFile( + ".opencode/agents/truth-route-auditor.md", + ); + const claudeRouteAuditorAgent = await repo.readFile( + ".claude/agents/truth-route-auditor.md", + ); expect(agents.split("\n").length).toBeLessThanOrEqual(20); expect(agents).not.toContain("### Truth Structure"); @@ -56,7 +68,7 @@ describe("installed workflow contract", () => { expect(agents).not.toContain("/skill truthmark-structure"); expect(agents).not.toContain("/skill truthmark-check"); expect(agents).toContain( - "Explicit workflows: Truth Structure, Truth Document, Truth Realize, Truth Check", + "Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check", ); expect(agents).not.toContain( "truthmark check --json --workflow truth-sync", @@ -81,13 +93,15 @@ describe("installed workflow contract", () => { "direct checkout inspection is the canonical path", ); expect(documentSkill).toContain("name: truthmark-document"); - expect(documentSkill).toContain("Truth Document: completed"); + expect(documentSkill).toContain("support/procedure.md"); + expect(documentSkill).toContain("support/report-template.md"); expect(documentSkill).toContain("must not write functional code"); expect(syncOpenCodeSkill).toContain("name: truthmark-sync"); expect(syncClaudeSkill).toContain("name: truthmark-sync"); expect(syncClaudeSkill).toContain( "Use this skill automatically before finishing", ); + expect(syncClaudeSkill).toContain("support/subagents-and-leases.md"); expect(realizeSkill).toContain("name: truthmark-realize"); expect(realizeSkill).toContain( "Use this skill only when the user explicitly asks", @@ -96,9 +110,20 @@ describe("installed workflow contract", () => { "must not edit truth docs or truth routing", ); expect(realizeOpenCodeSkill).toContain("name: truthmark-realize"); - expect(realizeOpenCodeSkill).toContain("Truth Realize: completed"); + expect(realizeOpenCodeSkill).toContain("support/report-template.md"); + expect(previewSkill).toContain("name: truthmark-preview"); + expect(previewSkill).toContain("Truth Preview is read-only"); + expect(previewSkill).toContain("intended, not authorized"); expect(checkSkill).toContain("name: truthmark-check"); - expect(checkSkill).toContain("Truth Check: completed"); + expect(checkSkill).toContain("support/report-template.md"); + expect(checkSkill).toContain("support/subagents-and-leases.md"); + expect(routeAuditorAgent).toContain('sandbox_mode = "read-only"'); + expect(routeAuditorAgent).toContain("Do not edit files"); + expect(openCodeRouteAuditorAgent).toContain("mode: subagent"); + expect(openCodeRouteAuditorAgent).toContain("edit: deny"); + expect(claudeRouteAuditorAgent).toContain("name: truth-route-auditor"); + expect(claudeRouteAuditorAgent).toContain("tools: Read, Grep, Glob, LS"); + expect(claudeRouteAuditorAgent).toContain("Do not edit files"); await expect( repo.readFile("skills/truthmark-sync/SKILL.md"), ).rejects.toThrow(); diff --git a/tests/markdown/discovery.test.ts b/tests/markdown/discovery.test.ts index a240aff..49ea3b2 100644 --- a/tests/markdown/discovery.test.ts +++ b/tests/markdown/discovery.test.ts @@ -57,6 +57,10 @@ describe("discoverMarkdownDocuments", () => { ".github/prompts/truthmark-sync.prompt.md", "# Ignore me\n", ); + await repo.writeFile( + ".github/agents/truth-route-auditor.agent.md", + "# Ignore me\n", + ); await repo.writeFile("CLAUDE.md", "# Ignore me\n"); await repo.writeFile("GEMINI.md", "# Ignore me\n"); await repo.writeFile( @@ -164,10 +168,10 @@ describe("init templates", () => { expect(agentsBlock).not.toContain("### Truth Structure"); expect(agentsBlock).not.toContain("### Truth Check"); expect(agentsBlock).toContain( - "Explicit workflows: Truth Structure, Truth Document, Truth Realize, Truth Check", + "Explicit workflows: Truth Structure, Truth Document, Truth Preview, Truth Realize, Truth Check", ); expect(agentsBlock).toContain( - "may write truth docs and docs/truthmark/areas.md only", + "Sync may write truth docs and truth routing files", ); expect(agentsBlock).toContain( "Support new or changed behavior-bearing truth claims with checkout evidence", diff --git a/tests/routing/areas-markdown-globs.test.ts b/tests/routing/areas-markdown-globs.test.ts new file mode 100644 index 0000000..b9e9350 --- /dev/null +++ b/tests/routing/areas-markdown-globs.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; + +import { parseAreasMarkdown } from "../../src/routing/areas.js"; + +describe("parseAreasMarkdown Markdown glob handling", () => { + it("normalizes Prettier-escaped Markdown glob values", () => { + const result = parseAreasMarkdown(`# Truthmark Areas + +## Authentication + +Truth documents: +- docs/truth/authentication.md + +Code surface: +- src/auth/\\*\\* +- src/session/\\*\\* + +Update truth when: +- authentication behavior changes +`); + + expect(result.diagnostics).toEqual([]); + expect(result.areas[0]?.codeSurface).toEqual([ + "src/auth/**", + "src/session/**", + ]); + }); +});