# Spec: BrainDrive Starter-Pack Memory Updates

## Overview

### What This Specifies

This document specifies the current BrainDrive memory update system that reconciles an existing owner's file-backed memory with changes shipped in the BrainDrive starter pack.

The implementation is in the BrainDrive product repo under:

- `builds/typescript/memory/update-prompting.ts`
- `builds/typescript/memory/brain-drive-layout.ts`
- `builds/typescript/memory/alpha-draft3-transition.ts`
- `builds/typescript/gateway/server.ts`
- `builds/typescript/client_web/src/components/layout/AppShell.tsx`
- `builds/typescript/client_web/src/api/gateway-adapter.ts`
- `builds/typescript/memory/update-prompting.test.ts`
- `builds/typescript/memory/brain-drive-layout.test.ts`
- `builds/typescript/memory/starter-pack-draft3-layout.test.ts`

This is a current-state specification, not a build plan. It describes what the code does today.

### Source Snapshot

| Item | Current state |
|---|---|
| Repo inspected | `/home/hex/Project/BrainDrive-Test-01` |
| Branch observed | `main` |
| TypeScript package version observed | `26.6.28` |
| Requested reference folder | `/home/hex/Reference/Designs/BrainDrive-MVP/BrainDrive - Update` |
| Reference folder content at inspection time | Empty |
| Main current behavior source | Live repo code and tests |
| Focused verification note | `memory/update-prompting.test.ts` passes; `memory/starter-pack-draft3-layout.test.ts` currently fails on starter-pack lint expectations. |

### Why This Matters

BrainDrive starter-pack files define the default memory layout, page instructions, procedure files, starter skills, and baseline owner artifacts for new users. Existing users may have changed their local memory, added owner state, customized instructions, or accumulated generated outputs. Updates must therefore deliver improved starter-pack behavior without overwriting personal memory or owner-authored work.

The current system does this by generating a starter-pack manifest, comparing it against the owner memory root, planning safe changes, applying only automatically applicable changes, preserving or deferring owner-controlled content, writing reports and backups, and exposing status through gateway endpoints and a client notice.

### Success Definition

The update system is successful when:

1. Existing owners receive missing or safely mergeable starter-pack improvements.
2. Owner state, overlays, source files, generated output, durable archives, personal facts, goals, plans, todos, and customized content are not overwritten automatically.
3. Every applied update has a plan, migration log entry, report, and backup when files changed.
4. Startup can perform automatic safe updates without blocking normal operation after completion.
5. The owner can see a completed update report in the web client when a report exists.

The update system is not successful if:

1. A starter-pack update overwrites owner-specific memory without a safe merge or explicit deferral.
2. A stale or partial plan is applied after the target file changed.
3. A missing model adapter causes the update process to fail instead of falling back to deterministic behavior.
4. Starter-pack changes to owner state files are treated as replaceable base content.
5. Retired Finance Budgetting paths are recreated as active starter-pack files.

## Product Behavior

### Current User / System Experience

On gateway startup, BrainDrive checks whether the owner's memory root is current with the starter pack for the running app version. Automatic updates are enabled by default. The gateway disables the startup auto-update only when `PAA_MEMORY_AUTO_UPDATE_ENABLED=false`.

If an update is pending, BrainDrive:

1. Runs the one-off Draft 3 memory transition before normal starter-pack reconciliation.
2. Generates a current starter-pack manifest.
3. Builds candidates by comparing each manifest file against the owner memory root.
4. Creates an LLM-assisted plan when a model adapter is available.
5. Falls back to a deterministic plan when no adapter is available or the LLM output is invalid/unusable.
6. Normalizes the plan so unsafe, incomplete, missing, high-risk, or non-auto-apply items become deferred.
7. Applies only auto-applicable items.
8. Creates a backup before writing any file changes.
9. Writes a Markdown report.
10. Updates memory update state and migration log files.
11. Attempts to commit the memory change to the memory git repository.
12. Reloads the gateway system prompt if `AGENT.md` was updated.

