From cc11b8e26c224db97ccc9e18588c9027625e2f09 Mon Sep 17 00:00:00 2001 From: MerlinH Date: Sun, 17 May 2026 01:06:41 +1000 Subject: [PATCH] (doc): readme enrichment --- README.de.md | 936 ++++++++++++++++++++++++++++++++++++++------------ README.es.md | 940 +++++++++++++++++++++++++++++++++++++------------- README.md | 943 +++++++++++++++++++++++++++++++++++++------------- README.ru.md | 946 ++++++++++++++++++++++++++++++++++++++------------- README.zh.md | 934 ++++++++++++++++++++++++++++++++++++++------------ 5 files changed, 3556 insertions(+), 1143 deletions(-) diff --git a/README.de.md b/README.de.md index ffc0675..f6b0da0 100644 --- a/README.de.md +++ b/README.de.md @@ -1,294 +1,694 @@ # Truthmark -**Truthmark installiert Repository-Wahrheits-Workflows für KI-Softwareentwicklung.** +**Deine Agenten schreiben Code. Truthmark macht ihren Kontext in Git prüfbar.** [English](README.md) | Deutsch | [中文](README.zh.md) | [Español](README.es.md) | [Русский](README.ru.md) -Truthmark-Banner +![Truthmark-Banner](docs/assets/truthmark-banner.png) -KI-Coding-Agenten schreiben bereits schnell Code. Der teure Teil ist, die Repository-Wahrheit mit den tatsächlichen Änderungen im Gleichschritt zu halten. +KI-Coding-Agenten können ein Repository schneller verändern, als Menschen den Kontext ausrichten können. -Truthmark fügt diesem Ablauf eine Abschlusskontrolle als Workflow hinzu. Der normale Pfad ist einfach: +Truthmark repariert den Teil, der normalerweise nach dem Code-Schreiben bricht: die Repository-Wahrheit. -- Agent ändert funktionalen Code -- relevante Tests laufen -- der installierte Truth-Sync-Workflow aktualisiert zugeordnete Wahrheitsdokumente, bevor der Agent fertig ist -- Truth-Doc-Diff prüfen, wenn einer erzeugt wurde +Es installiert eine Git-native, branch-gebundene Workflow-Schicht, die KI-Coding-Agenten hilft, die richtigen Dokumente zu aktualisieren, Ownership-Grenzen zu respektieren und Menschen normale Diffs zur Prüfung zu hinterlassen. -Die meisten Tools bitten Teams darum, sich eine Gewohnheit anzueignen. Truthmark macht daraus Repository-Workflow-Infrastruktur. +Kein gehosteter Dienst. -Truthmark macht aus einem KI-Workflow Repository-Infrastruktur statt persönlichem Tooling. Es installiert eine Git-native, branch-gebundene Wahrheitsschicht im Repository, gibt Agenten explizites Routing und begrenzte Workflow-Flächen und hält diese Wahrheit in Git prüfbar, statt sie über Prompt-Verlauf, veraltete Dokumentation oder privaten Tool-Zustand zu verstreuen. +Keine Datenbank. -Das ist wichtig, weil der Workflow mit dem Branch lebt. Sobald ein Repository initialisiert ist, reisen Regeln, Routing und installierte Workflow-Flächen im Repository mit, sodass Zusammenarbeit und Übergaben weniger von der Rechnerkonfiguration einer einzelnen Person abhängen. +Keine verborgene Memory-Schicht. -Für Teams, die bereits wissen, dass Agenten Code erzeugen können, beantwortet Truthmark das nächste Problem: wie das Repository selbst lesbar, prüfbar und steuerbar bleibt, wenn KI-gestützte Arbeit skaliert. +Kein zusätzlicher Server im Betrieb. -## Visueller Überblick +Nur Repository-Wahrheit, die mit dem Branch mitwandert. - - - - - - - - -
- Truthmark-Funktionen -
Funktionen
- Was Truthmark installiert und wie sich die Workflow-Fläche aufteilt. -
- Truthmark-Positionierung -
Positionierung
- Wo Truthmark im Verhältnis zu Prompts, Memory und Spec-Workflows steht. -
- Truthmark-Sync-Ablauf -
Sync-Ablauf
- Wie Truth Sync normale Codeänderungen vor einer Übergabe abschließt. -
+## Das Problem -## Warum Teams es nutzen +KI-Coding-Agenten sind gut darin, Code zu erzeugen. Dadurch entsteht eine neue Fehlerart. -Truthmark versucht nicht, Agenten klüger wirken zu lassen. Es soll KI-gestützte Repository-Änderungen vertrauenswürdiger machen. +Die Implementierung ändert sich, aber die Repository-Erzählung driftet ab: -- Installierte Truth-Sync-Läufe nach Codeänderungen machen Dokumentationspflege zu einer Workflow-Schutzschicht statt zu einer Teamgewohnheit. -- Branch-gebundene Wahrheit bewegt sich mit dem Code, sodass Reviewer aktuelle Wahrheit in normalen Git-Diffs prüfen können. -- Repository-native Workflow-Flächen machen Rollout leichter und Übergaben robuster als reine Pro-User-Konfiguration. -- Explizites Routing in `docs/truthmark/areas.md` und delegierten untergeordneten Routendateien gibt Agenten Zuständigkeitsgrenzen und sicherere Schreibpfade. -- Local-first-Betrieb vermeidet einen Daemon, eine Datenbank, einen Remote-Dienst oder eine MCP-Abhängigkeit. -- Das Routing-Modell ist sprachunabhängig, mit Coverage-Diagnostik für gängige JavaScript-, TypeScript-, Go-, Python-, C#- und Java-Codeflächen. +- Verhalten lebt im Chatverlauf +- Architekturdokumente fallen zurück +- Produktentscheidungen verschwinden nach der Übergabe +- Reviewer sehen Code-Diffs ohne die zugehörigen Truth-Diffs +- Branches entwickeln unbemerkt unterschiedliche Versionen davon, „was wahr ist“ +- jede Agentensitzung muss Kontext neu entdecken -Für Tech Leads liegt der Wert in Governance ohne Zusatzinfrastruktur: Tests, Code Review und Ownership leisten weiterhin die eigentliche Arbeit; Truthmark macht den Kontext des Agenten dauerhaft, prüfbar und branch-gebunden. +Truthmark verwandelt diesen fragilen Kontext in festgeschriebene Repository-Infrastruktur. -## Wo Truthmark hineinpasst +Statt darauf zu vertrauen, dass jeder Mensch und jeder Agent die richtige Dokumentationsgewohnheit beibehält, installiert Truthmark diese Gewohnheit im Repository. -Truthmark ist keine allgemeine KI-Produktivitätssuite. Es besetzt eine bestimmte Schicht im Stack: branch-gebundene, prüfbare Repository-Wahrheit, die mit der Implementierung synchron bleibt. +## Das Versprechen -| Wenn du brauchst | Beste Wahl | -| --------------------------------------------------------------------------- | ------------------------------------------- | -| Bessere Ergebnisse aus einer einzelnen Coding-Sitzung | Bessere Prompts und enger gefasste Aufgaben | -| Bequemlichkeit über Sitzungen hinweg für einen Agenten oder eine Person | Speicherwerkzeuge | -| Spec-first-Planung für neue Features | Spezifikations-Tools wie Spec Kit | -| Branch-gebundene, prüfbare Repository-Wahrheit, die mit dem Code mitwandert | Truthmark | +Wenn ein Agent funktionalen Code ändert, sollte die Arbeit nicht mit einem reinen Code-Diff enden. -Der Punkt ist nicht, dass Prompts, Memory oder Specs nutzlos wären. Der Punkt ist, dass keines davon allein Repository-Wahrheit in ein in Git festgeschriebenes, prüfbares Asset verwandelt, das Übergaben, Reviews und auseinanderlaufende Branches übersteht. +Der normale Truthmark-Pfad ist: -## Inhalt +```text +agent ändert funktionalen Code +relevante Tests laufen +Truth Sync prüft zugeordnete Truth-Dokumente +Truth-Dokumente werden bei Bedarf aktualisiert +Mensch prüft Code-Diff + Truth-Diff +committen oder übergeben +``` -- [Warum Teams es nutzen](#warum-teams-es-nutzen) -- [Was Truthmark löst](#was-truthmark-löst) -- [Wo Truthmark hineinpasst](#wo-truthmark-hineinpasst) -- [Erste Schritte](#erste-schritte) -- [Wie es läuft](#wie-es-läuft) -- [Was es installiert](#was-es-installiert) -- [Befehle](#befehle) -- [Warum es existiert](#warum-es-existiert) -- [Projektstatus](#projektstatus) -- [Dokumentation](#dokumentation) -- [Nicht-Ziele](#nicht-ziele) -- [Lizenz](#lizenz) +Das ist der Kernwert: **KI-Arbeit wird leichter vertrauenswürdig, weil das Repository lesbar bleibt.** -## Was Truthmark löst +## Zwei Oberflächen, ein Wahrheitssystem -Truthmark macht Repository-Wahrheit zu einer expliziten Workflow-Fläche für Agenten: +Truthmark ist nicht nur eine CLI. -- `.truthmark/config.yml` definiert den festgeschriebenen Hierarchievertrag. -- `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. +Es hat zwei unterschiedliche Oberflächen, und diese Unterscheidung ist wichtig. -Das ist das Kernversprechen: Agentenkontext wird zu festgeschriebenem Repository-Zustand statt zu einem privaten Sitzungsartefakt. +### 1. Menschenorientierte CLI -## Erste Schritte +Die CLI ist für Maintainer, Reviewer und Automatisierung. -Installiere Truthmark in dem Repository, das du initialisieren möchtest: +Nutze sie, um ein Repository zu konfigurieren, Workflow-Dateien zu installieren oder zu aktualisieren, Truth-Artefakte zu validieren und optionalen Review-Kontext zu erzeugen. + +```bash +truthmark config +truthmark init +truthmark check +``` + +Die CLI bereitet die Repository-Umgebung vor und validiert sie. + +Sie ist nicht die Runtime für den KI-Workflow. + +### 2. KI-orientierte Workflow-Oberflächen + +Die KI-orientierten Oberflächen sind für Coding-Agenten. + +Truthmark installiert host-native Skills, Prompts, Commands, verwaltete Instruktionsblöcke und unterstützte Subagent-Oberflächen, damit KI-Agenten repository-spezifische Truth-Workflows in ihren normalen Coding-Tools befolgen können. + +Beispiele: + +```text +/truthmark-sync +/truthmark-document +/truthmark-structure +/truthmark-realize +/truthmark-preview +/truthmark-check +``` + +Sie sehen wie Befehle aus, weil Agenten-Hosts Workflows über Slash-Commands, Prompts, Skills oder Projektbefehle bereitstellen. + +Es sind keine Shell-Befehle. + +Es sind KI-orientierte Workflow-Einstiegspunkte. + +Die Trennung ist das Produkt: + +```text +Menschen besitzen den Repository-Vertrag +Truthmark installiert den Vertrag ins Repo +Agenten arbeiten innerhalb dieses Vertrags +Truth-Updates erscheinen als Git-Diffs +Menschen prüfen das Ergebnis +``` + +## Quick Start + +### Voraussetzungen + +- Node.js `>=20` +- npm +- ein Git-Repository + +### Truthmark installieren + +Führe dies in dem Repository aus, das du initialisieren möchtest: ```bash cd /path/to/your-repo npm install -g truthmark +``` + +### Den Repository-Wahrheitsvertrag erstellen + +```bash +truthmark config +``` + +Das erzeugt: + +```text +.truthmark/config.yml +``` + +Prüfe diese Datei, bevor du fortfährst. Sie definiert den festgeschriebenen Hierarchievertrag für das Repository. + +### Die Workflow-Oberflächen installieren + +```bash +truthmark init +``` + +Das installiert oder aktualisiert: + +- Routendateien +- Truth-Doc-Scaffolding +- verwaltete Instruktionsblöcke +- KI-orientierte Workflow-Oberflächen für konfigurierte Plattformen + +### Das Setup validieren + +```bash +truthmark check +``` + +Prüfe danach die generierten Dateien, bevor du committest. + +Typische Dateien sind: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/repository.md +docs/templates/ +docs/truth/ +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/ +.claude/ +.opencode/ +.github/ +.gemini/ +``` + +Die genauen Dateien hängen von `.truthmark/config.yml` ab. + +## Erste echte Nutzung + +Die meisten Repositories brauchen nach der Initialisierung einen Aufräumschritt. + +Das Standard-Scaffold beginnt mit einem breiten Bereich `repository`. Echte Repositories brauchen meist präziseres Routing. + +Bitte deinen Agenten, die breite Route in tatsächliche Produkt-, Service-, Domänen- oder Ownership-Bereiche aufzuteilen: + +```text +/truthmark-structure die breite repository-area in auth, billing und notifications aufteilen +``` + +Danach nutzt du deinen KI-Coding-Agenten normal. + +Wenn der Agent funktionalen Code ändert, wirkt Truth Sync als Abschlusskontrolle und prüft vor der Übergabe, ob zugeordnete Truth-Dokumente geändert werden müssen. + +## Was du bekommst + +| Fähigkeit | Was sie tut | +| --- | --- | +| Git-native Wahrheit | Hält Repository-Wahrheit in festgeschriebenem Markdown und Config. | +| Branch-gebundener Kontext | Wahrheit wandert mit dem Branch statt in einer privaten Sitzung zu leben. | +| Menschen-CLI | Gibt Maintainern Befehle für Setup, Aktualisierung, Validierung und Inspektion. | +| KI-orientierte Workflows | Gibt Agenten host-native Workflows für Sync, Dokumentation, Struktur, Preview, Realisierung und Audit. | +| Explizites Routing | Ordnet Codebereiche kanonischen Truth-Dokumenten zu. | +| Prüffähige Übergaben | Erzeugt normale Git-Diffs für Code und Truth-Dokumente. | +| Local-first-Betrieb | Benötigt keinen gehosteten Dienst, Daemon, keine Datenbank und keinen MCP-Server. | +| Sicherere Schreibgrenzen | Trennt code-first, doc-first, read-only und doc-only Workflows. | +| Validierung | Meldet Probleme bei Routing, Autorität, Frontmatter, Links, generierten Oberflächen, Branch-Scope, Freshness und Coverage. | + +## Visueller Überblick + +![Truthmark-Funktionen](docs/assets/truthmark-features.png) + +**Funktionen:** was Truthmark installiert und wie die Workflow-Oberfläche aufgeteilt ist. + +![Truthmark-Positionierung](docs/assets/truthmark-position.png) + +**Positionierung:** wo Truthmark im Verhältnis zu Prompts, Memory und Spec-Workflows steht. + +![Truthmark-Sync-Ablauf](docs/assets/truthmark-syncflow.png) + +**Sync-Ablauf:** wie Truth Sync normale Codeänderungen vor der Übergabe abschließt. + +## Warum Teams es nutzen + +Truthmark ist für Teams, die bereits wissen, dass KI-Agenten Code erzeugen können. + +Das nächste Problem ist Governance. + +Nicht Governance als Zeremonie. Governance als einfache Frage: + +> Erzählt das Repository nach dieser KI-gestützten Änderung noch die Wahrheit? + +Truthmark hilft Teams, diese Frage mit festgeschriebenen Dateien, explizitem Routing und prüffähigen Diffs zu beantworten. + +Es ist nützlich, wenn du Folgendes brauchst: + +- weniger Dokumentationsdrift +- bessere Übergaben +- branch-spezifische Produktwahrheit +- dauerhaften Architektur- und API-Kontext +- explizite Ownership zwischen Dokumentation und Code +- sicherere Schreibgrenzen für Agenten +- prüffähigen Kontext statt verborgener Memory +- KI-Workflows, die weiterhin aus festgeschriebenen Repo-Dateien funktionieren + +## Wo Truthmark hineinpasst + +Truthmark ersetzt keine Prompts, Memory, Specs, Tests oder Code Review. + +Es gibt diesen Workflows einen dauerhaften Ort in Git. + +| Bedarf | Besser passend | +| --- | --- | +| Bessere Ausgabe aus einer Agentensitzung | Besserer Prompt | +| Persönliche oder sitzungsbezogene Kontinuität | Memory-Tool | +| Plan-first Feature-Arbeit | Spec-Workflow | +| Branch-gebundene Wahrheit, die mit dem Code mitwandert | Truthmark | +| Korrektheit von Verhalten validieren | Tests und Review | +| KI-gestützte Kontextänderungen prüfen | Truthmark plus Git-Review | + +Truthmarks Spur ist absichtlich eng: + +```text +Repository-Wahrheit explizit machen +sie zu Code routen +Agenten-Workflows darum installieren +das Ergebnis in Git prüffähig halten +``` + +## Wie Truthmark läuft + +Truthmark läuft lokal gegen den aktiven Git-Worktree. + +Die menschenorientierte CLI liest und schreibt Repository-Dateien und beendet sich danach. + +Die KI-orientierten Workflow-Oberflächen sind festgeschriebene Dateien, die Agenten-Hosts später laden können. Dadurch können Agenten dem installierten Workflow aus dem Repository-Zustand folgen, statt von einem Hintergrundprozess von Truthmark abzuhängen. + +Die dauerhaften Oberflächen sind normale Repo-Dateien: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +docs/**/* +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/skills/ +.claude/skills/ +.opencode/skills/ +.github/prompts/ +.gemini/commands/truthmark/ +``` + +Generierte Workflow-Oberflächen enthalten Truthmark-Versionsmarker. Nach einem Upgrade von Truthmark erneut ausführen: + +```bash +truthmark init +``` + +Prüfe danach die generierten Diffs. + +## Unterstützte Agentenplattformen + +Die Standardkonfiguration enthält jede unterstützte Plattform. + +Entferne Plattformen, die du nicht nutzt, aus `.truthmark/config.yml`, und führe danach erneut aus: + +```bash +truthmark init +``` + +| Plattform-Configname | Generierte Oberfläche | Aufrufform | +| --- | --- | --- | +| `codex` | `.codex/skills/truthmark-*/`, `.codex/agents/` | `/truthmark-*` oder `$truthmark-*` | +| `claude-code` | `.claude/skills/truthmark-*/`, `.claude/agents/`, `CLAUDE.md` | `/truthmark-*` | +| `github-copilot` | `.github/prompts/`, `.github/agents/`, `.github/copilot-instructions.md` | `/truthmark-*` in unterstützten Copilot-IDEs; `@truth-*` Custom Agents in Copilot CLI | +| `opencode` | `.opencode/skills/truthmark-*/`, `.opencode/agents/` | `/skill truthmark-*` | +| `gemini-cli` | `.gemini/commands/truthmark/`, `GEMINI.md` | `/truthmark:*` | + +Unbekannte Plattformnamen sind Config-Fehler. + +Das Entfernen einer Plattform stoppt künftige Aktualisierungen für diese Plattform. Es löscht zuvor generierte Dateien nicht. + +## KI-orientierte Workflows + +Diese Workflows werden in unterstützte KI-Coding-Hosts installiert. + +Sie werden von Agenten oder Agenten-Hosts während der Repository-Arbeit genutzt. Sie sind keine Top-Level-Shell-Befehle. + +| Workflow | Richtung | Nutze ihn, wenn | Schreibgrenze | +| --- | --- | --- | --- | +| Truth Structure | topology-first | Die Standardroute zu breit ist, Ownership mehrere Bereiche umfasst oder Routendateien noch auf Platzhalter zeigen. | Erstellt oder repariert Routing und Starter-Truth-Dokumente. | +| Truth Document | implementation-first | Verhalten bereits im Code existiert, aber kanonische Truth-Dokumente fehlen oder schwach sind. | Schreibt nur Truth-Dokumente und Routing. Funktionaler Code darf nicht geändert werden. | +| Truth Sync | code-first | Funktionaler Code geändert wurde und zugeordnete Truth-Dokumente vor der Übergabe aktualisiert werden müssen könnten. | Aktualisiert Truth-Dokumente. Funktionaler Code darf von Truth Sync nicht umgeschrieben werden. | +| Truth Preview | read-only | Der Agent vor Änderungen wahrscheinliches Routing einschätzen muss. | Liest nur. Autorisiert keine Schreibzugriffe. | +| Truth Realize | doc-first | Produkt- oder Architektur-Truth-Dokumente führen und Code daran angepasst werden soll. | Aktualisiert nur Code. Der Agent darf die Truth-Dokumente, die er realisiert, nicht bearbeiten. | +| Truth Check | audit-first | Ein Reviewer oder Agent die Gesundheit der Repository-Wahrheit auditieren muss. | Auditiert und berichtet. | + +### Wichtige Unterscheidung + +Verwechsle diese zwei Oberflächen nicht: + +| Oberfläche | Genutzt von | Beispiel | Bedeutung | +| --- | --- | --- | --- | +| Menschen-CLI | Menschen, Skripte, CI-ähnliche Checks | `truthmark check` | Truth-Artefakte des Repositorys im Terminal validieren. | +| KI-orientierter Workflow | Coding-Agenten und Agenten-Hosts | `/truthmark-check` | Einen Agenten bitten, den installierten Audit-Workflow auszuführen. | + +Die Namen sind absichtlich verwandt, aber die Oberflächen sind unterschiedlich. + +## Normale KI-gestützte Codeänderung + +Die meisten Nutzer sollten Truth Sync nicht jedes Mal manuell aufrufen müssen. + +Truth Sync ist die installierte Abschlusskontrolle für funktionale Codeänderungen. + +```text +agent ändert funktionalen Code +agent führt relevante Tests aus oder fordert sie an +installierter Workflow erkennt, dass funktionaler Code geändert wurde +Truth Sync prüft zugeordnete Truth-Dokumente +agent aktualisiert Truth-Dokumente bei Bedarf +Mensch prüft Code-Diff + Truth-Diff +``` + +Der direkte Aufruf ist trotzdem nützlich für Fehlersuche, frühes Synchronisieren oder eine explizite Übergabe: + +```text +/truthmark-sync die Repository-Wahrheit jetzt vor der Übergabe synchronisieren +``` + +## Bestehendes Verhalten ohne Doku + +Nutze Truth Document, wenn die Implementierung bereits existiert, aber die Repository-Wahrheit unvollständig ist. + +```text +/truthmark-document das implementierte Session-Timeout-Verhalten unter docs/truth/authentication dokumentieren +``` + +Truth Document prüft Implementierung, Tests, Routendateien und vorhandene Dokumente als Evidenz. + +Es schreibt nur Truth-Dokumente und Routing. + +Es darf keinen funktionalen Code ändern. + +## Doc-first-Änderungen + +Nutze Truth Realize, wenn eine Produkt- oder Architekturentscheidung in Dokumenten beginnt und Code daran angepasst werden soll. + +```text +/truthmark-realize docs/truth/authentication/session-timeout.md in Code realisieren +``` + +Truth Realize ist doc-first. + +Die Truth-Dokumente führen. Der Code folgt. + +Der Agent darf die Truth-Dokumente, die er realisiert, nicht bearbeiten. + +## Read-only-Routing-Preview + +Nutze Truth Preview vor einer Änderung, wenn der Agent wahrscheinliches Routing verstehen muss. + +```text +/truthmark-preview das wahrscheinliche Truth-Routing für Änderungen an der Billing-API prüfen +``` + +Truth Preview ist read-only. + +Es ist Auswahl- und Planungshilfe, keine Schreibautorisierung und kein Ersatz für Truth Check. + +## Repository-Truth-Audit + +Nutze Truth Check, wenn du einen agentenorientierten Audit-Workflow möchtest. + +```text +/truthmark-check Routing und Truth-Coverage vor dem Review auditieren +``` + +Nutze die menschenorientierte CLI, wenn du Terminalvalidierung möchtest: + +```bash +truthmark check +``` + +Beides ist nützlich. Es ist nicht dieselbe Oberfläche. + +## Menschenorientierte CLI-Befehle + +Die meisten Maintainer beginnen mit drei Befehlen. + +| Befehl | Zweck | +| --- | --- | +| `truthmark config` | Erstellt `.truthmark/config.yml`. Schreibt nur diese Datei, außer `--stdout` wird verwendet. | +| `truthmark init` | Installiert oder aktualisiert konfigurierte Workflow-Oberflächen aus der geprüften Config. | +| `truthmark check` | Validiert Config, Autorität, Routing, entscheidungstragende Dokumente, Frontmatter, interne Links, Branch-Scope, generierte Oberflächen, Freshness und Coverage-Diagnostik. | + +Optionale Repository-Intelligence-Helfer erzeugen abgeleiteten Review-Kontext für den aktiven Checkout. + +Sie sind keine Quellen der Wahrheit. + +| Befehl | Zweck | +| --- | --- | +| `truthmark index` | Baut RepoIndex- und RouteMap-JSON für den aktiven Checkout. | +| `truthmark impact --base ` | Ordnet geänderte Dateien gerouteten Truth-Dokumenten, besitzenden Routen, nahen Tests und öffentlichen Symbolen zu. | +| `truthmark context --workflow [--base ]` | Erzeugt ein begrenztes ContextPack für Truth Sync, Truth Document oder Truth Realize. Nutze `--format markdown` für eine menschenlesbare Fassung. | + +Strukturierte Ausgabe ist mit `--json` verfügbar, wo sie unterstützt wird. + +## Konfiguration + +Truthmark ist config-first. + +Die wichtigste Config-Datei ist: + +```text +.truthmark/config.yml +``` + +Neue Repositories sollten ausführen: + +```bash +truthmark config +``` + +Prüfe danach die generierte Config, bevor du ausführst: + +```bash +truthmark init +``` + +Wichtige Config-Bereiche sind: + +| Config-Bereich | Zweck | +| --- | --- | +| `version` | Version des Config-Vertrags. | +| `platforms` | Agenten-Hosts, die plattformspezifische generierte Oberflächen erhalten sollen. | +| `docs.layout` | Aktueller Docs-Layoutmodus. | +| `docs.roots` | Benannte kanonische Dokumentationswurzeln. | +| `docs.routing.root_index` | Pfad zum Root-Routenindex. | +| `docs.routing.area_files_root` | Verzeichnis für delegierte untergeordnete Routendateien. | +| `docs.routing.default_area` | Dateiname des initial erzeugten untergeordneten Routings ohne Erweiterung. | +| `docs.routing.max_delegation_depth` | Aktuelle maximale Routing-Delegationstiefe. | +| `authority` | Geordnete kanonische Dokumente und Globs, die als Repository-Truth-Autorität dienen. | +| `instruction_targets` | Dateien, die gemeinsam verwaltete Instruktionsblöcke erhalten, etwa `AGENTS.md`. | +| `frontmatter.required` | Metadatenfelder, die bei Fehlen Error-Diagnostik erzeugen. | +| `frontmatter.recommended` | Metadatenfelder, die bei Fehlen Review-Diagnostik erzeugen. | +| `ignore` | Glob-Muster, die von relevanten Checks und Routing-Logik ausgeschlossen sind. | + +## Repository-Truth-Routing + +Truthmark ordnet Codeoberflächen Truth-Dokumenten zu. + +Die wichtigsten Routendateien sind: + +```text +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +``` + +Eine Route sagt dem Agenten: + +- welche Codeoberfläche zu einem Bereich gehört +- welche Truth-Dokumente diesen Bereich besitzen +- wann Truth aktualisiert werden sollte +- welche Art von Truth-Dokument beteiligt ist + +Das Standard-Scaffold beginnt breit. Bestehende Repositories sollten die Standardroute meist in echte Ownership-Bereiche aufteilen. + +Beispiel: + +```text +/truthmark-structure die breite repository-area in frontend, backend, billing und deployment aufteilen +``` + +Gutes Routing gibt Truth Sync präzise Ziele. + +Schlechtes Routing zwingt Agenten zum Raten. + +## Was Truthmark installiert + +Truthmark installiert eine kompakte, repository-native Truth-Schicht. + +Typische Scaffold- und generierte Dateien sind: + +```text +.truthmark/config.yml + +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md + +docs/templates/behavior-doc.md +docs/templates/contract-doc.md +docs/templates/architecture-doc.md +docs/templates/workflow-doc.md +docs/templates/operations-doc.md +docs/templates/test-behavior-doc.md + +docs/truth/README.md +docs/truth/repository/README.md +docs/truth/repository/overview.md + +docs/standards/default-principles.md +docs/standards/documentation-governance.md + +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md + +.codex/skills/truthmark-*/ +.codex/agents/ + +.claude/skills/truthmark-*/ +.claude/agents/ + +.opencode/skills/truthmark-*/ +.opencode/agents/ + +.github/prompts/truthmark-*.prompt.md +.github/agents/ + +.gemini/commands/truthmark/*.toml +``` + +Truthmark bewahrt manuellen Inhalt außerhalb verwalteter Instruktionsblöcke. + +Generierte Workflow-Oberflächen werden von Truthmark verwaltet und können durch erneutes Ausführen aktualisiert werden: + +```bash +truthmark init +``` + +## Subagents und begrenzte Evidenzprüfungen + +Wo der Host es unterstützt, kann Truthmark projektbezogene Prüfer-Agenten und einen geleasten `truth-doc-writer` installieren. + +Diese helfen, große Truth-Aufgaben begrenzt zu halten: + +- Route Auditors prüfen Route-Ownership +- Claim Verifiers prüfen, ob Dokumentclaims durch Evidenz gestützt sind +- Doc Reviewers prüfen Truth-Doc-Qualität +- geleaste Doc Writers bearbeiten begrenzte Truth-Doc-Schreib-Shards + +Der Parent-Workflow besitzt weiterhin finale Interpretation, Schreibgrenzen, Diff-Validierung und Abnahme. + +Das ist wichtig: Subagents helfen bei begrenzter Evidenzarbeit. Sie ersetzen den Haupt-Workflow-Vertrag nicht. + +## Review-Schleife + +Truthmark ist für normalen Git-Review entworfen. + +Eine gute KI-gestützte Übergabe sollte Folgendes zeigen: + +```text +Code-Diff +Test-Evidenz +Truth-Doc-Diff, falls nötig +Routing-Änderungen, falls nötig +Agentenbericht +``` + +Der Reviewer sollte beantworten können: + +- Welcher Code hat sich geändert? +- Welche Truth-Dokumente besitzen diesen Code? +- Mussten diese Dokumente aktualisiert werden? +- Falls nicht, warum nicht? +- Ist der Agent innerhalb der Workflow-Schreibgrenze geblieben? +- Sind Test- oder Verifikationsevidenz enthalten? + +## Beispiele + +### Ein Repository initialisieren + +```bash +npm install -g truthmark truthmark config truthmark init truthmark check ``` -Wenn du stattdessen unveröffentlichte Änderungen aus einem Source-Checkout ausprobieren möchtest: +### Unbenutzte Agentenplattformen entfernen -```bash -cd /path/to/truthmark -npm install -npm run build -cd /path/to/your-repo -node /path/to/truthmark/dist/main.js config -node /path/to/truthmark/dist/main.js init -node /path/to/truthmark/dist/main.js check -``` - -Prüfe `.truthmark/config.yml` vor `init`; es ist der in Git festgeschriebene Hierarchievertrag. Nach `init` solltest du die generierte Workflow-Fläche und die Routendateien prüfen, damit die gerouteten Dokumente zu den Dokumenten passen, die deinen Code tatsächlich verantworten: +Bearbeiten: ```text .truthmark/config.yml -docs/truthmark/areas.md -docs/truthmark/areas/repository.md -docs/templates/behavior-doc.md -docs/truth/README.md -docs/truth/repository/README.md -docs/truth/repository/overview.md -AGENTS.md -CLAUDE.md -GEMINI.md ``` -Unterstützte Plattformen sind `codex`, `opencode`, `claude-code`, `github-copilot` und `gemini-cli`. Die Standardkonfiguration enthält alle davon; entferne Plattformen, die du nicht nutzt, aus `.truthmark/config.yml`, bevor du `truthmark init` erneut ausführst. -Die standardmäßig erzeugte Struktur verwendet Truth-`README.md`-Dateien als Indizes und beginnt die Wahrheit über aktuelles Verhalten in begrenzten Blattdokumenten wie `docs/truth/repository/overview.md`. +Danach erneut ausführen: -Bestehende Repositories brauchen nach `init` meist einen Aufräumschritt: Führe den installierten Truth-Structure-Workflow aus, wenn die erzeugte `repository`-Route zu breit ist, Ownership mehrere Produkte oder Services umfasst oder Routendateien noch auf Platzhalterdokumente zeigen. Truth Structure teilt breite Routings auf, erstellt oder repariert erste kanonische Wahrheitsdokumente und gibt Truth Sync präzise Ziele, bevor funktionale Codearbeit beginnt. Codex, Claude Code und unterstützte Copilot-IDEs können ihn mit `/truthmark-structure` aufrufen; Hosts im OpenCode-Stil können `/skill truthmark-structure` verwenden. +```bash +truthmark init +truthmark check +``` -## Wie es läuft - -Truthmark ist am stärksten auf dem Standardpfad, nicht als Sammlung manueller Befehle. Der handelnde Agent und die Host-Umgebung entscheiden, ob delegiert oder der installierte Workflow inline ausgeführt wird. - -### Vorhandenes Verhalten ohne Doku - -Nutze das, wenn die Implementierung bereits existiert, aber die kanonischen Wahrheitsdokumente fehlen oder schwach sind: +### Breites Routing aufteilen ```text -benutzer identifiziert ein implementiertes verhalten oder einen api-endpunkt -benutzer ruft truth document ausdrücklich auf -agent liest implementierung, tests, routing und vorhandene docs -agent schreibt nur truth docs und routing -truth-doc-diff prüfen +/truthmark-structure die breite repository-area in auth, billing, notifications und deployment aufteilen ``` -Truth Document ist manuell und implementation-first: Code dient als Beleg, Wahrheitsdokumente werden erstellt oder repariert, und funktionaler Code darf nicht geändert werden. Codex, Claude Code und unterstützte Copilot-IDEs können es mit `/truthmark-document` aufrufen. Hosts im OpenCode-Stil können `/skill truthmark-document` verwenden. +### Implementiertes Verhalten dokumentieren ```text -/truthmark-document dokumentiere das implementierte session-timeout-verhalten unter docs/truth/authentication +/truthmark-document den implementierten Password-Reset-Flow unter docs/truth/authentication dokumentieren ``` -### Normale Codeänderungen - -Die meisten Nutzer sollten Truth Sync nicht direkt aufrufen müssen. Entscheidend ist, dass der installierte Agenten-Workflow Truth Sync als Abschlusskontrolle behandelt, wenn funktionaler Code geändert wurde. Der normale Ablauf ist: +### Nach Codeänderungen synchronisieren ```text -agent ändert funktionalen code -relevante tests laufen -der installierte truth-sync-workflow läuft, bevor der agent fertig ist -truth-doc-diff prüfen, falls einer erzeugt wurde -arbeit committen oder übergeben +/truthmark-sync die Repository-Wahrheit jetzt vor der Übergabe synchronisieren ``` -Truth Sync ist code-first: Code führt, Wahrheitsdokumente folgen, und Truth Sync darf funktionalen Code nicht umschreiben. Seine Hauptaufgabe ist, über den installierten Agenten-Workflow als Abschlusskontrolle zu laufen, wenn funktionaler Code geändert wurde. Direkte Aufrufe sind vor allem für Fehlersuche, frühe Synchronisierung vor einer Übergabe oder bewusstes Ausführen des Workflows gedacht. - -Codex, Claude Code und unterstützte Copilot-IDEs können es mit `/truthmark-sync` aufrufen. Hosts im OpenCode-Stil können `/skill truthmark-sync` verwenden. +### Eine doc-first Entscheidung realisieren ```text -/truthmark-sync die repository-wahrheit jetzt vor der übergabe synchronisieren +/truthmark-realize docs/truth/billing/invoice-retry-policy.md in Code realisieren ``` -### Doc-first-Änderungen +### Truth-Gesundheit im Terminal auditieren -Nutze das, wenn eine Produkt- oder Architekturentscheidung in der Doku beginnt: - -```text -benutzer bearbeitet wahrheitsdokumente -benutzer ruft truth realize ausdrücklich auf -agent liest wahrheitsdokumente und relevanten code -agent aktualisiert nur code -relevante tests laufen -arbeit committen oder übergeben +```bash +truthmark check ``` -Truth Realize ist manuell und doc-first: Wahrheitsdokumente führen, Code folgt, und der Agent darf die Wahrheitsdokumente, die er realisiert, nicht bearbeiten. +### Branch-Impact-Kontext erzeugen -Codex, Claude Code und unterstützte Copilot-IDEs können es mit `/truthmark-realize` aufrufen. Hosts im OpenCode-Stil können `/skill truthmark-realize` verwenden. - -```text -/truthmark-realize docs/truth/authentication/session-timeout.md in code umsetzen +```bash +truthmark impact --base main ``` -## Was es installiert +### Workflow-Kontext erzeugen -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 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. - -`README.md`-Dateien von Features sind Indizes. Truth Sync soll begrenzte Blattdokumente für aktuelles Verhalten lesen und aktualisieren. Generierte Workflow-Flächen bewahren die Autorität der Repository-Regeln, während sie Implementierungscode und kanonische Wahrheitsdokumente als Belege für aktuelles Verhalten behandeln. - -Generierte Flächen werden von Truthmark verwaltet, enthalten einen Versionsmarker und können mit `truthmark init` aktualisiert werden. - -## Befehle - -Truthmark V1 hält die Terminal-CLI fokussiert. Die meisten menschlichen Nutzer brauchen nur Einrichtung, Aktualisierung und Validierung: - -| 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. | - -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: - -| 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. | - -Alle oben genannten CLI-Befehle unterstützen `--json`, wenn strukturierte Ausgabe für Automatisierung nützlich ist. - -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 +```bash +truthmark context --workflow truth-sync --base main --format markdown ``` -## Warum es existiert - -Die meisten KI-Coding-Workflows optimieren für die nächste Antwort. Truthmark optimiert für die nächste Übergabe. -Es geht davon aus, dass ernsthafte Teams Folgendes brauchen: - -- branch-spezifische Produktwahrheit -- dauerhafte Architektur- und API-Entscheidungen -- explizite Zuständigkeit zwischen Dokumentation und Code -- sichere Schreibgrenzen für Agenten -- normale Git-Diffs, die Menschen prüfen können -- lesbares Markdown, das Teammitglieder ohne Spezialwerkzeuge inspizieren können -- Wahrheit, die mit dem Branch mitwandert, statt in verborgenem Sitzungszustand zu leben -- Workflows, die auch funktionieren, wenn das Paket nicht global installiert ist - ## Projektstatus -Truthmark ist kein Memory-Server und kein MCP-Server. Es ist eine Repository-Praxis, verpackt als kleiner CLI-Installer plus agent-native Workflow-Flächen, die KI-Workflow-Regeln in Repository-Infrastruktur verwandeln. - -V1 bietet derzeit: +Truthmark V1 bietet derzeit: - `truthmark config` - `truthmark init` @@ -296,15 +696,58 @@ V1 bietet derzeit: - `truthmark index` - `truthmark impact` - `truthmark context` -- verwaltete `AGENTS.md`-Workflow-Anweisungen -- 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 +- verwaltete Instruktionsblöcke +- generierte Truth-Structure-Workflow-Oberflächen +- generierte Truth-Document-Workflow-Oberflächen +- generierte Truth-Sync-Workflow-Oberflächen +- generierte Truth-Preview-Workflow-Oberflächen +- generierte Truth-Realize-Workflow-Oberflächen +- generierte Truth-Check-Workflow-Oberflächen +- Diagnostik für Route, Autorität, Entscheidungsstruktur, Frontmatter, Links, Freshness, generierte Oberflächen und Coverage +- abgeleitete RepoIndex-, RouteMap-, ImpactSet- und ContextPack-Artefakte +- host-spezifische Oberflächen für Codex, Claude Code, GitHub Copilot, OpenCode und Gemini CLI + +## Entwicklung + +Abhängigkeiten installieren: + +```bash +npm install +``` + +Die lokale Entwicklungs-CLI ausführen: + +```bash +npm run dev -- init +npm run dev -- check +``` + +Den vollständigen Projektcheck ausführen: + +```bash +npm run check +``` + +Nützliche Skripte: + +| Skript | Zweck | +| --- | --- | +| `npm run dev` | Führt den TypeScript-CLI-Einstiegspunkt mit `tsx` aus. | +| `npm run build` | Baut das Paket. | +| `npm run lint` | Führt ESLint aus. | +| `npm run typecheck` | Führt TypeScript-Checks aus. | +| `npm run test` | Führt Tests aus. | +| `npm run check` | Führt Lint, Typecheck, Tests und Build aus. | +| `npm run release:check` | Führt release-orientierte Validierung aus. | + +Wenn du Truthmark selbst änderst, siehe [CONTRIBUTORS.md](CONTRIBUTORS.md). ## Dokumentation -Die Root-README ist für Menschen gedacht, die das Paket evaluieren und ausprobieren. Detaillierte funktionale und geschäftliche Spezifikationen liegen unter `docs/`: +Die README ist der schnelle Pfad für Evaluation und Setup. + +Aktuelles Verhalten im Detail lebt unter `docs/`: - [Dokumentationsindex](docs/README.md) - [Architekturüberblick](docs/architecture/overview.md) @@ -314,11 +757,11 @@ Die Root-README ist für Menschen gedacht, die das Paket evaluieren und ausprobi - [Installierte Workflows](docs/truth/workflows/overview.md) - [Leitfaden zur Pflege von Repository-Wahrheit](docs/standards/maintaining-repository-truth.md) -Aktuelles Verhalten gehört in den oben genannten kanonischen Dokumentationsbaum. +## Designgrenzen -## Nicht-Ziele +Truthmark ist absichtlich klein. -Truthmark V1 ist nicht: +Es ist nicht: - ein gehosteter Dienst - ein MCP-Server @@ -327,8 +770,49 @@ Truthmark V1 ist nicht: - ein CI- oder PR-Enforcement-Produkt - ein Ersatz für Tests, Code Review oder technische Führung - eine autonome Code-Rewrite-Engine +- ein Framework für Modelltraining oder Fine-Tuning +- eine verborgene Memory-Schicht -Es ist ein leichtgewichtiger Weg, lokale KI-Coding-Agenten dazu zu bringen, die Wahrheit zu respektieren, die dein Team in Git pflegt. +Diese Grenzen sind Teil des Produkts. + +Truthmark hält den Workflow lokal, festgeschrieben, branch-gebunden und prüffähig. + +## Sicherheit und Review-Disziplin + +Truthmark hilft dem Repository, ehrlich zu bleiben. Es beweist nicht, dass der Code korrekt ist. + +Teams sollten weiterhin: + +- relevante Tests ausführen +- funktionale Codeänderungen prüfen +- Truth-Doc-Änderungen prüfen +- Secrets aus der Dokumentation heraushalten +- repository-spezifische Instruktionen außerhalb verwalteter Blöcke halten +- Diffs generierter Workflow-Oberflächen nach Upgrades prüfen +- menschliche Ownership über Produkt- und Architekturentscheidungen behalten + +Truthmark macht Agentenkontext sichtbar. Es ersetzt menschliches Urteil nicht. + +## Roadmap-Richtung + +Die aktuelle Zukunftsrichtung betont: + +- stärkere Evidenzberichte in `truthmark check` +- klarere Adoptionsbeispiele +- Beispiel-Repositories mit echten Truth-Sync-Zyklen +- Migrationsleitfäden für Teams, die bereits Agenten-Instruktionsdateien nutzen +- Konformitätstests für generierte Host-Oberflächen +- route-aware Hinweise auf stale truth +- begrenzte Implementierungschecklisten für doc-first Arbeit + +Der Schwerpunkt bleibt gleich: + +```text +Repository-Wahrheit +agent-native Workflows +Git-Review +branch-gebundener Kontext +``` ## Lizenz diff --git a/README.es.md b/README.es.md index 39dd4b3..f57cfb4 100644 --- a/README.es.md +++ b/README.es.md @@ -1,294 +1,694 @@ # Truthmark -**Truthmark instala flujos de verdad del repositorio para el desarrollo de software con IA.** +**Tus agentes escriben código. Truthmark hace que su contexto sea revisable en Git.** [English](README.md) | [Deutsch](README.de.md) | [中文](README.zh.md) | Español | [Русский](README.ru.md) -Banner de Truthmark +![Banner de Truthmark](docs/assets/truthmark-banner.png) -Los agentes de programación con IA ya escriben código rápido. La parte costosa es mantener alineada la verdad del repositorio con lo que realmente cambió. +Los agentes de programación con IA pueden cambiar un repositorio más rápido de lo que las personas pueden mantener alineado su contexto. -Truthmark añade una guarda de cierre basada en flujo de trabajo. El camino normal es simple: +Truthmark arregla la parte que normalmente se rompe después de escribir el código: la verdad del repositorio. -- el agente cambia código funcional -- se ejecutan las pruebas relevantes -- el flujo instalado Truth Sync actualiza los documentos de verdad asignados antes de que el agente termine -- se revisa el diff de documentos de verdad si se produjo uno +Instala una capa de flujo de trabajo nativa de Git y acotada a la rama que ayuda a los agentes de programación con IA a actualizar los documentos correctos, respetar los límites de propiedad y dejar a las personas diffs normales que puedan revisar. -La mayoría de las herramientas pide al equipo adoptar un hábito. Truthmark convierte ese hábito en infraestructura de flujo del repositorio. +Sin servicio alojado. -Truthmark convierte un flujo de trabajo con IA en infraestructura del repositorio, no en tooling personal. Instala una capa de verdad nativa de Git y acotada a la rama dentro del propio repositorio, da a los agentes rutas explícitas y superficies de trabajo acotadas, y mantiene esa verdad revisable en Git en lugar de dispersarla por el historial de prompts, documentación obsoleta o estado privado de herramientas. +Sin base de datos. -Eso importa porque el flujo vive con la rama. Una vez inicializado un repositorio, las reglas, el enrutamiento y las superficies instaladas viajan dentro del repo, así que la colaboración y los traspasos dependen menos de la configuración local de una sola persona. +Sin capa oculta de memoria. -Para equipos que ya saben que los agentes pueden generar código, Truthmark responde al siguiente problema: cómo hacer que el repositorio siga siendo legible, revisable y gobernable a medida que crece el trabajo asistido por IA. +Sin servidor adicional que operar. -## Resumen visual +Solo verdad del repositorio que se mueve con la rama. - - - - - - - - -
- Características de Truthmark -
Características
- Lo que instala Truthmark y cómo se divide la superficie de trabajo. -
- Posicionamiento de Truthmark -
Posicionamiento
- Dónde encaja Truthmark frente a prompts, memoria y flujos spec-first. -
- Flujo de sync de Truthmark -
Flujo de sync
- Cómo Truth Sync cierra cambios normales de código antes del traspaso. -
+## El problema -## Por qué los equipos lo adoptan +Los agentes de programación con IA son buenos produciendo código. Eso crea un nuevo modo de fallo. -Truthmark no intenta hacer que los agentes suenen más inteligentes. Intenta que los cambios de repositorio asistidos por IA sean más confiables. +La implementación cambia, pero la historia del repositorio se desvía: -- El flujo instalado Truth Sync tras cambios de código convierte el mantenimiento de documentación en una salvaguarda del flujo, no en un hábito del equipo. -- La verdad acotada a la rama viaja con el código, de modo que quienes revisan pueden inspeccionar la verdad actual en diffs normales de Git. -- Las superficies de flujo nativas del repositorio hacen el despliegue más ligero y los traspasos más resistentes que una simple configuración por usuario. -- El enrutamiento explícito en `docs/truthmark/areas.md` y en archivos de rutas secundarias delegadas da a los agentes límites de responsabilidad y rutas de escritura más seguras. -- La operación local-first evita depender de un demonio, una base de datos, un servicio remoto o MCP. -- El modelo de enrutamiento es independiente del lenguaje, con diagnósticos de cobertura para superficies comunes de código JavaScript, TypeScript, Go, Python, C# y Java. +- el comportamiento vive en el historial de chat +- los documentos de arquitectura quedan atrás +- las decisiones de producto desaparecen después del traspaso +- quienes revisan ven diffs de código sin los diffs de verdad relacionados +- las ramas desarrollan silenciosamente distintas versiones de “lo que es verdad” +- cada sesión de agente tiene que redescubrir el contexto desde cero -Para responsables técnicos, el valor es gobernanza sin infraestructura extra: las pruebas, la revisión de código y la propiedad siguen haciendo el trabajo real; Truthmark vuelve el contexto del agente duradero, inspeccionable y acotado a la rama. +Truthmark convierte ese contexto frágil en infraestructura del repositorio confirmada en Git. -## Dónde encaja Truthmark +En lugar de depender de que cada persona y cada agente recuerden el hábito correcto de documentación, Truthmark instala ese hábito en el repositorio. -Truthmark no es una suite general de productividad para IA. Ocupa una capa concreta de la pila: verdad de repositorio revisable, acotada a la rama y alineada con la implementación. +## La promesa -| Si necesitas | Mejor opción | -| ------------------------------------------------------------------------------ | -------------------------------------------- | -| Mejores resultados en una sola sesión de programación | Mejores prompts y una tarea mejor delimitada | -| Continuidad cómoda entre sesiones para un agente o una persona | Herramientas de memoria | -| Planificación spec-first para nuevas funciones | Herramientas de especificación como Spec Kit | -| Verdad del repositorio, revisable y acotada a la rama, que viaja con el código | Truthmark | +Cuando un agente cambia código funcional, el trabajo no debería terminar con solo un diff de código. -La idea no es que los prompts, la memoria o las especificaciones no sirvan. La idea es que ninguno de ellos, por sí solo, convierte la verdad del repositorio en un activo confirmado en Git, inspeccionable y capaz de sobrevivir a traspasos, revisiones y divergencias entre ramas. +El camino normal de Truthmark es: -## Contenido +```text +el agente cambia código funcional +se ejecutan pruebas relevantes +Truth Sync revisa los documentos de verdad asignados +los documentos de verdad se actualizan cuando hace falta +una persona revisa el diff de código + el diff de verdad +confirmar o traspasar +``` -- [Por qué los equipos lo adoptan](#por-qué-los-equipos-lo-adoptan) -- [Qué resuelve Truthmark](#qué-resuelve-truthmark) -- [Dónde encaja Truthmark](#dónde-encaja-truthmark) -- [Primeros pasos](#primeros-pasos) -- [Cómo se ejecuta](#cómo-se-ejecuta) -- [Qué instala](#qué-instala) -- [Comandos](#comandos) -- [Por qué existe](#por-qué-existe) -- [Estado del proyecto](#estado-del-proyecto) -- [Documentación](#documentación) -- [No objetivos](#no-objetivos) -- [Licencia](#licencia) +Ese es el valor central: **el trabajo con IA es más fácil de confiar porque el repositorio sigue siendo legible.** -## Qué resuelve Truthmark +## Dos superficies, un sistema de verdad -Truthmark convierte la verdad del repositorio en una superficie explícita de flujo de trabajo para agentes: +Truthmark no es solo una CLI. -- `.truthmark/config.yml` define el contrato de jerarquía confirmado en el repositorio. -- `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. +Tiene dos superficies distintas, y la distinción importa. -Esta es la promesa central: el contexto del agente pasa a ser estado confirmado del repositorio, no un artefacto privado de una sesión. +### 1. CLI orientada a personas -## Primeros pasos +La CLI es para mantenedores, revisores y automatización. -Instala Truthmark en el repositorio que quieras inicializar: +Úsala para configurar un repositorio, instalar o refrescar archivos de flujo de trabajo, validar artefactos de verdad y generar contexto opcional para revisión. + +```bash +truthmark config +truthmark init +truthmark check +``` + +La CLI prepara y valida el entorno del repositorio. + +No es el runtime del flujo de trabajo con IA. + +### 2. Superficies de flujo orientadas a IA + +Las superficies orientadas a IA son para agentes de programación. + +Truthmark instala skills, prompts, comandos, bloques de instrucciones administrados y superficies de subagentes nativos del host para que los agentes de IA puedan seguir flujos de verdad específicos del repositorio dentro de sus herramientas normales de programación. + +Ejemplos: + +```text +/truthmark-sync +/truthmark-document +/truthmark-structure +/truthmark-realize +/truthmark-preview +/truthmark-check +``` + +Parecen comandos porque los hosts de agentes exponen flujos mediante slash commands, prompts, skills o comandos de proyecto. + +No son comandos de shell. + +Son puntos de entrada de flujo para IA. + +La división es el producto: + +```text +las personas poseen el contrato del repositorio +Truthmark instala el contrato en el repo +los agentes operan dentro de ese contrato +las actualizaciones de verdad aparecen como diffs de Git +las personas revisan el resultado +``` + +## Inicio rápido + +### Requisitos + +- Node.js `>=20` +- npm +- un repositorio Git + +### Instalar Truthmark + +Ejecuta esto dentro del repositorio que quieres inicializar: ```bash cd /path/to/your-repo npm install -g truthmark +``` + +### Crear el contrato de verdad del repositorio + +```bash +truthmark config +``` + +Esto crea: + +```text +.truthmark/config.yml +``` + +Revisa este archivo antes de continuar. Define el contrato de jerarquía confirmado en el repositorio. + +### Instalar las superficies de flujo + +```bash +truthmark init +``` + +Esto instala o refresca: + +- archivos de rutas +- scaffolding de documentos de verdad +- bloques de instrucciones administrados +- superficies de flujo orientadas a IA para las plataformas configuradas + +### Validar la configuración + +```bash +truthmark check +``` + +Después revisa los archivos generados antes de confirmar. + +Los archivos típicos incluyen: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/repository.md +docs/templates/ +docs/truth/ +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/ +.claude/ +.opencode/ +.github/ +.gemini/ +``` + +Los archivos exactos dependen de `.truthmark/config.yml`. + +## Primer uso real + +La mayoría de los repositorios necesita una pasada de limpieza después de la inicialización. + +El scaffold predeterminado empieza con un área amplia `repository`. Los repositorios reales suelen necesitar rutas más precisas. + +Pide a tu agente que divida la ruta amplia en áreas reales de producto, servicio, dominio o propiedad: + +```text +/truthmark-structure divide el área amplia repository en auth, billing y notifications +``` + +Después usa tu agente de programación con IA normalmente. + +Cuando el agente cambia código funcional, Truth Sync actúa como guarda de cierre que revisa si los documentos de verdad asignados deben cambiar antes del traspaso. + +## Qué obtienes + +| Capacidad | Qué hace | +| --- | --- | +| Verdad nativa de Git | Mantiene la verdad del repositorio en Markdown y config confirmados. | +| Contexto acotado a la rama | La verdad se mueve con la rama en lugar de vivir en una sesión privada. | +| CLI humana | Da a mantenedores comandos de configuración, refresco, validación e inspección. | +| Flujos orientados a IA | Da a los agentes flujos nativos del host para sincronización, documentación, estructura, preview, realización y auditoría. | +| Rutas explícitas | Mapea áreas de código a documentos de verdad canónicos. | +| Traspasos revisables | Produce diffs normales de Git para código y documentos de verdad. | +| Operación local-first | No requiere servicio alojado, demonio, base de datos ni servidor MCP. | +| Límites de escritura más seguros | Separa flujos code-first, doc-first, read-only y doc-only. | +| Validación | Reporta problemas de rutas, autoridad, frontmatter, enlaces, superficies generadas, alcance de rama, frescura y cobertura. | + +## Resumen visual + +![Características de Truthmark](docs/assets/truthmark-features.png) + +**Características:** qué instala Truthmark y cómo se divide la superficie de flujo. + +![Posición de Truthmark](docs/assets/truthmark-position.png) + +**Posición:** dónde encaja Truthmark frente a prompts, memoria y flujos de especificación. + +![Flujo de sync de Truthmark](docs/assets/truthmark-syncflow.png) + +**Flujo de sync:** cómo Truth Sync cierra cambios normales de código antes del traspaso. + +## Por qué los equipos lo adoptan + +Truthmark es para equipos que ya saben que los agentes de IA pueden generar código. + +El siguiente problema es la gobernanza. + +No gobernanza como ceremonia. Gobernanza como una pregunta simple: + +> Después de este cambio asistido por IA, ¿el repositorio todavía dice la verdad? + +Truthmark ayuda a los equipos a responder con archivos confirmados, rutas explícitas y diffs revisables. + +Es útil cuando necesitas: + +- menos deriva de documentación +- mejores traspasos +- verdad de producto específica de cada rama +- contexto duradero de arquitectura y API +- propiedad explícita entre documentos y código +- límites de escritura más seguros para agentes +- contexto revisable en lugar de memoria oculta +- flujos de IA que sigan funcionando desde archivos confirmados del repo + +## Dónde encaja Truthmark + +Truthmark no reemplaza prompts, memoria, especificaciones, pruebas ni revisión de código. + +Les da a esos flujos un lugar duradero donde aterrizar en Git. + +| Necesidad | Mejor opción | +| --- | --- | +| Mejor salida de una sesión de agente | Mejor prompt | +| Continuidad personal o por sesión | Herramienta de memoria | +| Trabajo de funciones plan-first | Flujo de especificación | +| Verdad acotada a la rama que viaja con el código | Truthmark | +| Validar la corrección del comportamiento | Pruebas y revisión | +| Revisar cambios de contexto asistidos por IA | Truthmark más revisión Git | + +El carril de Truthmark es estrecho por diseño: + +```text +hacer explícita la verdad del repositorio +mapearla al código +instalar flujos de agentes alrededor de ella +mantener el resultado revisable en Git +``` + +## Cómo se ejecuta Truthmark + +Truthmark se ejecuta localmente contra el worktree Git activo. + +La CLI orientada a personas lee y escribe archivos del repositorio, y luego termina. + +Las superficies de flujo orientadas a IA son archivos confirmados que los hosts de agentes pueden cargar después. Eso permite que los agentes sigan el flujo instalado desde el estado del repositorio, sin depender de un proceso de Truthmark en segundo plano. + +Las superficies duraderas son archivos ordinarios del repo: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +docs/**/* +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/skills/ +.claude/skills/ +.opencode/skills/ +.github/prompts/ +.gemini/commands/truthmark/ +``` + +Las superficies de flujo generadas incluyen marcadores de versión de Truthmark. Después de actualizar Truthmark, vuelve a ejecutar: + +```bash +truthmark init +``` + +Luego revisa los diffs generados. + +## Plataformas de agentes compatibles + +La configuración predeterminada incluye todas las plataformas compatibles. + +Elimina de `.truthmark/config.yml` las plataformas que no uses, y luego vuelve a ejecutar: + +```bash +truthmark init +``` + +| Nombre de plataforma en config | Superficie generada | Forma de invocación | +| --- | --- | --- | +| `codex` | `.codex/skills/truthmark-*/`, `.codex/agents/` | `/truthmark-*` o `$truthmark-*` | +| `claude-code` | `.claude/skills/truthmark-*/`, `.claude/agents/`, `CLAUDE.md` | `/truthmark-*` | +| `github-copilot` | `.github/prompts/`, `.github/agents/`, `.github/copilot-instructions.md` | `/truthmark-*` en IDEs de Copilot compatibles; agentes personalizados `@truth-*` en Copilot CLI | +| `opencode` | `.opencode/skills/truthmark-*/`, `.opencode/agents/` | `/skill truthmark-*` | +| `gemini-cli` | `.gemini/commands/truthmark/`, `GEMINI.md` | `/truthmark:*` | + +Los nombres de plataforma desconocidos son errores de configuración. + +Eliminar una plataforma detiene futuros refrescos para esa plataforma. No elimina archivos generados previamente. + +## Flujos orientados a IA + +Estos flujos se instalan en hosts de programación con IA compatibles. + +Los usan agentes o hosts de agentes durante el trabajo en el repositorio. No son comandos de shell de nivel superior. + +| Flujo | Dirección | Úsalo cuando | Límite de escritura | +| --- | --- | --- | --- | +| Truth Structure | topology-first | La ruta predeterminada es demasiado amplia, la propiedad abarca varias áreas o los archivos de rutas siguen apuntando a placeholders. | Crea o repara rutas y documentos de verdad iniciales. | +| Truth Document | implementation-first | El comportamiento ya existe en código, pero faltan o son débiles los documentos de verdad canónicos. | Escribe solo documentos de verdad y rutas. No debe cambiar código funcional. | +| Truth Sync | code-first | Cambió código funcional y puede que los documentos de verdad asignados deban actualizarse antes del traspaso. | Actualiza documentos de verdad. Truth Sync no debe reescribir código funcional. | +| Truth Preview | read-only | El agente necesita previsualizar rutas probables antes de editar. | Solo lee. No autoriza escrituras. | +| Truth Realize | doc-first | Documentos de verdad de producto o arquitectura lideran y el código debe actualizarse para coincidir. | Actualiza solo código. El agente no debe editar los documentos de verdad que está realizando. | +| Truth Check | audit-first | Un revisor o agente necesita auditar la salud de la verdad del repositorio. | Audita e informa. | + +### Distinción importante + +No confundas estas dos superficies: + +| Superficie | Usada por | Ejemplo | Significado | +| --- | --- | --- | --- | +| CLI humana | personas, scripts, checks tipo CI | `truthmark check` | Validar artefactos de verdad del repositorio desde la terminal. | +| Flujo orientado a IA | agentes de programación y hosts de agentes | `/truthmark-check` | Pedir a un agente que ejecute el flujo instalado de auditoría. | + +Los nombres están relacionados a propósito, pero las superficies son distintas. + +## Cambio normal de código asistido por IA + +La mayoría de los usuarios no debería invocar Truth Sync manualmente cada vez. + +Truth Sync es la guarda de cierre instalada para cambios de código funcional. + +```text +el agente cambia código funcional +el agente ejecuta o pide pruebas relevantes +el flujo instalado detecta que cambió código funcional +Truth Sync revisa los documentos de verdad asignados +el agente actualiza documentos de verdad si hace falta +una persona revisa el diff de código + el diff de verdad +``` + +La invocación directa sigue siendo útil para depurar, forzar una sincronización temprana o hacer explícito el traspaso: + +```text +/truthmark-sync sincroniza ahora la verdad del repositorio antes del traspaso +``` + +## Comportamiento existente sin docs + +Usa Truth Document cuando la implementación ya existe pero la verdad del repositorio está incompleta. + +```text +/truthmark-document documenta el comportamiento implementado de timeout de sesión bajo docs/truth/authentication +``` + +Truth Document inspecciona implementación, pruebas, archivos de rutas y documentación existente como evidencia. + +Escribe solo documentos de verdad y rutas. + +No debe cambiar código funcional. + +## Cambios doc-first + +Usa Truth Realize cuando una decisión de producto o arquitectura empieza en documentos y el código debe actualizarse para coincidir. + +```text +/truthmark-realize realiza docs/truth/authentication/session-timeout.md como código +``` + +Truth Realize es doc-first. + +Los documentos de verdad lideran. El código sigue. + +El agente no debe editar los documentos de verdad que está realizando. + +## Preview de rutas de solo lectura + +Usa Truth Preview antes de un cambio cuando el agente necesita entender la ruta probable. + +```text +/truthmark-preview previsualiza la ruta de verdad probable para cambios en la API de billing +``` + +Truth Preview es read-only. + +Es una ayuda de selección y planificación, no una autorización de escritura ni un reemplazo de Truth Check. + +## Auditoría de verdad del repositorio + +Usa Truth Check cuando quieres un flujo de auditoría orientado a agentes. + +```text +/truthmark-check audita rutas y cobertura de verdad antes de la revisión +``` + +Usa la CLI orientada a personas cuando quieres validación en terminal: + +```bash +truthmark check +``` + +Ambas son útiles. No son la misma superficie. + +## Comandos CLI orientados a personas + +La mayoría de los mantenedores empieza con tres comandos. + +| Comando | Propósito | +| --- | --- | +| `truthmark config` | Crea `.truthmark/config.yml`. Solo escribe ese archivo, salvo que se use `--stdout`. | +| `truthmark init` | Instala o refresca superficies de flujo configuradas desde la config revisada. | +| `truthmark check` | Valida configuración, autoridad, rutas, documentos con decisiones, frontmatter, enlaces internos, alcance de rama, superficies generadas, frescura y diagnósticos de cobertura. | + +Los ayudantes opcionales de inteligencia del repositorio generan contexto derivado para revisión sobre el checkout activo. + +No son fuentes de verdad. + +| Comando | Propósito | +| --- | --- | +| `truthmark index` | Construye JSON de RepoIndex y RouteMap para el checkout activo. | +| `truthmark impact --base ` | Mapea archivos cambiados a documentos de verdad 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. Usa `--format markdown` para una versión legible por personas. | + +La salida estructurada está disponible con `--json` donde se admite. + +## Configuración + +Truthmark es config-first. + +El archivo principal de configuración es: + +```text +.truthmark/config.yml +``` + +Los repositorios nuevos deberían ejecutar: + +```bash +truthmark config +``` + +Luego revisar la config generada antes de ejecutar: + +```bash +truthmark init +``` + +Las áreas importantes de configuración incluyen: + +| Área de config | Propósito | +| --- | --- | +| `version` | Versión del contrato de configuración. | +| `platforms` | Hosts de agentes que deben recibir superficies generadas específicas de plataforma. | +| `docs.layout` | Modo actual de layout de documentación. | +| `docs.roots` | Raíces nombradas de documentación canónica. | +| `docs.routing.root_index` | Ruta del índice raíz de rutas. | +| `docs.routing.area_files_root` | Directorio para archivos de rutas secundarias delegadas. | +| `docs.routing.default_area` | Nombre base de la ruta secundaria inicial generada. | +| `docs.routing.max_delegation_depth` | Profundidad máxima actual de delegación de rutas. | +| `authority` | Documentos canónicos y globs ordenados usados como autoridad de verdad del repositorio. | +| `instruction_targets` | Archivos que reciben bloques de instrucciones administrados compartidos, como `AGENTS.md`. | +| `frontmatter.required` | Campos de metadatos que producen diagnósticos de error cuando faltan. | +| `frontmatter.recommended` | Campos de metadatos que producen diagnósticos de revisión cuando faltan. | +| `ignore` | Patrones glob excluidos de checks relevantes y lógica de rutas. | + +## Rutas de verdad del repositorio + +Truthmark mapea superficies de código a documentos de verdad. + +Los archivos principales de rutas son: + +```text +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +``` + +Una ruta le dice al agente: + +- qué superficie de código pertenece a un área +- qué documentos de verdad poseen esa área +- cuándo debe actualizarse la verdad +- qué tipo de documento de verdad participa + +El scaffold predeterminado empieza amplio. Los repositorios existentes suelen tener que dividir la ruta predeterminada en áreas reales de propiedad. + +Ejemplo: + +```text +/truthmark-structure divide el área amplia repository en frontend, backend, billing y deployment +``` + +Un buen routing da a Truth Sync destinos precisos. + +Un mal routing hace que los agentes adivinen. + +## Qué instala Truthmark + +Truthmark instala una capa compacta de verdad nativa del repositorio. + +Los archivos típicos generados y de scaffold incluyen: + +```text +.truthmark/config.yml + +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md + +docs/templates/behavior-doc.md +docs/templates/contract-doc.md +docs/templates/architecture-doc.md +docs/templates/workflow-doc.md +docs/templates/operations-doc.md +docs/templates/test-behavior-doc.md + +docs/truth/README.md +docs/truth/repository/README.md +docs/truth/repository/overview.md + +docs/standards/default-principles.md +docs/standards/documentation-governance.md + +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md + +.codex/skills/truthmark-*/ +.codex/agents/ + +.claude/skills/truthmark-*/ +.claude/agents/ + +.opencode/skills/truthmark-*/ +.opencode/agents/ + +.github/prompts/truthmark-*.prompt.md +.github/agents/ + +.gemini/commands/truthmark/*.toml +``` + +Truthmark conserva el contenido manual fuera de los bloques de instrucciones administrados. + +Las superficies de flujo generadas son administradas por Truthmark y pueden refrescarse volviendo a ejecutar: + +```bash +truthmark init +``` + +## Subagentes y checks acotados de evidencia + +Donde el host lo admite, Truthmark puede instalar agentes verificadores con alcance de proyecto y un `truth-doc-writer` con lease. + +Ayudan a mantener acotadas las tareas grandes de verdad: + +- route auditors inspeccionan la propiedad de rutas +- claim verifiers revisan si las afirmaciones de docs están respaldadas por evidencia +- doc reviewers inspeccionan la calidad de los documentos de verdad +- leased doc writers manejan shards acotados de escritura de documentos de verdad + +El flujo padre sigue siendo dueño de la interpretación final, los límites de escritura, la validación del diff y la aceptación. + +Esto es importante: los subagentes ayudan con trabajo acotado de evidencia. No reemplazan el contrato principal del flujo. + +## Bucle de revisión + +Truthmark está diseñado para revisión normal en Git. + +Un buen traspaso asistido por IA debería mostrar: + +```text +diff de código +evidencia de pruebas +diff de documentos de verdad, si hace falta +cambios de rutas, si hacen falta +informe del agente +``` + +Quien revisa debería poder responder: + +- ¿Qué código cambió? +- ¿Qué documentos de verdad poseen ese código? +- ¿Esos documentos necesitaron actualizaciones? +- Si no, ¿por qué no? +- ¿El agente permaneció dentro del límite de escritura del flujo? +- ¿Se incluye evidencia de pruebas o verificación? + +## Ejemplos + +### Inicializar un repositorio + +```bash +npm install -g truthmark truthmark config truthmark init truthmark check ``` -Si quieres probar cambios aún no publicados desde un checkout del código fuente: +### Quitar plataformas de agentes no usadas -```bash -cd /path/to/truthmark -npm install -npm run build -cd /path/to/your-repo -node /path/to/truthmark/dist/main.js config -node /path/to/truthmark/dist/main.js init -node /path/to/truthmark/dist/main.js check -``` - -Revisa `.truthmark/config.yml` antes de `init`; es el contrato de jerarquía confirmado en el repositorio. Después de `init`, revisa la superficie de flujo de trabajo generada y los archivos de rutas para que los documentos enrutados coincidan con los documentos que realmente gobiernan tu código: +Edita: ```text .truthmark/config.yml -docs/truthmark/areas.md -docs/truthmark/areas/repository.md -docs/templates/behavior-doc.md -docs/truth/README.md -docs/truth/repository/README.md -docs/truth/repository/overview.md -AGENTS.md -CLAUDE.md -GEMINI.md ``` -Las plataformas compatibles son `codex`, `opencode`, `claude-code`, `github-copilot` y `gemini-cli`. La configuración predeterminada las incluye todas; elimina de `.truthmark/config.yml` las plataformas que no uses antes de volver a ejecutar `truthmark init`. -La estructura generada por defecto usa los `README.md` de verdad como índices y empieza la verdad sobre el comportamiento actual en documentos hoja acotados, como `docs/truth/repository/overview.md`. +Luego vuelve a ejecutar: -Los repositorios existentes suelen necesitar una pasada de limpieza después de `init`: ejecuta el flujo instalado Truth Structure cuando la ruta `repository` generada sea demasiado amplia, la propiedad abarque varios productos o servicios, o los archivos de rutas sigan apuntando a documentos de marcador de posición. Truth Structure divide rutas amplias, crea o repara documentos de verdad canónica iniciales y da a Truth Sync destinos precisos antes de que empiece el trabajo de código funcional. Codex, Claude Code y los IDEs de Copilot compatibles pueden invocarlo con `/truthmark-structure`; los hosts de estilo OpenCode pueden usar `/skill truthmark-structure`. +```bash +truthmark init +truthmark check +``` -## Cómo se ejecuta - -Truthmark es más fuerte en el camino por defecto, no como un conjunto de comandos manuales. El agente que actúa y el entorno anfitrión deciden si delegan o ejecutan el flujo instalado en línea. - -### Comportamiento existente sin docs - -Usa esto cuando la implementación ya existe pero faltan o son débiles los documentos de verdad canónica: +### Dividir una ruta amplia ```text -el usuario identifica un comportamiento implementado o un endpoint de api -el usuario invoca explícitamente truth document -el agente lee implementación, pruebas, rutas y docs existentes -el agente solo escribe truth docs y rutas -revisar el diff de truth docs +/truthmark-structure divide el área amplia repository en auth, billing, notifications y deployment ``` -Truth Document es manual y con prioridad de implementación: el código sirve como evidencia, los documentos de verdad se crean o reparan, y no se debe cambiar código funcional. Codex, Claude Code y los IDEs de Copilot compatibles pueden invocarlo con `/truthmark-document`; los hosts de estilo OpenCode pueden usar `/skill truthmark-document`. +### Documentar comportamiento implementado ```text -/truthmark-document documenta el comportamiento implementado del timeout de sesión en docs/truth/authentication +/truthmark-document documenta el flujo implementado de restablecimiento de contraseña bajo docs/truth/authentication ``` -### Cambios de código normales - -La mayoría de los usuarios no debería invocar Truth Sync directamente. Lo importante es que el flujo instalado del agente trate Truth Sync como una guarda de cierre cuando cambió código funcional. El flujo normal es: +### Sincronizar después de cambios de código ```text -el agente cambia código funcional -se ejecutan las pruebas relevantes -el flujo instalado truth sync se ejecuta antes de que el agente termine -revisar el diff de truth docs si se produjo uno -confirmar o entregar el trabajo +/truthmark-sync sincroniza ahora la verdad del repositorio antes del traspaso ``` -Truth Sync es code-first: el código lidera, los documentos de verdad siguen, y Truth Sync no debe reescribir código funcional. Su tarea principal es ejecutarse mediante el flujo instalado del agente como guarda de cierre cuando cambió código funcional. La invocación directa se usa sobre todo para depurar, forzar una sincronización temprana antes de entregar el trabajo o ejecutar el flujo de forma intencional. - -Codex, Claude Code y los IDEs de Copilot compatibles pueden invocarlo con `/truthmark-sync`. Los hosts de estilo OpenCode pueden usar `/skill truthmark-sync`. +### Realizar una decisión doc-first ```text -/truthmark-sync sincroniza ahora la verdad del repositorio antes de la entrega +/truthmark-realize realiza docs/truth/billing/invoice-retry-policy.md como código ``` -### Cambios doc-first +### Auditar la salud de verdad desde la terminal -Usa este flujo cuando una decisión de producto o arquitectura empieza en la documentación: - -```text -el usuario edita truth docs -el usuario invoca explícitamente truth realize -el agente lee truth docs y el código relevante -el agente actualiza solo el código -se ejecutan las pruebas relevantes -confirmar o entregar el trabajo +```bash +truthmark check ``` -Truth Realize es manual y doc-first: los documentos de verdad lideran, el código sigue, y el agente no debe editar los documentos de verdad que está realizando. +### Generar contexto de impacto de rama -Codex, Claude Code y los IDEs de Copilot compatibles pueden invocarlo con `/truthmark-realize`. Los hosts de estilo OpenCode pueden usar `/skill truthmark-realize`. - -```text -/truthmark-realize realiza docs/truth/authentication/session-timeout.md como código +```bash +truthmark impact --base main ``` -## Qué instala +### Generar contexto de workflow -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 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. - -Los `README.md` de funciones son índices. Se espera que Truth Sync lea y actualice documentos hoja acotados para el comportamiento actual. Las superficies de flujo generadas preservan la autoridad de las reglas del repositorio mientras tratan el código de implementación y los documentos canónicos de verdad como evidencia del comportamiento actual. - -Las superficies generadas son administradas por Truthmark, incluyen un marcador de versión y pueden refrescarse con `truthmark init`. - -## Comandos - -Truthmark V1 mantiene enfocada la CLI de terminal. La mayoría de los usuarios humanos solo necesita configuración, actualización y validación: - -| 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. | - -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: - -| 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. | - -Todos los comandos CLI anteriores admiten `--json` cuando la salida estructurada es útil para automatización. - -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 +```bash +truthmark context --workflow truth-sync --base main --format markdown ``` -## Por qué existe - -La mayoría de los flujos de programación con IA optimizan la siguiente respuesta. Truthmark optimiza el siguiente traspaso. -Asume que los equipos serios necesitan: - -- verdad de producto específica de cada rama -- decisiones duraderas de arquitectura y API -- propiedad explícita entre documentación y código -- límites seguros de escritura para agentes -- diffs normales de Git que humanos puedan revisar -- Markdown legible que el equipo pueda inspeccionar sin herramientas especiales -- verdad que viaje con la rama en lugar de vivir en estado oculto de sesión -- flujos que sigan funcionando aunque el paquete no esté instalado globalmente - ## Estado del proyecto -Truthmark no es un servidor de memoria ni un servidor MCP. Es una práctica de repositorio empaquetada como un pequeño instalador CLI más superficies de flujo de trabajo nativas para agentes que convierten las reglas del flujo de IA en infraestructura del repositorio. - -V1 actualmente ofrece: +Truthmark V1 actualmente proporciona: - `truthmark config` - `truthmark init` @@ -296,39 +696,123 @@ V1 actualmente ofrece: - `truthmark index` - `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 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 +- bloques de instrucciones administrados +- superficies generadas de flujo Truth Structure +- superficies generadas de flujo Truth Document +- superficies generadas de flujo Truth Sync +- superficies generadas de flujo Truth Preview +- superficies generadas de flujo Truth Realize +- superficies generadas de flujo Truth Check +- diagnósticos de rutas, autoridad, estructura de decisiones, frontmatter, enlaces, frescura, superficies generadas y cobertura +- artefactos derivados RepoIndex, RouteMap, ImpactSet y ContextPack +- superficies específicas de host para Codex, Claude Code, GitHub Copilot, OpenCode y Gemini CLI + +## Desarrollo + +Instalar dependencias: + +```bash +npm install +``` + +Ejecutar la CLI local de desarrollo: + +```bash +npm run dev -- init +npm run dev -- check +``` + +Ejecutar el check completo del proyecto: + +```bash +npm run check +``` + +Scripts útiles: + +| Script | Propósito | +| --- | --- | +| `npm run dev` | Ejecuta el punto de entrada CLI en TypeScript con `tsx`. | +| `npm run build` | Construye el paquete. | +| `npm run lint` | Ejecuta ESLint. | +| `npm run typecheck` | Ejecuta checks de TypeScript. | +| `npm run test` | Ejecuta las pruebas. | +| `npm run check` | Ejecuta lint, typecheck, pruebas y build. | +| `npm run release:check` | Ejecuta validación orientada a release. | + +Cuando cambies Truthmark en sí, consulta [CONTRIBUTORS.md](CONTRIBUTORS.md). ## Documentación -El README raíz es para personas que evalúan y prueban el paquete. Las especificaciones funcionales y de negocio detalladas viven en `docs/`: +El README es el camino rápido para evaluación y configuración. + +El comportamiento actual detallado vive bajo `docs/`: - [Índice de documentación](docs/README.md) - [Resumen de arquitectura](docs/architecture/overview.md) - [Contratos de API y CLI](docs/truth/contracts.md) - [Comportamiento de init y scaffold](docs/truth/init-and-scaffold.md) - [Diagnósticos de check](docs/truth/check-diagnostics.md) -- [Flujos de trabajo instalados](docs/truth/workflows/overview.md) +- [Flujos instalados](docs/truth/workflows/overview.md) - [Guía para mantener la verdad del repositorio](docs/standards/maintaining-repository-truth.md) -El comportamiento actual pertenece al árbol canónico de documentación anterior. +## Límites de diseño -## No objetivos +Truthmark es intencionalmente pequeño. -Truthmark V1 no es: +No es: - un servicio alojado - un servidor MCP - una base de datos vectorial - un generador de sitios de documentación - un producto de enforcement para CI o PR -- un sustituto de pruebas, revisión de código o liderazgo técnico +- un reemplazo de pruebas, revisión de código o liderazgo técnico - un motor autónomo de reescritura de código +- un framework de entrenamiento o fine-tuning de modelos +- una capa oculta de memoria -Es una forma ligera de hacer que los agentes locales de programación con IA respeten la verdad que tu equipo guarda en Git. +Esos límites son parte del producto. + +Truthmark mantiene el flujo local, confirmado, acotado a la rama y revisable. + +## Seguridad y disciplina de revisión + +Truthmark ayuda a que el repositorio se mantenga honesto. No prueba que el código sea correcto. + +Los equipos deberían seguir: + +- ejecutando pruebas relevantes +- revisando cambios de código funcional +- revisando cambios de documentos de verdad +- manteniendo secretos fuera de la documentación +- manteniendo instrucciones específicas del repositorio fuera de bloques administrados +- revisando diffs de superficies de flujo generadas después de upgrades +- conservando propiedad humana sobre decisiones de producto y arquitectura + +Truthmark hace visible el contexto del agente. No reemplaza el juicio humano. + +## Dirección de la hoja de ruta + +La dirección futura actual enfatiza: + +- reportes de evidencia más fuertes en `truthmark check` +- ejemplos de adopción más claros +- repositorios de ejemplo que muestren ciclos reales de Truth Sync +- guías de migración para equipos que ya usan archivos de instrucciones para agentes +- pruebas de conformidad para superficies generadas de host +- pistas de verdad obsoleta conscientes de rutas +- checklists acotadas de implementación para trabajo doc-first + +El centro de gravedad se mantiene igual: + +```text +verdad del repositorio +flujos nativos para agentes +revisión en Git +contexto acotado a la rama +``` ## Licencia diff --git a/README.md b/README.md index 2294e05..efb4c76 100644 --- a/README.md +++ b/README.md @@ -1,301 +1,694 @@ # Truthmark -**Truthmark installs repository truth workflows for AI software development.** +**Your agents write code. Truthmark makes their context reviewable in Git.** English | [Deutsch](README.de.md) | [中文](README.zh.md) | [Español](README.es.md) | [Русский](README.ru.md) -Truthmark banner +![Truthmark banner](docs/assets/truthmark-banner.png) -AI coding agents already write code fast. The expensive part is keeping repository truth aligned with what changed. +AI coding agents can change a repository faster than humans can keep its context aligned. -Truthmark adds a finish-time workflow guard to that workflow. The normal path is simple: +Truthmark fixes the part that usually breaks after the code is written: the repository truth. -- agent changes functional code -- run relevant tests -- the installed Truth Sync workflow updates mapped truth docs before the agent finishes -- review the truth-doc diff if one was produced +It installs a Git-native, branch-scoped workflow layer that helps AI coding agents update the right docs, respect ownership boundaries, and leave humans with normal diffs they can review. -Most tools ask teams to adopt a habit. Truthmark turns the habit into repository workflow infrastructure. +No hosted service. -Truthmark turns an AI workflow into repo infrastructure, not personal tooling. It installs a Git-native, branch-scoped truth layer inside the repository, gives agents explicit routing and bounded workflow surfaces, and keeps that truth reviewable in Git instead of scattering it across prompt history, stale docs, or private tool memory. +No database. -That matters because the workflow lives with the branch. Once a repository is initialized, the rules, routing, and installed workflow surfaces travel in-repo, so collaboration and handoffs are less dependent on one person's machine setup. +No hidden memory layer. -For teams who already know agents can generate code, Truthmark answers the next problem: how to keep the repository itself legible, reviewable, and governable as AI-assisted work scales. +No extra server to operate. -## Visual overview +Just repository truth that moves with the branch. - - - - - - - - -
- Truthmark features -
Features
- What Truthmark installs and how the workflow surface is split. -
- Truthmark position -
Position
- Where Truthmark fits relative to prompts, memory, and spec workflows. -
- Truthmark sync flow -
Sync flow
- How Truth Sync closes out normal code changes before handoff. -
+## The problem -## Why teams adopt it +AI coding agents are good at producing code. That creates a new failure mode. -Truthmark is not trying to make agents sound smarter. It is trying to make AI-assisted repository change easier to trust. +The implementation changes, but the repository story drifts: -- Installed Truth Sync after code changes turns documentation maintenance into a workflow safeguard instead of a team habit. -- Branch-scoped truth moves with the code, so reviewers can inspect current truth in ordinary Git diffs. -- Repository-native workflow surfaces make rollout lighter and handoffs more resilient than per-user setup alone. -- Explicit routing in `docs/truthmark/areas.md` and delegated child route files gives agents ownership boundaries and safer write paths. -- Local-first operation avoids a daemon, database, remote service, or MCP dependency. -- The routing model is language-agnostic, with coverage diagnostics for common JavaScript, TypeScript, Go, Python, C#, and Java code surfaces. +- behavior lives in chat history +- architecture docs fall behind +- product decisions disappear after handoff +- reviewers see code diffs without the related truth diffs +- branches quietly develop different versions of “what is true” +- each agent session has to rediscover context from scratch -For tech leads, the value is governance without extra infrastructure: tests, code review, and ownership still do the real work; Truthmark makes the agent's context durable, inspectable, and branch-scoped. +Truthmark turns that fragile context into committed repository infrastructure. -## Where Truthmark fits +Instead of relying on every human and every agent to remember the right documentation habit, Truthmark installs the habit into the repository. -Truthmark is not a general AI productivity suite. It occupies a specific layer of the stack: branch-scoped, reviewable repository truth that stays aligned with implementation. +## The promise -| If you need | Best fit | -| --------------------------------------------------------------------- | --------------------------------------- | -| Better results from a single coding session | Better prompts and tighter task framing | -| Convenience across sessions for one agent or one operator | Memory tools | -| Spec-first planning for new features | Spec tools such as Spec Kit | -| Branch-scoped, reviewable repository truth that travels with the code | Truthmark | +When an agent changes functional code, the work should not end with only a code diff. -The point is not that prompts, memory, or specs are useless. The point is that none of them, by themselves, turn repository truth into a committed, inspectable asset that survives handoffs, review, and branch divergence. +The normal Truthmark path is: -## Table of Contents +```text +agent changes functional code +relevant tests run +Truth Sync checks mapped truth docs +truth docs update when needed +human reviews code diff + truth diff +commit or hand off +``` -- [Why teams adopt it](#why-teams-adopt-it) -- [What Truthmark solves](#what-truthmark-solves) -- [Where Truthmark fits](#where-truthmark-fits) -- [Get started](#get-started) -- [How it runs](#how-it-runs) -- [What it installs](#what-it-installs) -- [Commands](#commands) -- [Why it exists](#why-it-exists) -- [Project status](#project-status) -- [Documentation](#documentation) -- [Non-goals](#non-goals) -- [License](#license) +That is the core value: **AI work becomes easier to trust because the repository stays legible.** -## What Truthmark solves +## Two surfaces, one truth system -Truthmark turns repository truth into an explicit workflow surface for agents: +Truthmark is not just a CLI. -- `.truthmark/config.yml` defines the committed hierarchy contract. -- `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. +It has two distinct surfaces, and the distinction matters. -This is the core promise: agent context becomes committed repository state instead of a private session artifact. +### 1. Human-facing CLI -## Get started +The CLI is for maintainers, reviewers, and automation. -Install Truthmark in the repository you want to initialize: +Use it to configure a repository, install or refresh workflow files, validate truth artifacts, and generate optional review context. + +```bash +truthmark config +truthmark init +truthmark check +``` + +The CLI prepares and validates the repository environment. + +It is not the AI workflow runtime. + +### 2. AI-facing workflow surfaces + +The AI-facing surfaces are for coding agents. + +Truthmark installs host-native skills, prompts, commands, managed instruction blocks, and supported subagent surfaces so AI agents can follow repository-specific truth workflows inside their normal coding tools. + +Examples: + +```text +/truthmark-sync +/truthmark-document +/truthmark-structure +/truthmark-realize +/truthmark-preview +/truthmark-check +``` + +These look like commands because agent hosts expose workflows through slash commands, prompts, skills, or project commands. + +They are not shell commands. + +They are AI-facing workflow entrypoints. + +The split is the product: + +```text +humans own the repository contract +Truthmark installs the contract into the repo +agents operate inside that contract +truth updates appear as Git diffs +humans review the result +``` + +## Quick start + +### Requirements + +- Node.js `>=20` +- npm +- a Git repository + +### Install Truthmark + +Run this inside the repository you want to initialize: ```bash cd /path/to/your-repo npm install -g truthmark +``` + +### Create the repository truth contract + +```bash +truthmark config +``` + +This creates: + +```text +.truthmark/config.yml +``` + +Review this file before continuing. It defines the committed hierarchy contract for the repository. + +### Install the workflow surfaces + +```bash +truthmark init +``` + +This installs or refreshes: + +- route files +- truth-doc scaffolding +- managed instruction blocks +- AI-facing workflow surfaces for configured platforms + +### Validate the setup + +```bash +truthmark check +``` + +Then review the generated files before committing. + +Typical files include: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/repository.md +docs/templates/ +docs/truth/ +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/ +.claude/ +.opencode/ +.github/ +.gemini/ +``` + +The exact files depend on `.truthmark/config.yml`. + +## First real use + +Most repositories need one cleanup pass after initialization. + +The default scaffold starts with a broad `repository` area. Real repositories usually need more precise routing. + +Ask your agent to split the broad route into actual product, service, domain, or ownership areas: + +```text +/truthmark-structure split the broad repository area into auth, billing, and notifications +``` + +After that, use your AI coding agent normally. + +When the agent changes functional code, Truth Sync acts as the finish-time guard that checks whether mapped truth docs need to change before handoff. + +## What you get + +| Capability | What it does | +| --- | --- | +| Git-native truth | Keeps repository truth in committed Markdown and config. | +| Branch-scoped context | Truth moves with the branch instead of living in a private session. | +| Human CLI | Gives maintainers setup, refresh, validation, and inspection commands. | +| AI-facing workflows | Gives agents host-native workflows for sync, documentation, structure, preview, realization, and audit. | +| Explicit routing | Maps code areas to canonical truth docs. | +| Reviewable handoffs | Produces ordinary Git diffs for both code and truth docs. | +| Local-first operation | Requires no hosted service, daemon, database, or MCP server. | +| Safer write boundaries | Separates code-first, doc-first, read-only, and doc-only workflows. | +| Validation | Reports routing, authority, frontmatter, link, generated-surface, branch-scope, freshness, and coverage issues. | + +## Visual overview + +![Truthmark features](docs/assets/truthmark-features.png) + +**Features:** what Truthmark installs and how the workflow surface is split. + +![Truthmark position](docs/assets/truthmark-position.png) + +**Position:** where Truthmark fits relative to prompts, memory, and spec workflows. + +![Truthmark sync flow](docs/assets/truthmark-syncflow.png) + +**Sync flow:** how Truth Sync closes out normal code changes before handoff. + +## Why teams adopt it + +Truthmark is for teams that already know AI agents can generate code. + +The next problem is governance. + +Not governance as ceremony. Governance as a simple question: + +> After this AI-assisted change, does the repository still tell the truth? + +Truthmark helps teams answer that with committed files, explicit routing, and reviewable diffs. + +It is useful when you need: + +- less documentation drift +- better handoffs +- branch-specific product truth +- durable architecture and API context +- explicit ownership between docs and code +- safer agent write boundaries +- reviewable context instead of hidden memory +- AI workflows that still work from committed repo files + +## Where Truthmark fits + +Truthmark does not replace prompts, memory, specs, tests, or code review. + +It gives those workflows a durable place to land in Git. + +| Need | Better fit | +| --- | --- | +| Better output from one agent session | Better prompt | +| Personal or session-level continuity | Memory tool | +| Plan-first feature work | Spec workflow | +| Branch-scoped truth that travels with code | Truthmark | +| Validating behavior correctness | Tests and review | +| Reviewing AI-assisted context changes | Truthmark plus Git review | + +Truthmark’s lane is narrow by design: + +```text +make repository truth explicit +route it to code +install agent workflows around it +keep the result reviewable in Git +``` + +## How Truthmark runs + +Truthmark runs locally against the active Git worktree. + +The human-facing CLI reads and writes repository files, then exits. + +The AI-facing workflow surfaces are committed files that agent hosts can load later. That means agents can follow the installed workflow from repository state instead of depending on a background Truthmark process. + +The durable surfaces are ordinary repo files: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +docs/**/* +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/skills/ +.claude/skills/ +.opencode/skills/ +.github/prompts/ +.gemini/commands/truthmark/ +``` + +Generated workflow surfaces include Truthmark version markers. After upgrading Truthmark, rerun: + +```bash +truthmark init +``` + +Then review the generated diffs. + +## Supported agent platforms + +The default config includes every supported platform. + +Remove platforms you do not use from `.truthmark/config.yml`, then rerun: + +```bash +truthmark init +``` + +| Platform config name | Generated surface | Invocation shape | +| --- | --- | --- | +| `codex` | `.codex/skills/truthmark-*/`, `.codex/agents/` | `/truthmark-*` or `$truthmark-*` | +| `claude-code` | `.claude/skills/truthmark-*/`, `.claude/agents/`, `CLAUDE.md` | `/truthmark-*` | +| `github-copilot` | `.github/prompts/`, `.github/agents/`, `.github/copilot-instructions.md` | `/truthmark-*` in supported Copilot IDEs; `@truth-*` custom agents in Copilot CLI | +| `opencode` | `.opencode/skills/truthmark-*/`, `.opencode/agents/` | `/skill truthmark-*` | +| `gemini-cli` | `.gemini/commands/truthmark/`, `GEMINI.md` | `/truthmark:*` | + +Unknown platform names are config errors. + +Removing a platform stops future refreshes for that platform. It does not delete previously generated files. + +## AI-facing workflows + +These workflows are installed into supported AI coding hosts. + +They are used by agents or agent hosts during repository work. They are not top-level shell commands. + +| Workflow | Direction | Use it when | Write boundary | +| --- | --- | --- | --- | +| Truth Structure | topology-first | The default route is too broad, ownership spans multiple areas, or route files still point at placeholders. | Creates or repairs routing and starter truth docs. | +| Truth Document | implementation-first | Behavior already exists in code, but canonical truth docs are missing or weak. | Writes truth docs and routing only. Functional code must not change. | +| Truth Sync | code-first | Functional code changed and mapped truth docs may need to be updated before handoff. | Updates truth docs. Functional code must not be rewritten by Truth Sync. | +| Truth Preview | read-only | The agent needs to preview likely routing before edits. | Reads only. Does not authorize writes. | +| Truth Realize | doc-first | Product or architecture truth docs lead and code should be updated to match. | Updates code only. The agent must not edit the truth docs it is realizing. | +| Truth Check | audit-first | A reviewer or agent needs to audit repository truth health. | Audits and reports. | + +### Important distinction + +Do not confuse these two surfaces: + +| Surface | Used by | Example | Meaning | +| --- | --- | --- | --- | +| Human CLI | humans, scripts, CI-like checks | `truthmark check` | Validate repository truth artifacts from the terminal. | +| AI-facing workflow | coding agents and agent hosts | `/truthmark-check` | Ask an agent to run the installed audit workflow. | + +The names are intentionally related, but the surfaces are different. + +## Normal AI-assisted code change + +Most users should not need to invoke Truth Sync manually every time. + +Truth Sync is the installed finish-time guard for functional code changes. + +```text +agent changes functional code +agent runs or asks for relevant tests +installed workflow detects that functional code changed +Truth Sync checks mapped truth docs +agent updates truth docs if needed +human reviews code diff + truth diff +``` + +Direct invocation is still useful for troubleshooting, forcing an early sync, or making the handoff explicit: + +```text +/truthmark-sync sync the repository truth now before handoff +``` + +## Existing behavior without docs + +Use Truth Document when the implementation already exists but the repository truth is incomplete. + +```text +/truthmark-document document the implemented session timeout behavior under docs/truth/authentication +``` + +Truth Document inspects implementation, tests, route files, and existing docs as evidence. + +It writes truth docs and routing only. + +It must not change functional code. + +## Doc-first changes + +Use Truth Realize when a product or architecture decision starts in docs and code should be updated to match. + +```text +/truthmark-realize realize docs/truth/authentication/session-timeout.md into code +``` + +Truth Realize is doc-first. + +The truth docs lead. The code follows. + +The agent must not edit the truth docs it is realizing. + +## Read-only routing preview + +Use Truth Preview before a change when the agent needs to understand likely routing. + +```text +/truthmark-preview preview the likely truth routing for changes to the billing API +``` + +Truth Preview is read-only. + +It is a selector and planning aid, not write authorization and not a replacement for Truth Check. + +## Repository truth audit + +Use Truth Check when you want an agent-facing audit workflow. + +```text +/truthmark-check audit routing and truth coverage before review +``` + +Use the human-facing CLI when you want terminal validation: + +```bash +truthmark check +``` + +Both are useful. They are not the same surface. + +## Human-facing CLI commands + +Most maintainers start with three commands. + +| Command | Purpose | +| --- | --- | +| `truthmark config` | Create `.truthmark/config.yml`. Writes only that file unless `--stdout` is used. | +| `truthmark init` | Install or refresh configured workflow surfaces from the reviewed config. | +| `truthmark check` | Validate configuration, authority, routing, decision-bearing docs, frontmatter, internal links, branch scope, generated surfaces, freshness, and coverage diagnostics. | + +Optional repository-intelligence helpers generate derived review context for the active checkout. + +They are not sources of truth. + +| Command | Purpose | +| --- | --- | +| `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. Use `--format markdown` for a human-readable pack. | + +Structured output is available with `--json` where supported. + +## Configuration + +Truthmark is config-first. + +The main config file is: + +```text +.truthmark/config.yml +``` + +New repositories should run: + +```bash +truthmark config +``` + +Then review the generated config before running: + +```bash +truthmark init +``` + +Important config areas include: + +| Config area | Purpose | +| --- | --- | +| `version` | Config contract version. | +| `platforms` | Agent hosts that should receive platform-specific generated surfaces. | +| `docs.layout` | Current docs layout mode. | +| `docs.roots` | Named canonical documentation roots. | +| `docs.routing.root_index` | Root route index path. | +| `docs.routing.area_files_root` | Directory for delegated child route files. | +| `docs.routing.default_area` | Initial scaffolded child route basename. | +| `docs.routing.max_delegation_depth` | Current maximum route delegation depth. | +| `authority` | Ordered canonical docs and globs used as repository truth authority. | +| `instruction_targets` | Files that receive shared managed instruction blocks, such as `AGENTS.md`. | +| `frontmatter.required` | Metadata fields that produce error diagnostics when missing. | +| `frontmatter.recommended` | Metadata fields that produce review diagnostics when missing. | +| `ignore` | Glob patterns excluded from relevant checks and routing logic. | + +## Repository truth routing + +Truthmark maps code surfaces to truth docs. + +The main routing files are: + +```text +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +``` + +A route tells the agent: + +- which code surface belongs to an area +- which truth docs own that area +- when truth should be updated +- what kind of truth doc is involved + +The default scaffold starts broad. Existing repositories should usually split the default route into real ownership areas. + +Example: + +```text +/truthmark-structure split the broad repository area into frontend, backend, billing, and deployment +``` + +Good routing gives Truth Sync precise destinations. + +Bad routing makes agents guess. + +## What Truthmark installs + +Truthmark installs a compact repository-native truth layer. + +Typical scaffolded and generated files include: + +```text +.truthmark/config.yml + +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md + +docs/templates/behavior-doc.md +docs/templates/contract-doc.md +docs/templates/architecture-doc.md +docs/templates/workflow-doc.md +docs/templates/operations-doc.md +docs/templates/test-behavior-doc.md + +docs/truth/README.md +docs/truth/repository/README.md +docs/truth/repository/overview.md + +docs/standards/default-principles.md +docs/standards/documentation-governance.md + +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md + +.codex/skills/truthmark-*/ +.codex/agents/ + +.claude/skills/truthmark-*/ +.claude/agents/ + +.opencode/skills/truthmark-*/ +.opencode/agents/ + +.github/prompts/truthmark-*.prompt.md +.github/agents/ + +.gemini/commands/truthmark/*.toml +``` + +Truthmark preserves manual content outside managed instruction blocks. + +Generated workflow surfaces are managed by Truthmark and may be refreshed by rerunning: + +```bash +truthmark init +``` + +## Subagents and bounded evidence checks + +Where supported by the host, Truthmark can install project-scoped verifier agents and a leased `truth-doc-writer`. + +These help keep large truth tasks bounded: + +- route auditors inspect route ownership +- claim verifiers check whether doc claims are supported by evidence +- doc reviewers inspect truth-doc quality +- leased doc writers handle bounded truth-doc writing shards + +The parent workflow still owns final interpretation, write boundaries, diff validation, and acceptance. + +This is important: subagents help with bounded evidence work. They do not replace the main workflow contract. + +## Review loop + +Truthmark is designed for ordinary Git review. + +A good AI-assisted handoff should show: + +```text +code diff +test evidence +truth-doc diff, if needed +routing changes, if needed +agent report +``` + +The reviewer should be able to answer: + +- What code changed? +- Which truth docs own that code? +- Did those docs need updates? +- If not, why not? +- Did the agent stay inside the workflow write boundary? +- Are tests or verification evidence included? + +## Examples + +### Initialize a repository + +```bash +npm install -g truthmark truthmark config truthmark init truthmark check ``` -If you want to try unreleased changes from a source checkout instead: +### Remove unused agent platforms -```bash -cd /path/to/truthmark -npm install -npm run build - -cd /path/to/your-repo -node /path/to/truthmark/dist/main.js config -node /path/to/truthmark/dist/main.js init -node /path/to/truthmark/dist/main.js check -``` - -Review `.truthmark/config.yml` before `init`; it is the committed hierarchy contract. After `init`, review the generated workflow surface and route files so the routed docs match the docs that actually own your code: +Edit: ```text .truthmark/config.yml -docs/truthmark/areas.md -docs/truthmark/areas/repository.md -docs/templates/behavior-doc.md -docs/truth/README.md -docs/truth/repository/README.md -docs/truth/repository/overview.md -AGENTS.md -CLAUDE.md -GEMINI.md ``` -Supported platforms are `codex`, `opencode`, `claude-code`, `github-copilot`, and `gemini-cli`. The default config includes all of them; remove platforms you do not use from `.truthmark/config.yml` before rerunning `truthmark init`. +Then rerun: -The default scaffold keeps truth `README.md` files as indexes and starts current behavior truth in bounded leaf docs such as `docs/truth/repository/overview.md`. +```bash +truthmark init +truthmark check +``` -Existing repositories usually need one cleanup pass after `init`: run the installed Truth Structure workflow when the generated `repository` route is too broad, ownership spans multiple products or services, or route files still point at placeholder docs. Truth Structure splits broad routing, creates or repairs starter canonical truth docs, and gives Truth Sync precise destinations before functional-code work begins. Codex, Claude Code, and supported Copilot IDEs can invoke it with `/truthmark-structure`; OpenCode-style hosts can invoke `/skill truthmark-structure`. +### Split broad routing ```text -/truthmark-structure split the broad repository area into auth, billing, and notifications +/truthmark-structure split the broad repository area into auth, billing, notifications, and deployment ``` -## How it runs - -Truthmark is strongest on the default path, not as a pile of manual commands. The acting agent and host environment decide whether to delegate or run the installed workflow inline. - -### Existing behavior without docs - -Use this when implementation already exists but the canonical truth docs are missing or weak: +### Document implemented behavior ```text -user identifies an implemented behavior or API endpoint -user explicitly invokes Truth Document -agent reads implementation, tests, routing, and existing docs -agent writes truth docs and routing only -review the truth-doc diff +/truthmark-document document the implemented password reset flow under docs/truth/authentication ``` -Truth Document is manual and implementation-first: code is inspected as evidence, truth docs are created or repaired, and functional code must not be changed. Codex, Claude Code, and supported Copilot IDEs can invoke it with `/truthmark-document`. OpenCode-style hosts can invoke `/skill truthmark-document`. - -```text -/truthmark-document document the implemented session timeout behavior under docs/truth/authentication -``` - -### Normal code changes - -Most users should not need to invoke Truth Sync directly. The important behavior is that the installed agent workflow treats Truth Sync as a finish-time guard when functional code changed. The normal path is: - -```text -agent changes functional code -run relevant tests -the installed Truth Sync workflow runs before the agent finishes -review the truth-doc diff if one was produced -commit or hand off the work -``` - -Truth Sync is code-first: code leads, truth docs follow, and Truth Sync must not rewrite functional code. Its main job is to run through the installed agent workflow as a finish-time guard when functional code changed. Direct invocation is mainly for troubleshooting, forcing an early sync before handoff, or running the workflow intentionally. - -Codex, Claude Code, and supported Copilot IDEs can invoke it with `/truthmark-sync`. OpenCode-style hosts can invoke `/skill truthmark-sync`. +### Sync after code changes ```text /truthmark-sync sync the repository truth now before handoff ``` -### Doc-first changes - -Use this when a product or architecture decision starts in docs: +### Realize a doc-first decision ```text -user edits truth docs -user explicitly invokes Truth Realize -agent reads truth docs and relevant code -agent updates code only -run relevant tests -commit or hand off the work +/truthmark-realize realize docs/truth/billing/invoice-retry-policy.md into code ``` -Truth Realize is manual and doc-first: truth docs lead, code follows, and the agent must not edit the truth docs it is realizing. +### Audit truth health from the terminal -Codex, Claude Code, and supported Copilot IDEs can invoke it with `/truthmark-realize`. OpenCode-style hosts can invoke `/skill truthmark-realize`. - -```text -/truthmark-realize realize docs/truth/authentication/session-timeout.md into code +```bash +truthmark check ``` -## What it installs +### Generate branch-impact context -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 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. - -Truth `README.md` files are indexes. Truth Sync is expected to read and update bounded leaf docs for current behavior. Generated workflow surfaces preserve repository-rule authority while treating implementation code and canonical truth docs as evidence for current behavior. - -Generated surfaces are managed by Truthmark, include a version marker, and may be refreshed by `truthmark init`. - -## Commands - -Truthmark V1 keeps the terminal CLI focused. Most human users only need setup, refresh, and validation: - -| 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. | - -The remaining CLI commands are optional repository-intelligence helpers. They generate derived review context for the active checkout; they are not sources of truth: - -| 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. | - -All CLI commands above support `--json` where structured output is useful for automation. - -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 +```bash +truthmark impact --base main ``` -## Why it exists +### Generate workflow context -Most AI coding workflows optimize for the next answer. Truthmark optimizes for the next handoff. - -It assumes serious teams need: - -- branch-specific product truth -- durable architecture and API decisions -- explicit ownership between docs and code -- safe write boundaries for agents -- ordinary Git diffs that humans can review -- readable Markdown that teammates can inspect without special tooling -- truth that travels with the branch instead of living in hidden session state -- workflows that still work when the package is not installed globally - -Truthmark is not a memory server and it is not an MCP server. It is a repository practice packaged as a small CLI installer plus agent-native workflow surfaces that turn AI workflow rules into repo infrastructure. +```bash +truthmark context --workflow truth-sync --base main --format markdown +``` ## Project status -V1 currently provides: +Truthmark V1 currently provides: - `truthmark config` - `truthmark init` @@ -303,15 +696,58 @@ V1 currently provides: - `truthmark index` - `truthmark impact` - `truthmark context` -- managed `AGENTS.md` workflow instructions -- 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 +- managed instruction blocks +- generated Truth Structure workflow surfaces +- generated Truth Document workflow surfaces +- generated Truth Sync workflow surfaces +- generated Truth Preview workflow surfaces +- generated Truth Realize workflow surfaces +- generated Truth Check workflow surfaces +- route, authority, decision-structure, frontmatter, link, freshness, generated-surface, and coverage diagnostics +- derived RepoIndex, RouteMap, ImpactSet, and ContextPack artifacts +- host-specific surfaces for Codex, Claude Code, GitHub Copilot, OpenCode, and Gemini CLI + +## Development + +Install dependencies: + +```bash +npm install +``` + +Run the local development CLI: + +```bash +npm run dev -- init +npm run dev -- check +``` + +Run the full project check: + +```bash +npm run check +``` + +Useful scripts: + +| Script | Purpose | +| --- | --- | +| `npm run dev` | Run the TypeScript CLI entry point with `tsx`. | +| `npm run build` | Build the package. | +| `npm run lint` | Run ESLint. | +| `npm run typecheck` | Run TypeScript checks. | +| `npm run test` | Run tests. | +| `npm run check` | Run lint, typecheck, tests, and build. | +| `npm run release:check` | Run release-oriented validation. | + +When changing Truthmark itself, see [CONTRIBUTORS.md](CONTRIBUTORS.md). ## Documentation -The root README is for people evaluating and trying the package. Detailed functional and business specifications live under `docs/`: +The README is the fast path for evaluation and setup. + +Detailed current behavior lives under `docs/`: - [Docs index](docs/README.md) - [Architecture overview](docs/architecture/overview.md) @@ -321,11 +757,11 @@ The root README is for people evaluating and trying the package. Detailed functi - [Installed workflows](docs/truth/workflows/overview.md) - [Repository truth maintenance guide](docs/standards/maintaining-repository-truth.md) -Current behavior belongs in the canonical docs tree above. +## Design boundaries -## Non-goals +Truthmark is intentionally small. -Truthmark V1 is not: +It is not: - a hosted service - an MCP server @@ -334,8 +770,49 @@ Truthmark V1 is not: - a CI or PR enforcement product - a replacement for tests, code review, or technical leadership - an autonomous code rewrite engine +- a model-training or fine-tuning framework +- a hidden memory layer -It is a lightweight way to make local AI coding agents respect the truth your team keeps in Git. +Those boundaries are part of the product. + +Truthmark keeps the workflow local, committed, branch-scoped, and reviewable. + +## Safety and review discipline + +Truthmark helps the repository stay honest. It does not prove the code is correct. + +Teams should still: + +- run relevant tests +- review functional code changes +- review truth-doc changes +- keep secrets out of docs +- keep repository-specific instructions outside managed blocks +- review generated workflow-surface diffs after upgrades +- keep human ownership over product and architecture decisions + +Truthmark makes agent context visible. It does not replace human judgment. + +## Roadmap direction + +The current future direction emphasizes: + +- stronger `truthmark check` evidence reporting +- clearer adoption examples +- example repositories showing real Truth Sync cycles +- migration guides for teams already using agent instruction files +- conformance tests for generated host surfaces +- route-aware stale-truth hints +- bounded implementation checklists for doc-first work + +The center of gravity stays the same: + +```text +repository truth +agent-native workflows +Git review +branch-scoped context +``` ## License diff --git a/README.ru.md b/README.ru.md index 6c49828..a38a56e 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,294 +1,694 @@ # Truthmark -**Truthmark устанавливает рабочие процессы истины репозитория для разработки ПО с ИИ.** +**Ваши агенты пишут код. Truthmark делает их контекст проверяемым в Git.** [English](README.md) | [Deutsch](README.de.md) | [中文](README.zh.md) | [Español](README.es.md) | Русский -Баннер Truthmark +![Баннер Truthmark](docs/assets/truthmark-banner.png) -ИИ-агенты уже быстро пишут код. Дорогая часть — удерживать истину репозитория в соответствии с тем, что реально изменилось. +ИИ-агенты для разработки могут менять репозиторий быстрее, чем люди успевают выравнивать его контекст. -Truthmark добавляет в этот процесс финальную защиту на уровне рабочего процесса. Обычный путь прост: +Truthmark чинит ту часть, которая обычно ломается после написания кода: истину репозитория. -- агент меняет функциональный код -- запускаются релевантные тесты -- установленный рабочий процесс Truth Sync обновляет связанные документы истины до завершения работы агента -- если был создан diff документов истины, его проверяют +Он устанавливает Git-native, ограниченный веткой слой рабочего процесса, который помогает ИИ-агентам обновлять правильные документы, соблюдать границы владения и оставлять людям обычные diff для ревью. -Большинство инструментов просит команды выработать привычку. Truthmark превращает эту привычку в инфраструктуру рабочего процесса репозитория. +Без размещенного сервиса. -Truthmark превращает ИИ-процесс в инфраструктуру репозитория, а не в персональный инструмент. Он устанавливает Git-native слой истины внутри репозитория, задает агентам явную маршрутизацию и ограниченные рабочие поверхности и сохраняет эту истину проверяемой в Git вместо того, чтобы разносить ее по истории промптов, устаревшей документации или приватному состоянию инструментов. +Без базы данных. -Это важно, потому что процесс живет вместе с веткой. После инициализации репозитория правила, маршрутизация и установленные рабочие поверхности путешествуют внутри репозитория, поэтому совместная работа и передача задач меньше зависят от локальной настройки одного человека. +Без скрытого слоя памяти. -Для команд, которые уже знают, что агенты умеют генерировать код, Truthmark решает следующую проблему: как сделать так, чтобы сам репозиторий оставался понятным, проверяемым и управляемым по мере роста ИИ-ассистированной разработки. +Без дополнительного сервера в эксплуатации. -## Визуальный обзор +Только истина репозитория, которая движется вместе с веткой. - - - - - - - - -
- Возможности Truthmark -
Возможности
- Что устанавливает Truthmark и как устроена рабочая поверхность. -
- Позиционирование Truthmark -
Позиционирование
- Где Truthmark находится относительно промптов, памяти и spec-first процессов. -
- Поток sync в Truthmark -
Поток sync
- Как Truth Sync закрывает обычные изменения кода перед передачей работы. -
+## Проблема -## Почему команды выбирают Truthmark +ИИ-агенты для разработки хорошо создают код. Это порождает новый режим отказа. -Truthmark не пытается сделать так, чтобы агенты звучали умнее. Он пытается сделать изменения в репозитории, выполненные с помощью ИИ, более надежными. +Реализация меняется, но история репозитория начинает расходиться: -- Установленный Truth Sync после изменений кода превращает поддержку документации в защиту рабочего процесса, а не в командную привычку. -- Истина, ограниченная веткой, движется вместе с кодом, поэтому ревьюеры могут проверять актуальную истину в обычных Git diff. -- Рабочие поверхности, встроенные в репозиторий, упрощают внедрение и делают передачу работы устойчивее, чем одна лишь персональная настройка. -- Явная маршрутизация в `docs/truthmark/areas.md` и делегированных дочерних файлах маршрутов дает агентам границы ответственности и более безопасные пути записи. -- Local-first работа избавляет от зависимости на демон, базу данных, удаленный сервис или MCP. -- Модель маршрутизации не зависит от языка и дает диагностику покрытия для распространенных поверхностей кода JavaScript, TypeScript, Go, Python, C# и Java. +- поведение живет в истории чата +- архитектурные документы отстают +- продуктовые решения исчезают после передачи работы +- ревьюеры видят diff кода без связанных diff истины +- ветки незаметно развивают разные версии того, «что является правдой» +- каждой сессии агента приходится заново открывать контекст -Для технических лидеров ценность в управлении без дополнительной инфраструктуры: тесты, ревью кода и владение зонами ответственности по-прежнему делают основную работу; Truthmark делает контекст агента долговечным, проверяемым и ограниченным веткой. +Truthmark превращает этот хрупкий контекст в зафиксированную инфраструктуру репозитория. -## Где уместен Truthmark +Вместо надежды на то, что каждый человек и каждый агент вспомнят правильную привычку документирования, Truthmark устанавливает эту привычку в репозиторий. -Truthmark не является универсальным набором ИИ-инструментов для продуктивности. Он занимает конкретный слой в стеке: проверяемая истина репозитория, ограниченная веткой и выровненная с реализацией. +## Обещание -| Если вам нужно | Лучший выбор | -| ------------------------------------------------------------------------------------------------ | ---------------------------------------------- | -| Лучшие результаты в одной сессии разработки | Более точные промпты и лучше очерченная задача | -| Удобная преемственность между сессиями для одного агента или оператора | Инструменты памяти | -| Spec-first планирование новых функций | Инструменты спецификаций, например Spec Kit | -| Проверяемая истина репозитория с областью действия в пределах ветки, которая идет вместе с кодом | Truthmark | +Когда агент меняет функциональный код, работа не должна заканчиваться только diff кода. -Смысл не в том, что промпты, память или спецификации бесполезны. Смысл в том, что ни один из этих подходов сам по себе не превращает истину репозитория в зафиксированный в Git, проверяемый актив, который переживает передачу работы, ревью и расхождение веток. +Обычный путь Truthmark: -## Содержание +```text +агент меняет функциональный код +запускаются релевантные тесты +Truth Sync проверяет сопоставленные документы истины +документы истины обновляются при необходимости +человек проверяет diff кода + diff истины +коммит или передача работы +``` -- [Почему команды выбирают Truthmark](#почему-команды-выбирают-truthmark) -- [Что решает Truthmark](#что-решает-truthmark) -- [Где уместен Truthmark](#где-уместен-truthmark) -- [Начало работы](#начало-работы) -- [Как он работает](#как-он-работает) -- [Что он устанавливает](#что-он-устанавливает) -- [Команды](#команды) -- [Зачем он существует](#зачем-он-существует) -- [Статус проекта](#статус-проекта) -- [Документация](#документация) -- [Не-цели](#не-цели) -- [Лицензия](#лицензия) +Главная ценность такова: **ИИ-работе легче доверять, потому что репозиторий остается понятным.** -## Что решает Truthmark +## Две поверхности, одна система истины -Truthmark превращает истину репозитория в явную рабочую поверхность для агентов: +Truthmark — это не только CLI. -- `.truthmark/config.yml` определяет зафиксированный контракт иерархии. -- `docs/truthmark/areas.md` и делегированные дочерние файлы маршрутов сопоставляют области кода с документами, которые за них отвечают. -- Truth Document создает или исправляет канонические документы истины для уже реализованного поведения, когда изменение кода не нужно. -- Truth Sync поддерживает синхронизацию сопоставленных документов истины при функциональных изменениях. -- Truth Preview предварительно показывает вероятную маршрутизацию рабочего процесса до правок, не авторизуя записи. -- Truth Realize дает изменениям, начинающимся с документации, ограниченный путь для обновления кода. -- `truthmark check` валидирует получившиеся артефакты истины. -- Вся модель остается local-first и Git-native. +У него две разные поверхности, и это различие важно. -Главное обещание такое: контекст агента становится зафиксированным состоянием репозитория, а не приватным артефактом отдельной сессии. +### 1. CLI для людей -## Начало работы +CLI предназначен для мейнтейнеров, ревьюеров и автоматизации. -Установите Truthmark в репозитории, который хотите инициализировать: +Используйте его, чтобы настроить репозиторий, установить или обновить файлы рабочих процессов, проверить артефакты истины и создать дополнительный контекст для ревью. + +```bash +truthmark config +truthmark init +truthmark check +``` + +CLI подготавливает и валидирует среду репозитория. + +Он не является runtime для ИИ-рабочего процесса. + +### 2. Поверхности рабочих процессов для ИИ + +Поверхности для ИИ предназначены для coding agents. + +Truthmark устанавливает host-native skills, prompts, commands, управляемые блоки инструкций и поддерживаемые поверхности subagents, чтобы ИИ-агенты могли следовать специфичным для репозитория truth-workflows внутри своих обычных инструментов разработки. + +Примеры: + +```text +/truthmark-sync +/truthmark-document +/truthmark-structure +/truthmark-realize +/truthmark-preview +/truthmark-check +``` + +Они выглядят как команды, потому что agent hosts раскрывают workflows через slash commands, prompts, skills или project commands. + +Это не shell-команды. + +Это точки входа workflow для ИИ. + +Разделение и есть продукт: + +```text +люди владеют контрактом репозитория +Truthmark устанавливает контракт в repo +агенты работают внутри этого контракта +обновления истины появляются как Git diff +люди проверяют результат +``` + +## Быстрый старт + +### Требования + +- Node.js `>=20` +- npm +- Git-репозиторий + +### Установить Truthmark + +Выполните это внутри репозитория, который хотите инициализировать: ```bash cd /path/to/your-repo npm install -g truthmark +``` + +### Создать контракт истины репозитория + +```bash +truthmark config +``` + +Это создает: + +```text +.truthmark/config.yml +``` + +Проверьте этот файл перед продолжением. Он определяет зафиксированный контракт иерархии для репозитория. + +### Установить поверхности рабочих процессов + +```bash +truthmark init +``` + +Это устанавливает или обновляет: + +- файлы маршрутов +- scaffolding документов истины +- управляемые блоки инструкций +- поверхности рабочих процессов для ИИ для настроенных платформ + +### Проверить настройку + +```bash +truthmark check +``` + +Затем проверьте сгенерированные файлы перед коммитом. + +Типичные файлы: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/repository.md +docs/templates/ +docs/truth/ +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/ +.claude/ +.opencode/ +.github/ +.gemini/ +``` + +Точный набор файлов зависит от `.truthmark/config.yml`. + +## Первое реальное использование + +Большинству репозиториев после инициализации нужен один этап очистки. + +Стандартный scaffold начинается с широкого area `repository`. Реальным репозиториям обычно нужна более точная маршрутизация. + +Попросите агента разделить широкий маршрут на реальные области продукта, сервиса, домена или владения: + +```text +/truthmark-structure раздели широкий repository area на auth, billing и notifications +``` + +После этого используйте своего ИИ-агента для разработки как обычно. + +Когда агент меняет функциональный код, Truth Sync действует как финальная защита, которая перед передачей работы проверяет, должны ли измениться сопоставленные документы истины. + +## Что вы получаете + +| Возможность | Что она делает | +| --- | --- | +| Git-native истина | Хранит истину репозитория в зафиксированных Markdown и config. | +| Контекст в пределах ветки | Истина движется с веткой вместо жизни в приватной сессии. | +| CLI для людей | Дает мейнтейнерам команды настройки, обновления, валидации и инспекции. | +| Workflows для ИИ | Дает агентам host-native workflows для sync, documentation, structure, preview, realization и audit. | +| Явная маршрутизация | Сопоставляет области кода с каноническими документами истины. | +| Проверяемые передачи работы | Создает обычные Git diff для кода и документов истины. | +| Local-first работа | Не требует размещенного сервиса, daemon, базы данных или MCP-сервера. | +| Более безопасные границы записи | Разделяет code-first, doc-first, read-only и doc-only workflows. | +| Валидация | Сообщает о проблемах маршрутизации, authority, frontmatter, ссылок, generated surfaces, branch scope, freshness и coverage. | + +## Визуальный обзор + +![Возможности Truthmark](docs/assets/truthmark-features.png) + +**Возможности:** что устанавливает Truthmark и как разделена поверхность workflow. + +![Позиционирование Truthmark](docs/assets/truthmark-position.png) + +**Позиция:** где Truthmark находится относительно prompts, memory и spec workflows. + +![Поток sync Truthmark](docs/assets/truthmark-syncflow.png) + +**Поток sync:** как Truth Sync закрывает обычные изменения кода перед передачей. + +## Почему команды выбирают его + +Truthmark предназначен для команд, которые уже знают, что ИИ-агенты могут генерировать код. + +Следующая проблема — governance. + +Не governance как церемония. Governance как простой вопрос: + +> После этого ИИ-ассистированного изменения репозиторий все еще говорит правду? + +Truthmark помогает командам отвечать на это с помощью зафиксированных файлов, явной маршрутизации и проверяемых diff. + +Он полезен, когда нужны: + +- меньший дрейф документации +- лучшие передачи работы +- продуктовая истина, специфичная для ветки +- долговечный архитектурный и API-контекст +- явное владение между документацией и кодом +- более безопасные границы записи для агентов +- проверяемый контекст вместо скрытой памяти +- ИИ-workflows, которые продолжают работать из зафиксированных файлов repo + +## Где уместен Truthmark + +Truthmark не заменяет prompts, memory, specs, tests или code review. + +Он дает этим workflows долговечное место в Git. + +| Потребность | Лучше подходит | +| --- | --- | +| Лучший результат из одной сессии агента | Лучший prompt | +| Персональная или сессионная преемственность | Memory tool | +| Работа над функцией plan-first | Spec workflow | +| Истина в пределах ветки, которая путешествует с кодом | Truthmark | +| Проверка корректности поведения | Tests and review | +| Ревью контекстных изменений, выполненных с ИИ | Truthmark plus Git review | + +Область Truthmark намеренно узкая: + +```text +сделать истину репозитория явной +связать ее с кодом +установить вокруг нее workflows агентов +сохранить результат проверяемым в Git +``` + +## Как работает Truthmark + +Truthmark работает локально с активным Git worktree. + +CLI для людей читает и записывает файлы репозитория, а затем завершается. + +Поверхности рабочих процессов для ИИ — это зафиксированные файлы, которые agent hosts могут загрузить позже. Поэтому агенты могут следовать установленному workflow из состояния репозитория, не завися от фонового процесса Truthmark. + +Долговечные поверхности — обычные файлы repo: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +docs/**/* +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/skills/ +.claude/skills/ +.opencode/skills/ +.github/prompts/ +.gemini/commands/truthmark/ +``` + +Сгенерированные поверхности workflow включают маркеры версии Truthmark. После обновления Truthmark снова выполните: + +```bash +truthmark init +``` + +Затем проверьте сгенерированные diff. + +## Поддерживаемые платформы агентов + +Конфигурация по умолчанию включает все поддерживаемые платформы. + +Удалите платформы, которыми не пользуетесь, из `.truthmark/config.yml`, затем снова выполните: + +```bash +truthmark init +``` + +| Имя платформы в config | Сгенерированная поверхность | Форма вызова | +| --- | --- | --- | +| `codex` | `.codex/skills/truthmark-*/`, `.codex/agents/` | `/truthmark-*` или `$truthmark-*` | +| `claude-code` | `.claude/skills/truthmark-*/`, `.claude/agents/`, `CLAUDE.md` | `/truthmark-*` | +| `github-copilot` | `.github/prompts/`, `.github/agents/`, `.github/copilot-instructions.md` | `/truthmark-*` в поддерживаемых Copilot IDE; custom agents `@truth-*` в Copilot CLI | +| `opencode` | `.opencode/skills/truthmark-*/`, `.opencode/agents/` | `/skill truthmark-*` | +| `gemini-cli` | `.gemini/commands/truthmark/`, `GEMINI.md` | `/truthmark:*` | + +Неизвестные имена платформ являются ошибками config. + +Удаление платформы останавливает будущие обновления для нее. Оно не удаляет ранее сгенерированные файлы. + +## Workflows для ИИ + +Эти workflows устанавливаются в поддерживаемые ИИ coding hosts. + +Они используются агентами или agent hosts во время работы с репозиторием. Это не shell-команды верхнего уровня. + +| Workflow | Направление | Когда использовать | Граница записи | +| --- | --- | --- | --- | +| Truth Structure | topology-first | Стандартный маршрут слишком широкий, владение охватывает несколько областей или файлы маршрутов все еще указывают на placeholders. | Создает или чинит routing и стартовые документы истины. | +| Truth Document | implementation-first | Поведение уже есть в коде, но канонические документы истины отсутствуют или слабы. | Пишет только документы истины и routing. Функциональный код менять нельзя. | +| Truth Sync | code-first | Функциональный код изменился, и сопоставленные документы истины могут потребовать обновления перед передачей. | Обновляет документы истины. Truth Sync не должен переписывать функциональный код. | +| Truth Preview | read-only | Агенту нужно предварительно понять вероятный routing перед правками. | Только чтение. Не авторизует записи. | +| Truth Realize | doc-first | Продуктовые или архитектурные документы истины ведут, и код нужно обновить под них. | Обновляет только код. Агент не должен редактировать документы истины, которые реализует. | +| Truth Check | audit-first | Ревьюеру или агенту нужно проверить здоровье истины репозитория. | Аудитирует и сообщает. | + +### Важное различие + +Не путайте эти две поверхности: + +| Поверхность | Используется | Пример | Значение | +| --- | --- | --- | --- | +| CLI для людей | людьми, скриптами, CI-подобными проверками | `truthmark check` | Проверить артефакты истины репозитория из терминала. | +| Workflow для ИИ | coding agents и agent hosts | `/truthmark-check` | Попросить агента выполнить установленный audit workflow. | + +Имена намеренно похожи, но поверхности разные. + +## Обычное изменение кода с помощью ИИ + +Большинству пользователей не нужно вручную вызывать Truth Sync каждый раз. + +Truth Sync — установленная финальная защита для изменений функционального кода. + +```text +агент меняет функциональный код +агент запускает или запрашивает релевантные тесты +установленный workflow обнаруживает, что функциональный код изменился +Truth Sync проверяет сопоставленные документы истины +агент обновляет документы истины при необходимости +человек проверяет diff кода + diff истины +``` + +Прямой вызов все равно полезен для отладки, принудительной ранней синхронизации или явной передачи работы: + +```text +/truthmark-sync синхронизируй истину репозитория прямо сейчас перед передачей +``` + +## Существующее поведение без docs + +Используйте Truth Document, когда реализация уже существует, но истина репозитория неполна. + +```text +/truthmark-document задокументируй реализованное поведение session timeout в docs/truth/authentication +``` + +Truth Document проверяет реализацию, тесты, файлы маршрутов и существующие docs как evidence. + +Он пишет только документы истины и routing. + +Он не должен менять функциональный код. + +## Doc-first изменения + +Используйте Truth Realize, когда продуктовое или архитектурное решение начинается в docs и код нужно обновить под него. + +```text +/truthmark-realize реализуй docs/truth/authentication/session-timeout.md в коде +``` + +Truth Realize работает doc-first. + +Документы истины ведут. Код следует. + +Агент не должен редактировать документы истины, которые реализует. + +## Read-only preview маршрутизации + +Используйте Truth Preview перед изменением, когда агенту нужно понять вероятную маршрутизацию. + +```text +/truthmark-preview покажи вероятный truth routing для изменений billing API +``` + +Truth Preview работает read-only. + +Это средство выбора и планирования, а не авторизация записи и не замена Truth Check. + +## Аудит истины репозитория + +Используйте Truth Check, когда нужен audit workflow для агента. + +```text +/truthmark-check проверь routing и truth coverage перед review +``` + +Используйте CLI для людей, когда нужна terminal validation: + +```bash +truthmark check +``` + +Оба варианта полезны. Это не одна и та же поверхность. + +## CLI-команды для людей + +Большинство мейнтейнеров начинают с трех команд. + +| Команда | Назначение | +| --- | --- | +| `truthmark config` | Создает `.truthmark/config.yml`. Пишет только этот файл, если не используется `--stdout`. | +| `truthmark init` | Устанавливает или обновляет настроенные поверхности workflow из проверенной config. | +| `truthmark check` | Валидирует config, authority, routing, документы с decisions, frontmatter, внутренние ссылки, branch scope, generated surfaces, freshness и coverage diagnostics. | + +Необязательные helpers repository-intelligence создают производный review context для активного checkout. + +Они не являются источниками истины. + +| Команда | Назначение | +| --- | --- | +| `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` для человекочитаемой версии. | + +Структурированный вывод доступен с `--json` там, где поддерживается. + +## Конфигурация + +Truthmark работает config-first. + +Главный config-файл: + +```text +.truthmark/config.yml +``` + +Новые репозитории должны выполнить: + +```bash +truthmark config +``` + +Затем проверить сгенерированную config перед запуском: + +```bash +truthmark init +``` + +Важные области config: + +| Область config | Назначение | +| --- | --- | +| `version` | Версия контракта config. | +| `platforms` | Agent hosts, которые должны получить сгенерированные поверхности для платформы. | +| `docs.layout` | Текущий режим layout документации. | +| `docs.roots` | Именованные корни канонической документации. | +| `docs.routing.root_index` | Путь к корневому индексу маршрутов. | +| `docs.routing.area_files_root` | Директория для делегированных дочерних файлов маршрутов. | +| `docs.routing.default_area` | Базовое имя начального scaffolded дочернего маршрута. | +| `docs.routing.max_delegation_depth` | Текущая максимальная глубина делегирования routing. | +| `authority` | Упорядоченные канонические docs и globs, используемые как authority истины репозитория. | +| `instruction_targets` | Файлы, которые получают общие управляемые блоки инструкций, например `AGENTS.md`. | +| `frontmatter.required` | Поля metadata, которые создают error diagnostics при отсутствии. | +| `frontmatter.recommended` | Поля metadata, которые создают review diagnostics при отсутствии. | +| `ignore` | Glob-паттерны, исключенные из релевантных checks и routing logic. | + +## Маршрутизация истины репозитория + +Truthmark сопоставляет code surfaces с документами истины. + +Основные файлы маршрутизации: + +```text +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +``` + +Маршрут сообщает агенту: + +- какая code surface принадлежит области +- какие документы истины владеют этой областью +- когда истину нужно обновлять +- какой тип документа истины участвует + +Стандартный scaffold начинается широко. Существующие репозитории обычно должны разделить стандартный маршрут на реальные области владения. + +Пример: + +```text +/truthmark-structure раздели широкий repository area на frontend, backend, billing и deployment +``` + +Хороший routing дает Truth Sync точные цели. + +Плохой routing заставляет агентов гадать. + +## Что устанавливает Truthmark + +Truthmark устанавливает компактный, встроенный в репозиторий слой истины. + +Типичные scaffolded и generated файлы: + +```text +.truthmark/config.yml + +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md + +docs/templates/behavior-doc.md +docs/templates/contract-doc.md +docs/templates/architecture-doc.md +docs/templates/workflow-doc.md +docs/templates/operations-doc.md +docs/templates/test-behavior-doc.md + +docs/truth/README.md +docs/truth/repository/README.md +docs/truth/repository/overview.md + +docs/standards/default-principles.md +docs/standards/documentation-governance.md + +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md + +.codex/skills/truthmark-*/ +.codex/agents/ + +.claude/skills/truthmark-*/ +.claude/agents/ + +.opencode/skills/truthmark-*/ +.opencode/agents/ + +.github/prompts/truthmark-*.prompt.md +.github/agents/ + +.gemini/commands/truthmark/*.toml +``` + +Truthmark сохраняет ручной контент вне управляемых блоков инструкций. + +Сгенерированные поверхности workflow управляются Truthmark и могут обновляться повторным запуском: + +```bash +truthmark init +``` + +## Subagents и ограниченные проверки evidence + +Там, где host поддерживает это, Truthmark может устанавливать project-scoped verifier agents и leased `truth-doc-writer`. + +Они помогают держать большие truth-задачи ограниченными: + +- route auditors проверяют владение маршрутами +- claim verifiers проверяют, поддержаны ли claims документов evidence +- doc reviewers проверяют качество truth docs +- leased doc writers обрабатывают ограниченные shards записи truth docs + +Родительский workflow все еще владеет финальной интерпретацией, границами записи, проверкой diff и приемкой. + +Это важно: subagents помогают с ограниченной evidence work. Они не заменяют основной контракт workflow. + +## Цикл ревью + +Truthmark спроектирован для обычного Git review. + +Хорошая ИИ-ассистированная передача работы должна показывать: + +```text +diff кода +test evidence +diff truth docs, если нужен +изменения routing, если нужны +отчет агента +``` + +Ревьюер должен уметь ответить: + +- Какой код изменился? +- Какие документы истины владеют этим кодом? +- Нужно ли было обновлять эти документы? +- Если нет, почему? +- Остался ли агент внутри границы записи workflow? +- Приложена ли evidence тестов или проверки? + +## Примеры + +### Инициализировать репозиторий + +```bash +npm install -g truthmark truthmark config truthmark init truthmark check ``` -Если вы хотите попробовать еще не выпущенные изменения из исходного checkout: +### Удалить неиспользуемые платформы агентов -```bash -cd /path/to/truthmark -npm install -npm run build -cd /path/to/your-repo -node /path/to/truthmark/dist/main.js config -node /path/to/truthmark/dist/main.js init -node /path/to/truthmark/dist/main.js check -``` - -Проверьте `.truthmark/config.yml` перед `init`; это зафиксированный в Git контракт иерархии. После `init` проверьте сгенерированную рабочую поверхность и файлы маршрутов, чтобы маршрутизированная документация действительно совпадала с документами, которые отвечают за ваш код: +Отредактируйте: ```text .truthmark/config.yml -docs/truthmark/areas.md -docs/truthmark/areas/repository.md -docs/templates/behavior-doc.md -docs/truth/README.md -docs/truth/repository/README.md -docs/truth/repository/overview.md -AGENTS.md -CLAUDE.md -GEMINI.md ``` -Поддерживаемые платформы: `codex`, `opencode`, `claude-code`, `github-copilot` и `gemini-cli`. Конфигурация по умолчанию включает их все; удалите из `.truthmark/config.yml` платформы, которыми не пользуетесь, перед повторным запуском `truthmark init`. -Стандартная шаблонная структура использует truth-`README.md` как индексы и начинает описывать истину текущего поведения в ограниченных листовых документах, например `docs/truth/repository/overview.md`. +Затем снова выполните: -Существующим репозиториям обычно нужен один этап очистки после `init`: запустите установленный рабочий процесс Truth Structure, если созданный маршрут `repository` слишком широкий, владение охватывает несколько продуктов или сервисов, либо файлы маршрутов все еще указывают на документы-заглушки. Truth Structure разделяет широкие маршруты, создает или исправляет начальные канонические документы истины и дает Truth Sync точные цели до начала работы с функциональным кодом. Codex, Claude Code и поддерживаемые IDE Copilot могут вызвать его через `/truthmark-structure`; хосты в стиле OpenCode могут использовать `/skill truthmark-structure`. +```bash +truthmark init +truthmark check +``` -## Как он работает - -Сильная сторона Truthmark — путь по умолчанию, а не набор ручных команд. Действующий агент и среда хоста сами решают, делегировать работу или выполнить установленный процесс на месте. - -### Существующее поведение без документации - -Используйте это, когда реализация уже есть, но канонические документы истины отсутствуют или слабы: +### Разделить широкий routing ```text -пользователь определяет реализованное поведение или api-эндпоинт -пользователь явно вызывает truth document -агент читает реализацию, тесты, маршрутизацию и существующие docs -агент пишет только truth docs и маршрутизацию -проверить diff truth docs +/truthmark-structure раздели широкий repository area на auth, billing, notifications и deployment ``` -Truth Document — это ручной процесс с приоритетом реализации: код служит доказательством, документы истины создаются или исправляются, и функциональный код менять нельзя. Codex, Claude Code и поддерживаемые IDE Copilot могут вызывать его через `/truthmark-document`; хосты в стиле OpenCode могут использовать `/skill truthmark-document`. +### Документировать реализованное поведение ```text -/truthmark-document документирует реализованное поведение session timeout в docs/truth/authentication +/truthmark-document задокументируй реализованный password reset flow в docs/truth/authentication ``` -### Обычные изменения кода - -Большинству пользователей не нужно напрямую вызывать Truth Sync. Главное, что установленный агентский процесс рассматривает Truth Sync как финальную защиту, когда менялся функциональный код. Нормальный путь выглядит так: - -```text -агент изменяет функциональный код -запускаются релевантные тесты -установленный truth sync workflow запускается до завершения агента -если был создан diff truth docs, он проверяется -работа коммитится или передается дальше -``` - -Truth Sync работает по принципу code-first: сначала идет код, затем документы истины, и Truth Sync не должен переписывать функциональный код. Его основная задача - выполняться через установленный агентский процесс как финальная защита, когда менялся функциональный код. Прямой вызов нужен в основном для отладки, ранней синхронизации перед передачей работы или намеренного запуска рабочего процесса. - -Codex, Claude Code и поддерживаемые IDE Copilot могут вызывать его через `/truthmark-sync`. Хосты в стиле OpenCode могут использовать `/skill truthmark-sync`. +### Синхронизировать после изменений кода ```text /truthmark-sync синхронизируй истину репозитория прямо сейчас перед передачей ``` -### Doc-first изменения - -Используйте этот путь, когда продуктовое или архитектурное решение начинается в документации: +### Реализовать doc-first решение ```text -пользователь редактирует truth docs -пользователь явно вызывает truth realize -агент читает truth docs и связанный код -агент обновляет только код -запускаются релевантные тесты -работа коммитится или передается дальше +/truthmark-realize реализуй docs/truth/billing/invoice-retry-policy.md в коде ``` -Truth Realize — это ручной doc-first процесс: документы истины идут первыми, код следует за ними, и агент не должен редактировать документы истины, которые он реализует. +### Проверить здоровье истины из терминала -Codex, Claude Code и поддерживаемые IDE Copilot могут вызывать его через `/truthmark-realize`. Хосты в стиле OpenCode могут использовать `/skill truthmark-realize`. - -```text -/truthmark-realize реализуй docs/truth/authentication/session-timeout.md в код +```bash +truthmark check ``` -## Что он устанавливает +### Создать branch-impact context -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 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 аудитирует здоровье истины репозитория. - -`README.md` функциональных разделов это индексы. Ожидается, что Truth Sync будет читать и обновлять ограниченные листовые документы для текущего поведения. Сгенерированные рабочие поверхности сохраняют приоритет правил репозитория, рассматривая код реализации и канонические документы истины как свидетельства текущего поведения. - -Сгенерированные поверхности управляются Truthmark, содержат маркер версии и могут обновляться через `truthmark init`. - -## Команды - -Truthmark V1 держит терминальный CLI сфокусированным. Большинству людей нужны только настройка, обновление и проверка: - -| CLI-команда для людей | Назначение | -| --------------------- | ---------- | -| `truthmark config` | Создает `.truthmark/config.yml`; пишет только этот файл, если не используется `--stdout`. | -| `truthmark init` | Устанавливает или обновляет локальные файлы рабочих процессов из проверенной конфигурации. | -| `truthmark check` | Валидирует конфигурацию, полномочия, маршрутизацию, документы с решениями, frontmatter, внутренние ссылки, область действия ветки и диагностику покрытия. | - -Остальные CLI-команды - необязательные помощники репозиторной аналитики. Они создают производный контекст для ревью активного checkout; они не являются источниками истины: - -| Необязательная 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` рендерит его в читаемый человеком вид. | - -Все CLI-команды выше поддерживают `--json`, когда структурированный вывод полезен для автоматизации. - -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 +```bash +truthmark impact --base main ``` -## Зачем он существует +### Создать workflow context -Большинство ИИ-процессов для разработки оптимизируют следующий ответ. Truthmark оптимизирует следующую передачу работы. -Он исходит из того, что серьезным командам нужны: - -- продуктовая истина, специфичная для ветки -- долговечные архитектурные и API-решения -- явная ответственность между документацией и кодом -- безопасные границы записи для агентов -- обычные Git diff, которые могут проверить люди -- читаемый Markdown, который команда может просматривать без специальных инструментов -- истина, которая путешествует вместе с веткой, а не живет в скрытом состоянии сессии -- рабочие процессы, которые продолжают работать, даже если пакет не установлен глобально +```bash +truthmark context --workflow truth-sync --base main --format markdown +``` ## Статус проекта -Truthmark не является сервером памяти и не является MCP-сервером. Это репозиторная практика, упакованная как небольшой CLI-установщик и родные для агентов рабочие поверхности, которые превращают правила ИИ-процесса в инфраструктуру репозитория. - -V1 сейчас предоставляет: +Truthmark V1 сейчас предоставляет: - `truthmark config` - `truthmark init` @@ -296,39 +696,123 @@ V1 сейчас предоставляет: - `truthmark index` - `truthmark impact` - `truthmark context` -- управляемые инструкции рабочих процессов в `AGENTS.md` -- сгенерированные skill-поверхности Truth Structure, Truth Document, Truth Sync, Truth Preview, Truth Realize и Truth Check для настроенных агентских хостов -- метаданные области ветки -- диагностика конфигурации, полномочий, маршрутизации, структуры решений, frontmatter, ссылок и полиглотного покрытия -- производные артефакты RepoIndex, RouteMap, ImpactSet и ContextPack для более быстрой локальной проверки, когда CLI доступен +- branch-scope metadata +- управляемые блоки инструкций +- сгенерированные поверхности workflow Truth Structure +- сгенерированные поверхности workflow Truth Document +- сгенерированные поверхности workflow Truth Sync +- сгенерированные поверхности workflow Truth Preview +- сгенерированные поверхности workflow Truth Realize +- сгенерированные поверхности workflow Truth Check +- diagnostics для route, authority, decision-structure, frontmatter, links, freshness, generated-surface и coverage +- производные артефакты RepoIndex, RouteMap, ImpactSet и ContextPack +- host-specific поверхности для Codex, Claude Code, GitHub Copilot, OpenCode и Gemini CLI + +## Разработка + +Установить зависимости: + +```bash +npm install +``` + +Запустить локальную development CLI: + +```bash +npm run dev -- init +npm run dev -- check +``` + +Запустить полный project check: + +```bash +npm run check +``` + +Полезные scripts: + +| Script | Назначение | +| --- | --- | +| `npm run dev` | Запускает TypeScript CLI entry point через `tsx`. | +| `npm run build` | Собирает package. | +| `npm run lint` | Запускает ESLint. | +| `npm run typecheck` | Запускает TypeScript checks. | +| `npm run test` | Запускает tests. | +| `npm run check` | Запускает lint, typecheck, tests и build. | +| `npm run release:check` | Запускает release-oriented validation. | + +Когда меняете сам Truthmark, смотрите [CONTRIBUTORS.md](CONTRIBUTORS.md). ## Документация -Корневой README предназначен для людей, которые оценивают и пробуют пакет. Подробные функциональные и бизнес-спецификации находятся в `docs/`: +README — быстрый путь для оценки и настройки. + +Подробное текущее поведение живет в `docs/`: - [Индекс документации](docs/README.md) - [Обзор архитектуры](docs/architecture/overview.md) - [Контракты API и CLI](docs/truth/contracts.md) - [Поведение init и scaffold](docs/truth/init-and-scaffold.md) - [Диагностика check](docs/truth/check-diagnostics.md) -- [Установленные workflow](docs/truth/workflows/overview.md) +- [Установленные workflows](docs/truth/workflows/overview.md) - [Руководство по поддержанию истины репозитория](docs/standards/maintaining-repository-truth.md) -Текущее поведение должно жить в каноническом дереве документации выше. +## Границы дизайна -## Не-цели +Truthmark намеренно небольшой. -Truthmark V1 не является: +Он не является: - размещенным сервисом - MCP-сервером - векторной базой данных - генератором сайтов документации -- продуктом принудительного контроля для CI или PR -- заменой тестов, code review или технического лидерства -- автономным движком для переписывания кода +- CI- или PR-enforcement продуктом +- заменой tests, code review или technical leadership +- автономным движком переписывания кода +- framework для model training или fine-tuning +- скрытым слоем памяти -Это легкий способ заставить локальных ИИ-агентов для разработки уважать истину, которую ваша команда хранит в Git. +Эти границы — часть продукта. + +Truthmark держит workflow локальным, зафиксированным, ограниченным веткой и проверяемым. + +## Безопасность и дисциплина ревью + +Truthmark помогает репозиторию оставаться честным. Он не доказывает, что код корректен. + +Команды все равно должны: + +- запускать релевантные тесты +- проверять изменения функционального кода +- проверять изменения документов истины +- держать secrets вне документации +- держать специфичные для репозитория инструкции вне managed blocks +- проверять diff сгенерированных workflow surfaces после upgrades +- сохранять человеческое владение продуктовыми и архитектурными решениями + +Truthmark делает контекст агента видимым. Он не заменяет человеческое суждение. + +## Направление roadmap + +Текущее будущее направление делает акцент на: + +- более сильной evidence reporting в `truthmark check` +- более ясных примерах adoption +- примерных репозиториях, показывающих реальные циклы Truth Sync +- migration guides для команд, уже использующих agent instruction files +- conformance tests для generated host surfaces +- route-aware подсказках о stale truth +- ограниченных implementation checklists для doc-first work + +Центр тяжести остается прежним: + +```text +истина репозитория +agent-native workflows +Git review +контекст в пределах ветки +``` ## Лицензия diff --git a/README.zh.md b/README.zh.md index a3f1aae..13748b1 100644 --- a/README.zh.md +++ b/README.zh.md @@ -1,294 +1,694 @@ # Truthmark -**Truthmark 为 AI 软件开发安装仓库事实工作流。** +**你的代理会写代码。Truthmark 让它们的上下文在 Git 中可审查。** [English](README.md) | [Deutsch](README.de.md) | 中文 | [Español](README.es.md) | [Русский](README.ru.md) -Truthmark 横幅 +![Truthmark 横幅](docs/assets/truthmark-banner.png) -AI 编码代理已经能很快写代码了。真正昂贵的是让仓库事实和实际变更保持一致。 +AI 编码代理改变仓库的速度,可能比人类对齐上下文的速度更快。 -Truthmark 在这个流程里加入了一个收尾阶段的工作流保护。正常路径很简单: +Truthmark 修复代码写完后通常会坏掉的那一部分:仓库事实。 -- 代理修改功能代码 -- 运行相关测试 -- 代理结束前,已安装的 Truth Sync 工作流更新已映射的事实文档 -- 如果产生了事实文档 diff,就审查它 +它安装一个 Git 原生、按分支生效的工作流层,帮助 AI 编码代理更新正确的文档、尊重所有权边界,并把人类可以审查的普通 diff 留下来。 -大多数工具要求团队养成一种习惯。Truthmark 把这个习惯变成仓库工作流基础设施。 +没有托管服务。 -Truthmark 把 AI 工作流变成仓库基础设施,而不是个人工具配置。它把一个 Git 原生、按分支生效的事实层安装到仓库里,为代理提供明确的路由和有边界的工作流载体,并让这些事实继续以 Git diff 的形式可审查,而不是散落在提示历史、陈旧文档或私有工具状态里。 +没有数据库。 -这之所以重要,是因为工作流跟着分支一起存在。仓库一旦初始化,规则、路由和已安装的工作流载体就会随仓库一起移动,协作和交接也就不再过度依赖某个人的本地配置。 +没有隐藏记忆层。 -对于已经知道代理能生成代码的团队,Truthmark 解决的是下一个问题:当 AI 辅助开发规模化时,怎样让仓库本身继续保持清晰、可审查、可治理。 +没有需要运行的额外服务器。 -## 可视化概览 +只有随分支移动的仓库事实。 - - - - - - - - -
- Truthmark 功能 -
功能
- Truthmark 安装了什么,以及工作流载体如何拆分。 -
- Truthmark 定位 -
定位
- Truthmark 相对提示词、记忆和规格工作流所处的位置。 -
- Truthmark 同步流程 -
同步流程
- Truth Sync 如何在交接前收束普通代码变更。 -
+## 问题 -## 为什么团队会采用它 +AI 编码代理很擅长产出代码。这会制造一种新的失效模式。 -Truthmark 不是为了让代理显得更聪明,而是为了让 AI 辅助的仓库变更更值得信任。 +实现改变了,但仓库叙事开始漂移: -- 代码变更后的已安装 Truth Sync 工作流,把文档维护从团队习惯变成工作流保护。 -- 按分支生效的事实会跟着代码一起走,所以审查者可以在普通 Git diff 里检查当前事实。 -- 仓库原生的工作流载体让推广更轻、交接更稳,不再只依赖个人本地配置。 -- `docs/truthmark/areas.md` 和委托的子路由文件里的显式路由,为代理提供更清晰的所有权边界和更安全的写入路径。 -- 本地优先的运行方式避免了守护进程、数据库、远程服务或 MCP 依赖。 -- 路由模型与语言无关,并为常见的 JavaScript、TypeScript、Go、Python、C# 和 Java 代码表面提供覆盖率诊断。 +- 行为存在于聊天历史里 +- 架构文档落后 +- 产品决策在交接后消失 +- 审查者看到代码 diff,却看不到相关的事实 diff +- 分支悄悄发展出不同版本的“什么是真的” +- 每个代理会话都必须从头重新发现上下文 -对技术负责人来说,它的价值是没有额外基础设施负担的治理:测试、代码审查和所有权仍然承担真正的工作;Truthmark 让代理上下文变得持久、可检查,并且限定在当前分支内。 +Truthmark 把这种脆弱上下文变成已提交的仓库基础设施。 -## Truthmark 适合放在哪里 +它不是依赖每个人和每个代理都记住正确的文档习惯,而是把这个习惯安装进仓库。 -Truthmark 不是一套通用 AI 生产力套件。它占据的是工具栈里的一个特定层级:随实现保持一致、按分支生效、可审查的仓库事实。 +## 承诺 -| 如果你需要 | 最合适的选择 | -| -------------------------------------------- | ------------------------------ | -| 单次编码会话获得更好结果 | 更好的提示词和更清晰的任务边界 | -| 一个代理或操作者跨会话延续便利性 | 记忆类工具 | -| 为新功能做规格优先的规划 | Spec Kit 等规格工具 | -| 随代码一起流转、可审查、按分支生效的仓库事实 | Truthmark | +当代理修改功能代码时,工作不应该只以代码 diff 结束。 -重点不是提示词、记忆或规格没有用。重点是,它们单独都不能把仓库事实变成一个已提交、可检查,并且能经受交接、审查和分支分叉的资产。 +Truthmark 的正常路径是: -## 目录 +```text +代理修改功能代码 +运行相关测试 +Truth Sync 检查已映射的事实文档 +需要时更新事实文档 +人类审查代码 diff + 事实 diff +提交或交接 +``` -- [为什么团队会采用它](#为什么团队会采用它) -- [Truthmark 解决什么问题](#truthmark-解决什么问题) -- [Truthmark 适合放在哪里](#truthmark-适合放在哪里) -- [快速开始](#快速开始) -- [它如何运行](#它如何运行) -- [它会安装什么](#它会安装什么) -- [命令](#命令) -- [它为什么存在](#它为什么存在) -- [项目状态](#项目状态) -- [文档](#文档) -- [非目标](#非目标) -- [许可证](#许可证) +核心价值是:**AI 工作更容易被信任,因为仓库仍然清晰可读。** -## Truthmark 解决什么问题 +## 两个表面,一个事实系统 -Truthmark 把仓库事实变成代理可见的显式工作流载体: +Truthmark 不只是一个 CLI。 -- `.truthmark/config.yml` 定义已提交的层级契约。 -- `docs/truthmark/areas.md` 和委托的子路由文件把代码区域映射到负责它们的文档。 -- Truth Document 在无需修改代码时,为已实现行为生成或修复规范事实文档。 -- Truth Sync 在功能性变更发生时,让已映射的事实文档保持同步。 -- Truth Preview 在编辑前预览可能的工作流路由,但不授权写入。 -- Truth Realize 为文档优先的变更提供有边界的代码更新路径。 -- `truthmark check` 验证最终形成的事实产物。 -- 整个模型保持本地优先和 Git 原生。 +它有两个不同表面,这个区别很重要。 -核心承诺很简单:代理上下文会成为已提交的仓库状态,而不是私有会话产物。 +### 1. 面向人的 CLI + +CLI 面向维护者、审查者和自动化。 + +用它来配置仓库、安装或刷新工作流文件、验证事实产物,并生成可选的审查上下文。 + +```bash +truthmark config +truthmark init +truthmark check +``` + +CLI 会准备并验证仓库环境。 + +它不是 AI 工作流运行时。 + +### 2. 面向 AI 的工作流表面 + +面向 AI 的表面是给编码代理使用的。 + +Truthmark 会安装宿主原生的技能、提示、命令、受管说明块和受支持的子代理表面,让 AI 代理能在正常编码工具中遵循仓库专属的事实工作流。 + +示例: + +```text +/truthmark-sync +/truthmark-document +/truthmark-structure +/truthmark-realize +/truthmark-preview +/truthmark-check +``` + +它们看起来像命令,是因为代理宿主通过 slash commands、prompts、skills 或 project commands 暴露工作流。 + +它们不是 shell 命令。 + +它们是面向 AI 的工作流入口。 + +这种拆分就是产品: + +```text +人类拥有仓库契约 +Truthmark 把契约安装进 repo +代理在契约内工作 +事实更新以 Git diff 出现 +人类审查结果 +``` ## 快速开始 -在你想初始化的仓库中安装 Truthmark: +### 要求 + +- Node.js `>=20` +- npm +- Git 仓库 + +### 安装 Truthmark + +在你想初始化的仓库中运行: ```bash cd /path/to/your-repo npm install -g truthmark +``` + +### 创建仓库事实契约 + +```bash +truthmark config +``` + +这会创建: + +```text +.truthmark/config.yml +``` + +继续之前先审查这个文件。它定义仓库中已提交的层级契约。 + +### 安装工作流表面 + +```bash +truthmark init +``` + +这会安装或刷新: + +- 路由文件 +- 事实文档脚手架 +- 受管说明块 +- 已配置平台的面向 AI 工作流表面 + +### 验证设置 + +```bash +truthmark check +``` + +然后在提交前审查生成的文件。 + +典型文件包括: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/repository.md +docs/templates/ +docs/truth/ +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/ +.claude/ +.opencode/ +.github/ +.gemini/ +``` + +确切文件取决于 `.truthmark/config.yml`。 + +## 第一次真实使用 + +大多数仓库在初始化后需要一次清理。 + +默认脚手架从一个宽泛的 `repository` 区域开始。真实仓库通常需要更精确的路由。 + +让你的代理把宽泛路由拆成真实的产品、服务、领域或所有权区域: + +```text +/truthmark-structure 将宽泛的 repository 区域拆成 auth、billing 和 notifications +``` + +之后就正常使用你的 AI 编码代理。 + +当代理修改功能代码时,Truth Sync 会作为收尾保护,在交接前检查已映射的事实文档是否需要改变。 + +## 你会得到什么 + +| 能力 | 作用 | +| --- | --- | +| Git 原生事实 | 将仓库事实保存在已提交的 Markdown 和配置中。 | +| 按分支生效的上下文 | 事实随分支移动,而不是存在于私有会话中。 | +| 面向人的 CLI | 为维护者提供设置、刷新、验证和检查命令。 | +| 面向 AI 的工作流 | 为代理提供宿主原生的同步、文档、结构、预览、实现和审计工作流。 | +| 显式路由 | 将代码区域映射到规范事实文档。 | +| 可审查交接 | 为代码和事实文档都产生普通 Git diff。 | +| 本地优先运行 | 不需要托管服务、守护进程、数据库或 MCP 服务器。 | +| 更安全的写入边界 | 区分 code-first、doc-first、read-only 和 doc-only 工作流。 | +| 验证 | 报告路由、权限边界、frontmatter、链接、生成表面、分支范围、freshness 和覆盖率问题。 | + +## 视觉概览 + +![Truthmark 功能](docs/assets/truthmark-features.png) + +**功能:** Truthmark 会安装什么,以及工作流表面如何拆分。 + +![Truthmark 定位](docs/assets/truthmark-position.png) + +**定位:** Truthmark 相对提示词、记忆和规格工作流所处的位置。 + +![Truthmark 同步流程](docs/assets/truthmark-syncflow.png) + +**同步流程:** Truth Sync 如何在交接前收束普通代码变更。 + +## 为什么团队会采用它 + +Truthmark 面向已经知道 AI 代理能生成代码的团队。 + +下一个问题是治理。 + +不是仪式化治理。治理就是一个简单问题: + +> 这次 AI 辅助变更之后,仓库还在讲真话吗? + +Truthmark 通过已提交文件、显式路由和可审查 diff 帮助团队回答这个问题。 + +当你需要这些东西时,它会很有用: + +- 更少的文档漂移 +- 更好的交接 +- 按分支生效的产品事实 +- 持久的架构和 API 上下文 +- 文档与代码之间的明确所有权 +- 更安全的代理写入边界 +- 可审查上下文,而不是隐藏记忆 +- 仍然能从已提交 repo 文件运行的 AI 工作流 + +## Truthmark 适合放在哪里 + +Truthmark 不替代提示词、记忆、规格、测试或代码审查。 + +它给这些工作流一个可以落在 Git 里的持久位置。 + +| 需求 | 更合适的选择 | +| --- | --- | +| 单次代理会话获得更好输出 | 更好的提示词 | +| 个人或会话级连续性 | 记忆工具 | +| plan-first 的功能工作 | 规格工作流 | +| 随代码移动、按分支生效的事实 | Truthmark | +| 验证行为正确性 | 测试和审查 | +| 审查 AI 辅助的上下文变更 | Truthmark 加 Git 审查 | + +Truthmark 的范围故意很窄: + +```text +让仓库事实显式化 +把它路由到代码 +围绕它安装代理工作流 +让结果在 Git 中可审查 +``` + +## Truthmark 如何运行 + +Truthmark 在本地针对当前 Git worktree 运行。 + +面向人的 CLI 读取并写入仓库文件,然后退出。 + +面向 AI 的工作流表面是已提交文件,代理宿主之后可以加载它们。这意味着代理可以从仓库状态遵循已安装工作流,而不依赖后台 Truthmark 进程。 + +持久表面都是普通 repo 文件: + +```text +.truthmark/config.yml +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +docs/**/* +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md +.codex/skills/ +.claude/skills/ +.opencode/skills/ +.github/prompts/ +.gemini/commands/truthmark/ +``` + +生成的工作流表面包含 Truthmark 版本标记。升级 Truthmark 后,重新运行: + +```bash +truthmark init +``` + +然后审查生成的 diff。 + +## 支持的代理平台 + +默认配置包含所有受支持平台。 + +从 `.truthmark/config.yml` 中移除你不使用的平台,然后重新运行: + +```bash +truthmark init +``` + +| 平台配置名 | 生成表面 | 调用形式 | +| --- | --- | --- | +| `codex` | `.codex/skills/truthmark-*/`, `.codex/agents/` | `/truthmark-*` 或 `$truthmark-*` | +| `claude-code` | `.claude/skills/truthmark-*/`, `.claude/agents/`, `CLAUDE.md` | `/truthmark-*` | +| `github-copilot` | `.github/prompts/`, `.github/agents/`, `.github/copilot-instructions.md` | 支持的 Copilot IDE 中使用 `/truthmark-*`;Copilot CLI 中使用 `@truth-*` custom agents | +| `opencode` | `.opencode/skills/truthmark-*/`, `.opencode/agents/` | `/skill truthmark-*` | +| `gemini-cli` | `.gemini/commands/truthmark/`, `GEMINI.md` | `/truthmark:*` | + +未知平台名是配置错误。 + +移除一个平台会停止该平台未来的刷新。它不会删除此前生成的文件。 + +## 面向 AI 的工作流 + +这些工作流会安装到受支持的 AI 编码宿主中。 + +代理或代理宿主会在仓库工作期间使用它们。它们不是顶层 shell 命令。 + +| 工作流 | 方向 | 何时使用 | 写入边界 | +| --- | --- | --- | --- | +| Truth Structure | topology-first | 默认路由过宽、所有权跨多个区域,或路由文件仍指向占位内容。 | 创建或修复路由和起始事实文档。 | +| Truth Document | implementation-first | 行为已经存在于代码中,但规范事实文档缺失或薄弱。 | 只写事实文档和路由。不能改变功能代码。 | +| Truth Sync | code-first | 功能代码已变更,已映射事实文档可能需要在交接前更新。 | 更新事实文档。Truth Sync 不能重写功能代码。 | +| Truth Preview | read-only | 代理需要在编辑前预览可能的路由。 | 只读。不授权写入。 | +| Truth Realize | doc-first | 产品或架构事实文档在前,代码应更新以匹配它们。 | 只更新代码。代理不能编辑它正在实现的事实文档。 | +| Truth Check | audit-first | 审查者或代理需要审计仓库事实健康状况。 | 审计并报告。 | + +### 重要区别 + +不要混淆这两个表面: + +| 表面 | 使用者 | 示例 | 含义 | +| --- | --- | --- | --- | +| 面向人的 CLI | 人类、脚本、类似 CI 的检查 | `truthmark check` | 从终端验证仓库事实产物。 | +| 面向 AI 的工作流 | 编码代理和代理宿主 | `/truthmark-check` | 请求代理运行已安装的审计工作流。 | + +名称有意相关,但表面不同。 + +## 普通 AI 辅助代码变更 + +大多数用户不应该每次都手动调用 Truth Sync。 + +Truth Sync 是为功能代码变更安装的收尾保护。 + +```text +代理修改功能代码 +代理运行或请求相关测试 +已安装工作流检测到功能代码变更 +Truth Sync 检查已映射事实文档 +代理在需要时更新事实文档 +人类审查代码 diff + 事实 diff +``` + +直接调用仍然适用于排查问题、强制提前同步,或让交接更明确: + +```text +/truthmark-sync 现在同步仓库事实,然后再交接 +``` + +## 已有行为但没有文档 + +当实现已经存在,但仓库事实不完整时,使用 Truth Document。 + +```text +/truthmark-document 在 docs/truth/authentication 下记录已实现的会话超时行为 +``` + +Truth Document 会把实现、测试、路由文件和现有文档作为证据来检查。 + +它只写事实文档和路由。 + +它不能改变功能代码。 + +## Doc-first 变更 + +当产品或架构决策从文档开始,并且代码应更新以匹配时,使用 Truth Realize。 + +```text +/truthmark-realize 将 docs/truth/authentication/session-timeout.md 实现到代码中 +``` + +Truth Realize 是 doc-first。 + +事实文档在前。代码跟随。 + +代理不能编辑它正在实现的事实文档。 + +## 只读路由预览 + +当代理需要在变更前理解可能的路由时,使用 Truth Preview。 + +```text +/truthmark-preview 预览 billing API 变更的可能事实路由 +``` + +Truth Preview 是 read-only。 + +它是选择器和规划辅助,不是写入授权,也不是 Truth Check 的替代品。 + +## 仓库事实审计 + +当你需要面向代理的审计工作流时,使用 Truth Check。 + +```text +/truthmark-check 在审查前审计路由和事实覆盖 +``` + +当你需要终端验证时,使用面向人的 CLI: + +```bash +truthmark check +``` + +两者都有用。它们不是同一个表面。 + +## 面向人的 CLI 命令 + +大多数维护者从三个命令开始。 + +| 命令 | 用途 | +| --- | --- | +| `truthmark config` | 创建 `.truthmark/config.yml`。除非使用 `--stdout`,否则只写这个文件。 | +| `truthmark init` | 从已审查配置安装或刷新已配置的工作流表面。 | +| `truthmark check` | 验证配置、权限边界、路由、承载决策的文档、frontmatter、内部链接、分支范围、生成表面、freshness 和覆盖率诊断。 | + +可选的仓库情报辅助工具会为当前 checkout 生成派生审查上下文。 + +它们不是事实来源。 + +| 命令 | 用途 | +| --- | --- | +| `truthmark index` | 为当前 checkout 构建 RepoIndex 和 RouteMap JSON。 | +| `truthmark impact --base ` | 将变更文件映射到已路由事实文档、所属路由、附近测试和公开符号。 | +| `truthmark context --workflow [--base ]` | 为 Truth Sync、Truth Document 或 Truth Realize 生成有边界的 ContextPack。使用 `--format markdown` 生成可读版本。 | + +受支持位置可使用 `--json` 获取结构化输出。 + +## 配置 + +Truthmark 是 config-first。 + +主配置文件是: + +```text +.truthmark/config.yml +``` + +新仓库应运行: + +```bash +truthmark config +``` + +然后先审查生成的配置,再运行: + +```bash +truthmark init +``` + +重要配置区域包括: + +| 配置区域 | 用途 | +| --- | --- | +| `version` | 配置契约版本。 | +| `platforms` | 应接收平台专属生成表面的代理宿主。 | +| `docs.layout` | 当前文档布局模式。 | +| `docs.roots` | 命名的规范文档根。 | +| `docs.routing.root_index` | 根路由索引路径。 | +| `docs.routing.area_files_root` | 委托子路由文件目录。 | +| `docs.routing.default_area` | 初始脚手架子路由 basename。 | +| `docs.routing.max_delegation_depth` | 当前最大路由委托深度。 | +| `authority` | 用作仓库事实权威的有序规范文档和 glob。 | +| `instruction_targets` | 接收共享受管说明块的文件,例如 `AGENTS.md`。 | +| `frontmatter.required` | 缺失时产生错误诊断的元数据字段。 | +| `frontmatter.recommended` | 缺失时产生审查诊断的元数据字段。 | +| `ignore` | 从相关检查和路由逻辑中排除的 glob 模式。 | + +## 仓库事实路由 + +Truthmark 将代码表面映射到事实文档。 + +主要路由文件是: + +```text +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md +``` + +路由告诉代理: + +- 哪个代码表面属于某个区域 +- 哪些事实文档拥有该区域 +- 何时应该更新事实 +- 涉及哪类事实文档 + +默认脚手架从宽泛路由开始。现有仓库通常应该把默认路由拆成真实所有权区域。 + +示例: + +```text +/truthmark-structure 将宽泛的 repository 区域拆成 frontend、backend、billing 和 deployment +``` + +好的路由会给 Truth Sync 精确目标。 + +坏的路由会让代理猜。 + +## Truthmark 会安装什么 + +Truthmark 安装一个紧凑、仓库原生的事实层。 + +典型脚手架和生成文件包括: + +```text +.truthmark/config.yml + +docs/truthmark/areas.md +docs/truthmark/areas/**/*.md + +docs/templates/behavior-doc.md +docs/templates/contract-doc.md +docs/templates/architecture-doc.md +docs/templates/workflow-doc.md +docs/templates/operations-doc.md +docs/templates/test-behavior-doc.md + +docs/truth/README.md +docs/truth/repository/README.md +docs/truth/repository/overview.md + +docs/standards/default-principles.md +docs/standards/documentation-governance.md + +AGENTS.md +CLAUDE.md +GEMINI.md +.github/copilot-instructions.md + +.codex/skills/truthmark-*/ +.codex/agents/ + +.claude/skills/truthmark-*/ +.claude/agents/ + +.opencode/skills/truthmark-*/ +.opencode/agents/ + +.github/prompts/truthmark-*.prompt.md +.github/agents/ + +.gemini/commands/truthmark/*.toml +``` + +Truthmark 会保留受管说明块之外的手写内容。 + +生成的工作流表面由 Truthmark 管理,可以通过重新运行来刷新: + +```bash +truthmark init +``` + +## 子代理和有边界证据检查 + +在宿主支持时,Truthmark 可以安装项目级验证代理和一个带租约的 `truth-doc-writer`。 + +这些有助于让大型事实任务保持有边界: + +- route auditors 检查路由所有权 +- claim verifiers 检查文档声明是否有证据支持 +- doc reviewers 检查事实文档质量 +- leased doc writers 处理有边界的事实文档写入分片 + +父工作流仍然负责最终解释、写入边界、diff 验证和验收。 + +这一点很重要:子代理帮助完成有边界的证据工作。它们不替代主工作流契约。 + +## 审查循环 + +Truthmark 为普通 Git 审查而设计。 + +一次好的 AI 辅助交接应该展示: + +```text +代码 diff +测试证据 +必要时的事实文档 diff +必要时的路由变更 +代理报告 +``` + +审查者应该能够回答: + +- 什么代码变了? +- 哪些事实文档拥有这些代码? +- 这些文档需要更新吗? +- 如果不需要,为什么? +- 代理是否留在工作流写入边界内? +- 是否包含测试或验证证据? + +## 示例 + +### 初始化仓库 + +```bash +npm install -g truthmark truthmark config truthmark init truthmark check ``` -如果你想从源码检出中试用尚未发布的变更: +### 移除未使用的代理平台 -```bash -cd /path/to/truthmark -npm install -npm run build -cd /path/to/your-repo -node /path/to/truthmark/dist/main.js config -node /path/to/truthmark/dist/main.js init -node /path/to/truthmark/dist/main.js check -``` - -在运行 `init` 之前先检查 `.truthmark/config.yml`;它是已提交的层级契约。`init` 之后,检查生成的工作流载体和路由文件,确保路由指向的文档确实是拥有你代码的文档: +编辑: ```text .truthmark/config.yml -docs/truthmark/areas.md -docs/truthmark/areas/repository.md -docs/templates/behavior-doc.md -docs/truth/README.md -docs/truth/repository/README.md -docs/truth/repository/overview.md -AGENTS.md -CLAUDE.md -GEMINI.md ``` -支持的平台是 `codex`、`opencode`、`claude-code`、`github-copilot` 和 `gemini-cli`。默认配置包含全部平台;请先从 `.truthmark/config.yml` 中移除不使用的平台,再重新运行 `truthmark init`。 -默认脚手架把 truth `README.md` 作为索引,并把当前行为事实放在有边界的叶子文档中,例如 `docs/truth/repository/overview.md`。 +然后重新运行: -现有仓库通常需要在 `init` 之后做一次清理:当生成的 `repository` 路由过宽、所有权跨越多个产品或服务,或路由文件仍指向占位文档时,运行已安装的 Truth Structure 工作流。Truth Structure 会拆分过宽的路由,创建或修复初始的规范事实文档,并在功能代码工作开始前为 Truth Sync 提供精确目标。Codex、Claude Code 和支持的 Copilot IDE 可以用 `/truthmark-structure` 调用它;OpenCode 风格的宿主可以用 `/skill truthmark-structure` 调用它。 +```bash +truthmark init +truthmark check +``` -## 它如何运行 - -Truthmark 最强的地方是默认路径,而不是一堆手动命令。由实际执行的代理和宿主环境决定是委托执行,还是内联运行已安装的工作流。 - -### 已实现但无文档的行为 - -当实现已经存在,但规范事实文档缺失或较弱时,使用这个流程: +### 拆分宽泛路由 ```text -用户识别一个已实现的行为或 API 端点 -用户显式调用 Truth Document -代理读取实现、测试、路由和现有文档 -代理只写 truth docs 和路由 -审查 truth-doc diff +/truthmark-structure 将宽泛的 repository 区域拆成 auth、billing、notifications 和 deployment ``` -Truth Document 是手动、implementation-first 的流程:代码作为证据,事实文档被创建或修复,且不能修改功能代码。Codex、Claude Code 和支持的 Copilot IDE 可以用 `/truthmark-document` 调用它;OpenCode 风格的宿主可以用 `/skill truthmark-document` 调用它。 +### 记录已实现行为 ```text -/truthmark-document 在 docs/truth/authentication 下记录已实现的会话超时行为 +/truthmark-document 在 docs/truth/authentication 下记录已实现的密码重置流程 ``` -### 常规代码变更 - -多数用户不需要直接调用 Truth Sync。关键在于,只要功能代码发生变化,已安装的代理工作流就会把 Truth Sync 当作收尾保护。正常路径是: +### 代码变更后同步 ```text -代理修改功能代码 -运行相关测试 -已安装的 Truth Sync 工作流在代理结束前运行 -如果生成了 truth-doc diff,就审查它 -提交或交接工作 +/truthmark-sync 现在同步仓库事实,然后再交接 ``` -Truth Sync 是 code-first:代码在前,事实文档跟随,且 Truth Sync 不能重写功能代码。它的主要职责是在功能代码发生变化时,通过已安装的代理工作流充当收尾保护。直接调用主要用于排查问题、交接前提前同步,或有意运行这套工作流。 - -Codex、Claude Code 和支持的 Copilot IDE 可以用 `/truthmark-sync` 调用它。OpenCode 风格的宿主可以用 `/skill truthmark-sync` 调用它。 +### 实现 doc-first 决策 ```text -/truthmark-sync 现在同步仓库 truth,然后再交接 +/truthmark-realize 将 docs/truth/billing/invoice-retry-policy.md 实现到代码中 ``` -### 文档优先变更 +### 从终端审计事实健康 -当产品或架构决策从文档开始时,使用这个流程: - -```text -用户编辑 truth docs -用户显式调用 Truth Realize -代理读取 truth docs 和相关代码 -代理只更新代码 -运行相关测试 -提交或交接工作 +```bash +truthmark check ``` -Truth Realize 是手动、文档优先的流程:事实文档在前,代码跟随,代理不能编辑它正在实现的事实文档。 +### 生成分支影响上下文 -Codex、Claude Code 和支持的 Copilot IDE 可以用 `/truthmark-realize` 调用它。OpenCode 风格的宿主可以用 `/skill truthmark-realize` 调用它。 - -```text -/truthmark-realize 将 docs/truth/authentication/session-timeout.md 实现为代码 +```bash +truthmark impact --base main ``` -## 它会安装什么 +### 生成工作流上下文 -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 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 审计仓库事实的健康状况。 - -功能 `README.md` 是索引。Truth Sync 预期读取并更新用于描述当前行为的有边界叶子文档。生成的工作流载体会保留仓库规则的权威性,同时把实现代码和规范事实文档当作当前行为的证据。 - -生成的载体由 Truthmark 管理,包含版本标记,并可通过 `truthmark init` 刷新。 - -## 命令 - -Truthmark V1 会保持终端 CLI 聚焦。大多数人类用户只需要设置、刷新和验证: - -| 面向人的 CLI | 用途 | -| ------------ | ---- | -| `truthmark config` | 创建 `.truthmark/config.yml`;除非使用 `--stdout`,否则只写入这个文件。 | -| `truthmark init` | 根据已审查配置安装或刷新本地工作流文件。 | -| `truthmark check` | 验证配置、权限边界、路由、承载决策的文档、frontmatter、内部链接、分支范围和覆盖率诊断。 | - -其余 CLI 命令是可选的仓库情报辅助工具。它们为当前 checkout 生成派生审查上下文;它们不是事实来源: - -| 可选 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` 会把它渲染成可读文本。 | - -上面所有 CLI 命令在需要结构化输出用于自动化时都支持 `--json`。 - -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 覆盖 +```bash +truthmark context --workflow truth-sync --base main --format markdown ``` -## 它为什么存在 - -大多数 AI 编码工作流优化的是下一次回答。Truthmark 优化的是下一次交接。 -它假设严肃团队需要: - -- 按分支生效的产品事实 -- 持久的架构和 API 决策 -- 文档与代码之间明确的所有权 -- 给代理设置安全的写入边界 -- 人类可以审查的普通 Git diff -- 团队成员无需特殊工具也能检查的可读 Markdown -- 随分支一起流转、而不是留在隐藏会话状态里的事实 -- 即使包没有全局安装也能工作的流程 - ## 项目状态 -Truthmark 不是记忆服务器,也不是 MCP 服务器。它是一套仓库实践,被打包成一个小型 CLI 安装器和代理原生的工作流载体,用来把 AI 工作流规则变成仓库基础设施。 - -V1 目前提供: +Truthmark V1 目前提供: - `truthmark config` - `truthmark init` @@ -296,15 +696,58 @@ V1 目前提供: - `truthmark index` - `truthmark impact` - `truthmark context` -- 受管的 `AGENTS.md` 工作流说明 -- 为已配置代理宿主生成的 Truth Structure、Truth Document、Truth Sync、Truth Preview、Truth Realize 和 Truth Check 技能载体 - 分支范围元数据 -- 配置、权限边界、路由、决策结构、frontmatter、链接和多语言覆盖率诊断 -- RepoIndex、RouteMap、ImpactSet 和 ContextPack 派生产物,可在 CLI 可用时加快本地检查 +- 受管说明块 +- 生成的 Truth Structure 工作流表面 +- 生成的 Truth Document 工作流表面 +- 生成的 Truth Sync 工作流表面 +- 生成的 Truth Preview 工作流表面 +- 生成的 Truth Realize 工作流表面 +- 生成的 Truth Check 工作流表面 +- 路由、权限边界、决策结构、frontmatter、链接、freshness、生成表面和覆盖率诊断 +- 派生的 RepoIndex、RouteMap、ImpactSet 和 ContextPack 产物 +- 面向 Codex、Claude Code、GitHub Copilot、OpenCode 和 Gemini CLI 的宿主专属表面 + +## 开发 + +安装依赖: + +```bash +npm install +``` + +运行本地开发 CLI: + +```bash +npm run dev -- init +npm run dev -- check +``` + +运行完整项目检查: + +```bash +npm run check +``` + +常用脚本: + +| 脚本 | 用途 | +| --- | --- | +| `npm run dev` | 用 `tsx` 运行 TypeScript CLI 入口。 | +| `npm run build` | 构建包。 | +| `npm run lint` | 运行 ESLint。 | +| `npm run typecheck` | 运行 TypeScript 检查。 | +| `npm run test` | 运行测试。 | +| `npm run check` | 运行 lint、typecheck、测试和 build。 | +| `npm run release:check` | 运行面向发布的验证。 | + +修改 Truthmark 本身时,请参阅 [CONTRIBUTORS.md](CONTRIBUTORS.md)。 ## 文档 -根 README 面向评估和试用这个包的人。详细的功能和业务规范位于 `docs/` 下: +README 是评估和设置的快速路径。 + +详细的当前行为位于 `docs/` 下: - [文档索引](docs/README.md) - [架构概览](docs/architecture/overview.md) @@ -314,11 +757,11 @@ V1 目前提供: - [已安装工作流](docs/truth/workflows/overview.md) - [仓库事实维护指南](docs/standards/maintaining-repository-truth.md) -当前行为应放在上面的规范文档树中。 +## 设计边界 -## 非目标 +Truthmark 有意保持小而清晰。 -Truthmark V1 不是: +它不是: - 托管服务 - MCP 服务器 @@ -327,8 +770,49 @@ Truthmark V1 不是: - CI 或 PR 强制执行产品 - 测试、代码审查或技术领导力的替代品 - 自主代码重写引擎 +- 模型训练或微调框架 +- 隐藏记忆层 -它是一种轻量方式,让本地 AI 编码代理尊重你的团队保存在 Git 中的事实。 +这些边界是产品的一部分。 + +Truthmark 让工作流保持本地、已提交、按分支生效并可审查。 + +## 安全和审查纪律 + +Truthmark 帮助仓库保持诚实。它不能证明代码正确。 + +团队仍然应该: + +- 运行相关测试 +- 审查功能代码变更 +- 审查事实文档变更 +- 不把 secrets 放进文档 +- 把仓库专属说明保留在受管块之外 +- 升级后审查生成工作流表面的 diff +- 保留人类对产品和架构决策的所有权 + +Truthmark 让代理上下文可见。它不替代人类判断。 + +## 路线图方向 + +当前未来方向强调: + +- 更强的 `truthmark check` 证据报告 +- 更清晰的采用示例 +- 展示真实 Truth Sync 循环的示例仓库 +- 面向已经使用代理说明文件团队的迁移指南 +- 生成宿主表面的符合性测试 +- 感知路由的 stale truth 提示 +- 面向 doc-first 工作的有边界实现清单 + +重心保持不变: + +```text +仓库事实 +代理原生工作流 +Git 审查 +按分支生效的上下文 +``` ## 许可证