# Spec: Your Profile Settings Page

> **Purpose:** Builder-facing BrainDrive product/engineering spec for the Settings page that displays and edits the owner profile.
> **Generated from:** Product request and current implementation review on 2026-07-09.
> **Primary product surface:** Settings modal, `Your Profile` tab, local and managed modes.
> **Recommendation:** Treat `me/profile.md` as the source of truth, keep the Settings page as a direct Markdown review/edit surface, and align the visible page heading to `Your Profile` for owner-facing consistency. Preserve AI-mediated profile capture as the primary path; direct editing is the owner's review and correction path.

## Overview

### What This Covers

The `Your Profile` Settings page lets a BrainDrive owner review and directly edit the cross-project owner profile stored at `me/profile.md`. The profile is BrainDrive's canonical home for stable facts, values, preferences, life context, and BrainDrive behavior preferences that matter across multiple projects.

This spec covers the owner-facing behavior, gateway API contract, memory file contract, trust boundaries, current implementation, recommended V1 gaps, and verification expectations for the `Your Profile` 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 value depends on remembering the right owner context without making the owner repeat themselves. The profile is high-trust memory because it can affect every project, recommendation, interview, plan, and agent response. The Settings page is the owner's plain review surface for that memory: they need to see what BrainDrive believes, correct it, remove it, and inspect the raw Markdown when needed.

The page is unsuccessful if it hides the profile, makes the owner edit a disconnected account profile instead of `me/profile.md`, silently loses profile content, stores secrets or one-project facts in the profile, or lets a malformed direct edit break future owner-memory workflows without recovery.

### Target Audience And Stakeholders

| Audience | Role / Need |
|---|---|
| Local BrainDrive owner | Needs a trusted way to inspect, correct, or remove cross-project profile facts stored on their machine. |
| Managed BrainDrive owner | Needs the same owner-memory review/edit surface while account and billing remain separate. |
| Builder / implementation owner | Maintains Settings UI, profile API wrappers, gateway `/profile` routes, memory-root path handling, git history, and Markdown rendering. |
| QA / harness audience | Verifies tab visibility, profile load/save behavior, empty/error states, Markdown rendering, edit/cancel/save flows, auth boundaries, and memory persistence. |
| Operator / maintainer | Diagnoses profile access/save failures without reading sensitive owner profile content unnecessarily. |

### Success Definition

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

1. Open Settings in local or managed mode and find `Your Profile`.
2. See the current `me/profile.md` content rendered as readable Markdown.
3. Understand that the profile is built through conversation and contains stable cross-project context.
4. Enter edit mode, change the Markdown, save, and see the updated rendered profile.
5. Cancel edits without changing the stored profile.
6. See a useful empty state if no profile exists yet.
7. See clear loading and error states if the profile cannot be read or saved.
8. Trust that profile saves write only to the owner profile file and preserve version history when git commit is available.

The work is not successful if:

1. The Settings page edits account name/email, provider settings, or agent instructions when the owner expects to edit `me/profile.md`.
2. A save overwrites unrelated memory files, starter-pack templates, owner overlays, secrets, or project artifacts.
3. A failed save leaves the UI implying the profile changed.
4. Raw Markdown is rendered unsafely or enables script execution.
5. Profile content is logged, sent to third-party services, or exposed through unauthenticated routes.
6. Direct edits normalize, reformat, truncate, or migrate profile content without explicit implementation scope.

### Definition Of Done (V1)

When V1 is done-done, it can:

1. Render `Your Profile` as a Settings tab in both local and managed modes.
2. Load `me/profile.md` through an authenticated/authorized gateway route.
3. Render existing profile Markdown in a safe, owner-readable view.
4. Show the owner session avatar/name as context without treating that account/session identity as the profile file.
5. Enter edit mode with the exact current file content.
6. Save full Markdown content back to `me/profile.md`.
7. Cancel edit mode without writing.
8. Show empty, loading, saving, and error states.
9. Preserve profile file path boundaries and write only under the configured memory root.
10. Attempt a memory git commit for UI profile saves, matching the decision that UI file edits should have history.
11. Include focused automated and manual verification for the profile tab and gateway profile routes.

Explicitly not required for done-done:

- Rich structured profile editor. Recommendation: keep raw Markdown edit in V1; a guided editor can be V2.
- AI rewriting or summarizing the profile from Settings. Recommendation: direct Settings edits are owner-controlled only.
- Profile diff/preview UI. Recommendation: future improvement, not V1 scope.
- Cross-device sync beyond existing memory backup/migrate/managed storage behavior.
- Account profile management. Account name/email/password/billing belong in Account, not `Your Profile`.

## Product Behavior

### User / System Experience

The owner opens Settings and selects `Your Profile`. The page explains that the profile builds naturally through conversation and captures stable facts about the owner's life, work, goals, and interaction preferences that personalize BrainDrive.

The page shows a small owner identity header using session data from `/session`: initials, display name, and role label `Owner`. This identity header is context only. The editable source of truth is the Markdown profile loaded from `/profile`.

