# BrainDrive Process Guardrails V2 Specification

## 1. Document Header

| Field | Value |
|---|---|
| Status | Draft for Review |
| Date | 2026-07-26 |
| Specification type | Feature / replacement runtime enhancement informed by a failed V1 activation design |
| Intended audience | Dave W, Dave J, BrainDrive engineering, AI coding agents, QA and harness maintainers, security reviewers, and future runtime maintainers |
| Project | BrainDrive model-independent process reliability |
| Primary repository | `BrainDriveAI/braindrive`; clean implementation work is expected to start from `dev` |
| Affected applications | TypeScript gateway/runtime, web-client empty-state process entry, owner memory tools, canonical starter-pack process files, supported provider integrations, and local/cloud verification harnesses |
| Related documents | `local-harness-proposal.md`; `2026-07-21-braindrive-process-guardrails-spec-d2.md`; `2026-07-21-braindrive-process-guardrails-implementation-plan.md`; `profile_issue.md` |
| Prior implementation reference | Branch `agent/process-guardrails`, commit `f9e61379`; retained as evidence and a selective reference, not as the implementation base |
| Base branch | `dev` at the time of drafting |
| Related decision | D4: judgment in text, orchestration in code, initially scoped to the local-model lane |
| Document owner | Dave W for product direction; Dave J for runtime boundary and implementation review |
| Revision summary | Re-specifies process guardrails from the original proposal, fixes the model-dependent entry failure, makes profile handling a required process outcome, defines one provider-independent controller as built-in behavior with no runtime switch, retains ≤12B local efficacy as the primary proof, and adds a cloud no-regression gate. |

### Approval State

- D4 ratifies the underlying direction: keep behavior and judgment in owner-editable text while moving deterministic process orchestration into code where smaller local models require it.
- The V1 implementation is not accepted as proof of that direction because real Ollama runs never entered the controller.
- This document is a replacement V2 contract. It does not amend or delete the V1 branch or its historical artifacts.
- Profile approval policy remains a product-policy question, but profile recognition, routing, and explicit disposition are required regardless of that decision.
- Implementation planning should begin only after the deterministic entry contract, unconditional provider-independent boundary, profile outcome contract, local efficacy bar, cloud no-regression bar, and V2 done-done definition are reviewed and accepted.

## 2. Executive Summary

BrainDrive's canonical owner process is expressed in readable memory files: interview the owner, write or update the page goals/specification, build the page plan, route stable cross-project facts to the owner profile, and establish the journal follow-up handoff. Smaller local models can conduct useful conversations but may skip procedure files, omit required writes, write artifacts out of order, silently ignore profile-worthy facts, or produce structurally invalid owner files.

The first process-guardrail implementation created substantial state, validation, retry, trace, and recovery machinery, but placed the activation decision behind a model-callable `process_start` tool. Real Gemma 31B and Gemma 12B Ollama runs were provider-eligible and page-eligible, yet neither called that tool. Both remained on the ordinary agent path, where all memory writes were still available. The stronger model largely followed the text process itself; the smaller model skipped required procedure and profile behavior. The controller therefore did not assist the models in the scenario it was built to improve.

V2 corrects the boundary first and keeps the first proof narrow:

1. The existing owner-visible empty-page CTA supplies a structural process-start signal through existing request metadata.
2. The gateway, not the model, decides that the registered process has started.
3. Each active stage receives its canonical owner-editable instructions and only the necessary owner context.
4. Code enforces stage order, permitted writes, deterministic artifact structure, explicit profile disposition, and one correction attempt.
5. The model may not bypass an active or explicitly requested process by writing canonical process artifacts through the ordinary path.
6. Ollama, BrainDrive Models, and BYOK OpenRouter always use the same guarded process semantics for eligible requests; provider identity does not change process behavior.
7. A real Gemma-class model at or below the 12B tier must pass the defined local live scenarios, and guarded cloud comparisons must meet the no-regression bar, before the built-in behavior is accepted.

The work is intentionally not a generalized workflow engine. It does not add a runtime judge, provider-specific prompt branches, a new process-definition language, a dashboard, or mixed-model routing. Existing V1 code may be reused only when it directly satisfies this contract more simply than a clean implementation.

## 3. Background and Context

### 3.1 Original Product Direction

The ratified proposal refined BrainDrive's text-first principle to:

> Judgment in text; orchestration in code where a model tier genuinely requires it.

The proposal identified a stable process shape and a repeated model limitation:

- The owner-readable process had stabilized around interview → specification → plan → journal.
- Small models could not reliably retain and execute the full process across a long open-ended context.
- More prompt text increased context pressure without guaranteeing sequence or writes.
- Fine-tuning could improve adherence but could not guarantee file placement, bounded retry, or completion.
- Code was justified for deterministic sequence and guarantees, while owner-editable text remained authoritative for questions, tone, qualitative criteria, and judgment.

The proposal's first intended proof lane was local models. Its success prediction was that sequencing failures would approach zero and remaining failures would concentrate in qualitative judgment.

### 3.2 Existing BrainDrive Process

The current starter pack defines:

- page `AGENT.md` files for scope, boundaries, and domain behavior;
- `run-interview.md` for interview and specification behavior;
- `run-planning.md` for plan behavior;
- `run-journal.md` for follow-up and journal behavior;
- page `spec.md`, `plan.md`, and `journal.md` as canonical owner artifacts;
- `me/profile.md` as the canonical home for confirmed stable cross-project owner facts, values, preferences, and life context.

The current gateway builds a general project-scoped prompt and runs the ordinary model/tool loop. The model decides which instruction files to read and which tools to call. This remains useful for general conversation, but it is not a deterministic process controller.

### 3.3 Existing Product Entry Surface

The web client already renders a process-oriented empty state for `finance`, `fitness`, `career`, `relationships`, and `new-project`. Each supported page presents a CTA such as `Let's get started` or `Let's figure it out`. Today that click sends only ordinary chat text through `ChatPanel` and the existing message metadata path. The request contract already permits metadata, and the gateway already uses metadata to resolve the active project.

This existing CTA is the preferred V2 structural entry point. It provides explicit owner action without adding a keyword classifier or requiring the local model to understand an internal runtime tool.

### 3.4 V1 Implementation and Failure Evidence

The V1 branch added approximately 10,000 lines across activation, process state, trace storage, a controller, guarded tools, gateway integration, tests, and documentation. The implementation included many sound internal concepts, but its process-start seam followed an unresolved recommendation from the prior build plan:

- expose `process_start` to an otherwise ordinary eligible model call;
- enter the controller only if the model calls it;
- preserve the ordinary unguarded path, including memory writes, when the model does not call it.

This behavior is verified in:

- `builds/typescript/engine/process-guardrails/activation.ts`;
- `builds/typescript/gateway/server.ts`;
- `builds/typescript/gateway/process-guardrails.ts`;
- `builds/typescript/gateway/process-guardrails.integration.test.ts`.

The integration tests explicitly expect an eligible no-start request to remain one ordinary model call with `memory_write` available and no process persistence.

On 2026-07-24:

- a Gemma 31B Ollama Fitness run remained `process_start_available` on every turn and never created guarded state;
- a Gemma 12B Ollama Relationships run did the same;
- the 31B model largely followed the process from text unaided;
- the 12B model did not read the full interview procedure, wrote noncanonical page artifacts, omitted required Relationships content, and never attempted to route stable household facts to the profile;
- neither run exercised staged context, deterministic validation, retry, or guarded persistence.

The V1 guarded write contract also allowed `me/profile.md` to be read but not written. That contradicted starter-pack procedures that require the interview to consider and, when permitted, route stable cross-project facts to the profile.

### 3.5 Lessons Applied to V2

1. A guardrail cannot depend on the target model volunteering to activate it.
2. Green scripted tests do not demonstrate local-model efficacy when the scripts always call the internal start tool.
3. Process entry must be a product-owned structural signal.
4. Protected process writes must not remain available as an unguarded bypass after explicit process entry.
5. Profile handling is part of the real BrainDrive interview process, not an optional future subsystem.
6. The profile approval policy may change without changing the requirement to identify, route, and explicitly resolve profile-worthy facts.
7. Real ≤12B evidence must gate complexity and acceptance early, rather than being deferred until after a large controller is complete.
8. Provider-independent activation can remain simple: one controller that always handles eligible process entry, with local efficacy and cloud no-regression proven separately before acceptance.

## 4. Problem Statement

### 4.1 Affected Actors

The primary affected actor is a BrainDrive owner using any supported model provider, with the highest efficacy risk concentrated in Ollama-served models at or below the 12B class. Builders and QA operators are affected because passing unit tests can currently coexist with complete runtime bypass during real owner use.

### 4.2 Trigger

The owner selects the process-oriented CTA on an empty supported page and expects BrainDrive to interview them and produce the page's canonical goals and plan while correctly considering profile information.

### 4.3 Incorrect Current Result

On the V1 branch, the CTA produces ordinary message text. The gateway exposes `process_start`, but the selected model must choose to call it. If the model does not:

- no guarded run starts;
- no stage-specific context is assembled;
- no sequencing or validation occurs;
- no retry is available for incomplete artifacts;
- ordinary memory writes remain available;
- no process trace or state proves that guardrails ran;
- the model may omit profile handling or write page artifacts outside their templates.

### 4.4 Expected Result

The CTA must cause the gateway to start the registered process deterministically before the first stage model call on every supported provider. The selected model must receive the correct stage instructions and context without needing to request guardrail assistance. Page artifact and profile outcomes must be structurally resolved before the process can complete.

### 4.5 User-Visible Impact

Owners can currently believe they tested process guardrails when they only tested the model's ordinary prompt adherence. A smaller model may sound competent during the conversation while silently producing incomplete or misplaced owner memory.

### 4.6 Operational and Data-Integrity Impact

- Efficacy conclusions are invalid when there is no guarded state or entry event.
- Scripted happy-path integration tests overstate real-model behavior.
- Canonical artifacts can be overwritten outside stage validation.
- Profile-worthy facts may be silently lost.
- A whole-file fallback write can damage customized owner content.
- Builders cannot separate controller quality from entry failure without inspecting low-level audit evidence.

### 4.7 Why Workarounds Are Insufficient

- Strengthening the `process_start` description still relies on model adherence.
- Natural-language keyword matching moves owner intent judgment into brittle code.
- Guarding every page message would disrupt ordinary questions and broaden the product behavior.
- Telling owners to use a special phrase does not create a structural signal.
- Waiting for a protected write before starting guardrails allows the interview itself to run without stage context.
- A larger model succeeding unguarded does not prove that a smaller model received assistance.

### 4.8 Defect Reproduction

| Field | Evidence |
|---|---|
| Preconditions | V1 branch; scope `all` or `local`; provider `ollama`; supported empty page; Gemma local model selected |
| Trigger | Owner clicks or sends the page CTA text, for example `Let's get started` |
| Current result | Activation remains `process_start_available`; model runs the ordinary loop; no process state or trace is created |
| Expected result | Structural CTA intent starts the interview stage before the model call |
| Frequency | Reproduced for both tested Gemma 31B and Gemma 12B conversations |
| Environment | BrainDrive TypeScript gateway/web client with Ollama OpenAI-compatible endpoint |
| Evidence | `diagnostics/audit/2026-07-24.jsonl`, prompt audit, conversations, and absence of process trace/state |
| Workaround | None that provides deterministic assistance; a model may happen to call `process_start` or follow the full process unaided |

### 4.9 Root-Cause Analysis

**Confirmed cause:** Process entry was delegated to a model-callable tool. The gateway initialized `processStartRequested` as false and started the controller only after receiving a successful `process_start` tool result.

**Confirmed contributing factor:** The pre-start executor delegated all non-control tools to the ordinary executor, so omission of `process_start` did not fail closed.

**Confirmed test gap:** No acceptance test required the existing CTA to enter the controller without model cooperation. Scripted controller tests supplied `process_start` directly.

**Confirmed profile contract gap:** The guarded stage definitions permitted `me/profile.md` reads but artifact validation accepted only the current page stage artifact.

**Process cause:** The original spec left owner-intent eligibility abstract. The implementation plan treated the process-start signal as an open question but allowed a recommended default to become production behavior before real local-model proof.

## 5. Goal

### 5.1 Primary Goal

Make the existing BrainDrive first-use interview → specification → plan → journal-handoff process reliably executable across supported providers by placing process entry, stage sequence, write boundaries, structural validation, bounded correction, and explicit profile disposition under runtime control while keeping qualitative behavior in owner-editable text. Prove the assistance is effective with an Ollama-served model at or below the 12B class and non-regressive for supported cloud providers.

### 5.2 Measurable Outcome

Across the frozen V2 local proof set:

- every CTA-started qualifying run enters guarded execution before its first model call;
- there are zero unrequested stage skips or out-of-order accepted artifacts;
- there are zero unguarded writes to protected process artifacts after structured process entry;
- every interview resolves profile disposition explicitly;
- valid page artifacts preserve their canonical structure and existing unrelated owner content;
- no automatic stage receives more than one correction attempt;
- at least one ≤12B local model completes the required end-to-end scenarios within the agreed 16 GB-class owner-hardware envelope.

### 5.3 Secondary Goals

- Keep changes to stage behavior possible through canonical text edits without TypeScript changes.
- Make guarded versus ordinary behavior unambiguous in evidence.
- Preserve normal conversation for non-CTA messages and unsupported pages.
- Apply one process contract across supported providers while preserving provider execution contracts and meeting the cloud no-regression bar.
- Make the profile approval rule replaceable without redesigning process entry or profile recognition.
- Reuse only the minimum proven V1 concepts needed for V2 acceptance.

## 6. Non-Goals

- Building a general workflow engine, process DSL, registry UI, or owner-authored process definitions.
- Provider-specific process prompts, stages, validators, retry budgets, profile rules, or completion semantics.
- A runtime enable/disable switch, feature flag, environment variable, settings control, or dormant disabled path for process guardrails.
- Automatically classifying arbitrary natural-language messages as process intent.
- Guarding every conversation on a supported page.
- Adding a runtime model judge or qualitative scoring gate.
- Fine-tuning, packaging, downloading, or distributing a local model.
- Routing different stages to different models.
- Rewriting starter-pack domain behavior to compensate for runtime entry.
- Resolving the universal profile approval policy in runtime code.
- Adding a dashboard, progress wizard, metrics service, or new diagnostics browser.
- Creating synthetic journal content during initial alignment.
- Migrating or deleting V1 diagnostic state.
- Reusing the V1 branch wholesale.

## 7. In Scope

### 7.1 Deterministic Entry

- Add a structural start signal to the existing supported-page empty-state CTA request.
- Validate the signal against the active page, current conversation, supported provider, and fixed process identity.
- Start the guarded interview stage without a preliminary model discovery call.
- Continue an already active guarded run from durable process state.
- Reject malformed, stale, cross-page, or unsupported start signals without starting guarded work.

### 7.2 Provider-Independent Built-In Availability

- Treat process guardrails as built-in behavior for every eligible structured process request.
- Do not add a runtime setting, environment variable, feature flag, provider scope mode, or disabled code path.
- Enable the same V2 process semantics for stable provider identities `ollama`, `braindrive-models`, and `openrouter`.
- Leave unknown providers, root Your Agent, and unsupported pages on the existing path.
- Do not add provider-specific stage definitions, prompts, validators, retries, state transitions, or profile behavior.

### 7.3 Fixed Process

- Support exactly one process with stages:
  1. interview;
  2. specification and profile disposition;
  3. plan;
  4. journal handoff.
- Keep each stage active across the owner turns it requires.
- Load the applicable page instructions and owner overlays for the active stage.
- Advance only after the current stage has an accepted structural outcome or an explicit owner override.

