# PRD Plugin

PRD Plugin is a project-agnostic plugin for turning ideas into traceable
project artifacts:

- brainstorm records
- PRD requirements
- architecture decisions and components
- implementation plans
- acceptance criteria
- evidence records
- agent memory and tracking state
- request, issue, bug, and compatibility intake records
- project health checks
- configurable cross-host Reasoning Guard with report-first evidence follow-through
- cross-artifact "fold it in" integration workflow
- end-to-end planning lifecycle workflow
- traceability reviews

It is not Gandalf-specific and not Auto-Harness-specific. Those projects can
use it, but the method is intended to work in any repository.

See [Reasoning Guard](docs/REASONING-GUARD.md) for its default report mode,
per-category overrides, lifecycle, visible-summary classification telemetry,
local latency and accuracy measurements, and host limits.

## Quick Install

In the downstream repo where you want to use PRD Plugin:

```bash
npm install --save-dev prd-plugin
npx prd-install . --codex --opencode --claude
```

The four install options are `--codex`, `--opencode`, `--claude`, and
`--opencode-skill-inject`. See the
[Install Options](#install-options) section and
[`docs/INSTALL-MATRIX.md`](docs/INSTALL-MATRIX.md) for the full matrix of what
each option installs.

PRD Plugin can also be used as a **Claude Code plugin** without a per-repo
install — the hub repo is a self-contained marketplace:

```text
/plugin marketplace add markusuk1/prd-plugin
/plugin install prd-plugin@prd-plugin
```

## Repository Model

The plugin itself lives outside target projects.

Each target project keeps its own method state in:

```text
.prd_plugin/
```

That folder is intended to be committed with the target repo unless the project
chooses otherwise.

Recommended target-repo layout:

```text
.agents/
  skills/
    project-memory/
      SKILL.md
    project-session-close/
      SKILL.md
    ...

.opencode/
  skill/
    project-memory/
      SKILL.md
    ...

.claude/
  settings.json
  hooks/
  commands/

.prd_plugin/
  config.json
  METHOD.md
  ID-SCHEME.md
  ids/
    registry.json
  state/
    artifacts/
      prd/
      architecture/
      implementation_plan/
    project.json
    memory.json
    decisions.json
    changelog.json
    tracking.json
    requests.json
    health.json
    sessions/
      shared/
        promoted-session-summaries.jsonl
  local/
    sessions/
  templates/
    brainstorm.md
    prd.json
    architecture.json
    implementation-plan.json
    human-exports/
      prd.md
      architecture.md
      implementation-plan.md
    decision-record.md
    evidence.md

docs/
  brainstorm/
  exports/
  decisions/
  evidence/
  traceability/
```

## Core Flow

```text
Idea
  -> brainstorm IDs
  -> PRD requirements
  -> architecture decisions/components
  -> implementation plan tasks
  -> evidence
  -> promoted agent memory
  -> request intake, when external agents propose changes
  -> health check
  -> traceability review
```

The goal is consistent thinking and traceability across repos without forcing a
specific product architecture.

## Superpowers Method Alignment

PRD Plugin adopts selected Superpowers execution disciplines as PRD-native
skills rather than competing with them. The adapted skills preserve the stronger
Superpowers method rules for implementation planning, test-first development,
root-cause debugging, and verification, while adding PRD Plugin's durable ID,
evidence, request, health, changelog, and traceability requirements.

Imported/adapted methods:

- `project-implementation-plan`
- `project-test-driven-implementation`
- `project-systematic-debugging`
- `project-verification-before-completion`

Superpowers controls execution discipline; PRD Plugin controls durable IDs and
project truth. `BR-*`, `PRD-*`, `ARCH-*`, `IMP-*`, `EV-*`, `REQ-*`, `MSG-*`,
`HLT-*`, `MEM-*`, `OBS-*`, `TRK-*`, `CHG-*`, and `DEC-*` remain
non-negotiable. See `THIRD_PARTY_NOTICES.md` for attribution.

## Planning Lifecycle Workflow

Use `project-planning-lifecycle` when brainstorms, early notes, accepted
requests, or rough feature ideas need to become a complete planning chain:

```text
brainstorm -> PRD -> architecture -> implementation plan -> traceability sync/review
```

The workflow prevents stale jumps from brainstorms straight into implementation
plans. It requires PRD requirements to cite `BR-*` or accepted `REQ-*` sources,
architecture to cite `PRD-*` or `DEC-*` sources, implementation tasks to cite
both `PRD-*` and `ARCH-*` sources, and open or stale `BR-Q-*`, `BR-RISK-*`,
`TRK-*`, `REQ-*`, and `HLT-*` items to be carried forward or recorded as
explicit follow-up.

## Canonical Planning Artifacts

JSON/JSONL is canonical for planning artifacts. Generate Markdown only on
explicit human request.

PRDs, architecture docs, and implementation plans live under
`.prd_plugin/state/artifacts/{artifact_type}/{artifact_id}.json` as the single
source of truth. Those JSON artifacts record stable IDs, short summaries,
source links, traceability, open questions, stale follow-ups, and evidence
expectations. Markdown exports may be created under `docs/exports/` for human
review, but exports are snapshots and must not be edited as project truth.

## Agent Memory Model

The plugin uses JSON as the canonical machine-readable format for agent-facing
project state. Markdown remains useful for optional human exports and document
branches, but durable agent memory and planning truth should live in structured
files that are easy to validate and selectively load.

Committed state belongs under `.prd_plugin/state/` by default. Raw session
memory belongs under `.prd_plugin/local/` and should be ignored by git. Agents
may write rich local session logs, but only concise, source-backed,
non-sensitive summaries should be promoted into committed project memory.

## LLM Wiki Navigation

When `knowledge.llm_wiki.enabled` is on, each repository can maintain durable
knowledge under `wiki/` and immutable source material under `raw/`. Wiki prose
must use inline links whenever it names another local Markdown file; a bare
filename is not considered navigable.

The downstream runtime audits this deterministically:

```bash
python .prd_plugin/scripts/prd_wiki_backfill.py --lint-links --format json
python .prd_plugin/scripts/prd_wiki_backfill.py --lint-links --fix --format json
```

The fixer changes only references with one unambiguous target. The PRD gate and
wiki drift check enforce the policy by default. Configure it with
`knowledge.llm_wiki.require_inline_md_links`; see the [wiki index](wiki/index.md)
for the compiled knowledge base.

## Configuration

Projects may customize method paths and policy in `.prd_plugin/config.json`.
Agents and scripts should read this file before assuming default state,
request, health, registry, or local session paths.

`prd_config.py` is the unified configuration tool. It classifies every shipped
persistent setting and inventories environment, install-time, host-wiring,
specialized-CRUD, and invocation-only controls. Use `inventory` or `audit` to
understand the surface, `describe`/`effective` to see ownership, latency, and
dependencies, and validated `set`/`enable`/`disable` operations to change it.
Built-in `lean`, `balanced`, and `thorough` profiles can be previewed with
`profile apply <name> --dry-run`; custom profiles support save/show/diff/apply/
delete. Profile writes are atomic and never auto-enable external integrations.
Agents have equivalent `prd_config_list`, `prd_config_get`, `prd_config_set`,
and `prd_config_profile` MCP tools.

All host hooks enter through one configuration-gated dispatcher process per
event. `hooks.enabled` disables all hook behavior; child switches independently
control session/prompt nudges, Stop guard/report/drift/reflection/archive work,
the precommit gate, and skill logging. The dispatcher checks config before
importing a handler, so disabling expensive behavior avoids that work rather
than merely hiding its output.

```bash
python .prd_plugin/scripts/prd_config.py inventory --json
python .prd_plugin/scripts/prd_config.py list --latency high
python .prd_plugin/scripts/prd_config.py profile apply balanced --dry-run
python .prd_plugin/scripts/prd_config.py profile apply balanced
python .prd_plugin/scripts/prd_config.py effective hooks.nudge.on_user_prompt
```

## Deterministic Workflows

PRD Plugin has one configurable workflow authority for bounded mechanics. Its
managed catalog covers session start/stop, request intake, requirements,
debugging, code review, verification, evidence, closeout, maintenance,
install/update, and hub release. The engine validates inputs and definitions,
executes only code-owned allowlisted actions, allocates duplicate-safe `WFR-*`
IDs, persists atomic checkpoints and receipts, and reports `completed` only
after every declared postcondition passes.

Legitimate product or engineering judgment is explicit. A workflow pauses at
`waiting_judgment` with a hash-bound, source-backed schema; AI-Collab resolves
the configured model profile and returns a result. Deterministic resume rejects
stale hashes, wrong executors/profiles, invalid schemas, and unknown sources.
The model cannot write canonical state.

```bash
python .prd_plugin/scripts/prd_workflows.py --repo-root . list --json
python .prd_plugin/scripts/prd_workflows.py --repo-root . audit --json
python .prd_plugin/scripts/prd_workflows.py --repo-root . plan engineering.verify --inputs '{"base_ref":"main"}' --json
python .prd_plugin/scripts/prd_workflows.py --repo-root . run engineering.verify --inputs '{}' --idempotency-key verify-local --json
```

The nine `prd_workflow_*` MCP tools expose list/actions/audit/plan/run/status/
resume/cancel/retry. UTCP exposes read-only workflow discovery, audit, plan, and
status. `.prd_plugin/config.json` controls the catalog, enabled workflow set,
state mutations, attempts, persisted-output bound, SessionStart/Stop routing,
and external judgment executor/profile/fallback. Use `/prd-workflow` or the
`project-deterministic-workflows` skill rather than rebuilding orchestration in
a host prompt.

Incremental verification remains focused and conservative. The full suite is a
deliberate release-boundary action in `hub.release`, not an automatic response
to each small change.

Non-deterministic report prose can be delegated without moving project truth or
provider credentials into this plugin. `reporting.delegation.*` configures an
off-by-default, provider-neutral policy: eligible tasks, the AI-Collab executor
contract, model profile, token/timeout bounds, source-reference validation, and
the `main`, `deterministic_only`, or `fail` fallback. `prd_config.py` exposes the
same settings (including comma-separated task lists). `prd_reporting.py` only
builds deterministic bundles and validates results; AI-Collab owns model
selection and execution.

AI-Collab's Substrate can also consume PRD Plugin state through the optional
adapter contract. It is disabled by default. Enable it directly in
`.prd_plugin/config.json` with `integrations.substrate.enabled: true` and set
`integrations.substrate.mode` to `observe`, or use the validated toggle surface:

```bash
python .prd_plugin/scripts/prd_config.py set integrations.substrate.enabled true
python .prd_plugin/scripts/prd_config.py set integrations.substrate.mode observe
```

`observe` projects canonical records, graph edges, and events. `coordinate`
discovers the live UTCP catalog and may call only explicitly enabled capability
groups. Ten nested automation switches independently control preflight,
knowledge/memory/context recall, notices, goal links, telemetry, reporting,
judgment, and verification. Every operation is source- and hash-bound; all
project-truth writes still go through PRD MCP.

Each installed repository owns `.prd_plugin/services.json`, declaring what it
consumes and provides, contract versions, capabilities, visibility, whether a
dependency is required, and its fallback. Use the `prd_service_*` MCP tools for
CRUD/audit. Safe plugin updates preserve the repository-owned manifest, while
the installer creates it for new and upgraded repositories.

Impact-scoped test selection is a separate off-by-default policy under
`verification.test_scope`. PRD Plugin collects the exact local git changes and
emits a deterministic plan; AI-Collab adds native impact neighbours, then PRD
Plugin maps nearby files to tests and executes argv-only configured or detected
commands. Any degraded, unmapped, broad, or unsafe selection widens to full
verification. Enable both the planner and its execution capability:

```bash
python .prd_plugin/scripts/prd_config.py set integrations.substrate.enabled true
python .prd_plugin/scripts/prd_config.py set integrations.substrate.mode coordinate
python .prd_plugin/scripts/prd_config.py set integrations.substrate.capabilities records,graph,events,impact,verification
python .prd_plugin/scripts/prd_config.py set verification.test_scope.enabled true
python .prd_plugin/scripts/prd_test_scope.py --repo-root . --execute
```

Exact changed files, explicit test ownership, and structural dependencies take
priority over prediction. Release/core changes, excessive breadth,
`impact_unavailable`, `impact_degraded`, or `unmapped_change` always widen or
fall back to full verification. The planner works without a remote or CI; those
systems may consume the same plan when present.

Stop-hook reflections are configured in the same file under `reflection`.
They are off by default. When `reflection.enabled` and `reflection.on_stop` are
true, the Stop hook asks the enabled questions from enabled categories, bounded
by `max_questions_per_stop`. The first Stop requests one concise reflection
pass and the next Stop succeeds, so reflection cannot recurse forever. The five
shipped questions cover behaviour quality, corrective action, retry value, and
harness friction. Answers stay in the host transcript/harness and never become
canonical project state.

Use `prd_config.py` for the global controls and
`prd_reflections.py` (or the four `prd_reflection_*` MCP tools) for complete
category/question CRUD, including activate/deactivate and moving questions.
Question creation allocates stable `RFQ-*` IDs under the shared state lock;
duplicate IDs and normalized question text are rejected.

## Script Install-Scope

PRD Plugin scripts are not blanket-installed into repositories that use the
plugin. The authoritative script install-scope policy is
`templates/script-install-scope.json`, and installed skeletons carry the same
policy at `.prd_plugin/templates/script-install-scope.json`.

Downstream repos should not receive a copied `scripts/` directory by default.
If a repo explicitly opts into local helper scripts, install only scripts marked
`downstream_runtime` or `downstream_optional`. Keep `hub_runtime` and
`plugin_development` scripts in the PRD Plugin hub/development repo or plugin
bundle. In particular, do not copy `release_check.py`,
`local_workflow_check.py`, `gap_audit.py`, `request_import.py`, or
`request_mailbox.py` into ordinary downstream repos.

## Repo-Local Skill Install

Host agents discover capabilities through their native delivery surfaces. Codex
and OpenAI/GPT agents read repo-local skills from
`.agents/skills/<skill-name>/SKILL.md`; opencode reads
`.opencode/skill/<skill-name>/SKILL.md` and the repo's `opencode.json` plugin
entry. Claude Code is plugin-primary by default: `prd-install --claude` writes
the repo-scoped `.claude/settings.json` marketplace + `enabledPlugins` config so
Claude loads the versioned `prd-plugin@prd-plugin` skills from the plugin.

Claude still supports a repo-pinned project copy when a repo explicitly wants
one: pass `--claude-skills`, or run
`python scripts/prd_install_skills.py --target-agent claude`, to populate
`.claude/skills/<skill-name>/SKILL.md`. None of the host agents read
`.prd_plugin/` as a skill source.

New repo skeleton installs include downstream runtime skills in `.agents/skills/`
and `.opencode/skill/` by default, and enable Claude through the plugin. Existing
repos can install or refresh the local PRD Plugin payload from the hub/plugin
bundle:

```bash
python scripts/prd_install.py D:/Projects/some-repo --codex --opencode --claude
```

This copies the repo skeleton (`.prd_plugin/`, `.codex-plugin/`, `.opencode/`,
`.claude-plugin/`, `.codex/hooks.json`), installs repo-local skills for
Codex/OpenAI and opencode, enables Claude plugin-primary support, and installs
allowed downstream runtime scripts. It skips existing files unless `--force` is
passed, and it refuses to install into the PRD Plugin hub repo itself. With
`--force`, existing `.prd_plugin/state/`, `.prd_plugin/ids/`, and configuration
are preserved. This is the safe update route. Never add `--yes` to a routine
update: it requests a destructive reset to skeleton defaults, is refused in
non-interactive sessions, and requires the exact interactive confirmation
phrase `RESET PRD STATE` when protected data exists. Plugin development and
hub-only scripts are never copied.

### Enforcement gate

`prd_gate.py` is the single enforcement validator that makes the policy
non-bypassable instead of advisory. `python .prd_plugin/scripts/prd_gate.py check`
fails on duplicate IDs, version-marker drift, `implemented` requests without
`graduated_to` (honoring `requests.implemented_requires_graduated_to`), stranded
outbox packages, malformed reflection configuration, and state-consistency
errors. It also exposes a tier decision
check (`prd_gate.py decision --action <class>`) that reads
`automation.autonomy_level`.

Hub release validation additionally runs
`python scripts/feature_skill_audit.py --repo-root .`. Its machine-readable
contract maps shipped capabilities, all workflow IDs, and all `/prd-*` commands
to current owning-skill guidance. `workflow_chml_audit.py` and
`local_workflow_check.py` include it, preventing byte-for-byte mirror parity
from hiding semantically stale skills.

Two enforcement surfaces ship with it: a host-neutral local git pre-commit hook
(`.githooks/pre-commit`, activate with `git config core.hooksPath .githooks`) and
a CI workflow (`.github/workflows/prd-gate.yml`). CI is the non-bypassable
backstop; the hook gives fast in-session feedback.

Installed helper scripts live under **`.prd_plugin/scripts/`** in the downstream
repo — `prd-install` does not create a repo-root `scripts/` directory. Skills
reference `scripts/<name>.py` from the hub's layout and guard each call with "if
available"; most referenced validators (`gap_audit.py`, `release_check.py`,
`local_workflow_check.py`, `version_advice.py`, `prd_doctor.py`,
…) are hub-only or optional by design and are not installed downstream.
`state_consistency_check.py` is the exception: it is installed by default beside
`prd_gate.py`, and the gate fails loudly if that validator is missing. The Codex
Stop hook (`.codex/hooks.json`) is guarded so it
no-ops when the optional `archive_automation_session.py` helper is absent, and it
targets `.prd_plugin/scripts/` downstream.

