# AI-Native Documentation Graph: Documentation Philosophy

Analyze the repository and generate or maintain an AI-friendly documentation system.

The documentation should be organized so both humans and AI coding agents can quickly navigate to the information relevant to their current task without reading unnecessary documents.

The documentation serves two audiences:

- **README.md** is the primary entry point for **humans**.
- **AGENTS.md** is the primary entry point for **AI coding agents**.

The documentation is **not** the source of truth.

**The source of truth is always the codebase.**

Documentation exists to explain, summarize, organize, and navigate the implementation.

---

# Documentation Layout

Always use the following directory structure:

```text
/
├── README.md
├── AGENTS.md
└── docs/
    ├── SPEC.md
    ├── ARCHITECTURE.md
    ├── API.md
    ├── DESIGN.md
    ├── ROADMAP.md
    ├── BACKLOG.md
    └── tickets/
        ├── T-001.md
        ├── T-002.md
        ├── T-003.md
        └── ...
```

Rules:

- `README.md` MUST exist in the project root.
- `AGENTS.md` MUST exist in the project root.
- All remaining documentation MUST live inside the `docs/` directory.
- Never place `SPEC.md`, `ARCHITECTURE.md`, `API.md`, `DESIGN.md`, `ROADMAP.md`, or `BACKLOG.md` in the project root.
- Individual implementation tickets MUST live under `docs/tickets/`.

---

# Operating Modes

## Existing Project

If the repository already contains source code:

- Inspect the implementation.
- Infer the current architecture.
- Infer implemented features.
- Infer API contracts.
- Infer design conventions.
- Infer project status.

Then generate or update the documentation to match the implementation.

If documentation already exists:

- Update it.
- Remove stale information.
- Preserve useful content.
- Keep cross references intact.

Never invent functionality that does not exist.

---

## Blank Project

If the repository contains little or no implementation:

**Do not proceed silently.** A blank or sparse project means the AI lacks the context necessary to produce useful output. The AI must actively solicit information before generating anything.

### Before Generating Documentation

Before creating any documentation scaffolding, the AI MUST interrogate the user to establish a minimum understanding of the project. Ask targeted questions covering:

- **Project identity:** What is this project? What problem does it solve?
- **Goals and scope:** What is the intended outcome? What is explicitly out of scope?
- **Target audience:** Who will use this? End users? Developers? Both?
- **Technology stack:** What languages, frameworks, databases, and platforms are planned or in use?
- **Constraints:** Are there performance, budget, timeline, compliance, or organizational constraints?
- **Existing context:** Is this a rewrite? A prototype? A production system? Are there predecessor systems?
- **Team context:** How many contributors? What roles? What is the team's experience level with the stack?

Do not accept vague answers. If the user provides an incomplete or ambiguous response, follow up with more specific questions until the picture is clear enough to produce actionable documentation.

### During Documentation Generation

Generate documentation scaffolding.

Create document structure with headings, placeholders, examples, and guidance for future contributors.

Clearly mark unknown sections with placeholders such as:

> TODO

or

> To be documented as implementation evolves.

Do not fabricate requirements or implementation details.

If the user's answers leave gaps in any documentation section, mark those gaps explicitly and ask the user to fill them before proceeding further.

The documentation should immediately serve as the project's documentation foundation.

---

# Source of Truth

The implementation is always authoritative.

Documentation should describe the implementation.

If documentation and code disagree:

- Trust the code.
- Update the documentation.

Never modify code simply to match documentation.

---

# Documentation Philosophy

The documentation should behave as a graph rather than a single monolithic document.

Every document should have one clear responsibility.

Avoid duplicated information.

Prefer linking instead of copying.

Optimize the documentation for:

- AI coding agents
- Human developers
- Low token usage
- Fast navigation
- Long-term maintainability

The documentation should enable an AI agent to efficiently determine which documents are relevant before reading them.

## Never Assume — Seek Clarification

**The AI must never assume missing context.** Every task, regardless of size, begins by verifying that enough is known to proceed correctly.

### When to Ask Questions

