> For the complete documentation index, see [llms.txt](https://faction-os.gitbook.io/faction-os-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase08-session03-local-erasure-runtime-and-controls/spec.md).

# Session Specification

**Session ID**: `phase08-session03-local-erasure-runtime-and-controls` **Phase**: 08 - Release Hardening and Legacy Decommission **Status**: Not Started **Created**: 2026-05-31 **Package**: Cross-cutting **Package Stack**: TypeScript protocol/server/web contracts plus JavaScript CLI and hooks state handling across `packages/protocol`, `apps/server`, `apps/cli`, `apps/hooks`, `apps/web`, docs, and Phase 08 PRD artifacts

***

## 1. Session Overview

This session implements the local and browser portion of the Phase 08 erasure workflow. Session 02 created the protocol-owned erasure vocabulary and inventory, but it intentionally did not delete data or add user controls. Session 03 turns that inventory into a user-initiated local workflow with dry-run preview, explicit confirmation, progress, partial-failure reporting, audit output, and verification for release-scoped local and browser state.

The work is cross-cutting. The server owns filesystem-backed local state such as archives, memory, settings, lifecycle files, logs, backups, exports, diagnostics, and spool posture. The CLI provides an operator control that can preview and confirm local erasure through loopback-only local behavior. The web cockpit provides a browser control that clears browser settings, replay buffers, War Room hints, local auth hints, and in-memory context after explicit confirmation. Protocol remains the source of shared status, audit, verification, unsupported-claim, and redaction vocabulary.

This session must not claim full trusted unified erasure. Worker Durable Object state, hosted account/storage/analytics/public replay/push/remote state, broad workspace-file deletion, production-hosted validation, and final release wording remain later Phase 08 work. Session 03 should close the local/browser runtime gap while keeping `P06-S07-ERASURE` open until Sessions 04 and 08 supply the remaining evidence.

***

## 2. Objectives

1. Add local erasure runtime contracts for dry-run previews, confirmation requests, progress states, execution summaries, audit entries, idempotency keys, partial failures, and verification results.
2. Implement local filesystem erasure for release-scoped local state with dry-run, explicit confirmation, redacted audit output, idempotency protection, transaction boundaries, partial-failure reporting, and verification.
3. Add CLI and web controls that expose preview, confirmation, progress, completed, partial-failure, unsupported, and verification states without raw sensitive values.
4. Add focused tests and docs proving local/browser erasure behavior, redaction, idempotency, unsupported boundaries, and no-overclaim wording.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase08-session01-release-requirements-and-risk-baseline` - provides Phase 08 claim gates, routing, risk ownership, and no-overclaim release vocabulary.
* [x] `phase08-session02-unified-erasure-contract-and-inventory` - provides shared erasure vocabulary, inventory rows, local/browser boundary ids, blocked payload categories, unsupported claims, and Session 03 handoff.
* [x] `phase07-session07-hosted-guardrails-validation-and-documentation-closeout` - provides disabled, planned, and unavailable hosted-service guardrails that must remain outside local erasure claims.
* [x] `phase03-session06-cli-diagnostics-and-recovery-controls` - provides narrow local recovery, listener PID, log, and spool behavior that must remain distinct from trusted erasure.

### Required Tools/Knowledge

* `packages/protocol/src/erasure.ts` and `.spec_system/PRD/phase_08/unified_erasure_inventory.md`.
* Local filesystem helpers in `apps/cli/src/lib/localFiles.js`, server archive/memory/export helpers, and hook spool/listener behavior.
* Browser stores in `apps/web/src/store/useSettingsStore.ts`, `useGameStore.ts`, and `useWarRoomStore.ts`.
* Current settings drawer, notification/audio/replay UX, and browser localStorage error handling patterns.
* Release, privacy/security, API, and package README no-overclaim wording.

### Environment Requirements

* Node 20+ and npm workspaces installed.
* No Cloudflare, Supabase, Umami, VAPID, hosted account, provider, or production credential is required.
* Tests must use temporary directories, synthetic browser storage, and mocked local server responses only.
* Implementation must not delete workspace source files, Worker Durable Object state, hosted state, public replay hosting, or provider/media draft state.

***

## 4. Scope

### In Scope (MVP)

* Local operator can preview release-scoped local erasure - server and CLI produce bounded summaries for FactionOS home, archives, memory, settings, lifecycle files, project-root state, logs, backups, valid spool entries, malformed spool entries, exports, diagnostics, scan runtime memory, and LLM runtime memory.
* Local operator can explicitly confirm local erasure - confirmed execution removes eligible local filesystem state, skips unsupported/manual-review boundaries, records redacted audit events, reports partial failures, and verifies absence where possible.
* Browser user can preview and confirm browser state erasure - web clears settings, replay buffer, faction hint, War Room hints, local auth hints, URL replay fragments, and in-memory UI context with duplicate-trigger prevention while in-flight.
* CLI and web copy separate local/browser erasure from Worker, hosted, workspace-file, public replay, production-hosted, analytics, push, remote, and full trusted unified erasure claims.
* Tests cover dry-run, confirmation phrase validation, idempotency, partial failure, sensitive-output redaction, unsupported boundary handling, browser storage cleanup, and verification.
* Docs update local erasure behavior, limitations, remaining Worker/hosted boundaries, and `P06-S07-ERASURE` residual-risk status.

### Out of Scope (Deferred)

* Worker Durable Object erasure - *Reason: Session 04 owns Worker erasure or explicit Worker no-claim behavior.*
* Hosted account deletion, hosted storage deletion, analytics deletion, public replay takedown, push subscription deletion, or remote-access deletion - *Reason: hosted surfaces remain planned, disabled, unavailable, or future-scope.*
* Broad workspace source-file deletion - *Reason: workspace files require manual review and final release approval, not a local runtime erase-all operation.*
* Production-hosted validation, mobile/accessibility certification, media release gate revalidation, and legacy decommission - *Reason: Sessions 05 through 07 own those gates.*
* Final trusted unified erasure release claim - *Reason: Session 08 must validate local/browser runtime plus Worker/no-claim handling and final no-overclaim wording.*

***

## 5. Technical Approach

### Architecture

Extend the Session 02 protocol contract with runtime-facing local erasure request, preview, execution, audit, and verification shapes. Keep `packages/protocol` pure and deterministic so server, web, and tests share vocabulary without side effects. Add local-specific ids and status helpers only where they derive from the existing inventory.

Add a server-side local erasure engine that resolves release-scoped paths from the FactionOS home and runtime configuration, builds dry-run summaries without reading payload contents, executes confirmed deletion only after an explicit confirmation phrase and idempotency key are present, and verifies eligible boundary absence after deletion. The engine should use temporary staging or atomic boundaries where practical, skip manual-review or unsupported boundaries, and return partial-failure entries instead of throwing away the whole result.

Add a local server route for the web and CLI to use when the local runtime is available. Route handlers must validate request bodies, enforce existing local auth middleware, map errors explicitly, and avoid raw paths or payloads. The CLI should expose a local erasure command that previews by default and requires an explicit `--confirm` phrase before destructive execution. The web should expose a browser-local control in Settings that previews browser boundaries, requires typed confirmation, disables duplicate actions while in-flight, resets/revalidates state on open, and reports local/server unavailable states clearly.

### Design Patterns

* Protocol-owned runtime vocabulary: shared request/result/status/audit shapes live in `packages/protocol`.
* Dry-run first: every destructive local path requires a preview path and explicit confirmation before mutation.
* Idempotent mutation: confirmed erasure accepts an idempotency key and treats already-absent boundaries as verified absence.
* Boundary-specific redaction: summaries expose boundary ids, labels, statuses, counts, booleans, docs paths, and synthetic ids only.
* Partial failure over broad failure: one failed boundary reports a failure and does not hide successful verified boundaries.
* UX state revalidation: browser controls re-read storage and local server availability when opened and reset transient state when closed.

### Technology Stack

* TypeScript in `packages/protocol`, `apps/server`, and `apps/web`.
* JavaScript in `apps/cli` and existing hook state helpers.
* React 18, Zustand, Vite, and Testing Library for browser controls.
* Express routes, existing local auth middleware, and Vitest focused test files.
* Markdown docs and Phase 08 PRD artifacts.

***

## 6. Deliverables

### Files to Create

| File                                            | Purpose                                                                                                                  | Est. Lines |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ---------- |
| `apps/server/src/lib/localErasure.ts`           | Local erasure dry-run, execution, audit, idempotency, partial-failure, and verification engine                           | \~320      |
| `apps/server/src/routes/erasure.ts`             | Local erasure preview and confirm HTTP routes with schema validation and explicit error mapping                          | \~160      |
| `apps/server/tests/localErasure.test.ts`        | Filesystem erasure runtime tests using temporary directories and synthetic fixtures                                      | \~240      |
| `apps/server/tests/erasureRoute.test.ts`        | Route tests for auth boundary, request validation, dry-run, confirm, idempotency, and redaction                          | \~180      |
| `apps/cli/src/commands/erase.js`                | CLI preview and confirmed local erasure command with loopback-only behavior                                              | \~180      |
| `apps/cli/src/lib/erasureClient.js`             | CLI HTTP/local summary client, confirmation validation, redacted output formatting, and failure mapping                  | \~180      |
| `apps/cli/tests/erasureClient.test.js`          | CLI erasure preview, confirm, timeout, malformed response, redaction, and non-loopback tests                             | \~180      |
| `apps/web/src/lib/localErasure.ts`              | Browser erasure helpers for localStorage/session URL fragments, preview summaries, and server route client               | \~220      |
| `apps/web/src/store/useLocalErasureStore.ts`    | UI state store for preview, confirmation, in-flight state, partial failure, verification, and reset-on-open behavior     | \~180      |
| `apps/web/src/components/LocalErasurePanel.tsx` | Settings panel for local/browser erasure preview, typed confirmation, progress, results, and unavailable states          | \~240      |
| `apps/web/tests/localErasure.test.ts`           | Browser erasure helper tests for storage cleanup, URL fragment cleanup, redaction, unavailable storage, and idempotency  | \~180      |
| `apps/web/tests/LocalErasurePanel.test.tsx`     | UI tests for preview, typed confirmation, duplicate-trigger prevention, focus behavior, partial failure, and state reset | \~220      |

### Files to Modify

| File                                         | Changes                                                                                                                   | Est. Lines |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `packages/protocol/src/erasure.ts`           | Add runtime request/result/audit/verification shapes and local/browser helper constants derived from Session 02 inventory | \~180      |
| `packages/protocol/tests/erasure.test.ts`    | Add runtime contract, idempotency, partial-failure, verification, and unsupported-boundary coverage                       | \~120      |
| `apps/server/src/server.ts`                  | Register local erasure routes after local auth and before unsupported route catch-all                                     | \~6        |
| `apps/cli/src/index.js`                      | Wire `factionos erase` help and command dispatch                                                                          | \~16       |
| `apps/web/src/components/SettingsDrawer.tsx` | Mount the local erasure panel in the settings drawer without disrupting existing controls                                 | \~30       |
| `docs/privacy-and-security.md`               | Document shipped local/browser erasure behavior, redaction, limits, and remaining open Worker/hosted scope                | \~45       |
| `docs/release.md`                            | Record Session 03 local/browser erasure evidence and continued no full trusted unified erasure claim                      | \~40       |
| `docs/api/README_api.md`                     | Document local erasure routes, schemas, auth boundary, and no-overclaim response behavior                                 | \~45       |
| `apps/cli/README_cli.md`                     | Document CLI preview/confirm erasure behavior and limitations                                                             | \~35       |
| `apps/web/README_web.md`                     | Document browser-local erasure controls, storage boundaries, failure states, and remaining non-local limitations          | \~35       |
| `apps/server/README_server.md`               | Document local erasure runtime scope, verification, and sensitive-output rules                                            | \~35       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] A local operator can run a dry-run preview for release-scoped local boundaries without exposing raw prompts, paths, commands, tokens, logs, exports, backups, replay buffers, or spool payloads.
* [ ] Confirmed local erasure requires an explicit confirmation phrase and idempotency key before deleting eligible local filesystem state.
* [ ] Confirmed local erasure reports completed, skipped, unsupported, manual-review, and partial-failure boundaries with redacted audit output and verification results.
* [ ] Already-absent local boundaries are handled idempotently as verified absence, not fatal errors.
* [ ] Browser erasure clears persisted settings, replay buffer, faction hint, War Room hints, auth hints, URL replay fragments, and in-memory UI context after typed confirmation.
* [ ] CLI and web controls expose preview, confirmation, progress, completed, partial-failure, unsupported, and unavailable states with duplicate-trigger prevention while in-flight.
* [ ] Worker Durable Object, hosted, public replay, analytics, push, remote-access, broad workspace-file, and full trusted unified erasure claims remain explicitly unsupported or out of scope.

### Testing Requirements

* [ ] Protocol runtime contract tests written and passing.
* [ ] Server local erasure runtime and route tests written and passing.
* [ ] CLI erasure command/client tests written and passing.
* [ ] Web browser erasure helper, store, and component tests written and passing.
* [ ] Manual docs/no-overclaim review completed.

### Non-Functional Requirements

* [ ] Local-first behavior does not require hosted credentials, Cloudflare credentials, provider keys, analytics config, push config, public replay hosting, or real executors.
* [ ] Erasure summaries, errors, audit entries, and docs use labels, counts, booleans, docs paths, and synthetic ids only.
* [ ] Destructive execution is explicit, duplicate-protected, idempotent, and verifies absence for eligible boundaries.
* [ ] Existing reset, leave, uninstall, diagnostics recovery, and manual cleanup wording remains distinct from local erasure and full trusted unified erasure.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] `git diff --check` passes.

***

## 8. Implementation Notes

### Key Considerations

* Keep the product claim precise: this session ships local/browser erasure runtime, not full trusted unified erasure.
* Do not delete broad workspace source files. Workspace files remain manual-review/final-release scope.
* Local backups are sensitive local developer data. Preview should show backup boundary status and counts without listing raw archive names or absolute paths.
* Malformed spool entries need careful treatment: existing diagnostics recovery removes malformed entries, while this session should report them distinctly and avoid reading raw contents.
* Browser authority tokens should remain memory-only. Browser erasure should clear hints and runtime state without implying Worker Durable Object deletion.

### Potential Challenges

* Safe path resolution: mitigate with a resolver that confines deletion to FactionOS home, configured backup dir, known logs dir, and explicitly owned files.
* Partial deletion failures: mitigate by reporting per-boundary failure and running verification after each boundary.
* Duplicate destructive triggers: mitigate with idempotency keys on the server, in-flight guards in CLI/web, and disabled controls during execution.
* Raw output leakage: mitigate with shared redaction tests that serialize all outputs and assert sensitive fixture strings are absent.
* Browser storage unavailable or quota failures: mitigate with explicit unavailable/error states and no fatal render path.

### Relevant Considerations

* \[P07] **Unified erasure deferred to Phase 08 (P07-R023)**: this session implements the local/browser runtime portion and keeps Worker/hosted/final release scope open.
* \[P07] **Redaction is boundary-specific**: previews, execution summaries, errors, audit entries, docs, and UI must not expose raw payloads or paths.
* \[P03] **Lifecycle state is local and file-based**: PID, port, workspace, listener, hook, spool, log, and backup state require idempotent deletion and stale-state tests.
* \[P03] **Local backups are sensitive state**: backup tarballs remain local and require explicit authority, dry-run, verification, and no upload.
* \[P03] **Protocol leads cross-package work**: shared erasure runtime vocabulary remains in `packages/protocol` before package-specific consumers use it.
* \[P06] **Do not call Worker leave or reset trusted erasure**: browser leave/reset and browser erasure do not delete Durable Object state.
* \[Security] **P06-S07-ERASURE**: local/browser erasure reduces the finding but does not close it until Worker handling and final release validation complete.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* A destructive local action could be triggered twice or without explicit user confirmation.
* Dry-run, progress, errors, audit output, or docs could leak raw local paths, prompts, tokens, logs, backups, exports, replay buffers, or spool payloads.
* Browser cleanup could leave stale in-memory state after clearing persisted storage.
* A local/browser-only success could be overclaimed as full trusted unified erasure.

***

## 9. Testing Strategy

### Unit Tests

* Test protocol runtime contracts for required status values, idempotency key handling, partial-failure reason coverage, audit event shapes, verification methods, and unsupported-boundary labels.
* Test local erasure path resolver with temporary FactionOS homes, configured backup dirs, logs dirs, sessions, memory, settings, lifecycle, project-root, spool, export, diagnostics, scan, and LLM runtime boundaries.
* Test server execution for dry-run-only behavior, explicit confirmation, idempotency, partial failure, absence verification, and sensitive-output redaction.
* Test CLI client behavior for preview, confirm, timeout, malformed JSON, auth-required, non-loopback URL rejection, and redacted console output.
* Test browser helpers for localStorage cleanup, URL fragment cleanup, storage-unavailable handling, idempotency, and no raw stored-value output.
* Test web panel interactions for loading, empty, error, unsupported, confirmation, disabled while pending, focus management, partial failure, completed, and state reset on re-entry.

### Integration Tests

* Run focused Vitest files for protocol, server, CLI, and web erasure work.
* Run affected workspace typechecks for `packages/protocol`, `apps/server`, and `apps/web`.
* Use mocked local server responses for web/CLI route-client behavior.

### Manual Testing

* Run a dry-run against a temporary `FACTIONOS_HOME` containing synthetic archives, memory, settings, lifecycle, logs, backups, spool, and export files.
* Run a confirmed erase against that temporary home and verify eligible files are absent while unsupported/manual-review boundaries are reported.
* Open the Settings drawer locally, preview browser erasure, confirm it, and verify settings/replay/War Room hints reset without layout overlap or broken focus.

### Edge Cases

* Missing FactionOS home.
* Empty FactionOS home.
* Already-erased boundaries.
* Read-only files or permission failures.
* Malformed spool JSON.
* Unavailable browser storage.
* Malformed local server response.
* Non-loopback local server URL.
* Duplicate confirm click or repeated CLI confirm with same idempotency key.
* Existing Worker room context, auth hints, replay fragment, and settings storage all present at once.

***

## 10. Dependencies

### External Libraries

* None new planned. Use Node built-ins, existing Express, existing React/Zustand, and existing Vitest/Testing Library setup.

### Other Sessions

* **Depends on**: `phase08-session02-unified-erasure-contract-and-inventory`
* **Depended by**: `phase08-session04-war-room-and-hosted-identity-release-gate`, `phase08-session08-release-candidate-validation-and-documentation-closeout`

***

## Next Steps

Run the implement workflow step to begin AI-led implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase08-session03-local-erasure-runtime-and-controls/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
