# Spec: Your Agent Settings Page

> **Purpose:** Builder-facing BrainDrive product/engineering spec for the Settings page that displays and edits the owner's global agent customization.
> **Generated from:** Product request and current implementation review on 2026-07-09.
> **Primary product surface:** Settings modal, `Your Agent` tab, local and managed modes.
> **Recommendation:** Keep `AGENT.md` as the managed/default runtime instruction layer and `AGENT-user.md` as the owner-controlled overlay. Treat Settings as the direct, explicit customization surface for global BrainDrive behavior, not as a project editor, profile editor, provider settings page, or AI rewrite tool.

## Overview

### What This Covers

The `Your Agent` Settings page lets a BrainDrive owner review the managed global agent instructions and edit their owner-specific global customization overlay. The customization controls BrainDrive's broad personality, tone, operating style, and cross-project working preferences before project-specific instructions are applied.

This spec covers the owner-facing behavior, gateway API contract, memory file contract, runtime prompt boundary, trust boundaries, current implementation, recommended V1 gaps, and verification expectations for the `Your Agent` Settings tab. It is intended to become the source of truth for product review, implementation planning, QA, regression testing, and future agents/builders.

### Why It Matters

BrainDrive's core value depends on acting like the owner's durable partner rather than a generic chatbot. The global agent layer is high leverage because it can influence every future conversation, project handoff, artifact update, and tone choice. Owners need a trusted place to customize that layer without overwriting managed defaults or mixing agent behavior with remembered personal facts.

The page is unsuccessful if it edits the managed default directly, hides owner customization state, stores secrets or one-project goals as global behavior, silently drops overlay edits, implies the agent can bypass BrainDrive safety rules, or changes project/page instructions when the owner expects a global setting.

### Target Audience And Stakeholders

| Audience | Role / Need |
|---|---|
| Local BrainDrive owner | Needs a trusted way to customize global BrainDrive behavior stored on their machine. |
| Managed BrainDrive owner | Needs the same behavior customization surface while account, billing, and hosted operations remain separate. |
| Builder / implementation owner | Maintains Settings UI, `/agent` API wrappers, gateway `/agent` routes, bootstrap prompt assembly, memory-root path handling, git history, and starter-pack behavior. |
| QA / harness audience | Verifies tab visibility, overlay load/save/revert behavior, default read-only display, auth boundaries, runtime prompt inclusion, error states, and memory persistence. |
| Operator / maintainer | Diagnoses agent customization failures without exposing sensitive owner-written instructions unnecessarily. |

### Success Definition

The `Your Agent` Settings page is successful when an owner can:

1. Open Settings in local or managed mode and find `Your Agent`.
2. Understand that global agent customization affects BrainDrive's broad working style across projects.
3. Review and edit only the owner customization overlay.
4. Save changes to the owner overlay and see a clear success state.
5. Revert unsaved draft changes without writing.
6. Inspect the managed default instructions as read-only reference.
7. Trust that managed updates can refresh the default without overwriting owner customization.
8. Trust that overlay changes are read into the runtime bootstrap prompt for subsequent agent turns.
9. See clear loading, saving, disabled, empty, and error states.
10. Trust that no provider keys, account settings, secrets, project goals, or profile facts are stored through this page unless the owner explicitly writes them as text and accepts the risk.

The work is not successful if:

1. The page writes to `AGENT.md` instead of the owner overlay.
2. Saving the overlay overwrites project-level files, profile memory, provider settings, secrets, starter-pack templates, or account data.
3. The owner cannot tell which content is managed default versus their customization.
4. A failed save leaves the UI implying the overlay changed.
5. Runtime prompt assembly ignores the saved overlay on later message requests.
6. The UI encourages storing passwords, API keys, provider credentials, billing data, or private tokens in agent instructions.
7. Owner customization is treated as stronger than safety, authorization, secret handling, or runtime validation.

### Definition Of Done (V1)

When V1 is done-done, it can:

1. Render `Your Agent` as a Settings tab in both local and managed modes.
2. Load the global managed default and owner overlay through an authorized gateway route.
3. Show the owner overlay in an editable textarea labeled `Your agent customization`.
4. Save the full overlay to the configured memory root as the owner customization file.
5. Keep the managed default read-only from Settings.
6. Show the managed default collapsed by default and expandable for inspection.
7. Disable save/revert actions when there are no unsaved changes or while saving.
8. Revert unsaved draft edits to the last loaded overlay.
9. Show loading, saving, success, and error states.
10. Attempt a memory git commit for overlay saves, matching the pattern for UI memory edits.
11. Ensure the next message request reads the current managed default plus owner overlay through bootstrap prompt assembly.
12. Include focused automated and manual verification for the Settings tab, gateway route, memory write, prompt inclusion, and auth boundaries.

Explicitly not required for done-done:

- Editing the managed default from Settings. Recommendation: keep managed default updates owned by BrainDrive release/migration flows.
- Rich structured preference editor. Recommendation: keep raw Markdown/plain-text overlay editing in V1; add guided controls later if product wants them.
- AI rewriting, summarizing, or validating owner customization from Settings. Recommendation: owner-entered text only in V1.
- Per-project agent editing from this tab. Recommendation: project instructions stay in project files and project UI.
- Account, billing, model/provider, browser access, backup, migrate, or profile management in this tab.

## Product Behavior

### User / System Experience

The owner opens Settings and selects `Your Agent`. The page explains that the global agent controls BrainDrive's personality, tone, and operating style across projects, while project and app agents add focused instructions on top.

The page has two visible content areas:

1. `Owner Customization` - an editable owner overlay. Current implementation labels the file row `AGENT-user.md`, uses textarea label `Your agent customization`, and placeholder `Add instructions for how your global agent should work with you...`.
2. `Managed Default` - a read-only, collapsible display of the managed base instructions. Current implementation labels the file row `AGENT.md`.

When the tab loads, the client calls `GET /agent`. The gateway authorizes memory access, reads the managed default from the configured memory root, reads the owner overlay when it exists, and returns both. The textarea draft is initialized from the overlay or an empty string when no overlay exists.

When the owner edits the textarea, `Save` and `Revert` become available. `Save` calls `PUT /agent` with the complete overlay text. The gateway writes the overlay and attempts a memory git commit. On success, the client reloads the agent content and shows `Your agent customization was saved.` `Revert` restores the draft to the last loaded overlay and clears local message/error state without calling the gateway.

Current implementation note: `/agent` save does not eagerly call `readBootstrapPrompt`. Message requests call `readBootstrapPrompt(runtimeConfig.memory_root)` at request time, so the overlay is expected to affect subsequent model requests through request-time prompt assembly. The client API contract currently says the gateway reloads the active bootstrap prompt after save; that wording should be clarified unless an explicit reload/cache invalidation behavior is added.

### Primary Flows

1. **Open Your Agent settings**
   - Owner opens Settings.
   - Owner selects `Your Agent`.
   - Client calls `GET /agent`.
   - Gateway authorizes `memory_access`.
   - Gateway reads the managed default and optional overlay.
   - Client renders `Owner Customization` expanded and `Managed Default` collapsed.

2. **Create first owner customization**
   - No owner overlay exists.
   - Textarea starts empty and shows the customization placeholder.
   - Owner enters global behavior instructions.
   - Owner clicks `Save`.
   - Client calls `PUT /agent` with the overlay text.
   - Gateway writes the overlay file and attempts a memory git commit.
   - Client reloads and shows success.

3. **Update existing owner customization**
   - Overlay exists.
   - Textarea starts with the saved overlay.
   - Owner edits the content.
   - `Save` becomes enabled.
   - Save writes the full updated overlay and reloads the saved state.

4. **Revert unsaved customization draft**
   - Owner changes the textarea.
   - Owner clicks `Revert`.
   - Client resets the draft to the last loaded overlay.
   - No gateway write occurs.

5. **Inspect managed default**
   - Owner expands `Managed Default`.
   - Client displays managed default content in a read-only preformatted block.
   - Owner cannot edit or save managed default content from this tab.

6. **Use overlay in later agent turns**
   - Owner saves overlay changes.
   - Owner sends a later message.
   - Gateway assembles the request-time bootstrap prompt from date context, managed base, and owner overlay.
   - Model receives the combined global instruction context subject to safety and runtime rules.

### Secondary Flows

- If agent content is loading, show `Loading your agent...` with a spinner.
- If `GET /agent` fails, show the returned error or `Failed to load your agent`.
- If managed default is missing, current gateway returns 404 `Agent not found`; V1 should show a recoverable error and avoid showing an editable surface that cannot be composed safely.
- If `PUT /agent` validation fails, show the gateway error and keep the draft in place.
- If network save fails, stay on the page, stop saving state, keep unsaved draft text, and show an error.
- If git commit fails after write, current gateway swallows the commit failure. V1 should not fail the save solely because git history is unavailable, but observability should make missing history diagnosable.
- If overlay is saved as an empty string, current behavior writes an empty overlay. Recommendation: allow empty overlay as an explicit reset path, but make the empty saved state visually clear in V1 or V2.
- If the owner closes Settings with unsaved changes, current implementation does not show an unsaved-change prompt. Recommendation: add a confirmation before treating close/navigation as source-of-truth V1 behavior.
- If overlay content is very long, the textarea and managed default display must remain scrollable without breaking the Settings modal.

### UX / Trust Bar

- The owner must understand that this page changes BrainDrive's global behavior preferences, not account identity, profile facts, model provider choice, or project goals.
- The owner must be able to distinguish the managed default from owner customization at a glance.
- The managed default must feel inspectable but not accidentally editable.
- Saving must be explicit; no autosave in V1.
- Revert must be lossless for stored overlay state.
- Loading, saving, success, and error states must be close to the edited content.
- The page must not imply owner customization overrides safety rules, memory authorization, provider secret handling, or tool approval boundaries.
- Recommendation: owner-facing copy should avoid unnecessary raw filenames unless the Settings audience is intentionally technical. If filenames remain visible, pair them with plain-language labels.

### Plain-Language Owner-Facing Expectations

- `Your Agent` means: "How BrainDrive should generally work with you."
- `Owner Customization` means: "Your personal instructions layered on top of BrainDrive's default behavior."
- `Managed Default` means: "BrainDrive's built-in global instructions; updates may improve this over time."
- Project-specific goals, plans, and agent behavior belong on the relevant project page.
- Stable facts about the owner belong in `Your Profile`, not in agent customization.
- Secrets, API keys, tokens, passwords, billing details, and private credentials do not belong here.
- Changes affect future agent turns; they do not rewrite old conversations or existing project artifacts.

## Goals

### Product Goals

- Give owners a trusted global behavior customization surface.
- Preserve BrainDrive-managed defaults while allowing owner personalization.
- Make the managed/default and owner/custom layers understandable.
- Keep global customization distinct from profile memory and project-specific instructions.
- Make the behavior auditable through plain text and memory history where available.

### User Goals