- The project is blank or nearly empty.
- The user's prompt is vague, ambiguous, or open to multiple interpretations.
- The AI is unsure about the intended technology stack, architecture, or design conventions.
- The codebase has evolved significantly since the last interaction and the knowledge base may be stale.
- The user references a feature, module, or concept that does not appear in the existing documentation or codebase.
- There are multiple plausible approaches and the tradeoffs are non-obvious.

### How to Ask

- Ask specific, targeted questions — not open-ended "what do you want?" prompts.
- Frame questions around the concrete decision the AI needs to make.
- Offer reasonable options when the space of possibilities is small.
- When the answer affects downstream behavior, explain why the question matters.
- Do not accept ambiguous answers; drill down until the intent is clear.

### Repeating the Process

As the knowledge base grows, the information graph deepens, and the codebase evolves, the AI must repeat this clarification process:

- Before every new task, check whether the existing context is sufficient.
- If the user's prompt is vague, seek clarification before acting.
- If implementation details have shifted since the last documented state, confirm assumptions.
- Treat every task as an opportunity to refine and deepen the project's documented understanding.

**Assume nothing. Ask always. Clarify relentlessly.**

## Read Minimization Principle

Documentation should be optimized for **selective retrieval**.

An AI coding agent should rarely need to read more than one or two documents to complete a task.

Each document should expose enough metadata and cross references for the AI to determine whether additional documents are relevant.

Avoid forcing AI agents to traverse the entire documentation graph to answer a localized question.

Prefer narrowly focused documents over large documents.

Every document should answer one category of questions well.

The intended workflow for AI agents is:

1. Read `AGENTS.md`
2. Determine which documentation is relevant.
3. Read only the required document(s).
4. Follow additional references only if necessary.
5. Return to the codebase, which remains the source of truth.

The intended workflow for humans is:

1. Read `README.md`
2. Understand the project.
3. Follow links to detailed documentation as needed.

---

# Cross References

Every document should contain a **Related Documentation** section near the top.

Use relative Markdown links.

Example:

```md
## Related Documentation

- [README.md](../README.md)
- [AGENTS.md](../AGENTS.md)
- [SPEC.md](SPEC.md)
- [ARCHITECTURE.md](ARCHITECTURE.md)
```

Only reference documents that are actually relevant.

Prefer links instead of duplicated explanations.

---

# Document Metadata

Every generated documentation file MUST begin with a concise metadata block immediately below the document title.

The metadata serves as a lightweight summary that enables both humans and AI coding agents to quickly determine whether the document is relevant before reading the remainder of the file.

This metadata is mandatory for every documentation file, including:

- `README.md`
- `AGENTS.md`
- `docs/SPEC.md`
- `docs/ARCHITECTURE.md`
- `docs/API.md`
- `docs/DESIGN.md`
- `docs/ROADMAP.md`
- `docs/BACKLOG.md`
- `docs/tickets/T-###.md`

Use the following format:

```md
# Document Title

> **Purpose:** Brief description of what this document covers.
>
> **Audience:** Human | AI | Both
>
> **Source of Truth:** Codebase (implementation is authoritative)
>
> **Last Updated:** <current date>
>
> **Depends On:**
> - Relative Markdown links to prerequisite documents, or `None`
>
> **Referenced By:**
> - Relative Markdown links to documents that commonly reference this document, or `Unknown`
```

## Metadata Rules

- Place the metadata immediately below the document title.
- Keep the metadata concise (approximately 5–10 lines).
- Use relative Markdown links.
- Include the intended **Audience** (`Human`, `AI`, or `Both`).
- The **Source of Truth** must always indicate that the implementation is authoritative.
- **Last Updated** should use the current date whenever documentation is generated or synchronized.
- **Depends On** lists only documents that should typically be read before this one.
- **Referenced By** lists documents that commonly depend on this document.
- If relationships are unknown (for example in a blank project), use `Unknown` rather than inventing references.
- Update the metadata whenever document relationships change.

The goal is for an AI agent to determine whether the document is relevant by reading only this metadata block.

---

# Generate the Following Documents

---

# /README.md

Purpose:

This is the primary documentation entry point for **human developers**.

It should help a new developer understand the project within a few minutes.

It should not attempt to document everything.

