> 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/phase05-session05-federation-event-redaction-and-cockpit-integration/spec.md).

# Session Specification

**Session ID**: `phase05-session05-federation-event-redaction-and-cockpit-integration` **Phase**: 05 - War Room Worker Integration **Status**: Complete **Created**: 2026-05-30 **Package**: Cross-package (`packages/protocol`, `apps/warroom`, `apps/web`) **Package Stack**: TypeScript, React 18, Vite, Zustand, Vitest, Cloudflare Workers, Durable Objects

***

## 1. Session Overview

This session wires the first redacted cockpit federation path through the optional War Room Worker. Sessions 01-04 established the trust model, typed Worker contract, web room lifecycle, join approval, presence, reconnect, and bounded catch-up behavior. Session 05 adds the allowlisted collaboration events that can safely cross the Worker boundary and makes remote participant context visible in the cockpit without turning it into local session truth.

The main implementation path remains protocol-first. Shared event shapes and validators in `packages/protocol` define what may be transferred, the Worker accepts only those validated frames before persistence or catch-up, and the web client/store renders only compact remote context. Prompts, file contents, command bodies, terminal output, transcripts, secrets, broad paths, exports, replay buffers, media drafts, scan payloads, diagnostics, local logs, and provider data must stay out of every Worker send, Worker buffer, remote event, browser overlay, replay path, export path, and localStorage path.

The result should make remote room activity useful but modest: participants can see redacted presence, focus, cursor, coarse hero state, bounded mission state, and room notices from peers. The local cockpit must still work without a Worker URL, without Cloudflare credentials, and without hosted identity, hosted storage, analytics, public replay hosting, remote execution, or unified erasure.

***

## 2. Objectives

