# Phase 0: Autonomous Exploration

**You (the AI agent) execute this phase entirely on your own.**
Do NOT ask the user questions yet. Explore first, ask later.

## 0a. Discover project structure

```
- Scan the repo root: list top-level files and directories
- Identify dependency files: package.json, requirements.txt, go.mod,
  pom.xml, Cargo.toml, pyproject.toml, etc.
- Identify entry points: main.py, index.ts, cmd/, src/main, etc.
- Identify test infrastructure: tests/, __tests__/, *_test.go, pytest.ini,
  jest.config, etc.
- Identify CI/CD: .github/workflows/, .gitlab-ci.yml, Jenkinsfile, etc.
- Identify existing docs: README.md, docs/, CONTRIBUTING.md, ARCHITECTURE.md
- Identify config: .env.example, config/, docker-compose.yml, etc.
```

## 0b. Audit existing documentation

If AGENTS.md, docs/prompt.md, docs/plan.md, or similar files already exist,
**do NOT skip them**. Read and audit them before creating anything new.

```
For each existing doc file found:
1. Read the full content
2. Check: does it have a clear structure (headings, sections)?
3. Check: does it contain actionable information or just vague text?
4. Check: are cross-references valid (do linked files exist)?
5. Check: are verification commands present and runnable?
6. Check: is the content consistent with the actual codebase?
   (e.g., does AGENTS.md reference modules that still exist?)
7. Check: is there duplication across docs?
8. Check: is there stale/outdated information?
```

Classify each existing doc:

- **healthy**: well-structured, accurate, can be kept as-is
- **salvageable**: has useful content but needs reorganization or gap-filling
- **stale**: references outdated code/architecture, needs major rewrite
- **redundant**: duplicates info from another doc, should be merged or removed

Generate a **Documentation Health Report** (included in the Discovery Report).

## 0c. Discover tech stack

```
- Parse dependency files to extract: language, framework, database,
  ORM, test framework, linter, formatter, bundler
- Check for TypeScript (tsconfig.json), Python (setup.py/pyproject.toml),
  Go (go.mod), Java (pom.xml), Rust (Cargo.toml)
- Identify external services: database connections, API clients,
  message queues, cloud SDKs
```

## 0d. Discover architecture layers and dependency boundaries

This step identifies the structure that the feedback surfaces protect.
See `docs/feedback-layer-model.md` for the conceptual model.

```
- Read README.md and any existing architecture docs
- Scan source directories to identify modules/packages/services
- Identify architectural layers and the allowed dependency directions
  (e.g., routes → services → repositories → models)
- Identify data flow: where does input come in, where does output go
- Identify user-facing surfaces: UI (web/mobile/desktop)? API? CLI?
  This determines which feedback surfaces matter most.
- Note which dependencies are "boring" (stable, composable) vs
  "opaque" (complex, poorly documented, magic behavior)
```

## 0e. Map feedback surfaces

For each of the four feedback surfaces, discover what already exists,
what is missing, and what commands exercise it. Record gaps explicitly.
This inventory becomes the basis of `docs/feedback-profile.json`.

### 0e-i. Static Constraint Feedback

Catches illegal structure before runtime.

```
- Lint: is there a linter configured? Does it pass?
- Formatter: is there a formatter? Is code consistently formatted?
- Import/dependency direction rules: are there rules that enforce
  layer boundaries (e.g., eslint import rules, Go internal packages,
  Python import-linter, Java ArchUnit)?
- Directory ownership rules: does the project enforce which code
  belongs in which directory?
- Pre-commit hooks: any git hooks that reject bad structure?
- CI static checks: do CI pipelines run lint or architecture checks?
- GAP: if layers were identified in 0d but no import rule enforces
  the allowed directions, record this as a constraint encoding gap.
```

### 0e-ii. Contract Feedback

Catches mismatches between layers or components.

```
- Type checking: strict mode? Any type errors? (tsconfig, mypy, pyright)
- Schema validation: are request/response shapes checked at build time
  or test time? (OpenAPI, JSON Schema, Zod, io-ts, Pydantic models)
- API contract tests: are there tests that verify provider/consumer
  contracts between layers? (integration tests between service → repo,
  route → service, etc.)
- Config shape validation: does the project validate its own config
  at startup or build time?
- GAP: if layers exchange data but no typecheck or schema test covers
  the boundary, record this as a contract feedback gap.
```

### 0e-iii. Runtime Feedback

Catches failures that only appear while the program is running.

```
- Structured logs: can the agent inspect logs after a run?
- Local traces: is there a tracing or observability setup for local dev?
- Browser/UI debug: is there a devtools, screenshot, or visual diff path?
- Smoke tests: is there a minimal run command that proves the app starts?
- Environment config validation: does the app fail fast on bad env vars?
- GAP: if the project has a user-facing surface but no way for the
  agent to observe runtime behavior, record this as a visibility gap.
```

### 0e-iv. Business-Flow Feedback

Catches "the code passes all checks, but the product behavior is wrong."

