🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

pi-agent-codebase-workflows

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

pi-agent-codebase-workflows - npm Package Compare versions

Comparing version
0.3.2
to
0.5.0
+5
prompts/migrate-structured-docs.md
---
description: "Migrate legacy prose docs to structured YAML"
argument-hint: "[focus]"
---
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:structured-docs-migration`. Convert deprecated prose-style docs into canonical YAML under the resolved structured docs root. Do not generate Markdown fallback artifacts; root `AGENTS.md` is allowed for harness interoperability when explicitly produced. Focus: $ARGUMENTS.
# Structured Artifact API Runtime Reference
Read this file only when creating/updating structured artifacts or validating artifact shape.
## Schema loading
Before writing any artifact, read this shared schema set only for outputs being written:
- common envelope: `schemas/common.schema.json`
- artifact schema: `schemas/<artifact-file-base>.schema.json`
Examples:
- `risk-register.yaml` -> `schemas/risk-register.schema.json`
- `repo-inventory.yaml` -> `schemas/repo-inventory.schema.json`
- `agent-operating-guide.yaml` -> `schemas/agent-operating-guide.schema.json`
Do not read all schemas. Do not use templates.
## Artifact to schema mapping
- `scopes.yaml` -> `scopes.schema.json`
- `repo-inventory.yaml` -> `repo-inventory.schema.json`
- `project-intent.yaml` -> `project-intent.schema.json`
- `architecture.yaml` -> `architecture.schema.json`
- `data-flow.yaml` -> `data-flow.schema.json`
- `data-model.yaml` -> `data-model.schema.json`
- `invariants.yaml` -> `invariants.schema.json`
- `dependency-rules.yaml` -> `dependency-rules.schema.json`
- `design-issues.yaml` -> `design-issues.schema.json`
- `risk-register.yaml` -> `risk-register.schema.json`
- `change-guide.yaml` -> `change-guide.schema.json`
- `testing-strategy.yaml` -> `testing-strategy.schema.json`
- `validation-baseline.yaml` -> `validation-baseline.schema.json`
- `contracts.yaml` -> `contracts.schema.json`
- `adr.yaml` -> `adr.schema.json`
- `agent-operating-guide.yaml` -> `agent-operating-guide.schema.json`
## Runtime rule
Schemas are contracts. Skills/prompts describe behavior. Project docs outside these shared runtime refs are maintainer aids and are not runtime instructions unless user explicitly asks about this package itself.
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/adr.schema.json",
"title": "adr",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"adrs"
],
"properties": {
"artifact": {
"const": "adr"
},
"adrs": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^adr:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/agent-operating-guide.schema.json",
"title": "agent-operating-guide",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"rules",
"required_workflows",
"validation_expectations",
"forbidden_shortcuts"
],
"properties": {
"artifact": {
"const": "agent_operating_guide"
},
"rules": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string"
}
},
"additionalProperties": true
}
},
"required_workflows": {
"type": "array"
},
"validation_expectations": {
"type": "object"
},
"forbidden_shortcuts": {
"type": "array"
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/architecture.schema.json",
"title": "architecture",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"architecture",
"components",
"dependency_direction",
"execution_flows",
"side_effect_boundaries"
],
"properties": {
"artifact": {
"const": "architecture"
},
"architecture": {
"type": "object"
},
"components": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^component:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
},
"dependency_direction": {
"type": "object"
},
"execution_flows": {
"type": "array"
},
"side_effect_boundaries": {
"type": "array"
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/change-guide.schema.json",
"title": "change-guide",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"change_workflows",
"routing",
"doc_update_rules",
"checklists"
],
"properties": {
"artifact": {
"const": "change_guide"
},
"change_workflows": {
"type": "array"
},
"routing": {
"type": "object"
},
"doc_update_rules": {
"type": "array"
},
"checklists": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string"
}
},
"additionalProperties": true
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/common.schema.json",
"title": "Structured Agent Artifact Envelope",
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns"
],
"properties": {
"schema_version": {
"const": "1.0"
},
"artifact": {
"type": "string"
},
"artifact_id": {
"type": "string",
"pattern": "^(scope|component|entity|invariant|risk|contract|flow|command|issue|adr|testplan|repo):[a-z0-9][a-z0-9._/-]*$"
},
"scope": {
"type": "object",
"required": [
"id",
"kind",
"source",
"docs_path"
],
"properties": {
"id": {
"type": "string",
"pattern": "^scope:[a-z0-9][a-z0-9._/-]*$"
},
"kind": {
"enum": [
"repo",
"path",
"domain"
]
},
"source": {
"type": [
"string",
"null"
]
},
"docs_path": {
"type": "string"
}
},
"additionalProperties": true
},
"status": {
"enum": [
"planned",
"partial",
"current",
"stale",
"deprecated"
]
},
"evidence_mode": {
"enum": [
"planned",
"observed",
"mixed"
]
},
"last_validated": {
"type": [
"string",
"null"
]
},
"owners": {
"type": "object",
"required": [
"primary",
"source_of_truth"
],
"properties": {
"primary": {
"type": [
"string",
"null"
]
},
"source_of_truth": {
"type": "boolean"
}
},
"additionalProperties": true
},
"depends_on": {
"type": "object",
"properties": {
"artifacts": {
"type": "array"
},
"scopes": {
"type": "array"
},
"contracts": {
"type": "array"
}
},
"additionalProperties": true
},
"evidence": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "^ev:[a-z0-9][a-z0-9._/-]*$"
},
"kind": {
"type": "string"
},
"path": {
"type": [
"string",
"null"
]
},
"symbol": {
"type": [
"string",
"null"
]
},
"command": {
"type": [
"string",
"null"
]
},
"observation": {
"type": "string"
},
"confidence": {
"enum": [
"low",
"medium",
"high"
]
}
},
"additionalProperties": true,
"required": [
"id",
"kind",
"path",
"symbol",
"command",
"observation",
"confidence"
]
}
},
"unknowns": {
"type": "array"
},
"notes": {
"type": [
"string",
"null"
]
},
"replacement_ref": {
"type": "string"
}
},
"additionalProperties": true
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/contracts.schema.json",
"title": "contracts",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"contracts"
],
"properties": {
"artifact": {
"const": "contracts"
},
"contracts": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^contract:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/data-flow.schema.json",
"title": "data-flow",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"flows"
],
"properties": {
"artifact": {
"const": "data_flow"
},
"flows": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^flow:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/data-model.schema.json",
"title": "data-model",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"entities",
"lifecycles",
"serialized_formats"
],
"properties": {
"artifact": {
"const": "data_model"
},
"entities": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^entity:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
},
"lifecycles": {
"type": "array"
},
"serialized_formats": {
"type": "array"
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/dependency-rules.schema.json",
"title": "dependency-rules",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"layers",
"rules",
"allowed_dependencies",
"violations",
"coupling_hotspots"
],
"properties": {
"artifact": {
"const": "dependency_rules"
},
"layers": {
"type": "array"
},
"rules": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string"
}
},
"additionalProperties": true
}
},
"allowed_dependencies": {
"type": "array"
},
"violations": {
"type": "array"
},
"coupling_hotspots": {
"type": "array"
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/design-issues.schema.json",
"title": "design-issues",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"issues"
],
"properties": {
"artifact": {
"const": "design_issues"
},
"issues": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^issue:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/invariants.schema.json",
"title": "invariants",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"invariants"
],
"properties": {
"artifact": {
"const": "invariants"
},
"invariants": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^invariant:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/project-intent.schema.json",
"title": "project-intent",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"intent"
],
"properties": {
"artifact": {
"const": "project_intent"
},
"intent": {
"type": "object"
},
"goals": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string"
}
},
"additionalProperties": true
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/repo-inventory.schema.json",
"title": "repo-inventory",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"project",
"directories",
"entry_points",
"commands",
"external_boundaries",
"configs"
],
"properties": {
"artifact": {
"const": "repo_inventory"
},
"project": {
"type": "object"
},
"directories": {
"type": "array"
},
"entry_points": {
"type": "array"
},
"commands": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^command:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
},
"external_boundaries": {
"type": "array"
},
"configs": {
"type": "array"
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/risk-register.schema.json",
"title": "risk-register",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"risks"
],
"properties": {
"artifact": {
"const": "risk_register"
},
"risks": {
"type": "array",
"items": {
"type": "object",
"required": [
"id",
"title",
"severity",
"confidence",
"status",
"evidence_refs"
],
"properties": {
"id": {
"type": "string",
"pattern": "^risk:[a-z0-9][a-z0-9._/-]*$"
},
"title": {
"type": "string"
},
"severity": {
"enum": [
"low",
"medium",
"high",
"critical"
]
},
"confidence": {
"enum": [
"low",
"medium",
"high"
]
},
"status": {
"type": "string"
},
"evidence_refs": {
"type": "array",
"items": {
"type": "string",
"pattern": "^ev:[a-z0-9][a-z0-9._/-]*$"
}
}
},
"additionalProperties": true
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/scopes.schema.json",
"title": "scopes",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"scopes",
"routing_rules"
],
"properties": {
"artifact": {
"const": "scopes"
},
"scopes": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^scope:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
},
"routing_rules": {
"type": "array"
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/testing-strategy.schema.json",
"title": "testing-strategy",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"test_structure",
"coverage_gaps",
"risk_to_test_priorities",
"known_blockers"
],
"properties": {
"artifact": {
"const": "testing_strategy"
},
"test_structure": {
"type": "array"
},
"coverage_gaps": {
"type": "array"
},
"risk_to_test_priorities": {
"type": "array"
},
"known_blockers": {
"type": "array"
},
"test_plans": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^testplan:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
}
}
}
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.invalid/pi-agent-codebase-workflows/validation-baseline.schema.json",
"title": "validation-baseline",
"allOf": [
{
"$ref": "common.schema.json"
}
],
"type": "object",
"required": [
"schema_version",
"artifact",
"artifact_id",
"scope",
"status",
"evidence_mode",
"last_validated",
"owners",
"depends_on",
"evidence",
"unknowns",
"commands",
"blockers",
"recommended_order"
],
"properties": {
"artifact": {
"const": "validation_baseline"
},
"commands": {
"type": "array",
"items": {
"type": "object",
"required": [
"id"
],
"properties": {
"id": {
"type": "string",
"pattern": "^command:[a-z0-9][a-z0-9._/-]*$"
}
},
"additionalProperties": true
}
},
"blockers": {
"type": "array"
},
"recommended_order": {
"type": "array"
}
}
}
---
name: structured-docs-migration
description: Migration workflow from deprecated prose-style docs/agent Markdown artifacts to canonical structured YAML artifacts under a resolved structured docs root. No fallback or Markdown generation.
---
# Structured Docs Migration
Goal: convert legacy prose-style documentation into canonical structured YAML artifacts for agent-first ingestion.
## Structured Artifact API Contract
Legacy prose artifacts are deprecated. Do not create, update, or rely on `docs/agent/*.md`, scoped prose docs, or generated human-readable Markdown views. Use structured YAML for canonical artifacts. Root `AGENTS.md` remains a harness interoperability file and may be generated/updated only by workflows that explicitly say so.
Resolved structured docs root:
Treat `docs/agent/api` as a logical layout rooted at a resolved structured docs root, not a fixed repo path.
Resolution rules:
1. Resolve `workspace_root` with `git rev-parse --show-toplevel 2>/dev/null` or fallback to `pwd`.
2. `safe-start` always creates and uses the initial repo-local root: `<workspace_root>/docs/agent/api`.
3. `structured-docs-migration` uses repo-local only when `<workspace_root>/docs/agent/api` already exists.
4. Otherwise use the global overlay root: `~/.pi/agent/workspaces/<workspace-fingerprint>/docs/agent/api`.
5. Derive `<workspace-fingerprint>` deterministically from the canonical `workspace_root` path and keep it stable for the same workspace.
6. Do not create new repo-local structured docs in unadopted repos unless the user explicitly asks for repo-local adoption there.
Logical structured layout under the resolved docs root:
```text
repo/
scopes.yaml
repo-inventory.yaml
project-intent.yaml
architecture.yaml
data-flow.yaml
data-model.yaml
invariants.yaml
dependency-rules.yaml
design-issues.yaml
risk-register.yaml
change-guide.yaml
testing-strategy.yaml
validation-baseline.yaml
contracts.yaml
adr.yaml
agent-operating-guide.yaml
scopes/
by-path/<repo-relative-path>/...
by-domain/<slug>/...
```
Every structured artifact must conform to `../_shared/references/schemas/common.schema.json` plus its artifact-specific schema. Do not inline, invent, or vary envelope fields.
Stable IDs required: `scope:*`, `component:*`, `entity:*`, `invariant:*`, `risk:*`, `contract:*`, `flow:*`, `command:*`, `issue:*`, `adr:*`, `testplan:*`.
Ownership rules:
- `scopes`: scope routing, ownership, cross-scope discovery only.
- `repo-inventory`: file tree, commands index, entry points, external boundaries, configs.
- `validation-baseline`: command status, blockers, recommended validation order.
- `project-intent`: goals, users, journeys, non-goals, constraints, assumptions.
- `architecture`: components, architecture style, side-effect boundaries, high-level flow refs.
- `data-flow`: typed flow graph/steps, inputs, outputs, error states.
- `data-model`: entities, IDs, schemas, relationships, lifecycles, serialized formats.
- `invariants`: rules, forbidden states, enforcement locations, invariant-test refs.
- `dependency-rules`: layers, allowed/forbidden dependencies, violations, coupling hotspots.
- `design-issues`: structural drift, deferred decisions, ambiguity, ownership gaps.
- `risk-register`: failure modes, severity/confidence, affected refs, suggested tests/fixes.
- `contracts`: cross-scope APIs, schemas, events, generated clients, DB/file/deployment/env contracts.
- `testing-strategy`: test topology, coverage gaps, risk-to-test priorities.
- `change-guide`: workflow routing and checklists; references owner artifacts, duplicates no facts.
- `adr`: structured decision records with bounded prose fields.
- `agent-operating-guide`: structured source for agent operating rules. Root `AGENTS.md` may mirror this in compact harness-readable Markdown when produced by safe-start or codebase-recon Pass 6.
Redundancy rule: define each fact in its owner artifact exactly once. Other artifacts reference IDs.
Current truth rule: canonical YAML artifacts represent current state, not audit history. Remove resolved or superseded records from canonical owner artifacts by default. Keep them only when another live record still references them or an active migration requires temporary continuity. Use Git history, PRs, issues, or ADRs for audit/history.
Prose rule: bounded prose allowed only in `summary`, `notes`, `rationale`, `context`, `decision`, `recommended_action`, and similar scalar fields.
Scope rule: if focus is path-like, write under `<docs-root>/scopes/by-path/<focus>/`; otherwise under `<docs-root>/scopes/by-domain/<slug>/`. Always update `<docs-root>/repo/scopes.yaml`.
## Runtime Schema Loading
When a workflow creates, updates, migrates, or validates structured artifacts, read `../_shared/references/artifact-api.md` first. Then read only the shared skill package schemas needed for the artifacts being written:
- `../_shared/references/schemas/common.schema.json`
- `../_shared/references/schemas/<artifact-file-base>.schema.json`
Do not read all schemas. Do not use templates. Schemas are runtime API contracts; project docs outside the shared runtime refs are maintainer aids unless the user asks about this package itself.
## Structured Artifact Write/Update Protocol
Use this protocol whenever creating or updating YAML artifacts.
### 1. Scope and owner resolution
1. Resolve scope first from task/focus and `<docs-root>/repo/scopes.yaml` when present.
2. Path focus uses longest prefix match; domain focus requires explicit domain/contract/task evidence.
3. Select the single owner artifact for each fact using the ownership rules above.
4. Never duplicate owner facts in router/checklist artifacts; reference stable IDs instead.
### 2. Read-before-write
1. Read the existing target YAML if it exists.
2. Read directly referenced owner artifacts needed to preserve refs and avoid duplication.
3. If target YAML is absent, create it with the common envelope and artifact-specific top-level keys.
4. Preserve unknown fields unless they conflict with this protocol; do not silently drop agent/user-added structured data.
### 3. Stable ID generation
1. Reuse existing IDs whenever the semantic object is the same, even if name/path changed.
2. New IDs use deterministic slugs from owner scope + semantic name: `risk:<slug>`, `entity:<slug>`, `component:<slug>`, etc.
3. If two objects slug-collide, append shortest stable discriminator from path/component/contract, not a random suffix.
4. Never renumber IDs because order changed.
### 4. Upsert semantics
For each discovered fact/object:
1. Match existing record by ID first.
2. If no ID match, match by stable source-of-truth fields: path+symbol, contract source path, command string+cwd, entity name+owner scope, rule owner+kind.
3. If matched, update only changed fields, append/refresh evidence, and preserve unrelated fields.
4. If unmatched, insert new record in deterministic order by ID or explicit `order` field.
5. If an existing observed record is resolved, superseded, or no longer supported, delete it from the canonical owner artifact by default.
6. Keep a record with `status: stale` or `deprecated` only when a live reference still depends on it or an active migration needs temporary continuity. Add evidence/unknown explaining why, and link replacement ID when known.
7. Delete accidental duplicates, malformed records, and unreferenced resolved/superseded records, and mention deletion in final response.
### 5. Evidence and confidence
1. Every observed record needs at least one evidence ref with file/symbol/command/doc/diff observation.
2. Planned records may use `evidence_mode: planned` and confidence `low` or `medium`.
3. Mixed records must separate observed fields from planned/assumed fields via evidence refs or `unknowns`.
4. Do not upgrade `status: current` or confidence `high` without source or command evidence.
### 6. Reference integrity
Before writing final artifacts:
1. Check every `*_ref`, `*_refs`, and `depends_on` ID points to a record in the same artifact set or is explicitly listed as external/unknown.
2. Prefer adding missing owner records as compact stubs over leaving dangling refs.
3. For cross-scope refs, ensure `scopes.yaml` and `contracts.yaml` identify owner/consumer relationship.
4. If ownership is ambiguous, create/update `design-issues.yaml` with `kind: ownership_gap` and reference it.
### 7. Status transitions
Allowed transitions:
- `planned -> partial -> current`
- `current -> stale -> current`
- `current|stale|partial -> deprecated`
Rules:
- `current` requires sufficient observed evidence for the represented scope.
- `partial` means useful but incomplete evidence.
- `stale` means contradicted by newer source evidence or missing source path. Use it as a temporary migration/quarantine state, not a permanent archive state.
- `deprecated` means superseded; include `replacement_ref` when known. Use it only when a live reference still needs continuity during migration; otherwise remove the record from the canonical artifact.
### 8. Deterministic formatting
1. Use YAML with two-space indentation.
2. Use stable top-level key order: envelope keys first, artifact-specific keys next.
3. Sort unordered arrays by `id`; keep ordered flow/checklist arrays by `order`.
4. Use `null`, `[]`, or `{}` consistently rather than omitting required envelope fields.
5. Keep prose scalar fields concise; no long narrative blocks.
### 9. Validation before completion
Perform best-effort validation after writing:
1. Re-read changed YAML for parse/syntax sanity when practical.
2. Validate against the shared schemas by inspection/re-read: envelope keys, artifact-specific top-level keys, required arrays/items, stable ID prefixes, and obvious dangling refs.
3. Verify no legacy Markdown artifacts were created or updated by the workflow, except root `AGENTS.md` when explicitly produced for harness interoperability.
4. Report changed YAML files, validation performed, unresolved unknowns, and any records intentionally retained or pruned as part of compaction.
## Invocation
Use this skill directly or use `/migrate-structured-docs` as the prompt-template shortcut for legacy prose-to-YAML migration.
## Migration Rules
- Do not edit production code.
- Read legacy Markdown only as migration input.
- Write canonical YAML under the resolved structured docs root; root `AGENTS.md` is the only allowed Markdown output.
- Do not generate replacement Markdown except root `AGENTS.md` when migrating old agent operating instructions for harness interoperability.
- Do not preserve fallback behavior. Legacy prose docs become deprecated after migration.
- Preserve information by mapping every durable fact to exactly one owner artifact.
- If a prose claim lacks source evidence, set `evidence_mode: mixed` or `planned`, confidence low/medium, and add an `unknowns` or `evidence` note.
- Resolve redundancy by keeping owner artifact fact and replacing duplicates with ID refs.
## Input Mapping
- `AGENTS.md` -> `agent-operating-guide.yaml` rules/checks, then regenerate compact root `AGENTS.md` from that structured source.
- `REPO_INVENTORY.md` -> `repo-inventory.yaml`, `validation-baseline.yaml`.
- `PROJECT_INTENT.md` -> `project-intent.yaml`.
- `ARCHITECTURE.md` -> `architecture.yaml`, refs to `dependency-rules.yaml`, `data-flow.yaml`.
- `DATA_FLOW.md` -> `data-flow.yaml`.
- `DATA_MODEL.md` -> `data-model.yaml`.
- `INVARIANTS.md` -> `invariants.yaml`.
- `DEPENDENCY_RULES.md` -> `dependency-rules.yaml`, design violations to `design-issues.yaml`.
- `DESIGN_ISSUES.md` -> `design-issues.yaml`.
- `RISK_REGISTER.md` -> `risk-register.yaml`.
- `CHANGE_GUIDE.md` -> `change-guide.yaml`.
- `TESTING_STRATEGY.md` -> `testing-strategy.yaml`.
- `VALIDATION_BASELINE.md` -> `validation-baseline.yaml`.
- `CONTRACTS.md` -> `contracts.yaml`.
- `adr/*.md` -> `adr.yaml` records.
- `SCOPES.md` and scoped prose dirs -> `scopes.yaml` and matching scoped YAML files.
## Migration Steps
1. Inventory legacy prose docs and scoped dirs.
2. Create `<docs-root>/repo/scopes.yaml` when any scope exists.
3. Convert each legacy doc to its owner YAML artifact using stable IDs.
4. Cross-link records by ID: risks -> invariants/entities/flows/contracts; tests -> risks/invariants; contracts -> owners/consumers.
5. Mark migrated artifacts with `evidence_mode: mixed` unless verified against source.
6. Validate no owner fact is duplicated across artifacts.
7. Report migrated files and unmapped/ambiguous claims.
## Output
- YAML files created/updated
- Legacy inputs consumed
- Ambiguous claims requiring source verification
- Duplicate facts collapsed
- Validation grep proving prompts/skills target structured YAML plus root `AGENTS.md` only when explicitly requested
+34
-0

@@ -15,2 +15,36 @@ # Changelog

## [0.5.0] - 2026-05-24
### Changed
- Switched workflow docs and prompts to treat `docs/agent/api` as a logical layout under a resolved docs root, with `safe-start` creating the initial repo-local root and other workflows defaulting to a global overlay when repo-local docs are absent.
- Removed package-published validator/runtime scripts and deleted bundled examples so the package ships only runtime skill/prompt assets and top-level docs.
- Simplified validation guidance to best-effort agent inspection and re-read instead of packaged validator commands.
### Fixes
- Clarified prompts, skills, README, tutorial, and troubleshooting so third-party repos are not implicitly treated as adopters of repo-local structured docs.
## [0.4.0] - 2026-05-20
### Added
- Added canonical structured artifact runtime references and per-artifact JSON schemas under `skills/_shared/references/`.
- Added `structured-docs-migration` skill and `/migrate-structured-docs` prompt for legacy prose-to-YAML migration.
- Added structured artifact validation scripts and validator tests.
- Added migration and structured artifact examples for risk-register conversion.
### Changed
- Shifted workflows to canonical YAML artifacts under `docs/agent/api/**` as the source of truth.
- Deprecated legacy project-agent prose Markdown artifacts under `docs/agent/*.md` and scoped prose docs.
- Kept root `AGENTS.md` as allowed harness interoperability Markdown output when explicitly produced.
- Updated prompts, skills, README, tutorial, and troubleshooting to structured artifact model.
### Fixes
- Fixed validator dangling-reference checks to include `ev:*` evidence references.
- Fixed read-only review prompt wording to remove write/update protocol mismatch.
- Clarified migration prompt wording: no Markdown fallback artifacts, while allowing root `AGENTS.md` when explicitly produced.
## [0.3.2] - 2026-05-19

@@ -17,0 +51,0 @@

+2
-3
{
"name": "pi-agent-codebase-workflows",
"version": "0.3.2",
"description": "Pi skills and prompt templates for safe greenfield starts, codebase reconstruction, architecture-aware review, and safe changes.",
"version": "0.5.0",
"description": "Pi skills and prompt templates for structured YAML artifact workflows: safe-start, codebase-recon, safe-change, architecture review, and legacy docs migration.",
"license": "MIT",

@@ -30,3 +30,2 @@ "author": "PriNova",

"prompts/",
"docs/",
"README.md",

@@ -33,0 +32,0 @@ "CHANGELOG.md",

+3
-9
---
description: Preflight + bug diagnosis without implementation
argument-hint: "<bug>"
description: "Structured bug diagnosis"
argument-hint: "[bug/focus]"
---
Use `/skill:safe-change`.
Task:
Fix this bug:
$ARGUMENTS
First run Universal Preflight, then Bug Diagnosis. Do not edit code. Stop with minimal fix plan, regression-test plan, and validation commands unless explicitly told to implement.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-change` bug diagnosis. Use canonical YAML artifacts only under the resolved structured docs root. Bug/focus: $ARGUMENTS. Diagnose violated invariant/contract/risk refs, root cause, minimal fix, regression test, validation command refs. Do not edit code.
---
description: Preflight + implement approved minimal bug fix
argument-hint: "<approved-plan-or-bug>"
description: "Structured bug implementation"
argument-hint: "[approved plan/focus]"
---
Use `/skill:safe-change`.
Task:
Implement this approved/minimal bug fix:
$ARGUMENTS
First run Universal Preflight. If no approved plan is present, perform Bug Diagnosis and stop for approval. If plan is clear/approved, perform Bug Implementation with regression tests and validation.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-change` bug implementation. Follow approved plan. Use/update canonical YAML artifacts only under the resolved structured docs root when durable semantics changed. No legacy prose docs. Plan/focus: $ARGUMENTS.
---
description: Preflight + feature design without implementation
argument-hint: "<feature>"
description: "Structured feature design"
argument-hint: "[feature/focus]"
---
Use `/skill:safe-change`.
Feature request:
$ARGUMENTS
First run Universal Preflight, then Feature Design. Do not edit code. Stop with test plan, minimal implementation plan, documentation update plan, and blocking questions only.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-change` feature design. Use canonical YAML artifacts only under the resolved structured docs root. Feature/focus: $ARGUMENTS. Design flow/data/invariant/contract/component impacts, side effects, risks, tests, validation refs, and owner YAML updates. Do not edit code.
---
description: Preflight + implement approved feature design
argument-hint: "<approved-design-or-feature>"
description: "Structured feature implementation"
argument-hint: "[approved design/focus]"
---
Use `/skill:safe-change`.
Task:
Implement this approved feature design:
$ARGUMENTS
First run Universal Preflight. If no approved design is present, perform Feature Design and stop for approval. If design is clear/approved, perform Feature Implementation with tests and validation.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-change` feature implementation. Follow approved design. Implement minimal change, add tests, validate, update owner YAML artifacts only for durable semantic changes. No legacy Markdown docs except root `AGENTS.md` when `agent-operating-guide.yaml` changes. Design/focus: $ARGUMENTS.
---
description: Safe-change universal preflight before any non-trivial task
argument-hint: "<task>"
description: "Structured safe-change preflight"
argument-hint: "[task/focus]"
---
Use `/skill:safe-change` Universal Preflight.
Task:
$ARGUMENTS
Use `docs/agent/SCOPES.md` if present to discover matching scoped docs before falling back to top-level docs.
Do not edit code. Produce the preflight output and say whether implementation should proceed now or wait for approval.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-change` structured preflight. Read only canonical YAML artifacts under the resolved structured docs root; do not read legacy prose docs. Focus/task: $ARGUMENTS. Output classification, artifacts read, matched scope, affected files, invariant/contract/risk refs, validation command refs, and approval status.
---
description: "Codebase reconstruction pass 1: repository inventory"
description: "Structured recon pass 1 inventory"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 1 — Repository Inventory.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If focus is provided, write scoped artifacts under `docs/agent/scopes/by-path/<focus>/` for path focus or `docs/agent/scopes/by-domain/<slug>/` for domain focus, and update `docs/agent/SCOPES.md`.
Write/update `docs/agent/REPO_INVENTORY.md`, or scoped `REPO_INVENTORY.md` when focus is provided. Do not edit source code.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 1. Write/update `repo-inventory.yaml` and `validation-baseline.yaml`; update `scopes.yaml` when focused. Canonical YAML only under the resolved structured docs root. Focus: $ARGUMENTS.
---
description: "Codebase reconstruction pass 2: observed architecture"
description: "Structured recon pass 2 architecture"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 2 — Architecture Reconstruction.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If focus is provided, write scoped artifacts under `docs/agent/scopes/by-path/<focus>/` for path focus or `docs/agent/scopes/by-domain/<slug>/` for domain focus, and update `docs/agent/SCOPES.md`.
Read `docs/agent/REPO_INVENTORY.md` or matching scoped `REPO_INVENTORY.md`. Write/update `docs/agent/ARCHITECTURE.md`, or scoped `ARCHITECTURE.md` when focus is provided. Do not edit source code.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 2. Read structured inventory/validation YAML. Write/update `architecture.yaml` with components, style, boundaries, flow refs. YAML only. Focus: $ARGUMENTS.
---
description: "Codebase reconstruction pass 3: data model and invariants"
description: "Structured recon pass 3 data model and invariants"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 3 — Data Model and Invariants.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If focus is provided, write scoped artifacts under `docs/agent/scopes/by-path/<focus>/` for path focus or `docs/agent/scopes/by-domain/<slug>/` for domain focus, and update `docs/agent/SCOPES.md`.
Read `docs/agent/REPO_INVENTORY.md` and `docs/agent/ARCHITECTURE.md`, or matching scoped prior docs. Write/update `docs/agent/DATA_MODEL.md` and `docs/agent/INVARIANTS.md`, or scoped `DATA_MODEL.md` and `INVARIANTS.md` when focus is provided. Do not edit source code.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 3. Read structured inventory/architecture YAML. Write/update `data-model.yaml` and `invariants.yaml`. YAML only. Focus: $ARGUMENTS.
---
description: "Codebase reconstruction pass 4: dependency rules and drift"
description: "Structured recon pass 4 dependencies and design issues"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 4 — Dependency Rules and Drift Detection.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If focus is provided, write scoped artifacts under `docs/agent/scopes/by-path/<focus>/` for path focus or `docs/agent/scopes/by-domain/<slug>/` for domain focus, and update `docs/agent/SCOPES.md`.
Read prior reconstruction docs, including matching scoped prior docs when focus is provided. Write/update `docs/agent/DEPENDENCY_RULES.md` and `docs/agent/DESIGN_ISSUES.md`, or scoped `DEPENDENCY_RULES.md` and `DESIGN_ISSUES.md` when focus is provided. Do not edit source code.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 4. Read structured inventory/architecture/data/invariant YAML. Write/update `dependency-rules.yaml` and `design-issues.yaml`. YAML only. Focus: $ARGUMENTS.
---
description: "Codebase reconstruction pass 5: bug-risk and subtle-failure analysis"
description: "Structured recon pass 5 risk register"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 5 — Bug-Risk and Subtle-Failure Analysis.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If focus is provided, write scoped artifacts under `docs/agent/scopes/by-path/<focus>/` for path focus or `docs/agent/scopes/by-domain/<slug>/` for domain focus, and update `docs/agent/SCOPES.md`.
Read architecture/data/invariants/dependency docs, including matching scoped docs when focus is provided. Write/update `docs/agent/RISK_REGISTER.md`, or scoped `RISK_REGISTER.md` when focus is provided. Do not edit source code.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 5. Read structured architecture/data/invariants/dependency YAML. Write/update `risk-register.yaml`. YAML only. Focus: $ARGUMENTS.
---
description: "Codebase reconstruction pass 6: create/update root AGENTS.md"
description: "Structured recon pass 6 agent operating guide"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 6 — Root Agent Operating Guide.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If `docs/agent/SCOPES.md` exists, include compact scoped-doc discovery guidance in root `AGENTS.md`.
Write/update project-root `AGENTS.md` only. Merge with existing root `AGENTS.md` if present. Never create `docs/AGENTS.md` or `docs/agent/AGENTS.md`.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 6. Write/update `agent-operating-guide.yaml` and root `AGENTS.md` for harness interoperability. Canonical facts remain in YAML; `AGENTS.md` stays compact and references canonical YAML. Focus: $ARGUMENTS.
---
description: "Codebase reconstruction pass 7: change guide"
description: "Structured recon pass 7 change guide"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 7 — Change Guide.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If focus is provided, write scoped artifacts under `docs/agent/scopes/by-path/<focus>/` for path focus or `docs/agent/scopes/by-domain/<slug>/` for domain focus, and update `docs/agent/SCOPES.md`.
Read architecture/data/invariants/dependency docs, including matching scoped docs when focus is provided. Write/update `docs/agent/CHANGE_GUIDE.md`, or scoped `CHANGE_GUIDE.md` when focus is provided. Do not edit source code.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 7. Write/update `change-guide.yaml` with routing/checklists and owner artifact refs. YAML only; no Markdown. Focus: $ARGUMENTS.
---
description: "Codebase reconstruction pass 8: consolidate semantic artifacts"
description: "Structured recon pass 8 consolidation"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 8 — Consolidation.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If `docs/agent/SCOPES.md` exists, use it to select relevant scoped docs and update scope status/currentness as needed.
Consolidate root `AGENTS.md` plus reconstruction docs. Reconcile contradictions without silently deleting disagreement evidence: resolve from source where possible, assign/clarify ownership for shared contracts where evidence supports it, or record unresolved disagreement as drift risk / `Known Unknown` with citations. Keep detailed scope-specific facts in scoped artifacts and summarize only stable repo-level guidance in top-level docs. De-duplicate repeated facts after preserving strongest evidence and materially different scope-specific observations. Do not edit source code.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 8. Consolidate canonical YAML artifacts under the resolved structured docs root, remove redundancy by owner refs, reconcile contradictions with evidence. Do not edit source or Markdown. Focus: $ARGUMENTS.
---
description: "Codebase reconstruction pass 9: observed architecture ADR"
description: "Structured recon pass 9 ADR"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 9 — Observed-Architecture ADR.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If focus is provided, read matching scoped docs and make ADR scope explicit.
Write `docs/agent/adr/0001-observed-architecture.md`. Do not edit source code.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 9. Write/update `adr.yaml` structured ADR records with bounded prose fields. YAML only. Focus: $ARGUMENTS.
---
description: "Codebase reconstruction pass 10: plan risk-to-tests conversion"
description: "Structured recon pass 10 risk-to-tests"
argument-hint: "[focus]"
---
Use `/skill:codebase-recon` Pass 10 — Risk-to-Tests Plan.
Focus, if provided: $ARGUMENTS
Use focus to scope this pass to a module/package/app/service/path in large repos or monorepos. If focus is provided, read matching scoped risk/invariant/data/change-guide docs first.
Select top 3–5 risks to convert into tests. Produce plan only unless explicitly asked to implement tests.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` Pass 10. Write/update `testing-strategy.yaml` with test topology, coverage gaps, and risk-to-test priorities. YAML only. Focus: $ARGUMENTS.
---
description: "Run all codebase reconstruction passes when repo size and complexity allow"
description: "Structured codebase reconstruction all passes"
argument-hint: "[focus]"
---
Use the `codebase-recon` skill in all-in-one mode.
Focus, if provided: $ARGUMENTS
Use focus to scope all passes to a module/package/app/service/path in large repos or monorepos. If focus is provided, write scoped artifacts under `docs/agent/scopes/by-path/<focus>/` for path focus or `docs/agent/scopes/by-domain/<slug>/` for domain focus, and update `docs/agent/SCOPES.md`.
First assess whether the repository is small/simple enough for reliable sequential reconstruction. If yes, run passes 1–10, writing top-level artifacts under `docs/agent/` when unscoped or scoped artifacts under `docs/agent/scopes/**` when focused, and keeping `AGENTS.md` at project root.
If the repo proves too large or complex, complete the current pass and tell the user which numbered pass to run next.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:codebase-recon` all-in-one mode. Produce canonical YAML artifacts under the resolved structured docs root; root `AGENTS.md` may be generated in Pass 6 for harness interoperability. No other Markdown docs. Focus: $ARGUMENTS. If repo is too large, finish current pass and recommend next pass.
---
description: Preflight + refactoring design without implementation
argument-hint: "<target>"
description: "Structured refactor design"
argument-hint: "[refactor/focus]"
---
Use `/skill:safe-change`.
Refactoring target:
$ARGUMENTS
First run Universal Preflight, then Refactoring Design. Do not edit code. Stop with staged plan, characterization-test plan, validation plan, rollback strategy, and docs update plan.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-change` refactoring design. Use canonical YAML artifacts only. Identify design issue/dependency rule refs, behavior to preserve, characterization tests, staged plan, validation refs, rollback. Do not edit code. Focus: $ARGUMENTS.
---
description: Preflight + implement approved refactoring stage
argument-hint: "<approved-stage-or-target>"
description: "Structured refactor implementation"
argument-hint: "[approved refactor/focus]"
---
Use `/skill:safe-change`.
Task:
Implement this approved refactoring stage:
$ARGUMENTS
First run Universal Preflight. If no approved refactoring design is present, perform Refactoring Design and stop. If stage is clear/approved, implement smallest safe behavior-preserving stage with validation.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-change` refactoring implementation. Preserve behavior. Follow approved stage. Update owner YAML only when durable structure/rules changed. No legacy Markdown docs except root `AGENTS.md` when `agent-operating-guide.yaml` changes. Focus: $ARGUMENTS.
---
description: Review current diff against architecture and invariants
description: "Structured architecture review"
argument-hint: "[scope]"
---
Use `/skill:arch-code-review`.
Review target/scope, if provided:
$ARGUMENTS
Use scope to focus review on a module/package/app/service/path when diff spans multiple areas. Use `docs/agent/SCOPES.md` if present to discover matching scoped docs and cross-scope contracts.
Review current diff. Do not edit code. Provide verdict, findings with severity/evidence/fix direction, missing tests, docs updates, drift risk, final recommendation.
Load `/skill:arch-code-review`, then read only task-relevant canonical YAML artifacts under the resolved structured docs root (resolve scope via `<docs-root>/repo/scopes.yaml` when present). Review current diff for architecture/data/invariant/dependency/contract/risk/test alignment. Scope: $ARGUMENTS. Read-only: do not edit code or artifacts.
---
description: Preflight + fix one failing risk test or risk cluster
argument-hint: "[risk-or-test]"
description: "Structured risk fix"
argument-hint: "[risk/focus]"
---
Use `/skill:safe-change` Risk-Fix Pass.
Focus, if provided:
$ARGUMENTS
Use focus to limit the risk-fix pass to a module/package/app/service/path or a tight risk/test cluster.
First run Universal Preflight. Select one failing risk test or tight risk cluster only. Do not fix all failing tests. Produce/execute minimal fix plan depending on approval context.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-change` risk-fix workflow. Select one risk from `<docs-root>/**/risk-register.yaml` or a failing risk-derived test. Fix minimally, validate, update risk/testing YAML refs. No legacy prose docs. Risk/focus: $ARGUMENTS.
---
description: "Safe-start pass 1: capture greenfield project intent and guidance level"
argument-hint: "[project idea / constraints]"
description: "Structured safe-start pass 1 intent"
argument-hint: "[intent/focus]"
---
Use `/skill:safe-start` Pass 1 — Intent Capture.
Project idea or constraints: $ARGUMENTS
Determine guidance level: Freshman, Standard, or Expert. If unclear, ask once; default to Standard when user wants to proceed.
Produce or update `docs/agent/PROJECT_INTENT.md` when creating files. If not editing yet, produce the same sections in chat.
Required output:
- Product goal
- Target users
- Primary user journeys
- Must-have features
- Non-goals
- Runtime/platform/deployment target
- Constraints and preferences
- Guidance level
- Assumptions
- Open questions
- Approval gate: confirm whether to proceed to data-flow design
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-start` Pass 1. Write/update `project-intent.yaml`, initial `repo-inventory.yaml`, optional `scopes.yaml`. YAML only. Input: $ARGUMENTS.
---
description: "Safe-start pass 2: data-first input/transformation/output design"
argument-hint: "[focus or project notes]"
description: "Structured safe-start pass 2 data flow"
argument-hint: "[focus]"
---
Use `/skill:safe-start` Pass 2 — Data Flow Design.
Focus or notes: $ARGUMENTS
Read `docs/agent/PROJECT_INTENT.md` if present. Do not choose modules before data shape is clear.
Produce/update:
- `docs/agent/DATA_FLOW.md`
- `docs/agent/DATA_MODEL.md`
- `docs/agent/INVARIANTS.md`
Required output:
- External inputs
- User inputs
- Files/events/API payloads
- Core entities/value objects
- Identifiers and relationships
- Lifecycle/state transitions
- Validation and normalization
- Transformation pipeline: input -> validation -> normalization -> domain operation -> output
- Outputs: UI states, API responses, reports, side effects
- Error states
- Invariants and forbidden states
- Persistence/serialization draft if needed
- Open questions and risks
- Approval gate: confirm whether to proceed to architecture decisions
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-start` Pass 2. Write/update `data-flow.yaml`, `data-model.yaml`, and `invariants.yaml`. YAML only. Focus: $ARGUMENTS.
---
description: "Safe-start pass 3: architecture decisions derived from data flow"
argument-hint: "[stack preference / constraints]"
description: "Structured safe-start pass 3 architecture"
argument-hint: "[focus]"
---
Use `/skill:safe-start` Pass 3 — Architecture Decisions.
Stack preference or constraints: $ARGUMENTS
Read first when present:
- `docs/agent/PROJECT_INTENT.md`
- `docs/agent/DATA_FLOW.md`
- `docs/agent/DATA_MODEL.md`
- `docs/agent/INVARIANTS.md`
Derive module boundaries from data flow and side-effect boundaries. Choose framework/libraries after boundaries are clear.
Produce/update:
- `docs/agent/ARCHITECTURE.md`
- `docs/agent/DEPENDENCY_RULES.md`
- `docs/agent/RISK_REGISTER.md`
- `docs/agent/adr/0001-initial-architecture.md`
Required output:
- Architecture overview
- Module boundaries and ownership
- Dependency direction
- Side-effect boundaries
- Stack/framework/library decisions and alternatives considered
- Configuration/secrets approach
- Error handling strategy
- Security/privacy basics
- Key risks and mitigations
- ADR: context, decision, alternatives, consequences
- Approval gate: confirm whether to proceed to contract docs or scaffold plan
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-start` Pass 3. Write/update `architecture.yaml`, `dependency-rules.yaml`, `design-issues.yaml`, `risk-register.yaml`, and `adr.yaml`. YAML only. Focus: $ARGUMENTS.
---
description: "Safe-start pass 4: create project contract docs for humans and future agents"
argument-hint: "[docs focus]"
description: "Structured safe-start pass 4 contract artifacts"
argument-hint: "[focus]"
---
Use `/skill:safe-start` Pass 4 — Project Contract Docs.
Docs focus: $ARGUMENTS
Read first when present:
- `docs/agent/PROJECT_INTENT.md`
- `docs/agent/DATA_FLOW.md`
- `docs/agent/DATA_MODEL.md`
- `docs/agent/INVARIANTS.md`
- `docs/agent/ARCHITECTURE.md`
- `docs/agent/DEPENDENCY_RULES.md`
- `docs/agent/RISK_REGISTER.md`
Create compact operational docs. Freshman mode may include short teaching notes and command explanations. Expert mode should be terse and contract-oriented.
Produce/update:
- `README.md`
- `AGENTS.md`
- `docs/agent/CHANGE_GUIDE.md`
- `docs/agent/TESTING_STRATEGY.md`
- optional `docs/agent/CONTRACTS.md`, `docs/agent/SECURITY.md`, `docs/agent/DEPLOYMENT.md`
Required output:
- Project overview
- Architecture rules
- Data model rules
- Invariants not to violate
- How to add/modify features
- How to validate changes
- Documentation update rules
- Forbidden shortcuts
- Approval gate: confirm whether to proceed to scaffold planning
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-start` Pass 4. Write/update structured YAML artifacts: `change-guide.yaml`, `testing-strategy.yaml`, `contracts.yaml` when needed, `agent-operating-guide.yaml`, and root `AGENTS.md` for harness interoperability. Do not write README or other prose docs. Focus: $ARGUMENTS.
---
description: "Safe-start pass 5: plan minimal scaffold and tooling before code"
argument-hint: "[framework/tooling preference]"
description: "Structured safe-start pass 5 scaffold plan"
argument-hint: "[focus]"
---
Use `/skill:safe-start` Pass 5 — Scaffold Plan.
Framework/tooling preference: $ARGUMENTS
Read prior design docs under `docs/agent/` if present. Do not scaffold before the plan is explicit unless user already approved implementation.
Produce a minimal scaffold plan with:
- File tree to create
- Package/build config choices
- Format/lint/typecheck choices where suitable
- Test runner and initial tests
- App entrypoint and health/hello path
- Config/env example if needed
- Exact commands to create/install/run
- Files that will be generated or edited
- Validation commands expected after scaffold
- Risks/assumptions
Avoid:
- speculative abstractions
- unused frameworks
- broad feature implementation
- auth/payment/admin systems unless the initial project goal requires them
Approval gate: ask whether to write files and run scaffold commands unless user explicitly requested implementation now.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-start` Pass 5. Produce scaffold plan in chat only before file creation approval: tree, tooling, commands, generated files, risks. Do not create docs except canonical YAML updates already approved. Focus: $ARGUMENTS.
---
description: "Safe-start pass 6: establish green validation baseline for new project"
argument-hint: "[validation focus]"
description: "Structured safe-start pass 6 validation baseline"
argument-hint: "[focus]"
---
Use `/skill:safe-start` Pass 6 — Validation Baseline.
Validation focus: $ARGUMENTS
Run the most relevant checks for the scaffolded project. Prefer project-local commands and wrappers.
Validate when applicable:
- install/bootstrap works
- format/lint command works
- typecheck/build works
- tests run
- app starts
- one smoke test proves runtime path
Produce/update `docs/agent/VALIDATION_BASELINE.md` with:
- Commands run
- Results
- Known warnings
- Blockers and exact errors if any
- Next best check when a command cannot run
- Baseline status: green / partial / blocked
Do not proceed to feature depth until baseline is green or blockers are explicitly accepted by user.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-start` Pass 6. Run/record applicable validations and write/update `validation-baseline.yaml` with command status, blockers, recommended order. YAML only. Focus: $ARGUMENTS.
---
description: "Safe-start pass 7: implement first thin vertical slice"
argument-hint: "[slice goal]"
description: "Structured safe-start pass 7 vertical slice"
argument-hint: "[focus]"
---
Use `/skill:safe-start` Pass 7 — Thin Vertical Slice.
Slice goal: $ARGUMENTS
Read first when present:
- `docs/agent/PROJECT_INTENT.md`
- `docs/agent/DATA_FLOW.md`
- `docs/agent/DATA_MODEL.md`
- `docs/agent/INVARIANTS.md`
- `docs/agent/ARCHITECTURE.md`
- `docs/agent/DEPENDENCY_RULES.md`
- `docs/agent/VALIDATION_BASELINE.md`
Implement one small end-to-end feature only. Include:
- Input adapter: UI/API/CLI/event/file as relevant
- Validation/schema if relevant
- Domain/core operation
- Output adapter/rendering/API response
- Persistence adapter or explicit in-memory/mock choice if persistence is deferred
- Tests around core invariant and runtime path
- Docs update only if durable semantics change
Before editing, state slice boundary, touched files, invariants at risk, and validation plan. Stop for approval unless user explicitly requested implementation now.
After editing, run focused validation and update validation/risk docs if needed.
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-start` Pass 7. Implement one thin vertical slice after approval/request. Update owner YAML artifacts only for durable semantic changes. Focus: $ARGUMENTS.
---
description: "Safe-start pass 8: hand off new project to safe-change workflow"
argument-hint: "[handoff focus]"
description: "Structured safe-start pass 8 handoff"
argument-hint: "[focus]"
---
Use `/skill:safe-start` Pass 8 — Handoff to Safe Change.
Handoff focus: $ARGUMENTS
Verify project is ready for documented-codebase work.
Check:
- Root `AGENTS.md` exists and is operational
- `docs/agent/` artifacts cover architecture, data model, invariants, dependency rules, tests, risks, and change guide
- Validation baseline commands are known and recently run
- First vertical slice is implemented or explicitly deferred
- Next work items are small enough for `safe-change`
Produce/update:
- `docs/agent/CHANGE_GUIDE.md`
- `docs/agent/RISK_REGISTER.md`
- optional `docs/agent/BACKLOG.md`
Final output:
- Handoff status: ready / partial / blocked
- Validation summary
- Remaining risks
- Next recommended work items
- Explicit instruction: future feature/bug/refactor work should use `/skill:safe-change`
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-start` Pass 8. Verify structured artifacts are ready for `safe-change`; update `change-guide.yaml`, `risk-register.yaml`, `repo-inventory.yaml`, `design-issues.yaml`, and `scopes.yaml` as needed. YAML only. Focus: $ARGUMENTS.
---
description: "Safe-start all-in-one greenfield workflow for small/simple projects"
argument-hint: "[project idea / constraints]"
description: "Structured safe-start all passes"
argument-hint: "[project intent/focus]"
---
Use `/skill:safe-start` all-in-one mode.
Project idea or constraints: $ARGUMENTS
Only use all-in-one mode if the project appears small/simple enough. Otherwise recommend starting with `/safe-start-01-intent`.
Workflow:
1. Determine guidance level: Freshman, Standard, or Expert. Default Standard if unclear.
2. Capture intent and assumptions.
3. Produce data-first design: inputs -> transformations -> outputs, data model, invariants.
4. Propose architecture decisions derived from data flow.
5. Propose contract docs and scaffold plan.
6. Stop for approval before writing files unless user explicitly requested implementation now.
7. If approved/requested, scaffold minimal baseline, run validation, implement one thin vertical slice, and hand off to `safe-change`.
Required final output:
- Files created/changed
- Validation run and result
- Handoff status: ready / partial / blocked
- Next safe-change-sized work items
Before writing/updating structured artifacts, after loading the selected skill, load shared refs relative to that skill: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and only the matching artifact schema(s). Follow the skill Structured Artifact Write/Update Protocol for scope resolution, stable IDs, upserts, evidence, reference integrity, status transitions, deterministic YAML formatting, and validation. Use `/skill:safe-start` all-in-one mode. Create canonical YAML artifacts under the resolved structured docs root and root `AGENTS.md` for harness interoperability. Do not create README or other prose docs as workflow artifacts. Stop for approval gates unless implementation explicitly requested. Input: $ARGUMENTS.
+61
-56
# pi-agent-codebase-workflows
Pi package with skills and prompt templates for safe greenfield starts, documented-codebase changes, reconstruction, and reviews.
Pi package with agent-first skills and prompt templates for structured codebase understanding, safe greenfield starts, safe changes, architecture-aware review, and migration from deprecated prose docs.
Credits: built for [pi](https://github.com/earendil-works/pi-mono), created by Mario Zechner ([GitHub: @badlogic](https://github.com/badlogic), [X: @badlogicgames](https://x.com/badlogicgames)) and the Earendil Works team ([@earendil-works](https://github.com/earendil-works)).
## Structured artifact model
## Included skills
Legacy prose-style project-agent docs are deprecated. Current workflows treat `docs/agent/api` as a logical layout under a resolved structured docs root:
- `safe-start` — create new projects safely with data-first design, project-agent docs, minimal scaffold, validation baseline, and first thin vertical slice.
- `codebase-recon` — reconstruct durable project understanding into `docs/agent/*.md` plus project-root `AGENTS.md`.
- `arch-code-review` — review current diffs against documented architecture, invariants, data model, dependency rules, risks, and tests.
- `safe-change` — preflight, design/diagnosis, implementation, validation, and semantic docs update workflow for safe code changes.
```text
<docs-root>/repo/*.yaml
<docs-root>/scopes/by-path/<repo-relative-path>/*.yaml
<docs-root>/scopes/by-domain/<slug>/*.yaml
```
## Usage docs
Resolution rules:
- resolve `workspace_root` with `git rev-parse --show-toplevel 2>/dev/null` or fallback to `pwd`
- `safe-start` creates and uses the initial repo-local root at `<workspace_root>/docs/agent/api`
- other skills use repo-local only when that root already exists
- otherwise use the global overlay root `~/.pi/agent/workspaces/<workspace-fingerprint>/docs/agent/api`
- derive `<workspace-fingerprint>` deterministically from the canonical `workspace_root` path and keep it stable for the same workspace
- [Tutorial](docs/TUTORIAL.md) — end-to-end workflows for small repos, monorepos, scoped reconstruction, safe changes, reviews, consolidation, and legacy docs.
- [Troubleshooting](docs/TROUBLESHOOTING.md) — common reconstruction, scoping, contract, review, and validation issues.
No workflow generates `docs/agent/*.md`, scoped Markdown docs, or README files as project-agent artifacts. Structured YAML is the API for further transformation and agent ingestion. Root `AGENTS.md` remains a compact harness interoperability file generated from `agent-operating-guide.yaml`, because not every coding harness consumes these skills/prompts directly.
All skills follow a Structured Artifact Write/Update Protocol: resolve scope and owner artifact first, read before write, preserve stable IDs, upsert by ID/source-of-truth fields, mark unsupported records stale/deprecated instead of deleting, require evidence, validate references, format YAML deterministically, and report validation.
## Included skills
- `safe-start` — create new projects with structured intent, data, architecture, contracts, validation, and handoff artifacts.
- `codebase-recon` — reconstruct existing codebases into structured YAML artifacts under the resolved structured docs root.
- `safe-change` — make documented-codebase changes using structured artifacts and update owner YAML only when durable semantics change.
- `arch-code-review` — review diffs against structured architecture, data, invariant, dependency, risk, contract, and test artifacts from the resolved structured docs root.
- `structured-docs-migration` — migrate deprecated prose-style docs into canonical structured YAML artifacts under the resolved structured docs root.
## Included prompt templates

@@ -29,3 +44,3 @@

- `/recon-05-risk-register`
- `/recon-06-agents`
- `/recon-06-agents` — writes `agent-operating-guide.yaml` and root `AGENTS.md`
- `/recon-07-change-guide`

@@ -36,3 +51,3 @@ - `/recon-08-consolidate`

Safe-start workflow:
Safe start:

@@ -49,3 +64,3 @@ - `/safe-start-all`

Safe-change workflow:
Safe change / review / migration:

@@ -61,2 +76,3 @@ - `/preflight`

- `/review-arch`
- `/migrate-structured-docs`

@@ -85,53 +101,45 @@ ## Install

## Focus/scoping arguments
## Scope/focus arguments
Reconstruction prompts accept optional `[focus]` arguments. Use them to scope analysis to a module, package, app, service, directory, or bounded domain area, especially in monorepos.
Prompts accept optional focus/scope arguments. Path-like focus writes under:
Example:
```bash
/recon-01-inventory packages/api
/recon-02-architecture apps/mobile auth flow
/recon-all services/billing
```text
<docs-root>/scopes/by-path/<focus>/
```
Without focus, reconstruction writes the traditional top-level `docs/agent/*.md` artifacts. With focus, reconstruction writes hierarchical scoped artifacts and updates `docs/agent/SCOPES.md`:
Domain-like focus writes under:
```text
docs/agent/
SCOPES.md
scopes/
by-path/packages/api/
README.md # optional local index for large/complex scopes
ARCHITECTURE.md
CONTRACTS.md
by-domain/auth-flow/
README.md # optional local index for large/complex scopes
ARCHITECTURE.md
CONTRACTS.md
<docs-root>/scopes/by-domain/<slug>/
```
Top-level docs remain valid as repo-level summaries/fallbacks. This is backward-compatible with repositories reconstructed before scoped artifacts existed. Later `/recon-08-consolidate` can reconcile multiple scoped artifacts into repo-level guidance.
`<docs-root>/repo/scopes.yaml` is the canonical scope registry. Path scopes match by longest prefix. Domain scopes require explicit task/domain/contract refs.
Safe-change and review workflows read `SCOPES.md` when present, match path scopes by longest prefix, and follow scoped `CONTRACTS.md` links for cross-module APIs, shared types, schemas, events, generated clients, and persistence boundaries.
## Artifact ownership
Review and risk-fix prompts also accept scope/focus arguments for targeted reviews or fixes.
- `scopes.yaml`: scope routing and ownership.
- `repo-inventory.yaml`: structure, entry points, command index, boundaries.
- `validation-baseline.yaml`: command status, blockers, validation order.
- `project-intent.yaml`: goals, users, journeys, constraints.
- `architecture.yaml`: components, style, side-effect boundaries.
- `data-flow.yaml`: typed flow graph and error states.
- `data-model.yaml`: entities, IDs, schemas, lifecycles, serialized formats.
- `invariants.yaml`: rules, forbidden states, enforcement.
- `dependency-rules.yaml`: layers, allowed/forbidden dependencies, violations.
- `design-issues.yaml`: drift, deferred decisions, ownership gaps.
- `risk-register.yaml`: failure modes and suggested tests/fixes.
- `contracts.yaml`: APIs, schemas, events, generated clients, persistence/deployment/env contracts.
- `testing-strategy.yaml`: test topology, gaps, risk-to-test priorities.
- `change-guide.yaml`: workflow routing and checklists.
- `adr.yaml`: structured ADR records.
- `agent-operating-guide.yaml`: structured operational rules for agents; root `AGENTS.md` mirrors compact harness-facing guidance.
## Artifact locations
## Runtime schemas and validation
Skills write durable project-agent docs under:
Runtime schema assets are shared under `skills/_shared/references/`. Skills load `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and the matching artifact schema(s) for files they write. `_shared` has no `SKILL.md`, so Pi does not discover it as a skill.
```text
docs/agent/
docs/agent/scopes/**
```
Project docs outside the shared runtime refs may exist in the source repo, but are not runtime instructions for installed extension users.
Project operating instructions stay at project root:
Validation is best-effort by agent inspection and re-read.
```text
AGENTS.md
```
The workflows intentionally avoid `docs/AGENTS.md` and `docs/agent/AGENTS.md`.
## Package structure

@@ -141,8 +149,5 @@

skills/
safe-start/SKILL.md
codebase-recon/SKILL.md
arch-code-review/SKILL.md
safe-change/
SKILL.md
references/*.md
_shared/references/artifact-api.md
_shared/references/schemas/*.schema.json
*/SKILL.md
prompts/