1. Define a protocol-owned redacted federation event allowlist with validators, blocked-field scanning, and exhaustive event-family handling.
2. Update the Worker socket path so only allowlisted frames are persisted, sender-excluded, bounded for catch-up, and rejected before sensitive data can cross the Worker boundary.
3. Add web send and receive paths for remote room context while keeping remote data isolated from local game state, replay persistence, exports, notifications, adapters, and localStorage.
4. Render remote participant or ghost hero context in the cockpit with clear local versus remote treatment, accessible labels, and non-color-only state cues.
5. Cover protocol, Worker, web store, component, and privacy-adjacent behavior with focused tests for redaction, sender exclusion, catch-up filtering, duplicate send guards, and sensitive-data blocking.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase05-session01-war-room-requirements-and-trust-baseline` - Provides the source-backed War Room trust model, transfer baseline, and redaction boundaries.
* [x] `phase05-session02-worker-api-hardening-and-client-contract` - Provides typed Worker REST, socket, safe-frame, error, participant, and catch-up contracts.
* [x] `phase05-session03-web-room-lifecycle-and-state-store` - Provides web Worker URL hints, room create/join/connect/disconnect controls, local-only fallback, and socket client plumbing.
* [x] `phase05-session04-join-approval-presence-and-reconnect-ux` - Provides leader approval, roster presence, reconnect, bounded catch-up summaries, leave/reset copy, and fake socket test utilities.
* [x] `phase04-session08-media-validation-and-documentation-closeout` - Confirms the current media, browser, local-first, and privacy posture before optional external transfer expands.

### Required Tools/Knowledge

* Protocol-owned War Room contracts in `packages/protocol/src/warroom.ts`.
* Worker Durable Object socket persistence and sender-excluded fan-out in `apps/warroom/src/index.ts`.
* Web War Room client and store patterns in `apps/web/src/lib/warRoomClient.ts` and `apps/web/src/store/useWarRoomStore.ts`.
* Existing battlefield, roster, replay, export, and localStorage privacy boundaries in `apps/web`.
* Vitest, Testing Library, happy-dom, and package-local fake WebSocket fixtures.

### Environment Requirements

* Node 20+ and npm workspace install are available.
* No Cloudflare credentials are required for implementation or tests.
* Focused tests must use mocks, fake browser sockets, or local Worker fixtures.
* Core local cockpit behavior must remain usable with no Worker URL configured.

***

## 4. Scope

### In Scope (MVP)

* Room participants can send compact redacted federation events - implemented through protocol-owned allowlist validators and a web helper that emits only approved event families.
* Worker socket handling rejects unknown event types, unknown fields, and blocked sensitive keys before persistence, catch-up, diagnostics, logs, or browser consumption.
* Sender-excluded remote updates reach other connected peers without creating duplicate local echoes, replay loops, or local event-log entries.
* The web store receives remote events into a dedicated remote-context state that is separate from local heroes, missions, notices, replay buffers, exports, notifications, adapters, settings, and identity hints.
* The battlefield and War Room panel render remote participant context with local/remote labels, accessible names, text state, and non-color-only cues.
* Catch-up frames use the same redacted allowlist as live remote events and summarize or render only safe compact context.
* Focused tests prove prompts, file contents, commands, terminal output, transcripts, secrets, broad paths, exports, replay buffers, scan payloads, media drafts, diagnostics, and logs cannot be federated.

### Out of Scope (Deferred)

* Sharing raw prompts, transcripts, command output, code files, archives, exports, replay buffers, media drafts, scan payloads, local logs, or broad paths - *Reason: explicitly non-transferable by the Phase 05 baseline.*
* Remote execution, shared hosted queues, inbound chat commands, public replay hosting, analytics, hosted account identity, or hosted storage - *Reason: later phases own these threat models and validation plans.*
* Broad mobile collaboration certification - *Reason: Phase 06 owns mobile and broader collaboration polish.*
* Worker deployment diagnostics, custom-domain health, WAF/rate-limit runbook completion, and environment guidance - *Reason: Session 06 owns deployment environment and diagnostics.*
* Phase 05 end-to-end validation, stable docs closeout, and security posture synchronization - *Reason: Session 07 owns validation and documentation closeout.*
* Unified erasure across Worker room state, browser hints, local logs, archives, exports, replay buffers, backups, and future hosted data - *Reason: Phase 08 owns trusted erasure.*

***

## 5. Technical Approach

### Architecture

Start in `packages/protocol/src/warroom.ts` by expanding the current safe socket frame model into a redacted federation allowlist. The contract should keep the existing safe management frames and add any MVP cockpit context frames needed by the session, such as coarse hero state, bounded mission status, room notice, and focus/cursor updates. Validators must reject unknown fields, invalid enum values, unbounded strings, non-finite coordinates, and blocked sensitive keys anywhere in nested payloads.

Update `apps/warroom/src/index.ts` to consume those shared validators without redefining payload shapes. The Durable Object should persist only validated allowlisted frames in the existing capped recent-event buffer, broadcast remote events to peers other than the sender, and send catch-up using the same redacted event shape. Invalid or sensitive frames should return deterministic `warroom_error` envelopes and must not enter storage or catch-up.

Add web helper logic in `apps/web/src/lib/warRoomFederation.ts` to derive safe outbound frames from local cockpit state and to map inbound frames into remote participant context. This helper should drop or replace sensitive fields before send, enforce bounded labels, avoid broad paths, and expose pure functions that can be tested without React or sockets.

Extend `apps/web/src/store/useWarRoomStore.ts` as the owner of remote War Room context. The store should send federation frames only while connected, guard duplicate or bursty triggers while a send is in flight, handle `remote_event` and catch-up frames into a dedicated remote context map, and clear remote context on leave, reset, hydration, socket cleanup, or participant removal. It must not call the local game store's `applyEvent` path for Worker frames.

Render remote state in the existing cockpit shell by composing a small battlefield overlay and concise War Room panel summaries. Remote treatment must remain visually distinct from local hero truth and expose accessible names, text labels, and local/remote markers. The panel copy should stop saying cockpit federation is future scope after this session, while still making the external transfer boundary visible.

### Design Patterns

* Protocol-first contracts: Add shared event and validator types before Worker or web consumers depend on them.
* Fail-closed validation: Unknown event families, unknown fields, invalid values, and blocked sensitive keys are rejected before persistence or UI consumption.
* Dedicated remote context: Worker room data stays in War Room state and never mutates local hero, mission, replay, export, notification, adapter, or settings state.
* Sender exclusion: Local sends do not create duplicate local echoes or replay feedback loops.
* Scoped socket lifecycle: Remote context and listeners clean up on leave, reset, hydration, disconnect, reconnect replacement, and component teardown.
* Accessible remote overlays: Remote cues use text, labels, and focusable or announced semantics where appropriate, not color alone.
* Honest external-transfer copy: The UI shows optional Worker federation without implying hosted identity, trusted deletion, public sharing, or production-hosted validation.

### Technology Stack

* TypeScript 5.9.3 in `packages/protocol`, `apps/warroom`, and `apps/web`.
* Cloudflare Worker, Durable Objects, and WebSocket in `apps/warroom`.
* React 18, Vite, Tailwind, and Zustand in `apps/web`.
* Vitest 4.1.7, Testing Library, happy-dom, and fake WebSocket fixtures.
* npm workspaces, Biome, and package-local TypeScript typechecks.

***

## 6. Deliverables

### Files to Create

| File                                                               | Purpose                                                                                                             | Est. Lines |
| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/web/src/lib/warRoomFederation.ts`                            | Pure outbound redaction, inbound remote-context mapping, and privacy guard helpers.                                 | \~220      |
| `apps/web/src/components/battlefield/RemoteParticipantOverlay.tsx` | Remote participant and ghost hero battlefield overlay with accessible local/remote treatment.                       | \~180      |
| `apps/web/tests/warRoomFederation.test.ts`                         | Helper tests for allowlisted outbound frames, sensitive-field blocking, inbound mapping, and local truth isolation. | \~220      |
| `apps/web/tests/WarRoomBattlefieldOverlay.test.tsx`                | Component tests for remote overlay labels, accessibility, empty state, and local/remote separation.                 | \~180      |