- Tell BrainDrive how to generally communicate and collaborate with me.
- Keep my personal preferences across projects without repeating them every time.
- Inspect BrainDrive's default agent instructions when I need to understand the baseline.
- Undo unsaved edits before they take effect.
- Avoid losing my customization when BrainDrive updates its managed default.

### Engineering Goals

- Keep Settings backed by the configured memory root, not duplicate client state.
- Keep `/agent` routes small, authorized, validated, and memory-root bounded.
- Reuse existing Settings modal patterns, authenticated fetch, icons, disabled states, and memory git commit behavior.
- Ensure runtime prompt assembly reads the overlay at the right time.
- Maintain compatibility with the protected `your-agent` project identity and legacy `braindrive-plus-one` migration behavior.
- Add focused tests without broad Settings refactors.

### Safety / Security / Trust Goals

- Require authorization for agent instruction read/write.
- Treat owner customization as sensitive owner memory.
- Do not log overlay contents in normal telemetry or error output.
- Do not store secrets or credentials in global agent customization.
- Prevent owner customization from overriding safety, authorization, secret handling, approval, or runtime validation rules.
- Keep managed defaults controlled by release/migration flows, not arbitrary client writes.

### Non-Goals

- No project-specific agent editor in this Settings tab.
- No profile fact editor in this Settings tab.
- No provider/model/account/billing/backup/migrate/browser-access behavior in this tab.
- No hidden AI rewriting or validation of owner-entered customization.
- No automatic migration of project agent overlays into the global overlay.
- No owner ability to disable required BrainDrive safety or memory rules through customization text.

## User Stories

### US-1: View Global Agent Layers - **Confirmed**

As a BrainDrive owner, I want to view my owner customization and the managed default so that I understand what global instructions shape BrainDrive.

**Source:** Implementation review of `SettingsModal.tsx`, `gateway-adapter.ts`, gateway `/agent` routes, `config.ts` bootstrap prompt assembly, and current Settings tests.

**Acceptance Criteria:**

```gherkin
Given Settings is open
When I select the Your Agent tab
Then the client requests GET /agent
And the gateway reads the managed default from the configured memory root
And the gateway returns the owner overlay when one exists
And the page shows Owner Customization and Managed Default as separate sections
```

```gherkin
Given the owner overlay does not exist
When the Your Agent tab loads
Then the customization textarea is empty
And the placeholder invites the owner to add global agent instructions
And the managed default remains available as read-only reference
```

### US-2: Save Owner Customization - **Confirmed**

As a BrainDrive owner, I want to save global agent customization so that future BrainDrive conversations use my preferred operating style.

**Source:** Implementation review of `updateRootAgentOverlay`, gateway `/agent` route, `readBootstrapPrompt`, and `SettingsModal.test.tsx`.

**Acceptance Criteria:**

```gherkin
Given the Your Agent tab has loaded
And I enter new text in Your agent customization
When I click Save
Then the client sends PUT /agent with overlay_content equal to the full draft
And the gateway validates the request body
And the gateway writes only the owner overlay under the configured memory root
And the managed default is not modified
And the page reloads the saved content
And the page shows "Your agent customization was saved."
```

```gherkin
Given the overlay was saved
When I send a later message
Then the runtime bootstrap prompt includes the managed default
And the runtime bootstrap prompt includes the saved owner overlay
And the owner overlay is still subordinate to safety, authorization, and runtime validation
```

### US-3: Revert Unsaved Draft - **Confirmed**

As a BrainDrive owner, I want to revert unsaved customization edits so that experimentation does not accidentally change my global agent.

**Source:** Implementation review of `YourAgentSection.handleRevert`.

**Acceptance Criteria:**

```gherkin
Given my saved owner customization is loaded
And I change the customization textarea
When I click Revert
Then the draft resets to the last loaded overlay
And no PUT /agent request is sent
And local error and success messages are cleared
```

### US-4: Inspect Managed Default Read-Only - **Confirmed**

As a BrainDrive owner, I want to inspect the managed default without editing it so that I can understand the baseline my customization layers onto.

**Source:** Implementation review of the `Managed Default` collapsible section and gateway GET behavior.

**Acceptance Criteria:**

```gherkin
Given the Your Agent tab has loaded
When I expand Managed Default
Then I see the managed default content in a read-only display
And there is no control that saves edits to managed default content
And the owner customization textarea remains the only editable agent content on the page
```

### US-5: Handle Load And Save Failures - **Confirmed**

As a BrainDrive owner, I want clear failure states so that I know whether my global agent customization changed.

**Source:** Implementation review of `YourAgentSection.loadAgent`, `YourAgentSection.handleSave`, and gateway error behavior.

**Acceptance Criteria:**

```gherkin
Given GET /agent fails
When the Your Agent tab loads
Then the page shows the returned error or "Failed to load your agent"
And the page does not claim customization was saved
```

```gherkin
Given PUT /agent fails
And I have unsaved draft content
When I click Save
Then the page keeps my draft visible
And the page shows the returned error or "Failed to save your agent"
And the page does not show the success message
```

### US-6: Keep Your Agent Separate From Projects - **Confirmed**

As a BrainDrive owner, I want global agent customization to stay separate from project goals and plans so that broad behavior preferences do not corrupt project work.

**Source:** Starter-pack `your-agent/AGENT.md`, root agent project constants, gateway project protection tests, and product request.

**Acceptance Criteria:**

```gherkin
Given I save text in Your Agent settings
When the gateway writes the customization
Then it writes the global owner overlay
And it does not write documents/your-agent/spec.md
And it does not create a Your Agent plan
And it does not change any project spec, plan, journal, or project AGENT file
```