Instead, it should introduce the project and link to the detailed documentation.

Contents should include:

- Project overview
- Features summary
- Screenshots (if available)
- Technology stack
- Prerequisites
- Installation
- Running locally
- Development workflow (mandatory TDD: tests are written before code)
- Testing
- Deployment (brief overview)
- Project structure
- Contributing
- Documentation links

Reference:

- AGENTS.md for AI coding agents.
- docs/SPEC.md for product behavior.
- docs/ARCHITECTURE.md for technical architecture.
- docs/API.md for API documentation.
- docs/DESIGN.md for the design system.
- docs/ROADMAP.md for product direction and long-term vision.
- docs/BACKLOG.md for current work queue and implementation progress.

---

# /AGENTS.md

Purpose:

Acts as the documentation router and entry point for AI coding agents.

This document should intentionally remain small.

It should help AI coding agents quickly determine which documentation they need.

Contents should include:

- Project overview
- Source of truth policy
- Documentation philosophy
- Documentation conventions
- Documentation index
- Navigation guide
- Development workflow — the mandatory TDD (test-first) cycle
- Updating documentation

Example documentation index:

| Document | Purpose | Read When |
|----------|----------|----------|
| README.md | Human onboarding | Learning the project |
| docs/SPEC.md | Functional requirements | Building or modifying features |
| docs/ARCHITECTURE.md | System architecture | Refactoring or structural changes |
| docs/API.md | API contracts | Backend/frontend integration |
| docs/DESIGN.md | Design system | UI work |
| docs/ROADMAP.md | Product direction | Understanding long-term goals |
| docs/BACKLOG.md | Active work queue | Determining the next ticket |
| docs/tickets/T-###.md | Individual implementation ticket | Executing a specific ticket |

Do not duplicate information contained in the other documentation files.

---

# /docs/SPEC.md

Purpose:

Describe **what** the system does and **why**.

Contents include:

- Product overview
- Goals
- Functional requirements
- User workflows
- User behavior
- Features
- Business rules
- Constraints
- Assumptions
- Non-functional requirements

Do **not** describe implementation details.

Reference:

- ARCHITECTURE.md for implementation details.
- API.md for interface contracts.
- DESIGN.md for UI behavior.
- README.md for project introduction.

---

# /docs/ARCHITECTURE.md

Purpose:

Describe **how** the system is built.

This document evolves alongside the implementation.

It should accurately reflect the current architecture of the codebase.

Contents include:

- Technology stack
- Folder structure
- System architecture
- Module boundaries
- Layers
- Services
- Database
- Authentication
- Authorization
- State management
- Integrations
- Data flow
- Event flow
- Design patterns
- Deployment architecture

Reference:

- SPEC.md for feature intent.
- API.md for interface contracts.
- DESIGN.md where frontend architecture overlaps with design.

---

# /docs/API.md

Purpose:

Describe communication contracts between system components.

Include:

- REST endpoints
- GraphQL operations
- RPC interfaces
- Server Actions
- Webhooks
- Authentication
- Authorization
- Request formats
- Response formats
- Validation
- Error handling
- Versioning

Reference:

- SPEC.md for endpoint purpose.
- ARCHITECTURE.md for service organization.

---

# /docs/DESIGN.md

Purpose:

Describe the project's design system.

Include:

- Design philosophy
- UX principles
- Accessibility
- Color palette
- Typography
- Spacing
- Components
- Icons
- Responsive behavior
- Interaction patterns
- Motion
- Design tokens

Reference:

- SPEC.md for UX requirements.
- ARCHITECTURE.md for frontend implementation.

---

# /docs/ROADMAP.md

Purpose:

Describe the long-term product direction.

Contents include:

- Vision
- Product milestones
- Major releases
- Strategic goals
- Future product direction

Rules:

- Contains only high-level planning.
- Never contains implementation details.
- Never tracks day-to-day development.
- Changes infrequently.
- Should remain concise.

Reference:

- BACKLOG.md for current work queue and implementation progress.
- SPEC.md for functional requirements.

---

# /docs/BACKLOG.md

Purpose:

Acts as the canonical work queue for the project.

Organize work into Kanban-style sections:

- Backlog
- Ready
- In Progress
- Review
- Done
- Blocked (optional)

Rules:

- Do not embed full ticket descriptions.
- Link to individual ticket documents under `docs/tickets/` instead.
- Reflect current implementation progress.
- Keep statuses synchronized with the project.

Reference:

- ROADMAP.md for strategic direction.
- docs/tickets/ for individual implementation tickets.

---

# /docs/tickets/T-###.md

Purpose:

Represent exactly one implementation ticket.

Each ticket contains:

- ID
- Title
- Status
- Priority
- Estimate
- Dependencies
- Context
- Acceptance Criteria
- Definition of Done
- Implementation Notes
- Related Documentation
- Related Files

## Ticket Filename Format

Name each ticket file with a short, descriptive name using this format:

```text
T-###-[descriptive-name].md
```

Guidelines:

- **DO** keep the ticket ID (`T-###`) at the beginning of the filename.
- **DO** add a concise, descriptive name that clearly communicates what the ticket is about.
- **DO** use the feature, behavior, or user outcome as the basis for the descriptive name.
- **DO** use lowercase words separated by hyphens (`kebab-case`).
- **DO** make the name specific enough that a developer or agent can understand the ticket's purpose from the filename alone.
- **DON'T** use vague names such as `update.md`, `fix.md`, `changes.md`, or `task.md`.
- **DON'T** include unnecessary implementation details unless they are important for identifying the ticket.
- **DON'T** change or omit the ticket ID.

Examples:

- `T-123-add-user-authentication.md`
- `T-124-export-orders-to-csv.md`
- `T-125-fix-checkout-payment-error.md`

The goal is for the filename to provide immediate context about **what the ticket is for**, without needing to open the file.

Rules:

- One ticket equals one unit of work.
- Tickets should remain focused and self-contained.
- AI agents should update ticket status as work progresses.
- Tickets should reference documentation rather than duplicate it.
- Every ticket's **Definition of Done** must include the mandatory TDD cycle (tests written first, minimal implementation, refactor, passing relevant test suite) — see the Test-Driven Development (TDD) section below.

## Ticket Slicing: Vertical Feature Slices

When creating tickets with `docgraph_ticket_create`, **slice tickets vertically by feature or user-facing capability, not horizontally by technical layer**.

Each ticket should represent a **complete, independently testable and preferably shippable slice of functionality**. A ticket should include the necessary changes across all relevant layers (e.g., UI, API, business logic, database) rather than creating separate tickets for each layer.

Guidelines:

- **DO** organize tickets around a feature, behavior, user outcome, or independently testable capability.
- **DO** include all required layers within the same feature ticket when they are necessary to deliver that capability.
- **DO** make each ticket independently testable whenever reasonably possible.
- **DO** prefer tickets that can be completed, tested, reviewed, and shipped incrementally.
- **DON'T** create separate tickets such as "Create database schema", "Implement API", or "Build frontend" when these are all required parts of the same feature.
- **DON'T** split work purely by architectural or technical layers such as frontend, backend, database, infrastructure, or services.
- **DO** split a feature into multiple tickets only when the resulting slices represent meaningful, independently testable capabilities or user outcomes.

The goal is to use **vertical feature slices** so that each ticket delivers a complete piece of functionality rather than an incomplete technical layer. This makes implementation, testing, code review, and incremental shipping easier.

Reference:

- BACKLOG.md for the overall work queue.
- SPEC.md for functional requirements.
- ARCHITECTURE.md for implementation context.

---

# Test-Driven Development (TDD) — Mandatory

**Tests are written before code. Always.** The TDD cycle is the mandatory first step of every small coding cycle — every new feature, function, enhancement, refactor, or bug fix begins with an automated test, and no production code is written or changed until that test exists.

For every change:

1. **Write the test first.** Define the expected behavior and acceptance criteria in an automated test before writing or modifying production code. Ticket acceptance criteria are the starting point for these tests.
2. **Run the test and confirm that it fails** for the expected reason (Red).
3. **Write the minimum code necessary** to make the test pass (Green).
4. **Refactor the implementation** while keeping all tests passing (Refactor).
5. **Run the relevant test suite** to verify that the change has not introduced regressions.