@@ -152,2 +157,2 @@ *.md

Pi discovers these through the `pi.skills` and `pi.prompts` entries in `package.json`.
Pi discovers skills and prompts through the `pi.skills` and `pi.prompts` entries in `package.json`.
---
name: arch-code-review
description: Architecture-aware code review for current diffs in documented codebases. Use to review changes against architecture, data model, invariants, dependency rules, risk register, side-effect boundaries, and tests. Read-only workflow.
description: Architecture-aware review against canonical structured YAML artifacts. Read-only workflow; no legacy prose docs.
---
# Architecture Code Review
# Architecture Code Review — Structured API Only
Goal: review proposed changes for correctness, drift, data consistency, side-effect boundary violations, and missing tests.
Goal: review diffs for correctness, drift, data consistency, side-effect boundaries, contract compatibility, and tests using YAML artifacts from the resolved structured docs root.
## Scope Argument
Review prompts accept an optional `[scope]` argument. Use it to focus review on a module, package, app, service, directory, or bounded domain area when a diff spans multiple areas. Still inspect immediate dependencies and contracts needed to judge correctness.
## Structured Artifact API Contract
## Artifact Compatibility Contract
Legacy prose artifacts are deprecated. Do not create, update, or rely on `docs/agent/*.md`, scoped prose docs, or generated human-readable Markdown views. Use structured YAML for canonical artifacts. Root `AGENTS.md` remains a harness interoperability file and may be generated/updated only by workflows that explicitly say so.
Architecture review accepts artifacts produced by both `safe-start` and `codebase-recon`.
Resolved structured docs root:
Canonical repo-level docs may include:
Treat `docs/agent/api` as a logical layout rooted at a resolved structured docs root, not a fixed repo path.
```text
docs/agent/
REPO_INVENTORY.md
PROJECT_INTENT.md
ARCHITECTURE.md
DATA_FLOW.md
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
TESTING_STRATEGY.md
VALIDATION_BASELINE.md
SCOPES.md
```
Resolution rules:
1. Resolve `workspace_root` with `git rev-parse --show-toplevel 2>/dev/null` or fallback to `pwd`.
2. `safe-start` always creates and uses the initial repo-local root: `<workspace_root>/docs/agent/api`.
3. Review reads repo-local only when `<workspace_root>/docs/agent/api` already exists.
4. Otherwise read the global overlay root: `~/.pi/agent/workspaces/<workspace-fingerprint>/docs/agent/api`.
5. Derive `<workspace-fingerprint>` deterministically from the canonical `workspace_root` path and keep it stable for the same workspace.
6. Do not create new repo-local structured docs in unadopted repos unless the user explicitly asks for repo-local adoption there.
Respect artifact headers when present:
Logical structured layout under the resolved docs root:
```text
Status: current | partial | stale
Evidence: planned | observed | mixed
Last validated: unknown | <date>
repo/
scopes.yaml
repo-inventory.yaml
project-intent.yaml
architecture.yaml
data-flow.yaml
data-model.yaml
invariants.yaml
dependency-rules.yaml
design-issues.yaml
risk-register.yaml
change-guide.yaml
testing-strategy.yaml
validation-baseline.yaml
contracts.yaml
adr.yaml
agent-operating-guide.yaml
scopes/
by-path/<repo-relative-path>/...
by-domain/<slug>/...
```
Treat `planned` docs as design intent, not source evidence. Use source diff and observed docs as implementation truth. Report divergence from intent only when it is unacknowledged, risky, or violates current docs/contracts.
Every structured artifact must conform to `../_shared/references/schemas/common.schema.json` plus its artifact-specific schema. Do not inline, invent, or vary envelope fields.
## Context Budget and Non-Duplication
Stable IDs required: `scope:*`, `component:*`, `entity:*`, `invariant:*`, `risk:*`, `contract:*`, `flow:*`, `command:*`, `issue:*`, `adr:*`, `testplan:*`.
Review should not load every artifact by default. Read router docs needed to locate scope, then owner artifacts relevant to changed semantics.
Ownership rules:
- `scopes`: scope routing, ownership, cross-scope discovery only.
- `repo-inventory`: file tree, commands index, entry points, external boundaries, configs.
- `validation-baseline`: command status, blockers, recommended validation order.
- `project-intent`: goals, users, journeys, non-goals, constraints, assumptions.
- `architecture`: components, architecture style, side-effect boundaries, high-level flow refs.
- `data-flow`: typed flow graph/steps, inputs, outputs, error states.
- `data-model`: entities, IDs, schemas, relationships, lifecycles, serialized formats.
- `invariants`: rules, forbidden states, enforcement locations, invariant-test refs.
- `dependency-rules`: layers, allowed/forbidden dependencies, violations, coupling hotspots.
- `design-issues`: structural drift, deferred decisions, ambiguity, ownership gaps.
- `risk-register`: failure modes, severity/confidence, affected refs, suggested tests/fixes.
- `contracts`: cross-scope APIs, schemas, events, generated clients, DB/file/deployment/env contracts.
- `testing-strategy`: test topology, coverage gaps, risk-to-test priorities.
- `change-guide`: workflow routing and checklists; references owner artifacts, duplicates no facts.
- `adr`: structured decision records with bounded prose fields.
- `agent-operating-guide`: structured source for agent operating rules. Root `AGENTS.md` may mirror this in compact harness-readable Markdown when produced by safe-start or codebase-recon Pass 6.
Artifact ownership rules:
- `CHANGE_GUIDE.md` routes workflow; semantic truth lives in specific docs.
- `REPO_INVENTORY.md` maps files/entry points/command names; `VALIDATION_BASELINE.md` owns command status/blockers.
- `ARCHITECTURE.md` owns structure and side-effect boundaries; `DEPENDENCY_RULES.md` owns import/dependency direction.
- `DATA_FLOW.md` owns lifecycles and transformations; `DATA_MODEL.md` owns schemas/entities; `INVARIANTS.md` owns rules/forbidden states.
- `DESIGN_ISSUES.md` owns drift/deferred design problems; `RISK_REGISTER.md` owns failure modes and risk-tested fixes.
- `TESTING_STRATEGY.md` owns test approach/gaps; `VALIDATION_BASELINE.md` owns exact validation status.
- `SCOPES.md` routes to scoped docs; scoped docs own local detail, top-level docs hold repo-wide summary.
Redundancy rule: define each fact in its owner artifact exactly once. Other artifacts reference IDs.
Prose rule: bounded prose allowed only in `summary`, `notes`, `rationale`, `context`, `decision`, `recommended_action`, and similar scalar fields.
Scope rule: if focus is path-like, read under `<docs-root>/scopes/by-path/<focus>/`; otherwise under `<docs-root>/scopes/by-domain/<slug>/`. Always resolve scope from `<docs-root>/repo/scopes.yaml` when present.
Flag review findings when a change duplicates detailed semantic truth across artifacts instead of updating the owner artifact and linking from router docs.
## Scoped Docs Discovery
Architecture review works with both legacy unscoped docs and hierarchical scoped docs.
## Runtime Schema Loading
If `docs/agent/SCOPES.md` is absent:
- review against top-level `docs/agent/*.md` only
When a workflow creates, updates, migrates, or validates structured artifacts, read `../_shared/references/artifact-api.md` first. Then read only the shared skill package schemas needed for the artifacts being written:
- `../_shared/references/schemas/common.schema.json`
- `../_shared/references/schemas/<artifact-file-base>.schema.json`
If `docs/agent/SCOPES.md` is present:
- read it before selecting deeper docs
- match diff paths and explicit scope arguments to `path` scopes by longest repo-relative path prefix
- use domain scopes only when review target, scope tags, or contract links make them relevant
- read matching scoped `README.md` only if present, then task-relevant scoped docs
- read top-level docs as fallback for missing categories and repo-wide rules
- safe-start scoped docs may include `PROJECT_INTENT.md`, `DATA_FLOW.md`, `TESTING_STRATEGY.md`, and `VALIDATION_BASELINE.md`; read them only when relevant to changed files/behavior
- for cross-scope diffs, read relevant scoped `CONTRACTS.md` and `DEPENDENCY_RULES.md` from each touched owner/consumer scope
- verify matched source paths still exist before treating scoped docs as current
- when scoped docs are marked `planned`, use them as intent and verify implementation-sensitive claims against source evidence
Do not read all schemas. Do not use templates. Schemas are runtime API contracts; project docs outside the shared runtime refs are maintainer aids unless the user asks about this package itself.
## Structured Artifact Write/Update Protocol
Use this protocol whenever creating or updating YAML artifacts.
### 1. Scope and owner resolution
1. Resolve scope first from task/focus and `<docs-root>/repo/scopes.yaml` when present.
2. Path focus uses longest prefix match; domain focus requires explicit domain/contract/task evidence.
3. Select the single owner artifact for each fact using the ownership rules above.
4. Never duplicate owner facts in router/checklist artifacts; reference stable IDs instead.
### 2. Read-before-write
1. Read the existing target YAML if it exists.
2. Read directly referenced owner artifacts needed to preserve refs and avoid duplication.
3. If target YAML is absent, create it with the common envelope and artifact-specific top-level keys.
4. Preserve unknown fields unless they conflict with this protocol; do not silently drop agent/user-added structured data.
### 3. Stable ID generation
1. Reuse existing IDs whenever the semantic object is the same, even if name/path changed.
2. New IDs use deterministic slugs from owner scope + semantic name: `risk:<slug>`, `entity:<slug>`, `component:<slug>`, etc.
3. If two objects slug-collide, append shortest stable discriminator from path/component/contract, not a random suffix.
4. Never renumber IDs because order changed.
### 4. Upsert semantics
For each discovered fact/object:
1. Match existing record by ID first.
2. If no ID match, match by stable source-of-truth fields: path+symbol, contract source path, command string+cwd, entity name+owner scope, rule owner+kind.
3. If matched, update only changed fields, append/refresh evidence, and preserve unrelated fields.
4. If unmatched, insert new record in deterministic order by ID or explicit `order` field.
5. If an existing observed record is no longer supported, do not delete it by default. Mark `status: stale` or `deprecated`, add evidence/unknown explaining why, and link replacement ID when known.
6. Delete only records known to be accidental duplicates or malformed, and mention deletion in final response.
### 5. Evidence and confidence
1. Every observed record needs at least one evidence ref with file/symbol/command/doc/diff observation.
2. Planned records may use `evidence_mode: planned` and confidence `low` or `medium`.
3. Mixed records must separate observed fields from planned/assumed fields via evidence refs or `unknowns`.
4. Do not upgrade `status: current` or confidence `high` without source or command evidence.
### 6. Reference integrity
Before writing final artifacts:
1. Check every `*_ref`, `*_refs`, and `depends_on` ID points to a record in the same artifact set or is explicitly listed as external/unknown.
2. Prefer adding missing owner records as compact stubs over leaving dangling refs.
3. For cross-scope refs, ensure `scopes.yaml` and `contracts.yaml` identify owner/consumer relationship.
4. If ownership is ambiguous, create/update `design-issues.yaml` with `kind: ownership_gap` and reference it.
### 7. Status transitions
Allowed transitions:
- `planned -> partial -> current`
- `current -> stale -> current`
- `current|stale|partial -> deprecated`
Rules:
- `current` requires sufficient observed evidence for the represented scope.
- `partial` means useful but incomplete evidence.
- `stale` means contradicted by newer source evidence or missing source path.
- `deprecated` means superseded; include `replacement_ref` when known.
### 8. Deterministic formatting
1. Use YAML with two-space indentation.
2. Use stable top-level key order: envelope keys first, artifact-specific keys next.
3. Sort unordered arrays by `id`; keep ordered flow/checklist arrays by `order`.
4. Use `null`, `[]`, or `{}` consistently rather than omitting required envelope fields.
5. Keep prose scalar fields concise; no long narrative blocks.
### 9. Validation before completion
Perform best-effort validation after writing:
1. Re-read changed YAML for parse/syntax sanity when practical.
2. Validate against the shared schemas by inspection/re-read: envelope keys, artifact-specific top-level keys, required arrays/items, stable ID prefixes, and obvious dangling refs.
3. Verify no legacy Markdown artifacts were created or updated by the workflow, except root `AGENTS.md` when explicitly produced for harness interoperability.
4. Report changed YAML files, validation performed, unresolved unknowns, and any intentionally stale/deprecated records.
## Invocation
Use this skill directly or use `/review-arch` as the prompt-template shortcut for architecture-aware diff review.
## Rules
- Do not edit code.
- Review current diff unless user specifies another target.
- Do not explicitly read `AGENTS.md`; pi injects root `AGENTS.md` automatically.
- Read only relevant deeper docs:
- `docs/agent/CHANGE_GUIDE.md` when present
- `docs/agent/SCOPES.md` when present
- matched scoped `README.md` if present, and relevant scoped docs when present
- matching scoped `REPO_INVENTORY.md` or top-level `docs/agent/REPO_INVENTORY.md` when entry points, commands, or external boundaries matter
- matching scoped `VALIDATION_BASELINE.md` or top-level `docs/agent/VALIDATION_BASELINE.md` when build/test/tooling/validation behavior changes; if absent, infer validation expectations from package/build files and note missing baseline only when relevant
- `docs/agent/PROJECT_INTENT.md` for scope, non-goals, users, journeys, or product-sensitive changes
- `docs/agent/ARCHITECTURE.md`
- `docs/agent/DATA_FLOW.md` for user journeys, pipelines, transformations, side effects, and error states
- `docs/agent/DATA_MODEL.md`
- `docs/agent/INVARIANTS.md`
- `docs/agent/DEPENDENCY_RULES.md`
- `docs/agent/RISK_REGISTER.md`
- `docs/agent/DESIGN_ISSUES.md` for known drift, deferred decisions, or refactor risks
- `docs/agent/TESTING_STRATEGY.md` for test coverage expectations and validation shape; if absent, infer from existing tests and mention missing strategy only when it materially affects review confidence
- scoped `CONTRACTS.md` files for touched cross-scope APIs, shared types, schemas, events, generated clients, or persistence boundaries
- Prioritize correctness, architecture drift, data consistency, side-effect boundaries, public contracts, and tests.
- Ignore style unless it affects maintainability or correctness.
- No generic comments.
- Every finding needs evidence and fix direction.
- Classify severity: critical / high / medium / low.
- Read-only. Do not edit code or artifacts.
- Review current diff unless user specifies target.
- Do not read legacy prose Markdown docs.
- Read `repo/scopes.yaml` first if present; match changed paths by longest prefix; then read relevant owner YAML artifacts.
- Every finding needs severity, location, evidence, owner artifact refs, why it matters, suggested fix.
- Prioritize correctness, invariants, contracts, dependency rules, side-effect boundaries, known risks, and tests.
## Review Checklist
- Does diff match documented architecture and dependency directions?
- Does diff preserve project intent/non-goals, or intentionally update them?
- Are invariants preserved or intentionally updated?
- Are data model/schema changes documented and tested?
- Are data-flow, transformation, side-effect, or error-state changes documented and tested?
- Are side effects kept at existing boundaries?
- Are public contracts/backward compatibility respected?
- Are known risk areas or `DESIGN_ISSUES.md` items touched or worsened?
- Are tests sufficient for changed behavior and aligned with `TESTING_STRATEGY.md` when present?
- Are validation baseline commands still correct after build/test/tooling changes?
- If scoped docs exist, did diff update owner/consumer docs and `SCOPES.md` where ownership/contracts changed?
- Did implementation combine feature, bug fix, and refactoring accidentally?
- Are docs updated only for durable semantic changes?
- Are detailed facts placed in the owner artifact instead of duplicated across router/index docs?
- Are docs marked `planned` now backed by observed implementation, still valid as intent, or stale?
- Diff matches `architecture.yaml` components/boundaries.
- Diff respects `dependency-rules.yaml`.
- Data/schema changes update `data-model.yaml` and `contracts.yaml` as owner artifacts.
- Flow/error-state changes update `data-flow.yaml`.
- Invariants in `invariants.yaml` remain enforced/tested.
- Known risks in `risk-register.yaml` are not worsened.
- Design drift in `design-issues.yaml` is addressed or not worsened.
- Tests align with `testing-strategy.yaml` and `validation-baseline.yaml` commands.
- Scope ownership and contract owner/consumer refs remain valid in `scopes.yaml` and `contracts.yaml`.
## Output
1. Summary verdict:
- approve
- approve with comments
- request changes
2. Findings, each with:
- Severity
- Location
- Problem
- Evidence
- Why it matters
- Suggested fix
1. Verdict: approve | approve with comments | request changes
2. Findings: severity, location, problem, evidence, owner refs, impact, suggested fix
3. Missing tests
4. Documentation updates needed
4. Structured artifact updates needed
5. Architecture drift risk
6. Final recommendation
---
name: codebase-recon
description: Reconstruction workflow for unfamiliar or undocumented codebases. Use to create compact semantic artifacts for architecture, data model, invariants, dependency rules, risks, root AGENTS.md, change guide, consolidation, ADRs, and risk-to-test planning. Supports numbered passes and all-in-one mode for small/simple repos.
description: Structured reconstruction workflow for unfamiliar or undocumented codebases. Produces agent-first YAML artifacts only under a resolved structured docs root, with no prose Markdown fallback.
---
# Codebase Reconstruction
# Codebase Reconstruction — Structured API Only
Goal: build durable, compact project understanding for future agents through bounded reconstruction passes.
Goal: reconstruct durable project understanding into canonical YAML artifacts for coding-agent ingestion.
## Core Rules
- Work in bounded passes.
- Prefer one session per pass for large or unfamiliar repos.
- Allow all-in-one mode when user asks for it and repo appears small/simple enough for reliable sequential reconstruction.
- Do not edit production code during reconstruction.
- Each pass produces or updates one compact artifact.
- Later passes read prior artifacts instead of re-reading whole repo.
- Mark uncertainty as `Observed` with confidence: low / medium / high.
- Cite evidence: files, symbols, commands, tests.
- Write/update project-root `AGENTS.md`; never write `docs/AGENTS.md` or `docs/agent/AGENTS.md`.
- Do not tell agent to read `AGENTS.md`; the harness injects it automatically in new sessions.
- Consolidation is part of this workflow.
## Structured Artifact API Contract
## Artifact Compatibility Contract
Legacy prose artifacts are deprecated. Do not create, update, or rely on `docs/agent/*.md`, scoped prose docs, or generated human-readable Markdown views. Use structured YAML for canonical artifacts. Root `AGENTS.md` remains a harness interoperability file and may be generated/updated only by workflows that explicitly say so.
Codebase-recon artifacts must remain compatible with projects bootstrapped by `safe-start` and later changed by `safe-change`.
Resolved structured docs root:
Canonical repo-level artifacts:
Treat `docs/agent/api` as a logical layout rooted at a resolved structured docs root, not a fixed repo path.
```text
AGENTS.md
Resolution rules:
1. Resolve `workspace_root` with `git rev-parse --show-toplevel 2>/dev/null` or fallback to `pwd`.
2. `safe-start` always creates and uses the initial repo-local root: `<workspace_root>/docs/agent/api`.
3. `codebase-recon` uses repo-local only when `<workspace_root>/docs/agent/api` already exists.
4. Otherwise use the global overlay root: `~/.pi/agent/workspaces/<workspace-fingerprint>/docs/agent/api`.
5. Derive `<workspace-fingerprint>` deterministically from the canonical `workspace_root` path and keep it stable for the same workspace.
6. Do not create new repo-local structured docs in unadopted repos unless the user explicitly asks for repo-local adoption there.
docs/
agent/
REPO_INVENTORY.md
PROJECT_INTENT.md # preserve/update when present; create only when useful
ARCHITECTURE.md
DATA_FLOW.md # preserve/update when present; create only when useful
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
TESTING_STRATEGY.md # required baseline artifact; may state unknowns/gaps
VALIDATION_BASELINE.md # required baseline artifact; may state blockers/not run
adr/
0001-observed-architecture.md
```
Logical structured layout under the resolved docs root:
Artifact header guidance when creating or updating durable docs:
```text
Status: current | partial | stale
Evidence: planned | observed | mixed
Last validated: unknown | <date>
repo/
scopes.yaml
repo-inventory.yaml
project-intent.yaml
architecture.yaml
data-flow.yaml
data-model.yaml
invariants.yaml
dependency-rules.yaml
design-issues.yaml
risk-register.yaml
change-guide.yaml
testing-strategy.yaml
validation-baseline.yaml
contracts.yaml
adr.yaml
agent-operating-guide.yaml
scopes/
by-path/<repo-relative-path>/...
by-domain/<slug>/...
```
Treat `safe-start` `planned` docs as intent until source evidence confirms them. Recon output should prefer `observed` evidence and should not silently delete intent docs; mark drift in `DESIGN_ISSUES.md` or `RISK_REGISTER.md` when intent and implementation disagree.
Every structured artifact must conform to `../_shared/references/schemas/common.schema.json` plus its artifact-specific schema. Do not inline, invent, or vary envelope fields.
## Context Budget and Non-Duplication
Stable IDs required: `scope:*`, `component:*`, `entity:*`, `invariant:*`, `risk:*`, `contract:*`, `flow:*`, `command:*`, `issue:*`, `adr:*`, `testplan:*`.
Each artifact should be either a source of truth for one semantic category or an index/router to other docs. Do not make every artifact a summary of every other artifact.
Ownership rules:
- `scopes`: scope routing, ownership, cross-scope discovery only.
- `repo-inventory`: file tree, commands index, entry points, external boundaries, configs.
- `validation-baseline`: command status, blockers, recommended validation order.
- `project-intent`: goals, users, journeys, non-goals, constraints, assumptions.
- `architecture`: components, architecture style, side-effect boundaries, high-level flow refs.
- `data-flow`: typed flow graph/steps, inputs, outputs, error states.
- `data-model`: entities, IDs, schemas, relationships, lifecycles, serialized formats.
- `invariants`: rules, forbidden states, enforcement locations, invariant-test refs.
- `dependency-rules`: layers, allowed/forbidden dependencies, violations, coupling hotspots.
- `design-issues`: structural drift, deferred decisions, ambiguity, ownership gaps.
- `risk-register`: failure modes, severity/confidence, affected refs, suggested tests/fixes.
- `contracts`: cross-scope APIs, schemas, events, generated clients, DB/file/deployment/env contracts.
- `testing-strategy`: test topology, coverage gaps, risk-to-test priorities.
- `change-guide`: workflow routing and checklists; references owner artifacts, duplicates no facts.
- `adr`: structured decision records with bounded prose fields.
- `agent-operating-guide`: structured source for agent operating rules. Root `AGENTS.md` may mirror this in compact harness-readable Markdown when produced by safe-start or codebase-recon Pass 6.
Artifact ownership:
- `AGENTS.md`: injected operating rules, forbidden shortcuts, validation expectations, and links only.
- `CHANGE_GUIDE.md`: workflow and doc-routing guide; link to semantic docs instead of repeating them.
- `SCOPES.md`: routing table for scoped docs; no detailed architecture or contract prose.
- `REPO_INVENTORY.md`: file tree, entry points, commands index, external boundaries; no architecture judgments.
- `PROJECT_INTENT.md`: product/user goals, non-goals, constraints, assumptions.
- `ARCHITECTURE.md`: components, boundaries, side-effect boundaries, high-level execution flows.
- `DEPENDENCY_RULES.md`: allowed/forbidden dependency direction and import boundaries.
- `DATA_FLOW.md`: input -> transformation -> output lifecycles, events, request paths, error states.
- `DATA_MODEL.md`: entities, schemas, IDs, relationships, persisted/serialized formats.
- `INVARIANTS.md`: rules, forbidden states, lifecycle constraints, enforcement locations.
- `DESIGN_ISSUES.md`: design drift, unresolved design problems, deferred decisions.
- `RISK_REGISTER.md`: failure modes with severity, evidence, failure scenario, suggested test/fix.
- `TESTING_STRATEGY.md`: test approach, coverage gaps, risk-to-test priorities.
- `VALIDATION_BASELINE.md`: exact commands, last status, blockers, next best checks.
- `CONTRACTS.md`: cross-scope APIs, schemas, events, generated clients, persistence/deployment interfaces.
Redundancy rule: define each fact in its owner artifact exactly once. Other artifacts reference IDs.
Current truth rule: canonical YAML artifacts represent current state, not audit history. Remove resolved or superseded records from canonical owner artifacts by default. Keep them only when another live record still references them or an active migration requires temporary continuity. Use Git history, PRs, issues, or ADRs for audit/history.
Prose rule: bounded prose allowed only in `summary`, `notes`, `rationale`, `context`, `decision`, `recommended_action`, and similar scalar fields.
Scope rule: if focus is path-like, write under `<docs-root>/scopes/by-path/<focus>/`; otherwise under `<docs-root>/scopes/by-domain/<slug>/`. Always update `<docs-root>/repo/scopes.yaml`.
Duplication rules:
- Prefer links/references over copied detail.
- If `VALIDATION_BASELINE.md` exists, `REPO_INVENTORY.md` may list command names but should link to baseline for status/blockers.
- If `TESTING_STRATEGY.md` exists, `CHANGE_GUIDE.md` should link to it for testing details.
- Top-level docs summarize stable repo-wide truths; scoped docs hold local detail.
- If a required artifact has little evidence, create a compact stub with `No known ...`, `Unknown`, or `Not yet validated`, not boilerplate prose.
## Target Artifacts
Unscoped/repo-level artifacts required by recon passes:
## Runtime Schema Loading
```text
AGENTS.md
When a workflow creates, updates, migrates, or validates structured artifacts, read `../_shared/references/artifact-api.md` first. Then read only the shared skill package schemas needed for the artifacts being written:
- `../_shared/references/schemas/common.schema.json`
- `../_shared/references/schemas/<artifact-file-base>.schema.json`
docs/
agent/
REPO_INVENTORY.md
ARCHITECTURE.md
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
TESTING_STRATEGY.md
VALIDATION_BASELINE.md
adr/
0001-observed-architecture.md
```
Do not read all schemas. Do not use templates. Schemas are runtime API contracts; project docs outside the shared runtime refs are maintainer aids unless the user asks about this package itself.
Scoped artifacts, created only when a pass receives a focus argument. Safe-start-compatible scoped docs may contain additional intent/flow/test/validation artifacts; preserve them when present.
## Structured Artifact Write/Update Protocol
```text
docs/
agent/
scopes/
by-path/<repo-relative-path>/
README.md # optional local index for large/complex scopes
REPO_INVENTORY.md
PROJECT_INTENT.md # preserve/update when present; create only when useful
ARCHITECTURE.md
DATA_FLOW.md # preserve/update when present; create only when useful
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
TESTING_STRATEGY.md # required when Pass 10 runs for this scope
VALIDATION_BASELINE.md # required when Pass 1 runs for this scope
CONTRACTS.md
by-domain/<domain-slug>/
README.md # optional local index for large/complex scopes
PROJECT_INTENT.md # preserve/update when present; create only when useful
ARCHITECTURE.md
DATA_FLOW.md # preserve/update when present; create only when useful
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
TESTING_STRATEGY.md # required when Pass 10 runs for this scope
VALIDATION_BASELINE.md # required when Pass 1 runs for this scope
CONTRACTS.md
```
Use this protocol whenever creating or updating YAML artifacts.
`docs/agent/SCOPES.md` is created when scoped artifacts exist and acts as their registry. Top-level docs remain valid and are used as repo-level summaries/fallbacks.
### 1. Scope and owner resolution
## Focus Argument and Scoped Artifacts
1. Resolve scope first from task/focus and `<docs-root>/repo/scopes.yaml` when present.
2. Path focus uses longest prefix match; domain focus requires explicit domain/contract/task evidence.
3. Select the single owner artifact for each fact using the ownership rules above.
4. Never duplicate owner facts in router/checklist artifacts; reference stable IDs instead.
Pass prompts accept an optional `[focus]` argument. Use it to scope reconstruction to a module, package, app, service, directory, or bounded domain area, especially in monorepos.
### 2. Read-before-write
Examples:
- `/recon-01-inventory packages/api`
- `/recon-02-architecture apps/mobile auth flow`
- `/skill:codebase-recon pass-03-data-invariants services/billing`
1. Read the existing target YAML if it exists.
2. Read directly referenced owner artifacts needed to preserve refs and avoid duplication.
3. If target YAML is absent, create it with the common envelope and artifact-specific top-level keys.
4. Preserve unknown fields unless they conflict with this protocol; do not silently drop agent/user-added structured data.
When focus is absent:
- run the pass in unscoped mode
- write/update the standard top-level `docs/agent/*.md` artifact for the pass
- if scoped artifacts already exist, use them only when the pass explicitly calls for consolidation
### 3. Stable ID generation
When focus is provided:
- inspect only the focused area plus immediate dependencies, entry points, tests, and external boundaries needed to understand it
- if focus is an existing repo-relative path, write to `docs/agent/scopes/by-path/<focus>/`
- if focus is not a path, write to `docs/agent/scopes/by-domain/<slug>/`
- update `docs/agent/SCOPES.md` with scope path, docs path, status, ownership, and external contracts
- optionally create/update scoped `README.md` only when helpful for large/complex scopes; otherwise rely on `SCOPES.md` as the index
- write pass findings into the scoped artifact for that pass, not into the top-level artifact
- include evidence paths that show the scoped boundary
- mark interactions with the rest of the repo as external dependencies/boundaries
- leave cross-scope reconciliation for Pass 8 consolidation
1. Reuse existing IDs whenever the semantic object is the same, even if name/path changed.
2. New IDs use deterministic slugs from owner scope + semantic name: `risk:<slug>`, `entity:<slug>`, `component:<slug>`, etc.
3. If two objects slug-collide, append shortest stable discriminator from path/component/contract, not a random suffix.
4. Never renumber IDs because order changed.
Scoped docs are additive and backward compatible. If a repository was reconstructed before scoped artifacts existed, keep existing top-level docs. Create `SCOPES.md` and scoped artifacts only when the first scoped pass runs. Later consolidation may summarize scoped findings into top-level docs.
### 4. Upsert semantics
This enables module/package-level reconstruction first, then later consolidation into repo-level artifacts.
For each discovered fact/object:
1. Match existing record by ID first.
2. If no ID match, match by stable source-of-truth fields: path+symbol, contract source path, command string+cwd, entity name+owner scope, rule owner+kind.
3. If matched, update only changed fields, append/refresh evidence, and preserve unrelated fields.
4. If unmatched, insert new record in deterministic order by ID or explicit `order` field.
5. If an existing observed record is resolved, superseded, or no longer supported, delete it from the canonical owner artifact by default.
6. Keep a record with `status: stale` or `deprecated` only when a live reference still depends on it or an active migration needs temporary continuity. Add evidence/unknown explaining why, and link replacement ID when known.
7. Delete accidental duplicates, malformed records, and unreferenced resolved/superseded records, and mention deletion in final response.
## Scope Registry and Contracts
### 5. Evidence and confidence
`docs/agent/SCOPES.md` should stay compact and act as the discovery index for future workflows.
1. Every observed record needs at least one evidence ref with file/symbol/command/doc/diff observation.
2. Planned records may use `evidence_mode: planned` and confidence `low` or `medium`.
3. Mixed records must separate observed fields from planned/assumed fields via evidence refs or `unknowns`.
4. Do not upgrade `status: current` or confidence `high` without source or command evidence.
Suggested columns:
- Scope
- Kind: `path` / `domain`
- Docs path
- Status: `planned` / `partial` / `current` / `stale` / `deprecated`
- Owns
- External contracts
- Last observed evidence
### 6. Reference integrity
Each scoped directory may include `CONTRACTS.md` for cross-module APIs, shared types, schemas, events, generated clients, persistence boundaries, or public internal contracts.
Before writing final artifacts:
1. Check every `*_ref`, `*_refs`, and `depends_on` ID points to a record in the same artifact set or is explicitly listed as external/unknown.
2. Prefer adding missing owner records as compact stubs over leaving dangling refs.
3. For cross-scope refs, ensure `scopes.yaml` and `contracts.yaml` identify owner/consumer relationship.
4. If ownership is ambiguous, create/update `design-issues.yaml` with `kind: ownership_gap` and reference it.
Contract rules:
- every cross-scope contract should have one owner scope
- owner scope documents source of truth, compatibility rules, tests, and consumers
- consumer scopes link to owner contract and document local usage/risk only
- do not duplicate full contract rules across scopes
- generated clients reference source schema owner
- if ownership is unclear, record it as a known unknown or drift risk
### 7. Status transitions
## Execution Modes
Allowed transitions:
- `planned -> partial -> current`
- `current -> stale -> current`
- `current|stale|partial -> deprecated`
Default: numbered-pass mode.
Use numbered-pass mode for large, complex, or unfamiliar repositories. User invokes one pass at a time, e.g.:
```text
/skill:codebase-recon pass-01-inventory
/skill:codebase-recon pass-02-architecture
/skill:codebase-recon pass-03-data-invariants
```
Equivalent numbered prompt templates are available as `/recon-01-inventory`, `/recon-02-architecture`, etc. At start of each later pass, read only relevant prior docs named in that pass. Do not re-analyze whole repository unless evidence is missing.
Optional: all-in-one mode.
Use all-in-one mode when user asks for it and repository size/complexity makes sequential reconstruction practical.
All-in-one mode may be requested with:
- `/skill:codebase-recon all`
- `/skill:codebase-recon all-in-one`
- `/recon-all`
Before all-in-one execution:
1. Inspect repository tree, package/build files, and major entry points.
2. Decide whether all-in-one mode is reasonable.
3. If not reasonable, explain why and recommend starting with Pass 1 only unless user explicitly wants to proceed.
In all-in-one mode, run passes 1–10 sequentially.
Rules:
- Write/update each artifact immediately after its pass.
- Treat written artifacts as source of truth for later passes.
- Before each pass, read only artifacts required by that pass.
- Keep each artifact compact and evidence-based.
- If repository proves larger or more complex than expected, finish current pass and report next numbered pass user should run.
- `current` requires sufficient observed evidence for the represented scope.
- `partial` means useful but incomplete evidence.
- `stale` means contradicted by newer source evidence or missing source path. Use it as a temporary migration/quarantine state, not a permanent archive state.
- `deprecated` means superseded; include `replacement_ref` when known. Use it only when a live reference still needs continuity during migration; otherwise remove the record from the canonical artifact.
Switch from all-in-one to numbered-pass mode when:
- repository is a monorepo or has multiple apps/packages/services
- source tree is too large to inspect meaningfully in one pass
- generated/vendor/build output dominates search results
- a pass requires deeper investigation than planned
- prior artifact needs substantial correction before later passes
- evidence is insufficient for next pass without broad re-reading
### 8. Deterministic formatting
## Pass 1 — Repository Inventory
1. Use YAML with two-space indentation.
2. Use stable top-level key order: envelope keys first, artifact-specific keys next.
3. Sort unordered arrays by `id`; keep ordered flow/checklist arrays by `order`.
4. Use `null`, `[]`, or `{}` consistently rather than omitting required envelope fields.
5. Keep prose scalar fields concise; no long narrative blocks.
Task: write/update `docs/agent/REPO_INVENTORY.md` and `docs/agent/VALIDATION_BASELINE.md`, or scoped `REPO_INVENTORY.md` / `VALIDATION_BASELINE.md` when focus is provided.
### 9. Validation before completion
Rules:
- No source edits.
- No architecture judgments yet.
- Inspect build/config/package files, directory tree, entry points, tests, validation commands, external boundaries.
- Create `VALIDATION_BASELINE.md` even if commands cannot be run; record exact unknowns, blockers, and next best checks.
Perform best-effort validation after writing:
1. Re-read changed YAML for parse/syntax sanity when practical.
2. Validate against the shared schemas by inspection/re-read: envelope keys, artifact-specific top-level keys, required arrays/items, stable ID prefixes, and obvious dangling refs.
3. Verify no legacy Markdown artifacts were created or updated by the workflow, except root `AGENTS.md` when explicitly produced for harness interoperability.
4. Report changed YAML files, validation performed, unresolved unknowns, and any records intentionally retained or pruned as part of compaction.
`REPO_INVENTORY.md` output sections:
- Project summary
- Build/test commands
- Entry points
- Major directories
- External dependencies/boundaries
- Unknowns
- Next recommended analysis targets
`VALIDATION_BASELINE.md` output sections:
- Install/bootstrap command(s)
- Format/lint command(s)
- Typecheck/build command(s)
- Test command(s)
- Runtime/smoke command(s)
- Last run status: run / not run / blocked
- Blockers and next best checks
## Core Rules
## Pass 2 — Architecture Reconstruction
- Do not edit production code.
- No Markdown artifacts except root `AGENTS.md` for harness interoperability in Pass 6.
- Each pass writes/updates only its owner artifacts.
- Later passes read prior YAML artifacts instead of re-reading whole repo.
- Evidence is mandatory for observed claims.
- Unknowns are explicit records, not vague prose.
- Use stable IDs and cross-references to mirror codebase ownership and relationships.
Read first: `docs/agent/REPO_INVENTORY.md`.
## Passes
Task: write/update `docs/agent/ARCHITECTURE.md`, or scoped `ARCHITECTURE.md` when focus is provided.
Users may invoke this skill directly for any pass, or use the matching prompt template as a pass shortcut.
Find:
- dominant architecture style: vertical slices, layered, MVC, clean/onion/hexagonal, framework-driven, mixed/unclear
- major modules/components
- dependency directions
- where domain logic lives
- side-effect boundaries: file I/O, network, DB, UI, shell/CLI, LLM/API
- 2–5 important execution flows from entry point to output
1. Inventory (`/recon-01-inventory`): write `repo-inventory.yaml` and `validation-baseline.yaml`; update `scopes.yaml` for focus.
2. Architecture (`/recon-02-architecture`): write `architecture.yaml` with components, style, boundaries, execution flow refs.
3. Data/invariants (`/recon-03-data-invariants`): write `data-model.yaml` and `invariants.yaml`.
4. Dependencies/drift (`/recon-04-dependency-rules`): write `dependency-rules.yaml` and `design-issues.yaml`.
5. Risks (`/recon-05-risk-register`): write `risk-register.yaml`.
6. Agent operating guide (`/recon-06-agents`): write `agent-operating-guide.yaml` and root `AGENTS.md`.
7. Change guide (`/recon-07-change-guide`): write `change-guide.yaml`.
8. Consolidation (`/recon-08-consolidate`): reconcile YAML artifacts, resolve contradictions with evidence, preserve owner-only facts.
9. ADR (`/recon-09-adr`): write `adr.yaml` with structured ADR records.
10. Risk-to-tests (`/recon-10-risk-tests`): write/update `testing-strategy.yaml`.
Output sections:
- Architecture overview
- Component map
- Dependency direction
- Main execution flows
- Side-effect boundaries
- Observed inconsistencies
- Confidence notes
All-in-one shortcut: `/recon-all` runs the pass sequence until the requested focus is complete or the repo size requires stopping at a pass boundary.
## Pass 3 — Data Model and Invariants
## Artifact Shape Source
Read first: `docs/agent/REPO_INVENTORY.md`, `docs/agent/ARCHITECTURE.md`.
Task: write/update `docs/agent/DATA_MODEL.md` and `docs/agent/INVARIANTS.md`, or scoped `DATA_MODEL.md` and `INVARIANTS.md` when focus is provided.
Focus only on semantically important data crossing module boundaries, persisted/serialized formats, configs, APIs, IDs, states, lifecycles.
Output sections:
- Core data model
- Data lifecycle
- Persisted/serialized formats
- Invariants
- Enforcement locations
- Unenforced assumptions
- Risk notes
## Pass 4 — Dependency Rules and Drift Detection
Read first: `docs/agent/REPO_INVENTORY.md`, `docs/agent/ARCHITECTURE.md`, `docs/agent/DATA_MODEL.md`, `docs/agent/INVARIANTS.md`.
Task: write/update `docs/agent/DEPENDENCY_RULES.md` and `docs/agent/DESIGN_ISSUES.md`, or scoped `DEPENDENCY_RULES.md` and `DESIGN_ISSUES.md` when focus is provided.
Find:
- observed module dependencies
- cycles
- cross-slice coupling
- shared/common/utils dumping-ground risks
- UI/CLI/framework code containing domain logic
- core logic with side effects
- unstable dependencies leaking into stable code
Output sections:
- Observed dependency rules
- Recommended dependency rules
- Violations
- Coupling hotspots
- Shared/common risk areas
- Drift risks
- Suggested future architecture tests
## Pass 5 — Bug-Risk and Subtle-Failure Analysis
Read first: `docs/agent/ARCHITECTURE.md`, `docs/agent/DATA_MODEL.md`, `docs/agent/INVARIANTS.md`, `docs/agent/DEPENDENCY_RULES.md`.
Task: write/update `docs/agent/RISK_REGISTER.md`, or scoped `RISK_REGISTER.md` when focus is provided.
Find high-signal risks only:
- inconsistent state transitions
- unchecked null/None/undefined
- shared mutable data
- ordering assumptions
- ID/reference mismatch
- error handling gaps
- concurrency/async/races
- persistence corruption
- API/schema mismatch
- missing tests around critical invariants
For each risk:
- Title
- Severity: low / medium / high / critical
- Confidence: low / medium / high
- Evidence
- Failure scenario
- Affected files
- Suggested test
- Suggested fix direction
## Pass 6 — Root Agent Operating Guide
Read first: `docs/agent/ARCHITECTURE.md`, `docs/agent/INVARIANTS.md`, `docs/agent/DATA_MODEL.md`, `docs/agent/DEPENDENCY_RULES.md`, `docs/agent/RISK_REGISTER.md`, `docs/agent/DESIGN_ISSUES.md`; when present, also read `docs/agent/PROJECT_INTENT.md`, `docs/agent/DATA_FLOW.md`, `docs/agent/TESTING_STRATEGY.md`, and `docs/agent/VALIDATION_BASELINE.md` only for operating guidance that affects future changes.
Task: write/update root `AGENTS.md`.
Rules:
- Keep compact and operational.
- Link to deeper docs; do not duplicate them.
- Treat `AGENTS.md` as an index of rules and pointers, not a semantic artifact dump.
- Focus on rules that prevent drift and bugs.
- Include design/implementation/verification workflow.
- If `docs/agent/SCOPES.md` exists, include scoped-doc discovery guidance: future agents should check `SCOPES.md`, use longest matching path scope first, then repo-level fallback.
- Merge with existing root `AGENTS.md` if present.
- Do not create `docs/AGENTS.md` or `docs/agent/AGENTS.md`.
Suggested sections:
- Project summary
- Architecture rules
- Data model rules
- Invariants not to violate
- Side-effect boundaries
- How to make a change
- How to validate a change
- When to update docs
- Forbidden shortcuts
- Current high-risk areas
## Pass 7 — Change Guide
Read first: `docs/agent/ARCHITECTURE.md`, `docs/agent/DATA_MODEL.md`, `docs/agent/INVARIANTS.md`, `docs/agent/DEPENDENCY_RULES.md`; when present, also read `docs/agent/PROJECT_INTENT.md`, `docs/agent/DATA_FLOW.md`, `docs/agent/TESTING_STRATEGY.md`, and `docs/agent/VALIDATION_BASELINE.md` for scope, data-flow tracing, test guidance, and validation commands.
Task: write/update `docs/agent/CHANGE_GUIDE.md`, or scoped `CHANGE_GUIDE.md` when focus is provided.
Required sections:
- Before coding
- How to locate affected slice/module
- How to discover matching scoped docs through `docs/agent/SCOPES.md` when present
- How to trace data flow
- How to add/modify data structures
- How to add side effects safely
- How to add tests
- How to avoid architecture drift
- Documentation update checklist, including compatible safe-start docs when present
- Final verification checklist
## Pass 8 — Consolidation
Read root `AGENTS.md` if it exists, all relevant top-level `docs/agent/*.md`, `docs/agent/SCOPES.md` if present, and relevant scoped docs under `docs/agent/scopes/**` created by previous passes.
Task: consolidate artifacts.
Rules:
- No source code edits.
- Reconcile contradictions; do not silently delete disagreement evidence.
- Preserve compatible safe-start docs (`PROJECT_INTENT.md`, `DATA_FLOW.md`, `TESTING_STRATEGY.md`, `VALIDATION_BASELINE.md`) at top-level and scoped paths when present; update status/evidence headers and cross-links when source evidence proves them current/stale.
- Read `docs/agent/SCOPES.md` first when present; use it to select relevant scoped summaries and changed/relevant scoped docs.
- When scoped passes disagree, resolve from source evidence where possible, assign/clarify ownership for shared contracts where evidence supports it, or record the disagreement as a drift risk / `Known Unknown` with cited evidence.
- Keep detailed scope-specific facts in scoped artifacts; summarize only stable repo-level guidance in top-level docs.
- Update `SCOPES.md` status/currentness when consolidation identifies stale, deprecated, or reconciled scopes.
- De-duplicate repeated facts only after preserving the strongest evidence paths and any materially different scope-specific observations.
- Keep root `AGENTS.md` short and operational.
- Ensure `ARCHITECTURE.md` describes structure, not line-by-line code.
- Ensure `INVARIANTS.md` contains rules, not implementation notes.
- Ensure `RISK_REGISTER.md` contains actionable risks, not generic design concerns owned by `DESIGN_ISSUES.md`.
- Ensure `CHANGE_GUIDE.md` routes readers to source-of-truth docs instead of duplicating them.
- Ensure `VALIDATION_BASELINE.md` exists after repo-level Pass 1 has run and names commands/blockers rather than broad strategy.
- Ensure `TESTING_STRATEGY.md` exists after repo-level Pass 10 has run and names observed test structure, gaps, and risk-to-test priorities.
- Preserve uncertainty markers where evidence incomplete.
- Add `Known Unknowns` where useful.
## Pass 9 — Observed-Architecture ADR
Read first: `docs/agent/ARCHITECTURE.md`, `docs/agent/DEPENDENCY_RULES.md`, `docs/agent/DATA_MODEL.md`, `docs/agent/INVARIANTS.md`, `docs/agent/DESIGN_ISSUES.md`.
Task: write `docs/agent/adr/0001-observed-architecture.md`.
Structure:
- ADR 0001: Observed Current Architecture
- Status: Accepted as observed baseline
- Context
- Decision
- Evidence
- Consequences
- Known Issues
- Follow-up Actions
## Pass 10 — Risk-to-Tests Plan
Read first: `docs/agent/RISK_REGISTER.md`, `docs/agent/INVARIANTS.md`, `docs/agent/DATA_MODEL.md`, `docs/agent/CHANGE_GUIDE.md`, `docs/agent/TESTING_STRATEGY.md`, and `docs/agent/VALIDATION_BASELINE.md`.
Task: write/update `docs/agent/TESTING_STRATEGY.md`, or scoped `TESTING_STRATEGY.md` when focus is provided, and select top 3–5 risks to convert into tests first.
Create `TESTING_STRATEGY.md` even if test coverage is sparse or unknown; record observed test types, gaps, risk-based priorities, and recommended next tests.
Selection criteria:
- high severity
- high confidence
- central invariant affected
- likely regression risk
- cheap to test
For each selected risk:
- Risk title
- Why test first
- Existing/new test file
- Test type: unit / characterization / regression / integration
- Exact scenario
- Expected behavior
- Minimal implementation plan
`TESTING_STRATEGY.md` output sections:
- Observed test structure
- Existing test types and commands
- Coverage gaps around invariants and risks
- Recommended test strategy
- Risk-to-test priorities
- Known blockers
Do not write production code in this pass.
For each pass, use the shared runtime schemas as the only shape contract: `../_shared/references/artifact-api.md`, `../_shared/references/schemas/common.schema.json`, and the matching artifact schema(s). Do not rely on prose key lists.

