# BrainDrive Process Guardrails Specification

## 1. Document Header

| Field | Value |
|---|---|
| Status | Ratified product direction; ready for test planning. Implementation remains gated by the quantitative local success/abort decision in OI-001 and cloud regression bar in OI-002. |
| Date | 2026-07-21 |
| Specification type | Feature / runtime enhancement |
| Intended audience | Dave W, Dave J, BrainDrive engineering, AI coding agents, QA/harness maintainers, security reviewers, and future runtime maintainers |
| Product | BrainDrive process guardrails |
| Primary repository | `BrainDriveAI/braindrive`, working tree `/home/hex/Project/BrainDrive-Test-01` |
| Affected application | TypeScript runtime and gateway under `builds/typescript/`; supported local and cloud provider lanes according to configured scope |
| Related systems | BrainDrive owner memory, starter-pack process instructions, runtime configuration, prompt-audit infrastructure, starter-pack testing harness, browser/runtime harness, Ollama, BrainDrive Models, and BYOK OpenRouter |
| Related decisions and work | D4 (ratified local-model harness direction, as reported in `info.md`); T-783 / Dave J commitment 7; T-764 fine-tune work; D289 small-model adherence finding; memory invariants M-1 through M-13 |
| Source document | `Braindrive-Guardrails/info.md`, including the 2026-07-21 ratification and provider-scope design update |
| Document owner | Dave W (product direction); Dave J (runtime implementation and production-flow boundary) |
| Revision summary | Defines one provider-independent guardrail contract with permanent `none` / `local` / `cloud` / `all` activation scope, defaulting to `all` when configuration is absent. Local models remain the first proof lane; cloud behavior is part of the release regression gate. |

### Approval State

- D4 ratifies the product direction and confirms the user stories as safe to plan against.
- The latest direction in `info.md` defines a permanent provider-scope control with `all` as normal product behavior and `none` as the baseline/rollback mode.
- OI-001 and OI-002 must be decided before implementation begins so local success and cloud regression thresholds cannot move after results are visible.
- After OI-001 and OI-002 are resolved, the next artifact is a verification plan, followed by a build plan.

## 2. Executive Summary

BrainDrive currently sends a conversation and its available tools through one open-ended agent loop. Small local models expose the failure most clearly, but every model remains responsible for remembering the full interview-to-artifact workflow, sequencing writes, following owner overrides, and recovering from incomplete output within one growing context. Existing evaluation evidence cited by the source material shows that this is a recurring adherence failure mode rather than only a prompt-authoring defect.

This feature adds one small process-control layer shared by supported local and cloud providers. It executes one product-defined process—interview, goals/specification, plan, and journal handoff—as explicit stages. Each stage receives only its owner-editable text instructions and the minimum required artifacts. Runtime code owns sequencing, deterministic validation, a single retry with feedback, resumability, and evidence. Text files continue to own voice, questions, criteria, and other judgment.

The V1 guardrails are deliberately narrow: one hardcoded process, deterministic validators, one fixed retry, locally stored append-only JSONL traces, no dashboard, no new UI, no workflow engine, no process-definition language, no mixed model routing, and no model-judged runtime gate. Activation is controlled by `BRAINDRIVE_PROCESS_GUARDRAILS_SCOPE`, whose accepted values are `none`, `local`, `cloud`, and `all`; an absent or empty value resolves to `all`. An explicit owner instruction may skip, reorder, redo, or stop any stage; the guardrails record and honor that override rather than fighting it.

The work succeeds only if it produces zero unrequested sequencing failures across the frozen evaluation set, materially improves end-to-end gate performance for at least one model that can run within a 16 GB MacBook-class system envelope, and meets a pre-decided no-regression bar for guarded cloud runs. Changing scope must not alter provider credentials, model selection, credits, tool authorization, or provider-specific API behavior.

## 3. Background and Context

### 3.1 Product Need

BrainDrive's owner-facing process is expressed primarily in plain-English memory files. The canonical memory architecture defines an owner-readable flow: orient, align through interview and `spec.md`, plan through `plan.md`, execute and learn through `journal.md`, then propagate material changes. This text-first approach supports owner control and model portability, but a small model can still fail to carry the full process across a long conversation.

The source material identifies repeated local-model failures such as skipped artifacts, plan-before-spec behavior, lost journal handoff, ignored process instructions, and open-ended loops. The proposed remedy is not to duplicate the behavioral prompt in code. It is to move only process guarantees into a narrow runtime controller while leaving judgment in owner-editable text.

### 3.2 Ratified Direction

The proposal was ratified as D4 on the 2026-07-21 Dave W / Dave J call, with the following governing constraints:

- Dave J owns the runtime build under T-783.
- Effort is bounded; complexity is added only when the preceding simpler form fails against an agreed gate.
- The simplicity-first ladder is part of the accepted framing.
- A model that requires more than a 16 GB MacBook-class system does not prove the owner-facing local-model bet.
- The guardrails express BrainDrive product guarantees for every supported model. Local is the first proof lane, while `none` / `local` / `cloud` / `all` is a permanent activation, testing, comparison, and rollback mechanism.

### 3.3 Verified Current Repository Behavior

The following facts were verified in `/home/hex/Project/BrainDrive-Test-01` on branch `dev`:

- `builds/typescript/gateway/server.ts` assembles the bootstrap prompt, selected skills, project context, prior conversation, and context-window result, then calls `runAgentLoop` once for the request.
- `builds/typescript/engine/loop.ts` implements a general model/tool loop. It has no explicit interview/spec/plan/journal process state.
- The engine currently retries an empty model completion once (`EMPTY_COMPLETION_MAX_RETRIES = 1`). It does not validate stage artifacts or retry a structurally invalid artifact.
- `builds/typescript/adapters/openai-compatible.json` defines `braindrive-models`, `openrouter`, and `ollama` profiles. The Ollama profile has `provider_id: "ollama"` and a local OpenAI-compatible base URL.
- `builds/typescript/adapters/index.ts` resolves the active provider profile and creates the same OpenAI-compatible adapter for all configured provider profiles.
- `builds/typescript/gateway/server.ts` exposes Ollama model discovery, pull, selection, and deletion behavior. Local-model support therefore exists; the older draft statement that it is unshipped is no longer accurate.
- Owner workflow behavior lives in starter-pack files such as page `AGENT.md`, `run-interview.md`, `run-planning.md`, and `run-journal.md`.
- Memory writes are performed through registered tools. Runtime safety guards already exist for repeated tool calls and destructive mutations, but not for process-stage completion.
- Optional prompt audit already writes sanitized, rotated JSONL under the owner's local memory diagnostics area. It defaults off, defaults to 14-day retention, and records request, response, tool, retry, and error events when enabled.
- Focused engine coverage exists in `builds/typescript/engine/loop.test.ts`; provider selection, config, gateway, memory, starter-pack layout, and web behavior have separate Vitest coverage.

### 3.4 Related Evaluation Infrastructure

The BrainDrive Library contains two complementary harness surfaces:

- `projects/active/foundation/starter-pack-testing-harness/` is the fast persona/model-evaluation lane. It consumes the real starter-pack files, uses Katie A/B/C scenarios, supports OpenRouter/Ollama-compatible runs, and emits transcripts, artifacts, provenance, deterministic gates, and judge output.
- `projects/active/foundation/braindrive-test-harness/` owns runtime/browser fidelity and verifies actual product behavior.

The offline conversational lane cannot prove runtime sequencing, actual file writes, UI behavior, or restart recovery by itself. Acceptance therefore requires both conversational evaluation and runtime-level evidence.

### 3.5 Canonical Memory Constraints

This feature must preserve the memory architecture's permanent invariants, especially:

- M-1 state/methodology separation.
- M-2 preservation of owner artifacts.
- M-3 and M-4 overlay read order and byte-for-byte overlay preservation.
- M-5 owner-write ownership.
- M-9 progressive disclosure.
- M-10 placement in the narrowest correct home.
- M-11 summary-based propagation.
- M-13 a thin, model-agnostic base prompt.

The guardrails do not create a parallel artifact universe. `spec.md`, `plan.md`, and `journal.md` remain the canonical owner artifacts in their established page locations.

## 4. Problem Statement

### 4.1 Affected Actor

The primary affected actor is any BrainDrive owner running an enabled provider. Privacy-motivated owners using Ollama are the first proof audience because local models expose the process-adherence problem most sharply. Owners using BrainDrive Models or BYOK OpenRouter are also affected when scope is `cloud` or `all`. Builders, QA operators, and maintainers need reproducible evidence about where any guarded run succeeded or failed.

### 4.2 Current Failure

When a model is asked to conduct a multi-stage owner process inside the current open-ended loop, it must simultaneously retain the long conversation, determine the current process stage, load the correct instructions, call the correct tools, preserve artifact ordering, handle owner redirection, and decide whether output is complete. Small local models fail this more often, but stronger hosted models can still skip writes, lose process state, call the wrong tool, or become difficult to recover and diagnose.

### 4.3 Required Outcome

For every enabled provider, the runtime must narrow each guarded model call to one explicit process stage, enforce only structural guarantees, validate the stage deterministically, retry one failed attempt with concrete feedback, and preserve enough local state to resume after interruption. Owner instructions must remain supreme, and behavioral judgment must remain in readable text.

### 4.4 Consequences of Leaving the Problem Unchanged

- Owners receive incomplete or incorrectly ordered artifacts.
- A failed long run must be repeated from the beginning.
- Builders cannot distinguish model capability failure from sequencing, tool, context, or prompt failure.
- Tuning may overfit prompts to test personas because the runtime offers no stable structural substrate.
- A fully local product claim remains unreliable on owner-class hardware, while cloud experiences remain less consistent than the product can make them.

### 4.5 Why Existing Workarounds Are Insufficient

- Adding more instructions increases context pressure and still relies on the model to self-sequence.
- Fine-tuning can improve adherence but cannot itself guarantee writes, retry caps, or resumability.
- The existing empty-completion retry handles a provider response with no usable output; it does not detect a structurally incomplete `spec.md` or `plan.md`.
- The offline harness can measure outcomes but cannot enforce behavior in the live product.

## 5. Goal

### 5.1 Primary Goal

Enable one complete BrainDrive owner process to run with the same structural guarantees across every configured provider scope, while proving material improvement for at least one Ollama-served model that fits a 16 GB MacBook-class system envelope and no material regression for guarded cloud providers.

### 5.2 Secondary Goals

- Make stage behavior changeable through text-file edits without runtime-code changes.
- Make failures attributable to a stage, validator, provider call, tool call, or owner override.
- Resume a partially completed process at the interrupted stage without repeating accepted stages.
- Produce bounded, local, privacy-preserving evidence suitable for QA and model comparison.
- Allow `none`, `local`, `cloud`, and `all` comparisons without separate guardrail implementations.
- Preserve provider credentials, credits, model selection, adapter behavior, and authorization across every scope.

### 5.3 Definition of Done for V1

V1 is done when all of the following are true:

1. The runtime resolves `BRAINDRIVE_PROCESS_GUARDRAILS_SCOPE` and applies the documented scope matrix to the resolved stable provider identity.
2. For an enabled provider, the runtime executes the hardcoded interview → goals/specification → plan → journal-handoff sequence as explicit stages.
3. Each stage loads its behavior from the canonical owner-editable text files and receives only required context.
4. Deterministic validation either accepts the first attempt or supplies one retry with machine-generated structural feedback.
5. An explicit owner override can skip, reorder, redo, or stop a stage without being blocked.
6. Accepted artifacts land in their existing memory-architecture locations and preserve owner content.
7. A process interrupted by a provider failure or runtime restart resumes at the first unfinished stage.
8. Every guarded run emits a minimal append-only locally stored trace, without raw owner content by default.
9. The agreed local success/abort bar in OI-001 and cloud regression bar in OI-002 pass on frozen, uncontaminated evaluation sets.
10. Automated tests prove `none`, `local`, `cloud`, `all`, missing-value, invalid-value, and unknown-provider behavior.

## 6. Non-Goals