### 7.4 Canonical Artifacts and Profile

- Preserve page `spec.md`, `plan.md`, and `journal.md` as canonical.
- Preserve `me/profile.md` as the canonical stable cross-project owner context.
- Require every completed interview to report whether profile-worthy facts were found.
- Support exact profile candidates, pending policy/approval, declined, not applicable, and safely written outcomes.
- Permit profile changes only through a narrow preserved update path.
- Prohibit profile deletion and whole-file replacement during the guarded process.

### 7.5 Structural Validation and Bounded Correction

- Validate path, stage, required headings, duplicate headings, protected-content preservation, and applicable profile disposition.
- Reject invalid candidates before canonical acceptance.
- Return deterministic structural feedback.
- Permit at most one automatic correction attempt for the same stage outcome.
- Stop automatic advancement after correction exhaustion.

### 7.6 Owner Control

- Honor explicit skip, redo, stop, and resume directions.
- Never reinterpret an owner override as model failure.
- Preserve the current approval subsystem and active owner-editable policy files.
- Keep profile approval policy outside hardcoded stage orchestration.

### 7.7 State and Evidence

- Persist the minimum state necessary to keep one process and one active stage coherent across turns and gateway restart.
- Record minimal sanitized events sufficient to prove entry, stage, attempt, validation, write, profile disposition, override, pause, and completion.
- Keep owner text and artifact bodies out of default process diagnostics.

### 7.8 Verification

- Add unit, integration, web-client, gateway, artifact, profile, failure, restart, and regression tests.
- Add an end-to-end test proving the CTA starts the process without a model `process_start` call.
- Run real Ollama proof scenarios with the target ≤12B model before V2 acceptance.
- Retain the 31B result as a comparison tier, not as the portability proof.
- Run matched pre-guardrail-baseline versus guarded-candidate BrainDrive Models and OpenRouter comparisons before accepting the built-in behavior.

## 8. Out of Scope

- General-purpose process configuration or more than one registered process.
- Guarded ad hoc chat updates to active, non-empty page artifacts unless separately started through a future structured refresh action.
- Root-agent routing into page guardrails.
- Automatic stale-page detection based on semantic model judgment.
- A new owner-facing control for refreshing an existing page in V2 V1.
- Universal policy for whether owner-stated profile facts require conversational confirmation.
- Automated profile propagation across multiple pages.
- To-do execution, external tool execution, reminders, outreach, scheduling, or app generation.
- New public provider-management behavior, credentials, credits, model selection, Ollama pull/delete behavior, or provider URLs.
- V1 state migration, V1 trace import, or compatibility with an in-progress V1 run.
- Detailed implementation modules, class names, database schema, task ordering, or milestone breakdown.

## 9. Stakeholders and Actors

| Actor | Relationship to V2 |
|---|---|
| BrainDrive owner using Ollama | Starts the process, answers stage questions, reviews proposed memory, exercises overrides, and owns all resulting artifacts |
| Owner using BrainDrive Models or BYOK OpenRouter | Receives the same process guarantees after structural entry, without provider, credential, credits, conversational-quality, or cost regressions beyond the accepted bar |
| Gemma-class ≤12B model | Primary capability proof target; supplies judgment and text/tool outcomes inside code-owned stages |
| Larger local model | Comparison tier and diagnostic reference, but cannot substitute for the ≤12B/16 GB proof |
| Web client | Presents the existing CTA and attaches authenticated structural process intent |
| Gateway/runtime | Validates entry, selects the stage, assembles context, enforces protected writes, validates outcomes, and advances or stops |
| Starter-pack instructions | Authoritative source for behavior, questions, qualitative criteria, profile policy, page boundaries, and owner customization |
| Memory tools | Apply authorized reads and narrowly validated mutations to canonical owner memory |
| Existing approval subsystem | Remains authoritative for tool approval decisions; V2 does not weaken or bypass it |
| QA/runtime harness | Proves real CTA entry, writes, correction, profile routing, persistence, and regressions |
| Local-model evaluation harness | Runs matched ≤12B and comparison scenarios and retains model/configuration provenance |
| Dave W | Owns product behavior, local-model trust judgment, and the final efficacy decision |
| Dave J | Owns runtime boundary review, simplicity constraint, and engineering acceptance |
| Security/privacy reviewer | Verifies metadata trust, authorization, redaction, file preservation, and no new egress |

## 10. User Stories

### US-1 — Deterministic Process Start — Confirmed by D4 Direction and V1 Evidence

As an owner using any supported provider, I want the existing page CTA to start process assistance deterministically so that the model does not have to remember to request the guardrails intended to help it.

**Acceptance notes:** Maps to FR-001, FR-002, FR-003, FR-012, NFR-001, AC-001 through AC-004.

```gherkin
Given a supported provider is selected and an empty supported page is open
When the owner selects the existing process CTA
Then the gateway starts the interview stage before the first stage model call
And the model is not required to call process_start
And guarded state and entry evidence exist
```

### US-2 — Stage-Guided Smaller Model — Confirmed by D4

As an owner, I want a smaller local model to receive only the active stage's instructions and necessary context so that it can focus on the current job and complete the process in order.

**Acceptance notes:** Maps to FR-004 through FR-006, NFR-001, NFR-006, AC-005 through AC-008.

### US-3 — Correct Canonical Writes — Confirmed by D4

As an owner, I want goals, plan, and journal outcomes written only to their canonical homes and only at the correct stage so that my memory remains trustworthy and editable.

**Acceptance notes:** Maps to FR-007 through FR-009, FR-012, FR-013, NFR-003, AC-009 through AC-014.

### US-4 — Profile Facts Are Never Silently Forgotten — Confirmed by Current Product Process

As an owner, I want stable cross-project facts surfaced and routed to my profile—or explicitly marked as not applicable, awaiting approval, or declined—so that a smaller model cannot silently omit context that should personalize BrainDrive.

**Acceptance notes:** Maps to FR-010, FR-011, NFR-003, NFR-006, AC-015 through AC-019.

```gherkin
Given an interview contains clear owner-provided stable cross-project facts
When the interview reaches playback and specification completion
Then the process records the exact profile candidates
And resolves each candidate according to the active text and approval policy
And does not complete with an absent profile disposition
```

### US-5 — Bounded Structural Recovery — Confirmed by D4

As an owner, I want a structurally incomplete artifact to receive one concrete correction opportunity so that BrainDrive does not silently accept broken memory or loop indefinitely.

**Acceptance notes:** Maps to FR-013, FR-014, NFR-002, AC-020 through AC-023.

### US-6 — Owner Direction Wins — Confirmed by D4

As an owner, I want to skip, redo, stop, or resume the process so that code-owned orchestration remains a guarantee rather than a constraint.

**Acceptance notes:** Maps to FR-015, NFR-006, AC-024 and AC-025.

### US-7 — Resume Without Repeating Accepted Work — Confirmed by D4

As an owner, I want an interrupted guarded process to continue at its unresolved stage so that accepted owner work is not regenerated or lost.

**Acceptance notes:** Maps to FR-016, NFR-003, NFR-007, AC-026 through AC-028.

### US-8 — Inspectable Proof — Confirmed by D4

As a builder or QA operator, I want evidence that distinguishes CTA entry, stage execution, model attempts, validation, profile disposition, and completion so that local-model claims cannot be made from an unguarded run.

**Acceptance notes:** Maps to FR-017, NFR-004, NFR-009, AC-029 through AC-031.

### US-9 — Provider-Independent Process and Ordinary Chat Compatibility — Confirmed Product Boundary

As an owner, I want the same process guarantees regardless of whether I use Ollama, BrainDrive Models, or BYOK OpenRouter, while ordinary non-process conversations remain unchanged.

**Acceptance notes:** Maps to FR-003, FR-018, NFR-008, NFR-010, NFR-015, AC-032 through AC-035, and AC-041.

## 11. Use Cases and Operational Scenarios

### UC-1 — First-Use CTA Starts Guarded Interview

- **Preconditions:** Effective provider ID is supported; active page is supported and shows its empty-state CTA; no active guarded run exists.
- **Trigger:** Owner selects the CTA.
- **Main flow:** Client sends normal CTA text plus structural process intent; gateway validates it; gateway creates the run and activates interview; runtime loads current page `AGENT.md`, `run-interview.md`, applicable overlays, profile, and current page artifacts; model begins the interview.
- **Alternate flow:** Owner stops immediately; run is stopped without writing page artifacts.
- **Failure flow:** Invalid metadata does not call the model as a guarded stage and produces a sanitized, recoverable error.
- **Expected final state:** Interview is active or waiting for owner input.
- **User-visible result:** Normal conversation begins without internal process terminology.
- **Operational result:** Entry evidence identifies configured state, provider/model, page, process, conversation, and active interview.

### UC-2 — Multi-Turn Interview With Profile Candidates

- **Preconditions:** Interview active; owner profile and page context were loaded.
- **Trigger:** Owner supplies goals, constraints, and stable cross-project facts over several turns.
- **Main flow:** Stage remains interview; model asks one useful question at a time according to text; playback includes user stories and exact profile candidates; owner responds; profile disposition is recorded; specification stage becomes eligible.
- **Alternate flow:** No stable cross-project facts exist; model reports `not_applicable` with no fabricated candidates.
- **Failure flow:** Model tries to complete without profile disposition; outcome is rejected with structural feedback.
- **Expected final state:** Interview accepted with explicit profile disposition.
- **User-visible result:** Owner sees a natural playback, not a schema or internal status.
- **Operational result:** Profile candidate status is present without raw facts in default diagnostics.

### UC-3 — Specification and Plan Written in Order

- **Preconditions:** Interview accepted or explicitly skipped; active text permits progression.
- **Trigger:** Model submits the specification candidate, then the plan candidate.
- **Main flow:** Specification path and structure are validated; accepted specification is persisted; plan stage receives the accepted specification and planning instructions; plan is validated and persisted.
- **Alternate flow:** Owner explicitly skips specification; plan receives an `absent_by_owner_choice` prerequisite.
- **Failure flow:** Plan write before specification acceptance is rejected unless an owner override exists.
- **Expected final state:** Both applicable artifacts accepted in order.
- **User-visible result:** Owner is directed to Your Goals and Your Plan only after successful writes.
- **Operational result:** Artifact paths and digests prove accepted order.

### UC-4 — Profile Write Under Active Policy

- **Preconditions:** Exact owner-provided profile candidates exist; active stage instructions and approval subsystem determine whether the update may proceed.
- **Trigger:** Profile update becomes permitted.
- **Main flow:** Runtime permits a narrowly scoped profile edit; validates canonical path, preservation, exact candidate relationship, and resulting digest; delegates through normal approval/authorization; records written disposition.
- **Alternate flow:** Approval is required and pending; process waits without blocking already-valid page artifact drafting.
- **Failure flow:** Owner declines, tool approval is denied, target changed, or model attempts whole-file replacement; no profile mutation is accepted.
- **Expected final state:** `written`, `declined`, or `awaiting_approval`, according to actual outcome.
- **User-visible result:** Owner receives only accurate claims about what was proposed or written.
- **Operational result:** No raw profile content appears in default process diagnostics.

### UC-5 — Invalid Artifact Corrected Once

- **Preconditions:** Active specification or plan stage.
- **Trigger:** Candidate is wrong-path, missing required structure, duplicated, or destructive.
- **Main flow:** Candidate is not accepted; deterministic codes are returned to the same stage; automatic attempt counter increments before one correction call; corrected candidate passes and is persisted.
- **Failure flow:** Second candidate is invalid; stage stops in `NEEDS_OWNER_ACTION`.
- **Expected final state:** Accepted after at most two attempts, or waiting for owner action.
- **User-visible result:** Natural correction or a clear weakness/recovery choice.
- **Operational result:** Both attempt results and final state are attributable without content bodies.

### UC-6 — Provider Interruption and Resume

- **Preconditions:** Guarded run active; accepted prior artifacts may exist.
- **Trigger:** The active provider disconnects, times out, or returns an unrecoverable provider error.
- **Main flow:** Runtime preserves accepted state and marks current stage paused; owner retries after availability returns; runtime validates stored references and resumes unresolved work.
- **Failure flow:** Canonical artifact changed while paused; owner edit wins and automatic resume stops for reconciliation.
- **Expected final state:** Resumed active stage or `NEEDS_OWNER_ACTION`.
- **User-visible result:** Existing provider-error recovery remains understandable; accepted work is not repeated.
- **Operational result:** Pause and resume reason recorded.

### UC-7 — Non-CTA Ordinary Conversation

- **Preconditions:** A supported provider and page are selected; no active guarded run.
- **Trigger:** Owner types an ordinary message instead of selecting the structural CTA.
- **Main flow:** Existing ordinary conversation behavior runs.
- **Alternate flow:** Future structured refresh action is not part of V2 V1.
- **Failure flow:** If the ordinary model attempts to mutate protected process artifacts on a recognized first-use starter page, the mutation fails closed with a recoverable process-start-required result.
- **Expected final state:** No guarded run unless the structural signal is present.
- **User-visible result:** Ordinary questions remain possible.
- **Operational result:** No false guarded-run evidence.

### UC-8 — Unsupported Provider

- **Preconditions:** Effective provider is unknown/unclassified.
- **Trigger:** Owner uses the page CTA or ordinary chat.
- **Main flow:** Existing unguarded path remains authoritative; V2 creates no state, validation, retry, or guarded diagnostics.
- **Expected final state:** No V2 run.
- **User-visible result:** Existing behavior.
- **Operational result:** A sanitized bypass reason may be logged through existing audit without a process trace.

### UC-9 — Same Process Across Supported Providers

- **Preconditions:** The same supported page, starter-pack revision, and owner scenario are used with Ollama, BrainDrive Models, and OpenRouter.
- **Trigger:** Owner selects the process CTA for each provider.
- **Main flow:** Each request enters the same fixed controller, stages, validation, profile, correction, override, state, and evidence contracts; only the existing provider adapter/model call differs.
- **Failure flow:** Provider-specific transport/auth/credits errors retain their existing mapping and do not alter process semantics.
- **Expected final state:** Structurally equivalent guarded outcomes or attributable provider/model failures.
- **User-visible result:** BrainDrive process behavior remains consistent across model choices.
- **Operational result:** Comparative evidence reports provider/model, latency, calls, tokens/cost when available, and structural results.

## 12. Current Behavior

### 12.1 Verified `dev` Baseline

- The web client has empty-state CTAs for the supported starter pages.
- CTA clicks call the same `append` path as ordinary chat and currently carry no process-specific distinction.
- `sendMessage` transmits optional metadata in the existing `POST /message` body.
- The gateway extracts project identity from metadata, builds project context, exposes normal tools, and calls the ordinary agent loop.
- Canonical starter-pack files contain the interview/specification/plan/journal/profile behavior.
- Ollama, BrainDrive Models, and OpenRouter share the OpenAI-compatible adapter abstraction.
- Existing memory tools and approval behavior protect mutations but do not enforce process stage order.

### 12.2 Verified V1 Branch Behavior

- Scope/provider/page eligibility alone does not enter guardrails.
- An eligible no-state request receives `process_start` as an additional tool.
- The gateway enters guardrails only after the model calls that tool successfully.
- The pre-start executor delegates ordinary reads and writes.
- Scripted integration tests define “no start” as a correct unguarded result.
- A resumable V1 state enters directly.
- Once started, the V1 controller includes fixed stages, validation, one retry, state, trace, and recovery.
- V1 stage validation rejects `me/profile.md` as a noncanonical stage artifact.

### 12.3 Verified Real-Model Behavior