After startup, the web client calls the memory update status endpoint. If a report exists and the browser has not dismissed that migration report, the client shows a notice: "BrainDrive is up to date." The owner can expand the report details or dismiss the notice. Dismissal is stored in browser localStorage under `braindrive.memoryUpdateReportSeen.<migration_id>`.

Manual update endpoints also exist for status, plan, apply, and report retrieval.

### Primary Flows

1. **Startup automatic update**
   - Trigger: gateway startup with automatic memory updates enabled.
   - System behavior: check status, run Draft 3 transition if needed, generate a plan, apply safe items, report results.
   - Outcome: owner memory is current where safe; unsafe content is deferred and reported.

2. **Manual status check**
   - Trigger: authenticated caller requests `GET /updates/memory/status`.
   - System behavior: generate manifest, ensure update state, compare current state and migration log.
   - Outcome: caller receives current app version, current memory pack version, target memory pack version, pending flag, migration id, report path, applied paths, and deferred paths.

3. **Manual plan generation**
   - Trigger: authenticated caller requests `POST /updates/memory/plan`.
   - System behavior: resolve current preferences and credentials, build optional memory update adapter, generate/normalize/write plan, append migration log, mark pending migration in state.
   - Outcome: caller receives a normalized plan.

4. **Manual apply**
   - Trigger: authenticated caller requests `POST /updates/memory/apply`.
   - System behavior: reads the saved plan for the current migration, refuses concurrent migration work, backs up memory if writes are needed, validates target files are unchanged since planning, applies safe items, writes report/log/state, reloads system prompt if needed.
   - Outcome: caller receives apply result with status, applied paths, deferred paths, report path, and backup path.

5. **Report display**
   - Trigger: authenticated caller requests `GET /updates/memory/reports/:migrationId`, or web client fetches the report after status shows a report path.
   - System behavior: validates the migration id shape and serves report Markdown if found.
   - Outcome: caller sees what was updated, what was left unchanged, and where backup was written.

### Secondary Flows

- **No pending update:** startup update returns `null`; status reports `pending=false`.
- **No model adapter available:** plan generation uses deterministic logic.
- **LLM output invalid or incomplete:** invalid output is ignored or normalized; missing manifest candidates receive deterministic items.
- **High-risk LLM item:** normalized to `defer`.
- **Owner-managed file already exists:** preserved or deferred depending on ownership and merge policy.
- **Missing starter-pack file:** ignored during manifest generation because development fixtures may not include every starter file.
- **Concurrent migration-sensitive operations:** gateway returns `423 migration_in_progress` for normal requests during migration, with explicit allowances for migration/update paths; manual memory update apply returns `409 migration_in_progress` if another migration is already active.
- **File changes after planning:** apply fails for that migration before writing the changed candidate because current hash no longer matches the planned candidate hash.
- **Git commit failure:** update can still complete; failure is audit-logged.

## User Stories

### US-1: Existing Owner Receives Safe Starter-Pack Improvements - Confirmed

As a BrainDrive owner with existing memory, I want BrainDrive to add safe starter-pack updates automatically so that new baseline instructions, project procedures, and starter skills can work without manual file surgery.

Acceptance criteria:

```gherkin
Given an existing memory root is missing a starter-pack file
And the file is included in the current starter-pack manifest
When BrainDrive runs the memory update
Then the missing file is created from the starter-pack source
And the update report lists the file under Updated
And a memory backup is created when file changes are applied
```

### US-2: Customized Existing Files Are Not Overwritten Without a Safe Merge - Confirmed

As a BrainDrive owner who has customized memory files, I want BrainDrive to preserve my local changes unless the system can safely merge them so that update automation does not destroy personal context or owner choices.

Acceptance criteria:

```gherkin
Given an existing manifest file differs from the starter-pack target
And no LLM merge is available
When BrainDrive generates and applies the update plan
Then the customized file is deferred
And the file content remains unchanged
And the report explains that the file was left unchanged for safety
```

```gherkin
Given an LLM plan marks a customized managed-base file as merge
And replacement_content is present
And risk is low or medium
When BrainDrive normalizes and applies the plan
Then the merged replacement content can be applied
And the file is listed in applied_paths
```