### Files to Modify

| File                                                  | Changes                                                                                                               | Est. Lines |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | ---------- |
| `packages/protocol/src/warroom.ts`                    | Add redacted federation event types, validators, blocked-field checks, and exhaustive parsing metadata.               | \~260      |
| `packages/protocol/tests/warroom.test.ts`             | Cover allowlisted frames, blocked categories, catch-up typing, unknown-field rejection, and enum exhaustiveness.      | \~180      |
| `apps/warroom/src/index.ts`                           | Consume shared federation validators for persistence, sender-excluded broadcast, catch-up filtering, and safe errors. | \~160      |
| `apps/warroom/tests/warroom.test.ts`                  | Cover sender exclusion, sensitive payload rejection before persistence, catch-up filtering, and recent-event bounds.  | \~220      |
| `apps/web/src/lib/warRoomClient.ts`                   | Add socket send helper or connection send wrapper with serialization failure handling and typed frame input.          | \~100      |
| `apps/web/src/store/useWarRoomStore.ts`               | Add outbound federation action, inbound remote context, cleanup, catch-up merge, and duplicate-send guards.           | \~260      |
| `apps/web/src/components/battlefield/Battlefield.tsx` | Render remote participant overlay without mutating local hero selection or local hero counts.                         | \~80       |
| `apps/web/src/components/WarRoomPanel.tsx`            | Add federation state summary, remote context counts, privacy copy, and remove Session 05 deferred wording.            | \~120      |
| `apps/web/src/lib/warRoomPresence.ts`                 | Summarize remote context and catch-up families without raw payload values.                                            | \~80       |
| `apps/web/tests/warRoomStore.test.ts`                 | Cover remote event ingestion, outbound send gating, sender-exclusion assumptions, cleanup, and replay isolation.      | \~220      |
| `apps/web/tests/WarRoomPanel.test.tsx`                | Cover federation summary, remote context copy, privacy wording, and sensitive-data absence.                           | \~180      |
| `apps/web/tests/Battlefield.test.tsx`                 | Verify remote overlays are labelled separately and do not change local hero count or selection behavior.              | \~120      |
| `apps/web/tests/replayPersist.test.ts`                | Prove Worker remote frames do not enter the local replay persistence path or replay feedback loop.                    | \~80       |
| `apps/web/tests/exportSession.test.ts`                | Prove export-adjacent state remains local and does not include remote room context.                                   | \~80       |
| `apps/web/README_web.md`                              | Document Session 05 shipped federation boundary and remaining deferrals.                                              | \~55       |
| `apps/warroom/README_warroom.md`                      | Document redacted federation event allowlist, sender exclusion, catch-up filtering, and blocked categories.           | \~60       |
| `packages/protocol/README_protocol.md`                | Document protocol ownership for redacted federation contracts.                                                        | \~45       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Protocol validators accept only the approved redacted federation event families and reject unknown event types, unknown fields, invalid values, and blocked sensitive keys.
* [ ] Worker socket handling rejects sensitive payloads before persistence, catch-up, diagnostics, logs, or browser consumption.
* [ ] Sender-excluded remote updates do not echo back to the originating participant and do not create duplicate local events.
* [ ] Web outbound sends are gated on connected room state and are skipped or failed safely when the Worker socket is unavailable.
* [ ] Remote participant context renders in the cockpit with clear local versus remote treatment, accessible names, and non-color-only state cues.
* [ ] Remote room data is not written into local hero state, mission state, replay persistence, export payloads, notifications, adapters, settings, or localStorage identity hints.
* [ ] Catch-up frames use the same redacted allowlist as live frames and do not expose raw Worker event payload values in broad UI copy.