### US-7: Preserve Managed Default Updates - **Recommended**

As a BrainDrive maintainer, I want owner customization stored separately from managed defaults so that managed improvements can ship without overwriting owner preferences.

**Source:** Current implementation and product recommendation.

**Acceptance Criteria:**

```gherkin
Given BrainDrive updates the managed default instructions
And an owner has an existing customization overlay
When the updated app reads global agent instructions
Then the updated managed default is read
And the owner's customization overlay is still read after it
And the owner customization file is not overwritten by the managed update
```

**Recommendation:** Treat this as a confirmed V1 invariant unless a future migration explicitly needs to transform overlay content with owner-visible backup and review.

### US-8: Warn Against Sensitive Content - **Recommended**

As a BrainDrive owner, I want the Settings page to warn me not to store secrets in agent instructions so that I do not accidentally expose credentials to future prompts.

**Source:** Security review of global prompt behavior and BrainDrive memory rules.

**Acceptance Criteria:**

```gherkin
Given I am editing Your agent customization
When I review the page guidance
Then I see clear language that secrets, API keys, tokens, passwords, and billing details do not belong here
And the page does not suggest using agent customization as credential storage
```

**Recommendation:** Add this warning before treating the page as complete source-of-truth V1 because overlay content can enter model prompts.

### US-9: Protect Unsaved Changes On Close Or Tab Switch - **Open**

As a BrainDrive owner, I want protection from accidental navigation away with unsaved customization so that I do not lose edits silently.

**Source:** Inferred from current behavior gap; no existing unsaved-change guard found in implementation review.

**Acceptance Criteria:**

```gherkin
Given I have unsaved Your Agent customization changes
When I close Settings or switch tabs
Then the system either asks me to confirm discarding changes
Or preserves the draft until I return during the same Settings session
```

**Recommendation:** Add a simple discard confirmation for V1 if implementation scope allows. If not, mark this as a known V1 limitation and test the current behavior explicitly.

### US-10: Clarify Runtime Effect Timing - **Open**

As a BrainDrive owner and QA reviewer, I want to know when saved customization affects agent behavior so that test expectations are accurate.

**Source:** Difference between current API contract wording and implementation/test evidence.

**Acceptance Criteria:**

```gherkin
Given I save Your Agent customization
When I send a new message after the save completes
Then the new message uses the current overlay in the bootstrap prompt
And product copy does not imply old conversations or in-flight responses are rewritten
```

**Recommendation:** Source-of-truth V1 should say changes affect subsequent message requests. Update stale contract wording if it claims eager reload behavior that does not exist.

## Requirements

### Functional Requirements

- [ ] `Your Agent` must be available in Settings in both local and managed modes.
- [ ] The tab must load global agent content only when selected or otherwise needed by the Settings modal.
- [ ] `GET /agent` must require memory access authorization.
- [ ] `GET /agent` must return managed default content and nullable owner overlay content.
- [ ] Missing managed default must produce a clear error; the UI must not silently create or overwrite it.
- [ ] Missing owner overlay must be represented as `null` from the API and an empty editable draft in the UI.
- [ ] The owner overlay textarea must be the only editable agent instruction surface on this page.
- [ ] `PUT /agent` must require memory access authorization.
- [ ] `PUT /agent` must validate that `overlay_content` is a string.
- [ ] `PUT /agent` must write the full overlay content to the configured memory root overlay file.
- [ ] `PUT /agent` must not write the managed default.
- [ ] `PUT /agent` must not write profile, provider, account, backup, export, browser access, project, or starter-pack files.
- [ ] Overlay saves must attempt a memory git commit using a clear message such as `Update global agent overlay via UI`.
- [ ] Git commit failure must not be misreported as content save failure if the file write succeeded, but it should be diagnosable.
- [ ] The UI must disable `Save` when there are no unsaved changes.
- [ ] The UI must disable `Save` and `Revert` while saving.
- [ ] `Revert` must restore the last loaded overlay without writing.
- [ ] The managed default must be collapsed by default and read-only when expanded.
- [ ] The runtime bootstrap prompt must read the managed default first and the owner overlay second when present.
- [ ] Owner overlay instructions must not override safety, authorization, secret handling, or runtime validation.

### AI / Model / Tool Behavior

No AI/model behavior is required to edit or save the Settings page itself. The Settings page is a direct owner-controlled text editor backed by gateway file APIs.

Because the saved overlay is included in future model prompts, these boundaries apply:

- [ ] The overlay may guide tone, communication style, routing preferences, approval preferences, and broad operating style.
- [ ] The overlay must not be treated as permission to bypass safety, authorization, tool approval, secret handling, or runtime validation.
- [ ] The overlay must not be used as credential storage.
- [ ] The overlay must not automatically rewrite project files, profile memory, or other artifacts.
- [ ] Future AI-assisted editing of the overlay requires separate scope, visible preview, owner approval, and tests proving it does not insert secrets or unsupported capabilities.

### Data, Memory, And Artifact Contracts