```
- Scenario/acceptance tests: do tests cover actual user or operator flows?
- E2E tests: Playwright, Cypress, Selenium, Supertest, etc.
  If the project has a UI or API surface but no E2E tests, flag as a gap.
  If the project is a pure library with no user-facing surface,
  do NOT invent browser/API E2E requirements.
- Golden output tests: are there reference outputs that catch drift?
- Fixture-based integration flows: do tests exercise multi-step workflows?
- GAP: if user-facing flows exist but no test covers them end-to-end,
  record this. But distinguish between "we should add E2E" and
  "the project shape doesn't warrant E2E."
```

## 0f. Classify business flows

For each significant user or operator flow discovered, classify the
evidence level. See `docs/feedback-layer-model.md` § "Business Flow
Verification Is The Hard Part."

| Class | Meaning | Example |
|---|---|---|
| **repo-confirmed** | Already encoded in the repo as tests, specs, or contracts | Existing E2E test for login flow |
| **inferred** | Agent inferred from code structure; propose but do not treat as truth | "Likely primary route based on router" |
| **human-confirmed** | Must be asked because getting it wrong distorts the harness | Top critical user flows, unacceptable failure modes |

For each flow, record:
- Name/description
- Classification (repo-confirmed / inferred / human-confirmed)
- Which feedback surfaces currently cover it (or "none")
- Proposed verification mechanism (if gap exists)

Inferred flows will be confirmed or corrected in Phase 1.

## 0g. Establish execution contract

```
- Detect the repo's primary shell:
  - Windows/PowerShell-first repo → `powershell -File ...`
  - Linux/macOS/bash-first repo → `bash ...`
- Record a platform-native execution contract:
  - Primary shell
  - Primary quality gate command
  - Primary doc validation command
  - Portable fallback commands available from the skill bundle when needed
- Try each discovered command and record: succeeds / fails / missing
```

## 0h. Generate Discovery Report

The report is organized so the human can see what feedback the project
already has and where the gaps are.

```markdown
# Discovery Report

## Confirmed
- Language: Python 3.11
- Framework: FastAPI + SQLAlchemy
- Database: PostgreSQL (connection in src/db.py)
- Tests: pytest (47 tests, 42 passing)
- Lint: ruff (configured in pyproject.toml)
- CI: GitHub Actions (2 workflows)
- Modules: [list with one-line descriptions]

## Architecture Layers
- Pattern: layered (routes → services → repositories)
- Layers: [list with allowed dependency direction]
- Data flow: HTTP request → route → service → DB → response
- User-facing surfaces: REST API (external clients), no UI

## Feedback Surface Inventory

| Surface | What exists | Gaps |
|---|---|---|
| Static Constraint | ruff (lint, passing); no import direction rules | Layer boundaries not enforced by tooling |
| Contract | No typecheck configured; Pydantic models exist but no schema tests | No build-time contract checks between layers |
| Runtime | No structured logs; app does not validate env vars at startup | Agent cannot observe runtime failures |
| Business-Flow | 42/47 pytest pass (unit level); no E2E or scenario tests | API surface has no end-to-end coverage |

## Business Flows

| Flow | Classification | Current coverage |
|---|---|---|
| User login + token refresh | repo-confirmed (test_auth.py) | Unit tests (5 failing) |
| Order creation | inferred (routes/orders.py → services/order.py) | None |
| Top critical user flow | human-confirmed (must ask) | Unknown |

## Execution Contract
- Primary shell: windows-powershell
- Primary quality gate command: `powershell -File scripts/quality-gates.ps1`
- Primary doc validation command: `powershell -File scripts/validate-docs.ps1`
- Portable fallback commands available if the repo later needs cross-platform support

## Existing Documentation Health
(only if docs already exist)

| File | Status | Issues |
|---|---|---|
| AGENTS.md | salvageable | Missing quality gates, references deleted module |
| docs/plan.md | stale | Milestones from 6 months ago, no verification commands |
| docs/prompt.md | not found | — |
| README.md | healthy | Accurate, well-structured |

Recommendation: **reorganize** (keep README.md, rewrite AGENTS.md and plan.md,
create prompt.md and project_spec.md from scratch)

## Inferred (need your confirmation)
- Architecture appears to be layered: routes → services → repositories
- Primary data flow: HTTP request → route → service → DB → response
- The project seems to be a [B2B SaaS / CLI tool / data pipeline / ...]

## Missing (need you to provide or decide)
- No .env.example found — what environment variables are needed?
- No deployment config — where does this run?
- Cannot determine the business goal from code alone
- Top 1-3 critical user flows (for business-flow feedback layer)
- Unacceptable failure modes in production

## Needs Manifest
[see Phase 0j]
```

## 0i. Generate Feedback Profile

Create a machine-readable summary of the current feedback layer.
This is the canonical contract for "what feedback surfaces exist, how strong
they are, where evidence lives, and what still needs human input."