@@ -1,39 +0,3 @@

# Bug Fix Workflow
# Structured Bug Fix
Use for errors, regressions, failing behavior, or mismatches between expected and actual behavior.
## Bug Diagnosis
After preflight, diagnose bug before editing.
Tasks:
1. Reproduce or locate bug.
2. Identify expected behavior.
3. Identify violated invariant, contract, or public behavior.
4. Identify affected files/modules.
5. Explain likely root cause.
6. Propose minimal fix plan.
7. Propose regression test and validation commands.
Stop unless user approved implementation.
## Bug Implementation
Continue from approved bug-fix plan.
Rules:
- Follow approved plan.
- Change production code only where necessary.
- Add/update regression test unless impossible; explain if impossible.
- Do not opportunistically refactor.
- Run focused test first, then relevant broader suite.
- Update `docs/agent/RISK_REGISTER.md` or scoped `RISK_REGISTER.md` if bug corresponds to known/new risk.
- Update `docs/agent/INVARIANTS.md`, `docs/agent/DATA_MODEL.md`, `docs/agent/CHANGE_GUIDE.md`, or scoped equivalents only if fix clarifies/changes durable rules.
Output:
- Files changed
- Root cause fixed
- Tests added/updated
- Validation results
- Documentation updates
- Remaining risks/follow-up
Diagnose before edits using structured YAML artifacts only. Identify violated invariant/contract/risk refs, root cause, minimal fix, regression test plan, and validation command refs. Implement only after approval unless explicitly requested. Update `risk-register.yaml`, `invariants.yaml`, `data-model.yaml`, or `contracts.yaml` only for durable semantic changes.

