> 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/phase19-session02-server-backbone/spec.md).

# Session Specification

**Session ID**: `phase19-session02-server-backbone` **Phase**: 19 - Orchestration Command Center Execution **Status**: Not Started **Created**: 2026-06-26 **Package**: apps/server **Package Stack**: TypeScript

***

## 1. Session Overview

This session adds the server-side command-center backbone in `apps/server` after Session 01 completed the shared protocol contracts. It introduces manager-owned, in-memory scaffolds, request validation, REST route bindings, WebSocket update emission, diagnostics integration, tests, and server/API documentation for the Phase 19 command-center families.

The session is next because Phase 19 is contract-first and the server backbone is the earliest unfinished dependency for the later web shell, campaign workbench, attention queue, executor registry, file/git, terminal/container, handoff, channel, metrics, and documentation sessions. The scope deliberately scaffolds route and manager behavior without claiming real file, git, terminal, container, remote, Worker, hosted, or channel execution.

The current server already has local route modules, manager-owned in-memory state, `RequestValidator` helpers, bounded route errors, optional auth/CORS/rate-limit middleware, WebSocket hydration, and tests for task queue and guarded action behavior. This session follows those patterns while consuming the new `@factionos/protocol` command-center DTOs, compact events, REST aliases, and capability envelopes.

***

## 2. Objectives