### US-3: Owner State Remains Owner-Controlled - Confirmed

As a BrainDrive owner, I want my profile, todos, project specs, and project plans to remain mine so that starter-pack updates do not replace personal goals, plans, status, or context.

Acceptance criteria:

```gherkin
Given a manifest file is classified as owner_state
And the file already exists
When BrainDrive plans an update
Then the existing file is preserved as no_change
And starter-pack updates do not replace it automatically
```

### US-4: Managed Base Files Can Receive Starter-Pack Updates - Confirmed

As a maintainer, I want managed base prompt/procedure files to be updateable so that improved BrainDrive behavior can reach existing installations.

Acceptance criteria:

```gherkin
Given a manifest file is classified as managed_base
And the file is missing
When BrainDrive applies the update plan
Then BrainDrive creates it from the starter pack
```

```gherkin
Given a manifest file is classified as managed_base
And the file exists with custom content
When no safe LLM merge is available
Then BrainDrive defers rather than overwrites it
```

### US-5: Owners Can Inspect Update Results - Confirmed

As a BrainDrive owner, I want a readable update report so that I can understand what changed and what was left untouched.

Acceptance criteria:

```gherkin
Given a memory update plan is applied
When BrainDrive writes the update report
Then the report includes status, timestamp, summary, updated items, deferred items, and backup information
```

### US-6: Startup Updates Do Not Re-run Completed Deferred Migrations - Confirmed

As a maintainer, I want deferred or partially applied migrations to stop repeating after the memory pack version is recorded current so that startup does not repeatedly prompt or attempt the same unsafe changes.

Acceptance criteria:

```gherkin
Given a migration status is deferred or partially_applied
And memory_update_state.memory_pack_version equals the target memory pack version
When automatic memory update runs again for the same migration
Then it returns null
```

## Requirements

### Functional Requirements

- The starter-pack update system must use a generated manifest as the source of update scope.
- The manifest memory pack version must be the normalized app version when the app version matches `N.N`, `N.N.N`, or `N.N.N.N`; otherwise it uses the app version string.
- The migration id must be `starter-pack-<normalized-version>`.
- The update system must resolve starter-pack source directory in this order:
  1. `PAA_STARTER_PACK_DIR`
  2. `<rootDir>/memory/starter-pack`
  3. `<rootDir>/builds/typescript/memory/starter-pack`
- Missing starter-pack source files must be skipped during manifest generation.
- Existing user memory must be compared by normalized SHA-256, where file content is normalized to end with a newline.
- The first update state must be initialized as current when all candidates match the starter pack.
- The first update state must be initialized as `unknown` with a pending migration when candidate drift exists.
- A migration is pending when:
  - latest handled migration does not already cover the target version, and
  - state has the current migration id pending, or
  - target version is greater than stored memory pack version, or
  - versions cannot be compared, or
  - any candidate hash differs from manifest hash.
- A migration is handled when status is `applied`, `partially_applied`, or `deferred`, and state memory pack version equals the manifest memory pack version, and migration target equals the manifest memory pack version.
- Automatic startup updates must run Draft 3 transition before starter-pack reconciliation.
- Applying a plan must validate every applicable candidate has not changed since planning.
- Applying a plan must create a full memory archive backup before applying file changes.
- Applying a plan must write report, migration log, and memory update state after completion.
- Applying a plan must attempt a memory git commit but must not fail the update solely because commit fails.
- If `AGENT.md` is applied, the gateway must reload the bootstrap prompt.

### Manifest Scope

The current manifest generated for version `26.6.28` contains 36 files.

Included:

| Target path pattern | Starter-pack source | Kind | Merge policy |
|---|---|---|---|
| `AGENT.md` | `base/AGENT.md` | `agent_prompt` | `replace_managed_if_current` |
| `me/todo.md` | `base/me/todo.md` | `user_memory_template` | `preserve_owner_state` |
| `me/profile.md` | `base/me/profile.md` | `user_memory_template` | `preserve_owner_state` |
| `documents/<project>/AGENT.md` | `projects/templates/<project>/AGENT.md` | `project_template` | ownership-derived |
| `documents/<project>/spec.md` | `projects/templates/<project>/spec.md` | `project_template` | ownership-derived |
| `documents/<project>/run-interview.md` | `projects/templates/<project>/run-interview.md` | `project_template` | ownership-derived |
| `documents/<project>/plan.md` | `projects/templates/<project>/plan.md` | `project_template` | ownership-derived |
| `documents/<project>/run-planning.md` | `projects/templates/<project>/run-planning.md` | `project_template` | ownership-derived |
| `skills/<skill-id>/SKILL.md` | `skills/<name>.md` | `starter_skill` | `create_if_missing_else_defer` |

Current project template directories included:

- `career`
- `finance`
- `fitness`
- `new-project`
- `relationships`
- `your-agent`

Project template directory explicitly excluded:

- `braindrive-plus-one`

Current starter skills included:

- `skills/feature-spec/SKILL.md`
- `skills/interview/SKILL.md`
- `skills/plan/SKILL.md`

Current starter-pack files not included in the update manifest:

- `memory/starter-pack/base/preferences/default.braindrive-managed-secret-ref.json`
- `memory/starter-pack/base/preferences/default.local-dev.json`
- `memory/starter-pack/base/preferences/default.openrouter-secret-ref.json`
- `memory/starter-pack/layout.contract.json`
- `memory/starter-pack/projects/projects.seed.json`
- Any project template files outside the five core files listed above.
- Any retired Finance Budgetting paths.
- Any optional `*-user.md` overlay files.

### Ownership And Merge Policy Rules

Path classification is provided by `classifyBrainDriveMemoryPath`.

| Ownership | Examples | Starter-pack update behavior |
|---|---|---|
| `managed_base` | `AGENT.md`, project `AGENT.md`, `run-interview.md`, `run-planning.md`, `README.md`, `*-rules.md`, `index.md`, procedure-like Markdown | Missing files can be created. Existing changed files require safe merge/replace content; otherwise deferred. |
| `owner_overlay` | `AGENT-user.md`, `run-interview-user.md`, `run-planning-user.md` | Existing files are preserved. Starter pack must not seed overlays. |
| `owner_state` | `me/profile.md`, `me/todo.md`, project `spec.md`, project `plan.md`, most owner-authored Markdown | Missing files can be created. Existing files are preserved as owner state. |
| `generated_output` | `documents/<project>/reports/latest.md` | Existing generated output is preserved. Starter pack must not replace it. |
| `durable_archive` | `documents/<project>/reports/monthly-2026-05.md` | Existing archive output is preserved. Starter pack must not replace it. |
| `source` | files under `statements`, `health-docs`, or `sources` except README contracts | Existing source files are preserved. Starter pack must not replace them. |
| `legacy_retired` | active or archived Finance Budgetting paths | Starter pack must not recreate or replace these paths. |
| `system_internal` | `system`, `preferences`, `skills` roots | Skills are handled through `MemorySkillStore`; update manifest does not include preferences. |

Policy derivation for project template paths:

- `owner_overlay` -> `preserve_owner_overlay`
- `owner_state` -> `preserve_owner_state`
- `generated_output` or `durable_archive` -> `generated_output_lifecycle`
- `source` -> `create_if_missing_else_defer`
- `managed_base` -> `create_if_missing_else_replace_managed`
- fallback -> `create_if_missing_else_defer`

### Planning Requirements

LLM planning prompt requirements:

- The LLM is instructed to merge starter-pack improvements while preserving owner customizations.
- Draft 3 uses managed base files plus optional `-user.md` owner overlays.
- Managed base content may be updated.
- Owner overlays, owner state, sources, and existing generated outputs must not be overwritten.
- Owner-specific facts, merchant mappings, preferences, goals, plans, todos, and personal context must never be moved into managed base files.
- Persistent owner rules belong in matching `-user.md` overlays or must be marked for review.
- Uncertain, destructive, or ambiguous changes must be marked `defer`.
- The LLM response must be valid JSON matching the plan schema.