- Creating provider-specific guardrail semantics or separate local and cloud implementations.
- Creating a general workflow engine, process-definition language, plugin surface, or owner-defined custom process system.
- Supporting more than one registered process in V1.
- Routing different stages to different models.
- Building a model-judged runtime quality gate in V1.
- Building a dashboard, metrics UI, progress wizard, or new Tier-0/Tier-2 settings surface.
- Replacing the current agent loop, provider adapter, memory-tool API, starter-pack architecture, or browser client.
- Fine-tuning, quantizing, packaging, or distributing the local model itself.
- Adopting Mellea or any Python dependency in the product runtime.
- Publishing the build-in-public content series.
- Changing provider credentials, models, credits, billing, tool authorization, or API behavior as part of guardrail activation.

## 7. In Scope

### 7.1 Runtime Control

- Parse and validate `BRAINDRIVE_PROCESS_GUARDRAILS_SCOPE`, with missing or empty configuration resolving to `all` and invalid non-empty configuration failing clearly.
- Classify supported providers from resolved stable `provider_id`: `ollama` as local; `braindrive-models` and `openrouter` as cloud.
- Apply the `none` / `local` / `cloud` / `all` activation matrix before process eligibility.
- Run one small explicit state machine around the existing model/tool capabilities for eligible requests on enabled providers.
- Use one hardcoded V1 process definition and fixed stage ordering, subject to owner override.
- Bound each stage to one initial attempt and at most one retry.
- Persist sufficient state to resume an interrupted run.

### 7.2 Text-Defined Behavior

- Load the existing page orientation and stage procedure files at the appropriate stage.
- Re-read stage behavior at the start of a new run so owner text changes take effect without code changes.
- Preserve base-plus-overlay read order.
- Keep tone, questions, criteria, and qualitative judgment out of guardrail code.

### 7.3 Artifact Contracts

- Validate that required artifacts exist in the expected page scope.
- Validate required structural sections without grading writing quality.
- Preserve existing owner content and memory routing.
- Treat the journal step as a handoff/eligibility stage under current memory semantics: the first interview/spec/plan session must not manufacture a journal entry merely to satisfy sequencing. A journal write occurs only when canonical `run-journal.md` rules say the conversation contains journal-worthy owner content.

### 7.4 Owner Control

- Recognize explicit skip, reorder, redo, stop, and resume instructions.
- Honor the override immediately.
- Adjust downstream prerequisites explicitly rather than converting an owner decision into a validation error.

### 7.5 Evidence and Diagnostics

- Emit minimal, append-only JSONL process events locally.
- Correlate process, stage, model call, tool calls, retry, override, and final state.
- Preserve detailed attempt content only when an explicit diagnostic/evaluation setting enables it.

### 7.6 Verification

- Add focused unit, integration, restart/recovery, privacy, and regression tests.
- Run the frozen Katie A/B/C evaluation assets without exposing those assets to the model instructions.
- Compare guarded and unguarded baselines across every supported provider using matched model, starter-pack revision, persona model, judge configuration, and test environment.

## 8. Out of Scope

- Any change to provider defaults, credentials, credits, billing, model selection, Ollama management, or provider-specific API configuration beyond the one guardrail-scope setting.
- Any new public HTTP endpoint or web-client control.
- A generalized process registry abstraction, even if the V1 implementation uses a small internal constant for the one process.
- Adaptive retries, per-stage retry budgets, exponential backoff, or model-specific branches.
- A runtime LLM judge. It may be proposed later only if deterministic gates plus one retry plateau below the agreed target.
- Automatic promotion of run attempts into training data. Export for T-764 requires a separate, owner-approved data contract.
- Raw transcript telemetry, cloud analytics, or network egress from the guardrail subsystem.
- Changes to the frozen gauntlet, persona definitions, or judge criteria made solely to improve this feature's score.
- Forcing a journal entry during initial alignment/planning when current journal rules say no entry belongs.
- Supporting models that only prove the approach on Spark/desktop-class memory while failing the 16 GB floor.

## 9. Stakeholders and Actors

| Actor | Relationship to the Feature |
|---|---|
| BrainDrive owner | Starts and redirects the process on any enabled provider; owns all resulting artifacts and may edit the behavior files. |
| Dave W | Product owner, Phase-A experiment owner, success-bar decision owner, and qualitative trust reviewer. |
| Dave J | Runtime implementation owner, reviewer of shared-path changes, and owner of the bounded-effort constraint. |
| BrainDrive TypeScript runtime | Resolves guardrail scope and provider class, controls stage state, invokes the existing model adapter and tools, and records evidence. |
| Ollama | Local OpenAI-compatible model server; returns completions and may time out, disconnect, or fail. |
| BrainDrive Models | Cloud provider profile subject to guardrails under `cloud` or `all`; credits and credential behavior remain unchanged. |
| BYOK OpenRouter | Cloud provider profile subject to guardrails under `cloud` or `all`; owner-key behavior remains unchanged. |
| Memory tools | Read and mutate owner files under existing authorization and safety contracts. |
| Starter-pack text files | Source of process behavior, page boundaries, artifact templates, and owner overlays. |
| Offline conversational harness | Measures model/content quality using frozen personas and gates; cannot by itself prove runtime correctness. |
| Runtime/browser harness | Proves live product activation, actual writes, recovery, and regression boundaries. |
| Security/privacy reviewer | Verifies scope resolution, provider classification, redaction, retention, no secret exposure, and no new guardrail telemetry egress. |

## 10. User Stories

### US-1 — Reliable Guarded Process — Confirmed (D4)

As a BrainDrive owner, I want BrainDrive to guide one defined process stage by stage so that the workflow remains reliable regardless of which enabled model provider I use.

Acceptance notes: maps to FR-001, FR-002, FR-004, FR-005, FR-016, NFR-001, and AC-001 through AC-005.

### US-2 — Owner Override Wins — Confirmed (D4)

As an owner, I want to skip, reorder, redo, or stop any stage by saying so, so that runtime guarantees never become constraints on me.

Acceptance notes: maps to FR-006, FR-016, NFR-006, AC-006, and AC-007.

### US-3 — Text-Editable Behavior — Confirmed (D4)

As an owner or product maintainer, I want to change a stage's voice, questions, or qualitative criteria by editing its text file so that behavioral ownership remains outside code.

Acceptance notes: maps to FR-003, NFR-005, AC-008, and AC-009.

### US-4 — Bounded Structural Recovery — Confirmed (D4)

As an owner, I want an incomplete stage to receive one automatic correction attempt and then a clear recovery path so that BrainDrive neither silently accepts a broken artifact nor loops indefinitely.

Acceptance notes: maps to FR-007, FR-008, FR-009, NFR-002, AC-010 through AC-013.

### US-5 — Resume Without Repeating Work — Confirmed (D4)

As a BrainDrive owner, I want an interrupted process to resume at the unfinished stage so that completed interviews and accepted artifacts are not lost or regenerated.

Acceptance notes: maps to FR-011, NFR-007, AC-016 and AC-017.

### US-6 — Inspectable Local Evidence — Confirmed (D4)

As a builder or QA operator, I want every guarded run to emit a locally inspectable trace so that failures and evaluation claims are grounded in evidence.

Acceptance notes: maps to FR-012, NFR-003, NFR-004, AC-018 through AC-020.

### US-7 — Configurable Provider Scope — Confirmed by 2026-07-21 Design Update

As a builder or operator, I want to apply guardrails to none, local providers, cloud providers, or all supported providers so that I can compare behavior, stage rollout, and recover safely without maintaining separate implementations.

Acceptance notes: maps to FR-001, FR-013, FR-015, NFR-008, AC-001, AC-021, and AC-022.

## 11. Use Cases and Operational Scenarios

### UC-1 — Successful Guarded Run

- Preconditions: configured scope enables the resolved supported provider; page has the canonical procedure and artifact files; no active conflicting process run exists.
- Trigger: the owner asks to begin or continue the registered align/plan process.
- Main flow: runtime starts a process identity, loads the current stage instructions, supplies minimal context, accepts deterministic-valid output, persists the artifact, advances, completes journal handoff, and closes the run.
- Alternate flow: a stage needs several conversational turns; the stage remains active until its completion contract is invoked.
- Failure flow: an invalid artifact follows UC-3; a provider interruption follows UC-4.
- Expected final state: `COMPLETED`, with canonical artifacts and a completed trace.
- User-visible result: normal BrainDrive conversation; no forced wizard or model-process chrome.
- Operational result: trace contains stage sequence, durations, validation outcomes, tool results, and model identity without raw content by default.

### UC-2 — Owner Skips the Specification

- Preconditions: guarded run is in interview or specification stage.
- Trigger: owner explicitly says to skip the specification and proceed to planning.
- Main flow: runtime marks the skipped stage as `SKIPPED_BY_OWNER`, records the verbatim-free override category, and starts planning with an explicit `upstream_artifact_absent_by_owner_choice` condition.
- Alternate flow: owner later asks to create the specification; runtime starts that stage as a redo/new stage and may then offer to reconcile the plan.
- Failure flow: the plan validator must not fail only because the intentionally skipped spec is absent.
- Expected final state: process may complete with a skipped spec, and the trace identifies why.
- User-visible result: BrainDrive complies without arguing or labeling the owner action as an error.
- Operational result: sequence deviation is attributable to owner choice rather than model failure.

### UC-3 — Deterministic Validation Failure

- Preconditions: a stage produces or mutates an artifact.
- Trigger: required file, required structural section, or write-placement check fails.
- Main flow: runtime rejects the attempt, preserves the prior accepted artifact, generates structural feedback, and retries the stage once.
- Alternate flow: retry passes and replaces only the unaccepted candidate.
- Failure flow: retry fails; runtime surfaces the best safe candidate and a plain-language weakness summary, marks the stage `NEEDS_OWNER_ACTION`, and stops automatic advancement.
- Expected final state: no corrupt or silently incomplete canonical artifact is treated as accepted.
- User-visible result: clear explanation and choices to edit, retry manually, skip, or stop.
- Operational result: both validation outcomes and retry count appear in the trace.

### UC-4 — Provider Failure and Resume

- Preconditions: one or more stages are accepted and the current stage is active.
- Trigger: the active provider is unavailable, times out, disconnects, rate-limits, or returns an unrecoverable provider error.
- Main flow: runtime persists the current stage state, leaves accepted artifacts unchanged, records the provider error, and marks the run `PAUSED_RECOVERABLE`.
- Alternate flow: owner selects resume after the provider is available; runtime revalidates accepted artifacts and restarts only the unfinished stage.
- Failure flow: saved state is unreadable; runtime does not overwrite it and asks the owner to start a new guarded run or use the intact artifacts manually.
- Expected final state: either resumed completion or an explicit recoverable stop.
- User-visible result: stage-specific message without a stack trace.
- Operational result: correlation between the failed model call and resumed stage is retained.

### UC-5 — Scope-Controlled Provider Request

- Preconditions: scope and resolved supported provider are known.
- Trigger: any message that is eligible for the registered process.
- Main flow: `none` bypasses every provider; `local` enables only Ollama; `cloud` enables BrainDrive Models and OpenRouter; `all` enables every explicitly classified supported provider.
- Alternate flow: missing or empty scope resolves to `all`.
- Failure flow: invalid non-empty scope fails configuration clearly; an unknown provider identity does not enter guardrails even under `all`.
- Expected final state: enabled providers may start guarded state; disabled or unknown providers use the existing unguarded path.
- User-visible result: no configuration mechanics appear in normal chat.
- Operational result: sanitized diagnostics record configured scope, resolved scope, provider identity/class, and activation decision.

### UC-6 — Owner Edits a Behavior File

- Preconditions: owner or maintainer changes an applicable managed text file through an authorized update path or changes an owner overlay.
- Trigger: the next new guarded run reaches that stage.
- Main flow: runtime reads managed base then matching owner overlay; the stage reflects the new behavioral instruction.
- Failure flow: file is missing or unreadable; runtime does not fall back to embedded behavioral text and instead reports the missing prerequisite.
- Expected final state: code remains unchanged; behavior changes only within higher-level safety and preservation rules.

## 12. Current Behavior

### 12.1 Verified Request Flow