See the [Install Options](#install-options) section for the five explicit
flags and the full matrix in [`docs/INSTALL-MATRIX.md`](docs/INSTALL-MATRIX.md).

### npm install

PRD Plugin is published as an npm package. In a downstream repo:

```bash
npm install --save-dev prd-plugin
```

Then install or refresh the local PRD Plugin payload:

```bash
npx prd-install D:/Projects/some-repo --codex --opencode --claude
```

The npm package ships the same skeleton, skills, templates, and scripts as
the git distribution. When installed from npm, `prd-install` writes an
npm-based `opencode.json` plugin spec (`prd-plugin@^<version>`) instead of
a git URL.

`prd-install` also creates or refreshes a marked PRD Plugin block in the
downstream repo's root `.gitignore`. It preserves every project-owned line
outside that block while ignoring per-clone `.prd_plugin` runtime and request
transport, generated `request-report/` output, local command adapters, secret
and npm-local files, Python caches, logs, temporary files, and OS metadata.
Committed PRD Plugin state, tracking branches, drift exports, evidence, MCP
configuration, and `.codex/environments/environment.toml` remain trackable.

To preview what would be installed:

```bash
npx prd-install D:/Projects/some-repo --dry-run --codex --opencode --claude
```

### Install Options

`prd-install` has five explicit flags. Each flag controls which skills,
scripts, and config sections are installed.

| Flag | Purpose | Default |
| --- | --- | --- |
| `--codex` / `--no-codex` | Install Codex skill discovery under `.agents/skills/` | on |
| `--opencode` / `--no-opencode` | Install opencode skill discovery under `.opencode/skill/` and write `opencode.json` | on |
| `--claude` / `--no-claude` | Enable Claude Code plugin-primary support (`.claude/settings.json` marketplace + `enabledPlugins`, plus hooks and commands) | on |
| `--opencode-skill-inject` / `--no-opencode-skill-inject` | Add the `opencode-agent-skills` plugin and the `prd-plugin` skill permission to `opencode.json` | on when `--opencode` is on |

Claude repo-local skills are an explicit escape hatch, not the default:
`--claude-skills` also copies project-level skills into `.claude/skills/` for
repos that want a repo-pinned copy instead of relying only on the enabled plugin.

Common combinations:

```bash
# Codex only
npx prd-install . --codex --no-opencode --no-claude

# Claude Code only
npx prd-install . --claude --no-codex --no-opencode

# Claude Code only, with repo-pinned project skills
npx prd-install . --claude --claude-skills --no-codex --no-opencode

# opencode with auto-injection
npx prd-install . --codex --opencode --opencode-skill-inject

# Full install with all hosts and add-ons
npx prd-install . --codex --opencode --claude --opencode-skill-inject

# Disable auto-injection
npx prd-install . --opencode --no-opencode-skill-inject
```

When the same flag exists as both `--X` and `--no-X`, they are mutually
exclusive. Combining `--codex`, `--opencode`, and `--claude` is the default for
new installs; `--no-codex`, `--no-opencode`, or `--no-claude` lets you install
for a subset of host agents only.

The full skill, script, and config matrix is documented in
[`docs/INSTALL-MATRIX.md`](docs/INSTALL-MATRIX.md).

The deprecated `--target-agent codex|opencode|both` flag is still accepted
and maps to the new options. It will be removed in a future release.

### Optional helpers

To also install optional helpers such as `prd_doctor.py`:

```bash
npx prd-install . --codex --opencode --include-optional-scripts
```

or from npm:

```bash
npx prd-install D:/Projects/some-repo --include-optional-scripts --target-agent both
```

The `.agents/skills` and `.opencode/skill` copies are repo-local agent
capability; Claude gets the same capability from the enabled plugin unless
`--claude-skills` is used. The `.prd_plugin/` directory is project state,
templates, and method configuration. Both are needed for a self-contained
downstream repo. PRD Plugin hub/development workflows, such as changing the
plugin package itself, stay in the plugin hub/bundle and are not installed into
ordinary downstream host-agent skill directories.

Downstream installs include `project-local-integration` for local requests such
as "fold this into project truth." That workflow updates the current repo's
PRD Plugin artifacts, memory, traceability, health, evidence, changelog, and
request state without pulling in plugin release or version-bump behavior.

When a downstream repo has explicitly installed optional helpers, agents can
run a read-only setup and policy diagnostic before changing project truth:

```bash
python scripts/prd_doctor.py --repo-root .
```

The doctor checks PRD Plugin config, request-state parseability, stale or
privacy-sensitive requests, and copied hub/development scripts that violate the
script install-scope policy.

## MCP State Tools

PRD Plugin ships a stdio MCP server (`mcp/server.cjs`, bin: `prd-plugin-mcp`) so
agents read and write `.prd_plugin` state through validated tools instead of
hand-editing JSON. The hard invariants live in the server: timestamps are
stamped server-side (UTC), record creation allocates globally unused IDs under
one lock even when the registry is stale, pre-existing duplicate identities stop
the write, every mutation is schema-limited, and writes are atomic and preserve
the file's existing indentation. The commit gate remains the deterministic
backstop for repos that still hand-edit.

`prd-install` copies the server to `.prd_plugin/mcp/server.cjs` and merges this
entry into the repo's `.mcp.json` (existing servers are preserved):

```json
{
  "mcpServers": {
    "prd-plugin": { "command": "node", "args": [".prd_plugin/mcp/server.cjs"] }
  }
}
```

Tools (underscore names — the MCP tool-name charset forbids dots):

| Tool | Use it when |
| --- | --- |
| `prd_status` | Starting a session / choosing what to work on, including tracking-branch summaries. |
| `prd_find` | Finding a bounded compact set by kind, status, link, or text without scanning JSON, including promoted `MEM-*` and `DBR-*` tracking-branch records. |
| `prd_get` | Loading one exact full record by ID, including promoted memory and tracking branches. |
| `prd_create` | Creating ordinary TRK/REQ/HLT state; allocation happens inside the locked write. |
| `prd_update` | Updating permitted mutable fields and valid lifecycle states. |
| `prd_link` | Symmetrically linking two existing records without duplicate links; promoted `MEM-*` can be linked while remaining non-mutable. |
| `prd_reflection_list` | Listing categorized questions and their configured/effective activation without scanning config JSON. |
| `prd_reflection_create` | Creating a category or a question; question IDs are allocated safely as `RFQ-*`. |
| `prd_reflection_update` | Editing, activating, deactivating, renaming, or moving one category/question. |
| `prd_reflection_delete` | Deleting a question or an empty category; non-empty category deletion requires explicit cascade. |
| `prd_open_tracking_branch` | Before parallel fan-out: the lead allocates one DBR tracking file per worker without touching canonical TRK state. |
| `prd_update_tracking_branch` | A worker records progress only in its assigned branch file; no canonical ID or registry write occurs. |
| `prd_promote_tracking_branch` | After worker branches merge: the lead serially applies one branch to canonical TRK state with conflict checks and idempotent DBR-MERGE provenance. |
| `prd_next_id` | Allocating an embedded planning ID; never use it before creating a record-backed ID. |
| `prd_open_goal` | Starting a piece of work: opens the TRK goal the stop-guard works toward. |
| `prd_update_goal` | Recording progress / moving status (one vocabulary: open, active, complete, resolved, deferred, parked, superseded). |
| `prd_close_goal` | Finishing: requires a linked `EV-*` or an explicit no-evidence reason. |
| `prd_file_request` | Filing a bug/change/compat REQ (lands as `proposed`) — the write path for headless sub-agents too. |
| `prd_record_evidence` | About to claim done/fixed/passing: record the proof first (optional markdown under `docs/evidence/`). |
| `prd_record_decision` | Recording a durable decision with provenance (`decided_by`, `autonomy_tier`, `linked_ids` required). |
| `prd_log_change` | Appending a CHG changelog record. |
| `prd_validate` | Pre-flighting the commit gate before you commit. |

`prd_status` and `prd_validate` shell out to the canonical Python helpers
(`prd_status.py`, `prd_gate.py`) so their output matches `/prd-status` and the
gate exactly. The server is CommonJS with zero runtime dependencies and works
against the CWD's `.prd_plugin/` (or `PRD_PLUGIN_ROOT`).

For parallel worktrees, the lead must open and commit one tracking branch per
worker before fan-out, then launch it with `PRD_WORKER_SESSION=1`,
`PRD_TRACKING_BRANCH_ID=<DBR-*>`, and `PRD_TRACKING_BRANCH_OWNER=<owner>`.
Workers update distinct files under
`.prd_plugin/state/tracking-branches/`; after code branches are merged, the lead
promotes each branch serially. Separate worktrees do not share a filesystem lock
or live registry, so workers never allocate canonical numeric IDs. When
`tracking.branching.require_for_parallel_agents` is true, the MCP runtime rejects
every canonical state/registry write from a worker and accepts only
`prd_update_tracking_branch` on its assigned branch. Workers leave requested
non-TRK state changes as branch notes for the lead to apply serially.

## Fold It In Workflow

The `project-fold-it-in` skill is the default workflow for cross-cutting plugin
changes. Use it when a change needs to be integrated across method docs, skills,
templates, config, state, scripts, workflows, validation, release hygiene, and
versioning rather than applied as an isolated edit.

In downstream repos, use `project-local-integration` instead. It handles
current-repo project-truth integration and explicitly excludes PRD Plugin
package release mechanics.

When the user asks to fold a change into the plugin workflow, the workflow
creates or checks an active goal before implementation, keeps the visible
progress plan aligned with it, and reports goal status at closeout.

## Project Health

Project health checks summarize whether the planning and memory graph is safe to
continue from. Health findings use `HLT-*` IDs and are stored in
`.prd_plugin/state/health.json`.

Health checks do not replace traceability reviews. They are compact operational
snapshots for agents: stale tracking records, orphan requirements, missing
evidence, weak memory provenance, unpromoted document branches, and other
attention points.
Every PRD Plugin skill has an explicit staleness responsibility so stale
requests, tracking records, health findings, request transport, automation
locks, and scheduler state are either resolved, refreshed with evidence, or
left as visible follow-up work.

## Request Intake

Outside agents should not directly change project truth for speculative ideas,
bug reports, or compatibility concerns. They should append a `REQ-*` record to
`.prd_plugin/state/requests.json` with their proposed change or issue,
rationale, affected IDs, provenance, severity, and risk. Before adding a new
`REQ-*`, search existing requests and `thread.messages` for the same issue. If a
bug still reproduces on a later version, append a `MSG-*` update to the original
request thread and update affected-version metadata rather than opening a new
request.

Request intake uses a hub-and-spoke privacy model. This `prd-plugin` repo is
the upstream hub for plugin-level requests and discussions. Repos using the
plugin should keep only their own local requests, issues, and messages unless
they explicitly submit a request upstream.

Accepted requests can graduate into `TRK-*`, `DBR-*`, `PRD-*`, `CHG-*`, or
other normal project artifacts. Rejected requests stay recorded with a decision
and rationale.

Requests can be discussed without changing project truth by adding `MSG-*`
records to the request's `thread.messages` array. Use `in_review` while the
request is being shaped and `needs_info` when the requester must reply before a
decision can be made. Only messages marked for upstream visibility should be
included in sanitized upstream submissions.

The request-check automation is intended to validate and triage requests
autonomously by risk band, not stop at a read-only summary.
Low- or medium-risk bug submissions with clear reproduction steps and a bounded
fix must continue into the bug investigation workflow, failing test, fix,
verification, request-state update, and commit unless the report is missing
required detail, unsafe, unbounded, or explicitly blocked by the user.

When the user asks to check messages, use the current repository's PRD Plugin
message surface first: call the `prd_check_messages` MCP tool.

`prd_check_messages` is a first-class MCP tool. If MCP is unavailable, run
`python .prd_plugin/scripts/message_check.py --repo-root . --config
.prd_plugin/config.json` downstream, or `python scripts/message_check.py
--repo-root . --config .prd_plugin/config.json` in this hub checkout. The
message check summarizes new and imported inbox packages, outgoing outbox
packages, scoped mailbox files, pending replies, and unresolved request-thread
messages in one report. Do not substitute an unrelated chat, email, or
collaboration inbox.

**Requests about PRD Plugin itself submit themselves.** File through the
`prd_file_request` MCP tool and nothing else is required: the record is
classified, flagged `upstream_submission: true`, exported as a sanitized package
to `.prd_plugin/outbox/`, and delivered into the hub inbox when one is
configured. Ordinary project requests are left alone.

Supplying `scope: local` explicitly is an authoritative routing decision: the
tool records `upstream_submission: false` and does not run autosubmit. Omit the
scope to use automatic classification. Canonical paths under `.prd_plugin/`
remain project state and do not count as references to the PRD Plugin product.

Installed configuration already points `config.requests.upstream_hub_path` at
the workspace hub, `D:\Projects\prd-plugin`, so plugin-owned requests are
delivered without a separate routing step. `PRD_UPSTREAM_HUB` remains an
explicit runtime override. If neither route resolves to a valid hub, the package
waits in the outbox. For a record written some other way, run the same pipeline
by hand:

```bash
python scripts/request_autosubmit.py --request-id REQ-001
```

It no-ops on ordinary requests and never fails a filing. `prd_gate.py` warns
(`unsubmitted_plugin_request`) for as long as a plugin bug sits unsubmitted.

To build a package without the classifier — any request, submitted deliberately:

```bash
python scripts/request_export.py --request-id REQ-001
```

That writes a portable upstream package to `.prd_plugin/outbox/`.

The hub repo stages incoming packages in `.prd_plugin/inbox/`, then publishes
repo-scoped replies through `.prd_plugin/mailboxes/<repo-id>/`. Downstream repos
pull only their own mailbox and merge request statuses/messages locally:

```bash
python scripts/request_pull.py --mailbox .prd_plugin/mailboxes/my-repo/mailbox.json
```

To reply from a downstream repo:

```bash
python scripts/request_reply.py --request-id REQ-001 --visibility upstream --body "Here are the repro steps..."
python scripts/request_export.py --request-id REQ-001
```

A PRD Plugin bug that lives only in local request state is an unreported bug.
Filing through `prd_file_request` completes the report for you; a record written
any other way needs `request_autosubmit.py` (or the manual
`request_export.py` + `request_import.py` pair) before the report is complete,
unless the hub or import path is unavailable and that blocker is reported.

## Automation Guard

Recurring request/mailbox checks should use a single-run lock before reading or
acting on intake state:

```bash
python scripts/automation_guard.py begin --name request-check
python scripts/automation_guard.py complete --name request-check --run-id <run-id>
```

Locks and pending markers live under `.prd_plugin/local/automation/`, which is
ignored by git. If a five-minute tick starts while a previous run is active,
the new tick records a pending follow-up and exits. When the active run
completes, it reports whether another pass is needed.

Treat scheduler state as a separate check from the local lock. The local guard
shows whether a run is active, stale, or pending, but it does not show whether
future ticks are still scheduled. To answer recurrence or pause/resume
questions, also inspect the host agent's app-side automation record (for
Codex, the file at
`%USERPROFILE%/.codex/automations/<automation-id>/automation.toml`; for
opencode, the equivalent host-managed schedule record) and read its `kind`,
`rrule`, and `status`.