Deterministic fallback planning:

- `no_change` when current SHA equals starter-pack SHA.
- `no_change` when an existing file is owner overlay, owner state, generated output, durable archive, source, or has a preserve/generation lifecycle merge policy.
- `create` when the target file is missing.
- `defer` for existing customized files when no LLM merge is available.

Plan normalization:

- Unknown or invalid actions become `defer`.
- Unknown or invalid risks become `high`.
- Unknown or invalid confidence becomes `medium`.
- Missing or empty required replacement content prevents auto-apply for `create`, `merge`, or `replace`.
- Existing preserve-class files are forced to `no_change`.
- Only `no_change`, preserve-class items, and low/medium-risk `create`, `merge`, or `replace` items with replacement content can auto-apply.
- High-risk or non-auto-apply items become `defer`.
- Any manifest candidate omitted by the LLM plan receives a deterministic plan item.
- Final items are sorted by path.

### Apply Requirements

An item is auto-applicable only when:

- Its candidate exists in the current manifest candidate map.
- It is `no_change`, or
- It has `auto_apply=true`.
- Risk is not `high`.
- Action is `create`, `merge`, or `replace`.
- `replacement_content` is present and non-empty.

Apply behavior:

- `no_change` writes nothing.
- Non-skill updates write normalized replacement content directly to the target memory path after creating parent directories.
- Starter skill updates use `MemorySkillStore`.
  - If the skill does not exist, create it with id, heading-derived or humanized name, starter-source description, content, `starter` tag, and `seeded_from` source path.
  - If the skill exists and action is `merge` or `replace`, update the skill content.
- Any plan item that is deferred or not auto-applicable is returned in `deferred_paths`.
- Migration status is:
  - `applied` when there are no deferred paths.
  - `deferred` when there are deferred paths and no applied paths.
  - `partially_applied` when both applied and deferred paths exist.
  - `failed` when apply throws after logging failure.

### Draft 3 Transition Requirements

Before normal automatic startup reconciliation, BrainDrive runs `applyAlphaDraft3Transition`.

Purpose:

- Archive retired Finance Budgetting files as historical owner data.
- Prevent old Finance Budgetting paths from being recreated as active product surfaces.

Input paths considered:

- Active retired root: `documents/finance/budget/**`
- Pre-Draft paths:
  - `documents/finance/budget.md`
  - `documents/finance/rules.md`
  - `documents/finance/budgeting/first-pass-budget.md`
  - `documents/finance/budgeting/monthly-comparison.md`
  - `documents/finance/budgeting/source-evidence.md`
  - `documents/finance/budgeting/report-contract.md`
  - `documents/finance/budgeting/saved-budget-rules.md`
  - `documents/finance/budgeting/index.md`
  - `documents/finance/statements/README.md`
  - `documents/finance/reports/README.md`
  - `documents/finance/reports/latest.md`

Archive behavior:

- Active budget files move under `documents/finance/archive/retired-budget/`.
- `README.md` under the retired active root becomes `original-README.md`.
- Pre-Draft paths move under `documents/finance/archive/retired-budget/pre-draft/`.
- If the preferred archive target already exists with identical content, reuse it.
- If it exists with different content, archive under `documents/finance/archive/retired-budget/conflicts/<source-path>`.
- Remove original source files after archiving.
- Remove the active `documents/finance/budget` directory after archive processing.
- Add `documents/finance/archive/retired-budget/README.md` if missing.
- Write transition plan, report, and backup when there are archive review paths.
- Attempt a memory git commit when paths were archived.

### Gateway Requirements

Memory update APIs:

| Method | Path | Behavior |
|---|---|---|
| `GET` | `/updates/memory/status` | Returns update status. |
| `POST` | `/updates/memory/plan` | Generates and persists normalized plan. |
| `POST` | `/updates/memory/apply` | Applies saved plan for current migration. |
| `GET` | `/updates/memory/reports/:migrationId` | Returns Markdown report or 404. |

Authorization:

- Each endpoint requires `administration`.
- Each endpoint requires `memory_access`.

Concurrency:

- Startup update sets `migrationInProgress=true`.
- Manual apply refuses to start when `migrationInProgress=true`.
- During migration, general requests are blocked with `423 migration_in_progress`.
- Requests under `/migration` and `/updates/memory` are allowed through the migration gate.

Configuration:

- `PAA_MEMORY_AUTO_UPDATE_ENABLED` defaults to true.
- `BRAINDRIVE_APP_VERSION` overrides resolved app version.
- If no app version override or applied release version exists, app version falls back to package version.
- Applied release version is read from `system/updates/state.json` using `last_applied_version`.

### Web Client Requirements

Current client behavior:

- `getMemoryUpdateStatus()` calls `GET /updates/memory/status`.
- `getMemoryUpdateReport(migrationId)` calls `GET /updates/memory/reports/:migrationId`.
- `AppShell` checks update status on mount.
- If `report_path` exists and the report has not been dismissed for that migration id, the client fetches and displays the report.
- The notice indicates whether deferred paths exist.
- Dismissal is local to the browser through localStorage.

Current client limitations:

- The web client does not expose a complete manual plan/apply UI.
- The notice is report-driven; it does not show pending updates before a report exists.

## Data, Memory, And Artifact Contracts

| Artifact | Path | Owner | Written by | Purpose |
|---|---|---|---|---|
| Memory update state | `system/updates/memory-state.json` | System | update subsystem | Tracks memory pack version, checked app version, pending/completed migration ids, report timestamp, update timestamp. |
| Migration log | `system/updates/memory-migrations.json` | System | update subsystem | Append-style list of migration status entries. Replaces same migration id + status entries when appending. |
| Starter-pack manifest copy | `system/updates/starter-pack-manifest.json` | System | plan/apply path | Stores current generated manifest in owner memory. |
| Plan | `system/updates/plans/<migration_id>.json` | System | plan generation | Stores normalized update plan. |
| Report | `system/updates/reports/<migration_id>.md` | System/owner-readable | apply path | Human-readable update outcome. |
| Backup | `system/updates/backups/<migration_id>.tar.gz` | System/recovery | apply path | Full memory archive before update writes. |
| Draft 3 transition plan | `system/updates/plans/draft3-memory-alpha.json` | System | Draft 3 transition | Records retired Budgetting archive plan. |
| Draft 3 transition report | `system/updates/reports/draft3-memory-alpha.md` | System/owner-readable | Draft 3 transition | Records retired Budgetting archive results. |
| Draft 3 transition backup | `system/updates/backups/draft3-memory-alpha.tar.gz` | System/recovery | Draft 3 transition | Full memory archive before Draft 3 archive changes. |

## Invariants And Edge Cases

### Properties That Must Always Hold

- Starter-pack updates must never automatically overwrite existing owner state.
- Existing owner overlays must be preserved.
- Existing generated output and durable archives must be preserved.
- Existing source files must be preserved.
- Existing customized managed-base files must be deferred unless a safe low/medium-risk plan provides replacement content.
- Missing manifest files can be created.
- Applying a plan must fail rather than write if a candidate file changed after planning.
- Reports must distinguish updated files from deferred/unchanged files.
- Backups must exist when file changes are applied.
- Missing model credentials must not prevent deterministic update planning.
- Invalid LLM output must not abort startup updates.
- Finance Budgetting retired paths must not be included in current starter-pack manifest updates.

### Edge Cases To Test

- Empty memory root.
- Memory root with only customized `AGENT.md`.
- Memory root already matching starter pack.
- Missing starter skills after layout initialization skipped legacy skill bootstrap.
- Existing customized project `AGENT.md` files.
- Missing project `run-interview.md` and `run-planning.md`.
- Existing owner `spec.md` and `plan.md`.
- LLM plan missing migration id.
- LLM plan omitting manifest candidates.
- LLM plan with high-risk merge.
- LLM plan with action requiring replacement content but no content.
- Existing target file changes between plan and apply.
- Missing starter-pack source directory.
- App version string that cannot be semver-compared.
- Migration log contains deferred migration for current memory pack version.
- Existing archive target conflict during Draft 3 transition.