Rules:

- The TDD cycle must begin **before any production code is written or changed** for the task.
- Do not skip the test-first step, even for small changes or seemingly trivial bug fixes.
- A task is not complete — and a ticket is not `Done` — until the relevant test suite passes.

# AI Ticket Workflow

The intended workflow for AI coding agents follows a ticket-driven process designed to minimize context usage and optimize for selective retrieval:

1. Read `AGENTS.md` to determine the documentation layout.
2. Read `BACKLOG.md` to identify the highest-priority ticket in the **Ready** column.
3. Open the corresponding ticket document under `docs/tickets/`.
4. Read only the documentation referenced by that ticket.
5. **Verify context:** If the ticket or its referenced documentation lacks sufficient detail to proceed confidently, grill the user for clarification before writing any code. Never assume missing details.
6. **Write the automated tests first.** Translate the ticket's acceptance criteria into automated tests before touching any production code. Run them and confirm they fail for the expected reason (Red).
7. **Implement and refactor.** Write the minimum code necessary to make the tests pass (Green), then refactor while keeping all tests passing (Refactor). Run the relevant test suite to verify no regressions.
8. Update the ticket status and any relevant fields, and add an implementation note describing what was implemented and verified.
9. Update any affected documentation to remain synchronized with the implementation.
10. Return to `BACKLOG.md` before selecting the next ticket.

AI agents should minimize context usage by following document references rather than reading unrelated documentation.

Each ticket is self-contained: the ticket itself, combined with the documentation it references, should provide everything necessary to complete the ticket.

---

# Ticket Completion, Verification & Reporting Rules

When implementing a ticket, update its Markdown checklist **only when the corresponding criterion has been verified**.

## Acceptance Criteria and Definition of Done

For every checklist item under `## Acceptance Criteria` and `## Definition of Done`:

* Change `- [ ]` to `- [x]` **only if the criterion is fully satisfied and verified**.
* For criteria that can be verified automatically, run the relevant tests, type checks, linting, build commands, or other appropriate validation before marking them complete.
* **Do not mark a criterion complete based solely on code inspection or assumption** when it requires executable or manual verification.
* If a criterion requires **human/manual testing or verification**, do not mark it `[x]` unless that verification has actually been performed.
* Leave criteria requiring outstanding human verification as `- [ ]`.
* Add an explicit HTML comment **inline on the same line as the criterion** explaining **exactly what the human needs to test or verify** (or, for verified criteria, record the verification evidence). The ticket round-trip preserves checkbox state and inline comments; a comment written on its own line would be rewritten as a separate unchecked item.

Use this format:

```md
- [x] pnpm dev serves a page at localhost:3000 with Header/Footer and Tailwind styles applied <!-- VERIFIED: `pnpm dev` served HTTP 200 with the expected SSR HTML (verified via curl). -->
- [ ] pnpm dev serves a page at localhost:3000 with Header/Footer and Tailwind styles applied <!-- HUMAN VERIFICATION REQUIRED: Start the development server, open localhost:3000 in a browser, and verify that the page renders correctly with the Header, Footer, and Tailwind styles applied. -->
```

The comment should describe the specific verification required. Avoid vague comments such as "needs manual testing."

## Verification Rules

Before marking a checkbox `[x]`:

1. **Determine how the criterion can be verified.**

   * **Automated:** Run the appropriate test, command, static check, or other automated validation.
   * **Manual:** Perform the required human verification.
   * **Both:** Satisfy both the automated and manual requirements.

2. **Only mark the checkbox `[x]` after successful verification.**

3. If an automated check fails:

   * Leave the checkbox unchecked.
   * Fix the implementation if appropriate.
   * Re-run the relevant check.
   * Mark it `[x]` only after it passes.

4. If human verification is required but cannot be performed in the current environment:

   * Leave the checkbox unchecked.
   * Add an inline `<!-- HUMAN VERIFICATION REQUIRED: ... -->` comment on the same line describing the exact steps and expected result.

5. **Never claim that human verification was performed when it was not.**

6. Do not remove, rewrite, weaken, or reinterpret acceptance criteria or Definition of Done items merely to make the ticket appear complete.