@@ -1,37 +0,3 @@

# Semantic Docs Update Rules
# Structured Artifact Update Rules
Update docs only when durable semantics changed.
Update relevant top-level or scoped docs for changes to:
- `PROJECT_INTENT.md`: project intent, scope, non-goals, users, journeys, or constraints
- `REPO_INVENTORY.md`: entry points, validation commands, directories, or external boundaries
- `ARCHITECTURE.md` / `DEPENDENCY_RULES.md`: architecture or dependency direction
- `DATA_FLOW.md`: transformation pipelines, side-effect flows, or error states
- `DATA_MODEL.md`: persisted/serialized formats, schemas, API contracts, or shared types
- `INVARIANTS.md`: lifecycle rules, state transitions, validation, or ownership rules
- `CONTRACTS.md`: public/internal contracts between modules/packages/services
- `TESTING_STRATEGY.md` / `VALIDATION_BASELINE.md`: test approach or known-good validation commands
- `RISK_REGISTER.md` / `DESIGN_ISSUES.md`: known risks, design issues, deferred decisions, or risk status
- `CHANGE_GUIDE.md`: safe-change workflow guidance discovered during implementation
When artifact headers exist, update `Status`, `Evidence`, or `Last validated` only when the change or validation materially affects planned/observed/currentness.
Non-duplication rules:
- Update the owner artifact first; update router/index docs only with links or short pointers.
- Do not copy detailed architecture into `CHANGE_GUIDE.md` or `AGENTS.md`.
- Do not copy scoped-local details into top-level docs unless they changed repo-wide guidance.
- If multiple docs mention the same concept, keep only one detailed source of truth and replace other copies with references.
Do not update docs for:
- purely mechanical edits
- local implementation detail with no durable semantic meaning
- test-only changes that do not reveal changed risk/invariant guidance
- formatting, naming, or low-level cleanup without architecture impact
When scoped docs exist:
- update matched scoped docs first
- update owner `CONTRACTS.md` for contract changes
- update consumer docs only for local usage/risk changes
- update `SCOPES.md` if scope status, ownership, contracts, or evidence changed
- update top-level docs only if repo-level summary/guidance changed
- leave broader reconciliation for codebase-recon Pass 8 when multiple scopes are affected
Update only canonical YAML owner artifacts under the resolved structured docs root. Treat them as current truth, not audit history. Use repo-local docs only when `<workspace_root>/docs/agent/api` already exists; otherwise update the global overlay root. Remove resolved or superseded records by default; keep `stale`/`deprecated` records only when live references or active migrations require temporary continuity. Do not create/update Markdown except root `AGENTS.md` when `agent-operating-guide.yaml` changes and harness interoperability guidance must mirror it. Owner mapping: scopes, repo-inventory, validation-baseline, project-intent, architecture, data-flow, data-model, invariants, dependency-rules, design-issues, risk-register, contracts, testing-strategy, change-guide, adr, agent-operating-guide. Use the skill Structured Artifact Write/Update Protocol: read before write, preserve stable IDs, upsert by ID/source-of-truth fields, prune unreferenced resolved/superseded records, require evidence, validate refs, use deterministic YAML formatting, and report validation.