| Data / Artifact | Source | Owner | Read/Write Rules | Retention / Migration |
|---|---|---|---|---|
| Managed global agent default (`AGENT.md`) | Starter-pack/base memory initialization and managed update/migration flows | BrainDrive product/runtime maintainers | Read by `GET /agent` and `readBootstrapPrompt`; not written by Your Agent Settings | Persisted in owner memory root; managed updates must preserve owner overlay |
| Owner global agent overlay (`AGENT-user.md`) | Owner edits in Settings, possible advanced file edits | BrainDrive owner | Read/write through `/agent`; read by `readBootstrapPrompt` after managed default; no secrets | Persisted in owner memory root; included in memory git history where available; must survive managed default updates |
| `GET /agent` response | Gateway memory read | Gateway API contract | Returns `{ managed_content, overlay_content }`; requires `memory_access`; no raw unrelated memory | Response is transient client state |
| `PUT /agent` request | Settings client | Gateway API contract | Accepts `{ overlay_content: string }`; writes only owner overlay; requires `memory_access` | Persisted as overlay file; commit attempted |
| Settings draft state | React component state | Client UI | Initialized from overlay; can diverge while editing; lost on close unless future guard/persistence is added | Transient per Settings session |
| Success/error message state | React component state | Client UI | Shows save/load results; must not include sensitive overlay content | Transient |
| Runtime bootstrap prompt | Gateway request-time prompt assembly | Runtime engine/gateway | Combines current date, managed default, and owner overlay; used as model system prompt source | Transient per model request; prompt audit may snapshot sources when enabled |
| Protected `your-agent` project manifest entry | Memory init/project service | BrainDrive memory/project system | Canonical id `your-agent`; legacy id `braindrive-plus-one`; protected from rename/delete | Migrated/normalized by init/project service; not edited by Settings `/agent` |
| Project-level agent files | Project folders under memory documents | Owner/project system | Not read or written by Your Agent Settings except as separate project UI/file flows | Persist with project memory; separate from global overlay |
| Logs/audit events | Gateway and runtime | Operator/maintainer | May log route/status/error metadata; must not log full overlay content by default | Retained according to app logging behavior |

### Interface / UX Requirements

- [ ] Tab label: `Your Agent`.
- [ ] Page heading: `Your Agent`.
- [ ] Current description: `Your global agent controls the personality, tone, and operating style BrainDrive uses across every project. Project and app agents add focused instructions on top of this one.`
- [ ] Section label: `Owner Customization`.
- [ ] Textarea accessible label: `Your agent customization`.
- [ ] Textarea placeholder: `Add instructions for how your global agent should work with you...`.
- [ ] Primary action labels: `Save`, `Saving...`.
- [ ] Secondary action label: `Revert`.
- [ ] Read-only section label: `Managed Default`.
- [ ] Loading copy: `Loading your agent...`.
- [ ] Success copy: `Your agent customization was saved.`
- [ ] Error copy must use gateway error text when available, otherwise `Failed to load your agent` or `Failed to save your agent`.
- [ ] `Owner Customization` should be expanded by default.
- [ ] `Managed Default` should be collapsed by default.
- [ ] Save button should use the amber primary style with dark readable text according to design tokens; current implementation uses white text on amber and should be checked against the design-system rule.
- [ ] Textarea must be monospaced, resizable, and tall enough for multi-paragraph instructions.
- [ ] Long managed default and overlay content must scroll without expanding the modal beyond usable bounds.
- [ ] Recommendation: include a concise warning that secrets and credentials do not belong in global agent instructions.
- [ ] Recommendation: include an unsaved-change guard or explicitly document that unsaved drafts are discarded on close/tab switch.

### Observability / Evidence Requirements

- [ ] Gateway route tests must prove unauthenticated requests are rejected.
- [ ] Gateway route tests must prove `GET /agent` reads managed default and nullable overlay.
- [ ] Gateway route tests must prove `PUT /agent` writes only the overlay.
- [ ] Runtime tests must prove a message request reads the current bootstrap prompt after an overlay save.
- [ ] Client tests must prove the tab loads, saves, reverts, and displays managed default only after expansion.
- [ ] Manual QA must capture screenshots of loading, empty overlay, edited draft, saved success, managed default expanded, and save error states.
- [ ] Security review evidence must confirm overlay content is not logged by default and raw secrets are not introduced into client config.
- [ ] Verification output must include exact commands, pass/fail result, and any blocked checks.

## Scope

### Work Type

- [x] **V1** - First complete source-of-truth behavior for this Settings page.
- [x] **Production** - Owner-facing settings behavior with auth, persistence, error states, and regression coverage.
- [x] **Documentation/specification** - Defines product and engineering contract.
- [x] **Interface / shell** - Settings modal tab and controls.
- [x] **Backend / gateway** - `/agent` routes and memory writes.
- [x] **Memory** - Global managed/default and owner overlay files.
- [x] **Testing / harness** - Focused UI, gateway, runtime, and manual verification.

### Implementation Location / Ownership

- `builds/typescript/client_web/src/components/settings/SettingsModal.tsx` - Settings tab list and `YourAgentSection`.
- `builds/typescript/client_web/src/components/settings/SettingsModal.test.tsx` - client behavior tests.
- `builds/typescript/client_web/src/api/gateway-adapter.ts` - `getRootAgent` and `updateRootAgentOverlay`.
- `builds/typescript/client_web/src/api/types.ts` - gateway response/request type ownership if expanded.
- `builds/typescript/client_web/src/api/CONTRACT.md` - documented `/api/agent` contract.
- `builds/typescript/gateway/server.ts` - `GET /agent`, `PUT /agent`, message prompt assembly, prompt audit source snapshots.
- `builds/typescript/gateway/auth-routes.integration.test.ts` - route/auth/runtime prompt integration coverage.
- `builds/typescript/config.ts` - `readBootstrapPrompt` managed/default plus overlay assembly.
- `builds/typescript/memory/root-agent.ts` - canonical protected `your-agent` project identity.
- `builds/typescript/gateway/projects.ts` - protected root-agent project service behavior.
- `builds/typescript/memory/init.ts` - starter-pack initialization, root-agent identity migration, fallback base agent content.
- `builds/typescript/memory/starter-pack/base/AGENT.md` - managed global default source template.
- `builds/typescript/memory/starter-pack/projects/templates/your-agent/AGENT.md` - protected Your Agent project behavior template.