Completed automation runs may be archived automatically from a Stop hook when
the transcript proves the session came from a Codex automation prompt with a
known Automation ID. Use the host agent's archive semantics (for Codex,
`codex archive <session-id>`) rather than moving or deleting transcript files
directly. Stop-hook archive scripts should not print arbitrary diagnostics to
stdout in normal hook mode because the host agent may parse stdout as hook
protocol output; use an explicit diagnostic flag such as `--json` for manual
checks.

## Version Advice

Repos using PRD Plugin can check what changed before bumping their installed
plugin version. Run `version_advice.py` from the PRD Plugin hub/development
repo or plugin bundle, not from a blanket-copied downstream `scripts/`
directory:

```bash
python scripts/version_advice.py --installed-repo D:/Projects/some-repo
```

The script reads the downstream repo's installed version, compares it with this
repo's `.prd_plugin/state/releases.json`, lists newer releases, and recommends
`safe_to_update`, `review_first`, or `blocked`. When review is needed, create a
`version_change` request with the current version, requested version, target
repo, migration blockers, and breaking-change concerns.

To append that request automatically when review is advised:

```bash
python scripts/version_advice.py --installed-repo D:/Projects/some-repo --write-request --requests D:/Projects/some-repo/.prd_plugin/state/requests.json
```

