# Agent Protocol Upgrade Prompt

**Purpose:** Bring an existing ontoref-adopted project up to the agent-aware protocol v2.
Covers: just recipe convention compliance, reflection mode step schema, agent CLAUDE.md
entry-point, graph readiness, and a full agent simulation smoke test.

**Prerequisite:** Project already has `.ontology/`, `reflection/modes/`, and `ontoref`
installed globally (`~/.local/bin/ontoref`, via `just install-daemon` from the ontoref repo).
If the project hasn't adopted ontoref at all, run `project-full-adoption-prompt.md` first.

**Substitutions required before use:**
- `{project_name}` — kebab-case project identifier
- `{project_dir}` — absolute path to project root

---

## Phase 0 — Discovery: what is the current state

Run these before touching anything.

```sh
cd {project_dir}

# What does ontoref already see about this project?
ONTOREF_ACTOR=agent ontoref describe capabilities

# Just recipe categorization
ONTOREF_ACTOR=agent ontoref describe capabilities \
  | from json | get just_recipes | group-by category | transpose key value \
  | each { |r| { category: $r.key, count: ($r.value | length) } }

# Project flags: which features are detected?
ONTOREF_ACTOR=agent ontoref describe capabilities \
  | from json | get project_flags

# Justfile convention violations
ONTOREF_ACTOR=agent ontoref validate justfile

# Existing reflection modes
ls reflection/modes/*.ncl 2>/dev/null || echo "no modes"

# Ontology graph — see nodes/edges and their level classification
ONTOREF_ACTOR=agent ontoref graph ontology
```

Identify:
- Which canonical just modules are missing (required: build, test, dev, ci)
- Whether `default` and `help` recipes exist in the root justfile
- Whether reflection modes have `actor` and `on_error` fields in their `steps[]`
- Whether `.ontology/core.ncl` nodes have `level` fields (for graph coloring)
- Whether `reflection/backlog.ncl` exists (for `has_backlog` flag)

---

## Phase 1 — Just recipe convention compliance

### 1a. Run the validator

```sh
ONTOREF_ACTOR=agent ontoref validate justfile --fmt json
```

Act on these fields in the output:
- `missing_required_modules` — canonical just files that must be created
- `missing_required_recipes` — `default` and/or `help` missing from root justfile
- `missing_required_variables` — `project_root` not declared anywhere

### 1b. Fix missing required modules

For each name in `missing_required_modules`, create `justfiles/{name}.just`:

```just
# {name} recipes for {project_name}

[doc("Show {name} help")]
help:
    @just --list
```

Import it in the root `justfile`:

```just
import 'justfiles/{name}.just'
```

**Recipe → module mapping:**

| Module  | What goes here |
|---------|----------------|
| `build` | Compilation, linking, binary generation, asset bundling |
| `test`  | Unit, integration, property-based tests |
| `dev`   | `fmt`, `lint`, `watch`, `clean`, local dev setup |
| `ci`    | CI pipeline orchestration (`ci-full`, `ci-lint`, `ci-test`, `ci-audit`) |
| `distro`| Packaging, `install-*`, `release`, distribution targets |
| `docs`  | Documentation generation and serving |
| `nickel`| Nickel typecheck, export, contract validation |
| `deploy`| Deployment to staging/production environments |

Move existing recipes to the correct module file. Group by concern, not by file size.

### 1c. Fix missing required recipes

If `default` is missing from root `justfile`:
```just
default:
    @just --list
```

If `help` is missing:
```just
[doc("Show available recipes")]
help:
    @just --list
```

### 1d. Fix missing required variables

```just
project_root := justfile_directory()
```

### 1e. Verify

```sh
ONTOREF_ACTOR=agent ontoref validate justfile
# Expected: "✓ justfile validates against convention"
```

---

## Phase 2 — Reflection mode step schema

For `run start` / `step report` / `graph <mode-id>` to work, each mode NCL file needs
steps with the v2 fields. Check what each mode currently has:

```sh
for f in reflection/modes/*.ncl; do
  echo "=== $f ==="
  nickel export --import-path $NICKEL_IMPORT_PATH "$f" 2>/dev/null \
    | jq '[.steps[] | {id, actor: (.actor // "MISSING"), on_error: (.on_error // "MISSING")}]'
done
```

Or via the ontoref CLI:

```sh
ONTOREF_ACTOR=agent ontoref describe mode | from json \
  | each { |m| { id: $m.id, steps: ($m.steps | length),
      missing_fields: ($m.steps | where { |s| ($s.actor? | is-empty) or ($s.on_error? | is-empty) } | length) } }
```

### 2a. Required fields per step

Each step in `steps[]` must have:

```nickel
{
  id         = "kebab-step-id",
  action     = "What this step does (human-readable).",
  actor      = 'Agent,     # 'Human | 'Agent | 'Both
  on_error   = 'Stop,      # 'Stop | 'Continue | 'Retry
  depends_on = [],         # list of { step = "id", kind = 'Always } or { step = "id", kind = 'OnSuccess }
}
```

**`actor` decision:**
- Agent does it autonomously (builds, file writes, nickel export, API calls) → `'Agent`
- Human must do it (review, approve, deploy decision) → `'Human`
- Either depending on context → `'Both`

**`on_error` decision:**
- Failure invalidates subsequent steps (build fails → tests cannot run) → `'Stop`
- Step can fail without blocking others (optional lint, docs) → `'Continue`
- Transient failures should be retried → `'Retry`