### Included

- Settings `Your Agent` tab behavior in local and managed modes.
- Owner customization overlay load, edit, save, revert, and success/error states.
- Managed default read-only inspection.
- Gateway `/agent` read/write contract.
- Runtime bootstrap prompt inclusion boundary.
- Memory file ownership and migration expectations.
- Security/trust rules for prompt-affecting owner text.
- Focused verification strategy and acceptance evidence.

### Explicitly Excluded

- Editing managed default instructions from Settings.
- Editing project-level `AGENT.md` or `AGENT-user.md` files from this tab.
- Creating or maintaining a Your Agent `spec.md` or `plan.md`.
- Profile editing; that belongs to `Your Profile`.
- Provider/model/key/credits behavior; that belongs to `AI Models`.
- Account, billing, password, email, subscription, backup, migrate, and browser access behavior.
- Rich preference schemas, guided forms, and AI-authored customization.
- External tool permissions, browser automation permissions, calendar/email access, reminders, or autonomous outside-world execution.

### Future Versions / Deepenings

- Guided global preference controls that compile to a transparent overlay.
- Diff view between managed default, previous overlay, and draft.
- Unsaved-change confirmation on close/tab switch.
- Restore previous overlay from memory history.
- Inline validation for unsafe claims such as "ignore safety" or credential-like content, with owner-controlled save.
- Plain-language display that hides filenames by default while keeping technical details available.
- Export/import preview of global agent customization during migrate flows.
- Separate project-level agent editor with clear project scoping, if product later approves it.

## Invariants And Edge Cases

### Properties That Must Always Hold

- The managed global default and owner overlay are separate layers.
- Settings writes only the owner overlay.
- Managed default is read-only from this page.
- Owner overlay cannot override safety, authorization, secret handling, approval, or runtime validation.
- `Your Agent` Settings does not write profile facts, project goals, project plans, project journals, provider settings, account data, backup settings, or secrets.
- Runtime prompt assembly reads managed default first and owner overlay second.
- Missing or invalid managed default is a visible error, not a silent destructive repair.
- Failed save does not show success.
- Revert does not write.
- Owner overlay content is sensitive and must not be logged by default.
- Protected `your-agent` project identity remains canonicalized and protected from rename/delete.

### Edge Cases To Test

- No owner overlay exists.
- Empty overlay exists.
- Very long overlay content.
- Overlay contains Markdown headings, lists, code fences, and plain text.
- Overlay contains text that looks like a credential.
- Managed default missing.
- GET `/agent` returns 401/403.
- GET `/agent` returns 404.
- PUT `/agent` body is missing `overlay_content`.
- PUT `/agent` body has non-string `overlay_content`.
- PUT `/agent` fails due to network/server error.
- File write succeeds but git commit fails.
- Owner edits then clicks `Revert`.
- Owner edits then closes Settings or switches tabs.
- Owner expands and collapses managed default.
- Local and managed mode tab lists both include `Your Agent`.
- Legacy root agent project id `braindrive-plus-one` exists in manifest.
- Subsequent message after save reads current overlay through request-time prompt assembly.

### Failure Modes

| Scenario | Expected Behavior |
|---|---|
| Managed default file is missing | Gateway returns a clear not-found error; UI shows a load error; no overlay write is attempted automatically. |
| Owner overlay is missing | Gateway returns `overlay_content: null`; UI shows an empty editable customization draft. |
| Overlay save request is invalid | Gateway returns invalid request; UI keeps draft and shows error. |
| Overlay file write fails | UI shows save error; success message is not shown; draft remains visible. |
| Git commit fails after file write | Save may still succeed; missing history is logged/diagnosable without exposing overlay text. |
| Owner stores credential-like text | V1 should warn against this; runtime must still treat it as prompt text, never as a secret source. |
| Owner writes instruction to ignore safety | Runtime safety, authorization, secret handling, and validation still win. |
| Owner switches tabs with unsaved changes | Open: recommended confirmation or documented draft-loss behavior. |
| Runtime prompt cache exists in future | Save must invalidate cache or next message must otherwise read current overlay before model call. |
| Legacy `braindrive-plus-one` project exists | Project services normalize to `your-agent`; Settings global overlay behavior remains independent. |

## Technical Context

### Existing System Context

Current implementation already includes a `Your Agent` tab in `SettingsModal.tsx`. The tab is visible in both local and managed modes. Local mode tab order is `AI Models`, `Your Profile`, `Your Agent`, `Browser Access` when desktop, `Backup`, and `Migrate`. Managed mode tab order is `Account`, `Your Profile`, `Your Agent`, and `Migrate`.

`YourAgentSection` loads agent content with `getRootAgent`, stores `managedContent`, nullable `overlayContent`, and editable `draft` state, and initializes the draft from the overlay or empty string. The section displays a top-level description, an info panel explaining the managed/default and overlay split, an expanded `Owner Customization` editor, and a collapsed `Managed Default` read-only block.

The client adapter calls:

- `GET /agent`, returning `{ managed_content, overlay_content }`.
- `PUT /agent`, sending `{ overlay_content }`.

The gateway routes authorize `memory_access`. `GET /agent` reads the managed default and optional owner overlay from `runtimeConfig.memory_root`. `PUT /agent` validates the body through `rootAgentUpdateSchema`, writes the overlay, attempts `commitMemoryChange`, and returns `{ ok: true }`.