### Testing Requirements

* [ ] Protocol tests cover allowlisted frames, blocked categories, unknown fields, enum validation, bounded strings, and catch-up frame typing.
* [ ] Worker tests cover sensitive payload rejection, sender exclusion, catch-up filtering, recent-event caps, and no persistence after invalid frames.
* [ ] Web helper and store tests cover outbound redaction, send gating, remote event ingestion, cleanup, catch-up merge, duplicate prevention, and replay isolation.
* [ ] Component tests cover War Room panel federation status and battlefield remote overlay accessibility.
* [ ] Privacy-adjacent tests prove replay persistence and export flows remain local and do not include remote room context.

### Non-Functional Requirements

* [ ] Core local FactionOS workflows remain usable with no Worker URL, no Cloudflare credentials, no hosted auth, no hosted storage, and no analytics.
* [ ] External transfer remains optional, explicit, allowlisted, bounded, and redacted by construction.
* [ ] UI copy does not claim hosted identity, public sharing safety, production hosted validation, or trusted deletion.
* [ ] No new runtime media, provider transfer, public-demo dependency, or quarantined historical content is promoted.

### Quality Gates

* [ ] All files ASCII-encoded
* [ ] Unix LF line endings
* [ ] Code follows project conventions
* [ ] Focused protocol, Worker, and web tests pass
* [ ] Relevant package typechecks pass

***

## 8. Implementation Notes

### Key Considerations

* Use `packages/protocol` as the source of truth before touching Worker or web consumers.
* Treat Worker federation as optional external transfer and keep the local server `/warroom` route separate.
* Prefer compact ids, short labels, enum states, normalized coordinates, and coarse status over broad local details.
* Keep remote state in War Room-specific store fields; do not route Worker frames through local `ServerEvent` replay or local game state mutation.
* Preserve sender-excluded semantics already covered by Worker tests.

### Potential Challenges

* Event allowlist can drift between protocol, Worker, and web: Mitigate by importing shared types and validators instead of redefining payload shapes.
* Remote overlay can look like local truth: Mitigate with explicit remote labels, separate test ids, local/remote copy, and no local selection mutation.
* Catch-up can accidentally expose raw ids or labels: Mitigate by summarizing families and mapping only approved compact context.
* Burst sends can spam the Worker or duplicate UI state: Mitigate with connection-state gating and in-flight or deterministic dedupe guards.
* Privacy adjacency can be implicit: Mitigate with replay and export tests that assert remote Worker frames stay out of local persistence and export paths.