When not editing, the page renders profile Markdown using the shared Markdown renderer. If the profile does not exist, the page shows an empty state: `No profile yet. Start a conversation and ask your partner to build your profile.`

When editing, the page replaces the rendered view with a monospaced textarea containing the current Markdown content. The owner can save or cancel. Save writes the entire draft to `me/profile.md`, exits edit mode on success, then reloads the saved profile. Cancel restores the last loaded profile content and exits edit mode.

Current implementation note: the tab label is `Your Profile`, but the section heading is `Owner Profile`. V1 should align owner-facing copy to `Your Profile` unless product explicitly wants a tab/heading distinction.

### Primary Flows

1. **Open profile tab**
   - Owner opens Settings.
   - Owner selects `Your Profile`.
   - Client calls `GET /profile`.
   - Gateway authorizes `memory_access`, reads `<memory_root>/me/profile.md`, and returns `{ content }`.
   - Client renders the returned Markdown or the empty state.

2. **Edit and save profile**
   - Owner clicks `Edit`.
   - Client copies the latest loaded profile content into the draft textarea.
   - Owner changes Markdown.
   - Owner clicks `Save`.
   - Client calls `PUT /profile` with `{ content: draft }`.
   - Gateway validates that `content` is a string, creates `<memory_root>/me` if needed, writes `profile.md`, and attempts `commitMemoryChange(..., "Update owner profile via UI")`.
   - Client exits edit mode and reloads from `GET /profile`.

3. **Cancel profile edit**
   - Owner clicks `Edit`.
   - Owner changes the draft.
   - Owner clicks `Cancel`.
   - Client restores the last loaded profile content, clears the local error state, exits edit mode, and does not call `PUT /profile`.

4. **Load empty profile**
   - Owner opens the tab before `me/profile.md` exists.
   - Gateway returns 404 with `{ content: null }`.
   - Client treats 404 as `null` and shows the empty state.

5. **Recover from save failure**
   - Owner clicks `Save`.
   - Gateway returns an error or network request fails.
   - Client remains in edit mode, stops showing saving state, and displays the error.
   - Stored profile content must remain unchanged unless the gateway completed the write.

### Secondary Flows

- If the profile is loading, show `Loading profile...` with a spinner.
- If profile load fails for a non-404 response, show the returned error and keep the page usable enough to retry by re-entering the tab or reopening Settings.
- If saving is in progress, disable `Save` and `Cancel` or otherwise prevent duplicate conflicting writes.
- If `getSession` fails, the identity header falls back to `Local Owner`, initials `LO`, and local email defaults; profile load/edit behavior still works.
- If the owner deletes all text and saves an empty string, V1 may write an empty profile file. Recommendation: allow this as an explicit owner deletion/correction path, but consider a confirmation or restore template flow in V2.
- If git commit fails after the file write, the current gateway swallows the commit failure. V1 should not fail the owner save solely because history is unavailable, but observability should make the missing history diagnosable.
- If profile content is very long, the textarea and rendered view should remain scrollable without breaking the Settings modal.

### UX / Trust Bar

- The owner must understand this page edits BrainDrive's remembered cross-project owner context, not their login account.
- The page must make direct editing feel powerful but recoverable.
- Saving must feel explicit; no autosave in V1.
- Cancel must be lossless for stored profile state.
- Loading, saving, and errors must be visible near the profile content.
- The rendered Markdown must be readable in dark mode and consistent with the Settings design system.
- Owner-facing copy should use `Your Profile` consistently with sidebar/tab naming and the canonical `# Your Profile` memory heading.
- The page should avoid exposing raw file paths in owner-facing copy unless the owner asks for technical details.

### Plain-Language Owner-Facing Expectations

- `Your Profile` means: "What BrainDrive knows about you across projects."
- The profile is built through conversation, but the owner can correct it manually.
- Stable cross-project facts belong here; one-project details belong in that project's goals/plan/journal.
- Secrets, API keys, passwords, billing data, private tokens, and provider keys do not belong here.
- Changes affect future BrainDrive context use; they do not automatically rewrite old conversations or project files.

## Goals

### Product Goals

- Give owners a trusted review and correction surface for BrainDrive's cross-project memory.
- Keep the owner profile inspectable as plain Markdown.
- Reinforce the separation between account settings, model settings, agent instructions, and owner memory.
- Preserve owner agency over remembered facts and preferences.
- Make profile edits recoverable through git history where available.

### User Goals

- See what BrainDrive currently knows about me.
- Correct or remove facts that are wrong, stale, too sensitive, or too broad.
- Add a cross-project preference once instead of repeating it in every project.
- Trust that BrainDrive is not hiding a separate profile database from me.
- Avoid editing login/account details when I mean to edit remembered context.

### Engineering Goals

- Keep the profile page backed by `me/profile.md`, not duplicate client-side state.
- Keep profile routes small, authorized, and memory-root bounded.
- Reuse existing Markdown rendering, settings modal patterns, authenticated fetch, and memory git commit behavior.
- Add focused tests without broad Settings refactors.
- Keep starter-pack profile template and initialized memory profile behavior aligned.