1. `gateway/server.ts` persists the owner message and resolves page/project context.
2. The gateway reads the bootstrap prompt, composes skills, adds project context, and constructs the context window.
3. The gateway resolves live preferences, provider profile, provider credential, and model.
4. `createModelAdapter` builds an OpenAI-compatible adapter for the resolved profile.
5. `runAgentLoop` repeatedly calls the model, streams assistant text, executes tool calls, and stops when the model returns no tool calls.
6. Conversation messages and tool messages are persisted by the gateway.

### 12.2 Verified State and Retry Behavior

- The loop tracks model iterations and repeated identical tool calls in memory for the current request.
- An empty completion receives one retry. Other provider failures terminate the request with a classified error.
- There is no durable process-run state, stage identity, stage-specific context, artifact acceptance state, or process resume token.
- A tool result can be recoverable or non-recoverable, but there is no stage-level recovery policy.

### 12.3 Verified Persistence and Diagnostics

- Owner conversation and memory artifacts are file-backed.
- Prompt audit is optional and local. When enabled, it writes sanitized JSONL with trace, conversation, correlation, model-call, provider, tool, and error evidence.
- Prompt audit is not a sufficient process-state store because it defaults off and its event vocabulary does not include process stages or artifact acceptance.

### 12.4 Strong Inferences

- The smallest integration boundary is around or immediately before the existing `runAgentLoop` call, after the effective provider has been resolved. Exact module ownership belongs in the build plan.
- Existing prompt-audit primitives can inform the new trace format, but process evidence must not depend on enabling content-rich prompt audit.

### 12.5 Assumptions in Earlier Draft That Are Now Incorrect

- Ollama is already represented in the provider configuration and gateway settings path.
- The current runtime has no guardrail-scope setting or provider-class activation matrix.
- A first alignment/planning session must not create an artificial journal entry merely to claim the journal stage ran; canonical journal procedure rules still govern actual journal writes.

## 13. Target Behavior

### 13.1 Entry and Eligibility

After resolving configuration and the effective provider, the runtime evaluates three independent conditions:

1. Scope eligibility: configured `none`, `local`, `cloud`, or `all` permits the explicitly classified resolved provider; missing or empty configuration resolves to `all`.
2. Provider eligibility: stable `provider_id` is a supported classified provider (`ollama` local; `braindrive-models` or `openrouter` cloud).
3. Process eligibility: the active page and owner intent match the one registered V1 process, or a persisted run for that conversation is resumable.

The activation matrix is:

| Resolved Scope | Ollama (`local`) | BrainDrive Models (`cloud`) | OpenRouter (`cloud`) |
|---|---:|---:|---:|
| `none` | Off | Off | Off |
| `local` | On | Off | Off |
| `cloud` | Off | On | On |
| `all` | On | On | On |

Missing or empty scope resolves to `all`. Invalid non-empty scope is a configuration error. An unknown provider identity remains unguarded until explicitly classified, including when scope is `all`.

If either condition is false, the runtime uses the existing flow without guardrail side effects.

### 13.2 Stage Execution

For an eligible run, the runtime:

1. Creates or resumes a stable process identity.
2. Determines the active stage from durable state.
3. Loads only the managed stage instructions, applicable owner overlay, owner input needed for the stage, and accepted prerequisite artifacts.
4. Invokes the existing model adapter and allowed tools.
5. Validates deterministic completion and write placement.
6. Accepts and advances, or retries once with structural feedback.
7. Persists state before exposing a transition as complete.

### 13.3 Context Narrowing

The model request for a stage must exclude unrelated page history, frozen test material, downstream stage instructions, and artifacts not named by that stage's contract. System-level safety and authorization context remains present. Narrowing must not omit an explicit current-turn owner instruction or an applicable owner overlay.

### 13.4 Validation

V1 validation is structural and deterministic. It may check:

- expected path is within the active page scope;
- expected artifact exists when the owner has not skipped it;
- required stable sections are present once each;
- the operation did not replace or remove protected owner content;
- the attempted write obeys the relevant preservation contract;
- the journal handoff respects journal eligibility rather than forcing content;
- retry count has not exceeded one.

V1 validation must not score empathy, tone, insight, usefulness, specificity, or prose quality in runtime code.

### 13.5 Owner Overrides

An explicit owner instruction takes precedence over default sequence. The runtime records a normalized override category and updates stage prerequisites. It does not require a special UI control. Ambiguous statements are handled conversationally by the active stage; only explicit owner direction changes process state.

### 13.6 Failure and Recovery

- Provider interruption pauses the run after durable state is saved.
- Missing instruction files stop the affected stage without using a hidden prompt fallback.
- Invalid first output receives one retry.
- Invalid retry stops automatic advancement and gives the owner recovery choices.
- Artifact persistence failure never produces an accepted-stage transition.
- Resume revalidates accepted artifact references before continuing.

### 13.7 Completion

A run completes when each stage is `ACCEPTED`, `SKIPPED_BY_OWNER`, or, for journal handoff, `HANDOFF_COMPLETE_NO_ENTRY` or `ACCEPTED`. Completion does not imply that every possible artifact was written; it means every required stage outcome was resolved according to owner choice and canonical process rules.

## 14. Functional Requirements

### FR-001 — Provider-Scope Activation

- Priority: Must.
- Requirement: The guardrail controller shall activate according to `BRAINDRIVE_PROCESS_GUARDRAILS_SCOPE`, whose accepted values are `none`, `local`, `cloud`, and `all`.
- Rationale: One shared architecture needs controlled baselines, provider-lane comparisons, staged configuration, and emergency rollback without semantic forks.
- Preconditions: Effective provider profile has been resolved and runtime configuration is available.
- Required behavior: Missing or empty scope resolves to `all`; `none` enables no provider; `local` enables `ollama`; `cloud` enables `braindrive-models` and `openrouter`; `all` enables all explicitly classified supported providers. Compare stable provider identity, not display label, model name, base-URL substring, or client metadata.
- Expected result: Every supported provider enters or bypasses process eligibility exactly according to the scope matrix.
- Error behavior: Invalid non-empty scope is a clear configuration error. Unknown provider identity remains unguarded even under `all` until its class is explicitly declared.
- Acceptance criteria: AC-001 and AC-021.

### FR-002 — Single Registered V1 Process

- Priority: Must.
- Requirement: V1 shall support exactly one product-defined process: interview → goals/specification → plan → journal handoff.
- Rationale: D4's simplicity-first constraint rejects a generalized workflow system before a second real process exists.
- Preconditions: FR-001 enables the resolved provider and owner intent is eligible.
- Required behavior: Use a fixed stage set and artifact contracts; do not expose owner-authored process definitions.
- Expected result: The registered process has a deterministic initial stage and terminal condition.
- Error behavior: Unknown process identifiers are not executed and fall back to normal conversation with an internal diagnostic.
- Acceptance criteria: AC-002 and AC-023.

### FR-003 — Text-Defined Stage Behavior

- Priority: Must.
- Requirement: Voice, questions, qualitative criteria, domain guidance, and owner customization shall be read from canonical text files rather than embedded in guardrail code.
- Rationale: Owner-editability is a non-negotiable BrainDrive product property.
- Preconditions: Applicable page and stage are known.
- Required behavior: Read managed base first and applicable `*-user.md` overlay second; re-read at the start of each new guarded run.
- Expected result: A behavior-only text edit affects the next run without a TypeScript change.
- Error behavior: Missing or unreadable required instructions stop the stage with a named-file diagnostic; no hidden behavioral fallback is used.
- Acceptance criteria: AC-008, AC-009, and AC-014.

### FR-004 — Stage-Scoped Context

- Priority: Must.
- Requirement: Each stage model call shall contain only system safety context, active owner direction, the stage's text instructions, applicable overlays, and artifacts explicitly required by that stage.
- Rationale: Context narrowing reduces small-model adherence failures and makes process behavior more deterministic and diagnosable for stronger models.
- Preconditions: Active stage and prerequisite artifacts are known.
- Required behavior: Exclude downstream instructions, unrelated project artifacts, and frozen evaluation content.
- Expected result: Traceable context assembly proves the stage boundary without recording raw content by default.
- Error behavior: If a required artifact is absent for a reason other than owner override, the stage does not call the model and reports the prerequisite failure.
- Acceptance criteria: AC-003 and AC-024.

### FR-005 — Deterministic Default Sequencing

- Priority: Must.
- Requirement: In the absence of an owner override, the runtime shall not accept plan completion before the goals/specification outcome and shall not declare process completion before journal handoff is resolved.
- Rationale: Sequencing is the primary runtime guarantee.
- Preconditions: Active guarded run with no applicable override.
- Required behavior: Advance only after durable acceptance of the current stage.
- Expected result: Zero unrequested out-of-order transitions across the release evaluation set.
- Error behavior: An attempted downstream write is rejected as a recoverable stage violation and supplied to the model as structural feedback within the retry budget.
- Acceptance criteria: AC-004 and AC-005.

### FR-006 — Owner Override Supremacy

- Priority: Must.
- Requirement: An explicit owner instruction shall be able to skip, reorder, redo, stop, or resume any stage.
- Rationale: BrainDrive must not force a process against owner intent.
- Preconditions: Owner direction is explicit enough to determine the requested state change.
- Required behavior: Apply the override, record its normalized category, and adapt downstream prerequisites.
- Expected result: The owner is obeyed without a validation block or argumentative response.
- Error behavior: Ambiguous direction remains conversational and does not mutate stage state until clarified.
- Acceptance criteria: AC-006 and AC-007.

### FR-007 — Deterministic Artifact Validation

- Priority: Must.
- Requirement: The runtime shall validate structural completion, correct scope, and preservation rules before accepting a stage artifact.
- Rationale: Structural guarantees belong in code and prevent silent incomplete writes.
- Preconditions: A stage claims completion or produces a candidate artifact.
- Required behavior: Validate path, existence, stable required sections, duplicate-section constraints, owner-content preservation, and stage-specific outcome.
- Expected result: Only structurally valid candidates become accepted artifacts.
- Error behavior: Validation produces machine-readable failure codes and a plain-language feedback summary without changing the prior accepted artifact.
- Acceptance criteria: AC-010 and AC-015.

### FR-008 — One Retry With Feedback

- Priority: Must.
- Requirement: A first deterministic validation failure shall permit exactly one automatic retry of the same stage with the failed checks supplied as feedback.
- Rationale: One retry captures the highest-value recovery without unbounded loops or adaptive policy complexity.
- Preconditions: First attempt failed deterministic validation and owner has not stopped or redirected.
- Required behavior: Increment a durable retry counter before the retry call.
- Expected result: Total automatic attempts per stage outcome never exceeds two.
- Error behavior: A process restart does not reset the retry counter.
- Acceptance criteria: AC-011 and AC-012.

### FR-009 — Validation Exhaustion Behavior

- Priority: Must.
- Requirement: After the retry fails, the runtime shall stop automatic advancement and surface the safest available candidate plus a plain-language structural weakness summary and recovery choices.
- Rationale: Silent bad output and infinite loops are both unacceptable.
- Preconditions: FR-008 retry has failed.
- Required behavior: Mark the stage `NEEDS_OWNER_ACTION`; offer manual edit, explicit retry, skip, or stop.
- Expected result: The owner retains control and accepted prior state remains intact.
- Error behavior: If no safe candidate exists, surface only the failure summary and choices.
- Acceptance criteria: AC-013.

### FR-010 — Canonical Artifact Placement and Journal Semantics

- Priority: Must.
- Requirement: Accepted artifacts shall use existing page locations and memory contracts; journal handoff shall not fabricate an initial-session entry.
- Rationale: Guardrails may enforce process structure but may not redefine owner memory.
- Preconditions: Stage produces or evaluates an artifact write.
- Required behavior: Apply M-1 through M-11 as relevant; preserve owner-authored content; follow `run-journal.md` eligibility for an actual journal write.
- Expected result: No parallel guardrail artifacts appear in owner-facing memory, and no empty or synthetic journal entry is created.
- Error behavior: Wrong-scope or destructive writes are rejected before stage acceptance.
- Acceptance criteria: AC-015, AC-025, and AC-026.

### FR-011 — Durable Resume