Before bumping this plugin's version, run the gap audit:

```bash
python scripts/gap_audit.py --target-version 0.5.30
```

The primary PRD Plugin development workflow check does not require a GitHub
remote:

```bash
python scripts/local_workflow_check.py
```

It validates structured files, runs full unittest discovery, checks state
consistency, checks script install-scope policy, runs gap audit, version
advice, release hygiene, and generates request and message reports. The request report
analyzes `.prd_plugin/state/requests.json`, counts outstanding, denied,
approved, implemented, in-review, and needs-info requests, and flags implemented
requests that do not link to the plugin artifacts they graduated into. It also
breaks intake down by request type, severity, request-thread message counts,
unresolved threads, stale requests, and privacy warnings. It flags stale
outstanding requests using `requests.stale_after_days` and stale accepted
requests using `health.accepted_request_stale_after_days`.

The state consistency check verifies that evidence and session summaries do not
claim missing `MEM-*`, `TRK-*`, `CHG-*`, `OBS-*`, or `SES-*` records, registry
counters do not skip absent canonical records, and state or fixture timestamps
are not in the future relative to validation time.

The optional GitHub Actions workflow at
`.github/workflows/request-intake-report.yml` is only a wrapper around the same
local command for repos that have GitHub configured. Plugin-impacting changes
should bump `.codex-plugin/plugin.json`, `.opencode/plugin.json`, and
`.claude-plugin/plugin.json` together, and skill changes should update related
docs or templates so repos using the plugin know what changed.