### Safety / Security / Trust Goals

- Require authorization for profile read/write.
- Treat profile content as sensitive owner memory.
- Do not log profile contents in normal telemetry or error output.
- Do not store secrets or credentials in profile content.
- Prevent Markdown rendering from executing scripts or unsafe HTML.
- Avoid AI-inferred sensitive profile writes from Settings; Settings writes only owner-entered text.

### Non-Goals

- No profile onboarding wizard in V1.
- No account name/email/password editing in this tab.
- No managed billing or subscription behavior in this tab.
- No provider credential, model, backup, migrate, browser access, or agent-instruction changes in this tab.
- No automatic classification of profile sections during direct edit.
- No background AI review, summarization, or moderation of owner-entered profile text.

## User Stories

### US-1: View Existing Profile - **Confirmed**

As a BrainDrive owner, I want to view my current profile so that I can see what BrainDrive remembers about me across projects.

**Source:** Implementation review of `SettingsModal.tsx`, `gateway-adapter.ts`, gateway `/profile` route, memory starter profile, and D91.

**Acceptance Criteria:**

```gherkin
Given Settings is open
And me/profile.md exists
When I select the Your Profile tab
Then the client requests GET /profile
And the gateway reads the configured memory root's me/profile.md
And the page renders the returned Markdown content
```

```gherkin
Given the profile contains Markdown headings and lists
When the profile is displayed
Then the content is rendered as readable Markdown
And unsafe script execution is not allowed
```

### US-2: Empty Profile State - **Confirmed**

As a new BrainDrive owner, I want a clear empty state when no profile exists so that I understand how the profile will be created.

**Source:** Current client and gateway behavior.

**Acceptance Criteria:**

```gherkin
Given me/profile.md does not exist
When I open Your Profile
Then the gateway returns content null
And the client shows "No profile yet. Start a conversation and ask your partner to build your profile."
And the page still offers Edit so I can create the profile manually
```

### US-3: Edit Profile Markdown - **Confirmed**

As a BrainDrive owner, I want to edit the profile Markdown directly so that I can correct what BrainDrive remembers.

**Source:** D91 and current `ProfileSection` implementation.

**Acceptance Criteria:**

```gherkin
Given the profile is loaded
When I click Edit
Then I see a textarea containing the exact loaded profile content
And I can change the Markdown
```

```gherkin
Given I am editing the profile
When I click Save
Then the client sends PUT /profile with the full draft content
And the gateway writes that content to me/profile.md
And the page exits edit mode after a successful save
And the page reloads and renders the saved content
```

### US-4: Cancel Without Writing - **Confirmed**

As a BrainDrive owner, I want to cancel profile edits so that experimental changes do not affect my saved memory.

**Source:** Current `handleCancel` behavior.

**Acceptance Criteria:**

```gherkin
Given I am editing the profile
And I have changed the draft
When I click Cancel
Then PUT /profile is not called
And the draft is reset to the last loaded profile content
And the page returns to read mode
```

### US-5: Save History For UI Edits - **Confirmed**

As a BrainDrive owner, I want profile edits made through Settings to enter memory history so that I can recover from mistakes.

**Source:** D92 and current gateway `commitMemoryChange` call.

**Acceptance Criteria:**

```gherkin
Given the profile save succeeds
When the memory root has git history available
Then BrainDrive attempts a commit with message "Update owner profile via UI"
And the save is not blocked solely by a git commit failure
```

**Recommendation:** Add evidence/logging for commit failures without exposing profile content, because the current route catches and ignores commit failures.

### US-6: Distinguish Profile From Account - **Confirmed**

As a BrainDrive owner, I want the profile tab to be separate from account settings so that I know whether I am editing memory or login details.

**Source:** Current Settings tabs and route separation.

**Acceptance Criteria:**

```gherkin
Given I open Settings in managed mode
When I need login, subscription, email, or password controls
Then those controls are in Account
And Your Profile only displays and edits owner-memory Markdown
```

```gherkin
Given I open Settings in local mode
When I select Your Profile
Then provider/model/backup/migrate/browser-access controls are not shown inside the profile panel
```

### US-7: Respect Profile Write Placement - **Recommended**

As a BrainDrive builder or agent, I want profile content to remain limited to stable cross-project owner facts and BrainDrive preferences so that project-specific or sensitive details do not pollute global memory.

**Source:** Memory architecture M-10, Profile Rules, base `AGENT.md`, and starter-pack Your Agent guidance.

**Acceptance Criteria:**

```gherkin
Given the owner edits profile content directly
When the content is saved
Then the system writes only the owner-entered text
And does not infer, classify, or promote project-specific details on its own
```

```gherkin
Given future AI assistance is added to profile editing
When a fact is inferred, sensitive, uncertain, or preference-like
Then BrainDrive asks for owner confirmation before writing it as settled profile content
```

**Recommendation:** Keep this as a product/trust rule in V1 even though direct Settings editing cannot enforce semantic placement automatically.