### Failure Modes

| Scenario | Current expected behavior |
|---|---|
| No starter-pack directory exists | Manifest contains no files; candidates are empty; status/plan operate with empty scope. |
| Model adapter unavailable | Deterministic plan is generated. |
| LLM throws or returns invalid JSON | Error is audit-logged and deterministic plan is used. |
| LLM omits some candidates | Missing candidates receive deterministic plan items during normalization. |
| LLM proposes unsafe item | Normalization defers it. |
| Plan file missing on manual apply | `applyMemoryUpdatePlan` throws `Memory update plan not found`. |
| Candidate changed after plan | Apply throws `Memory file changed before update apply: <path>`. |
| Report id is malformed | Report read returns null; API returns 404. |
| Git commit fails | Audit log records failure; apply result still returns if file writes/report/state succeeded. |
| Startup update throws | Audit log records `memory_update.startup_failed`; gateway continues after clearing migration flag. |

## Technical Context

### Current Implementation Model

The update system is a reconciliation layer between:

1. Starter-pack source files shipped with the app.
2. Existing owner memory files.
3. BrainDrive Draft 3 ownership classification.
4. Optional LLM merge assistance.
5. Deterministic safety fallback.
6. Gateway startup/manual API surfaces.
7. Owner-readable reports and backups.

### Integration Points

- Memory root path resolution: `resolveMemoryPath`.
- Git/archive operations: `exportMemoryArchive`, `commitMemoryChange`.
- Starter skills: `MemorySkillStore`, `slugifySkillName`.
- Model planning: `ModelAdapter.complete`.
- Gateway auth: `authorize(request.authContext, "administration")` and `authorize(request.authContext, "memory_access")`.
- Gateway startup prompt reload: `readBootstrapPrompt`.
- Web client notification: `AppShell`.
- Draft 3 memory layout validation: `lintDraft3MemoryStarterPack`.

### Hard Constraints

- Do not put BrainDrive-owned provider keys in client config.
- Do not modify owner state automatically once it exists.
- Do not seed owner overlay files from the starter pack.
- Do not recreate retired Finance Budgetting active paths.
- Do not treat manual or automatic memory update as a substitute for memory backup/restore.
- Do not suppress update errors by silently writing unsafe changes.
- Do not assume every starter-pack file is in update scope; manifest generation is explicit and narrow.

## Test Strategy

### Existing Automated Coverage

Current focused tests cover:

- Missing starter files are auto-created.
- Customized existing files are deferred without an LLM.
- Starter skill creation is owned by the update subsystem when startup layout skips legacy skill bootstrap.
- Life-area project templates in the starter-pack manifest include the five core files.
- Finance Budgetting and Fitness health-doc stale paths are not included in the manifest or applied.
- LLM-generated merge can apply customized `AGENT.md`.
- Incomplete LLM plans are normalized without aborting startup updates.
- Already-current memory reports no pending update.
- Gateway exposes status, plan, apply, and report endpoints.
- Draft 3 path classification distinguishes managed base, owner overlay, owner state, generated output, durable archive, source, legacy retired, and system internal paths.
- Draft 3 starter-pack layout lint rejects stale paths, seeded overlays, builder-only starter skills, missing required files, and missing preservation rules.

Observed verification result on 2026-06-29:

- `npm run test -- memory/update-prompting.test.ts` passed: 1 test file, 6 tests.
- `npm run test -- memory/brain-drive-layout.test.ts memory/starter-pack-draft3-layout.test.ts` failed: `memory/brain-drive-layout.test.ts` passed, but `memory/starter-pack-draft3-layout.test.ts` failed because current starter-pack templates do not document optional overlays in project `AGENT.md` files and are missing several required lint markers.

### Verification Commands

Focused commands for this subsystem:

```bash
cd builds/typescript
npm run test -- memory/update-prompting.test.ts
npm run test -- memory/brain-drive-layout.test.ts
npm run test -- memory/starter-pack-draft3-layout.test.ts
npm run test -- gateway/auth-routes.integration.test.ts
```