- The tested Gemma 31B and Gemma 12B requests were `ollama`, scope `all`, and page-eligible.
- All recorded activations remained `process_start_available` with `process_start_requested: false`.
- No guarded process state or trace was created.
- The 31B model read more of the process text and completed more behavior unaided.
- The 12B Relationships model read only limited instructions, wrote noncanonical spec/plan content, omitted mandatory capability-boundary content, and did not attempt profile routing.

### 12.4 Strong Inference

The V1 controller may improve smaller-model behavior once entered, but the available real runs cannot support that conclusion because entry never occurred.

### 12.5 Assumption

A structural CTA signal plus stage-scoped context will materially improve the target ≤12B model. This must be proven before V2 V1 acceptance; it is not treated as a verified fact.

## 13. Target Behavior

### 13.1 Availability and Entry

V2 V1 activates when all of the following are true:

1. Effective stable provider identity is `ollama`, `braindrive-models`, or `openrouter`.
2. Active project is one of `career`, `finance`, `fitness`, `relationships`, or `new-project`.
3. The request contains an authenticated structural intent generated by the existing page CTA, or the conversation has a valid active V2 run.
4. Required canonical process files are present and readable.

No configuration or runtime switch participates in eligibility.

The CTA signal is product metadata, not natural-language classification. The displayed text remains owner-facing and editable without becoming the security boundary.

### 13.2 Fixed Process

The runtime supports one process:

```text
interview
  → specification + profile disposition
  → plan
  → journal handoff
  → completed
```

An owner override may skip, redo, stop, or resume. Journal handoff may complete without writing an entry when the current `run-journal.md` says no journal-worthy content exists.

### 13.3 Stage Context

Every stage receives:

- system safety and authorization context;
- current owner message and stage-associated prior owner/model turns needed for coherence;
- page `AGENT.md` and applicable owner overlay;
- the active procedure file and applicable procedure overlay;
- `me/profile.md` where the stage contract permits it;
- current canonical page artifacts explicitly required by the stage;
- accepted prerequisite status, including explicit owner-skip status.

The stage does not receive unrelated page files, downstream procedures, frozen test personas, or hidden qualitative policy in code.

### 13.4 Interview and Profile Behavior

The interview remains active across owner turns until the active procedure's playback/done criteria are reached. Before interview acceptance, the model must submit:

- structural interview outcome;
- whether stable cross-project profile facts were present;
- exact candidates when present;
- a profile disposition for each candidate.

Allowed dispositions are behaviorally:

- `not_applicable`: no eligible stable cross-project fact was provided;
- `proposed`: exact candidate was surfaced to the owner;
- `awaiting_approval`: active instructions or approval state require owner action;
- `declined`: owner declined or did not authorize the candidate;
- `written`: the exact candidate was safely applied and verified.

The exact field names are a build-plan decision. The runtime must not invent a profile candidate or silently convert a page-specific fact into a profile fact.

### 13.5 Artifact Writes

- Interview conversation does not directly accept a plan.
- Specification stage writes only the active page `spec.md` plus the separately validated profile operation when applicable.
- Plan stage writes only the active page `plan.md`.
- Journal handoff writes only the active page `journal.md` when eligible.
- Profile mutation is never treated as the specification artifact and never permits whole-file replacement.
- Canonical writes pass existing authentication, authorization, and approval behavior after V2 validation.

### 13.6 Validation and Correction

Validation is deterministic and structural. It checks:

- active process/page/stage;
- canonical path;
- required stable sections exactly once;
- prerequisite state;
- write type and preservation;
- profile candidate/disposition coherence;
- journal eligibility;
- duplicate/replayed operation identity.

The first invalid candidate may receive one automatic correction attempt with exact structural codes. A second invalid result stops automatic work.

### 13.7 State and Recovery

V2 persists only what is necessary to:

- identify one active process per conversation/page;
- identify active stage and stage revision;
- record attempt count;
- record accepted artifact references/digests;
- record profile dispositions without raw profile fact text in default diagnostics;
- record owner override and terminal/recoverable status;
- reject stale concurrent results;
- resume after gateway or provider interruption.

Owner artifacts remain the source of truth. Process state never overrides a newer owner edit.

### 13.8 User Experience

The owner experiences the existing page CTA and normal conversation. Internal process names and control tools do not appear in chat. The UI may show existing thinking/tool/approval/error states, but V2 V1 adds no progress wizard.

### 13.9 Completion

A run completes only when:

- interview is accepted or skipped by owner;
- specification is accepted or skipped by owner;
- every profile candidate has an explicit disposition;
- plan is accepted or skipped by owner;
- journal handoff is resolved, with or without a valid entry;
- no protected mutation is pending or ambiguous.

## 14. Functional Requirements

### FR-001 — Unconditional Eligible Activation

- **Priority:** Must.
- **Requirement:** Every structurally initiated eligible process request shall enter V2; activation shall not depend on a runtime switch, environment variable, feature flag, settings control, provider scope mode, or model choice.
- **Rationale:** Guardrails are part of the supported process contract, not optional infrastructure that can leave eligible models on an unguarded path.
- **Preconditions:** Provider, page, structural intent, process files, and current state are resolved.
- **Required behavior:** Enter V2 whenever the fixed eligibility conditions pass. Keep ordinary behavior only for requests that are genuinely outside those conditions.
- **Expected result:** Every supported provider receives the same built-in guarded process, with no disabled branch or dormant activation code.
- **Error behavior:** An eligibility validation failure follows the named safe ineligible/error behavior; it must not be reinterpreted as an operator-disabled mode.
- **Acceptance criteria:** AC-001, AC-032, AC-035.

### FR-002 — Structural CTA Entry

- **Priority:** Must.
- **Requirement:** Selecting the existing process CTA on an eligible page shall attach a structural start signal that the gateway validates and consumes before the first guarded model call.
- **Rationale:** The target model cannot be responsible for activating its own assistance.
- **Preconditions:** A supported provider and supported empty page are active.
- **Required behavior:** Bind the signal to the authenticated request, active project, conversation, and single registered process; do not infer it from display text.
- **Expected result:** Interview starts without `process_start` model behavior or a discovery model call.
- **Error behavior:** Missing or invalid signal does not create a guarded run; malformed or cross-page signal fails safely.
- **Acceptance criteria:** AC-002 through AC-004.

### FR-003 — Fixed Provider and Page Boundary

- **Priority:** Must.
- **Requirement:** V2 shall enter for stable provider IDs `ollama`, `braindrive-models`, and `openrouter` on `career`, `finance`, `fitness`, `relationships`, or `new-project` with required process files and valid start/resume state.
- **Rationale:** A fixed supported-provider and page boundary prevents semantic scope creep while avoiding provider-specific process behavior.
- **Preconditions:** Effective provider and page are resolved.
- **Required behavior:** Use stable provider ID and canonical page ID, never model name, label, URL substring, or untrusted display text. Apply the same entry, stage, validation, correction, protected-write, profile, and completion semantics to all supported providers.
- **Expected result:** Supported providers receive one shared process contract; unknown providers and unsupported pages use existing behavior with no V2 state or validation.
- **Error behavior:** Unknown providers/pages remain unguarded and diagnostically attributable.
- **Acceptance criteria:** AC-003, AC-032 through AC-034.

### FR-004 — Canonical Text-Defined Behavior

- **Priority:** Must.
- **Requirement:** Stage questions, tone, qualitative criteria, profile policy, and domain behavior shall be loaded from canonical managed text plus applicable owner overlays.
- **Rationale:** Judgment remains owner-readable and changeable.
- **Preconditions:** Active stage and page are known.
- **Required behavior:** Read managed base first and overlay second; preserve overlays byte-for-byte; re-read instructions for a new run and define safe behavior for mid-run changes.
- **Expected result:** Behavior-only text edits require no TypeScript change.
- **Error behavior:** Missing required text stops the stage with the named missing reference; no hidden prompt fallback.
- **Acceptance criteria:** AC-005, AC-006, AC-031.

### FR-005 — Stage-Scoped Context

- **Priority:** Must.
- **Requirement:** Each guarded call shall receive only safety context, active owner direction, active stage instructions, applicable overlays, and explicitly required owner artifacts.
- **Rationale:** Context narrowing is the primary assistance provided to smaller models.
- **Preconditions:** Active stage and prerequisites are known.
- **Required behavior:** Exclude downstream procedures, unrelated projects, irrelevant history, and frozen evaluation material.
- **Expected result:** Context evidence identifies sources/digests without recording bodies by default.
- **Error behavior:** Missing required prerequisite stops before the model call unless explicitly absent by owner choice.
- **Acceptance criteria:** AC-005 through AC-007.

### FR-006 — Deterministic Stage Sequence

- **Priority:** Must.
- **Requirement:** In the absence of an owner override, V2 shall execute interview → specification/profile disposition → plan → journal handoff.
- **Rationale:** Sequence is the core code-owned guarantee.
- **Preconditions:** Active guarded run.
- **Required behavior:** Keep a conversational stage active across turns; advance only after durable acceptance.
- **Expected result:** No unrequested stage skip or out-of-order accepted write.
- **Error behavior:** Downstream outcomes are rejected with a recoverable stage-order code.
- **Acceptance criteria:** AC-007 through AC-010.

### FR-007 — Canonical Specification

- **Priority:** Must.
- **Requirement:** The specification stage shall create or update only the active page `spec.md` according to the active procedure and preservation contract.
- **Rationale:** Your Goals must remain canonical, structured, and owner-owned.
- **Preconditions:** Interview accepted or skipped by owner.
- **Required behavior:** Validate canonical path, required headings, duplicates, status/date/changelog rules, and unrelated-content preservation.
- **Expected result:** Accepted specification is structurally complete and durably written.
- **Error behavior:** Invalid or destructive candidate remains unaccepted.
- **Acceptance criteria:** AC-009 through AC-012.

### FR-008 — Canonical Plan

- **Priority:** Must.
- **Requirement:** The plan stage shall create or update only the active page `plan.md` after specification resolution.
- **Rationale:** Planning must follow alignment unless the owner explicitly changes the order.
- **Preconditions:** Specification accepted or absent by owner choice.
- **Required behavior:** Load `run-planning.md`, accepted spec status, profile context, and existing plan; validate canonical structure and preservation.
- **Expected result:** Accepted plan reflects the resolved goal context and is durably written.
- **Error behavior:** Plan-before-spec without override is rejected.
- **Acceptance criteria:** AC-010 through AC-013.

### FR-009 — Journal Handoff Integrity

- **Priority:** Must.
- **Requirement:** V2 shall resolve journal handoff without fabricating an initial-session entry.
- **Rationale:** Process completion must not create false owner history.
- **Preconditions:** Plan resolved.
- **Required behavior:** Follow active `run-journal.md`; write only journal-worthy owner content; prevent duplicate entry.
- **Expected result:** Handoff is either complete-with-no-entry or accepted-with-one-valid-entry.
- **Error behavior:** Synthetic, empty, or duplicate entry is rejected.
- **Acceptance criteria:** AC-013, AC-014.

### FR-010 — Mandatory Profile Consideration

- **Priority:** Must.
- **Requirement:** Every completed interview shall explicitly state whether eligible stable cross-project profile facts were present and identify exact candidates when present.
- **Rationale:** Smaller models must not silently omit profile routing.
- **Preconditions:** Interview reaches playback/completion.
- **Required behavior:** Distinguish stable cross-project facts from page goals, one-off details, inferences, secrets, and unsupported claims.
- **Expected result:** Profile disposition is never absent at interview completion.
- **Error behavior:** Missing, inconsistent, or fabricated disposition rejects completion and receives structural feedback.
- **Acceptance criteria:** AC-015 through AC-017.

### FR-011 — Policy-Compatible Safe Profile Update

- **Priority:** Must.
- **Requirement:** V2 shall support safe profile proposal and update outcomes without hardcoding one universal conversational-approval policy.
- **Rationale:** Profile correctness is required now; the team's approval-policy decision must remain changeable.
- **Preconditions:** Exact owner-provided profile candidates exist.
- **Required behavior:** Active instructions and existing approval behavior determine whether a candidate is proposed, awaiting approval, declined, or written; only targeted preserved edits to `me/profile.md` are permitted.
- **Expected result:** Actual profile state and owner-facing claim match.
- **Error behavior:** Delete, whole-file replacement, unapproved required-consent write, stale-target write, or candidate mismatch is rejected.
- **Acceptance criteria:** AC-016 through AC-019.

### FR-012 — Protected Write Boundary

- **Priority:** Must.
- **Requirement:** After valid structured process entry, and on a recognized first-use starter page, ordinary tools shall not bypass stage validation for `spec.md`, `plan.md`, `journal.md`, or the guarded profile operation.
- **Rationale:** A parallel unguarded write path nullifies the guardrails.
- **Preconditions:** V2 start signal accepted, run active, or a supported-provider request targets a supported page whose canonical artifacts match the recognized first-use starter state.
- **Required behavior:** Intercept protected mutations before delegation; route them through active-stage validation, or reject them with process-start-required when no guarded run is active.
- **Expected result:** All accepted process writes are attributable to a guarded stage.
- **Error behavior:** Wrong-stage or ordinary-path mutation returns a recoverable structural error with no file change.
- **Acceptance criteria:** AC-004, AC-011, AC-018, AC-020.

### FR-013 — Deterministic Validation

- **Priority:** Must.
- **Requirement:** V2 shall validate structural outcome, write placement, preservation, prerequisites, and profile-disposition coherence before acceptance.
- **Rationale:** Structural correctness belongs in code.
- **Preconditions:** Model reports stage completion or attempts a protected mutation.
- **Required behavior:** Return stable machine-readable codes and a concise model-facing explanation; never grade empathy or prose quality.
- **Expected result:** Only structurally valid outcomes advance.
- **Error behavior:** Prior canonical owner content remains intact.
- **Acceptance criteria:** AC-011, AC-017, AC-020 through AC-022.

### FR-014 — One Automatic Correction

- **Priority:** Must.
- **Requirement:** The first deterministic failure for a stage outcome may trigger exactly one automatic correction attempt; the second failure shall stop automatic advancement.
- **Rationale:** Bounded recovery provides value without loops.
- **Preconditions:** FR-013 rejects the first candidate and owner has not redirected.
- **Required behavior:** Persist attempt count before the correction call and retain the same stage/revision identity.
- **Expected result:** Automatic attempts never exceed two.
- **Error behavior:** Exhaustion ends in `NEEDS_OWNER_ACTION` with recovery choices.
- **Acceptance criteria:** AC-020 through AC-023.

### FR-015 — Owner Override Supremacy

- **Priority:** Must.
- **Requirement:** Explicit owner direction shall be able to skip, redo, stop, or resume the active process.
- **Rationale:** Guardrails are guarantees, not constraints.
- **Preconditions:** Direction is explicit enough to determine the requested control action.
- **Required behavior:** Apply normalized override before default progression and update prerequisites.
- **Expected result:** Owner direction is obeyed without being counted as model failure.
- **Error behavior:** Ambiguous direction remains conversational and does not mutate process state.
- **Acceptance criteria:** AC-024, AC-025.

### FR-016 — Minimal Durable Resume

- **Priority:** Must.
- **Requirement:** V2 shall persist enough state to resume the first unresolved stage after gateway/provider interruption without regenerating accepted artifacts.
- **Rationale:** Multi-turn guarded processes must survive common interruptions.
- **Preconditions:** A run has started.
- **Required behavior:** Persist stage/revision/attempt, accepted artifact references, profile disposition status, and terminal/recoverable outcome; revalidate digests on resume.
- **Expected result:** Accepted work is reused and owner edits win.
- **Error behavior:** Corrupt, unsupported, or conflicting state is preserved and stops for owner action rather than overwritten.
- **Acceptance criteria:** AC-026 through AC-028.

### FR-017 — Minimal Process Evidence