- Priority: Must.
- Requirement: Guarded runs shall persist enough state to resume at the first unfinished stage after provider failure or runtime restart.
- Rationale: Provider and runtime interruptions must not discard completed owner work.
- Preconditions: A process has started and is not terminal.
- Required behavior: Persist process identity, stage states, retry counts, accepted artifact references/digests, and last transition before reporting the transition complete.
- Expected result: Resume never regenerates an accepted stage unless the owner requests redo or revalidation detects incompatible artifact change.
- Error behavior: Corrupt state is preserved for diagnosis; the runtime does not overwrite it or guess a transition.
- Acceptance criteria: AC-016 and AC-017.

### FR-012 — Locally Stored Process Trace

- Priority: Must.
- Requirement: Every guarded run shall emit an append-only JSONL trace stored locally and independent of optional content-rich prompt audit.
- Rationale: QA claims and recovery need ground truth even when prompt audit is disabled.
- Preconditions: A guarded run is instantiated.
- Required behavior: Record schema version, timestamps, process/run ID, conversation/correlation IDs, provider/model identifiers, stage transitions, validator codes, retry counts, override categories, tool result status, durations, and terminal state.
- Expected result: An operator can reconstruct what happened without raw owner text.
- Error behavior: Trace persistence failure does not expose content or falsely report success; it marks the run diagnostically degraded and is surfaced before acceptance testing claims are made.
- Acceptance criteria: AC-018 through AC-020.

### FR-013 — Scope and Provider Preservation

- Priority: Must.
- Requirement: Scope selection shall change only whether an eligible request enters the shared guardrail controller; it shall not change provider credentials, credits, model selection, adapter behavior, tool authorization, persistence contracts, or streaming/API behavior.
- Rationale: Provider scope is an activation boundary, not a provider implementation fork.
- Preconditions: Scope and effective provider identity/class have been resolved.
- Required behavior: Disabled providers use the existing unguarded path without process state, stage prompts, validation calls, or process trace events. Enabled providers use the same guardrail semantics.
- Expected result: `none`, `local`, `cloud`, and `all` comparisons differ only in guardrail entry for the documented provider matrix.
- Error behavior: Provider classification uncertainty uses the unguarded path and emits a sanitized diagnostic; it never guesses from URL or model name.
- Acceptance criteria: AC-021 and AC-022.

### FR-014 — Evaluation Isolation and Anti-Overfit

- Priority: Must.
- Requirement: Frozen gauntlet prompts, persona literals, judge mechanics, and expected answers shall never be placed in stage instructions, runtime feedback, or model-training exports.
- Rationale: Passing by memorizing the test invalidates the product claim.
- Preconditions: Any change to stage instructions, validators, or evaluation assets.
- Required behavior: Apply the existing harness anti-overfit scan and blinded comparison practices.
- Expected result: Behavior remains general to unseen owners.
- Error behavior: A contamination finding invalidates the run set and blocks acceptance until removed and rerun.
- Acceptance criteria: AC-024.

### FR-015 — Scope Configuration and Rollback

- Priority: Must.
- Requirement: One enum-valued environment variable shall control provider scope permanently, with `all` as the default when the variable is absent or empty and `none` as the complete rollback/baseline mode.
- Rationale: The team needs controlled testing and rollback without a feature-flag platform or separate local/cloud implementations.
- Preconditions: Runtime configuration is loading.
- Required behavior: Normalize case and trim whitespace; accept only `none`, `local`, `cloud`, and `all`; expose the resolved value to the activation boundary; record configured/resolved scope in sanitized diagnostics.
- Expected result: Changing the value and reloading according to existing configuration semantics changes only future guardrail entry, never owner artifacts or completed traces.
- Error behavior: Invalid non-empty configuration fails startup/config loading clearly rather than silently selecting another scope.
- Acceptance criteria: AC-027 and AC-028.

### FR-016 — Explicit Terminal States

- Priority: Must.
- Requirement: Every guarded run shall finish in exactly one explicit terminal or resumable state.
- Rationale: Owners and operators must distinguish completion, owner stop, recoverable pause, validation exhaustion, and unrecoverable state corruption.
- Preconditions: A run has started.
- Required behavior: Use the state model in Section 18 and emit the final state once.
- Expected result: No run remains implicitly active after its request stream ends.
- Error behavior: Unexpected internal exceptions persist `FAILED_INTERNAL` when possible and return a sanitized owner-facing error.
- Acceptance criteria: AC-005, AC-013, AC-017, and AC-020.

## 15. Non-Functional Requirements

| ID | Priority | Requirement | Measurable Acceptance |
|---|---|---|---|
| NFR-001 | Must | Reliability | Zero unrequested sequencing failures across the frozen release evaluation set; every run has one terminal/resumable state. |
| NFR-002 | Must | Bounded execution | No stage outcome causes more than two automatic model attempts; no retry counter resets after restart. |
| NFR-003 | Must | Privacy | Default product traces contain no raw owner messages, prompts, artifact bodies, provider payloads, credentials, or secrets. |
| NFR-004 | Must | Auditability | Each accepted transition can be tied to one run ID, stage, validator result, artifact reference/digest, and timestamp. |
| NFR-005 | Must | Maintainability / ownership | A behavior-only change to voice, questions, or qualitative criteria requires no TypeScript modification and passes the standing owner-edit eval. |
| NFR-006 | Must | Trust and usability | Explicit owner overrides are obeyed on the next state transition and never represented as model failure. |
| NFR-007 | Must | Data integrity / recovery | Accepted artifacts survive provider failure and restart without duplication, truncation, or silent replacement. |
| NFR-008 | Must | Compatibility | Every scope/provider pair matches the activation matrix; disabled providers show no added model calls, retries, trace writes, or process latency, while enabled providers retain existing provider/API contracts. |
| NFR-009 | Must | Privacy boundary | Guardrail execution and diagnostics add no network destination beyond the provider and existing product services already used by the request; guardrail traces remain locally stored. |
| NFR-010 | Must | Portability | Acceptance includes at least one qualifying local model demonstrated within a 16 GB MacBook-class total system-memory envelope, including OS and BrainDrive headroom. |
| NFR-011 | Should | Performance evidence | Traces record stage and total durations and model attempts so guarded-vs-baseline latency can be compared; V1 sets no unsupported fixed latency target. |
| NFR-012 | Must | Simplicity | V1 introduces no workflow-engine dependency, Python runtime dependency, process DSL, model judge, dashboard, adaptive retry, or second registered process. |

## 16. Business Rules and Invariants

1. Provider scope invariant: only an explicitly classified supported provider enabled by resolved `none` / `local` / `cloud` / `all` scope can enter the guardrail path; missing or empty scope resolves to `all`.
2. Owner supremacy invariant: an explicit owner instruction can override every default stage transition.
3. Behavior/code bright line: code owns structure, sequencing, bounded retry, persistence, and deterministic safety; text owns judgment and interaction behavior.
4. Artifact authority invariant: existing owner memory files remain canonical; traces and run state are diagnostics, not owner-facing substitutes.
5. Preservation invariant: a failed or unaccepted attempt cannot destroy the last accepted owner artifact.
6. Acceptance-before-advance invariant: default stage advancement occurs only after durable acceptance.
7. Retry invariant: at most one automatic retry per stage outcome, including across restart.
8. Disabled-provider invariant: a provider disabled by the resolved scope creates no guardrail state or trace; enabled providers receive identical core guardrail semantics.
9. No-cheating invariant: frozen evaluation inputs never appear in production instructions, feedback, or training exports.
10. Local privacy invariant: default trace metadata excludes raw owner content and secrets.
11. Journal integrity invariant: journal handoff is always resolved, but a journal entry is written only when canonical journal rules require one.
12. Model identity invariant: no new Tier-0 model or guardrail chrome is introduced.
13. Memory placement invariant: profile, page specification, plan, journal, and propagation rules continue to follow M-10 and M-11.
14. Bounded-complexity invariant: a new abstraction is not admitted to V1 merely because it might be useful for a hypothetical second process.

## 17. Domain Model

### 17.1 Guarded Process

- Purpose: durable identity and lifecycle for one guarded owner process.
- Identity: stable opaque run ID scoped to one owner installation and conversation.
- Important fields: schema version, conversation ID, page ID, process kind, provider identity, model identity, creation/update times, active stage, terminal state.
- Ownership: system-managed local diagnostics state; references owner artifacts but is not itself owner content.
- Lifecycle: created, active, paused/needs action, completed/stopped/failed, retained, expired.
- Invalid states: two active stages; completed without all stages resolved; provider not enabled by the recorded scope; retry count below recorded attempts.
- Persistence: durable across gateway restart; exact storage module is a build-plan decision.

### 17.2 Process Stage

- Purpose: one bounded unit of model behavior and artifact outcome.
- Identity: run ID plus stable stage kind.
- Stage kinds: `interview`, `specification`, `plan`, `journal_handoff`.
- Important fields: status, attempt count, instruction references/digests, required artifact references, candidate result, validator results, owner override, start/end times.
- Relationships: belongs to one guarded process; may depend on accepted or owner-skipped upstream stages.
- Valid states: `PENDING`, `ACTIVE`, `VALIDATING`, `RETRY_PENDING`, `ACCEPTED`, `SKIPPED_BY_OWNER`, `HANDOFF_COMPLETE_NO_ENTRY`, `NEEDS_OWNER_ACTION`, `PAUSED_RECOVERABLE`, `STOPPED_BY_OWNER`, `FAILED_INTERNAL`.
- Invalid states: `ACCEPTED` without a passing validator when an artifact is required; more than two automatic attempts.

### 17.3 Artifact Contract

- Purpose: structural definition of what a stage may read, write, and accept.
- Identity: process kind plus stage kind plus contract version.
- Important fields: permitted scope, required/optional artifact, stable section requirements, preservation checks, downstream availability rules.
- Ownership: product runtime for structural properties; no voice, qualitative rubric, or domain answer content.
- Compatibility: contract versions must allow resume or explicitly stop incompatible old state without guessing.

### 17.4 Stage Instructions

- Purpose: owner-readable behavioral definition for a stage.
- Identity: canonical managed file plus optional owner overlay.
- Important properties: text content, read order, content digest for evidence.
- Ownership: managed base belongs to BrainDrive; overlay belongs to owner and is preserved byte-for-byte during starter-pack updates.
- Lifecycle: read at run start; changed content applies to a new run. Mid-run edit handling follows Section 25.

### 17.5 Process Trace Event

- Purpose: append-only evidence for reconstruction and QA.
- Identity: run ID plus monotonically ordered event sequence or timestamp/order pair.
- Important fields: schema version, event name, stage, attempt, IDs, status, codes, durations, sanitized metadata.
- Ownership: local system diagnostics.
- Retention: 14 days by default, aligning with existing prompt-audit defaults; configurable within existing local preference constraints in a later build decision only if needed.

## 18. State Model

### 18.1 Process Transitions

| Current State | Event | Conditions | Next State | Side Effects |
|---|---|---|---|---|
| No run | Eligible guarded process starts | Scope enables classified provider + eligible intent | `ACTIVE` | Create run, set interview active, emit start event. |
| `ACTIVE` | Stage candidate produced | Write/tool result available | `VALIDATING` | Persist candidate reference and validator start. |
| `VALIDATING` | All checks pass | First or retry attempt | `ACTIVE` or `COMPLETED` | Accept artifact, persist transition, activate next unresolved stage or finish. |
| `VALIDATING` | Checks fail | First attempt | `RETRY_PENDING` | Persist codes and increment retry counter. |
| `RETRY_PENDING` | Retry begins | Owner has not redirected | `ACTIVE` | Supply structural feedback and invoke same stage. |
| `VALIDATING` | Checks fail | Retry exhausted | `NEEDS_OWNER_ACTION` | Preserve accepted prior state, surface recovery choices. |
| `ACTIVE` | Owner skips/reorders/redoes | Explicit instruction | `ACTIVE` | Record override and activate requested stage/outcome. |
| `ACTIVE` or `VALIDATING` | Owner stops | Explicit instruction | `STOPPED_BY_OWNER` | Persist terminal state; no further automatic calls. |
| Any nonterminal | Provider/runtime interruption | State persist succeeds | `PAUSED_RECOVERABLE` | Record failure; leave accepted artifacts intact. |
| `PAUSED_RECOVERABLE` | Resume | State and references valid | `ACTIVE` | Continue first unfinished stage. |
| `PAUSED_RECOVERABLE` | Resume validation fails | State/artifact incompatibility | `NEEDS_OWNER_ACTION` | Explain mismatch; do not guess or overwrite. |
| Any nonterminal | Unexpected internal failure | Best-effort state write | `FAILED_INTERNAL` | Sanitized error and diagnostic event. |