### US-8: Handle Load And Save Errors - **Recommended**

As a BrainDrive owner, I want clear errors when profile loading or saving fails so that I know whether my memory changed.

**Source:** Current error states plus implementation review.

**Acceptance Criteria:**

```gherkin
Given GET /profile fails with a non-404 error
When I open Your Profile
Then the page shows the error
And does not pretend that no profile exists
```

```gherkin
Given PUT /profile fails
When I click Save
Then the page remains in edit mode
And the visible error explains the failure
And the last loaded profile content is not replaced in UI state as saved content
```

**Recommendation:** Add a retry affordance or document that reopening Settings is the retry path.

### US-9: Use Owner-Facing Naming Consistently - **Recommended**

As a BrainDrive owner, I want Settings labels to match the rest of BrainDrive so that I know where to review profile memory.

**Source:** Current tab label `Your Profile`, canonical profile heading `# Your Profile`, memory architecture naming, and T-721 history.

**Acceptance Criteria:**

```gherkin
Given I open the profile settings page
When I read the page title
Then the visible heading says "Your Profile"
And the role label "Owner" may remain in the identity header
```

**Recommendation:** Change the current section heading from `Owner Profile` to `Your Profile` during V1 polish.

## Requirements

### Functional Requirements

- [ ] Settings navigation must include `Your Profile` in both local and managed modes.
- [ ] Selecting `Your Profile` must render only the profile panel.
- [ ] The panel must call `GET /profile` on mount.
- [ ] The client must treat a 404 profile response as `null`, not as a fatal load error.
- [ ] Non-404 load errors must be displayed.
- [ ] The read view must render Markdown safely.
- [ ] The empty state must explain that the profile can be built through conversation.
- [ ] `Edit` must be disabled while the initial profile load is in progress.
- [ ] Entering edit mode must initialize the draft from the latest loaded profile content or `""`.
- [ ] `Cancel` must reset the draft and exit edit mode without a write.
- [ ] `Save` must call `PUT /profile` with `{ content: draft }`.
- [ ] `Save` must show a saving state and prevent duplicate writes while in flight.
- [ ] A successful save must exit edit mode and reload profile content from the gateway.
- [ ] A failed save must leave the draft visible and show the error.
- [ ] The gateway must require `memory_access` authorization for both read and write.
- [ ] The gateway must read/write only `<memory_root>/me/profile.md`.
- [ ] The gateway must create `<memory_root>/me` before first manual save if missing.
- [ ] The gateway must reject a `PUT /profile` payload whose `content` is not a string.
- [ ] The gateway must attempt a memory commit after successful file write.
- [ ] The page must not edit account, billing, provider, model, backup, migrate, browser access, or root-agent settings.

### AI / Model / Tool Behavior

No AI/model behavior is required for the Settings page itself. The Settings page is a direct owner-controlled Markdown editor.

Future AI/tool behavior may touch this area only under these boundaries:

- [ ] AI may propose profile updates in conversation, but inferred/sensitive/preference-like facts require owner confirmation before being written as settled profile content.
- [ ] AI must route stable cross-project facts to `me/profile.md` and project-specific facts to the relevant project artifacts.
- [ ] AI must not store secrets, API keys, passwords, payment details, auth tokens, or provider keys in `me/profile.md`.
- [ ] AI must not rewrite the entire profile from Settings without an explicit owner action and a preservation/recovery story.
- [ ] Tool calls that edit `me/profile.md` must preserve existing owner content unless the owner explicitly asks for deletion or replacement.

### Data, Memory, And Artifact Contracts

| Data / Artifact | Source | Owner | Read/Write Rules | Retention / Migration |
|---|---|---|---|---|
| `me/profile.md` | Memory root, starter pack, conversation writes, Settings direct edits | BrainDrive owner | Canonical cross-project profile. Settings reads full file and writes full owner-edited Markdown. Agents write only confirmed stable cross-project facts and preferences. | Retained with memory. Included in starter layout and migrations/backups according to memory system rules. |
| Profile Markdown draft | Browser component state | BrainDrive owner | Initialized from loaded profile. May be changed locally until Save. Cancel discards. | Ephemeral; not persisted unless saved. |
| Rendered profile HTML | Client Markdown renderer | Client UI | Derived from profile Markdown. Must be sanitized/safe. | Ephemeral. |
| Session user display | `GET /session` via `getSession` | Auth/session layer | Used only for avatar initials, display name, and role label. Does not modify `me/profile.md`. | Session-scoped. Local synthetic email must not be treated as profile content. |
| `GET /profile` response | Gateway route | Gateway/memory layer | Returns `{ content }` or 404 with `{ content: null }` when missing. Requires `memory_access`. | No separate retention. |
| `PUT /profile` request | Client Settings page | Owner via UI | Body must be `{ content: string }`. Writes only profile file. Requires `memory_access`. | Persists to profile file. |
| Memory git commit | `commitMemoryChange` after save | Memory/versioning layer | Attempt commit with `Update owner profile via UI`. Do not include profile content in logs. | Retained in local memory git history when available. |
| Starter profile template | `builds/typescript/memory/starter-pack/base/me/profile.md` | BrainDrive starter pack | Provides canonical baseline `# Your Profile` structure for new owners. | Updated through starter-pack/migration process, not by Settings direct edit. |
| Local test memory profile | `builds/typescript/your-memory/me/profile.md` | Development fixture | Mirrors starter profile baseline for local test owner. | Development fixture only; paired changes required if starter defaults change. |
| Errors | Gateway/client error handling | Runtime | Error messages may include failure reason, not profile contents. | Logs must avoid sensitive content. |

