# Governance-First Adaptive Orchestration

Status: implemented through Plan 003: governance/content evidence and adaptive
staffing are enforced as separate planes.

## Purpose

GedPi should scale ceremony and staffing independently. A request's risk decides
what evidence must exist; available assistants decide only how the work is
performed. The coordinator remains the only user-facing brain and final decision
owner in every configuration.

## Invariants

1. Governance works identically with optional agents enabled or disabled.
2. A role name, launch, completion event, disabled-role fallback, Markdown file,
   branch name, or successful process is never authorization.
3. Every mutating request explicitly opens or continues one immutable work ID.
4. `.ged/runtime/<work-id>/governance.json` is the sole machine authority.
5. The coordinator owns scope, risk, plan acceptance, evidence adjudication,
   commits, pushes, and lifecycle transitions.
6. One writer owns a checkout/worktree. Parallel writers require intentionally
   isolated worktrees.
7. Publication is user-owned. GedPi never pushes without an explicit request.

## Governance plane

### Work modes

- **read-only**: inspection, explanation, research, or reporting. It opens no
  mutating work and authorizes no repository mutation.
- **direct-change**: mutation is requested, ambiguity is resolved, risk is not
  high, and the change is clear, bounded, reversible, and deterministically
  checkable.
- **planned-change**: the user requests planning, risk is high, a user-owned
  decision is unresolved, the coordinator escalates, or any direct-change
  condition is missing.

The resolver applies precedence rather than a heuristic score:

1. no mutation intent → read-only;
2. unresolved user decision → planned-change with mutation still blocked;
3. explicit planned minimum, high risk, or coordinator escalation →
   planned-change;
4. every direct-change eligibility fact true → direct-change;
5. otherwise → planned-change.

File count and staffing are not mode authority.

### Task-scoped identity

Work IDs are generated and immutable. Branch and HEAD are diagnostic metadata
only. Session-scoped pointers live under
`.ged/runtime/active-work/<session-key>.json` and bind a work ID to one fresh
agent-request nonce. Every new mutating request must call `ged_work open`, or
`ged_work continue` when the user is explicitly continuing the exact work ID.

Open receives structured minimum mode, ambiguity, risk, direct-change facts,
and an optional execution profile. Governance is initialized before the new
work item is bound to the request. Continue fails closed for absent, malformed,
read-only, unresolved, paused, blocked, completed, cancelled, or imported
non-selectable state.

### Authoritative state

`governance.json` stores schema version, work identity, revision, lifecycle,
mode decision, execution profile, append-only evidence, approvals, and optional
current slice. Accepted changes use serialized compare-and-swap semantics.
Markdown status and handoff files are regenerable projections only.

Legacy `checkpoints.json` files remain parser/migration inputs while
compatibility is needed. Migration preserves byte-exact ignored backups and may
import one unambiguous candidate as paused review data. Legacy role evidence is
never copied into authorizing fields or selected as current work.

### Role-neutral transitions

`ged_governance accept-plan` fingerprints exact SPEC/TASKS/TESTS bytes and
appends satisfied plan evidence after the coordinator finalizes the canonical
artifacts and any configured human review is complete. With Plannotator
selected, `gedpi_plan_review` runs first and its structured tool result binds
the approval to those exact current bytes; missing or stale visual approval
blocks acceptance. Planned-change source mutation requires the latest plan
evidence to be satisfied.

`ged_governance record-verification` executes argv-based checks, records bounded
outputs/exits and non-secret runtime keys, and binds satisfied evidence to the
full repository snapshot plus observed work scope. Structured review findings,
failed commands, unscoped changes, malformed evidence, and process success
alone are non-authorizing. A later failed plan or verification record supersedes
an earlier satisfied record of the same kind.

Known mutation-capable calls, mutating bash, and unknown tools enter
authoritative durable pending state before execution. Pre/post snapshots append
implementation evidence with exact changed paths whenever final content differs,
even after a failed process; final no-op/restore calls clear pending state. A
pending call blocks commit even after restart. Assistant results can inform the
coordinator but never write these transitions automatically.

Before commit, staged paths must be inside observed work scope and the full
current snapshot must equal current verification. Auto-staging and compound
commit commands are rejected. A milestone is recorded only when HEAD advances
and the committed tree exactly equals the pre-call verified index tree. Commit
pairing is durable and reconciled after restart; mismatched hook-expanded trees
remain fail-closed. A milestone does not consume plan evidence or close current
or legacy work.

### Explicit lifecycle

`ged_lifecycle` changes one exact work ID with a coordinator-owned reason and a
runtime timestamp. Active work can pause or become completed, abandoned, or
superseded. Paused work can resume or become terminal. Terminal work never
transitions again and cannot authorize a later request.

Every accepted lifecycle change appends immutable `from`/`to` history and
advances governance revision once. Any durable pending mutation blocks a
transition. Completion additionally requires the same current plan and
verification evidence required for commit. Commits, staffing changes, subagent
events, Markdown edits, and legacy checkpoints never change lifecycle.

### Protected Ged paths

The runtime resolves existing targets and their nearest existing ancestors,
including symlinks, rather than trusting a `.ged` substring:

- current `SPEC.md`, `TASKS.md`, `TESTS.md`, `NOTES.md`, durable root memory,
  and project skills are metadata mutations;
- governance state, session pointers, migration records, `META.json`, other
  work items, and unknown `.ged` paths are runtime-owned and protected;
- paths outside `.ged` are source mutations for the current guard boundary.

## Current enforcement boundary

The runtime uses conservative tool classification plus pre/post repository
snapshots. This is an accident-prevention and evidence boundary, not an OS
sandbox: processes outside Pi and adversarial filesystem races cannot be
attributed with OS-level certainty. Snapshots must stabilize across repeated
captures, and large files use streaming full-content hashes.

## Execution staffing plane

Staffing is capacity, not governance. The pure recommendation selector uses:

```text
team shape = f(decomposability, context spread, difficulty, budget)
```

The coordinator owns the final choice among:

- **solo**: coordinator executes directly;
- **assisted**: one focused scout, reviewer, or verifier;
- **coordinated**: several disjoint evidence producers and/or isolated workers;
- **high-stakes**: stronger independent review and stricter acceptance.

High-stakes difficulty takes deeper fresh review; low budget prefers solo;
disjoint work can become coordinated; broad, bounded, or difficult work can be
assisted. Staffing can escalate or shrink without changing work mode. A
planned-change can remain solo; a read-only request can use several scouts.

Capabilities are typed separately from model bindings. Legacy role aliases map
to Scout, planner, plan-reviewer, verifier, Worker, and Smart Worker. Scout and
review roles are fresh read-only leaves. Worker is a fork-capable writer leaf.
Smart Worker is a fork-capable writer with only explicitly assigned depth-one
read-only fanout.

The adaptive binding validates exact live registry IDs before saving:

| Capability | Primary | Thinking | Fallback |
|---|---|---|---|
| Scout | `openai-codex/gpt-5.6-sol` | `low` | Luna/low |
| Worker | `openai-codex/gpt-5.6-luna` | `max` | Sol/max |
| Smart Worker | `openai-codex/gpt-5.6-sol` | `high` | Luna/max |
| Planner/reviewer/verifier defaults | Sol | high | Luna/high or max |

Explicit user role bindings remain higher precedence. Missing active candidate
chains are diagnosed without startup failure or silent provider substitution.
User-facing `maximum` and legacy `reasoningEffort` normalize to `max`.

GedPi statically validates the public pi-subagents `workflowScript` shape.
Direct `runs.run`/`runs.all` launches must be returned or awaited. Parallel
readers are permitted. More than one possible writer requires managed
`worktree: true` on every writer lane or at workflow level. Dynamic parallel
lanes require workflow-level isolation; aliases, duplicate isolation fields,
and spread-based ambiguity fail closed. A current-checkout async writer holds a
checkout-scoped filesystem lease and durable pending mutation until its exact
completion event captures pre/post content. Independent processes contend on
the same atomic lease directory. After restart, an active lease is reclaimed
only when its exact pi-subagents `status.json` is terminal; missing, corrupt,
launching, or paused state remains fail-closed. Managed worktree writers return handoff
artifacts for coordinator adjudication.

Ordinary Worker contracts expose no subagent tool and set recursion depth zero.
Top-level read-only contracts omit bash/edit/write and include only native
inspection plus supervisor coordination tools.
Smart Worker exposes the current public subagent runtime at depth one. Its
child-only extension registers a public inherited capability ceiling allowing
only the four read-only Ged agent names and read/grep/find/ls plus internal
supervisor/structured-output tools; nested bash/edit/write and writer agents are
removed or rejected before launch.

Native `contact_supervisor`/`subagent_supervisor` is used for required child
decisions, structured input, and plan-changing discoveries. Routine completion
returns through subagent results. External `pi-intercom` peer messaging is a
separate setting, disabled by default. When explicitly enabled, it only sends
verified facts or dependency updates to an exact user-directed target; peers
never ask each other for decisions, direct edits, change scope, or turn inbound
messages into authority.

## Durable memory

- Fresh init creates required machine metadata only; human Markdown is lazy and
  must contain substantive content.
- `.ged/PROJECT.md`, root `CONTEXT.md`, and sparse `docs/adr/` records are the
  canonical project-summary, vocabulary, and decision destinations.
- Direct work gets `DIRECT.md`; planned work gets SPEC/TASKS/TESTS; attempt and
  recovery artifacts live under `.ged/work/<work-id>/tasks/<task-id>/`.
- `.ged/runtime/<work-id>/governance.json` contains authoritative machine state.
- Runtime Markdown is optional projection/handoff material, generated only for
  explicit status or real cross-session handoff needs.
- Explicit reusable project skills live under Pi-native `.agents/skills/` and
  persist independently of task completion.
- `.pi/` contains ignored acceleration caches such as the repo map.

Legacy v2 glossary/decision bytes are backed up and migrated exactly once;
ambiguous substantive data is retained and reported instead of guessed away.
Dynamic prompt content is trust-labeled and collision-safe framed. Current-state
documents should be edited in place. Historical narrative belongs in Git
history, release notes, retained archives, or explicit ADRs.