## System Tests

The `system_tests/` directory contains a downstream integration test harness for
REQ-028. It creates a temporary downstream repo, installs PRD Plugin from the
local hub source, injects a canary `.env`, and drives an agent through scripted
user prompts using either a deterministic mock driver or the opencode CLI
simulated agent driver. After each scenario it asserts:

- durable state files are created and cross-linked by ID
- canonical planning/evidence/decision artifacts exist
- `state_consistency_check.py` reports no errors
- no secrets leak into output, logs, or persisted files
- no hub-only scripts run and no hub repo files are touched
- git push/merge only happen with explicit consent

Run the mock-driven system tests (no opencode required):

```bash
python -m pytest system_tests -v
```

The opencode-driven scenario tests run automatically when the opencode CLI is
installed and are skipped otherwise. Set `OPENCODE_MODEL` to override the
default model (`opencode/deepseek-v4-flash-free`):

```bash
set OPENCODE_MODEL=opencode/deepseek-v4-flash-free
python -m pytest system_tests/scenarios/ -v
```

You can also include system tests in the local workflow check:

```bash
python scripts/local_workflow_check.py --include-system-tests
```

## Current Version Scope

The current package contains host-agent-neutral method docs, templates,
structured agent state, request intake, project health checks, configuration,
a downstream-safe installer (`scripts/prd_install.py`), repo-local skill
installation, and a local request-report script, state consistency validator,
mandatory upstream reporting rules for downstream PRD Plugin bug reports,
sanitized upstream request export helper, release hygiene checks, version advice
script, pre-bump gap audit, a PRD Plugin development local workflow check runner,
downstream-safe local integration, Superpowers-adapted PRD-native planning, TDD,
debugging, and verification skills, read-only downstream `prd_doctor.py`
diagnostics, read-only `message_check.py` inbox/outbox/mailbox/thread summaries,
scoped request mailboxes, guarded recurring automation with explicit app-side
scheduler verification, protocol-safe automation-only session archiving through
a Stop hook, a risk-based autonomous request-check workflow, request-thread
deduplication for persistent bugs and repeated repros, autonomous investigation
and commit requirements for clear low/medium-risk bug reports, workflow-wide
staleness checks, an end-to-end planning lifecycle workflow, canonical JSON
planning artifacts with Markdown exports only on human request, plus a default
goal-backed fold-it-in integration workflow, and a complete deterministic
workflow authority with validated LLM judgment overlays, WFR receipts, CLI,
MCP/UTCP management, hook routing, and downstream installer migration.