### 18.2 Forbidden Transitions

- Provider disabled by scope or unknown provider identity → any guarded process state.
- `ACCEPTED` stage → `PENDING` without explicit owner redo or version reconciliation.
- First validation failure → second retry beyond the one-retry cap.
- `COMPLETED` → automatic model call.
- `STOPPED_BY_OWNER` → resume without a new explicit owner instruction.
- Missing unskipped prerequisite → downstream accepted state.
- Journal handoff → synthetic journal content solely to satisfy the state machine.

## 19. Data Requirements

| Data | Read/Create/Update/Delete | Source of Truth | Lifetime and Integrity | Sensitivity / Redaction |
|---|---|---|---|---|
| Process state | Create/update; expire after retention only when terminal | Guardrail state store under local memory diagnostics | Durable before acknowledged transitions; schema-versioned; corrupt state preserved | IDs and status are diagnostic; no raw content required |
| Stage instruction content | Read only by runtime | Canonical managed text plus owner overlay | Read according to overlay order; overlay preserved | May contain owner preferences; body excluded from minimal trace |
| Owner artifacts | Read/update through existing memory tools | Existing page `spec.md`, `plan.md`, `journal.md`, and profile as applicable | Existing history/preservation semantics; no guardrail-owned copies | Owner-sensitive; never copied to default trace |
| Candidate attempt | Create/update until accepted or exhausted | Transient/durable recovery record selected in build plan | Must survive retry/restart if needed; safe candidate may be offered to owner | Content retention off by default in product; eval mode may retain with explicit setup |
| Trace events | Append only | Local guardrail JSONL | 14-day default; rotation behavior should reuse proven prompt-audit semantics where practical | Redact secrets; omit message/artifact bodies by default |
| Evaluation reports | Create outside product runtime | Harness output directories | Retained with provenance according to harness project practice | Test personas only; no real-owner data in release evidence |

No schema migration of owner artifacts is required. New runtime state must be versioned independently. Deleting or disabling guardrail diagnostics must never delete `spec.md`, `plan.md`, `journal.md`, conversations, or owner overlays.

## 20. API and Interface Requirements

### 20.1 Public API

V1 adds no public HTTP endpoint and changes no existing request or SSE response schema. Existing clients continue to send ordinary chat messages and receive existing stream events.

### 20.2 Internal Behavioral Interface

The implementation shall provide an internal boundary capable of:

- resolving guardrail scope, classifying the effective provider, and deciding activation;
- starting or resuming a guarded process;
- requesting the next stage-scoped model/tool execution;
- accepting model/tool outcomes;
- validating a candidate;
- applying an owner override;
- returning an existing `StreamEvent` sequence and terminal/resumable outcome;
- writing sanitized trace events.

Exact function names, module paths, and TypeScript types are build-plan decisions. The interface must not require the web client to understand stage state.

### 20.3 Configuration Interface

One validated environment variable, `BRAINDRIVE_PROCESS_GUARDRAILS_SCOPE`, controls activation. Accepted values are `none`, `local`, `cloud`, and `all`; values are case-insensitive after trimming. Missing or empty resolves to `all`. Invalid non-empty values fail configuration clearly. The setting must not be stored inside provider secrets, contain a credential, or affect provider credits, keys, model selection, or authorization.

### 20.4 UI Interface

- No new entry point, button, progress stepper, or modal.
- Existing chat remains the only owner-facing interaction surface.
- Existing loading/streaming and error rendering remain compatible.
- Recovery choices are delivered in conversation using existing assistant text.

## 21. External Integration Requirements

### 21.1 Ollama

- Purpose: local model inference through the existing OpenAI-compatible profile.
- Authentication: retain current Ollama credential behavior; introduce no BrainDrive-owned key.
- Required permission: local network access to the configured Ollama origin only.
- Request behavior: stage-scoped requests use the existing adapter contract.
- Timeout/error mapping: use existing provider classification, augmented with stage/run correlation.
- Retry behavior: provider-level empty-completion retry and stage-validation retry must be counted and distinguishable. Stage retry does not authorize unbounded provider retries.
- Ambiguous outcome: model calls alone do not mutate external resources; artifact writes are reconciled from local tool results and persisted state.
- Availability assumption: Ollama may be stopped or restarted independently; the process must pause resumably.

### 21.2 BrainDrive Models and BYOK OpenRouter

- Purpose: cloud model inference through the existing OpenAI-compatible profiles when scope is `cloud` or `all`.
- Authentication and credits: retain existing BrainDrive Models credits and BYOK OpenRouter credential behavior; the guardrails introduce no provider key and never make BrainDrive Models credits a prerequisite for Ollama or BYOK OpenRouter.
- Request behavior: stage-scoped requests use the same existing adapter contract as the unguarded path.
- Timeout, rate-limit, and error mapping: retain existing provider classification and add only stage/run correlation.
- Cost and retry behavior: the single V1 retry ceiling applies wherever guardrails are enabled; measured call, token, latency, and cost deltas are release evidence under OI-002.
- Availability assumption: cloud providers may fail or rate-limit; the process pauses resumably without duplicating accepted writes.

### 21.3 Memory Tools

- Purpose: canonical file reads and writes.
- Authentication/authorization: retain existing owner auth context, tool availability, approval mode, path containment, and mutation guards.
- Retry behavior: do not blindly repeat a write after an ambiguous local result; first read/reconcile the target artifact and operation state.
- Error mapping: distinguish path/validation failure, approval denial, recoverable tool error, and non-recoverable tool error.

### 21.4 Evaluation Harnesses

- Purpose: offline model/content evaluation and live runtime verification.
- Credentials: harness credentials remain external to this feature and must never be copied into product config or traces.
- Comparison: same frozen scenarios, pack commit, target model, persona model, judge model, and runner options for baseline and guarded runs.
- Availability: lack of a model/hardware test environment blocks the model-capability acceptance claim but not unit-test development.

## 22. Validation Rules

1. Scope must be absent/empty or normalize to exactly `none`, `local`, `cloud`, or `all`; any other non-empty value is invalid.
2. Missing or empty scope resolves to `all`.
3. Provider identity must be present and explicitly classify as `ollama` local, `braindrive-models` cloud, or `openrouter` cloud before guarded activation.
4. Scope/provider activation must match the matrix in Section 13.1; unknown providers remain unguarded.
5. Active page must resolve to a canonical page scope with the registered process files.
6. Required instruction files must be readable; matching owner overlays are optional and read after managed bases.
7. A process run ID, conversation ID, page ID, stage kind, contract version, scope, provider class, and retry count are required in durable state.
8. Attempt number is an integer in `{1, 2}` for automatic attempts.
9. A stage cannot have more than one active attempt.
10. An accepted artifact path must remain within the intended active page scope.
11. A required artifact must exist unless the owner explicitly skipped it or the stage outcome permits no artifact.
12. Stable required sections must appear exactly once unless the canonical template explicitly permits repetition.
13. A candidate cannot delete protected sections, overlays, or unrelated owner content.
14. A journal entry cannot be created without journal-worthy owner content under the active `run-journal.md` contract.
15. A downstream stage with an owner-skipped prerequisite must receive an explicit absent-by-owner-choice marker, not a fabricated artifact.
16. Resume must verify run schema version and accepted artifact references/digests.
17. Trace fields are allowlisted; raw message, prompt, artifact, provider payload, key, token, cookie, or authorization fields are rejected from minimal trace serialization.
18. Evaluation evidence is invalid if anti-overfit scanning finds persona literals or rubric mechanics in production behavior files or runtime feedback.

## 23. Error Handling

| Category | Detection | Owner-Visible Behavior | Operator Evidence | Retry / Recovery | Final State |
|---|---|---|---|---|---|
| Eligibility/configuration | Scope invalid, provider unknown, or provider disabled | Invalid non-empty scope produces a clear configuration error; disabled/unknown providers use existing unguarded behavior | Sanitized configured/resolved scope, provider ID/class, activation decision, and error code | Correct config or provider classification and start a new run | No guarded state |
| Missing instruction | Required text file unreadable | Name the missing process file and say the stage cannot continue | File reference/digest status, no body | Restore file or owner chooses unguarded/stop | `NEEDS_OWNER_ACTION` |
| Structural validation | Candidate violates contract | One automatic correction; then weakness summary and choices | Validator codes and attempt | One automatic retry only | Active or `NEEDS_OWNER_ACTION` |
| Authorization/approval denial | Existing tool result denies write | Explain that the write was not approved and do not advance | Tool name/status, no secret | Owner may approve/retry explicitly | `NEEDS_OWNER_ACTION` |
| Persistence failure | Artifact or state write fails | Explain work was not marked complete | Error category/correlation | Reconcile target, then explicit retry | `PAUSED_RECOVERABLE` or `FAILED_INTERNAL` |
| Provider unavailable/timeout/rate limit | Existing provider classifier | Identify the active provider as unavailable and preserve progress | Provider category, stage, call ID | Resume after service returns | `PAUSED_RECOVERABLE` |
| Empty completion | Existing empty-response handling exhausts | Existing provider error, correlated to stage | Empty-retry events and stage | Manual resume; stage retry budget remains separate | `PAUSED_RECOVERABLE` |
| Context too large | Context preparation or provider signals overflow | Explain active stage needs a smaller input or owner direction | Stage/context estimates without content | Owner can narrow, edit, skip, or stop | `NEEDS_OWNER_ACTION` |
| Corrupt resume state | Schema/digest validation fails | Say progress state cannot be trusted; artifacts remain available | Preserve corrupt state and error code | Manual recovery or new run | `NEEDS_OWNER_ACTION` |
| Internal exception | Unhandled runtime failure | Sanitized generic error with progress-preservation statement | Correlation and stack only in existing protected logs | Maintainer repair; explicit resume if safe | `FAILED_INTERNAL` |

## 24. Retry, Recovery, and Idempotency

### 24.1 Retry Classes

- Existing provider empty-completion retry: unchanged and recorded separately.
- Stage structural retry: one automatic retry after deterministic validation failure.
- Owner-requested redo/retry: not automatic; begins a new explicit attempt cycle or stage revision and is recorded as owner-directed.
- Artifact write retry: never blind. Re-read and reconcile the target and recorded operation before repeating.

### 24.2 Canonical Operation Identity

A stage attempt is identified by run ID, stage kind, stage revision, and attempt number. Artifact mutations must also retain the existing tool-call identity/correlation available from the engine. Replaying the same accepted attempt cannot create a duplicate artifact or duplicate journal entry.

### 24.3 Restart Behavior

- Persist retry count before calling the retry.
- Persist accepted transition before advancing.
- On restart, load the latest valid process snapshot/events, validate referenced artifacts, and continue the first unfinished stage.
- If the runtime cannot determine whether a write succeeded, reconcile by reading the artifact and comparing the expected structural outcome/digest before writing again.

### 24.4 Partial Completion

Accepted upstream artifacts remain accepted. An incomplete downstream candidate remains unaccepted and cannot overwrite the accepted artifact. The owner may inspect/use accepted artifacts even if the overall process is paused or stopped.

## 25. Concurrency and Race Conditions

1. Only one active guarded process may control a given conversation/page/process tuple at a time.
2. A second simultaneous request for the same tuple must either join the active run safely or receive a conflict outcome; it must not create a second state machine.
3. State updates must use a monotonic revision or equivalent compare-and-set rule so stale requests cannot overwrite newer transitions.
4. Out-of-order model/tool results from a superseded attempt are recorded as stale and ignored for acceptance.
5. An owner edit to an accepted artifact during a run wins. Resume/advance must detect the digest change and revalidate rather than overwrite it.
6. An owner edit to a behavior file during an active stage does not silently change that active attempt. The current stage uses its recorded instruction digest; the new text applies on owner-requested redo or the next run.
7. Duplicate completion messages or restart replays cannot append a duplicate journal entry.
8. Two different conversations may run independently against different pages; existing memory-tool mutation safety remains authoritative when paths overlap.