### Interface / UX Requirements

- [ ] Settings tab label: `Your Profile`.
- [ ] Recommended panel heading: `Your Profile`.
- [ ] Current explanatory copy may remain: `Your profile builds naturally through conversation. It captures the stable facts about your life, work, and goals that help personalize every interaction.`
- [ ] Identity header must show owner initials, name, and role label `Owner`.
- [ ] Primary read action: `Edit`.
- [ ] Edit actions: `Cancel` and `Save`.
- [ ] Saving label: `Saving...` or equivalent spinner plus saving text.
- [ ] Loading label: `Loading profile...`.
- [ ] Empty state: `No profile yet. Start a conversation and ask your partner to build your profile.`
- [ ] Textarea must be large enough for practical Markdown editing and use monospaced text.
- [ ] Buttons must respect disabled state while loading/saving.
- [ ] Error message must be shown inline above the content area.
- [ ] Amber primary button text must meet the design token contrast rule: amber fill uses dark text. Current implementation uses white text on amber for `Save`; V1 polish should align with design guidance.
- [ ] Text must not overflow the Settings modal on desktop or narrow widths.
- [ ] The page must remain dark-mode only and use existing Settings modal design tokens.

### Observability / Evidence Requirements

- [ ] Automated test output for profile API wrappers.
- [ ] Automated test output for Settings profile tab load/edit/cancel/save/error states.
- [ ] Gateway route tests proving authorized profile read/write and invalid payload handling.
- [ ] Manual screenshot or recording of local-mode `Your Profile` read and edit states.
- [ ] Manual screenshot or recording of managed-mode `Your Profile` tab visibility.
- [ ] Evidence that `me/profile.md` changes after save.
- [ ] Evidence that a memory git commit is attempted or that commit failure is logged/reported safely.
- [ ] Evidence that Markdown rendering does not execute unsafe content.
- [ ] Evidence that profile content is not logged by normal errors or tests.

## Scope

### Work Type

- [x] **Production** - Existing owner-facing Settings feature with memory/security implications.
- [x] **V1** - Source-of-truth behavior, focused hardening, and tests.
- [x] **Documentation/specification** - This spec defines source-of-truth behavior.
- [x] **Interface / shell** - Settings modal tab and panel.
- [x] **Backend / gateway** - `/profile` read/write routes.
- [x] **Memory** - `me/profile.md` read/write and git commit.
- [x] **Testing / harness** - UI/API regression coverage.
- [ ] **Secrets** - Only by exclusion: secrets must not be stored here.

### Implementation Location / Ownership

- `builds/typescript/client_web/src/components/settings/SettingsModal.tsx` - Settings tab registration and `ProfileSection`.
- `builds/typescript/client_web/src/api/gateway-adapter.ts` - `getOwnerProfile`, `updateOwnerProfile`.
- `builds/typescript/client_web/src/api/auth-adapter.ts` - session data for identity header.
- `builds/typescript/client_web/src/components/markdown/MarkdownContent` - profile Markdown rendering.
- `builds/typescript/gateway/server.ts` - `GET /profile` and `PUT /profile`.
- `builds/typescript/memory/starter-pack/base/me/profile.md` - starter profile template.
- `builds/typescript/your-memory/me/profile.md` - local fixture profile.
- `builds/typescript/memory/init.ts` and `builds/typescript/memory/init.test.ts` - memory initialization coverage.
- `builds/typescript/client_web/src/components/settings/SettingsModal.test.tsx` - recommended focused profile tab UI coverage.
- `builds/typescript/client_web/src/api/gateway-adapter.test.ts` - recommended profile API wrapper coverage.
- `builds/typescript/gateway/*test.ts` - recommended route/integration coverage.

### Included

- Profile tab visibility and navigation in Settings.
- Profile Markdown read view.
- Profile Markdown edit, save, and cancel.
- Empty, loading, saving, and error states.
- Gateway profile read/write API behavior.
- Memory file path, write, and commit behavior.
- Profile data placement rules and boundaries.
- Local and managed mode expectations for the tab.
- Focused test and acceptance evidence requirements.

### Explicitly Excluded