## OpenCode Deployment

Starting with v0.5.30, PRD Plugin ships an opencode-compatible delivery layer
alongside the Codex layer:

- `.opencode/plugin.json` — opencode plugin manifest (mirrors the Codex
  manifest's `name`, `version`, `skills`, `interface`, and `capabilities`).
- `.opencode/skill/<skill>/SKILL.md` — the same downstream_runtime skill set
  that ships under `.agents/skills/`, discoverable by opencode agents.
- `prd_install_skills.py --target-agent opencode` (or `--target-agent both`)
  to populate the opencode target on demand.
- `templates/repo-skeleton/.opencode/` — pre-seeded for new downstream repos.

The method itself (ID scheme, state schema, request/evidence/health workflow,
skills) is host-agent neutral. Only the discovery paths and a few host-agent
references in the docs (e.g. Codex's `%USERPROFILE%/.codex/...` automation
record path) needed to change. Existing Codex consumers keep working without
modification.

## Claude Code Deployment

PRD Plugin ships a Claude Code delivery layer alongside the Codex and opencode
layers:

- `prd-install --claude` is plugin-primary: it writes the repo-scoped
  `.claude/settings.json` marketplace + `enabledPlugins` config for
  `prd-plugin@prd-plugin`, plus `.claude/hooks/` and `.claude/commands/`.
- `.claude-plugin/plugin.json` + `.claude-plugin/marketplace.json` make the hub
  repo installable as a Claude Code plugin via `/plugin marketplace add`, loading
  the plugin's standard top-level `skills/` directory directly. The Claude
  manifest intentionally does not use the Codex/opencode `skills` field; its
  `version` tracks `.codex-plugin/plugin.json` and is checked by
  `release_check.py`.
- `.claude/skills/<skill>/SKILL.md` remains supported for repo-pinned installs.
  Use `prd-install --claude --claude-skills` or
  `prd_install_skills.py --target-agent claude` when a repo intentionally wants
  project-level Claude skills instead of relying only on the enabled plugin.
- `templates/repo-skeleton/.claude/` carries Claude hooks, commands, and
  settings. The installer skips skeleton `.claude/skills/` by default; the
  canonical writer for that target is the explicit `--claude-skills` escape hatch.

The `SKILL.md` frontmatter (`name` + `description`) is already the format Claude
Code expects, so the same canonical skill content can be used by the plugin and
by the optional repo-local `.claude/skills/` copy.