`readBootstrapPrompt` in `config.ts` reads the managed default, optional owner overlay, and current date. It assembles a prompt that explicitly says overlays personalize or narrow behavior but do not override safety, preservation rules, authorization, secret handling, or runtime validation.

The `/message` route calls `readBootstrapPrompt(runtimeConfig.memory_root)` at request time before composing skills and sending the model request. Existing integration tests verify message requests use request-time bootstrap prompt content rather than a stale startup prompt.

The protected `your-agent` project is a related but separate surface. It is the general entry point/router project in the project list, with canonical id `your-agent`, legacy id `braindrive-plus-one`, display name `Your Agent`, icon `sparkles`, and starter template `projects/templates/your-agent/AGENT.md`. Project services protect canonical and legacy root-agent ids from rename/delete. The starter template explicitly says Your Agent does not maintain its own spec or plan.

### Integration Points

- **UI:** Settings modal, tab filtering by mode, collapsible panels, textarea controls, success/error banners.
- **API:** `GET /agent`, `PUT /agent`, authenticated fetch, local owner headers.
- **Backend:** Fastify gateway route authorization, zod request validation, memory file reads/writes.
- **Runtime:** Request-time bootstrap prompt assembly and model system prompt source.
- **Storage:** Configured memory root, managed default, owner overlay, git history where available.
- **Auth:** `memory_access` authorization for read/write.
- **Project system:** Protected `your-agent` project identity and legacy migration.
- **Starter pack:** Base global agent template and Your Agent project template.
- **Tests:** Settings modal tests, auth route integration tests, project service tests, memory init/root-agent tests, prompt context tests.
- **Docs:** Client API contract and this source-of-truth spec.

### Hard Constraints

- Do not put BrainDrive-owned provider keys or owner API keys in global agent files.
- Do not use owner customization as a credential source.
- Do not let owner customization override safety, authorization, secret handling, tool approval, or runtime validation.
- Do not write managed default from this Settings page.
- Do not confuse the Settings `Your Agent` tab with the protected `your-agent` project page.
- Do not create a Your Agent spec or plan as part of this Settings feature.
- Do not change memory path resolution casually.
- Do not hard-code production/staging URLs.
- Do not remove Ollama, BYOK OpenRouter, BrainDrive Models, backup, migrate, account, profile, or browser access settings while working in this area.

### Build Workflow Inputs

- Keep edits scoped to `YourAgentSection`, `/agent` routes, adapter contract, and focused tests unless a broader product decision is approved.
- If adding copy, align with existing dark-mode design tokens and avoid light text on amber primary fills.
- If changing runtime effect semantics, update both implementation and `client_web/src/api/CONTRACT.md`.
- If adding unsaved-change protection, coordinate with other Settings tabs so modal/tab navigation behavior remains consistent.
- If adding secret-like content warnings, keep them local and non-blocking unless a separate validation policy is approved.
- If changing starter-pack defaults, add migration/update handling for existing owner memory without overwriting customized owner files.

## Test Strategy

### Test Levels Required

- **Unit:** root-agent id normalization/protection helpers, request schema validation if changed.
- **Client component:** `Your Agent` tab rendering, load state, edit/save/revert, managed default expansion, disabled states, error states, local/managed visibility.
- **Gateway integration:** authenticated GET/PUT, unauthenticated rejection, missing managed default, missing overlay, invalid body, file write, commit attempt behavior.
- **Runtime integration:** saved overlay appears in subsequent bootstrap prompt/model request; overlay remains subordinate to safety/runtime boundary text.
- **Regression:** profile tab, AI Models tab, backup/migrate tab, account tab, project list/root-agent protection, message sending.
- **Manual verification:** UI screenshots across normal, empty, edited, saving, saved, managed-expanded, and failure states.
- **Security verification:** no secrets in client config, no overlay content in normal logs, auth boundaries enforced.

### Verification Approach

Recommended commands from the repo root:

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

```bash
cd builds/typescript
npm run web:test -- SettingsModal
```

```bash
cd builds/typescript
npm run test -- auth-routes.integration
```

```bash
cd builds/typescript
npm run test -- root-agent projects project-chat-context
```

Before release or broader Settings changes:

```bash
cd builds/typescript
npm run build
```

Manual QA should inspect the Settings modal in local mode and managed mode. If UI changes are made, capture desktop and narrow viewport screenshots for the `Your Agent` tab, including long content behavior.

### Acceptance Evidence

- Test output showing focused client and gateway tests pass.
- Test output or prompt-audit evidence showing request-time prompt includes the saved overlay after save.
- Screenshot of empty overlay state.
- Screenshot of edited unsaved draft with enabled actions.
- Screenshot of saved success state.
- Screenshot of managed default expanded.
- Screenshot or test evidence for load/save error state.
- Security review note confirming no credential/config regressions.
- File diff showing no unrelated settings/provider/profile/project changes.

### Baseline / Regression Impact

Existing flows that must continue working:

- Settings modal opens and closes with Escape and close controls.
- Local mode still shows `AI Models`, `Your Profile`, `Your Agent`, desktop-only `Browser Access`, `Backup`, and `Migrate`.
- Managed mode still shows `Account`, `Your Profile`, `Your Agent`, and `Migrate`.
- `Your Profile` still reads/writes `me/profile.md`.
- AI Models provider choice, BrainDrive Models credits, OpenRouter BYOK, and Ollama remain independent.
- Memory backup and migration settings remain local-mode scoped.
- Protected `your-agent` project remains present, canonicalized, and protected from rename/delete.
- Project-level AGENT files remain editable only through their own project/file mechanisms.
- Message sending continues to build a valid system prompt and stream responses.