- Account email/password/name/subscription management -> Account tab.
- AI Models, provider credentials, BrainDrive Models credits, Ollama, OpenRouter -> AI Models spec.
- Your Agent managed/default/overlay editing -> Your Agent settings spec.
- Backup and Migrate behavior -> Backup/Migrate specs.
- Browser Access / Tailscale access behavior -> Browser Access/Tailscale specs.
- Memory starter-pack migrations beyond preserving the profile template contract.
- Rich profile form fields, guided editing, validation of semantic profile sections, or AI profile rewrite.
- Any storage of secrets, credentials, billing records, or raw provider keys in `me/profile.md`.

### Future Versions / Deepenings

- Structured editor for common sections such as identity, values, work style, and BrainDrive preferences.
- Profile diff before save and restore previous version.
- Confirmation when saving an empty profile or deleting large sections.
- Inline guidance for what belongs in the profile versus project goals/plans.
- "Suggest profile updates" flow that shows AI-proposed changes for owner approval.
- Last-updated indicator sourced from file metadata or git history.
- Conflict detection if another process changes `me/profile.md` while the owner is editing.
- Full-text profile search or section jump links for long profiles.

## Invariants And Edge Cases

### Properties That Must Always Hold

- [ ] `me/profile.md` is the source of truth for the Settings profile content.
- [ ] Profile read/write routes require authorization.
- [ ] Settings profile saves write only to `<memory_root>/me/profile.md`.
- [ ] Direct Settings edits do not write account, provider, agent, backup, migrate, or project files.
- [ ] Profile content is treated as sensitive owner memory.
- [ ] Secrets and credentials must not be intentionally stored in the profile.
- [ ] The read view must not execute scripts from Markdown.
- [ ] Cancel must never persist draft changes.
- [ ] Save success must reflect persisted content, not only local draft state.
- [ ] Missing profile is distinct from load failure.
- [ ] Starter-pack default profile heading remains `# Your Profile`.
- [ ] Account/session identity display does not overwrite profile file content.

### Edge Cases To Test

- [ ] `me/profile.md` missing.
- [ ] Empty profile file exists.
- [ ] Very long profile content.
- [ ] Markdown headings, lists, links, code blocks, and tables.
- [ ] Unsafe Markdown/HTML input.
- [ ] Unicode and special characters in profile content.
- [ ] Save empty string.
- [ ] Invalid `PUT /profile` body with missing or non-string `content`.
- [ ] Unauthorized profile read/write.
- [ ] Read failure after Settings is open.
- [ ] Save failure with network error.
- [ ] Save succeeds but git commit fails.
- [ ] `getSession` fails but profile loads.
- [ ] Local mode tab set.
- [ ] Managed mode tab set.
- [ ] Narrow viewport with long words or long Markdown lines.
- [ ] Two saves clicked quickly.
- [ ] Profile changed externally while edit draft is open.

### Failure Modes

| Scenario | Expected Behavior |
|---|---|
| `GET /profile` returns 404 | Client shows empty profile state, not a fatal error. |
| `GET /profile` returns 500 | Client shows inline load error and does not claim there is no profile. |
| `PUT /profile` receives non-string content | Gateway rejects request; client shows save error. |
| `PUT /profile` fails | Client remains in edit mode with draft intact and shows error. |
| File write succeeds but git commit fails | Save remains successful; safe diagnostic evidence is available without profile content leakage. |
| Markdown contains script/HTML injection | Rendered view does not execute unsafe code. |
| Owner saves empty content | Empty profile is persisted and rendered as empty/no-content state according to V1 decision. |
| Session load fails | Identity header falls back; profile read/edit still works. |
| Unauthorized request hits `/profile` | Gateway denies access. |
| Memory root is unavailable | Gateway returns error; client displays failure and does not fake success. |
| Concurrent external edit during local draft | V1 may last-write-wins; future version should detect conflicts. |
| Owner enters secrets in profile | V1 does not inspect content automatically; UX/docs should clearly state secrets do not belong here. |

## Technical Context

### Existing System Context

- **Current behavior:** `SettingsModal.tsx` defines `profile` as the `Your Profile` tab for local and managed modes. `ProfileSection` loads content with `getOwnerProfile`, renders it with `MarkdownContent`, and edits via a textarea. `updateOwnerProfile` saves the full draft. Gateway `/profile` routes read/write `me/profile.md` under the configured memory root and authorize `memory_access`.
- **Known gaps / bugs:** There is no obvious focused SettingsModal profile tab test in the current test file; the gateway-adapter test file does not currently cover `getOwnerProfile` / `updateOwnerProfile`; gateway route tests for `/profile` were not found in the reviewed output. The panel heading currently says `Owner Profile` while the tab and canonical memory heading say `Your Profile`. The `Save` button currently appears to use white text on amber, which conflicts with the project design note that amber primary uses dark text.
- **Related specs/docs:** Existing `settings-ai-models-page-spec.md`; memory architecture v4.2; starter-pack `base/AGENT.md`; starter profile template.
- **Related decisions:** D91 owner profile renders `me/profile.md` in Settings; D92 UI file saves commit to git; D93 managed Settings tabs were simplified; T-721 made `# Your Profile` canonical.

### Integration Points