### 2b. Verify graph output for each mode

```sh
ONTOREF_ACTOR=agent ontoref graph <mode-id>
```

Each mode should render a `flowchart TD` with nodes colored by actor class (human/agent/both)
and dependency edges. If you see `note["Failed to export mode"]`, the NCL export is broken.

---

## Phase 3 — CLAUDE.md agent entry-point

Add this block to `.claude/CLAUDE.md`. Insert before the last major section or append at
the end.

```markdown
## Agent Entry-Point Protocol

When arriving at this project as an agent, execute these discovery steps in order
before any code changes:

```sh
# 1. Project capabilities — what this project has and can do (JSON for parsing)
ONTOREF_ACTOR=agent ontoref describe capabilities

# 2. Available reflection modes — operational DAGs you can execute
ONTOREF_ACTOR=agent ontoref describe mode

# 3. Start a run before any structured work session
ONTOREF_ACTOR=agent ontoref run start <mode-id> --task "description"

# 4. Report each step as you complete it
ONTOREF_ACTOR=agent ontoref step report <mode-id> <step-id> --status pass|fail|skip

# 5. Verify mode completion (checks all required steps are reported)
ONTOREF_ACTOR=agent ontoref mode complete <mode-id>
```

Graph output (Mermaid DSL, parseable):
```sh
ONTOREF_ACTOR=agent ontoref graph ontology     # ontology nodes + edges
ONTOREF_ACTOR=agent ontoref graph deps         # Rust crate dependency graph
ONTOREF_ACTOR=agent ontoref graph flow         # current run step statuses
ONTOREF_ACTOR=agent ontoref graph <mode-id>    # mode DAG colored by actor
```

Justfile validation:
```sh
ONTOREF_ACTOR=agent ontoref validate justfile  # check against convention schema
```

The `describe capabilities` JSON output contains: `project_flags` (has_rust, has_ui,
has_mdbook, has_nats, has_precommit, has_backlog, has_git_remote, open_prs, crates),
`just_recipes` (categorized by canonical module), `backlog_pending` count, and full
ontology/reflection metadata.

---

## Phase 4 — Graph readiness

### 4a. Ontology node levels

`graph ontology` colors nodes by the `level` field. Nodes without `level` fall back to
`project` class (dark neutral). Add `level` to nodes in `.ontology/core.ncl` where
the distinction matters:

```nickel
{ id = "my-node", name = "Name", level = 'Practice, ... }
# 'Axiom | 'Tension | 'Practice | 'Project | 'Moment
```

Validate:
```sh
ONTOREF_ACTOR=agent ontoref graph ontology
# classDef coloring should be visible in the Mermaid output
```

### 4b. Crate dependency graph (Rust projects only)

```sh
ONTOREF_ACTOR=agent ontoref graph deps
```

`Single-crate project — no inter-crate deps to show` is the correct output for
non-workspace projects. If workspace members are missing, check `Cargo.toml [workspace]`
has `members` listed.

---

## Phase 5 — Smoke test: full agent simulation

```sh
cd {project_dir}

# Discovery
ONTOREF_ACTOR=agent ontoref describe capabilities | from json \
  | select project_flags backlog_pending

# List modes — pick one for the test
ONTOREF_ACTOR=agent ontoref describe mode | from json

# Start a run (replace <mode-id> and <first-step-id> with real values from above)
ONTOREF_ACTOR=agent ontoref run start <mode-id> \
  --task "agent protocol upgrade smoke test"

# Pending steps
ONTOREF_ACTOR=agent ontoref run status

# Report one step
ONTOREF_ACTOR=agent ontoref step report <mode-id> <first-step-id> --status pass

# Flow graph — reported step should show as pass
ONTOREF_ACTOR=agent ontoref graph flow

# Complete the run
ONTOREF_ACTOR=agent ontoref mode complete <mode-id>
```

Expected:
- `describe capabilities` → parseable JSON, non-empty `project_flags` and `just_recipes`
- `run start` → `{ run_id, mode, task, started_at }`
- `run status` → all steps `pending` before any reports
- `graph flow` → reported step colored `pass`, rest `pending`
- `mode complete` → `ok: true` if all `Stop`-on-error steps were reported, else `blockers` list

---

## Checklist

### Just recipe convention
- [ ] `validate justfile` returns ok
- [ ] Required canonical modules present: `build`, `test`, `dev`, `ci`
- [ ] Root `justfile` has `default` and `help` recipes
- [ ] `project_root` variable declared

### Reflection mode step schema
- [ ] All modes export cleanly via `nickel export`
- [ ] Every step has `actor`, `on_error`, `depends_on` fields
- [ ] `graph <mode-id>` renders with actor-colored nodes for all modes

### CLAUDE.md agent entry-point
- [ ] `.claude/CLAUDE.md` has Agent Entry-Point Protocol section

### Graph readiness
- [ ] `graph ontology` renders without errors, node levels correct
- [ ] `graph deps` renders without errors
- [ ] `graph flow` renders after a run with at least one reported step

### Smoke test
- [ ] `describe capabilities` parses as JSON without errors
- [ ] `run start` → `step report` → `mode complete` cycle completes without errors
- [ ] `mode complete` returns `ok: true`

### Do NOT commit without developer review