- **Priority:** Must.
- **Requirement:** V2 shall emit sanitized evidence for entry, stage activation, validation, correction, protected write, profile disposition, override, pause/resume, and completion.
- **Rationale:** A guarded efficacy claim requires proof that guardrails actually ran.
- **Preconditions:** Valid run starts.
- **Required behavior:** Correlate process, conversation, page, provider/model, stage, attempt, validator codes, artifact digests, and terminal state; omit bodies and secrets.
- **Expected result:** Operators can distinguish guarded, bypassed, failed-entry, and completed runs.
- **Error behavior:** Diagnostic failure is surfaced in test evidence and does not falsely report guarded success.
- **Acceptance criteria:** AC-029 through AC-031.

### FR-018 — Provider and Ineligible-Path Compatibility

- **Priority:** Must.
- **Requirement:** Unknown providers, root-agent conversations, unsupported pages, and ordinary non-process requests shall retain existing behavior and contracts; supported providers shall retain their provider-specific execution contracts while always using the same guarded process semantics for eligible requests.
- **Rationale:** V2 must strengthen the process without coupling it to one inference provider or destabilizing provider integrations.
- **Preconditions:** A request is ineligible, or a supported provider executes an eligible guarded request.
- **Required behavior:** When ineligible, create no V2 state, stage calls, corrections, or protected process diagnostics. For all requests, preserve provider credentials, credits, model selection, approvals, API/SSE semantics, and memory behavior.
- **Expected result:** Ordinary ineligible paths remain unchanged; supported providers differ only where their existing adapter and model execution require it.
- **Error behavior:** Bypass reason may be sanitized but must not affect the response.
- **Acceptance criteria:** AC-032 through AC-035, AC-041.

## 15. Non-Functional Requirements

| ID | Priority | Area | Measurable Requirement |
|---|---|---|---|
| NFR-001 | Must | Reliability | Every valid CTA-started eligible request enters V2 before its first stage model call; zero such requests may remain on the ordinary path. |
| NFR-002 | Must | Bounded execution | No stage outcome may cause more than two automatic model attempts, including across restart. |
| NFR-003 | Must | Data integrity | V2 must not delete, truncate, wholly replace, duplicate, or silently overwrite unrelated content in `spec.md`, `plan.md`, `journal.md`, `me/profile.md`, or owner overlays. |
| NFR-004 | Must | Privacy | Default V2 state and diagnostics contain no owner messages, artifact bodies, profile fact text, provider payloads, credentials, tokens, or secret values. |
| NFR-005 | Must | Simplicity | V2 supports one process and one shared supported-provider contract with deterministic validators and one correction budget; adding a second process, provider-specific semantic fork, model judge, DSL, or dashboard requires a separate accepted specification. |
| NFR-006 | Must | Owner editability | A change limited to questions, tone, qualitative done criteria, or profile approval behavior in canonical text must not require TypeScript changes. |
| NFR-007 | Must | Recovery | Gateway/provider interruption must not invalidate accepted artifacts or reset the correction counter; a conflicting owner edit must win over stored process state. |
| NFR-008 | Must | Compatibility | Ineligible flows retain existing request, SSE, provider, credential, credits, authorization, approval, and memory contracts with no V2 model call or write overhead; guarded cloud flows retain those contracts while adding only the shared process controls. |
| NFR-009 | Must | Auditability | Each guarded transition is attributable to one run, conversation, page, process, stage/revision, attempt, provider/model, validator result, artifact digest where applicable, and timestamp. |
| NFR-010 | Must | Usability and trust | Owners see normal BrainDrive language, accurate write claims, existing approval behavior, and clear recovery choices; internal process controls are never displayed as owner instructions. |
| NFR-011 | Must | Portability | At least one model at or below the 12B class completes the live acceptance set within a measured 16 GB-class total system-memory envelope, including operating system and BrainDrive headroom. |
| NFR-012 | Should | Performance | A guarded stage that does not require a correction adds no discovery-model call; process entry itself is code-only. Comparative latency, token use, and provider cost where applicable are reported by provider rather than hidden. |
| NFR-013 | Must | Security | Structural intent and process state never grant new file, provider, or tool permissions and never bypass existing authentication, authorization, approval, or path-containment checks. |
| NFR-014 | Must | Test validity | Scripted/fake-provider tests prove mechanics only; V2 acceptance requires real ≤12B Ollama efficacy evidence plus matched cloud no-regression evidence and must reject any run without verified guarded entry. |
| NFR-015 | Must | Cloud no-regression | Matched guarded BrainDrive Models and OpenRouter comparisons have zero new hard-gate failures, no decrease in structural pass rate, remain within the ratified latency/token/cost bounds, and pass human conversational-quality review. |

## 16. Business Rules and Invariants

1. **Entry ownership:** A valid CTA signal or valid resumable state—not a model decision—starts V2.
2. **Provider-independent rule:** Stable provider IDs `ollama`, `braindrive-models`, and `openrouter` enter the same V2 process for every eligible request.
3. **No-switch rule:** Eligible process guardrails are built in and cannot be disabled by runtime configuration, environment variable, feature flag, provider scope, or settings UI.
4. **Single-process rule:** V2 V1 knows exactly one interview/specification/plan/journal-handoff process.
5. **Text-judgment rule:** Questions, voice, qualitative criteria, and profile policy remain in canonical text.
6. **Code-orchestration rule:** Entry, sequence, permitted writes, structural validation, attempt bound, and explicit outcome resolution belong to runtime control.
7. **One active stage:** A run has no more than one active stage.
8. **Acceptance before advance:** A stage advances only after durable acceptance or explicit owner override.
9. **Protected-write rule:** No process artifact is accepted through an ordinary bypass after structured entry.
10. **Canonical-placement rule:** Page goals, plan, journal, and profile facts remain in their established memory homes.
11. **Profile-accounting rule:** A completed interview always has an explicit profile disposition, including `not_applicable`.
12. **No-fabrication rule:** V2 never invents profile facts, owner approval, journal history, or artifact success.
13. **Profile-preservation rule:** Guarded profile behavior never deletes or wholly replaces `me/profile.md`.
14. **Owner-policy rule:** Runtime does not impose a universal conversational profile-approval rule.
15. **Owner-override rule:** Explicit owner direction wins over default sequence.
16. **Attempt rule:** One initial automatic attempt plus at most one automatic correction per stage outcome.
17. **Owner-edit-wins rule:** A newer owner artifact edit invalidates stale candidate/state assumptions.
18. **No hidden behavior fallback:** Missing required process instructions stop the stage rather than substituting code-owned prose.
19. **No false evidence:** A bypassed or failed-entry run cannot be counted as guarded.
20. **No test contamination:** Frozen personas, expected answers, judge rubrics, and fixture-specific facts never enter runtime stage context.
21. **Provider-contract isolation:** V2 cannot change provider credentials, credits, selection, adapter behavior, routing, or existing authorization contracts.
22. **No new authority:** Structural metadata identifies intent; it grants no permission to mutate files.
23. **Same-process rule:** Provider identity may select existing model execution plumbing and diagnostic labels, but never different stage order, profile obligations, validators, retry bounds, protected writes, or completion rules.

## 17. Domain Model

### 17.1 Structural Process Intent

- **Purpose:** Express the owner's explicit selection of the existing page process CTA.
- **Identity:** Bound to request, active project, and registered process; exact field naming is deferred to build planning.
- **Important properties:** action kind, process kind/version, page identity, client origin.
- **Owner:** Product client produces it; gateway validates it.
- **Lifecycle:** Exists for the initiating request only and is consumed once.
- **Valid state:** Authenticated, recognized action, supported active page, eligible provider/scope.
- **Invalid state:** Unknown action, mismatched page, replay for another conversation, unsupported provider, or untrusted standalone text.
- **Persistence:** Intent may be recorded as sanitized entry evidence; raw UI text is not required.

### 17.2 Guarded Run

- **Purpose:** Track one active fixed process for one owner conversation and page.
- **Identity:** Stable run ID plus conversation ID, page ID, and fixed process kind.
- **Important properties:** current stage, stage revision, outcome, provider/model reference, timestamps, diagnostic health.
- **Relationships:** Owns stage outcomes and references canonical artifacts; does not own artifact bodies.
- **Ownership:** Runtime diagnostic/control state; owner artifacts remain owner-owned.
- **Lifecycle:** Created on valid structural entry; active/waiting/paused; completed/stopped/needs-owner-action; retained according to local diagnostic policy.
- **Invalid states:** More than one active stage, more than two automatic attempts, terminal state with pending mutation, or mismatched page/provider identity.
- **Compatibility:** State is schema-versioned and not read as owner memory.

### 17.3 Stage Outcome

- **Purpose:** Represent structural completion of interview, specification, plan, or journal handoff.
- **Identity:** Run ID + stage kind + stage revision.
- **Important properties:** status, attempt count, instruction references/digests, prerequisites, candidate/artifact reference, validator codes, owner override.
- **Lifecycle:** Pending → active/waiting → validating → accepted/skipped/needs-owner-action.
- **Invalid states:** Accepted without required artifact/disposition; attempt above two; downstream accepted with missing unskipped prerequisite.

### 17.4 Canonical Artifact Reference

- **Purpose:** Tie accepted stage state to an existing owner artifact without duplicating its body.
- **Identity:** Canonical memory-relative path and content digest.
- **Important properties:** path, digest, accepted timestamp, stage/revision.
- **Ownership:** Owner owns content; runtime stores only reference metadata.
- **Lifecycle:** Created at acceptance; revalidated on resume; invalidated by conflicting owner edit.

### 17.5 Profile Candidate and Disposition

- **Purpose:** Ensure profile-worthy facts are considered and resolved.
- **Identity:** Stage-local candidate identity; default diagnostics use only count/status/digest, not fact text.
- **Important properties:** exact candidate in model/stage exchange, source owner-message reference, disposition, resulting profile digest if written.
- **Relationships:** Belongs to interview/specification outcome; may cause a separately validated profile edit.
- **Ownership:** Fact content is owner data; policy comes from canonical instructions and approval behavior.
- **Lifecycle:** Identified → proposed/awaiting approval → written or declined; or interview reports not applicable.
- **Invalid states:** Written without matching candidate; invented candidate; missing disposition; claimed written with unchanged/mismatched artifact.

### 17.6 Owner Override

- **Purpose:** Represent explicit skip, redo, stop, or resume.
- **Identity:** Run ID + normalized category + stage revision.
- **Important properties:** category, target stage when applicable, owner-message reference.
- **Ownership:** Owner direction is authoritative.
- **Persistence:** Store normalized category and reference, not raw owner text, in default process state.

## 18. State Model

### 18.1 Run Transitions

| Current State | Event | Conditions | Next State | Side Effects |
|---|---|---|---|---|
| `IDLE` | CTA intent accepted | Supported provider/page, required files | `INTERVIEW_ACTIVE` | Create run; record entry; assemble interview context |
| `INTERVIEW_ACTIVE` | Model asks owner question | Stage incomplete | `INTERVIEW_WAITING_OWNER` | Persist active stage; end request normally |
| `INTERVIEW_WAITING_OWNER` | Owner responds | State valid | `INTERVIEW_ACTIVE` | Reassemble stage context with relevant stage turns |
| `INTERVIEW_ACTIVE` | Outcome submitted | Playback/done contract and profile disposition present | `VALIDATING` | Validate structural interview outcome |
| `VALIDATING` | Interview passes | First or correction attempt | `SPECIFICATION_ACTIVE` | Persist accepted interview/profile disposition |
| `SPECIFICATION_ACTIVE` | Specification candidate submitted | Interview accepted/skipped | `VALIDATING` | Validate candidate and optional profile operation |
| `VALIDATING` | Specification passes | Candidate durable | `PLAN_ACTIVE` | Persist artifact reference; load planning context |
| `PLAN_ACTIVE` | Plan candidate submitted | Specification accepted/skipped | `VALIDATING` | Validate plan |
| `VALIDATING` | Plan passes | Candidate durable | `JOURNAL_HANDOFF_ACTIVE` | Persist plan reference; load journal handoff rules |
| `JOURNAL_HANDOFF_ACTIVE` | Handoff resolves | Entry eligible or no-entry valid | `COMPLETED` | Persist final state; write entry only if valid |
| Any active/waiting state | Explicit owner skip | Override valid | Next requested stage | Mark skipped-by-owner and adjust prerequisite |
| Any active/waiting state | Explicit owner redo | Target previously resolved | Target stage active, revision +1 | Preserve old accepted history/reference |
| Any active/waiting state | Explicit owner stop | Always | `STOPPED_BY_OWNER` | No further automatic model calls |
| Any active/validating state | Provider/runtime interruption | State persistence succeeds | `PAUSED_RECOVERABLE` | Preserve accepted artifacts and attempt count |
| `PAUSED_RECOVERABLE` | Resume | State/references valid | First unresolved active state | Reassemble fresh context |
| Any validating state | First validation failure | Attempt 1 | `CORRECTION_PENDING` | Persist codes and increment attempt before call |
| `CORRECTION_PENDING` | Correction begins | Owner has not redirected | Prior active stage | Supply deterministic feedback |
| Any validating state | Validation failure after correction | Attempt 2 | `NEEDS_OWNER_ACTION` | Stop automatic advancement; preserve safe state |
| Any nonterminal state | Internal invariant failure | Best-effort safe persistence | `FAILED_INTERNAL` | Sanitized error; no accepted mutation claim |

### 18.2 Profile Substate

| State | Allowed Next States | Meaning |
|---|---|---|
| `UNASSESSED` | `NOT_APPLICABLE`, `PROPOSED` | Interview has not yet resolved profile relevance |
| `NOT_APPLICABLE` | Terminal for current interview revision | No eligible stable cross-project candidate |
| `PROPOSED` | `AWAITING_APPROVAL`, `DECLINED`, `WRITTEN` | Exact candidate was surfaced |
| `AWAITING_APPROVAL` | `DECLINED`, `WRITTEN` | Active instructions/approval require owner action; this may remain an explicit nonblocking disposition when page artifacts and handoff complete |
| `DECLINED` | Terminal for candidate/revision | Owner did not authorize or rejected candidate |
| `WRITTEN` | Terminal for candidate/revision | Matching preserved profile mutation verified |

### 18.3 Forbidden Transitions

- `IDLE` → guarded stage from ordinary model text or model-only `process_start`.
- `INTERVIEW_ACTIVE` → `PLAN_ACTIVE` without specification resolution or explicit override.
- Any stage → `COMPLETED` with profile substate `UNASSESSED`.
- `PROPOSED`/`AWAITING_APPROVAL` → `WRITTEN` without a verified matching profile mutation.
- First validation failure → more than one automatic correction.
- Accepted stage → pending without explicit redo or conflict reconciliation.
- Terminal run → automatic model call.
- Unknown provider or unsupported page → any V2 run state.
- Journal handoff → synthetic journal content.
- Stale candidate → canonical overwrite.

## 19. Data Requirements