### Relevant Considerations

* \[P03-apps/warroom+apps/web] **War Room federation is still separate**: This session wires the approved web-to-Worker federation path while keeping the local server out of room relay behavior.
* \[P03] **Redaction is boundary-specific**: Worker payloads, catch-up, browser overlays, replay, export, logs, and diagnostics each need explicit minimization.
* \[P03-packages/protocol] **Protocol leads cross-package work**: Redacted room and event contracts must be updated in `packages/protocol` before Worker or web code depends on them.
* \[P00] **Hosted services are optional**: Core local workflows must still work without Cloudflare, hosted accounts, hosted storage, analytics, or public client tokens.
* \[P02-apps/web] **Responsive and accessibility debt**: Remote overlays and War Room summaries need accessible names, text states, focus-safe controls, and mobile-friendly layout.
* \[P03] **Unified erasure still missing**: Leave/reset copy must not imply trusted deletion of Worker room data, browser hints, local logs, exports, replay buffers, backups, or future hosted records.
* \[P04] **Asset provenance gate remains active**: Do not add new media or promote conditional media for remote context.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Sensitive local developer data leaks through Worker socket frames, catch-up, logs, browser overlays, replay persistence, or export-adjacent state.
* Remote room context mutates local hero or mission truth and creates confusing selection, replay, notification, or export behavior.
* Sender-excluded events or reconnect catch-up create duplicate local echoes, stale remote overlays, or unbounded retained context.

***

## 9. Testing Strategy

### Unit Tests

* Protocol validator tests for each allowlisted federation event family, invalid enums, unbounded strings, non-finite values, unknown fields, blocked nested keys, and catch-up typing.
* Web federation helper tests for outbound redaction, inbound remote-context mapping, blocked categories, bounded labels, local truth isolation, and exhaustive event-family handling.
* Store tests for send gating, in-flight dedupe, remote event ingestion, catch-up merge, participant removal, leave/reset cleanup, reconnect cleanup, and replay isolation.

### Integration Tests

* Worker Durable Object tests for accepted federation frames, sender-excluded remote broadcasts, rejected sensitive frames, no persistence after invalid frames, and bounded catch-up.
* Web component tests for War Room panel federation summaries and battlefield remote overlay accessibility.
* Replay and export tests proving Worker remote frames are not included in local replay persistence or export payloads.

### Manual Testing

* Start the app with no Worker URL and confirm the cockpit remains local-only.
* In a mocked or local Worker room, connect two participants, send redacted focus or hero-state context, and confirm only the peer sees remote context.
* Trigger invalid sensitive frames in tests or dev tools and confirm the Worker reports a safe error without retaining the payload.
* Leave/reset a room and confirm remote context clears without trusted-erasure claims.

### Edge Cases

* Worker URL absent, malformed, offline, or rate-limited.
* Socket missing, closing, replaced during reconnect, or closed while a send is pending.
* Unknown remote event family or unknown event fields.
* Sensitive key nested inside an otherwise valid frame.
* Reconnecting participant receives catch-up with mixed valid and invalid candidate events.
* Remote participant leaves, disconnects, or is absent from the latest roster.
* Local hero or mission referenced by a remote focus hint is missing.
* Replay is active while remote Worker frames arrive.

***

## 10. Dependencies

### External Libraries

* No new external libraries are planned.
* Existing workspace dependencies: React 18, Zustand, Vite, Vitest, Testing Library, happy-dom, Wrangler, and Cloudflare Worker types.

### Other Sessions

* **Depends on**: `phase05-session01-war-room-requirements-and-trust-baseline`, `phase05-session02-worker-api-hardening-and-client-contract`, `phase05-session03-web-room-lifecycle-and-state-store`, `phase05-session04-join-approval-presence-and-reconnect-ux`
* **Depended by**: `phase05-session06-deployment-environment-and-diagnostics`, `phase05-session07-war-room-validation-and-documentation-closeout`, Phase 06 collaboration, isolation, and mobile work

***

## 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/phase05-session05-federation-event-redaction-and-cockpit-integration/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.