@@ -1,51 +0,3 @@

# Feature Workflow
# Structured Feature
Use for new behavior, API capability, UI behavior, data flow, integration, or user-facing functionality.
## Feature Design
After preflight, design before implementation.
Tasks:
1. Feature summary
2. Affected user/execution flow
3. Affected modules/files
4. Data model impact
5. Invariants affected or introduced
6. Side effects needed and boundaries
7. Dependency rule impact
8. Risks
9. Test plan
10. Minimal implementation plan
11. Documentation update plan
12. Blocking open questions only
Rules:
- Prefer extending existing concepts over new abstractions.
- Keep side effects at existing side-effect boundaries.
- Do not introduce global/shared utilities unless justified.
- Stop unless user approved implementation.
## Feature Implementation
Continue from approved feature design.
Rules:
- Follow approved design.
- Keep changes inside affected slice/module when possible.
- No unrelated refactoring.
- Add/update tests according to test plan.
- Preserve existing invariants.
- Keep side effects behind existing boundaries.
- Update docs only for durable semantic changes.
- Run focused tests, then broader validation.
Output:
- Files changed
- Feature behavior implemented
- Data model changes
- Invariants added/changed
- Tests added/updated
- Validation results
- Documentation updates
- Remaining risks/limitations
Design before edits. Identify flow/data/invariant/contract/component impacts, side-effect boundaries, risks, test plan, validation command refs, and owner YAML artifacts to update. Implement after approval unless explicitly requested.