- Settings modal tab filtering by mode and runtime.
- Auth/session route for owner avatar/name display.
- Gateway authenticated fetch and local owner headers.
- Gateway authorization via `memory_access`.
- Configured `runtimeConfig.memory_root`.
- File system read/write for `me/profile.md`.
- Memory git commit helper.
- Markdown renderer.
- Starter-pack memory initialization.
- Local and managed mode Settings navigation.
- Memory backup/migrate indirectly, because profile is part of owner memory.

### Hard Constraints

- Do not store secrets, provider keys, auth tokens, billing data, or passwords in `me/profile.md`.
- Do not read/write profile outside the configured memory root.
- Do not silently overwrite starter-pack templates or owner overlays from Settings.
- Do not make profile saves depend on model/provider availability.
- Do not require BrainDrive Models credits for profile access.
- Do not expose profile read/write unauthenticated.
- Do not add external services or third-party profile sync in V1.
- Do not turn direct Settings edit into an AI rewrite flow without a separate spec.
- Preserve local and managed mode visibility unless a new Settings navigation decision changes it.

### Build Workflow Inputs

- Align visible heading from `Owner Profile` to `Your Profile`.
- Add mocks and focused tests for `getOwnerProfile` / `updateOwnerProfile` in `SettingsModal.test.tsx`.
- Add gateway-adapter tests for 404-as-null, success, and error mapping.
- Add gateway route tests for authorized read/write, missing file, invalid body, and commit behavior.
- Consider safe logging for commit failure after profile save.
- Consider a maximum content size limit only if consistent with memory file handling elsewhere; do not invent one casually.
- Consider conflict detection as V2 if external profile edits are common.

## Test Strategy

### Test Levels Required

- [x] **Unit** - Client API wrapper behavior, profile component state transitions where practical.
- [x] **Integration** - Gateway profile routes and file persistence.
- [ ] **Property-based** - Not required for V1 unless Markdown sanitization utilities already use it.
- [x] **E2E / workflow** - Manual or Playwright flow for opening Settings, editing profile, saving, and verifying render.
- [x] **Regression** - Settings navigation, Account tab, Your Agent tab, AI Models tab, Memory Backup/Migrate tabs.
- [ ] **Harness / AI judge** - Not required for direct Settings page; profile write-placement should remain covered by memory/agent harness separately.
- [x] **Human review** - UX copy, trust clarity, dark-mode readability, and profile/account separation.
- [x] **Cross-platform/responsive** - Browser and desktop shell where Settings modal is used; narrow viewport sanity.
- [x] **Security verification** - Auth boundary and Markdown safety.

### Verification Approach

- **Focused web tests:**
  - `cd builds/typescript && npm run web:test -- SettingsModal`
  - `cd builds/typescript && npm run web:test -- gateway-adapter`
- **Focused gateway/memory tests:**
  - `cd builds/typescript && npm run test -- gateway`
  - `cd builds/typescript && npm run test -- memory/init`
- **Typecheck/build:**
  - `cd builds/typescript && npm run web:typecheck`
  - `cd builds/typescript && npm run build` before release handoff when profile changes ship with broader Settings changes.
- **Manual verification:**
  - Start the app with `cd builds/typescript && npm run dev`.
  - Open Settings in local mode.
  - Open `Your Profile`, edit a harmless test line, save, and verify it renders.
  - Verify `<memory_root>/me/profile.md` changed.
  - Verify git history contains or attempted the UI save commit where applicable.
  - Repeat tab visibility in managed mode if the mode can be run locally.

### Acceptance Evidence

- [ ] Test output for client profile wrapper coverage.
- [ ] Test output for Settings profile tab UI coverage.
- [ ] Test output for gateway profile route coverage.
- [ ] Screenshot of read state with rendered Markdown.
- [ ] Screenshot of edit state with textarea and Save/Cancel.
- [ ] Screenshot or test assertion of empty state.
- [ ] Evidence of save persistence to `me/profile.md`.
- [ ] Evidence that cancel does not call the update API.
- [ ] Evidence of authorization failure for unauthenticated/unauthorized profile requests.
- [ ] Evidence that unsafe Markdown does not execute.
- [ ] Human review approval for copy and naming.

### Baseline / Regression Impact

- **Always-run checks affected:** web typecheck, SettingsModal web tests, gateway tests, memory init tests.
- **Additional checks triggered:** Markdown safety test if renderer behavior changes; manual Settings modal review for both local and managed modes.
- **Existing user flows that must keep working:** AI Models settings, Account settings, Your Agent settings, Browser Access, Backup, Migrate, chat provider error "Open Settings", memory initialization, memory backup/migrate.
- **Global properties affected:** owner memory trust, profile placement, authenticated memory access, direct file save history.

## Security, Privacy, And Trust Considerations

### Risk Level

- [x] **Medium** - The page handles sensitive owner memory, file writes, Markdown rendering, and authenticated gateway routes.

This is not high risk in the same way as secrets/payment/code execution, but a bad implementation can expose or corrupt deeply personal owner context across every BrainDrive project.