| Data | Operation | Source of Truth | Lifetime / Integrity | Sensitivity / Redaction |
|---|---|---|---|---|
| Structural process intent | Read/validate/consume | Authenticated client request metadata | Request-scoped; single-use | Low sensitivity; do not trust without page/provider validation |
| Guarded run state | Create/update/read | Local V2 state store selected in build plan | Durable across gateway restart; schema-versioned; corrupt state preserved | IDs/status only; no owner content |
| Stage instruction content | Read | Starter-pack managed file + owner overlay | Re-read at defined boundary; overlay never modified by V2 | May contain owner preferences; body excluded from process diagnostics |
| Conversation turns | Read existing/persist existing behavior | Conversation store | Existing retention and ownership | Owner-sensitive; do not duplicate into V2 state |
| Page `spec.md` | Read/update | Canonical owner memory | Existing git/history/preservation; no parallel copy | Owner-sensitive |
| Page `plan.md` | Read/update | Canonical owner memory | Existing git/history/preservation; no parallel copy | Owner-sensitive |
| Page `journal.md` | Read/update when eligible | Canonical owner memory | Existing journal preservation; no synthetic entry | Owner-sensitive |
| `me/profile.md` | Read/targeted update | Canonical owner memory | No delete/full replace; preserve unrelated bytes; existing history | Potentially sensitive; exact facts excluded from default V2 diagnostics |
| Artifact candidate | Validate/transiently retain as needed | Model/tool attempt | Retain only long enough for validation/recovery; build plan chooses bounded storage | Owner-sensitive; never in default trace |
| Artifact reference | Create/read | V2 state | Path + digest + acceptance metadata | Metadata only |
| Profile disposition | Create/update | V2 stage state plus canonical artifact result | Durable for run; content-free status in default state | Candidate body omitted; count/digest/status allowed |
| Process evidence | Append/emit | Existing protected local audit mechanism or bounded V2 equivalent | Retention follows documented local diagnostics policy | Strict allowlist; no raw content/secrets |

### 19.1 Migration Requirements

- No owner artifact schema migration is required.
- V1 state and traces are not imported into V2.
- Existing `spec.md`, `plan.md`, `journal.md`, profile, overlays, conversations, and git history remain intact.
- V2 state must use a distinct schema/process version so an old V1 file cannot be mistaken for resumable V2 state.
- Disabling or removing V2 diagnostics must never delete owner artifacts.

## 20. API and Interface Requirements

### 20.1 Existing Public Message Interface

- Continue using the existing authenticated `POST /message` request and SSE response behavior.
- Use the existing optional message metadata capacity for the structural start signal unless build planning proves that a narrower established contract is required.
- Do not add a second process-start endpoint solely for V2.
- Preserve existing conversation ID, project metadata, error mapping, streaming, tool approvals, and message persistence.

### 20.2 Structural Start Contract

The interface must semantically carry:

- process action: start;
- fixed process kind/version;
- active page identity or a server-verifiable binding to it;
- client origin sufficient to distinguish the existing CTA action from ordinary typed text.

Exact property names are deferred to build planning. The server must derive provider, authenticated actor, canonical page, required file presence, and conversation identity itself rather than trusting client claims.

### 20.3 Internal Controller Contract

The internal boundary must be able to:

- validate start/resume eligibility;
- assemble stage context from canonical sources;
- invoke the existing model adapter and authorized tool executor;
- accept a structural stage outcome;
- validate and apply protected writes;
- apply an owner override;
- persist minimal state before acknowledged transitions;
- emit existing `StreamEvent` variants;
- return an explicit terminal or recoverable outcome.

### 20.4 Profile Interface

- Profile candidate reporting is an internal structured stage outcome, not a public owner API.
- Profile mutation must pass through existing memory tool authorization and approval.
- V2 validation wraps the permitted operation but cannot grant permission.
- Owner-visible chat must state whether the update was proposed, awaiting approval, declined, or written; it may not expose internal enum names.

### 20.5 UI Interface

- Reuse the existing empty-page CTA and visual design.
- CTA click attaches structural process intent in addition to the displayed chat text.
- Ordinary composer submission does not impersonate CTA intent merely because its text matches.
- Existing loading, tool, approval, stop, error, retry, mobile, keyboard, and responsive behavior remain.
- Internal process tools/events are filtered from owner-visible SSE/chat.

## 21. External Integration Requirements

### 21.1 Ollama

| Concern | Requirement |
|---|---|
| Purpose | Serve the selected local model through the existing OpenAI-compatible adapter |
| Authentication | Preserve current owner-configured Ollama behavior; V2 adds no credential |
| Permissions | No permission beyond existing model calls |
| Request behavior | Use active stage context and allowed tools; no discovery call for CTA entry |
| Response behavior | Parse through existing adapter; structural outcomes use existing tool-call capability or an equivalent internal structured mechanism selected during build planning |
| Timeout/error | Map through existing provider errors; pause recoverably when run state exists |
| Retry | V2 structural correction is not a transport retry; transport behavior remains adapter-owned |
| Idempotency | Model calls cannot directly establish accepted writes without validation/reconciliation |
| Availability | Ollama may be stopped/restarted independently |
| Security | No new network destination; do not log base URL credentials or payload bodies in V2 evidence |

### 21.2 Cloud Providers

| Concern | Requirement |
|---|---|
| Purpose | Execute the same guarded process through existing BrainDrive Models and OpenRouter adapters |
| Process semantics | Use the identical entry, stages, profile obligations, validators, correction cap, protected writes, overrides, and completion rules as Ollama |
| Provider execution | Preserve each provider's existing model selection, request mapping, streaming, tool-call parsing, error mapping, and transport retry behavior |
| Authentication and credits | Preserve existing credential, authorization, and BrainDrive Models credit behavior; V2 adds no provider credential and does not make BrainDrive Models credits apply to Ollama or BYOK OpenRouter |
| Security | Introduce no BrainDrive-owned provider key into client configuration; do not record provider payloads, keys, sensitive URLs, or response bodies in V2 evidence |
| Availability and recovery | Map provider interruption through existing errors and pause an active guarded run recoverably |
| Acceptance | Pass the matched cloud no-regression bar in Section 31.5 before the built-in behavior is accepted |

## 22. Validation Rules

### 22.1 Start Validation

- Effective provider ID must equal `ollama`, `braindrive-models`, or `openrouter`.
- Page ID must be supported and canonical.
- Required process files must exist and be readable.
- Start action must be recognized and bound to the active request/page.
- Existing active run must be absent or explicitly resumable.
- Root Your Agent is not eligible.
- Display text is not evidence of structural intent.

### 22.2 Stage Outcome Validation

- Outcome stage and revision must match active state.
- Attempt identity must be current and not previously consumed.
- Required prerequisite must be accepted or explicitly absent by owner choice.
- Profile disposition must be present for interview/specification completion.
- Structural outcome must not claim a write without an attributable verified mutation.
- Owner override category must be recognized and applicable.

### 22.3 Page Artifact Validation

- Path must equal the active page/stage canonical path.
- Delete is forbidden.
- Required stable headings occur exactly once.
- Status, date, and changelog structures required by active templates remain.
- Candidate is nonempty and not merely untouched template guidance when completion is claimed.
- A whole-file candidate for page `spec.md` or `plan.md` is permitted only when the existing target exactly matches a recognized unmodified starter-template digest and the candidate passes every structural check; populated or customized artifacts require targeted preserved edits.
- A plan cannot be accepted before specification resolution.
- Journal entry must satisfy active eligibility and duplicate-prevention rules.

### 22.4 Profile Validation

- Path must be exactly `me/profile.md`.
- Candidate must correspond to an exact profile candidate from the active interview revision.
- Candidate source must be owner-provided, not inferred or fabricated.
- Mutation must be a targeted preserved edit/insertion.
- Delete and whole-file replacement are forbidden.
- Existing headings and unrelated content remain.
- Required conversational/tool approval under active contracts must be satisfied.
- Resulting digest must be reconciled before disposition becomes `written`.

### 22.5 Error Presentation

- Owner-facing errors use plain language and do not show paths unless current BrainDrive conventions require them for recovery.
- Model-facing correction includes deterministic failed checks, not hidden qualitative judgment.
- Operator evidence uses stable categories/codes without raw inputs.

## 23. Error Handling

| Category | Detection | Owner-Visible Behavior | Operator Evidence | Retry / Recovery | Final State |
|---|---|---|---|---|---|
| Ineligible start | Provider/page/files/state mismatch | Existing ordinary behavior or concise unavailable message when CTA specifically failed | Bypass/eligibility code | Restore required files, select a supported provider/page, or use ordinary chat | No V2 state |
| Invalid structural metadata | Schema/binding failure | Request rejected or safe ordinary fallback according to established request-validation policy | Validation code, no raw metadata | Repeat valid CTA action | No V2 state |
| Missing instruction | Stage load failure | Name owner-facing process area that cannot continue; no hidden fallback | Missing reference/digest status | Restore file or stop | `NEEDS_OWNER_ACTION` |
| Structural candidate failure | Validator codes | One automatic correction; then clear weakness and choices | Stage/attempt/codes | One automatic correction | Active or `NEEDS_OWNER_ACTION` |
| Approval denial | Existing approval result | State that proposed write was not applied | Tool/status/profile disposition | Owner may explicitly retry or decline | Waiting/declined |
| Wrong-stage write | Protected executor | No accepted file change; natural correction | Path class/stage/code | Within one correction budget | Active or needs owner |
| Persistence failure | Write/state result | Work is not claimed complete | Operation class and sanitized error | Reconcile actual artifact; owner choice if ambiguous | Paused/needs owner |
| Provider unavailable | Adapter error | Existing provider recovery language | Provider class/model ref/status | Owner retries after service returns | `PAUSED_RECOVERABLE` |
| Context overflow | Existing context handling | Existing warning/error recovery | Existing correlation plus stage | Compact only within stage contract; retry owner-controlled if needed | Paused/needs owner |
| Stale owner edit | Digest mismatch | Explain that newer owner changes were preserved | Expected/current digest status | Re-read and redo with owner control | `NEEDS_OWNER_ACTION` |
| Corrupt/unsupported state | State schema/read | Explain process cannot resume automatically; artifacts remain | Version/error category | Start a new V2 run or continue ordinary chat | `NEEDS_OWNER_ACTION` |
| Internal invariant failure | Runtime assertion/transition validation | Safe generic error; no false completion | Protected error and state snapshot metadata | Manual diagnosis; no blind retry | `FAILED_INTERNAL` |
| Diagnostic degradation | Audit write failure | Normally no owner interruption unless acceptance evidence is required | Protected application log | Fix before claiming pass | Run marked degraded |

## 24. Retry, Recovery, and Idempotency

### 24.1 Automatic Correction

- Applies only to deterministic stage/outcome validation failure.
- Maximum is one correction after the initial attempt.
- Attempt count is durable before the correction call.
- Restart cannot reset it.
- Owner-requested explicit redo creates a new stage revision and is not an automatic third attempt.

### 24.2 Transport Retry

- Existing adapter/network retry behavior remains separate.
- V2 must not convert provider timeouts into automatic duplicate artifact mutations.
- A provider interruption after a tool call requires artifact reconciliation before repeating any mutation.

### 24.3 Canonical Operation Identity

Every protected mutation must be attributable to:

- run ID;
- stage kind and revision;
- attempt;
- operation/tool-call ID;
- canonical target path;
- expected prior digest when the file exists;
- candidate/result digest.

Replaying the same accepted operation identity returns/reconstructs the accepted result without another write.

### 24.4 Ambiguous Outcome Reconciliation

If a tool response is lost or persistence fails after delegation:

1. Read the canonical target through a protected server path.
2. Compare the actual digest and required structure with the validated candidate.
3. If it matches, mark applied without rewriting.
4. If it does not match, do not blindly repeat; pause or return owner action.

### 24.5 Restart and Resume

- Load V2 state by conversation/page/process identity.
- Validate schema, terminal status, active stage, attempt count, and artifact references.
- Re-read active instructions and canonical artifacts.
- If accepted references still match, continue first unresolved stage.
- If owner content differs, preserve it and stop for reconciliation.

## 25. Concurrency and Race Conditions

- At most one active V2 mutation may commit for a conversation/page/process tuple.
- Two simultaneous CTA requests must not create two active runs; one canonical run wins and the other resolves to existing state or conflict without extra model work.
- Stale model outcomes lose when stage revision or attempt identity has advanced.
- An owner file edit made after candidate validation but before delegation wins; the candidate is rejected on digest mismatch.
- Two protected writes to the same artifact are serialized or guarded by optimistic revision checks.
- Writes to different owner artifacts may proceed only when the state contract permits them; parallel specification and plan acceptance is forbidden.
- Stop/override received before an in-flight result is committed prevents automatic advancement; an already-applied file mutation must be reconciled and reported honestly.
- Process-state persistence and artifact persistence must have a defined ordering that never exposes accepted state before verified canonical data.
- V2 assumes one application process for initial implementation only if verified during build planning; multi-process deployment requires a cross-process concurrency decision before support is claimed.

## 26. Security and Privacy

### 26.1 Authentication and Authorization

- Reuse current authenticated owner context.
- Structural metadata does not authenticate the user and does not grant permission.
- All file operations retain current authorization, approval, path containment, and mutation safety.
- V2 adds no roles, scopes, credentials, tokens, or secrets.

### 26.2 Input and Model Trust

- Treat client metadata, owner text, model output, tool arguments, overlays, persisted V2 state, and provider responses as untrusted.
- Schema-validate control outcomes and path-resolve canonical targets server-side.
- Never accept executable process definitions, arbitrary paths, or provider IDs from the model.
- Internal controls are available only in server-constructed guarded context.

### 26.3 Data and Logging

- Do not record raw owner messages, prompts, profile candidates, artifact bodies, or provider payloads in default V2 state/evidence.
- Do not record keys, tokens, cookies, authorization headers, secret references by value, full environment output, or sensitive URLs.
- Allow only enumerated event fields and reject unknown content-shaped fields in protected diagnostics.
- V2 adds no telemetry egress or external analytics destination.

### 26.4 Destructive-Action Protection

- Delete is forbidden for all V2 canonical artifacts.
- Whole-profile replacement is forbidden.
- Existing owner content and overlays are preserved.
- Removing or replacing V2 code must leave all owner files intact.

### 26.5 Risk Level

**High trust/data-integrity risk:** V2 handles sensitive owner memory and AI-generated mutations. It adds no new network surface, but incorrect orchestration could corrupt or misplace owner data. Data preservation and truthful write claims are release-blocking.

## 27. User Experience Requirements

### 27.1 Entry

- Existing supported-page empty state and CTA remain visually consistent.
- CTA action starts V2 whenever supported provider/page eligibility passes.
- The CTA label remains owner-facing text; structural behavior does not depend on the exact phrase.
- Unsupported behavior continues through the existing ordinary chat behavior; the CTA must not become a dead control.

### 27.2 Conversation

- Interview feels like the page's existing advisor, not a form or workflow engine.
- One cognitive question at a time remains text-defined.
- Stage changes are not announced with internal names unless owner-facing procedure calls for a natural handoff.
- Owner can stop, redirect, or correct naturally.

### 27.3 Profile

- Exact profile candidates are presented in owner-facing language when active instructions require proposal.
- The process never claims Your Profile changed unless the verified write occurred.
- Pending/declined profile handling does not erase or falsify the page goals and plan.

### 27.4 Loading and Approvals

- Existing typing/tool status and approval cards remain.
- Internal process controls do not create visible tool cards.
- Stop streaming remains available and leaves recoverable state.

### 27.5 Failure and Recovery

- Provider interruption uses existing understandable recovery language.
- Validation exhaustion explains the structural problem and offers owner choices without exposing internal schemas.
- Refresh/reopen reflects persisted conversation and process outcome accurately.
- Mobile, keyboard, and responsive CTA/composer behavior remain accessible.

## 28. Observability and Diagnostics

### 28.1 Required Events

At minimum, V2 evidence must distinguish:

- `entry_accepted`;
- `entry_rejected` or `bypassed`;
- `stage_activated`;
- `stage_waiting_owner`;
- `outcome_received`;
- `validation_failed`;
- `correction_started`;
- `validation_passed`;
- `protected_write_applied`;
- `protected_write_reconciled`;
- `profile_disposition_recorded`;
- `owner_override_applied`;
- `process_paused`;
- `process_resumed`;
- `process_completed`;
- `process_stopped`;
- `process_failed`;
- `diagnostics_degraded`.