## Security, Privacy, And Trust Considerations

### Risk Level

**Medium.** The page does not directly handle credentials, payments, code execution, or external network calls beyond the local gateway. However, it writes prompt-affecting owner memory that can shape every future model request. Bad or sensitive content in the overlay can create trust, privacy, and behavior risks.

### Threat / Trust Assessment

| Area | Assessment |
|---|---|
| User input | Free-form owner text; may include sensitive preferences, private facts, or credential-like strings. |
| Code execution | No direct code execution from this page; text may influence future model/tool behavior but must remain subordinate to approval/runtime rules. |
| Data sensitivity | High-context behavioral preferences; can reveal communication needs, privacy boundaries, or owner situation. |
| Network surface | Client talks to authenticated local/managed gateway routes; no direct third-party calls from this tab. |
| Model/tool behavior | Overlay enters future prompts and can influence model style/routing; must not override tools, auth, secret handling, or safety. |
| Blast radius | Global across projects and future turns; a bad overlay can degrade many workflows. |
| Owner trust | High. The owner needs clear separation between managed default, owner customization, profile facts, and project data. |

### Required Mitigations

- Require `memory_access` authorization for `/agent`.
- Validate request body shape before write.
- Keep writes bounded to the configured memory root overlay path.
- Never write managed default from Settings.
- Do not log full overlay content by default.
- Show clear managed/default versus owner/custom labels.
- Warn owners not to store secrets or credentials in customization.
- Keep overlay subordinate to safety, authorization, secret handling, and runtime validation in bootstrap prompt text and runtime behavior.
- Attempt git history for saves where available.
- Preserve owner overlay across managed default updates.
- Add or document unsaved-change behavior.

## Explicit Boundaries

### Do Not Modify Without Updated Scope

- `AI Models` provider/credits/key behavior.
- BrainDrive-owned provider key provisioning.
- OpenRouter BYOK or Ollama availability.
- Account, billing, password, email, or subscription behavior.
- `Your Profile` memory contract.
- Backup/migrate/browser access flows.
- Project file editing semantics.
- Memory path resolution, import/export, backup/restore, or history semantics.
- Starter-pack managed default content beyond explicit agent-default work.
- Protected root-agent project migration rules.
- Runtime safety, authorization, approval, and secret-handling policies.

### Do Not Introduce

- Client-visible BrainDrive-owned provider keys.
- Any behavior that treats global agent customization as a credential store.
- Autosave without an explicit product decision and recovery strategy.
- Editing `AGENT.md` from this Settings tab.
- Silent overwrites of owner overlay during managed default updates.
- AI-generated overlay rewrites without preview and owner approval.
- Claims that customization can grant external account, browser, email, calendar, reminder, purchasing, or autonomous execution abilities.
- Logging of full overlay content in normal app logs.
- Broad Settings refactors unrelated to this tab.
- Light text on amber primary fills if it violates the design-system contrast rule.

### Out Of Scope Even If Related

- Your Agent project page redesign.
- Project-specific agent customization editor.
- Profile memory capture and profile Settings behavior.
- Model/provider setup and credit purchase flows.
- External tool calling permissions.
- Owner onboarding interviews.
- Memory backup/migrate UX.
- Hosted deployment/staging pipeline behavior.
- Full prompt management/versioning system.

## Open Questions And Recommendations

1. **Should unsaved changes be guarded on close/tab switch?**
   - **Recommendation:** Yes. Add a simple confirmation or preserve draft state during the Settings session. If not implemented in V1, document and test the current draft-loss behavior.

2. **Should filenames remain visible in owner-facing Settings copy?**
   - **Recommendation:** Keep plain-language labels primary. Filenames can remain as secondary technical context if product wants transparency, but the page should not require owners to understand file names.

3. **Should empty overlay save be treated as reset?**
   - **Recommendation:** Yes. Allow saving an empty overlay as an explicit reset to managed default behavior, and show a clear empty/customization-not-set state after save.

4. **Should the client API contract claim immediate bootstrap reload?**
   - **Recommendation:** Update the wording to "changes affect subsequent message requests" unless implementation adds explicit cache invalidation/reload semantics.

5. **Should the page warn against secrets before save or always near the textarea?**
   - **Recommendation:** Always show a concise warning near the textarea. Do not block saves in V1 unless separate validation scope is approved.

6. **Should owner customization support Markdown rendering or remain plain textarea only?**
   - **Recommendation:** Keep plain textarea only in V1. A preview/diff view is useful later, but not required for direct customization.

7. **Should managed hosted mode use the same memory files and route behavior as local mode?**
   - **Recommendation:** Keep the UI contract identical, but verify hosted storage/auth deployment details before changing managed behavior.

8. **Should overlay saves produce user-visible history or restore UI?**
   - **Recommendation:** Not required for V1. Continue committing where available and consider restore/diff in V2.

## Changelog

- 2026-07-09: Initial source-of-truth spec created from product request and current implementation review.

## Conversation References

- User request: create a complete source-of-truth spec for `The Your Agent Settings Page`.
- Reviewed repo: `/home/hex/Project/BrainDrive-Test-01/`.
- Reviewed adjacent specs: `settings-ai-models-page-spec.md`, `settings-your-profile-page-spec.md`.
- Reviewed implementation paths listed in Technical Context.

## Approval

Status: **Draft for product/engineering review**.

Recommended next step: review the open questions, accept or adjust the recommendations, then create a verification plan before implementation changes.