7. Do not mark a criterion `[x]` simply because the implementation was completed. **Verification is required.**

## Inform the User/Developer About Outstanding Human Verification

After completing the implementation, **review every unchecked criterion** and determine whether it requires human/manual testing or verification.

If one or more criteria require human verification that has not been performed:

* **Explicitly inform the user/developer in the final implementation summary.**
* Clearly identify **which criteria remain unverified**.
* Explain **what the user/developer needs to test or verify**.
* Do not bury this information in the general implementation summary.
* Make it clear that the ticket may be implemented but is **not fully verified/complete** until the outstanding human checks are performed.

For example, the final summary should include a section such as:

```md
### Human Verification Required

The following acceptance criteria still require manual verification:

- `pnpm dev` → Open `localhost:3000` in a browser and verify the Header/Footer render correctly and Tailwind styles are applied.
- README quickstart → Follow the documented setup instructions from a clean clone and verify the application starts successfully.

These criteria remain unchecked in the ticket because the required human verification was not performed by the agent.
```

If **no human verification is outstanding**, explicitly state that no additional human verification is required.

For example:

```md
### Human Verification Required

None. All applicable acceptance criteria and Definition of Done items were verified automatically.
```

## Final Checklist Review

Before producing the final implementation summary:

1. Review **all** checkboxes under `## Acceptance Criteria`.
2. Review **all** checkboxes under `## Definition of Done`.
3. Ensure every `[x]` has corresponding verification evidence.
4. Ensure every criterion requiring human verification has an explicit `HUMAN VERIFICATION REQUIRED` comment if that verification remains outstanding.
5. Ensure outstanding human verification is clearly reported in the final summary.
6. Do not present the ticket as fully complete if any required verification remains outstanding.

## Checkbox Meaning

The final ticket should accurately represent the actual verification state:

* `- [x]` → **Implemented and verified**
* `- [ ]` + `HUMAN VERIFICATION REQUIRED` → **Implemented/ready, but human verification is still outstanding**
* `- [ ]` without a human-verification comment → **Not yet satisfied or not yet verified**

The goal is for the ticket checklist and final implementation summary to provide an **accurate record of implementation and verification status**, rather than simply indicating that the code changes were made.

---

# Documentation Quality Rules

Every document should:

- Have one clearly defined responsibility.
- Avoid duplicated information.
- Reference related documents instead of copying them.
- Be concise and structured.
- Use Markdown headings consistently.
- Prefer bullet lists over long paragraphs.
- Use tables where they improve readability.
- Be optimized for AI parsing.
- Be optimized for human readability.
- Remain synchronized with the implementation.

---

# Synchronization Rules

Whenever implementation changes:

- Update affected documentation.
- Preserve cross references.
- Remove obsolete information.
- Keep terminology consistent.
- Update document metadata.
- Update document relationships if needed.
- Ensure every Markdown link remains valid.
- Ensure README.md continues to reflect the project's current state without duplicating detailed documentation.

Never leave stale documentation.

---

# Final Goal

Produce a modular documentation system where:

- `README.md` → Human onboarding
- `AGENTS.md` → AI documentation router
- `docs/SPEC.md`, `docs/ARCHITECTURE.md`, `docs/API.md`, `docs/DESIGN.md` → Stable reference documentation
- `docs/ROADMAP.md` → Strategic product vision
- `docs/BACKLOG.md` → Active work queue
- `docs/tickets/` → Individual executable implementation tickets
- Every document begins with a metadata block.
- Every document links to related documentation instead of duplicating content.
- Human developers can quickly understand the project and discover detailed documentation through README.md.
- AI coding agents can efficiently determine which documents are relevant before reading them.
- The implementation remains the sole source of truth.
- The documentation works equally well for:
  - Existing projects
  - Brand-new projects
  - Mature production systems
  - Empty repositories with only documentation scaffolding

The final result should form a lightweight, interconnected documentation graph that clearly separates stable documentation from execution planning, minimizes token usage, supports selective retrieval by AI agents, provides an excellent onboarding experience for humans, and evolves alongside the codebase without becoming the source of truth.