Exact event names may follow existing audit conventions, but their semantic distinctions are required.

### 28.2 Required Allowlisted Fields

- schema/contract version;
- UTC timestamp and sequence;
- correlation, conversation, run, page, and process identifiers;
- configured/resolved scope;
- provider ID/class and selected model ID;
- stage, stage revision, and attempt;
- decision/outcome/status;
- instruction and artifact references/digests;
- validator codes;
- operation/tool/model call IDs and status;
- profile disposition and candidate count/digest, never candidate text;
- owner override category;
- pause/recovery reason;
- duration where available;
- state before/after;
- diagnostic health.

### 28.3 Operator Questions Evidence Must Answer

1. Did the CTA supply structural intent?
2. Did the gateway accept or reject entry, and why?
3. Did the first model call run inside the interview stage?
4. Which procedure sources were loaded?
5. Which stage and attempt produced a candidate?
6. Which validation checks passed or failed?
7. Was a protected write applied, denied, reconciled, or not applied?
8. Was profile handling considered and what disposition resulted?
9. Did an owner override change sequence?
10. What state is safe to resume?
11. Did the run complete under guardrails or bypass them?

### 28.4 Metrics and Alerts

V2 V1 requires reportable counts from protected process evidence, not a metrics service:

- entry attempts/accepted/rejected/bypassed;
- guarded completion rate by model/scenario;
- unrequested sequencing failure count;
- first-attempt and correction recovery rate;
- profile-disposition correctness;
- validation exhaustion count;
- provider/infrastructure failure count separated from model failure;
- latency and model-call count by guarded stage.

No dashboard or production alerting is required.

## 29. Compatibility Requirements

- Existing owner artifacts and conversations remain readable and editable.
- Existing starter-pack filenames and owner overlays remain authoritative.
- Existing local and managed authentication/authorization remains.
- Existing memory-tool API and approval UX remain.
- Existing provider profiles, credentials, credits, model selection, discovery, pull, and delete behavior remain.
- Existing `POST /message` and SSE event shapes remain compatible; optional metadata may be extended without breaking older clients.
- Older clients that do not send structural intent continue ordinary chat and cannot claim guarded execution.
- Supported providers enter the same V2 process for every eligible structural request; provider identity does not change process semantics.
- V1 process state is not resumable as V2; it is preserved or ignored safely.
- Mixed-version client/server behavior fails safe: an unknown process-intent field is ignored by an older server, while a V2 server treats absence as ordinary chat.
- Downgrade leaves canonical owner files intact; any V2 state becomes inert diagnostic data.

## 30. Migration and Rollout Requirements

### 30.1 Development Base

- New implementation work starts from current `dev`, not from `agent/process-guardrails`.
- The V1 branch remains available for code archaeology, tests, and selective reuse.
- No deletion commit is required to “remove” V1 from the new branch because V1 is absent from `dev`.

### 30.2 Built-In Activation

- Do not introduce `BRAINDRIVE_PROCESS_GUARDRAILS` or any equivalent runtime configuration, environment variable, feature flag, provider scope, or settings control.
- Eligible process requests always enter V2.
- If V2 is later removed from the product, remove its runtime code, tests, and documentation through an explicit product change rather than retaining an inactive branch.

### 30.3 Existing Owner State

- No backfill or owner artifact rewrite.
- Existing populated specs/plans/profile/journals remain untouched.
- V2 V1 structured CTA applies to empty first-use pages; existing active pages remain ordinary unless a future structured refresh entry is added.
- V1 diagnostic state does not trigger V2.

### 30.4 Proof and Release

- Establish matched baseline evidence from a fixed pre-guardrail `dev` revision before guarded cloud comparison.
- Exercise the candidate implementation directly in local development/dogfood and cloud verification environments; do not add a runtime bypass for testing.
- Require both the real ≤12B Ollama efficacy bar and matched BrainDrive Models/OpenRouter no-regression bar before merging or releasing the built-in behavior.
- If efficacy or regression acceptance fails, do not ship the candidate. Revise or remove the implementation code on the feature branch; owner artifacts created during valid tests remain owner-owned and are not automatically reverted.

### 30.5 Cleanup

- Do not delete V1 branch/history as part of V2.
- Do not remove V1 reference documents.
- V1 implementation concepts may be selectively reintroduced only with direct requirement/test justification.

## 31. Testing Requirements

### 31.1 Verification Levels

- **Unit:** unconditional eligibility, absence of a runtime disable path, structural intent validation, stage transitions, profile disposition, artifact validators, correction cap, override normalization, and redaction.
- **Property-based:** one-active-stage, attempt bound, no forbidden transition, canonical path containment, profile preservation, stale-result rejection, and terminal-state uniqueness.
- **Integration:** web metadata → gateway entry → stage context → model/tool outcome → canonical write → persisted state/evidence.
- **Web client:** CTA metadata differs from ordinary composer text while visual/keyboard/mobile behavior remains.
- **Gateway/API:** existing request/SSE compatibility, authentication, approval, provider error mapping, conversation persistence, and no internal control leakage.
- **Persistence/recovery:** restart, corrupt state, stale state, owner edit conflict, ambiguous write reconciliation, duplicate request, and concurrent CTA.
- **Regression:** all supported provider integrations, root Your Agent, unsupported pages, ordinary chat, provider settings, credits, and memory tools.
- **Runtime/browser harness:** real CTA click through the real web client, gateway, adapter boundary, tools, canonical files, and restart.
- **Real-model harness:** actual Ollama model, canonical starter pack, frozen scenarios, captured process evidence, artifacts, and measured system memory.
- **Human review:** conversational quality, owner trust, appropriateness of profile candidates, and absence of mechanical workflow leakage.

### 31.2 Required Test Matrix

| Scenario | Preconditions | Trigger | Expected Result | Test Level |
|---|---|---|---|---|
| CTA first-use success | Supported provider, empty Fitness page | Click CTA | Entry accepted before first model call; interview active | Web + integration + E2E |
| CTA text typed manually | Same, no active run | Type `Let's get started` in composer | No forged CTA metadata; ordinary behavior unless later structured action exists | Web + integration |
| Model ignores internal start | Valid CTA | Provider response never calls `process_start` | Guarded interview still runs; no dependency on model start call | Integration + real model |
| No disable path | Any supported provider/page and valid CTA | Attempt ordinary deployment/runtime variations | Request always enters V2; no config, flag, or setting bypass exists | Unit + integration + static review |
| Cloud provider | OpenRouter or BrainDrive Models | Click CTA | Same guarded process semantics; existing provider execution/credentials/credits preserved | Integration + regression + E2E |
| Unknown provider | Unclassified ID | Click CTA | Existing path; sanitized bypass | Unit + integration |
| Root Your Agent | Supported provider | Use root empty-state suggestion | No V2 run | Web + integration |
| Unsupported/custom page | Supported provider | Send message | No V2 run | Unit + integration |
| Missing process file | Eligible page missing required procedure | Click CTA | No stage model call; named safe failure | Integration |
| Multi-turn interview | Active run | Owner answers several questions | Same interview stage persists until playback outcome | Controller + E2E |
| Known profile/page context | Existing profile context | Start interview | Model receives known context and asks only gaps/confirmation | Context + harness |
| Profile candidates present | Owner gives stable household/schedule facts | Complete playback | Exact candidates and disposition recorded | Unit + integration + real model |
| No profile candidate | Only page-specific facts | Complete playback | `not_applicable`; no fabricated candidate/write | Unit + harness |
| Approval required | Instruction fixture requires exact approval | Candidate proposed, no approval yet | Awaiting approval; no write; page process may continue as allowed | Integration + human |
| Approval not required fixture | Instruction fixture permits confirmed owner-stated facts | Candidate resolved | Safe targeted write possible without orchestration code change | Integration |
| Profile declined | Candidate proposed | Owner declines | No profile write; disposition declined; accurate chat | Integration |
| Profile whole-file write attempt | Active stage | Model requests replacement | Rejected; original profile unchanged | Unit + integration |
| Plan before spec | No override | Model attempts plan write | Rejected and corrected within budget | Unit + integration |
| Wrong-page write | Career run | Model targets Fitness artifact | Rejected; neither file changed | Unit + security |
| Missing/duplicate headings | Active artifact stage | Submit invalid candidate | One structural correction; no premature acceptance | Unit + integration |
| Correction succeeds | First candidate invalid | Corrected candidate valid | Accepted on attempt 2; no attempt 3 | Controller |
| Correction fails | Two invalid candidates | Second validation fails | `NEEDS_OWNER_ACTION`; safe recovery choices | Controller + E2E |
| Owner skips specification | Interview active | Explicit skip | Plan receives absent-by-choice prerequisite | Controller + human |
| Owner stops | Any active stage | Explicit stop | Terminal stop; no automatic calls | Controller + E2E |
| Journal no-entry | Initial alignment complete | Handoff has no journal-worthy content | Complete-with-no-entry; journal unchanged | Unit + integration |
| Journal eligible | Follow-up content is eligible | Handoff | Exactly one preserved entry | Integration |
| Provider interruption | Active stage | Active provider unavailable | Paused recoverably; accepted work intact | Failure injection + E2E |
| Gateway restart | Active/waiting stage | Restart and send owner reply | Resume unresolved stage with attempt count intact | Persistence + E2E |
| Owner edit conflict | Candidate validated; owner edits file | Commit/resume | Owner edit wins; stale candidate rejected | Concurrency + integration |
| Duplicate CTA | Two near-simultaneous clicks | Requests race | One active run; no duplicate model/process work | Concurrency |
| Duplicate accepted operation | Same operation replayed | Replay after response loss | No duplicate write/journal entry | Idempotency |
| Diagnostics redaction | Guarded success/failure with secret-shaped inputs | Inspect evidence | No messages, bodies, facts, payloads, or secrets | Security |
| Real Gemma ≤12B set | Frozen starter-pack scenarios | Run through actual UI/runtime/Ollama | Meets entry, sequence, profile, artifact, correction, and hardware bar | Real model + human |
| Gemma 31B comparison | Same scenarios/config except model | Run comparison | Reported separately; not used for 16 GB acceptance | Real model |
| BrainDrive Models no-regression | Matched pre-guardrail baseline and guarded candidate | Run repeated comparison | No hard/structural regression; performance/cost and conversation bar pass | Cloud integration + human |
| OpenRouter no-regression | Matched pre-guardrail baseline and guarded candidate | Run repeated comparison | No hard/structural regression; performance/cost and conversation bar pass | Cloud integration + human |

### 31.3 Real-Model Evaluation Protocol

Each scored run must record:

- BrainDrive commit and clean/dirty status;
- starter-pack revision/digests;
- model identifier, quantization, context setting, and Ollama version;
- hardware, operating system, total memory, and measured peak total system memory;
- scenario ID and uncontaminated persona input;
- CTA entry evidence;
- complete stage/attempt/validation/profile disposition summary;
- canonical output artifact digests and retained evaluation copies where permitted;
- infrastructure errors separated from model/process failures;
- human review result and reason.

Runs lacking `entry_accepted` and stage evidence are classified as unguarded/invalid, not failed guarded attempts and not passes.

### 31.4 V2 Local Efficacy Bar

Before V2 V1 is accepted:

1. Run at least three frozen representative first-use scenarios that collectively cover goals, hard constraints, profile-worthy facts, and one correction opportunity.
2. Run at least three repeats per scenario with the same qualifying ≤12B model/configuration.
3. Require 100% structural CTA entry.
4. Require zero unrequested sequencing failures.
5. Require zero protected-write bypasses, data-loss events, fabricated journal entries, or false write claims.
6. Require correct profile consideration/disposition in every run; qualitative appropriateness of candidates receives human review.
7. Require all required page artifacts to pass deterministic structure/preservation checks, either first attempt or the single correction.
8. Require at least 8 of 9 runs to complete without `NEEDS_OWNER_ACTION` caused by model structural failure.
9. Require measured execution within the 16 GB-class total system-memory envelope.
10. Treat provider/infrastructure failures separately and rerun them with preserved evidence; do not erase them from the report.

This recommended bar is subject to product-owner review in OI-002 but is the default if no different bar is ratified before test execution.

### 31.5 Cloud No-Regression Bar

Before V2 acceptance, each cloud provider must be tested using a fixed pre-guardrail baseline revision and the guarded candidate with the same provider, model, starter-pack revision, frozen scenarios, model settings, and repeat count:

1. Require 100% guarded entry for candidate runs and record the exact baseline and candidate revisions.
2. Require zero new hard-gate failures: no sequencing violation, protected-write bypass, data loss, fabricated journal/profile fact, false write claim, credential/credit regression, authorization bypass, or incompatible request/SSE behavior.
3. Require guarded structural pass rate to be no lower than the matched pre-guardrail baseline.
4. Require median end-to-end process latency and provider-reported token use/cost, where available, to increase by no more than 20% versus the matched pre-guardrail baseline unless product owners ratify a different bound before execution.
5. Require human review to find no decrease in conversational clarity, responsiveness, trust, or absence of internal workflow leakage.
6. Report provider/model-specific results separately; a pass by one cloud provider cannot substitute for the other.

The 20% bound is the recommended default under OI-006. The test plan must define sample count and comparison method before execution and may not loosen the bound after seeing results without recording a product decision.

### 31.6 Commands and Repositories

The later test plan/build plan must name exact commands after final file/module selection. At minimum it must cover the repository-standard checks applicable to changed areas:

- main TypeScript tests and build;
- web typecheck, tests, and build;
- desktop preflight when client contracts change;
- runtime/browser harness;
- real Ollama local-model run set.

No command may be claimed passing unless run output is read and retained in the completion evidence.

## 32. Acceptance Criteria