@@ -1,39 +0,3 @@

# Universal Preflight
# Structured Preflight
Preflight comes before every non-trivial safe-change task.
Read first:
- `docs/agent/CHANGE_GUIDE.md` if present
- `docs/agent/SCOPES.md` if present; then apply `references/scoped-docs.md`
- matching scoped `REPO_INVENTORY.md` or top-level `docs/agent/REPO_INVENTORY.md` if present, for entry points, commands, and external boundaries
- matching scoped `VALIDATION_BASELINE.md` or top-level `docs/agent/VALIDATION_BASELINE.md` if present, for known-good validation commands and blockers; if absent, derive validation commands from `REPO_INVENTORY.md`, package/build files, and test config, and note missing baseline in preflight
If scoped docs match the task, read nearest scoped `README.md` only if present and only task-relevant scoped docs first. Then read only missing or repo-wide top-level docs relevant to task:
- `docs/agent/PROJECT_INTENT.md` or scoped `PROJECT_INTENT.md` for scope, non-goals, users, journeys, and product constraints
- `docs/agent/ARCHITECTURE.md` or scoped `ARCHITECTURE.md` for module/flow changes
- `docs/agent/DATA_FLOW.md` or scoped `DATA_FLOW.md` for user journeys, pipelines, transformations, side effects, and error states
- `docs/agent/DATA_MODEL.md` or scoped `DATA_MODEL.md` for data changes
- `docs/agent/INVARIANTS.md` or scoped `INVARIANTS.md` for rule-sensitive changes
- `docs/agent/DEPENDENCY_RULES.md` or scoped `DEPENDENCY_RULES.md` for imports/module boundaries
- `docs/agent/RISK_REGISTER.md` or scoped `RISK_REGISTER.md` for risky areas
- `docs/agent/DESIGN_ISSUES.md` or scoped `DESIGN_ISSUES.md` for refactoring/design work
- `docs/agent/TESTING_STRATEGY.md` or scoped `TESTING_STRATEGY.md` for test design and validation approach; if absent, infer from existing tests and note missing strategy in preflight
- scoped `CONTRACTS.md` files for touched cross-scope APIs, shared types, schemas, events, generated clients, or persistence boundaries
When artifact headers exist, treat `planned` docs as intent and verify implementation-sensitive claims against source evidence.
Context budget rules:
- Do not read every canonical artifact by default.
- Read owner artifact for the changed semantic category, plus router docs needed to find it.
- Prefer scoped docs for local detail and top-level docs for repo-wide fallback.
- If a needed owner artifact is absent, infer from source evidence and note missing artifact in preflight.
- Do not duplicate findings across docs during update planning; update the owner artifact and link from router docs.
Before editing code, produce:
1. Task classification: bug fix / feature / refactoring / risk-fix / test-only / docs-only
2. Relevant docs read
3. Affected slice/module/user flow
4. Expected files to inspect
5. Invariants/contracts at risk
6. Existing tests/validation commands
7. Whether implementation should proceed now or wait for approval
Read `<docs-root>/repo/scopes.yaml` if present, match scope, then read only relevant owner YAML artifacts under the resolved structured docs root. Do not read legacy prose docs. Use repo-local docs only when `<workspace_root>/docs/agent/api` already exists; otherwise use the global overlay root. Produce classification, artifacts read, scope, affected files, invariant/contract/risk refs, validation command refs, and approval status.

@@ -1,53 +0,3 @@

# Refactoring Workflow
# Structured Refactoring
Use for behavior-preserving structure changes, design cleanup, decomposition, dependency direction cleanup, or reducing drift. Do not combine refactoring with feature work or unrelated bug fixes.
## Refactoring Design
After preflight, design refactor before edits.
Rules:
- No behavior change.
- Treat refactoring as separate use case.
- Identify smell/design issue precisely with evidence.
- Identify tests protecting behavior.
- If tests insufficient, propose characterization tests first.
- Prefer staged refactorings over rewrites.
- Do not introduce new architecture style unless explicitly requested.
Output:
- Refactoring goal
- Current design problem
- Evidence
- Behavior to preserve
- Affected files/modules
- Invariants to preserve
- Required characterization tests
- Refactoring stages
- Validation plan
- Rollback strategy
- Documentation update plan
Stop unless user approved implementation.
## Refactoring Implementation
Continue from approved refactoring design, one smallest safe stage.
Rules:
- Preserve behavior.
- Do not combine with feature work.
- Do not fix unrelated bugs unless they block refactor.
- Add characterization tests before behavior-sensitive changes.
- Keep each change mechanically understandable.
- Run tests after each meaningful stage.
- Update docs only if durable structure/dependency/change guidance changed.
Output:
- Stage completed
- Files changed
- Behavior preserved
- Tests added/updated
- Validation results
- Documentation updates
- Remaining stages
Behavior-preserving only. Identify `design-issues.yaml` issue refs, `dependency-rules.yaml` rule refs, behavior to preserve, characterization tests, staged plan, validation command refs, rollback. Update owner YAML only when durable structure/rules changed.

@@ -1,31 +0,3 @@

# Risk-Fix Workflow
# Structured Risk Fix
Use when risk-derived tests fail or `RISK_REGISTER.md` / scoped `RISK_REGISTER.md` identifies actionable risks.
Read first:
- `docs/agent/CHANGE_GUIDE.md`
- `docs/agent/SCOPES.md` if present; then apply `references/scoped-docs.md`
- matching scoped risk/invariant/data docs when applicable
- `docs/agent/RISK_REGISTER.md`
- `docs/agent/INVARIANTS.md`
- `docs/agent/DATA_MODEL.md`
Rules:
- Do not fix all failing tests at once.
- Select one failing test or tightly related risk cluster.
- Prioritize: critical data corruption, security/safety, persistence/state inconsistency, public API/schema breakage, incorrect domain behavior, architecture boundary violation, performance/cleanup.
- Explain violated invariant.
- Identify minimal production-code change.
- Do not change test unless demonstrably wrong.
- Do not refactor unrelated code.
- Run focused test first, then surrounding suite.
- Update `docs/agent/RISK_REGISTER.md` or scoped `RISK_REGISTER.md` status.
Output:
- Selected failing test/risk cluster
- Root cause
- Invariant violated
- Minimal fix plan
- Files changed
- Validation result
- Remaining failing tests/risks
Use structured YAML artifacts only. Select one `risk-register.yaml` risk or tightly related cluster. Explain invariant violated, minimal fix, focused test, validation command refs. Update risk status and testing strategy refs after validation.

@@ -1,23 +0,3 @@