## 26. Security and Privacy

### 26.1 Authentication and Authorization

- Reuse the existing authenticated owner context and tool permission model.
- Add no new role, permission, token, secret, or credential.
- Do not bypass approval mode for guardrail-generated writes.
- Do not change authentication or authorization routes.

### 26.2 Trust Boundaries

- Owner text, owner overlays, model output, tool input, and provider responses are untrusted inputs.
- Structural validators may accept or reject candidates but cannot grant new tool permissions.
- Ollama and cloud provider endpoints remain outside the guardrail controller's trust boundary; scope activation grants no additional trust or permission.
- Stage instructions cannot override system safety, authorization, preservation rules, or explicit owner artifact content.

### 26.3 Secret Handling

- Never record API keys, authorization headers, cookies, vault references by value, tokens, passwords, or provider payloads in the minimal trace.
- Reuse the existing audit sanitizer patterns where practical, but verify the guardrail trace with dedicated tests.
- Provider configuration remains security-sensitive and outside owner artifact backup semantics.

### 26.4 Data Exposure

- Minimal traces remain local under the owner's memory diagnostics boundary.
- No trace upload, analytics call, or telemetry endpoint is added.
- Content-rich attempt capture is off by default and cannot be silently enabled by any guardrail scope or provider selection.
- Real-owner failed attempts are not training data. A separate consented export workflow is required for T-764.

### 26.5 Destructive-Action Protection

- Existing tool approval, path containment, loop guard, and mutation-scope guard remain active.
- Candidate validation cannot authorize deletion or whole-file replacement forbidden by the active procedure.
- Disabling or uninstalling the feature cannot delete owner artifacts.

Risk level: Medium. The feature handles owner input, model output, and file writes but introduces no new public network surface, payment flow, or secret.

## 27. User Experience Requirements

- Entry point: existing chat on a page whose resolved supported provider is enabled by guardrail scope.
- First use: no setup wizard; if required process files are missing, provide a direct recovery explanation.
- Loading: existing streaming/loading behavior remains; no mandatory stage counter.
- Success: respond naturally, summarize what was created or updated, and identify the useful next step.
- Failure: name the affected stage in plain language, state what remains safe, and present actionable choices.
- Recovery: accept ordinary language such as resume, redo that step, skip this, or stop.
- Owner override: comply without framing the owner's decision as a validation error.
- Empty state: a new page uses canonical starter-pack templates and begins the interview stage.
- Refresh/restart: returning to the conversation can resume the paused stage after state validation.
- Accessibility: no new visual control is introduced; existing chat accessibility requirements remain the regression baseline.
- Model disclosure: do not introduce model names or guardrail mechanics into Tier-0 happy-path copy.
- Journal: do not tell the owner that an entry was written unless an actual canonical journal write succeeded and existing journal communication rules require the notice.

## 28. Observability and Diagnostics

### 28.1 Required Event Categories

- process started/resumed/completed/stopped/paused/failed;
- stage activated/candidate produced/validation passed/validation failed/accepted/skipped/redo;
- retry scheduled/started/exhausted;
- owner override category;
- artifact reference and content digest, not artifact body;
- tool call/result status and existing call ID;
- provider/model identity and model-call ID;
- state revision and schema version;
- duration and attempt counts;
- trace persistence degradation.

### 28.2 Correlation

Every event includes run ID, conversation ID, gateway correlation ID, configured/resolved scope, provider identity/class, activation decision, and stage kind where applicable. Model-call and tool-call IDs are included when available. Owner actor IDs are not needed unless the existing auth mode already supplies a non-sensitive identifier.

### 28.3 Operator Questions the Trace Must Answer

1. Why did this request enter the guardrail path?
2. Which stage was active?
3. Which instructions and artifacts were referenced by digest?
4. Did the model, a tool, validation, persistence, or the owner cause the transition?
5. Was a retry used, and why?
6. Which artifact was accepted, skipped, or left unchanged?
7. Can the run resume safely?
8. Did the request enter or bypass guardrails according to the scope/provider matrix?

### 28.4 Metrics and Alerts

V1 requires reportable counts derived from JSONL, not a metrics service or dashboard: activation by scope/provider, completion rate, sequencing failures, validation failure rate, retry recovery rate, owner overrides, resumptions, stage duration, total duration, model calls, token/cost evidence where the provider supplies it, and attempts. Product alerts are out of scope; acceptance reports must flag any scope-matrix violation, data-loss event, or hard quality/trust regression as an automatic failure.

## 29. Compatibility Requirements

- Existing `POST /message` request and SSE response contracts remain unchanged.
- Existing provider profiles, credentials, model-selection UI, Ollama pull/delete behavior, and adapter configuration remain valid.
- BrainDrive Models credits are not required for Ollama or BYOK OpenRouter.
- Existing conversations and owner artifacts require no migration.
- Existing starter-pack files remain readable and editable; owner overlays remain byte-for-byte preserved by starter-pack updates.
- A mixed-version downgrade may ignore guardrail state but must leave owner artifacts intact. A later upgrade may resume only if the stored schema is supported and artifact references revalidate.
- Setting scope to `none` restores the current unguarded path for all providers without attempting to translate or delete completed owner artifacts.
- Desktop, Docker, and server-only modes use the same scope and provider-class rules; environment-specific base URLs do not determine eligibility.

## 30. Migration and Rollout Requirements

### 30.1 Owner Data

No owner-artifact migration or backfill is required. Existing `spec.md`, `plan.md`, `journal.md`, conversations, and overlays remain the source of truth.

### 30.2 New Runtime State

New process state and trace records require an explicit schema version. Unsupported records are preserved and surfaced for manual recovery; they are not silently rewritten.

### 30.3 Evidence-Gated Enablement

The behavioral rollout contract is:

1. Code supports all four scopes from V1; development and proof environments may explicitly use `none` or `local` while evidence is incomplete.
2. Missing or empty production configuration resolves to the intended product default, `all`; this path must be tested explicitly because existing deployments may omit the variable.
3. Baseline runs use `none`; local proof uses `local`; cloud comparison uses `cloud`; intended product behavior uses `all`.
4. OI-001 local success/abort and OI-002 cloud regression gates are decided before code and applied without moving thresholds after results are known.
5. Default-`all` release occurs only after local proof, cloud comparison, scope-matrix verification, and all acceptance criteria pass.
6. Any scope-matrix violation, owner-data loss, override violation, retry overflow, privacy failure, hard quality regression, or test contamination blocks default-`all` acceptance regardless of aggregate score.

This is a safe-behavior rollout contract, not an implementation milestone plan.

### 30.4 Rollback

Set `BRAINDRIVE_PROCESS_GUARDRAILS_SCOPE=none`. Rollback must stop new guarded runs for every provider, leave existing artifacts and diagnostics intact, and route future messages through current unguarded paths. `local` may be used as a narrower operational hold when only cloud regressions are under investigation. A paused guarded run remains inspectable and may be manually abandoned; automatic conversion to an unguarded run is not required.

## 31. Testing Requirements

### 31.1 Required Levels

- Unit: state transitions, eligibility, validator codes, override handling, retry cap, redaction, stale-result rejection.
- Integration: gateway/provider selection, existing adapter, memory tools, artifact placement, approval denial, trace persistence.
- Recovery: provider interruption, restart between validation and acceptance, ambiguous write reconciliation, corrupt state.
- Property/invariant: scope/provider matrix, disabled-provider non-entry, retry bound, accepted-artifact preservation, one terminal state, owner override supremacy.
- Harness/model evaluation: frozen Katie A/B/C, anti-overfit scan, local guarded-vs-baseline delta, cloud guarded-vs-baseline quality/feel/latency/token/cost evidence, and 16 GB-class model evidence.
- Runtime/browser: actual app entry, streaming, file writes, restart/resume, no new UI regressions.
- Security/privacy: trace allowlist/redaction, no new egress, no secret value, no unauthorized write.
- Manual review: conversational feel, owner override behavior, failure clarity, absence of wizard-like friction.

### 31.2 Test Matrix

| Scenario | Preconditions | Trigger | Expected Result | Test Level |
|---|---|---|---|---|
| Normal local process | Ollama, valid files | Start process | Ordered accepted stages and completion | Integration/E2E |
| Normal cloud process | BrainDrive Models or OpenRouter, valid files, scope `cloud`/`all` | Start process | Same ordered guardrail semantics and canonical artifacts | Integration/E2E |
| Scope `none` | Each supported provider | Start same intent | Existing loop only; no process state/events or extra attempts | Unit/Integration/Regression |
| Scope `local` | Each supported provider | Start same intent | Ollama guarded; BrainDrive Models/OpenRouter unguarded | Unit/Integration |
| Scope `cloud` | Each supported provider | Start same intent | Ollama unguarded; BrainDrive Models/OpenRouter guarded | Unit/Integration |
| Scope `all` | Each supported provider | Start same intent | Every classified supported provider guarded | Unit/Integration |
| Scope missing or empty | Each supported provider | Start same intent | Resolves to `all`; every classified provider guarded | Config/Integration |
| Scope invalid | Non-empty unsupported value | Load config | Clear configuration failure; no silent fallback | Unit/Config |
| Unknown provider | Scope `all` | Start same intent | Existing unguarded path plus sanitized classification diagnostic | Unit/Integration |
| Missing behavior file | Ollama, file absent | Enter stage | No model call; clear recovery | Unit/Integration |
| Owner text edit | Change stage behavior text | Start next run | Changed behavior, no code change | Harness/Manual |
| Owner overlay | Base plus overlay conflict | Enter stage | Overlay wins unless higher invariant applies | Integration |
| Plan-before-spec model attempt | No owner override | Model writes plan early | Candidate rejected and feedback emitted | Unit/Integration |
| Owner skips spec | Explicit owner direction | Advance to plan | Skip recorded; plan not blocked by absence | Unit/E2E |
| First validation failure | Invalid sections | Validate | One retry with codes | Unit/Integration |
| Retry failure | Two invalid attempts | Validate second | Needs-owner-action; no third attempt | Unit/E2E |
| Approval denied | Ask-on-write mode | Deny write | No acceptance or advance | Integration |
| Provider timeout/rate limit | Guarded local or cloud stage | Provider failure | Paused resumably; accepted artifacts intact | Failure injection |
| Restart after accepted stage | Durable state exists | Restart/resume | Continue next stage, no duplicate write | Recovery |
| Restart before retry | First failure persisted | Restart/resume | Retry count remains one; one retry maximum | Recovery |
| Ambiguous file write | Write result interrupted | Resume | Read/reconcile before any repeat | Recovery/Integration |
| Concurrent same run | Two requests | Both advance | One winner; stale result ignored | Concurrency |
| Mid-run owner artifact edit | Accepted artifact changed | Advance/resume | Detect change and revalidate; do not overwrite | Concurrency/Integration |
| Journal no-entry handoff | Initial process has no journal-worthy update | Complete handoff | No synthetic journal entry; valid completion | Integration/E2E |
| Journal-worthy update | Canonical rules say write | Complete handoff | One correct entry and required owner notice | Integration/E2E |
| Trace privacy | Realistic secret-shaped content | Complete/fail run | Minimal trace contains no raw content/secret | Security |
| Test contamination | Persona literal inserted | Run anti-overfit scan | Acceptance blocked | Harness |
| 16 GB qualification | Candidate model installed | Frozen eval | Memory footprint verified and target gate evaluated | Hardware/Harness |
| Cloud regression comparison | Same hosted model and frozen inputs under `none` then `cloud`/`all` | Run matched suite | OI-002 quality, feel, latency, call/token, and cost thresholds evaluated | Harness/Manual |

### 31.3 Repository Verification Commands

The build plan may refine focused commands, but the final change must at minimum run:

```bash
cd builds/typescript
npm run test
npm run build
npm run web:typecheck
npm run web:test
```

If no web file changes, web checks remain regression evidence because the chat contract must remain compatible. Desktop preflight is required if runtime packaging/config changes affect staged desktop assets.

### 31.4 Ground-Truth Evidence