- [ ] **AC-001:** Every eligible supported-provider CTA request enters V2 with no runtime configuration, environment variable, feature flag, provider scope, settings control, or model decision involved.
- [ ] **AC-002:** Existing supported-page CTA sends a structural process-start signal distinct from ordinary typed text.
- [ ] **AC-003:** Gateway validates stable provider ID, page, process files, request binding, and current state before entry.
- [ ] **AC-004:** A valid CTA enters interview before the first stage model call without a model `process_start` call, preliminary model discovery call, or ordinary protected-write bypass.
- [ ] **AC-005:** Active stage loads canonical managed behavior and applicable overlay in the required order.
- [ ] **AC-006:** A behavior-only instruction/overlay edit changes the next run without TypeScript modification and without overlay mutation.
- [ ] **AC-007:** Stage context contains only required active-stage sources and excludes downstream, unrelated, and frozen evaluation content.
- [ ] **AC-008:** A multi-turn interview remains the active stage until its structural outcome is accepted or the owner overrides it.
- [ ] **AC-009:** Specification cannot be accepted before interview resolution unless explicitly skipped by owner.
- [ ] **AC-010:** Plan cannot be accepted before specification resolution unless explicitly skipped/reordered by owner.
- [ ] **AC-011:** Protected writes use only the active page/stage canonical target and reject wrong-page, wrong-stage, delete, or destructive replacement attempts.
- [ ] **AC-012:** Accepted specification preserves canonical structure and unrelated owner content.
- [ ] **AC-013:** Accepted plan preserves canonical structure, reflects resolved prerequisites, and lands only in canonical `plan.md`.
- [ ] **AC-014:** Journal handoff produces either no entry when ineligible or exactly one preserved entry when eligible; synthetic/duplicate entries are impossible.
- [ ] **AC-015:** Interview completion always records profile relevance as not applicable or exact candidate dispositions.
- [ ] **AC-016:** Stable owner-provided cross-project facts in the frozen scenarios are surfaced as exact profile candidates; page-specific/inferred facts are not silently promoted.
- [ ] **AC-017:** Missing, fabricated, or inconsistent profile disposition fails deterministic validation.
- [ ] **AC-018:** Guarded profile operation permits only matching targeted `me/profile.md` edits and rejects delete, whole-file replacement, stale target, or candidate mismatch.
- [ ] **AC-019:** Owner-visible profile claims match actual proposed/pending/declined/written state under both approval-policy fixtures.
- [ ] **AC-020:** Invalid protected outcomes are rejected before canonical acceptance and receive stable structural feedback.
- [ ] **AC-021:** The first validation failure permits one automatic correction with durable attempt count.
- [ ] **AC-022:** A valid correction is accepted and reconciled without duplicate mutation.
- [ ] **AC-023:** A second invalid result ends automatic advancement in `NEEDS_OWNER_ACTION`; no third automatic attempt occurs, including after restart.
- [ ] **AC-024:** Explicit owner skip, redo, stop, and resume actions are honored and recorded as owner choices.
- [ ] **AC-025:** Ambiguous owner direction does not mutate process state until resolved conversationally.
- [ ] **AC-026:** Provider/gateway interruption preserves accepted artifacts, active stage, revision, and attempt count.
- [ ] **AC-027:** Resume continues first unresolved work and never regenerates matching accepted artifacts.
- [ ] **AC-028:** Newer owner edits and corrupt/unsupported state stop automatic resume without overwrite.
- [ ] **AC-029:** Every valid run emits sanitized entry, stage, validation, write, profile, override, pause/resume, and terminal evidence as applicable.
- [ ] **AC-030:** Default evidence contains no owner text, artifact/profile bodies, provider payloads, credentials, tokens, sensitive URLs, or secret values.
- [ ] **AC-031:** A reviewer can prove from evidence whether a run was guarded, which sources/stages/attempts ran, what was accepted, and why it stopped/completed.
- [ ] **AC-032:** Unknown providers, root Your Agent, unsupported pages, and ordinary non-process requests create no V2 state, stage model call, correction, validation, or protected-write behavior.
- [ ] **AC-033:** `ollama`, `braindrive-models`, and `openrouter` use identical entry, sequencing, profile, validation, correction, protected-write, override, and completion semantics for eligible requests.
- [ ] **AC-034:** Existing provider credentials, credits, model selection, adapter behavior, approvals, auth, message persistence, request schema compatibility, and SSE events do not regress.
- [ ] **AC-035:** No runtime guardrail switch or disabled code path exists; removing V2 later requires an explicit product/code removal that preserves owner artifacts.
- [ ] **AC-036:** At least one ≤12B model passes the real-model success bar within measured 16 GB-class total system memory.
- [ ] **AC-037:** Scripted and real-model reports reject any no-entry run as invalid guardrail evidence rather than a guarded pass.
- [ ] **AC-038:** Full applicable unit/integration/web/build/desktop/harness checks pass with no unrelated changes.
- [ ] **AC-039:** Operator/developer documentation explains unconditional eligible activation, CTA entry, supported/ineligible boundaries, proof requirements, diagnostics privacy, and the absence of a runtime disable mechanism.
- [ ] **AC-040:** Dave W and Dave J review the V2 done-done definition and confirm that deterministic entry, profile disposition, ≤12B efficacy, data integrity, provider-independent semantics, and cloud no-regression are the finish line.
- [ ] **AC-041:** Matched pre-guardrail-baseline and guarded-candidate comparisons for BrainDrive Models and OpenRouter pass every Section 31.5 hard, structural, performance/cost, provider-contract, and human-quality requirement.

## 33. Requirement Traceability Matrix

| Requirement | User Story | System Area | Acceptance Criteria | Verification |
|---|---|---|---|---|
| FR-001 | US-1, US-9 | Built-in activation | AC-001, AC-032, AC-035 | Eligibility, static-boundary, and integration tests |
| FR-002 | US-1 | Web/gateway entry | AC-002–AC-004 | Web test, gateway integration, E2E |
| FR-003 | US-1, US-9 | Eligibility | AC-003, AC-032–AC-034 | Matrix unit/integration tests |
| FR-004 | US-2 | Instruction loading | AC-005, AC-006, AC-031 | Loader/context tests, owner-edit eval |
| FR-005 | US-2 | Context assembly | AC-005–AC-007 | Context manifests, anti-contamination tests |
| FR-006 | US-2, US-3 | Process control | AC-007–AC-010 | State/controller property tests, E2E |
| FR-007 | US-3 | Specification | AC-009–AC-012 | Validator/tool integration |
| FR-008 | US-3 | Planning | AC-010–AC-013 | Validator/controller integration |
| FR-009 | US-3 | Journal | AC-013, AC-014 | Journal eligibility/idempotency tests |
| FR-010 | US-4 | Profile outcome | AC-015–AC-017 | Outcome schema + real-model scenarios |
| FR-011 | US-4 | Profile mutation/policy | AC-016–AC-019 | Dual-policy fixtures, preservation tests |
| FR-012 | US-1, US-3, US-4 | Tool boundary | AC-004, AC-011, AC-018, AC-020 | Protected-executor integration/security |
| FR-013 | US-3, US-4, US-5 | Validation | AC-011, AC-017, AC-020–AC-022 | Unit/property/integration |
| FR-014 | US-5 | Correction | AC-020–AC-023 | Controller/restart tests |
| FR-015 | US-6 | Owner control | AC-024, AC-025 | Controller + human UX |
| FR-016 | US-7 | State/recovery | AC-026–AC-028 | Restart/conflict/failure injection |
| FR-017 | US-8 | Evidence | AC-029–AC-031 | Schema/redaction/report tests |
| FR-018 | US-9 | Compatibility | AC-032–AC-035, AC-041 | Regression matrix/full suite |
| NFR-001 | US-1, US-2 | Reliability | AC-002–AC-004, AC-036, AC-037 | E2E + real model |
| NFR-002 | US-5 | Bounded execution | AC-021–AC-023 | Property/restart tests |
| NFR-003 | US-3, US-4, US-7 | Data integrity | AC-011–AC-019, AC-026–AC-028 | Preservation/conflict/idempotency |
| NFR-004 | US-8 | Privacy | AC-029, AC-030 | Security/redaction tests |
| NFR-005 | All | Simplicity/scope | AC-038, AC-040 | Architecture/spec/diff review |
| NFR-006 | US-2, US-4, US-6 | Owner editability/control | AC-006, AC-016, AC-019, AC-024 | Owner-edit/policy fixture/human review |
| NFR-007 | US-7 | Recovery | AC-026–AC-028 | Restart/failure injection |
| NFR-008 | US-9 | Compatibility | AC-032–AC-035, AC-038, AC-041 | Provider/full regression suite |
| NFR-009 | US-8 | Auditability | AC-029–AC-031, AC-037 | Evidence schema and report review |
| NFR-010 | US-4, US-6, US-9 | Trust/usability | AC-019, AC-024, AC-025, AC-034 | Human UX + web regression |
| NFR-011 | US-2 | Portability | AC-036 | Measured real-hardware run |
| NFR-012 | US-1, US-8 | Performance | AC-004, AC-029, AC-031, AC-041 | Call-count/latency/token/cost evidence |
| NFR-013 | US-3, US-4, US-9 | Security | AC-003, AC-011, AC-018, AC-030, AC-034 | Auth/path/security tests |
| NFR-014 | US-8 | Test validity | AC-036, AC-037, AC-040, AC-041 | Local/cloud harness reports and human sign-off |
| NFR-015 | US-8, US-9 | Cloud no-regression | AC-034, AC-041 | Matched cloud comparisons and human review |

## 34. Risks and Mitigations

| Risk | Likelihood | Impact | Detection | Mitigation |
|---|---|---|---|---|
| CTA metadata can be forged | Medium | High | API/security tests | Treat as intent only; server validates auth/page/provider/files and grants no permissions |
| Typed-text path still bypasses desired process | Medium | Medium | UX scenarios | Define CTA as guaranteed V2 entry; protected first-use writes fail closed; future refresh entry separate |
| Existing CTA is not shown for all desired states | High for active/stale pages | Medium | UI state inventory | Scope V2 V1 to first-use empty pages; specify future structured refresh separately |
| ≤12B still fails qualitative interview quality | Medium | High | Real-model/human review | Keep judgment in text; measure honestly; do not add code-owned qualitative policy without new evidence |
| ≤12B cannot produce reliable structured tool outcomes | Medium | High | Early thin vertical-slice run | Prove entry + one interview outcome before importing deeper V1 machinery; stop/reassess if impossible |
| Profile policy changes during build | High | Medium | Team decision/text diff | Separate mandatory recognition/disposition from text/approval-controlled write authorization |
| Profile candidates overcapture sensitive facts | Medium | High | Frozen adverse scenarios/human review | Require owner-provided stable cross-project facts, exact proposal, existing approvals, no inference |
| Profile write damages customized file | Medium | Critical | Preservation/property tests | Targeted edit only, digest check, no delete/full replace, owner edit wins |
| Protected boundary blocks legitimate ordinary updates | Medium | Medium | Regression scenarios | Apply after structural entry; scope fail-closed first-use behavior narrowly; owner override available |
| V1 complexity is copied wholesale | Medium | High | Diff/architecture review | Start from `dev`; every reused concept must map directly to a Must requirement and test |
| Minimal state is insufficient for restart | Medium | Medium | Failure injection | Persist only required identities/status/references; add no broader trace content |
| State and artifact commit diverge | Medium | Critical | Ambiguous-outcome tests | Defined reconciliation, digest verification, no accepted-state-before-artifact rule |
| Cloud behavior regresses through guarded execution | Medium | High | Matched provider matrix, contract tests, human review | One shared semantic controller, preserved adapters/contracts, Section 31.5 gate; do not merge/release a failing candidate |
| A dormant disable path fragments behavior or becomes dead code | Medium | High | Static review, runtime-surface inventory, eligibility tests | Introduce no runtime switch or flag; require code removal through an explicit future product change |
| Real-model evaluation is contaminated | Medium | High | Prompt/context snapshots, anti-overfit scan | Frozen scenarios outside runtime, provenance, reject contaminated run set |
| Infrastructure errors distort model score | High | Medium | Provider/error evidence | Classify separately and rerun without deleting evidence |
| 16 GB model cannot meet bar | Medium | High | Measured candidate sweep | Stop or revise local-model claim; larger model cannot substitute |
| Diagnostics leak owner data | Medium | Critical | Redaction/secret-shaped property tests | Strict allowlist; content-free state/evidence; protected local storage |
| Owner sees mechanical workflow behavior | Medium | Medium | Human UX review | Hide internal controls; stage behavior remains canonical text |
| Existing approval system interaction is ambiguous | Medium | High | Dual-policy and denial tests | Preserve existing approval semantics; never claim write without verified result |

## 35. Dependencies

| Dependency | Type | Effect |
|---|---|---|
| Ratified D4 proposal | Product decision | Authorizes code-owned orchestration and establishes the small-local-model efficacy target |
| Current `dev` branch | Repository baseline | Clean implementation base without V1 guardrail code |
| Existing web empty-state CTA | Product interface | Supplies the preferred deterministic first-use entry |
| Existing message metadata path | Internal interface | Can carry structural intent without a new endpoint |
| Gateway project resolution | Internal | Supplies canonical active page and conversation binding |
| Existing model/tool loop | Internal | Executes active stage calls and tools |
| Existing memory tools and approval store | Internal/security | Retain mutation authorization and owner approval behavior |
| Starter-pack page/process/profile files | Product data | Authoritative behavior and canonical artifact structure |
| Conversation and memory git/history | Internal data | Preserve owner turns, artifacts, recovery, and conflict evidence |
| Ollama OpenAI-compatible endpoint | External local service | Required for real local-model calls and efficacy proof |
| Existing BrainDrive Models and OpenRouter adapters | External provider integrations | Required for provider-independent compatibility and matched cloud no-regression proof |
| Qualifying ≤12B model | Model asset | Required for V2 acceptance |
| 16 GB-class hardware or measured equivalent | Test environment | Required for portability proof |
| Runtime/browser harness | QA | Proves actual CTA, gateway, writes, restart, and UI compatibility |
| Local-model evaluation harness | QA | Provides frozen scenarios, provenance, artifacts, and comparison reports |
| Dave W/Dave J review | Team | Required for done-done, profile policy direction, and efficacy acceptance |
| Security/privacy review | Team | Required because V2 mutates sensitive owner memory |

No new paid external service, production credential, Python product dependency, workflow framework, model judge, or cloud telemetry service is required.

## 36. Assumptions

| Assumption | Why Required | Evidence | Risk if Incorrect | Recommended Validation |
|---|---|---|---|---|
| Existing CTA accurately represents owner intent to begin the first-use process | Enables deterministic entry without language parsing | Page copy explicitly promises a short interview then spec/plan | CTA may be treated as generic chat only | Confirm with product owner; retain as default because it is the clearest existing action |
| Existing metadata path can safely carry structural intent | Avoids a new endpoint/UI | Client and gateway already transmit/consume project metadata | Adapter normalization may strip or over-trust fields | Prove with focused contract tests before implementation planning finalizes shape |
| First-use empty pages are sufficient for V2 V1 proof | Keeps scope bounded | Real failure occurred on empty starter pages | Active/stale refresh remains unguarded | Explicitly defer refresh action; do not claim broader coverage |
| Canonical starter-pack headings are stable enough for deterministic structure checks | Enables bounded validation | Current templates and procedures rely on stable sections | Owner customization could alter headings | Test managed templates plus supported overlays; define preservation-compatible customization boundary |
| Profile recognition can be structurally required without hardcoding approval policy | Avoids repeating V1 omission while policy evolves | Recognition/disposition and authorization are separable | Model may misuse dispositions | Dual-policy fixtures and real-model candidate scenarios |
| One correction captures most structural mistakes | Preserves simplicity | D4 simplicity-first direction and prior design | Recovery rate may be inadequate | Measure; do not add adaptive retry without new spec |
| Minimal durable state is needed across normal provider/runtime interruptions | Multi-turn process must remain coherent | Providers and gateway can stop independently | Persistence complexity may outweigh early proof | Build-plan thin slice should prove entry/stage first, but V2 done-done retains restart requirement |
| A qualifying ≤12B model can meet the defined bar | Core local proposition | 12B run showed useful conversation despite process omissions | No model may meet quality/structure on 16 GB | Use acceptance result to validate or reject the proposition honestly |
| One shared semantic process is feasible across supported providers | Avoids provider-specific behavior and broadens protection consistently | All three providers already execute through the model/tool loop and expose stable provider IDs | Adapter/tool-call differences may leak into process behavior | Run the same contract suite for every provider plus matched real cloud comparisons |
| Existing approval semantics remain authoritative | Avoids policy duplication | Memory mutations already use approvals | Conversational and tool approval may differ | Document both during test planning and require truthful state mapping |

## 37. Open Items and Questions

### OI-001 — Universal Profile Conversational-Approval Policy

- **Question:** Must every profile candidate receive explicit conversational approval, or only candidates that are inferred, sensitive, uncertain, broad, preference-like, or governed by page-specific instructions?
- **Why it matters:** It changes the transition from `proposed` to `written`, but not profile recognition or safe mutation.
- **Available evidence:** Base instructions require confirmation for some categories; several page procedures, especially Relationships, require exact approval. The team is actively reviewing the intended policy.
- **Options:**
  1. Require exact approval for every profile update.
  2. Require it only for riskier categories and allow clear owner-stated stable facts under normal write approval.
  3. Preserve page/procedure-specific policy.