### Threat / Trust Assessment

- **User input:** Accepts arbitrary Markdown text. Must be written as text and rendered safely.
- **Code execution:** No code execution should occur. Markdown must not execute scripts or unsafe HTML.
- **Data sensitivity:** Profile can contain identity, family, health, work, values, preferences, constraints, and life context. Treat as private owner data.
- **Network surface:** `/profile` read/write routes expose memory content through the gateway and must require authorization.
- **Model/tool behavior:** No model behavior in this page. Future AI-assisted profile edits require confirmation boundaries.
- **Blast radius:** Wrong or leaked profile content can affect every project and future BrainDrive response.
- **Owner trust:** The owner must be able to inspect, correct, remove, and understand profile memory.

### Required Mitigations

- [ ] Require authorization for profile routes.
- [ ] Keep route path fixed to configured memory root plus `me/profile.md`.
- [ ] Reject invalid save payloads.
- [ ] Render Markdown safely.
- [ ] Do not log profile content in normal errors, analytics, or audit events.
- [ ] Keep secrets and credentials out of profile guidance.
- [ ] Preserve edit/cancel/save clarity.
- [ ] Attempt git history for direct UI saves.
- [ ] Add focused regression tests around profile read/write.

## Explicit Boundaries

### Do Not Modify

- [ ] Provider profile configuration or credentials.
- [ ] Account, billing, password, email, or subscription behavior.
- [ ] Memory backup/migrate semantics.
- [ ] Starter-pack profile template unless the task explicitly changes defaults and includes migration/update impact.
- [ ] Project `spec.md`, `plan.md`, `journal.md`, or page procedures from the profile Settings page.
- [ ] Owner overlays such as `AGENT-user.md` from this page.

### Do Not Introduce

- [ ] A separate profile database or client-only profile cache as source of truth.
- [ ] Rich profile schema migration without separate approval.
- [ ] AI rewrite/summarization in Settings V1.
- [ ] External profile sync or third-party storage.
- [ ] Secret scanning that silently deletes owner text without review.
- [ ] Raw HTML rendering that bypasses Markdown safety.

### Security / Trust Boundaries

- [ ] Never commit secrets or credentials to `me/profile.md`.
- [ ] Never expose profile content without gateway authorization.
- [ ] Never send profile content to model/provider APIs from Settings.
- [ ] Never treat account session identity as a replacement for owner memory.
- [ ] Never silently promote project-specific facts into profile.
- [ ] Never claim a profile update happened unless the file write succeeded.

### Out Of Scope Even If Related

- [ ] Account tab redesign.
- [ ] Your Agent customization redesign.
- [ ] AI Models or credits repair work.
- [ ] Browser Access/Tailscale settings.
- [ ] Memory architecture rewrite.
- [ ] Starter-pack migration engine.
- [ ] Full profile lifecycle/audit dashboard.

## Open Questions

- [ ] Should saving an empty profile be allowed without confirmation, or should V1 ask for confirmation when the draft is empty?
- [ ] Should commit failure after a successful write surface a non-blocking warning to the owner, or only safe diagnostics for developers/operators?
- [ ] Should the profile page include inline "what belongs here" guidance, or keep that guidance in conversation/starter-pack docs?
- [ ] Should direct edits preserve or auto-update `Last updated` in the Markdown, or avoid semantic edits entirely?
- [ ] Should V1 add conflict detection if the profile file changes after the owner enters edit mode?
- [ ] Does managed mode have the same `/profile` backing store contract as local mode in all deployments, or does hosted storage need a separate managed profile persistence spec?

## Changelog

| Date | Change | Reason | Source | Decision |
|---|---|---|---|---|
| 2026-07-09 | Initial source-of-truth spec created for Your Profile Settings page. | Product request; no prior dedicated spec existed. | Current implementation review and Library docs. | - |

## Conversation References

| Date | Source | Topics Discussed | Link |
|---|---|---|---|
| 2026-03-31 | Settings UX, BrainDrive Models, Owner Profile | D91 profile renders `me/profile.md`; D92 UI saves commit; D93 managed settings simplification. | `/home/hex/Reference/BrainDrive-Library/transcripts/2026-03/2026-03-31-settings-ux-braindrive-models-owner-profile-dave-w-claude.md` |
| 2026-07-01 | Memory Architecture v4.2 | Profile placement, write ownership, propagation, owner-memory invariants. | `/home/hex/Reference/BrainDrive-Library/projects/production/braindrive-repo/foundation/memory-architecture/memory-architecture.md` |
| 2026-07-09 | User request | Requested complete source-of-truth spec for The Your Profile Settings Page. | `/home/hex/.codex/attachments/a8314299-f7f8-47aa-abbf-a594cb16bd55/pasted-text.txt` |

## Approval

- [ ] Reviewed by: _______________
- [ ] Date: _______________
- [ ] Ready for Planning: [ ]

---

*Next: After this spec is reviewed and accepted, generate a focused test plan for the Your Profile Settings page before creating a build plan.*