- Unit and integration test output from the changed branch.
- Guarded and baseline local and cloud run traces with matching provenance.
- Artifact diffs proving canonical placement and preservation.
- A runtime/browser recording or report proving live activation and resume.
- Measured peak total memory or a real run on 16 GB-class hardware; model weight size alone is insufficient.
- Anti-overfit scan output.
- Scope/provider matrix evidence proving correct entry and bypass behavior, including missing, empty, invalid, and unknown-provider cases.
- Cloud comparison report covering quality, feel, latency, model calls/tokens, and cost, with required sign-off.

## 32. Acceptance Criteria

- [ ] AC-001: `none`, `local`, `cloud`, and `all` produce the documented activation matrix for Ollama, BrainDrive Models, and OpenRouter; unknown providers remain unguarded.
- [ ] AC-002: Exactly one V1 process is registered and no owner-defined process input is accepted.
- [ ] AC-003: Each stage request includes only its required instructions, overlays, active owner direction, and prerequisite artifacts.
- [ ] AC-004: Across the frozen release set, no unrequested plan is accepted before the specification outcome.
- [ ] AC-005: Every run ends in exactly one documented terminal or resumable state, and completion requires all stage outcomes resolved.
- [ ] AC-006: Explicit skip, reorder, redo, stop, and resume instructions are honored without a guardrail veto.
- [ ] AC-007: An owner-skipped prerequisite is represented explicitly and does not cause a false validation failure downstream.
- [ ] AC-008: A behavioral text-file edit changes the next run without a TypeScript code change.
- [ ] AC-009: Managed base plus owner-overlay read order is verified, and the overlay remains byte-for-byte unchanged by this feature.
- [ ] AC-010: Wrong path, missing artifact, missing/duplicate required sections, and destructive replacement are deterministically rejected.
- [ ] AC-011: The first structural failure receives one retry containing the failed structural checks.
- [ ] AC-012: No stage outcome receives more than two automatic attempts, including across restart.
- [ ] AC-013: Retry exhaustion stops advancement, preserves accepted state, and gives clear owner recovery choices.
- [ ] AC-014: A missing required instruction file stops the stage without an embedded behavioral fallback.
- [ ] AC-015: Accepted writes use canonical owner-memory locations and preserve unrelated owner content.
- [ ] AC-016: Provider interruption after an accepted stage preserves that stage and records a resumable state.
- [ ] AC-017: Restart resumes the first unfinished stage without duplicating accepted writes or resetting retry state.
- [ ] AC-018: Every guarded run emits schema-versioned append-only JSONL events sufficient to reconstruct its stage history.
- [ ] AC-019: Default process traces contain no raw owner messages, prompt text, artifact bodies, provider payloads, credentials, or secrets.
- [ ] AC-020: Trace and state failures are visible and never cause a false successful acceptance claim.
- [ ] AC-021: A provider disabled by resolved scope creates no guardrail state, trace events, validation calls, or additional model attempts; an enabled provider receives the same core guardrail semantics.
- [ ] AC-022: Existing gateway, SSE, provider credentials, credits, model selection, approval, adapter, and web-client regression suites pass under every scope.
- [ ] AC-023: V1 contains no workflow engine, process DSL, Python runtime dependency, model judge, dashboard, adaptive retry, or second process.
- [ ] AC-024: Anti-overfit scanning finds no frozen persona literal, answer, judge mechanic, or gauntlet content in production instructions or runtime feedback.
- [ ] AC-025: Journal handoff completes without writing an entry when canonical journal eligibility is not met.
- [ ] AC-026: When journal eligibility is met, at most one correct entry is written and existing journal preservation/owner-notice rules hold.
- [ ] AC-027: `BRAINDRIVE_PROCESS_GUARDRAILS_SCOPE` accepts only `none`, `local`, `cloud`, and `all`; matching is trimmed/case-insensitive; missing or empty resolves to `all`; invalid non-empty values fail configuration clearly.
- [ ] AC-028: Setting scope to `none` restores existing unguarded paths for every provider without deleting or rewriting owner artifacts, run state, or traces.
- [ ] AC-029: The pre-decided OI-001 success bar passes for guarded versus baseline runs on the same frozen inputs.
- [ ] AC-030: At least one passing target model is verified within a 16 GB MacBook-class total system-memory envelope.
- [ ] AC-031: Unit, integration, recovery, concurrency, security, harness, runtime/browser, and manual-review evidence listed in Section 31 is complete.
- [ ] AC-032: The specification, verification plan, operator-facing configuration documentation, and recovery behavior documentation agree with shipped behavior.
- [ ] AC-033: Guarded cloud runs satisfy the pre-decided OI-002 thresholds for quality, conversational feel, latency, model calls/tokens, and cost, with Dave J and Dave W sign-off as specified.

## 33. Requirement Traceability Matrix

| Requirement | User Story | System Area | Acceptance Criterion | Verification |
|---|---|---|---|---|
| FR-001 | US-1, US-7 | Gateway/provider eligibility | AC-001, AC-021 | Provider matrix unit/integration tests |
| FR-002 | US-1 | Process controller | AC-002, AC-023 | Registry/state tests and dependency audit |
| FR-003 | US-3 | Starter-pack/instruction loading | AC-008, AC-009, AC-014 | Owner-edit eval and overlay tests |
| FR-004 | US-1 | Context assembly | AC-003, AC-024 | Context snapshot/allowlist and contamination tests |
| FR-005 | US-1 | State machine/validators | AC-004, AC-005 | Transition property tests and frozen eval |
| FR-006 | US-2 | Override handling | AC-006, AC-007 | Unit plus Katie override scenarios |
| FR-007 | US-4 | Artifact validation | AC-010, AC-015 | Validator and memory integration tests |
| FR-008 | US-4 | Retry controller | AC-011, AC-012 | Retry and restart tests |
| FR-009 | US-4 | Failure UX/state | AC-013 | Exhaustion E2E and manual review |
| FR-010 | US-1 | Memory/journal | AC-015, AC-025, AC-026 | File diffs and journal workflow tests |
| FR-011 | US-5 | Durable state/recovery | AC-016, AC-017 | Failure injection and restart tests |
| FR-012 | US-6 | Diagnostics | AC-018, AC-019, AC-020 | JSONL schema, redaction, failure tests |
| FR-013 | US-7 | Scope/provider preservation | AC-001, AC-021, AC-022 | Matrix tests, call-path spies, and full regression suite |
| FR-014 | US-1, US-6 | Harness/instructions | AC-024 | Anti-overfit scan and blinded runs |
| FR-015 | US-7 | Runtime config/rollback | AC-027, AC-028 | Config and rollback integration tests |
| FR-016 | US-1, US-4, US-5 | State model | AC-005, AC-013, AC-017, AC-020 | State property tests |
| NFR-001 | US-1 | Reliability | AC-004, AC-005, AC-029, AC-033 | Frozen harness and property tests |
| NFR-002 | US-4 | Bounded execution | AC-011, AC-012 | Retry property tests |
| NFR-003 | US-6 | Privacy | AC-019 | Security/redaction corpus tests |
| NFR-004 | US-6 | Auditability | AC-018, AC-020 | Trace reconstruction test |
| NFR-005 | US-3 | Maintainability | AC-008, AC-009 | Text-only owner-edit eval |
| NFR-006 | US-2 | Trust/UX | AC-006, AC-007 | Override scenario suite/manual review |
| NFR-007 | US-5 | Data integrity | AC-015, AC-016, AC-017 | Recovery and artifact-diff tests |
| NFR-008 | US-7 | Compatibility | AC-001, AC-021, AC-022, AC-027, AC-028, AC-033 | Scope matrix and cloud regression suite |
| NFR-009 | US-6, US-7 | Network/privacy | AC-019, AC-021 | Network-destination instrumentation |
| NFR-010 | US-1 | Portability | AC-030 | Measured hardware run |
| NFR-011 | US-6 | Performance evidence | AC-018, AC-029 | Guarded/baseline report |
| NFR-012 | US-1, US-7 | Simplicity | AC-023 | Dependency/architecture review |

## 34. Risks and Mitigations

| Risk | Likelihood | Impact | Detection | Mitigation |
|---|---|---|---|---|
| Guardrails become a second prompt system | Medium | High | Code review finds behavioral strings in TypeScript | Enforce FR-003 and owner-edit eval; reject qualitative criteria in code |
| Shared guardrails degrade cloud quality, feel, latency, or cost | Medium | Critical | Matched `none` versus `cloud`/`all` report | Decide OI-002 before code; hold deployment at `local`/`none` until corrected and signed off |
| Scope misclassification enables the wrong provider | Medium | Critical | Scope/provider matrix and diagnostic mismatch | Explicit provider-ID classification; unknown providers stay unguarded |
| Missing variable unexpectedly activates all providers on upgrade | Medium | High | Missing-config upgrade test | Treat missing=`all` as an explicit release path; require default-all gates and rollback docs |
| Deterministic validator is too strict | Medium | High | Owner overrides or valid customized artifacts fail | Validate structure only; honor override; use canonical stable sections |
| Validator is too weak | Medium | High | Broken artifacts pass | Frozen failure fixtures; runtime/browser artifact checks |
| Retry duplicates a write | Medium | High | Duplicate sections/journal entries | Durable attempt identity and read-before-repeat reconciliation |
| Resume overwrites owner edits | Medium | Critical | Digest mismatch on resume | Owner edit wins; revalidate and stop for owner action |
| Trace leaks owner content or secrets | Medium | Critical | Redaction/allowlist security tests | Minimal allowlisted schema, content off by default, locally stored retention |
| Evaluation overfits personas | Medium | High | Anti-overfit scan or suspicious delta | Frozen/blinded eval; general behavior-only fixes |
| 16 GB target cannot pass | Medium | High | Measured candidate sweep | Test ≤12B candidate first; stop or re-scope per OI-001 |
| Existing 31B fine-tune conflicts with hardware floor | High | Medium | Measured Q4 memory exceeds floor | Treat 31B as Spark/desktop tier; promote ≤12B pilot candidate |
| Complexity grows before evidence | Medium | High | Added judge/DSL/engine/dashboard | NFR-012 gate and explicit entry conditions for future work |
| Forced journal write violates memory architecture | Medium | High | Initial session creates synthetic entry | FR-010 and dedicated no-entry handoff test |
| Prompt audit and process trace diverge | Medium | Medium | Conflicting IDs/status | Share correlation/schema primitives where practical; process trace remains authoritative for stage state |
| Local Ollama instability contaminates model comparison | High | Medium | Provider-error rate/provenance | Sequential matched runs; rerun infrastructure failures; report them separately |

## 35. Dependencies

| Dependency | Type | Effect |
|---|---|---|
| OI-001 quantitative success/abort decision | Product/QA | Blocking before implementation; prevents moving the goalposts after results are visible. |
| OI-002 cloud regression decision | Product/QA | Blocking before implementation because `all` is the default and cloud tradeoffs must be judged against a pre-decided bar. |
| BrainDrive TypeScript runtime | Internal | Hosts provider resolution, gateway request flow, engine loop, config, and tests. |
| Ollama OpenAI-compatible endpoint | External local service | Required for live local-model verification; may be unavailable or unstable. |
| Canonical starter-pack files | Internal product data | Behavioral source and artifact templates; changes must be paired across fixture/starter-pack/migration rules where applicable. |
| Memory architecture M-1 through M-13 | Internal contract | Governs placement, preservation, overlays, propagation, and prompt boundaries. |
| Memory tools and authorization | Internal | Required for real reads/writes and approval behavior. |
| Prompt-audit implementation | Internal reference | Provides proven JSONL rotation, retention, correlation, and sanitizer patterns; not a mandatory runtime dependency for process state. |
| Starter-pack testing harness | Internal QA | Supplies frozen persona/model evaluation and anti-overfit checks. |
| BrainDrive runtime/browser harness | Internal QA | Proves live writes, restart, UI compatibility, scope activation, and cloud regression behavior. |
| 16 GB-class hardware or measured equivalent | Test infrastructure | Required for the portability acceptance claim. |
| Candidate ≤12B quantized local model | Model asset | Required to test the stated owner hardware floor. |
| Dave W and Dave J review | Team | Dave W owns success/trust judgment; Dave J owns runtime boundary and bounded effort. |

No new production credential, paid external service, workflow library, or Python product dependency is required.

## 36. Assumptions