Broader commands before release:

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

### Acceptance Evidence

- Passing focused Vitest output.
- Generated manifest snapshot for the target package version.
- Example update report showing updated/deferred paths.
- Backup path present when files were applied.
- Memory state showing `memory_pack_version` equal to target version after handled migration.
- Migration log containing a final `applied`, `partially_applied`, or `deferred` entry.

## Security, Privacy, And Trust Considerations

### Risk Level

High. The subsystem reads and writes owner memory files, may use model output to generate replacement content, writes backups, serves update reports over authenticated API endpoints, and can run automatically on startup.

### Trust Requirements

- Owner facts, preferences, goals, plans, todos, personal context, and source evidence must not be moved into managed base files.
- LLM output must be normalized through deterministic rules before apply.
- High-risk or ambiguous model output must be deferred.
- Existing owner files must be hash-checked immediately before apply.
- Backups must be created before writes.
- Reports must be owner-readable and explicit about what changed.
- Endpoints must remain authorized.
- Browser dismissal must not delete the underlying report.

### Current Mitigations

- Narrow manifest scope.
- Ownership-based classification.
- Deterministic fallback.
- Plan normalization.
- Hash-based stale-plan detection.
- Backup before writes.
- Markdown report after apply.
- Migration log and state files.
- Gateway migration lock.
- Auth checks for all update endpoints.
- Audit logs for plan/apply/startup failures and unavailable adapters.

## Explicit Boundaries

### Do Not Modify Automatically

- Existing `me/profile.md`.
- Existing `me/todo.md`.
- Existing project `spec.md`.
- Existing project `plan.md`.
- Existing owner overlays such as `AGENT-user.md`, `run-interview-user.md`, and `run-planning-user.md`.
- Existing source files under `statements`, `health-docs`, or `sources`.
- Existing generated reports.
- Existing durable archive reports.
- Retired Finance Budgetting active/archive paths.
- Preferences files.
- Provider secrets or credentials.

### Do Not Include In Starter-Pack Memory Update Scope Without A Spec Change

- Starter-pack preference defaults.
- `layout.contract.json`.
- `projects.seed.json`.
- Project template files outside `AGENT.md`, `spec.md`, `run-interview.md`, `plan.md`, and `run-planning.md`.
- Optional overlay files.
- Builder-only skills.
- Any active Finance Budgetting app files.

### Out Of Scope For Current System

- Full owner-facing manual update review UI.
- Three-way merge against previous starter-pack versions.
- Semantic validation of LLM merged content beyond normalization and risk gating.
- Automatic resolution of deferred files.
- Cross-device sync of dismissed update notices.
- Exposing backup restore from the update notice itself.

## Open Questions And Recommendations

No implementation-blocking open questions were found in the current code path. The behavior is explicit in implementation and covered by focused tests.

Recommendations for future hardening:

1. Add an owner-facing manual review/apply screen for pending updates before a report exists.
2. Store dismissed update notices in memory or account state if dismissal should sync across browsers.
3. Add a manifest snapshot test that locks the exact current update scope for each release.
4. Add a stale-plan API test that verifies apply fails when a target file changes between plan and apply.
5. Add explicit test coverage for high-risk LLM items being normalized to `defer`.
6. Consider a three-way merge strategy using previous starter-pack hashes if automatic managed-base updates need to become more aggressive without risking owner changes.
7. Add report links or recovery guidance that point owners to the backup path and explain when to use it.

## Changelog

| Date | Change | Reason | Source |
|---|---|---|---|
| 2026-06-29 | Initial current-state spec created. | Document BrainDrive starter-pack memory update behavior from live code. | `/home/hex/Project/BrainDrive-Test-01` |

## Conversation References

| Date | Source | Topics Discussed |
|---|---|---|
| 2026-06-29 | User request in Codex | Create a complete Markdown spec for BrainDrive update functionality, focused on how starter-pack changes update user memory and which files can be updated. |

## Approval

- [ ] Reviewed by: _______________
- [ ] Date: _______________
- [ ] Accepted as current-state spec: [ ]