- **Tradeoffs:** Option 1 is simplest to explain but adds friction. Option 2 is efficient but requires dependable classification. Option 3 preserves owner-editability and current behavior but can vary across pages.
- **Recommendation:** Use option 3 for V2: active canonical instructions govern conversational approval, while the existing tool approval subsystem always remains. Require explicit recognition/disposition in all cases.
- **Default if undecided:** Preserve current page/procedure text exactly; do not introduce a universal runtime rule.
- **Decision owner:** Dave W with Dave J confirming enforceability.
- **Impact of delay:** Non-blocking for spec/test planning because dual-policy fixtures are required; blocking only for final owner-facing copy/sign-off if the team wants one universal rule.

### OI-002 — Final ≤12B Quantitative Bar

- **Question:** Is the recommended 8-of-9 end-to-end completion bar sufficient, too weak, or too strong?
- **Why it matters:** The threshold must be fixed before results are interpreted.
- **Available evidence:** D4 requires material improvement and near-zero sequencing failures; V1 never generated valid guarded efficacy evidence.
- **Options:**
  1. Use the Section 31.4 bar.
  2. Require 9-of-9 completion.
  3. Use a larger statistically powered set.
- **Tradeoffs:** Option 2 may overreact to model variance; option 3 conflicts with bounded V1 effort; option 1 is interpretable and retains zero-tolerance hard invariants.
- **Recommendation:** Adopt Section 31.4: 8-of-9 completion with 100% entry/profile accounting and zero hard-invariant failures.
- **Default if undecided:** Section 31.4 applies.
- **Decision owner:** Dave W; Dave J confirms engineering/evaluation cost.
- **Impact of delay:** Blocking before real scored runs begin; non-blocking for test-plan drafting and thin-slice mechanics.

### OI-003 — Active Instruction Change During a Run

- **Question:** Should an owner edit to `AGENT.md` or an active procedure apply immediately or on the next run?
- **Why it matters:** Immediate application can produce mid-run inconsistency; ignoring owner changes weakens editability.
- **Available evidence:** V1 proposed digest stability per attempt and re-read at new run.
- **Options:**
  1. Freeze instruction digests for the entire run.
  2. Re-read at every owner turn.
  3. Freeze per stage/revision and apply changes at the next stage or explicit redo.
- **Recommendation:** Option 3. It respects owner edits without changing a stage's contract mid-attempt.
- **Default if undecided:** Freeze per stage revision; detect changes and apply on next stage/redo.
- **Decision owner:** Dave J with Dave W reviewing owner expectations.
- **Impact of delay:** Blocking for state/context contract implementation.

### OI-004 — Ordinary Typed Start or Existing-Page Refresh

- **Question:** How should an owner structurally start V2 when the empty-state CTA is absent or they type a similar phrase manually?
- **Why it matters:** V2 V1 guarantees first-use CTA behavior but not active/stale page refresh.
- **Available evidence:** The current product has a structural empty-state CTA but no explicit refresh metadata/control. Keyword matching was a V1 concern.
- **Options:**
  1. Add phrase matching.
  2. Add a future explicit Refresh Goals & Plan action.
  3. Guard every page message.
- **Recommendation:** Option 2 in a later specification. Do not add keyword parsing or guard every message.
- **Default if undecided:** V2 V1 remains first-use CTA only; typed text is ordinary chat.
- **Decision owner:** Dave W for UX; Dave J for request contract.
- **Impact of delay:** Non-blocking for V2 V1; limits the claim to first-use process reliability.

### OI-005 — State Storage and Retention

- **Question:** Which existing local persistence mechanism should store minimal V2 state and how long should terminal state remain?
- **Why it matters:** V1 built a large custom state/trace subsystem; V2 should not repeat complexity without need.
- **Available evidence:** Conversation storage, prompt audit, and V1 state/trace code offer patterns, but owner artifacts cannot be used as hidden control state.
- **Options:**
  1. Reuse/adapt the V1 store.
  2. Extend a suitable existing conversation-associated metadata store.
  3. Create a smaller protected V2 store.
- **Recommendation:** Decide during build planning after a thin persistence spike. Prefer the smallest existing mechanism that supports atomic revision checks, restart, and protected model access; otherwise create a minimal V2 store. Retain terminal state for 14 days by default to align with existing diagnostic precedent.
- **Default if undecided:** Minimal protected V2 store, 14-day terminal retention, nonterminal state retained until resolved or explicitly abandoned.
- **Decision owner:** Dave J.
- **Impact of delay:** Blocking for durable resume implementation, not for spec acceptance.

### OI-006 — Final Cloud No-Regression Bound

- **Question:** Is the recommended maximum 20% median increase in end-to-end latency and provider-reported token use/cost the correct cloud acceptance bound?
- **Why it matters:** Provider-independent guardrails should improve reliability without imposing an unbounded cloud experience or cost penalty.
- **Available evidence:** Structural entry is code-only and adds no discovery call, but stage scoping and a possible single correction can change total calls, tokens, latency, and cost.
- **Options:**
  1. Use the Section 31.5 maximum 20% median increase.
  2. Ratify a stricter bound.
  3. Ratify a different bound separately for latency and token/cost.
- **Tradeoffs:** One 20% limit is simple and measurable; stricter limits may reject worthwhile reliability gains; split limits are more precise but add evaluation complexity.
- **Recommendation:** Use option 1 for V2. Hard/provider-contract failures and structural pass-rate regression remain zero-tolerance regardless of the performance bound.
- **Default if undecided:** Section 31.5 applies.
- **Decision owner:** Dave W for product tolerance; Dave J confirms measurement feasibility.
- **Impact of delay:** Blocking before matched scored cloud runs begin; non-blocking for mechanics and test-plan drafting.

## 38. Recommended Decisions

1. **Start V2 from `dev`; preserve V1 branch/history.**
   - Rationale: Clean design boundary without losing evidence.
   - Consequence: Reuse is selective and justified.
   - Alternative rejected: Deleting V1 through a large reverse commit.
   - Status: Foundational and blocking for implementation setup.

2. **Use the existing empty-state CTA as the deterministic first-use signal.**
   - Rationale: It is explicit owner action already promising the process.
   - Consequence: No model activation decision or phrase parser.
   - Alternative rejected: Optional model `process_start`.
   - Status: Foundational and blocking.

3. **Use one unconditional provider-independent controller with no runtime switch.**
   - Rationale: The same process assistance strengthens every supported model and avoids provider-specific behavior.
   - Consequence: Every eligible request is guarded; Ollama proves efficacy and both cloud providers prove no regression before merge/release.
   - Alternative rejected: Local/Ollama-only semantic scope or any `off`/`on`/`none`/`local`/`all` activation mode.
   - Status: Foundational and blocking.

4. **Make profile consideration and disposition mandatory.**
   - Rationale: Profile omission is a real smaller-model process failure independent of approval policy.
   - Consequence: Every interview reports not-applicable or exact candidate status.
   - Alternative rejected: Deferring all profile behavior.
   - Status: Foundational and blocking.

5. **Keep profile approval behavior text/approval-controlled.**
   - Rationale: Policy may change without changing orchestration.
   - Consequence: Test both approval-required and approval-not-required instruction fixtures.
   - Alternative rejected: Universal hardcoded policy.
   - Status: Non-blocking policy decision under recommended default.

6. **Fail closed on protected process writes after structured entry.**
   - Rationale: Unguarded writes nullify the controller.
   - Consequence: Wrong-stage attempts receive structural feedback.
   - Alternative rejected: Delegating all non-control tools.
   - Status: Blocking.

7. **Require real ≤12B proof before V2 acceptance.**
   - Rationale: Scripted calls prove mechanics, not model assistance.
   - Consequence: No efficacy claim without entry/stage/profile/artifact/hardware evidence.
   - Alternative rejected: Deferring live proof after full infrastructure build.
   - Status: Blocking for done-done.

8. **Retain deterministic validation and one correction; exclude runtime judging.**
   - Rationale: Matches simplicity-first D4 direction.
   - Consequence: Qualitative quality remains human/harness-reviewed.
   - Alternative rejected: Model judge in V1.
   - Status: Blocking scope boundary.

9. **Scope V2 V1 entry to first-use empty pages.**
   - Rationale: Existing deterministic CTA is available and directly reproduces the failure.
   - Consequence: Active/stale refresh remains a future structured action.
   - Alternative rejected: Keyword matching or guarding every page message.
   - Status: Non-blocking limitation, required for honest claims.

10. **Prefer stage-revision instruction stability and minimal persistence.**
    - Rationale: Owner edits apply predictably without rebuilding V1 complexity.
    - Consequence: Build plan selects the smallest safe store and concurrency mechanism.
    - Alternative rejected: Freezing forever or reloading mid-attempt.
    - Status: Blocking for detailed implementation planning.

11. **Permit whole-file page-artifact candidates only against an exact unmodified starter template; never permit whole-profile replacement.**
    - Rationale: Initial page creation can remain simple without exposing customized owner files to destructive replacement.
    - Consequence: Populated/customized page artifacts and all profile changes use targeted preserved edits.
    - Alternative rejected: Broad whole-file replacement or mandatory targeted editing of every untouched starter template.
    - Status: Blocking preservation contract.

## 39. Future Considerations

- Add a structured Refresh Goals & Plan action for existing/stale pages after first-use V2 proof.
- Evaluate local models smaller than 12B after one 12B-class model passes.
- Extend the provider-independent contract to additional future providers only after they pass the same compatibility and no-regression gates.
- Add a second process only after a real second product workflow requires orchestration; then consider extracting a registry.
- Consider a runtime qualitative judge only if deterministic orchestration succeeds but measured failures are predominantly qualitative and the privacy/latency/cost tradeoff is accepted.
- Add richer owner-visible progress only if real usage shows that normal conversation and existing loading states are insufficient.
- Consider consent-based export of failed local-model attempts for fine-tuning under a separate data-governance contract.
- Consider longer-lived or owner-inspectable process diagnostics only if support evidence shows a need.
- Add structured profile candidate review UI only if conversational policy proves confusing; it is not required for V2 V1.

## 40. Glossary

| Term | Definition |
|---|---|
| Active stage | The one process stage currently permitted to ask for owner input or submit a structural outcome. |
| Canonical artifact | The established owner-memory file for the active page: `spec.md`, `plan.md`, `journal.md`, or `me/profile.md` as applicable. |
| Correction | The one allowed automatic model attempt after deterministic validation rejects the initial outcome. |
| CTA | The existing empty-page owner action such as `Let's get started` or `Let's figure it out`. |
| D4 | Ratified direction: judgment in text and orchestration in code, with small local models as the primary efficacy target. |
| Eligible process request | A structurally initiated request on a supported provider and page with required process files and valid start/resume state; it always enters V2. |
| Guarded run | A run started by valid structural intent or valid V2 resume state and executed through the V2 controller. |
| Hard invariant | A zero-tolerance property such as deterministic entry, no data loss, correct sequence, no bypass, or no fabricated profile/journal result. |
| Supported provider | A stable provider ID currently covered by the shared V2 contract: `ollama`, `braindrive-models`, or `openrouter`. |
| Owner override | Explicit owner direction to skip, redo, stop, or resume a stage. |
| Profile candidate | An exact owner-provided stable cross-project fact identified for possible routing to `me/profile.md`. |
| Profile disposition | The explicit outcome for profile handling: not applicable, proposed, awaiting approval, declined, or written. |
| Protected write | A process-related mutation to canonical page artifacts or the guarded profile operation that must pass stage validation. |
| Structural intent | Authenticated request metadata generated by a product action; it identifies process initiation but grants no permission. |
| Structural validation | Deterministic checks of stage, path, prerequisite, required structure, preservation, and outcome coherence; not prose-quality judgment. |
| V1 implementation | The prior `agent/process-guardrails` branch implementation, not the V2 first usable version defined in this document. |
| V2 V1 | The first accepted usable version of the redesigned provider-independent process guardrails specified here. |

## 41. Definition of Done

V2 V1 is “done done” only when all of the following are true:

1. A real owner action on the existing supported-page CTA deterministically starts the guarded interview without model cooperation.
2. The full fixed process resolves interview, specification, profile disposition, plan, and journal handoff in order, subject to owner override.
3. Protected artifact/profile writes cannot bypass active-stage validation.
4. Profile-worthy facts are never silently ignored, and profile writes are safe and truthful under the active policy.
5. Invalid structural outcomes receive no more than one automatic correction.
6. Interruptions resume without losing accepted work or overwriting owner edits.
7. Default evidence proves entry and outcomes without exposing owner content or secrets.
8. All ordinary/ineligible paths retain their existing contracts; supported providers retain their execution, credential, credits, authorization, and streaming contracts when guarded.
9. At least one ≤12B model meets the Section 31.4 live bar within the measured 16 GB-class system envelope.
10. BrainDrive Models and OpenRouter each meet the Section 31.5 matched no-regression bar.
11. All applicable repository, web, gateway, persistence, security, runtime-harness, and real-model checks pass.
12. Dave W and Dave J read back and agree to this finish line.

The following are explicitly **not** required for V2 V1:

- support for providers beyond Ollama, BrainDrive Models, and OpenRouter;
- active/stale-page refresh entry;
- generalized workflows;
- runtime model judge;
- mixed-model routing;
- dashboard/progress wizard;
- fine-tuning or model distribution;
- a universal hardcoded profile conversational-approval policy.

## 42. Changelog

| Date | Change | Reason | Source |
|---|---|---|---|
| 2026-07-26 | Initial V2 specification created | Return to the ratified local-harness proposal, incorporate real 31B/12B evidence, correct model-dependent entry, require profile disposition, and reduce scope/complexity | Current Codex/user review; `local-harness-proposal.md`; V1 code/tests/audit evidence |
| 2026-07-26 | Revised V2 to one provider-independent contract | Simple guardrails can strengthen every supported model; retain local efficacy as the primary proof while preventing cloud regressions | Dave W follow-up review |
| 2026-07-26 | Removed runtime activation switch and rollback mode | Accepted guardrails are built-in process behavior; a future removal should remove code instead of retaining a disabled path | Dave W follow-up review |

## 43. Conversation References

| Date | Source | Topics | Reference |
|---|---|---|---|
| 2026-07-18 | Dave W / Claude discussion | Small-model adherence, Mellea pattern, text/code bright line, local-only harness | Preserved in `local-harness-proposal.md` |
| 2026-07-21 | Dave W / Dave J call | D4 ratification, bounded effort, 16 GB floor, simplicity-first ladder | Summarized in proposal/prior specification |
| 2026-07-21 through 2026-07-23 | Prior specification and implementation sessions | V1 provider scope, controller/state/validation design, model-signaled start, rollout adjustment | Prior spec/plan/prompt packs |
| 2026-07-24 | Real Ollama testing | Gemma 31B and Gemma 12B remained unguarded; 12B missed procedure/profile behavior | Local prompt/audit/conversation evidence |
| 2026-07-24 through 2026-07-26 | Current review | Starter-pack profile policy verification, guarded profile write mismatch, activation root cause, clean-branch redesign | Current Codex/user conversation and `profile_issue.md` |

## 44. Approval

- [ ] Product behavior reviewed by Dave W.
- [ ] Runtime/simplicity boundary reviewed by Dave J.
- [ ] Profile recognition/disposition contract accepted.
- [ ] Deterministic CTA entry contract accepted.
- [ ] Unconditional provider-independent activation and supported provider set accepted.
- [ ] No-runtime-switch/no-disabled-code-path boundary accepted.
- [ ] Section 31.4 quantitative bar accepted or explicitly amended before scored runs.
- [ ] Section 31.5 cloud no-regression bar accepted or explicitly amended before scored runs.
- [ ] Security/privacy/data-preservation review complete.
- [ ] Definition of Done read back and mutually confirmed.
- [ ] Ready for test-plan generation.
- [ ] Ready for implementation planning after test-plan acceptance.

---

Next step after review and approval: create the verification/test plan from this specification, including the thin real-model proof gate, before creating the implementation plan.