| Assumption | Why Required | Evidence | Risk if Incorrect | Recommended Validation |
|---|---|---|---|---|
| `ollama`, `braindrive-models`, and `openrouter` remain stable provider identities | Defines explicit local/cloud classification | Current adapter profiles and gateway logic | Wrong requests enter or bypass scopes | Lock with config/adapter matrix tests |
| Missing or empty guardrail scope should mean `all` | Defines normal product behavior and upgrade semantics | Current design decision in `info.md` | Existing deployments may activate guardrails unexpectedly | Test missing/empty upgrades and require OI-001/OI-002 release gates before default-all acceptance |
| Existing stage files can serve as behavior sources | Avoids a parallel prompt system | Starter-pack `AGENT.md` and `run-*` layout | Stage context may need a new dedicated text file | Prototype context assembly and owner-edit eval |
| Stable artifact sections can be checked structurally | Enables deterministic V1 validation | Canonical templates and memory required-shape rules | Owner customization may legitimately change structure | Define contract from stable headings and test overlays/customized fixtures |
| One retry captures most recoverable structural misses | Implements bounded-effort direction | Ratified simplicity ladder | Improvement may plateau below success bar | Measure retry recovery; add model judge only under future entry condition |
| Minimal traces plus artifact references are enough for product diagnosis | Protects privacy | Existing prompt-audit metadata and source requirements | Some failures may be hard to reproduce | Allow explicit temporary diagnostic mode, off by default |
| 14-day trace retention is a safe V1 default | Avoids an arbitrary new policy | Existing prompt-audit default | Process evidence may expire too early/late | Confirm during test-plan/security review; document any change before build |
| Current journal procedure is authoritative over the proposal's phrase “journal always written” | Resolves a source conflict without fabricating owner history | Memory architecture and shipped `run-journal.md` say initial alignment does not force an entry | Stakeholders may intend a new initial-session entry | Dave W/Dave J explicitly confirm in spec review; default remains no synthetic entry |
| A qualifying ≤12B model can be selected for the pilot | Needed for 16 GB acceptance | Source estimates 7–12B at Q4 | No candidate meets quality gate | Apply OI-001 abort/re-scope decision |
| No new UI is required for owner override or recovery | Keeps V1 bounded | Existing interaction is conversational | Recovery may be unclear in practice | Human UX review of failure scenarios |

## 37. Open Items and Questions

### OI-001 — Quantitative Success and Abort Bar (Blocking)

- Question: What guarded-versus-baseline result validates the bet, and what result stops the effort?
- Why it matters: D4 requires bounded effort, and the threshold must be set before results are visible.
- Available evidence: the source requires material improvement, zero sequencing failure, frozen Katie A/B/C gates, and a 16 GB hardware floor; no numeric delta was ratified.
- Options:
  1. Any positive delta: cheap but too noisy to justify runtime complexity.
  2. Absolute 20-percentage-point improvement in end-to-end pass rate with no hard-invariant failure: meaningful and easy to interpret.
  3. Statistical-confidence target across a much larger run set: stronger but likely violates bounded effort for V1.
- Recommendation: choose option 2. Use matched baseline/guarded runs with at least three repeats per frozen scenario. Success requires (a) zero unrequested sequencing failures, (b) no scope-matrix, owner-override, data-loss, privacy, or preservation failure, and (c) at least +20 absolute percentage points in end-to-end pass rate for one qualifying 16 GB-class model. Abort the runtime build if improvement is below +10 points after the deterministic-gates-plus-one-retry experiment. A result from +10 to +19 points permits one explicit go/no-go review but does not authorize added complexity automatically.
- Default if undecided: do not start implementation.
- Decision owner: Dave W, with Dave J confirming the bounded engineering cost.
- Impact of delay: test planning and implementation remain blocked.

### OI-002 — Cloud Regression Bar for Default `all` (Blocking)

- Question: What quality, feel, latency, model-call/token, and cost deltas are acceptable when comparing the same hosted model under `none` and `cloud`/`all`?
- Why it matters: `all` is the default even when configuration is absent, so cloud guardrails are normal product behavior rather than a later optional rollout.
- Available evidence: the guardrails should strengthen structural reliability, but stage decomposition and one retry may add latency, calls, tokens, cost, or mechanical conversational feel. No quantitative cloud threshold has been ratified.
- Options:
  1. Require zero increase in latency/cost: safest financially but likely rejects any staged implementation regardless of quality benefit.
  2. Use bounded quantitative regression thresholds plus hard invariant gates and human product sign-off.
  3. Use sign-off without thresholds: flexible but permits moving the bar after seeing results.
- Recommendation: choose option 2. Require no decrease in hard-gate pass rate; zero scope, owner-override, artifact, privacy, retry-bound, or recovery regressions; median total-process latency and provider-reported token/cost increases no greater than 20% versus matched `none` runs; and no decrease in median structured conversational-feel rating. Any exception requires an explicit spec amendment, not informal sign-off. Dave J signs off the production-flow metrics and Dave W signs off product feel.
- Default if undecided: do not accept a default-`all` release; development may remain explicitly `local` or `none`.
- Decision owner: Dave J for the production-flow boundary, with Dave W approving product feel.
- Impact of delay: test planning and default-all implementation acceptance remain blocked.

### OI-003 — Pilot Model Versus Existing 31B Fine-Tune Order (Non-Blocking for Spec; Blocking for Hardware Acceptance)

- Question: Which model proves the 16 GB owner-hardware claim while the fine-tune project currently prioritizes a dense 31B model estimated above that floor?
- Why it matters: a Spark-only success cannot satisfy AC-030.
- Available evidence: source estimates the 31B model at roughly 18–20 GB at Q4 and identifies 7–12B Q4 as the practical target band.
- Options:
  1. Promote a ≤12B candidate into the guardrail pilot.
  2. Keep 31B first and waive the hardware floor.
  3. Treat 31B as a separate Spark/desktop-tier experiment while independently testing ≤12B for V1.
- Recommendation: combine options 1 and 3. Test the smallest credible ≤12B candidate first for V1; keep 31B work explicitly labeled Spark/desktop-tier and unable to satisfy AC-030.
- Default if undecided: the 31B result may inform engineering but cannot pass the V1 portability gate.
- Decision owner: Dave W / local-model evaluation owner.
- Impact of delay: runtime unit work could proceed after OI-001, but V1 cannot be accepted.

## 38. Recommended Decisions

1. Adopt the OI-001 +20-point success / below-10-point abort recommendation before implementation. Blocking.
2. Adopt OI-002's hard no-regression gates and recommended 20% median latency/token/cost ceilings before implementation. Blocking for default-`all` acceptance.
3. Use a ≤12B Q4-class candidate as the first owner-hardware pilot; classify the 31B fine-tune separately. Blocking for final acceptance, not for test-plan writing.
4. Preserve canonical journal semantics: resolve journal handoff every run, but write no synthetic initial-session entry. Non-blocking unless Dave W/Dave J explicitly amend the memory contract.
5. Keep V1 deterministic-only. A model judge may be proposed only after evidence shows deterministic validation plus one retry plateaued below the agreed target. Non-blocking; prevents scope growth.
6. Keep minimal trace retention at 14 days and content capture off by default, matching the existing prompt-audit privacy posture. Non-blocking; confirm during security/test-plan review.
7. Use one permanent enum scope variable with `none`, `local`, `cloud`, and `all`; default missing/empty configuration to `all`, reject invalid non-empty values, and keep unknown providers unguarded. Foundational.
8. Treat process behavior files as the product behavior authority and process state/trace as system diagnostics only. Non-blocking and foundational.

## 39. Future Considerations

The following are explicitly outside V1 and require new evidence and specification updates:

- A deterministic-validator plateau may justify a text-defined model judge. Entry condition: OI-001 is not met, failures are demonstrably qualitative rather than structural, and added latency/privacy/cost is accepted.
- A second real product process may justify extracting a reusable registry or configuration format. Entry condition: duplicated process code exists and causes measurable maintenance pain.
- Mixed per-stage model routing may be considered after single-provider guarded execution is reliable.
- Owner-defined custom processes would require a separate safety, UI, validation, and compatibility contract.
- A Tier-2 diagnostics/config surface may be considered only if reading JSONL and using existing settings becomes an observed owner/operator problem.
- Consent-based failed-attempt export for T-764 requires a separate privacy and data-governance spec.
- Additional providers require an explicit stable identity, local/cloud classification, and compatibility decision; they are not implicitly included by URL shape or by selecting `all`.

## 40. Glossary

| Term | Definition |
|---|---|
| Accepted artifact | A canonical owner artifact that passed structural validation and was durably persisted. |
| Artifact contract | Structural rules for a stage's permitted inputs, outputs, path, required sections, and preservation behavior. |
| Cloud provider | An explicitly classified remote provider; V1 includes BrainDrive Models and BYOK OpenRouter. |
| Guardrail controller | The shared runtime process-control boundary specified here; not a general workflow engine. |
| Guardrail scope | Resolved `none`, `local`, `cloud`, or `all` activation value governing which classified providers may enter guardrails. |
| Guarded run | A process run whose classified provider is enabled by scope and whose owner intent passed process eligibility. |
| Journal handoff | Final process outcome that establishes the transition into ongoing journal/follow-up behavior; it does not necessarily create an entry. |
| Local provider | An explicitly classified owner-local provider; V1 currently includes Ollama. |
| Mellea pattern | Decompose, externalize control flow, validate, and retry. BrainDrive adopts the pattern, not the Python library. |
| Owner override | Explicit owner direction to skip, reorder, redo, stop, or resume a stage. |
| Process stage | One bounded unit of model/tool work with explicit input, validation, and outcome state. |
| Qualifying model | A model that meets the agreed quality gate and the measured 16 GB MacBook-class total-memory constraint. |
| Structural feedback | Deterministic explanation such as missing file, wrong path, or missing required section; not qualitative prose judgment. |
| Unrequested sequencing failure | A stage skipped, reordered, or falsely completed by system/model behavior without an explicit owner instruction. |

## Changelog

| Date | Change | Reason | Source / Decision |
|---|---|---|---|
| 2026-07-21 | Initial complete software specification created from the ratified proposal and live repository evidence. | Convert mixed proposal/build notes into a testable product/engineering contract. | `info.md`, D4 report, repository inspection |
| 2026-07-21 | Initially restricted activation permanently to Ollama/local models. | Reflected the direction available when the first complete spec was written; subsequently superseded. | Prior `info.md` direction |
| 2026-07-21 | Replaced permanent local-only scope with one shared architecture and permanent `none` / `local` / `cloud` / `all` scope; missing/empty defaults to `all`; invalid non-empty config errors; cloud regression bar restored as OI-002. | Guardrails are product guarantees useful across models, while scope provides testing and rollback. | Current `info.md` design mechanic and user discussion |
| 2026-07-21 | Reconciled “journal always written” with canonical journal rules as a required handoff that may produce no entry. | Avoid synthetic owner history and preserve memory architecture. | M-10/M-11 and shipped `run-journal.md` |
| 2026-07-21 | Made deterministic validation the complete V1 gate and deferred runtime model judging. | Ratified simplicity-first ladder. | D4 framing in `info.md` |

## Conversation References

| Date | Source | Topics | Reference |
|---|---|---|---|
| 2026-07-18 | Dave W / Claude discussion | Mellea pattern, small-model process failures, text/code bright line, local process harness | Summarized in `Braindrive-Guardrails/info.md` |
| 2026-07-21 | Dave W / Dave J call | Ratification as D4, Dave J ownership, bounded effort, simplicity-first ladder, open quantitative gate | Summarized in `Braindrive-Guardrails/info.md` |
| 2026-07-21 | Current specification session | Repository-grounded specification, local-only intermediate direction, then provider-scope reconciliation with default `all` | User discussion and current `info.md` |

## Approval

- [x] Product direction ratified as D4, per source material.
- [ ] OI-001 quantitative local success/abort bar approved by Dave W and acknowledged by Dave J.
- [ ] OI-002 cloud regression bar approved by Dave J and Dave W.
- [ ] Verification plan reviewed.
- [ ] Specification read back by builder and finish line confirmed.
- [ ] Ready for implementation planning after the preceding approval items.

---

Next step: resolve OI-001 and OI-002, then create the verification plan before the build plan.