1. Add command-center manager scaffolds for plans, tasks, attention, capabilities, heroes, permissions, file intents, workpads, evidence, verification, handoffs, diagnostics, channels, usage, and notification readiness.
2. Add REST routes that validate command-center snapshot queries and scaffold mutations, enforce idempotency and expected revisions, and return compact capability or error envelopes.
3. Emit compact command-center WebSocket update frames for accepted mutations and hydrate new sockets without leaking raw developer payloads.
4. Update diagnostics, route docs, and tests so scaffolded capability is visibly distinct from implemented execution.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase19-session01-protocol-and-events` - Provides command-center DTOs, parser helpers, compact WebSocket event families, REST aliases, capability states, and unavailable envelopes in `packages/protocol`.

### Required Tools Or Knowledge

* Node 26.2.0+ and npm 11.16.0 workspace commands.
* Existing server route patterns in `apps/server/src/routes/orchestration.ts` and `apps/server/src/routes/guardedActions.ts`.
* Existing manager patterns in `apps/server/src/managers/taskQueue.ts` and `apps/server/src/managers/guardedActions.ts`.
* Existing validation and error helpers in `apps/server/src/lib/requestValidation.ts`, `apps/server/src/lib/orchestrationValidation.ts`, and `apps/server/src/lib/guardedActionValidation.ts`.
* Existing WebSocket hydration and broadcast patterns in `apps/server/src/ws/handlers.ts` and `apps/server/src/ws/broadcaster.ts`.

### Environment Requirements

* Run from the repository root with dependencies installed.
* No hosted credentials, provider credentials, Cloudflare access, real executors, Docker runtime, terminal PTY runtime, channel webhook secrets, or database service is required.

***

## 4. Scope

### In Scope (MVP)

* Server consumers can request command-center snapshots - add root and `/api` mounted `GET /command-center/*` routes for capabilities, plans, tasks, attention, executors, hero lifecycle, executions, permissions, file intents, workpads, evidence, verification, handoffs, diagnostics, channels, usage, and notification readiness.
* Server consumers can exercise safe scaffold mutations - add bounded `POST` or decision routes for draft plan campaigns, plan tasks, attention items, permission decisions, capability refresh, execution-run unavailable results, review gates, handoffs, channel commands, and notification readiness where the protocol contract already defines a request shape.
* Manager code owns idempotency, revision checks, duplicate-trigger prevention, timeout or stale-state cleanup, audit refs, event entries, counts, and deterministic ordering for scaffolded state.
* Unsupported or non-ready families return structured capability errors with repair guidance and docs paths instead of running executors.
* WebSocket clients receive compact command-center update frames on hydration and accepted mutations.
* Server route tests cover validation, stale revisions, duplicate mutation, event emission, and capability-error responses.

### Out Of Scope (Deferred)

* Full file, git, terminal, container, remote access, Worker, hosted, or channel execution - Reason: later Phase 19 sessions own concrete executor families after permission, audit, redaction, output caps, rollback, tests, and docs land.
* Web component restructuring or Zustand store changes - Reason: Session 03 owns web shell and store wiring after server routes exist.
* Persistent storage or migrations for command-center state - Reason: the Session 02 stub calls for manager shells and route bindings, while current analogous queue and guarded-action managers are in-memory.
* Importing, copying, transforming, or shipping `EXAMPLES/` artifacts - Reason: Phase 19 preserves historical material as evidence only.

***

## 5. Technical Approach

### Architecture

Create a server-owned `OrchestrationCommandCenterManager` in `apps/server/src/managers/orchestrationCommandCenter.ts`. The manager keeps bounded in-memory collections for the command-center families named by the Session 02 stub and exposes list, create or decision, count, capability, cleanup, and event-entry helpers. It should reuse Session 01 parser helpers from `@factionos/protocol` at manager or route boundaries so malformed values fail closed before entering state.

Create `apps/server/src/lib/commandCenterValidation.ts` for route-specific query, body, id, expected revision, idempotency key, and command-center parser adaptation. Validation errors should use compact `invalid_request` responses and must not echo raw request bodies, prompts, command text, file contents, tokens, terminal output, provider payloads, absolute paths, or other blocked payloads.

Create `apps/server/src/routes/commandCenter.ts` and mount it through the existing `mountLocalApiRoutes` function in `apps/server/src/server.ts`, so every route is available at both root and `/api` like current local APIs. Route handlers should share one mutation wrapper that prevents duplicate in-flight triggers, calls manager methods, emits the matching `command_center_*_update` event through `Broadcaster`, and returns protocol-shaped list, mutation, capability, conflict, validation, or unavailable envelopes.

Extend WebSocket hydration in `apps/server/src/ws/handlers.ts` with the manager's compact initial command-center events after the existing guarded-action hydration frames. Extend `apps/server/src/lib/orchestrationDiagnostics.ts` so local diagnostics report command-center scaffold availability and counts without raw state rows. Update `apps/server/README_server.md`, `docs/api/README_api.md`, and `docs/api/event-api-hook-contracts.md` to document the scaffolded route families, emitted event families, and explicit non-executing boundary.

### Design Patterns

* Manager-owned state: matches `TaskQueueManager`, `GuardedActionManager`, and `SuggestionManager` ownership boundaries.
* Shared mutation wrapper: matches existing route duplicate-trigger prevention while consolidating command-center in-flight locks.
* Protocol parser adaptation: consumes Session 01 command-center parsers rather than duplicating DTO validation.
* Compact broadcast frames: matches current queue, template, mission graph, guarded-action, Notice Board, and Quest Board event posture.
* Capability-first non-execution: keeps real executor, hosted, Worker, and inbound command families unavailable or proposal-only until later scoped sessions prove readiness.

***

## 6. Deliverables

### Files To Create

| File                                                     | Purpose                                                                                                                                              | Est. Lines |
| -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/server/src/managers/orchestrationCommandCenter.ts` | In-memory command-center manager scaffolds, counts, idempotency/revision helpers, capability envelopes, cleanup, and compact event entry builders    | \~750      |
| `apps/server/src/lib/commandCenterValidation.ts`         | Route query/body/id validation and protocol parser adaptation for command-center routes                                                              | \~320      |
| `apps/server/src/routes/commandCenter.ts`                | REST snapshot and scaffold mutation route bindings plus broadcast helpers                                                                            | \~480      |
| `apps/server/tests/commandCenterManager.test.ts`         | Manager tests for idempotency, stale revisions, cleanup, unavailable capabilities, counts, and compact entries                                       | \~300      |
| `apps/server/tests/commandCenterRoutes.test.ts`          | Route tests for validation, snapshot lists, scaffold mutations, duplicate handling, stale revisions, event emission, and non-ready capability errors | \~460      |

### Files To Modify

| File                                                 | Changes                                                                                                                                       | Est. Lines |
| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/server/src/server.ts`                          | Instantiate command-center manager, mount routes, pass manager to diagnostics and WebSocket handlers, and include lifecycle cleanup if needed | \~35       |
| `apps/server/src/ws/handlers.ts`                     | Send compact command-center hydration events in deterministic order                                                                           | \~60       |
| `apps/server/src/lib/orchestrationDiagnostics.ts`    | Add command-center scaffold availability and bounded counts to local diagnostics                                                              | \~60       |
| `apps/server/tests/orchestrationDiagnostics.test.ts` | Cover command-center diagnostics availability and compactness                                                                                 | \~80       |
| `apps/server/tests/websocket.test.ts`                | Extend hydration-order and compactness coverage for command-center frames                                                                     | \~90       |
| `apps/server/README_server.md`                       | Document server command-center scaffold routes, events, and non-executing capability boundary                                                 | \~120      |
| `docs/api/README_api.md`                             | Add public API rows and boundary notes for the scaffolded command-center endpoints                                                            | \~120      |
| `docs/api/event-api-hook-contracts.md`               | Add route/event reconciliation notes for command-center server-produced frames and typed-only versus scaffolded behavior                      | \~140      |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Command-center manager exposes bounded snapshot state and compact event entries for every Session 02 family.
* [ ] Root and `/api` command-center routes validate all query/body inputs and return protocol-shaped snapshots, mutations, capability envelopes, conflicts, validation errors, or unavailable errors.
* [ ] Accepted scaffold mutations emit the matching compact `command_center_*_update` WebSocket event.
* [ ] Duplicate idempotency keys and duplicate in-flight route triggers do not create duplicate manager records or duplicate state transitions.
* [ ] Stale expected revisions produce compact conflict responses.
* [ ] Non-ready file, git, terminal, container, remote, Worker, hosted, and channel capabilities return structured repair guidance without executing work.
* [ ] Existing task queue, agent template, guarded action, diagnostics, and WebSocket hydration behavior still works.

### Testing Requirements

* [ ] Unit tests written and passing for command-center manager behavior.
* [ ] Route tests written and passing for accepted and rejected command-center inputs.
* [ ] WebSocket tests verify command-center hydration and mutation events.
* [ ] `npm --workspace apps/server run typecheck` passes.
* [ ] Focused server Vitest targets pass for command-center manager, command-center routes, diagnostics, WebSocket hydration, orchestration routes, and guarded actions.

### Non-Functional Requirements

* [ ] Broad REST and WebSocket payloads do not expose raw prompts, command bodies, diffs, terminal output, file contents, transcript text, provider payloads, tokens, secrets, broad absolute paths, hosted account data, raw logs, replay buffers, or export payloads.
* [ ] Route responses remain bounded, deterministic, and sorted for repeatable web/store consumption.
* [ ] Server middleware boundaries remain unchanged: loopback bind defaults, local bearer auth, CORS/origin checks, fixed-window rate limiting, and body-size caps still wrap the route module.
* [ ] No new runtime dependency or database dependency is added.

### Quality Gates

* [ ] All files ASCII-encoded
* [ ] Unix LF line endings
* [ ] Code follows project conventions
* [ ] Primary user-facing surfaces contain product-facing copy only

***

## 8. Implementation Notes

### Working Assumptions

* The selected package context is `apps/server`: the candidate stub declares `apps/server`, Session 01 completed the shared protocol package prerequisite, and later Phase 19 sessions depend on server route behavior. Planning can proceed without user arbitration because no other unfinished Phase 19 session has an earlier dependency position.
* Command-center routes should use a new `/command-center/*` local route namespace mounted at both root and `/api`: the protocol exposes command-center REST aliases but not concrete path constants, while current server route modules use direct product namespaces and are mounted by `server.ts` at both prefixes. This keeps the Session 02 route family coherent without reusing historical `EXAMPLES/` paths.
* Command-center state should be in-memory for this session: the stub asks for manager shells and route bindings, current `TaskQueueManager` and `GuardedActionManager` are in-memory, and persistence is not listed until later feature-specific sessions need durable artifacts.
* WebSocket hydration should append command-center frames after existing local orchestration frames: `README_server.md` documents the current hydration order through `guarded_action_update`, and appending avoids breaking existing client expectations for earlier frames.

### Conflict Resolutions

* The Phase 19 PRD says execution is in scope for the phase, while the master PRD, considerations, and security posture keep real executors deferred unless permission, audit, redaction, tests, docs, and unavailable states exist. This session resolves the conflict by adding server scaffolds and capability errors only; no executor runs, filesystem mutations, git operations, terminal commands, containers, remote access, Worker execution, hosted transfer, or inbound trusted command execution are shipped.
* Historical `EXAMPLES/` route inventories include many command, permission, channel, file, git, terminal, container, and remote paths, while the active PRD says `EXAMPLES/` remains evidence only. This session uses current protocol contracts and server route conventions as implementation truth, and keeps historical paths out of runtime code.
* The UX PRD asks orchestration controls to expose only shipped local contracts, while Session 02 adds many planned families. This session records capability/unavailable states and docs so the future web shell can render scaffolded or non-ready states without presenting execution as available.

### Key Considerations

* Keep local server boundary conservative: validation, auth, CORS/origin checks, rate limits, and body-size caps must continue to wrap all new routes.
* Keep broad payloads compact: IDs, state labels, counts, bounded summaries, safe repo-relative paths, docs paths, revisions, and blocked categories are acceptable; raw developer payloads are not.
* Keep manager APIs boring and testable: deterministic sort order, bounded arrays, explicit conflict envelopes, and no hidden background execution.

### Potential Challenges

* Scope breadth: Mitigate by using one generic manager scaffold with family-specific parser, event, and capability adapters instead of implementing full domain behavior for every future feature.
* Event union breadth: Mitigate by adding focused builders for each `command_center_*_update` event and tests that assert compactness.
* Route count: Mitigate with a small route registration table for list and mutation bindings while keeping each public path explicit in tests and docs.
* Unsupported claims: Mitigate by returning capability envelopes with `unavailable`, `proposal_only`, or `approved_not_executing` states and docs paths for non-ready families.

### Relevant Considerations

* \[P03] **Real executors remain unimplemented by design**: This session keeps real file, git, terminal, remote, and container execution unavailable.
* \[P03-apps/server] **Local server boundary must stay conservative**: New routes must preserve loopback defaults, CORS/origin checks, local auth, request validation, rate limits, body caps, and explicit unavailable behavior.
* \[P07] **Redaction is boundary-specific**: Command-center routes, diagnostics, WebSocket frames, and docs each need separate minimization.
* \[P18-apps/server] **Manager-owned persistence and snapshot emission**: Manager ownership keeps command-center filtering, state, and broadcasts aligned even though this session remains in-memory.
* \[P18-apps/server] **Single-flight scan guards matter**: Apply the same duplicate-trigger thinking to command-center mutations so concurrent route calls cannot create duplicate records.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Broad route or WebSocket snapshots leaking raw prompts, command bodies, local paths, terminal output, provider payloads, tokens, or file contents.
* Duplicate triggers or stale revisions mutating scaffold state twice or overwriting newer records.
* Capability scaffolds being mistaken for shipped executor behavior.

***

## 9. Testing Strategy

### Unit Tests

* Test manager create/list/decision paths for idempotency, duplicate results, expected revision conflicts, stale cleanup, bounded counts, deterministic ordering, unavailable capability envelopes, and compact event entries in `apps/server/tests/commandCenterManager.test.ts`.
* Test validation helpers for malformed bodies, unsafe paths, oversized strings, unknown enum values, invalid IDs, missing JSON objects, raw blocked fields, and compact error mapping in `apps/server/tests/commandCenterRoutes.test.ts`.

### Integration Tests

* Test route snapshots and scaffold mutations through `createFactionOsServer` for `/command-center/*` and `/api/command-center/*`.
* Test WebSocket clients receive command-center hydration frames and mutation events without raw payload fields in `apps/server/tests/websocket.test.ts`.
* Test orchestration diagnostics include command-center availability and counts without raw state rows in `apps/server/tests/orchestrationDiagnostics.test.ts`.

### Runtime Verification

* Run `npm --workspace apps/server run typecheck`.
* Run focused Vitest targets for `apps/server/tests/commandCenterManager.test.ts`, `apps/server/tests/commandCenterRoutes.test.ts`, `apps/server/tests/orchestrationDiagnostics.test.ts`, `apps/server/tests/websocket.test.ts`, `apps/server/tests/orchestration.test.ts`, and `apps/server/tests/guardedActions.test.ts`.
* Run `git diff --check -- apps/server docs/api`.

### Edge Cases

* Duplicate idempotency key reuse, duplicate in-flight route calls, stale expected revisions, missing records, malformed JSON bodies, invalid route IDs, unsafe repo paths, absolute paths, URL-like paths, unknown capability states, unsupported executor families, oversized compact arrays, expired attention or permission items, empty snapshots, unavailable diagnostics, and raw-field attempts nested in arrays or objects.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase19-session01-protocol-and-events`
* Depended by: `phase19-session03-web-shell-and-store`, `phase19-session04-campaign-workbench`, `phase19-session05-attention-and-permissions`, `phase19-session06-executor-registry`, and later Phase 19 sessions that consume server command-center snapshots, events, capabilities, and unavailable states.

***

## Next Steps

Run the `implement` workflow step to begin 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/phase19-session02-server-backbone/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.