# Scoped Docs Discovery
# Structured Scoped Artifact Discovery
Safe-change works with both legacy unscoped reconstruction docs and hierarchical scoped docs.
If `docs/agent/SCOPES.md` is absent:
- use the existing top-level `docs/agent/*.md` workflow only
If `docs/agent/SCOPES.md` is present:
- read it during preflight
- match task target paths/files to `path` scopes by longest repo-relative path prefix
- use domain scopes only when task wording, scope tags, or contract links make them relevant
- read nearest matching scope `README.md` only if present
- read only task-relevant scoped docs, then top-level docs as fallback for missing categories or repo-wide rules
- standard scoped docs may include `REPO_INVENTORY.md`, `ARCHITECTURE.md`, `DATA_MODEL.md`, `INVARIANTS.md`, `DEPENDENCY_RULES.md`, `DESIGN_ISSUES.md`, `RISK_REGISTER.md`, `CHANGE_GUIDE.md`, and `CONTRACTS.md`
- safe-start scoped docs may also include `PROJECT_INTENT.md`, `DATA_FLOW.md`, `TESTING_STRATEGY.md`, and `VALIDATION_BASELINE.md`; read them only when task-relevant
- before trusting a path scope, verify the scoped source path still exists; if not, treat scoped docs as historical/stale and fall back to top-level/source evidence
- when scoped docs are marked `planned`, use them as intent and verify implementation-sensitive claims against source evidence
- if multiple scopes match with equal confidence, read all relevant scope summaries and note ambiguity in preflight
Cross-scope contract rule:
- when touched code imports, exposes, serializes, persists, or validates data across module/package/service boundaries, read local scoped `CONTRACTS.md` and linked owner `CONTRACTS.md` if present
- owner contract docs are source of truth; consumer docs describe local usage/risk only
- if contract ownership is unclear, identify it as a risk before implementation
Use `<docs-root>/repo/scopes.yaml`. Match path scopes by longest prefix; use domain scopes only by explicit task/domain/contract refs; fallback to repo only when no scope exists. Scoped YAML lives under `<docs-root>/scopes/by-path/<path>/` or `<docs-root>/scopes/by-domain/<slug>/`. Verify path scopes still exist before trusting observed claims.
---
name: safe-change
description: Safe-change workflow for documented codebases. Use for bug fixes, feature work, refactoring, risk-fix passes, test-only work, and docs-only work. Every workflow starts with preflight, then design/diagnosis, approval gate, implementation, validation, and semantic docs update only when needed.
description: Structured safe-change workflow for documented codebases. Reads and writes only canonical YAML artifacts under a resolved structured docs root.
---
# Safe Change
# Safe Change — Structured API Only
Goal: make changes in an existing documented codebase without architecture drift.
Goal: make changes without architecture drift using canonical structured artifacts.
## Task/Focus Arguments
Prompt arguments may include a target, focus, or scope. Use these to limit investigation and implementation to a module, package, app, service, directory, user flow, risk cluster, or bounded domain area. In monorepos, prefer scoped preflight/design first, then broader consolidation only when durable docs need repo-level reconciliation.
## Structured Artifact API Contract
## Core Rules
Legacy prose artifacts are deprecated. Do not create, update, or rely on `docs/agent/*.md`, scoped prose docs, or generated human-readable Markdown views. Use structured YAML for canonical artifacts. Root `AGENTS.md` remains a harness interoperability file and may be generated/updated only by workflows that explicitly say so.
- Preflight comes first for every non-trivial task. Read `references/preflight.md`.
- Do not edit code during preflight/design/diagnosis unless explicitly asked.
- Separate bug fixing, feature work, and refactoring. Never combine in one pass.
- Prefer smallest safe change inside affected slice/module.
- Preserve public behavior unless task requires changing it.
- Add regression/characterization tests when behavior is risky or uncovered.
- Run focused validation first, then relevant broader validation.
- Update docs only when durable semantics changed. Read `references/docs-update.md` when docs may need updates.
- Do not explicitly read `AGENTS.md`; The harness injects root `AGENTS.md` automatically.
Resolved structured docs root:
## Artifact Compatibility Contract
Treat `docs/agent/api` as a logical layout rooted at a resolved structured docs root, not a fixed repo path.
Safe-change accepts artifacts produced by both `safe-start` and `codebase-recon`.
Resolution rules:
1. Resolve `workspace_root` with `git rev-parse --show-toplevel 2>/dev/null` or fallback to `pwd`.
2. `safe-start` always creates and uses the initial repo-local root: `<workspace_root>/docs/agent/api`.
3. `safe-change` uses repo-local only when `<workspace_root>/docs/agent/api` already exists.
4. Otherwise use the global overlay root: `~/.pi/agent/workspaces/<workspace-fingerprint>/docs/agent/api`.
5. Derive `<workspace-fingerprint>` deterministically from the canonical `workspace_root` path and keep it stable for the same workspace.
6. Do not create new repo-local structured docs in unadopted repos unless the user explicitly asks for repo-local adoption there.
Canonical repo-level docs may include:
Logical structured layout under the resolved docs root:
```text
docs/agent/
REPO_INVENTORY.md
PROJECT_INTENT.md
ARCHITECTURE.md
DATA_FLOW.md
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
TESTING_STRATEGY.md
VALIDATION_BASELINE.md
SCOPES.md
repo/
scopes.yaml
repo-inventory.yaml
project-intent.yaml
architecture.yaml
data-flow.yaml
data-model.yaml
invariants.yaml
dependency-rules.yaml
design-issues.yaml
risk-register.yaml
change-guide.yaml
testing-strategy.yaml
validation-baseline.yaml
contracts.yaml
adr.yaml
agent-operating-guide.yaml
scopes/
by-path/<repo-relative-path>/...
by-domain/<slug>/...
```
Respect artifact headers when present:
Every structured artifact must conform to `../_shared/references/schemas/common.schema.json` plus its artifact-specific schema. Do not inline, invent, or vary envelope fields.
```text
Status: current | partial | stale
Evidence: planned | observed | mixed
Last validated: unknown | <date>
```
Stable IDs required: `scope:*`, `component:*`, `entity:*`, `invariant:*`, `risk:*`, `contract:*`, `flow:*`, `command:*`, `issue:*`, `adr:*`, `testplan:*`.
Treat `planned` docs as design intent, not source evidence. Verify against code before relying on them for implementation-sensitive claims.
Ownership rules:
- `scopes`: scope routing, ownership, cross-scope discovery only.
- `repo-inventory`: file tree, commands index, entry points, external boundaries, configs.
- `validation-baseline`: command status, blockers, recommended validation order.
- `project-intent`: goals, users, journeys, non-goals, constraints, assumptions.
- `architecture`: components, architecture style, side-effect boundaries, high-level flow refs.
- `data-flow`: typed flow graph/steps, inputs, outputs, error states.
- `data-model`: entities, IDs, schemas, relationships, lifecycles, serialized formats.
- `invariants`: rules, forbidden states, enforcement locations, invariant-test refs.
- `dependency-rules`: layers, allowed/forbidden dependencies, violations, coupling hotspots.
- `design-issues`: structural drift, deferred decisions, ambiguity, ownership gaps.
- `risk-register`: failure modes, severity/confidence, affected refs, suggested tests/fixes.
- `contracts`: cross-scope APIs, schemas, events, generated clients, DB/file/deployment/env contracts.
- `testing-strategy`: test topology, coverage gaps, risk-to-test priorities.
- `change-guide`: workflow routing and checklists; references owner artifacts, duplicates no facts.
- `adr`: structured decision records with bounded prose fields.
- `agent-operating-guide`: structured source for agent operating rules. Root `AGENTS.md` may mirror this in compact harness-readable Markdown when produced by safe-start or codebase-recon Pass 6.
## Context Budget and Non-Duplication
Redundancy rule: define each fact in its owner artifact exactly once. Other artifacts reference IDs.
Current truth rule: canonical YAML artifacts represent current state, not audit history. Remove resolved or superseded records from canonical owner artifacts by default. Keep them only when another live record still references them or an active migration requires temporary continuity. Use Git history, PRs, issues, or ADRs for audit/history.
Prose rule: bounded prose allowed only in `summary`, `notes`, `rationale`, `context`, `decision`, `recommended_action`, and similar scalar fields.
Scope rule: if focus is path-like, write under `<docs-root>/scopes/by-path/<focus>/`; otherwise under `<docs-root>/scopes/by-domain/<slug>/`. Always update `<docs-root>/repo/scopes.yaml`.
Do not read or update every artifact by default. Read only docs relevant to task category, scope, and risk. During preflight, apply `references/preflight.md`; during semantic docs updates, apply `references/docs-update.md`.
## Scoped Docs
If `docs/agent/SCOPES.md` exists or task uses a module/package/app/service/path focus, read `references/scoped-docs.md` during preflight. Scoped docs are optional and backward-compatible; if absent, use top-level `docs/agent/*.md` only.
## Runtime Schema Loading
## Workflow Selection
When a workflow creates, updates, migrates, or validates structured artifacts, read `../_shared/references/artifact-api.md` first. Then read only the shared skill package schemas needed for the artifacts being written:
- `../_shared/references/schemas/common.schema.json`
- `../_shared/references/schemas/<artifact-file-base>.schema.json`
Classify task during preflight, then read the matching reference before design, diagnosis, or implementation:
Do not read all schemas. Do not use templates. Schemas are runtime API contracts; project docs outside the shared runtime refs are maintainer aids unless the user asks about this package itself.
- bug/error/regression/failing behavior -> `references/bug-fix.md`
- new behavior/API/UI capability/integration -> `references/feature.md`
- behavior-preserving structure change/design cleanup -> `references/refactoring.md`
- known risk, failing risk-derived test, or actionable `RISK_REGISTER.md` item -> `references/risk-fix.md`
- test-only task -> use `references/preflight.md`, preserve behavior, validate focused tests, update docs only if durable risk/invariant guidance changes
- docs-only task -> use `references/docs-update.md`, do not edit production code
## Structured Artifact Write/Update Protocol
## Universal Preflight Summary
Use this protocol whenever creating or updating YAML artifacts.
Read first:
- `docs/agent/CHANGE_GUIDE.md` if present
- `docs/agent/SCOPES.md` if present; then apply `references/scoped-docs.md`
- matching scoped `REPO_INVENTORY.md` or top-level `docs/agent/REPO_INVENTORY.md` if present, for entry points, commands, and boundaries
- matching scoped `VALIDATION_BASELINE.md` or top-level `docs/agent/VALIDATION_BASELINE.md` if present, for known-good validation commands and blockers; if absent, derive validation commands from `REPO_INVENTORY.md`, package/build files, and test config, and note missing baseline in preflight
### 1. Scope and owner resolution
Read only docs relevant to task:
- project intent for scope, user-goal, non-goal, or product-sensitive changes
- architecture docs for module/flow changes
- data-flow docs for changes to user journeys, pipelines, transformations, or side effects
- data model docs for data/schema/API/type changes
- invariant docs for rule-sensitive changes
- dependency rules for imports/module boundaries
- risk register for risky areas
- design issues for refactoring/design work
- testing strategy for new/changed tests or validation approach; if `TESTING_STRATEGY.md` is absent, infer from existing tests and note missing strategy in preflight
- scoped `CONTRACTS.md` files for touched cross-scope APIs, shared types, schemas, events, generated clients, or persistence boundaries
1. Resolve scope first from task/focus and `<docs-root>/repo/scopes.yaml` when present.
2. Path focus uses longest prefix match; domain focus requires explicit domain/contract/task evidence.
3. Select the single owner artifact for each fact using the ownership rules above.
4. Never duplicate owner facts in router/checklist artifacts; reference stable IDs instead.
Before editing code, produce:
1. Task classification
2. Relevant docs read
3. Affected slice/module/user flow
4. Expected files to inspect
5. Invariants/contracts at risk
6. Existing tests/validation commands
7. Whether implementation should proceed now or wait for approval
### 2. Read-before-write
## Approval Gates
1. Read the existing target YAML if it exists.
2. Read directly referenced owner artifacts needed to preserve refs and avoid duplication.
3. If target YAML is absent, create it with the common envelope and artifact-specific top-level keys.
4. Preserve unknown fields unless they conflict with this protocol; do not silently drop agent/user-added structured data.
- Bug fixes: diagnose and propose minimal fix before implementation.
- Features: design and propose test plan before implementation.
- Refactors: design staged behavior-preserving plan before implementation.
- Risk fixes: select one failing test/risk cluster and propose minimal fix before implementation.
### 3. Stable ID generation
Stop for approval unless user explicitly asked to implement immediately.
1. Reuse existing IDs whenever the semantic object is the same, even if name/path changed.
2. New IDs use deterministic slugs from owner scope + semantic name: `risk:<slug>`, `entity:<slug>`, `component:<slug>`, etc.
3. If two objects slug-collide, append shortest stable discriminator from path/component/contract, not a random suffix.
4. Never renumber IDs because order changed.
### 4. Upsert semantics
For each discovered fact/object:
1. Match existing record by ID first.
2. If no ID match, match by stable source-of-truth fields: path+symbol, contract source path, command string+cwd, entity name+owner scope, rule owner+kind.
3. If matched, update only changed fields, append/refresh evidence, and preserve unrelated fields.
4. If unmatched, insert new record in deterministic order by ID or explicit `order` field.
5. If an existing observed record is resolved, superseded, or no longer supported, delete it from the canonical owner artifact by default.
6. Keep a record with `status: stale` or `deprecated` only when a live reference still depends on it or an active migration needs temporary continuity. Add evidence/unknown explaining why, and link replacement ID when known.
7. Delete accidental duplicates, malformed records, and unreferenced resolved/superseded records, and mention deletion in final response.
### 5. Evidence and confidence
1. Every observed record needs at least one evidence ref with file/symbol/command/doc/diff observation.
2. Planned records may use `evidence_mode: planned` and confidence `low` or `medium`.
3. Mixed records must separate observed fields from planned/assumed fields via evidence refs or `unknowns`.
4. Do not upgrade `status: current` or confidence `high` without source or command evidence.
### 6. Reference integrity
Before writing final artifacts:
1. Check every `*_ref`, `*_refs`, and `depends_on` ID points to a record in the same artifact set or is explicitly listed as external/unknown.
2. Prefer adding missing owner records as compact stubs over leaving dangling refs.
3. For cross-scope refs, ensure `scopes.yaml` and `contracts.yaml` identify owner/consumer relationship.
4. If ownership is ambiguous, create/update `design-issues.yaml` with `kind: ownership_gap` and reference it.
### 7. Status transitions
Allowed transitions:
- `planned -> partial -> current`
- `current -> stale -> current`
- `current|stale|partial -> deprecated`
Rules:
- `current` requires sufficient observed evidence for the represented scope.
- `partial` means useful but incomplete evidence.
- `stale` means contradicted by newer source evidence or missing source path. Use it as a temporary migration/quarantine state, not a permanent archive state.
- `deprecated` means superseded; include `replacement_ref` when known. Use it only when a live reference still needs continuity during migration; otherwise remove the record from the canonical artifact.
### 8. Deterministic formatting
1. Use YAML with two-space indentation.
2. Use stable top-level key order: envelope keys first, artifact-specific keys next.
3. Sort unordered arrays by `id`; keep ordered flow/checklist arrays by `order`.
4. Use `null`, `[]`, or `{}` consistently rather than omitting required envelope fields.
5. Keep prose scalar fields concise; no long narrative blocks.
### 9. Validation before completion
Perform best-effort validation after writing:
1. Re-read changed YAML for parse/syntax sanity when practical.
2. Validate against the shared schemas by inspection/re-read: envelope keys, artifact-specific top-level keys, required arrays/items, stable ID prefixes, and obvious dangling refs.
3. Verify no legacy Markdown artifacts were created or updated by the workflow, except root `AGENTS.md` when explicitly produced for harness interoperability.
4. Report changed YAML files, validation performed, unresolved unknowns, and any records intentionally retained or pruned as part of compaction.
## Core Rules
- Preflight first for every non-trivial task.
- Read only relevant YAML owner artifacts.
- Do not read or update legacy prose Markdown artifacts.
- Do not edit code during preflight/design/diagnosis unless explicitly asked.
- Separate bug fixing, features, refactoring, risk fixes, tests, docs-only structured updates.
- Add tests for risky or uncovered behavior.
- Update structured artifacts only when durable semantics changed.
## Reference Files
Read these modular references at the matching workflow step:
- Always start with `references/preflight.md`.
- If `<docs-root>/repo/scopes.yaml` exists or task has a path/domain focus, also read `references/scoped-docs.md`.
- Bug fixes: read `references/bug-fix.md` before diagnosis/implementation.
- Features: read `references/feature.md` before design/implementation.
- Refactoring: read `references/refactoring.md` before design/implementation.
- Risk fixes: read `references/risk-fix.md` before selecting/fixing a risk.
- Test-only tasks: read `references/preflight.md`; read `references/docs-update.md` only if durable testing/risk facts change.
- Structured-docs-only tasks or any semantic artifact update: read `references/docs-update.md` before writing YAML artifacts.
References inherit this skill's Structured Artifact API Contract and Write/Update Protocol. If a reference conflicts with this skill, this skill wins.
## Preflight Output
Before edits, produce:
1. task classification
2. YAML artifacts read
3. matched scope from `repo/scopes.yaml`
4. affected slice/module/user flow
5. expected files to inspect
6. invariant/contract/risk refs at stake
7. validation command refs
8. proceed or wait for approval
## Workflow Selection
Users may invoke this skill directly for any workflow, or use the matching prompt template as a shortcut.
- Preflight (`/preflight`): classify task, match scope, identify owner artifacts/refs, and decide proceed vs approval.
- Bug diagnosis (`/bug-diagnose`): diagnose expected behavior, violated invariant/contract, root cause, minimal fix, regression test.
- Bug implementation (`/bug-implement`): implement approved minimal fix, add regression test, validate, update durable YAML facts only when semantics changed.
- Feature design (`/feature-design`): design flow/data/invariant/contract impacts, side effects, risks, tests, docs updates.
- Feature implementation (`/feature-implement`): implement approved design minimally, test, validate, update owner YAML artifacts when durable semantics changed.
- Refactor design (`/refactor-design`): preserve behavior, identify design issue/dependency rule, characterization tests, staged plan.
- Refactor implementation (`/refactor-implement`): execute approved refactor stage, keep behavior stable, validate.
- Risk fix (`/risk-fix`): select one risk or failing risk-derived test, fix minimally, update risk status.
- Test-only: preserve behavior; update testing strategy only if durable coverage/risk facts changed.
- Structured-docs-only: update owner YAML artifacts only.
## Structured Docs Update Rules
Update owners only:
- intent/scope/non-goals -> `project-intent.yaml`
- file tree/entry points/command index -> `repo-inventory.yaml`
- command status/blockers -> `validation-baseline.yaml`
- architecture/components/boundaries -> `architecture.yaml`
- flows/error states -> `data-flow.yaml`
- schemas/entities/lifecycles -> `data-model.yaml`
- rules/enforcement -> `invariants.yaml`
- imports/layers -> `dependency-rules.yaml`
- cross-scope APIs/schemas/events -> `contracts.yaml`
- risks/failure modes -> `risk-register.yaml`
- design drift/deferred decisions -> `design-issues.yaml`
- tests/gaps/priorities -> `testing-strategy.yaml`
- workflow/checklists -> `change-guide.yaml`
---
name: safe-start
description: Safe greenfield project creation workflow. Use when starting a new project from scratch, bootstrapping a repo, choosing initial architecture, scaffolding baseline tooling, creating project-agent docs, and implementing the first thin vertical slice. Adapts guidance for freshman, standard, and expert developers.
description: Structured greenfield project workflow. Creates agent-first YAML project truth under a resolved structured docs root plus root AGENTS.md for harness interoperability.
---
# Safe Start
# Safe Start — Structured API Only
Goal: create new projects safely by defining data-first project truth before code, scaffolding the smallest validated baseline, then handing future work to `safe-change`.
Goal: create new projects by defining canonical structured artifacts before feature depth, then scaffold and validate one thin slice.
## Core Principles
- Create durable project truth before feature depth.
- Design data flow first: input data -> transformations -> output data.
- Derive module boundaries from data and side-effect boundaries, not from early framework guesses.
- Keep architecture simple enough for current needs; record intentional extension points only.
- Build validation harness before real features.
- Implement one thin vertical slice before expanding scope.
- After baseline and first slice are validated, future changes should use `safe-change`.
## Structured Artifact API Contract
## Guidance Levels
Legacy prose artifacts are deprecated. Do not create, update, or rely on `docs/agent/*.md`, scoped prose docs, or generated human-readable Markdown views. Use structured YAML for canonical artifacts. Root `AGENTS.md` remains a harness interoperability file and may be generated/updated only by workflows that explicitly say so.
At start, determine guidance level from user preference or ask once:
Resolved structured docs root:
```text
Preferred guidance level?
1. Freshman: explain decisions and commands.
2. Standard: concise but guided.
3. Expert: compact, assumption-driven.
```
Treat `docs/agent/api` as a logical layout rooted at a resolved structured docs root, not a fixed repo path.
Default: `Standard`.
Resolution rules:
1. Resolve `workspace_root` with `git rev-parse --show-toplevel 2>/dev/null` or fallback to `pwd`.
2. `safe-start` always creates and uses the initial repo-local root: `<workspace_root>/docs/agent/api`.
3. Other skills use repo-local only when `<workspace_root>/docs/agent/api` already exists.
4. Otherwise use the global overlay root: `~/.pi/agent/workspaces/<workspace-fingerprint>/docs/agent/api`.
5. Derive `<workspace-fingerprint>` deterministically from the canonical `workspace_root` path and keep it stable for the same workspace.
6. Do not create new repo-local structured docs in unadopted repos unless the user explicitly asks for repo-local adoption there.
Same safety gates apply at every level. Only communication and artifact density change:
Logical structured layout under the resolved docs root:
- Freshman: more explanation, glossary, command notes, simpler questions, explicit file tree, starter tests, minimal jargon.
- Standard: concise decisions, enough rationale to maintain project safely.
- Expert: terse assumptions, ADRs, contracts, risk gates, extension points, fewer explanations.
## Artifact Compatibility Contract
Safe-start artifacts must be compatible with later `safe-change` work and with `codebase-recon` consolidation.
Baseline repo-level artifacts:
```text
README.md
AGENTS.md
.env.example # when env/config exists
docs/agent/
REPO_INVENTORY.md
PROJECT_INTENT.md
ARCHITECTURE.md
DATA_FLOW.md
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
TESTING_STRATEGY.md
VALIDATION_BASELINE.md
adr/
0001-initial-architecture.md
repo/
scopes.yaml
repo-inventory.yaml
project-intent.yaml
architecture.yaml
data-flow.yaml
data-model.yaml
invariants.yaml
dependency-rules.yaml
design-issues.yaml
risk-register.yaml
change-guide.yaml
testing-strategy.yaml
validation-baseline.yaml
contracts.yaml
adr.yaml
agent-operating-guide.yaml
scopes/
by-path/<repo-relative-path>/...
by-domain/<slug>/...
```
Optional when useful:
Every structured artifact must conform to `../_shared/references/schemas/common.schema.json` plus its artifact-specific schema. Do not inline, invent, or vary envelope fields.
```text
docs/agent/BACKLOG.md
docs/agent/CONTRACTS.md
docs/agent/DEPLOYMENT.md
docs/agent/SECURITY.md
```
Stable IDs required: `scope:*`, `component:*`, `entity:*`, `invariant:*`, `risk:*`, `contract:*`, `flow:*`, `command:*`, `issue:*`, `adr:*`, `testplan:*`.
Artifact header guidance for durable docs:
Ownership rules:
- `scopes`: scope routing, ownership, cross-scope discovery only.
- `repo-inventory`: file tree, commands index, entry points, external boundaries, configs.
- `validation-baseline`: command status, blockers, recommended validation order.
- `project-intent`: goals, users, journeys, non-goals, constraints, assumptions.
- `architecture`: components, architecture style, side-effect boundaries, high-level flow refs.
- `data-flow`: typed flow graph/steps, inputs, outputs, error states.
- `data-model`: entities, IDs, schemas, relationships, lifecycles, serialized formats.
- `invariants`: rules, forbidden states, enforcement locations, invariant-test refs.
- `dependency-rules`: layers, allowed/forbidden dependencies, violations, coupling hotspots.
- `design-issues`: structural drift, deferred decisions, ambiguity, ownership gaps.
- `risk-register`: failure modes, severity/confidence, affected refs, suggested tests/fixes.
- `contracts`: cross-scope APIs, schemas, events, generated clients, DB/file/deployment/env contracts.
- `testing-strategy`: test topology, coverage gaps, risk-to-test priorities.
- `change-guide`: workflow routing and checklists; references owner artifacts, duplicates no facts.
- `adr`: structured decision records with bounded prose fields.
- `agent-operating-guide`: structured source for agent operating rules. Root `AGENTS.md` may mirror this in compact harness-readable Markdown when produced by safe-start or codebase-recon Pass 6.
```text
Status: current | partial | stale
Evidence: planned | observed | mixed
Last validated: unknown | <date>
```
Redundancy rule: define each fact in its owner artifact exactly once. Other artifacts reference IDs.
Current truth rule: canonical YAML artifacts represent current state, not audit history. Remove resolved or superseded records from canonical owner artifacts by default. Keep them only when another live record still references them or an active migration requires temporary continuity. Use Git history, PRs, issues, or ADRs for audit/history.
Prose rule: bounded prose allowed only in `summary`, `notes`, `rationale`, `context`, `decision`, `recommended_action`, and similar scalar fields.
Scope rule: if focus is path-like, write under `<docs-root>/scopes/by-path/<focus>/`; otherwise under `<docs-root>/scopes/by-domain/<slug>/`. Always update `<docs-root>/repo/scopes.yaml`.
Use `planned` before scaffold/implementation exists. Update to `observed` or `mixed` after validation against real files and commands.
Rules:
- Project operating instructions stay at root `AGENTS.md`.
- Do not create `docs/AGENTS.md` or `docs/agent/AGENTS.md`.
- Keep docs compact and operational.
- Docs should describe durable semantics, not tutorial prose, except in Freshman mode where short teaching notes are allowed.
- Avoid duplicate source-of-truth facts: `AGENTS.md` stays short and operational; semantic docs hold durable detail; `CHANGE_GUIDE.md` holds workflow.
## Context Budget and Non-Duplication
## Runtime Schema Loading
Each artifact should be either a source of truth for one semantic category or an index/router to other docs. Do not make every artifact a summary of every other artifact.
When a workflow creates, updates, migrates, or validates structured artifacts, read `../_shared/references/artifact-api.md` first. Then read only the shared skill package schemas needed for the artifacts being written:
- `../_shared/references/schemas/common.schema.json`
- `../_shared/references/schemas/<artifact-file-base>.schema.json`
Artifact ownership:
- `AGENTS.md`: injected operating rules, forbidden shortcuts, validation expectations, and links only.
- `CHANGE_GUIDE.md`: workflow and doc-routing guide; link to semantic docs instead of repeating them.
- `SCOPES.md`: routing table for scoped docs; no detailed architecture or contract prose.
- `REPO_INVENTORY.md`: file tree, entry points, commands index, external boundaries; no architecture judgments.
- `PROJECT_INTENT.md`: product/user goals, non-goals, constraints, assumptions.
- `ARCHITECTURE.md`: components, boundaries, side-effect boundaries, high-level execution flows.
- `DEPENDENCY_RULES.md`: allowed/forbidden dependency direction and import boundaries.
- `DATA_FLOW.md`: input -> transformation -> output lifecycles, events, request paths, error states.
- `DATA_MODEL.md`: entities, schemas, IDs, relationships, persisted/serialized formats.
- `INVARIANTS.md`: rules, forbidden states, lifecycle constraints, enforcement locations.
- `DESIGN_ISSUES.md`: design drift, unresolved design problems, deferred decisions.
- `RISK_REGISTER.md`: failure modes with severity, evidence, failure scenario, suggested test/fix.
- `TESTING_STRATEGY.md`: test approach, coverage gaps, risk-to-test priorities.
- `VALIDATION_BASELINE.md`: exact commands, last status, blockers, next best checks.
- `CONTRACTS.md`: cross-scope APIs, schemas, events, generated clients, persistence/deployment interfaces.
Do not read all schemas. Do not use templates. Schemas are runtime API contracts; project docs outside the shared runtime refs are maintainer aids unless the user asks about this package itself.
Duplication rules:
- Prefer links/references over copied detail.
- If `VALIDATION_BASELINE.md` exists, `REPO_INVENTORY.md` may list command names but should link to baseline for status/blockers.
- If `TESTING_STRATEGY.md` exists, `CHANGE_GUIDE.md` should link to it for testing details.
- Top-level docs summarize stable repo-wide truths; scoped docs hold local detail.
- If a required artifact has little content, create a compact stub with `No known ...`, `Unknown`, or `Not yet validated`, not boilerplate prose.
## Structured Artifact Write/Update Protocol
## Scope/Focus Arguments
Use this protocol whenever creating or updating YAML artifacts.
Prompt arguments may include a target, focus, scope, domain, service, package, app, tool, or environment. Use these to limit a pass to one planned boundary while keeping repo-level docs as summary/fallback.
### 1. Scope and owner resolution
When a scope/focus is provided:
- define whether it is path-based (`apps/web`, `packages/sdk`, `infra/prod`) or domain-based (`billing`, `identity`, `plugin-system`)
- create/update `docs/agent/SCOPES.md` before writing scoped docs
- write detailed findings to matching scoped artifacts, not only top-level docs
- update top-level docs only with stable repo-level summary or cross-scope guidance
- identify owner/consumer contracts when the scope exposes APIs, shared types, events, schemas, generated clients, persistence formats, deployment interfaces, CLIs, SDKs, plugins, or infra modules
1. Resolve scope first from task/focus and `<docs-root>/repo/scopes.yaml` when present.
2. Path focus uses longest prefix match; domain focus requires explicit domain/contract/task evidence.
3. Select the single owner artifact for each fact using the ownership rules above.
4. Never duplicate owner facts in router/checklist artifacts; reference stable IDs instead.
## Scoped Artifacts
### 2. Read-before-write
Use scoped safe-start artifacts for monorepos, enterprise-grade systems, dev-tools platforms, infra/IaC repos, multi-service systems, or any project where one repo-level summary would hide ownership boundaries.
1. Read the existing target YAML if it exists.
2. Read directly referenced owner artifacts needed to preserve refs and avoid duplication.
3. If target YAML is absent, create it with the common envelope and artifact-specific top-level keys.
4. Preserve unknown fields unless they conflict with this protocol; do not silently drop agent/user-added structured data.
Scoped artifacts mirror `codebase-recon` scope layout:
### 3. Stable ID generation
```text
docs/agent/
SCOPES.md
scopes/
by-path/<repo-relative-path>/
README.md # optional local index for large/complex scopes
REPO_INVENTORY.md
PROJECT_INTENT.md
ARCHITECTURE.md
DATA_FLOW.md
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
TESTING_STRATEGY.md
VALIDATION_BASELINE.md
CONTRACTS.md # when scope owns cross-scope APIs/schemas/events
by-domain/<domain-slug>/
README.md # optional local index for large/complex scopes
PROJECT_INTENT.md
ARCHITECTURE.md
DATA_FLOW.md
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
TESTING_STRATEGY.md
VALIDATION_BASELINE.md
CONTRACTS.md
```
1. Reuse existing IDs whenever the semantic object is the same, even if name/path changed.
2. New IDs use deterministic slugs from owner scope + semantic name: `risk:<slug>`, `entity:<slug>`, `component:<slug>`, etc.
3. If two objects slug-collide, append shortest stable discriminator from path/component/contract, not a random suffix.
4. Never renumber IDs because order changed.
`docs/agent/SCOPES.md` is required when scoped artifacts exist. Suggested columns:
- Scope
- Kind: `path` / `domain`
- Docs path
- Status: `planned` / `partial` / `current` / `stale` / `deprecated`
- Owns
- External contracts
- Last validated evidence
### 4. Upsert semantics
When to introduce scopes:
- monorepo with apps/packages/services under separate paths
- enterprise codebase with independently owned domains or bounded contexts
- dev-tools repo with CLI, SDK, server, extension, plugin, or template surfaces
- infra repo with environments, modules, deployment pipelines, policy, or runtime ops boundaries
- cross-scope contracts exist: APIs, shared types, events, generated clients, persistence formats, deployment interfaces
For each discovered fact/object:
1. Match existing record by ID first.
2. If no ID match, match by stable source-of-truth fields: path+symbol, contract source path, command string+cwd, entity name+owner scope, rule owner+kind.
3. If matched, update only changed fields, append/refresh evidence, and preserve unrelated fields.
4. If unmatched, insert new record in deterministic order by ID or explicit `order` field.
5. If an existing observed record is resolved, superseded, or no longer supported, delete it from the canonical owner artifact by default.
6. Keep a record with `status: stale` or `deprecated` only when a live reference still depends on it or an active migration needs temporary continuity. Add evidence/unknown explaining why, and link replacement ID when known.
7. Delete accidental duplicates, malformed records, and unreferenced resolved/superseded records, and mention deletion in final response.
Scope rules:
- Prefer `by-path` when source path is known or will be scaffolded.
- Use `by-domain` for business/platform domains before final paths exist.
- Every cross-scope contract should have one owner scope documented in `CONTRACTS.md`.
- Consumer scopes link to owner contracts and record local usage/risk only.
- Top-level docs remain repo-level summaries and fallback guidance; scope docs hold detailed local truth.
- Safe-start handoff must explain whether future `safe-change` work should use top-level docs, scoped docs, or both.
### 5. Evidence and confidence
## Execution Modes
1. Every observed record needs at least one evidence ref with file/symbol/command/doc/diff observation.
2. Planned records may use `evidence_mode: planned` and confidence `low` or `medium`.
3. Mixed records must separate observed fields from planned/assumed fields via evidence refs or `unknowns`.
4. Do not upgrade `status: current` or confidence `high` without source or command evidence.
Default: numbered-pass mode.
### 6. Reference integrity
Use one pass at a time for uncertain, high-risk, large, commercial, regulated, or multi-service projects:
Before writing final artifacts:
1. Check every `*_ref`, `*_refs`, and `depends_on` ID points to a record in the same artifact set or is explicitly listed as external/unknown.
2. Prefer adding missing owner records as compact stubs over leaving dangling refs.
3. For cross-scope refs, ensure `scopes.yaml` and `contracts.yaml` identify owner/consumer relationship.
4. If ownership is ambiguous, create/update `design-issues.yaml` with `kind: ownership_gap` and reference it.
```text
/safe-start-all
/safe-start-01-intent
/safe-start-02-data-flow
/safe-start-03-architecture
/safe-start-04-contract-docs
/safe-start-05-scaffold-plan
/safe-start-06-validation
/safe-start-07-vertical-slice
/safe-start-08-handoff
```
### 7. Status transitions
Optional all-in-one mode may be used when user explicitly asks and project is small/simple enough:
Allowed transitions:
- `planned -> partial -> current`
- `current -> stale -> current`
- `current|stale|partial -> deprecated`
```text
/skill:safe-start all
```
Rules:
- `current` requires sufficient observed evidence for the represented scope.
- `partial` means useful but incomplete evidence.
- `stale` means contradicted by newer source evidence or missing source path. Use it as a temporary migration/quarantine state, not a permanent archive state.
- `deprecated` means superseded; include `replacement_ref` when known. Use it only when a live reference still needs continuity during migration; otherwise remove the record from the canonical artifact.
In all-in-one mode:
1. Capture intent, guidance level, and whether scoped artifacts are needed.
2. Produce data-first design and scaffold plan.
3. Stop for approval before writing files unless user explicitly requested implementation.
4. Scaffold, validate, implement first vertical slice if approved/requested.
5. Report validation and handoff status, including whether future work should use scoped docs.
### 8. Deterministic formatting
## Approval Gates
1. Use YAML with two-space indentation.
2. Use stable top-level key order: envelope keys first, artifact-specific keys next.
3. Sort unordered arrays by `id`; keep ordered flow/checklist arrays by `order`.
4. Use `null`, `[]`, or `{}` consistently rather than omitting required envelope fields.
5. Keep prose scalar fields concise; no long narrative blocks.
Stop for approval after these outputs unless user explicitly requested implementation now:
### 9. Validation before completion
1. Intent summary and assumptions.
2. Data-flow design and core data model.
3. Architecture/scaffold plan and validation commands.
4. First vertical-slice plan.
Perform best-effort validation after writing:
1. Re-read changed YAML for parse/syntax sanity when practical.
2. Validate against the shared schemas by inspection/re-read: envelope keys, artifact-specific top-level keys, required arrays/items, stable ID prefixes, and obvious dangling refs.
3. Verify no legacy Markdown artifacts were created or updated by the workflow, except root `AGENTS.md` when explicitly produced for harness interoperability.
4. Report changed YAML files, validation performed, unresolved unknowns, and any records intentionally retained or pruned as part of compaction.
Never perform destructive actions, remote deployments, credential setup, paid service provisioning, production database changes, or publishing without explicit permission.
## Pass 1 — Intent Capture
## Core Rules
Prompt template: `/safe-start-01-intent`.
- Produce canonical YAML artifacts under the resolved structured docs root. Safe-start creates the initial repo-local root at `<workspace_root>/docs/agent/api`; root `AGENTS.md` is the only Markdown workflow output.
- Do not write README or prose docs as workflow artifacts. Root `AGENTS.md` is allowed as compact harness interoperability output.
- Design data flow first, then boundaries, then scaffold.
- Stop for approval after intent, data flow, architecture/scaffold plan, and vertical-slice plan unless user explicitly requested implementation.
- After baseline and first slice, future changes use `safe-change` with structured artifacts.
Task: define project purpose, constraints, guidance level, scope, and non-goals.
## Guidance Levels
Output/update:
- `docs/agent/PROJECT_INTENT.md`
- `docs/agent/REPO_INVENTORY.md` with planned/observed scaffold inventory, entry points, validation commands, and external boundaries
- `docs/agent/SCOPES.md` when scoped artifacts are needed
- matching scoped `PROJECT_INTENT.md` / `REPO_INVENTORY.md` when a focus or scope is in play
- initial `README.md` summary if creating files now
Ask once if unknown: `freshman`, `standard`, or `expert`. Guidance level affects conversation only, not artifact schema.
Required sections for `PROJECT_INTENT.md`:
- Product goal
- Target users
- Primary user journeys
- Must-have features
- Non-goals
- Runtime/platform/deployment target
- Constraints and preferences
- Guidance level
- Scope model: unscoped repo, path scopes, domain scopes, or deferred
- Assumptions
- Open questions
## Passes
Required sections for `REPO_INVENTORY.md`:
- Planned/observed project summary
- Planned/observed build and validation commands
- Planned/observed entry points
- Planned/observed major directories
- External dependencies/boundaries
- Scope registry summary when scoped artifacts exist
- Unknowns
- Next recommended design/scaffold targets
Users may invoke this skill directly for any pass, or use the matching prompt template as a pass shortcut.
## Pass 2 — Data Flow Design
1. Intent (`/safe-start-01-intent`): write `project-intent.yaml`, initial `repo-inventory.yaml`, optional `scopes.yaml`.
2. Data flow (`/safe-start-02-data-flow`): write `data-flow.yaml`, `data-model.yaml`, `invariants.yaml`.
3. Architecture (`/safe-start-03-architecture`): write `architecture.yaml`, `dependency-rules.yaml`, `design-issues.yaml`, `risk-register.yaml`, `adr.yaml`.
4. Contract docs (`/safe-start-04-contract-docs`): write `change-guide.yaml`, `testing-strategy.yaml`, optional `contracts.yaml`, `security`/`deployment` as contract records if needed, `agent-operating-guide.yaml`, and root `AGENTS.md`.
5. Scaffold plan (`/safe-start-05-scaffold-plan`): output plan in chat only; after approval create files.
6. Validation baseline (`/safe-start-06-validation`): write `validation-baseline.yaml` from actual commands/status.
7. Thin vertical slice (`/safe-start-07-vertical-slice`): implement one minimal slice; update structured artifacts only for durable semantic changes.
8. Handoff (`/safe-start-08-handoff`): update `change-guide.yaml`, `risk-register.yaml`, `repo-inventory.yaml`, `design-issues.yaml`, `scopes.yaml`.
Prompt template: `/safe-start-02-data-flow`.
All-in-one shortcut: `/safe-start-all` runs the pass sequence with approval gates unless implementation was explicitly requested.
Read first: `docs/agent/PROJECT_INTENT.md` if present; `docs/agent/SCOPES.md` and matching scoped intent/inventory when scoped artifacts are in play.
## Required Artifact Content
Task: design data-first system shape.
Output/update:
- `docs/agent/DATA_FLOW.md`
- `docs/agent/DATA_MODEL.md`
- `docs/agent/INVARIANTS.md`
- matching scoped `DATA_FLOW.md`, `DATA_MODEL.md`, and `INVARIANTS.md` when a focus or scope is in play
Required sections:
- External inputs
- User inputs
- Files/events/API payloads
- Core entities/value objects
- Identifiers and relationships
- Lifecycle/state transitions
- Validation and normalization
- Transformation pipeline
- Outputs: UI states, API responses, reports, side effects
- Error states
- Invariants and forbidden states
- Persistence/serialization draft if needed
## Pass 3 — Architecture Decisions
Prompt template: `/safe-start-03-architecture`.
Read first: project intent, data flow, data model, invariants, and `docs/agent/SCOPES.md` / matching scoped docs when scoped artifacts are in play.
Task: choose initial architecture after data shape is known.
Output/update:
- `docs/agent/ARCHITECTURE.md`
- `docs/agent/DEPENDENCY_RULES.md`
- `docs/agent/DESIGN_ISSUES.md`
- `docs/agent/RISK_REGISTER.md`
- `docs/agent/adr/0001-initial-architecture.md`
- matching scoped artifacts when a focus or scope is in play
Required sections:
- Architecture overview
- Module boundaries derived from data flow
- Dependency direction
- Side-effect boundaries
- Stack/framework/library decisions
- Configuration/secrets approach
- Error handling strategy
- Security/privacy basics
- Known design issues, deferred decisions, and drift risks
- Key risks and mitigations
- ADR with context, decision, alternatives, consequences
## Pass 4 — Project Contract Docs
Prompt template: `/safe-start-04-contract-docs`.
Read first: intent, data flow/model, architecture, dependency rules, and `docs/agent/SCOPES.md` / matching scoped docs when scoped artifacts are in play.
Task: create operational docs for future agents and developers.
Output/update:
- `README.md`
- `AGENTS.md`
- `docs/agent/CHANGE_GUIDE.md`
- `docs/agent/TESTING_STRATEGY.md`
- optional `docs/agent/CONTRACTS.md`, `SECURITY.md`, `DEPLOYMENT.md`
- matching scoped artifacts and owner `CONTRACTS.md` files when scoped artifacts are in play
Required content:
- How to understand project quickly
- Architecture rules
- Data flow and data model rules
- Invariants not to violate
- How to discover matching scoped docs through `docs/agent/SCOPES.md` when present
- How to add/modify features
- How to validate changes
- Documentation update rules, including planned/observed/status header updates when useful
- Freshman-friendly command explanations when guidance level is Freshman
## Pass 5 — Scaffold Plan
Prompt template: `/safe-start-05-scaffold-plan`.
Read first: all prior design docs, including `docs/agent/SCOPES.md` and matching scoped docs when scoped artifacts are in play.
Task: propose minimal file tree and tooling before writing project code.
Output:
- concise scaffold plan
- package/build/test/lint/typecheck choices
- exact commands to create/install/run
- generated files list
- risks/assumptions
Scaffold should include only:
- package/build config
- formatter/linter/typecheck where suitable
- test runner
- app entrypoint
- minimal runtime health/hello path
- config/env example if needed
- CI only if requested or clearly expected
Avoid:
- speculative abstractions
- unused frameworks
- premature auth/payment/admin systems
- mock complexity beyond first slice needs
## Pass 6 — Validation Baseline
Prompt template: `/safe-start-06-validation`.
Task: make baseline checks green before real feature depth. For scoped projects, validate repo-level commands plus independently runnable scope commands where practical.
Output/update:
- `docs/agent/VALIDATION_BASELINE.md`
- matching scoped `VALIDATION_BASELINE.md` for independently validated apps/packages/services/tools/infra scopes
Required validations when applicable:
- install/bootstrap works
- format/lint command works
- typecheck/build works
- tests run
- app starts
- one smoke test proves runtime path
If any validation cannot run, record exact blocker and next best check.
## Pass 7 — Thin Vertical Slice
Prompt template: `/safe-start-07-vertical-slice`.
Read first: prior docs and validation baseline, including matching scoped docs when scoped artifacts are in play.
Task: implement one small end-to-end feature crossing real boundaries. In scoped projects, choose one scope or one owner/consumer contract path for the first slice unless the user explicitly asks for a broader enterprise scaffold.
Slice should include:
- input adapter: UI/API/CLI/event/file as relevant
- validation/schema if relevant
- domain/core operation
- output adapter/rendering/API response
- persistence adapter or explicit in-memory/mock choice if persistence is deferred
- tests around core invariant and runtime path
- docs update only if durable semantics change
Stop at one slice. Do not build broad feature set.
## Pass 8 — Handoff to Safe Change
Prompt template: `/safe-start-08-handoff`.
Task: verify project is ready for normal documented-codebase workflow.
Output/update:
- `docs/agent/CHANGE_GUIDE.md`
- `docs/agent/RISK_REGISTER.md`
- `docs/agent/REPO_INVENTORY.md`
- `docs/agent/DESIGN_ISSUES.md`
- `docs/agent/SCOPES.md` when scoped artifacts exist
- optional `docs/agent/BACKLOG.md`
Checklist:
- root `AGENTS.md` exists and is operational
- `REPO_INVENTORY.md` exists and reflects planned vs observed scaffold state
- `DESIGN_ISSUES.md` exists, even if it says no known issues/deferred decisions
- docs/agent artifacts cover architecture, data flow, data model, invariants, dependency rules, tests, risks, validation baseline
- `CHANGE_GUIDE.md` links or points to `PROJECT_INTENT.md`, `DATA_FLOW.md`, `TESTING_STRATEGY.md`, and `VALIDATION_BASELINE.md` when relevant
- validation baseline commands are known and recently run
- first slice is implemented or explicitly deferred
- scoped docs exist when repo complexity warrants them, with `SCOPES.md` identifying owners and contracts
- next work items are small enough for `safe-change`
Final note should say whether future work should use `safe-change`, whether scoped docs should be read, and which docs to read first.
- `project-intent.yaml`: `intent.product_goal`, `target_users`, `primary_journeys`, `must_have_features`, `non_goals`, `constraints`, `assumptions`, `open_questions`.
- `data-flow.yaml`: `flows` with triggers, inputs, ordered steps, outputs, error states, risk refs.
- `data-model.yaml`: `entities`, `lifecycles`, `serialized_formats`.
- `invariants.yaml`: invariant records with enforcement status and locations.
- `architecture.yaml`: style, components, boundaries, dependency direction, execution flow refs.
- `contracts.yaml`: owner/consumer contract records for APIs, schemas, events, generated clients, persistence, deployment, env, CLI.
- `validation-baseline.yaml`: command records with cwd, status, last_run, blockers, recommended order.
# Troubleshooting
## No docs were created
Check that the prompt used a reconstruction command:
```text
/recon-01-inventory
/recon-02-architecture
/recon-all
```
Reconstruction must not edit production code, but it should write `docs/agent/*.md` or scoped docs under `docs/agent/scopes/**`.
If the repo is large, prefer numbered passes over `/recon-all`.
## Agent wrote scoped findings into top-level docs
Expected behavior:
- no focus argument -> top-level `docs/agent/*.md`
- focus argument -> `docs/agent/scopes/by-path/<focus>/...` or `docs/agent/scopes/by-domain/<slug>/...`
Fix:
1. Move or summarize misplaced details into the correct scoped artifact.
2. Update `docs/agent/SCOPES.md`.
3. Run `/recon-08-consolidate` later if top-level summaries need reconciliation.
## `SCOPES.md` missing or stale
`docs/agent/SCOPES.md` is created when first scoped pass runs. It may not exist in purely unscoped or legacy repos.
If scoped docs exist but `SCOPES.md` is missing:
- create/update `docs/agent/SCOPES.md`
- list each scope, docs path, status, ownership, and external contracts
If stale:
- mark outdated scopes as `stale` or `deprecated`
- update evidence paths and status during next scoped pass or consolidation
## Scope path was renamed
Scoped path docs can become historical after source moves.
Fix:
1. Verify whether the source path still exists.
2. If moved, update `SCOPES.md` with new path and status.
3. Treat old scoped docs as historical until revalidated against source.
4. Re-run relevant scoped pass for the new path.
## Too many scoped directories
Avoid creating a scope for every folder.
Prefer scopes for:
- packages
- apps
- services
- bounded domains
- major modules with separate ownership or contracts
Consolidate or deprecate tiny scopes in `SCOPES.md` when they add noise.
## Agent read too many files
For large repos, provide explicit focus:
```text
/recon-02-architecture packages/api
/preflight fix token refresh in packages/api
/review-arch packages/api
```
Scoped workflows should inspect focused area plus immediate dependencies, tests, entry points, and external boundaries only.
If investigation expands too broadly, stop and narrow target path/domain.
## Cross-scope contract ownership unclear
Use `CONTRACTS.md`.
Rules:
- one owner scope per contract
- owner documents source of truth, compatibility rules, tests, and consumers
- consumers link to owner contract and document local usage/risk only
If ownership cannot be determined, record it as:
- known unknown
- drift risk
- follow-up item for consolidation
## Top-level and scoped docs disagree
Do not silently delete disagreement evidence.
Fix:
1. Check source evidence.
2. Prefer latest verified source-backed observation.
3. Keep scope-specific facts in scoped docs.
4. Summarize stable repo-level guidance in top-level docs.
5. Run `/recon-08-consolidate` to reconcile contradictions.
## Existing legacy docs already exist
Legacy top-level docs remain valid.
Safe-change and review use top-level docs when `SCOPES.md` is absent. First focused recon pass adds scoped docs and `SCOPES.md` without deleting old docs.
Use consolidation when enough scoped material exists to update repo-level summaries.
## Monorepo too large for `/recon-all`
Use numbered/scoped passes instead:
```text
/recon-01-inventory
/recon-02-architecture packages/api
/recon-03-data-invariants packages/api
/recon-02-architecture apps/mobile
```
Keep each pass bounded. Let `/recon-08-consolidate` reconcile later.
## Safe-change ignored scoped docs
Check:
- `docs/agent/SCOPES.md` exists
- target path is listed or covered by longest-prefix scope
- scoped source path still exists
- task wording includes relevant path/domain
Fix by providing explicit target:
```text
/preflight fix billing total rounding in services/billing
```
## Review missed a cross-module contract
Check whether touched API/type/schema/event is documented in scoped `CONTRACTS.md`.
If not:
1. Identify owner scope.
2. Add or update owner `CONTRACTS.md`.
3. Link consumer scope to owner contract.
4. Re-run `/review-arch` with explicit scope if needed.
## Validation command unavailable
Use best available focused validation:
- targeted test for changed package/module
- type check for affected package
- lint for affected package
- build/smoke test for affected app/service
If no validation can run, report why and name the next best command for the user to run.
# Tutorial
This package provides pi skills and prompt templates for starting new projects safely, reconstructing codebase knowledge, making safe changes, and reviewing architecture drift.
## Install
From git:
```bash
pi install git:github.com/PriNova/pi-agent-codebase-workflows
```
Local development/test:
```bash
pi install /absolute/path/to/pi-agent-codebase-workflows
# or one-off
pi -e /absolute/path/to/pi-agent-codebase-workflows
```
## Start a new project safely
For small/simple greenfield projects, run all safe-start passes:
```text
/safe-start-all build a small habit tracker web app
```
For larger, higher-risk, or learning-oriented projects, run numbered passes so each decision is reviewable:
```text
/safe-start-01-intent
/safe-start-02-data-flow
/safe-start-03-architecture
/safe-start-04-contract-docs
/safe-start-05-scaffold-plan
/safe-start-06-validation
/safe-start-07-vertical-slice
/safe-start-08-handoff
```
Safe-start is data-first:
```text
input data -> validation/normalization -> domain transformation -> output data/side effects
```
Module boundaries are derived after data flow is understood.
At the start, choose guidance level:
```text
Freshman - more explanations, command notes, simple questions
Standard - concise but guided
Expert - compact, assumption-driven, contract/ADR oriented
```
Safe-start creates project operating docs such as:
```text
README.md
AGENTS.md
docs/agent/PROJECT_INTENT.md
docs/agent/DATA_FLOW.md
docs/agent/DATA_MODEL.md
docs/agent/INVARIANTS.md
docs/agent/ARCHITECTURE.md
docs/agent/DEPENDENCY_RULES.md
docs/agent/RISK_REGISTER.md
docs/agent/TESTING_STRATEGY.md
docs/agent/CHANGE_GUIDE.md
docs/agent/VALIDATION_BASELINE.md
```
After `/safe-start-08-handoff`, use `/skill:safe-change` or safe-change prompts for normal feature, bug, and refactor work.
## Reconstruct a small repo
For small/simple repos, run all reconstruction passes:
```text
/recon-all
```
This creates repo-level docs under:
```text
docs/agent/
```
and project operating guidance at:
```text
AGENTS.md
```
## Reconstruct a large repo or monorepo
Start with inventory:
```text
/recon-01-inventory
```
Use the inventory's recommended targets for scoped passes:
```text
/recon-02-architecture packages/api
/recon-03-data-invariants packages/api
/recon-04-dependency-rules packages/api
/recon-05-risk-register packages/api
/recon-02-architecture apps/mobile
/recon-03-data-invariants apps/mobile
```
Focused path passes write hierarchical scoped docs:
```text
docs/agent/scopes/by-path/packages/api/
README.md # optional local index for large/complex scopes
ARCHITECTURE.md
DATA_MODEL.md
INVARIANTS.md
DEPENDENCY_RULES.md
DESIGN_ISSUES.md
RISK_REGISTER.md
CHANGE_GUIDE.md
CONTRACTS.md
```
Focused domain passes write:
```text
docs/agent/scopes/by-domain/auth-flow/
```
`docs/agent/SCOPES.md` indexes scoped docs for later workflows.
## Understand generated docs
Repo-level docs:
```text
docs/agent/ARCHITECTURE.md
docs/agent/DATA_MODEL.md
docs/agent/INVARIANTS.md
docs/agent/DEPENDENCY_RULES.md
docs/agent/RISK_REGISTER.md
docs/agent/CHANGE_GUIDE.md
```
Use repo-level docs as summaries and fallback guidance.
Scoped docs:
```text
docs/agent/scopes/by-path/<path>/...
docs/agent/scopes/by-domain/<slug>/...
```
Use scoped docs for package/module/service/domain-specific facts.
`CONTRACTS.md` documents cross-module APIs, shared types, schemas, events, generated clients, persistence boundaries, and ownership.
## Make a safe change
Start with preflight:
```text
/preflight fix login refresh bug in packages/api
```
For a bug:
```text
/bug-diagnose fix login refresh bug in packages/api
/bug-implement approved plan
```
For a feature:
```text
/feature-design add export endpoint to packages/api
/feature-implement approved plan
```
For a refactor:
```text
/refactor-design split billing service adapter
/refactor-implement approved stage 1
```
Safe-change reads `docs/agent/SCOPES.md` when present, matches path scopes by longest prefix, reads scoped docs first, then falls back to repo-level docs.
## Review architecture
Review current diff:
```text
/review-arch
```
Review with explicit focus:
```text
/review-arch packages/api
```
Review checks architecture drift, data consistency, invariants, dependency direction, public contracts, side-effect boundaries, and tests.
## Consolidate scoped findings
After several scoped passes, reconcile them:
```text
/recon-08-consolidate
```
Consolidation keeps detailed facts in scoped docs and summarizes stable repo-level guidance into top-level docs.
## Legacy reconstructed repos
Repos reconstructed before scoped artifacts still work.
If only top-level `docs/agent/*.md` exists:
- safe-change uses those docs
- review uses those docs
- a later focused recon pass creates `docs/agent/SCOPES.md` and scoped artifacts additively
- existing top-level docs are not deleted
Use consolidation later to reconcile old repo-level details with newer scoped docs.