```json
{
  "version": 1,
  "project": {
    "name": "repo-name",
    "state": "greenfield-empty | existing-repo | reorganizing-existing",
    "kind": "web-app | api-service | cli | library | unknown",
    "languages": ["TypeScript"],
    "user_facing_surfaces": ["cli"]
  },
  "execution_contract": {
    "primary_shell": "windows-powershell",
    "primary_quality_gate_command": "powershell -File scripts/quality-gates.ps1",
    "primary_doc_validation_command": "powershell -File scripts/validate-docs.ps1"
  },
  "feedback_surfaces": {
    "static_constraint": {
      "status": "missing | partial | strong",
      "mechanisms": ["eslint", "import-boundary rule"],
      "commands": ["powershell -File scripts/quality-gates.ps1"],
      "evidence_paths": ["eslint.config.js"],
      "gaps": ["No layer-boundary rule yet"]
    },
    "contract": {},
    "runtime": {},
    "business_flow": {}
  },
  "business_flows": [
    {
      "name": "Primary CLI command",
      "classification": "repo-confirmed | inferred | human-confirmed",
      "current_coverage": ["business_flow"],
      "verification_target": "CLI smoke path passes end-to-end",
      "evidence_paths": ["tests/test_cli.py"]
    }
  ],
  "observability": {
    "logs": "where to inspect logs",
    "metrics_traces": "where to inspect metrics/traces",
    "runtime_debug": "where to inspect runtime debug evidence"
  },
  "priority_gaps": [
    "Highest-value missing feedback mechanisms"
  ],
  "human_inputs": [
    {
      "type": "human_decision",
      "name": "Top critical user/operator flows",
      "reason": "Cannot safely infer business truth from code alone",
      "blocking": true
    }
  ]
}
```

Rules:
- Keep `repo-confirmed`, `inferred`, and `human-confirmed` distinct. Do not collapse them.
- Empty repos may have no `business_flows` yet, but must still list the missing human inputs required to build business-flow feedback later.
- Do not invent mechanisms. If a feedback surface is weak, record the gap instead of pretending it is covered.
- `docs/harness-manifest.json` and `docs/feedback-profile.json` must agree on the execution contract, but they serve different purposes.

## 0j. Generate Needs Manifest

Create a structured list of everything the AI agent needs to operate:

```yaml
needs:
  # Things the human must provide
  - type: human_decision
    name: "Project goal (North Star)"
    reason: "Cannot infer business objective from code"
    blocking: true

  - type: human_decision
    name: "Hard constraints"
    reason: "Need to know what is absolutely forbidden"
    blocking: true

  - type: human_decision
    name: "Priority ordering of quality attributes"
    reason: "Need to know tradeoffs: speed vs correctness vs coverage"
    blocking: true

  # Things the agent can fix but needs permission
  - type: tooling
    name: "pytest configuration"
    reason: "Found tests/ but no conftest.py or pytest.ini"
    blocking: false
    auto_fixable: true

  # Things that require external setup
  - type: env_var
    name: "DATABASE_URL"
    reason: "Referenced in src/db.py but not in any .env or config"
    blocking: true

  - type: external_service
    name: "PostgreSQL instance"
    reason: "Integration tests require a running database"
    blocking: false
    workaround: "Can use SQLite for unit tests"
```

## 0k. Generate Harness Needs Assessment

Based on discovery, assess what harness artifacts this project actually needs.
Do NOT assume a fixed list — derive the needs from what you found.

**Document roles** (assess each):

| Role | When needed | When NOT needed |
|---|---|---|
| `agents_doc` | Always — the agent navigation layer | — |
| `plan_doc` | Always — milestone tracking | — |
| `prompt_doc` | Always — current milestone contract | — |
| `implement_doc` | Always — execution runbook | — |
| `project_spec_doc` | When stable project-level principles are worth keeping across milestones | Trivial single-milestone project |
| `documentation_doc` | When the project has multiple iterations to track | Single-shot task |
| `compaction_doc` | When long-running agent sessions are expected | Short tasks that fit in one session |
| `failure_taxonomy_doc` | When the project has enough complexity for recurring failure patterns | Simple projects |

For each role, record: `needed` / `recommended` / `not-needed-yet` with a reason.

**Script needs** (assess each):
- Quality gate script: needed if quality tools exist or will be set up
- Doc validation script: needed if multiple docs will be generated
- Cross-platform variants (.sh + .ps1): needed if the team uses multiple OS

**Operational sub-skill needs** (assess each):
- `iterate`: always needed
- `quality-audit`: needed if quality tools or feedback surfaces require periodic audit
- `milestone-promote`: needed if there are multiple milestones or explicit handoff checkpoints

Do NOT create separate sub-skills for review-packet assembly or doc maintenance by default.
Those responsibilities should usually stay inside `milestone-promote` and normal iteration/doc validation flow unless the repo proves a separate reusable capability is necessary.

**Additional harness artifacts** (discover, don't assume):
- E2E playbook: only if the project has user-facing surfaces
- API contract doc: only if the project exposes APIs
- Deployment runbook: only if deployment is in scope
- Architecture decision records: only if cross-cutting architectural decisions are expected
- Any other artifact the discovery suggests — do not invent needs, discover them

Present the Discovery Report, Feedback Profile, Needs Manifest, and Harness Needs Assessment together.

**After presenting the Discovery Report, Feedback Profile, Needs Manifest, and Harness Needs Assessment, proceed to Phase 1.**
