> 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-session15-metrics-and-notifications/spec.md).

# Session Specification

**Session ID**: `phase19-session15-metrics-and-notifications` **Phase**: 19 - Orchestration Command Center Execution **Status**: Not Started **Created**: 2026-06-27 **Package**: null **Package Stack**: mixed

***

## 1. Session Overview

This session turns the command-center metrics and notification records that already exist in protocol, server, and web state into an operator-facing health surface. It is next because Sessions 04, 05, 06, 09, 10, and 14 are complete, and the only earlier unfinished Phase 19 candidate is this metrics and notifications slice.

The implementation is cross-cutting across `packages/protocol`, `apps/server`, and `apps/web`. It extends the existing command-center usage metric and notification readiness contracts, adds manager-owned aggregation and readiness/routing behavior on the server, and replaces the current generic Metrics pane with a product surface for task, hero, plan, queue, executor, attention, and notification health.

The session preserves the local-first boundary. Browser notifications can route local OS notifications, including hidden-tab service-worker delivery, and Web Push subscribe/unsubscribe surfaces can report readiness when VAPID configuration and explicit consent exist. Analytics capture, hosted push delivery, and active hosted claims remain out of scope.

***

## 2. Objectives

1. Add typed command-center metric kinds, rollups, notification channels, readiness, subscription, and routing categories without raw telemetry leakage.
2. Implement server-owned metric aggregation for duration, events, tool usage, estimated tokens/cost, lines changed, failures, retries, throughput, queue age, blocked age, review backlog, pending approvals, latency, executor utilization, provider usage imports, and plan/hero/task rollups.
3. Add local notification and Web Push readiness behavior for approvals, questions, blocked tasks, failed tasks, and review gates with consent, duplicate-trigger prevention, and no-claim fallback states.
4. Replace the generic web Metrics pane with a metrics and notifications panel, header attention summary, mobile attention filters, local notification routing, and focused tests.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase19-session04-campaign-workbench` - provides campaign, task, and queue state for rollups.
* [x] `phase19-session05-attention-and-permissions` - provides attention and permission state for routing and approval metrics.
* [x] `phase19-session06-executor-registry` - provides executor capability and execution records.
* [x] `phase19-session09-heroes-and-lineage` - provides hero lifecycle and lineage state.
* [x] `phase19-session10-mission-artifacts` - provides workpad, evidence, verification, and review-gate records.
* [x] `phase19-session14-channels-and-scope` - provides channel/scope records and filters that metrics must respect.

### Required Tools Or Knowledge

* Current command-center protocol contracts in `packages/protocol/src/orchestrationCommandCenter.ts`.
* Current server command-center manager, routes, validation, session import, and hosted-operation posture in `apps/server/src/`.
* Current web Orchestration shell, store, WebSocket reducer, local notification helper, hosted-operation helper, and cost projection helper in `apps/web/src/`.
* Current docs and no-claim posture for push, Web Push, VAPID, analytics, remote access, and hosted operations.

### Environment Requirements

* Node 26.2.0+ and npm 11.16.0.
* Root npm workspace dependencies installed.
* Local validation through Vitest, TypeScript, Biome, and root workspace checks.

***

## 4. Scope

### In Scope (MVP)

* Operators can see task, hero, plan, queue, executor, attention, approval, review, provider, cost, and throughput metrics as bounded command-center records - aggregate from existing manager-owned state and helper outputs.
* Operators can see compact attention counts, severity/risk distribution, age buckets, mobile filters, and notification routing status - reuse attention and permission records with explicit loading, empty, error, offline, and stale states.
* Operators can opt into local OS notification routing for approvals, questions, blocked tasks, failed tasks, and review gates - route through existing local notification helpers with duplicate-trigger prevention while in flight.
* Operators can inspect Web Push readiness and gated subscribe/unsubscribe state - require explicit consent and configured VAPID posture, and return unavailable/disabled states without claiming active hosted push delivery by default.
* Engineers can validate aggregation, readiness, subscription validation, severity counts, hidden-tab routing, no raw payload echo, and no-claim boundaries through focused protocol, server, and web tests.

### Out Of Scope (Deferred)

* Analytics capture, analytics dashboards, or telemetry export by default - Reason: Phase 19 calls for command-center operational metrics, not analytics ingestion.
* Hosted push delivery without configured VAPID, explicit consent, auth, audit, payload minimization, rate limits, tests, and docs - Reason: hosted services remain disabled-default guardrails.
* New remote access, hosted identity, production-hosted validation, or trusted erasure claims - Reason: cumulative security findings remain open.
* Final keyboard shortcut workflow, cross-link closeout, Playwright coverage, and documentation sweep - Reason: owned by Session 16.
* Raw terminal output, prompts, command bodies, provider payloads, broad paths, replay buffers, or export payloads in metrics or notification payloads - Reason: blocked payload categories remain boundary-specific.

***

## 5. Technical Approach

### Architecture

Protocol changes lead the work. Extend `packages/protocol/src/orchestrationCommandCenter.ts` with typed metric kinds, rollup target metadata, notification channels, notification payload categories, routing categories, subscription status, readiness fields, and parser coverage before server and web code consume them.

Server aggregation should live behind a new usage metrics manager that reads existing command-center collections and imported provider usage summaries through narrow inputs. The manager should produce bounded `CommandCenterUsageMetric` records and notification readiness records, then persist them in the existing `OrchestrationCommandCenterManager` maps and emit `command_center_usage_update`.

Notification routing should be separate from analytics and executor behavior. A server helper validates preferences, VAPID readiness, subscription payloads, consent, and payload categories. Web routing uses the existing local notification module and service-worker background path for hidden tabs while the Web Push route reports unavailable or disabled unless all gates are satisfied.

The web surface should replace the generic `PaneGrid` Metrics tab with a purpose-built panel that uses pure view-model helpers. Cost projection display should reuse `apps/web/src/lib/costProjection.ts`; broad rows should remain metadata-only.

### Design Patterns

* Protocol-first contracts: prevents server/web drift for metric and notification vocabulary.
* Manager-owned aggregation: keeps counts, age buckets, utilization, provider imports, and WebSocket emission in one server boundary.
* Readiness-gated notifications: local notifications can route now; Web Push stays disabled or unavailable until consent and VAPID config are proven.
* Pure web normalization: reject malformed metric and notification events before Zustand mutation.
* Product-facing UI copy: the Metrics pane shows operational state, not debug output or raw telemetry.

***

## 6. Deliverables

### Files To Create

| File                                                                     | Purpose                                                                                                               | Est. Lines |
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/server/src/managers/usageMetricsManager.ts`                        | Manager-owned command-center aggregation for usage, age, backlog, utilization, provider imports, and rollups.         | \~260      |
| `apps/server/src/lib/notificationRouting.ts`                             | Preference, readiness, VAPID, subscription, payload category, and routing validation helpers.                         | \~220      |
| `apps/server/src/routes/commandCenterNotifications.ts`                   | Local notification preference/readiness and Web Push subscribe/unsubscribe routes.                                    | \~180      |
| `apps/server/tests/usageMetricsManager.test.ts`                          | Aggregation tests for counts, durations, age buckets, provider imports, utilization, and redaction.                   | \~200      |
| `apps/server/tests/notificationRouting.test.ts`                          | Routing helper tests for preferences, subscriptions, VAPID readiness, consent, categories, and no raw echo.           | \~180      |
| `apps/server/tests/commandCenterNotifications.test.ts`                   | Route tests for readiness, subscribe/unsubscribe gating, validation, idempotency, and WebSocket updates.              | \~190      |
| `apps/web/src/lib/commandCenterMetrics.ts`                               | Pure view-model helpers for metrics rollups, attention severity counts, cost links, and readiness cards.              | \~220      |
| `apps/web/src/lib/commandCenterNotifications.ts`                         | Local command-center notification routing helper for attention/review events and duplicate suppression.               | \~180      |
| `apps/web/src/components/orchestration/MetricsAndNotificationsPanel.tsx` | Product metrics, attention summary, local notification, and Web Push readiness panel.                                 | \~260      |
| `apps/web/tests/commandCenterMetrics.test.ts`                            | Web helper tests for metric buckets, cost projection labels, severity counts, and safe copy.                          | \~170      |
| `apps/web/tests/commandCenterNotifications.test.ts`                      | Web routing tests for local notifications, hidden-tab service-worker path, consent states, and duplicate suppression. | \~170      |
| `apps/web/tests/MetricsAndNotificationsPanel.test.tsx`                   | Component tests for metrics, readiness, filters, empty/error/offline states, and accessibility.                       | \~200      |

### Files To Modify

| File                                                            | Changes                                                                                                                    | Est. Lines |
| --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `packages/protocol/src/orchestrationCommandCenter.ts`           | Add metric kind, rollup, notification channel, routing category, payload category, subscription status, and parser fields. | \~180      |
| `packages/protocol/tests/orchestrationCommandCenter.test.ts`    | Cover metric kind parsing, notification readiness/subscription parsing, blocked fields, and no raw payloads.               | \~140      |
| `packages/protocol/tests/events.test.ts`                        | Cover compact usage/notification update events with new fields.                                                            | \~60       |
| `apps/server/src/lib/commandCenterValidation.ts`                | Accept enriched usage and notification readiness mutations with explicit error mapping.                                    | \~45       |
| `apps/server/src/managers/orchestrationCommandCenter.ts`        | Store enriched metrics/readiness, refresh aggregated metrics, emit usage updates, and expose route helpers.                | \~120      |
| `apps/server/src/routes/commandCenter.ts`                       | Add missing usage mutation route and wire usage refresh behavior with duplicate-trigger prevention.                        | \~55       |
| `apps/server/src/server.ts`                                     | Mount notification command-center routes under root and `/api` with existing auth, body limits, and rate limits.           | \~35       |
| `apps/server/src/lib/claudeSessionImport.ts`                    | Expose bounded provider usage import fields where present.                                                                 | \~35       |
| `apps/server/src/lib/codexSessionImport.ts`                     | Expose bounded provider usage import fields where present.                                                                 | \~35       |
| `apps/server/tests/commandCenterManager.test.ts`                | Cover refreshed metric records, combined event counts, and readiness state transitions.                                    | \~90       |
| `apps/server/tests/commandCenterRoutes.test.ts`                 | Cover usage POST/refresh routes, hydration frame expectations, WebSocket updates, and no raw echo.                         | \~90       |
| `apps/web/src/lib/orchestrationApi.ts`                          | Add usage mutation/refresh and notification preference/subscription clients with timeout/offline/error mapping.            | \~120      |
| `apps/web/src/store/useGameStore.ts`                            | Store notification preferences/readiness, normalize enriched metric events, and preserve selected detail on refresh.       | \~100      |
| `apps/web/src/store/useWsClient.ts`                             | Validate enriched usage/notification event frames before store mutation.                                                   | \~80       |
| `apps/web/src/lib/notifications.ts`                             | Add command-center notification categories, bounded payload builders, and hidden-tab delivery coverage.                    | \~95       |
| `apps/web/src/lib/useNotifications.ts`                          | Subscribe to command-center attention/review changes without replaying stale records.                                      | \~75       |
| `apps/web/src/lib/hostedOperations.ts`                          | Reflect Web Push readiness/subscription posture without implying active hosted delivery.                                   | \~55       |
| `apps/web/src/lib/commandCenterUi.ts`                           | Add metric status, notification readiness, attention severity, and mobile filter view helpers.                             | \~130      |
| `apps/web/src/components/orchestration/OrchestrationHeader.tsx` | Add compact attention count and severity distribution to the command-center header.                                        | \~55       |
| `apps/web/src/components/orchestration/AttentionWorkbench.tsx`  | Add mobile-focused attention filters and age/severity count presentation.                                                  | \~85       |
| `apps/web/src/components/orchestration/CommandCenterPanes.tsx`  | Mount the metrics and notifications panel in the Metrics tab.                                                              | \~45       |
| `apps/web/src/components/orchestration/OrchestrationShell.tsx`  | Load metrics/readiness, route notification actions, refresh metrics, and pass settings/online state.                       | \~120      |
| `apps/web/src/components/SettingsDrawer.tsx`                    | Surface local notification and Web Push readiness controls without active push claims.                                     | \~70       |
| `apps/web/tests/OrchestrationPanel.test.tsx`                    | Cover Metrics tab behavior, attention header summary, mobile filters, and notification actions.                            | \~180      |
| `apps/web/tests/orchestrationApi.test.ts`                       | Cover metrics refresh, notification preferences, subscription clients, and failure mapping.                                | \~120      |
| `apps/web/tests/commandCenterStore.test.ts`                     | Cover enriched usage/notification event normalization and malformed payload rejection.                                     | \~90       |
| `apps/web/tests/notifications.test.ts`                          | Cover new command-center categories, hidden-tab routing, throttle buckets, and payload bounding.                           | \~120      |
| `apps/web/tests/useNotifications.test.tsx`                      | Cover command-center attention routing without seed replay or disabled-notification leakage.                               | \~100      |
| `apps/web/tests/hostedOperations.test.ts`                       | Cover Web Push readiness copy and no active delivery claims.                                                               | \~70       |
| `docs/api/README_api.md`                                        | Document usage refresh, notification readiness, preference, and subscribe/unsubscribe boundaries.                          | \~80       |
| `apps/server/README_server.md`                                  | Document usage metrics manager and notification routing limits.                                                            | \~65       |
| `apps/web/README_web.md`                                        | Document metrics panel, local notification routing, mobile filters, and Web Push no-claim posture.                         | \~75       |
| `packages/protocol/README_protocol.md`                          | Document enriched command-center metrics and notification contracts.                                                       | \~45       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Operators can see task, hero, plan, queue, executor, attention, approval, review, provider, and cost metrics in the Orchestration Metrics tab.
* [ ] Metrics include duration, events, tool-use count, estimated tokens/cost, lines changed, failures, retries, throughput, stalled tasks, blocked age, review backlog, pending approvals age, latency, queue age, executor utilization, provider usage imports, and plan/hero/task rollups where source data exists.
* [ ] Attention summary shows compact counts, risk/severity distribution, age buckets, and mobile filters.
* [ ] Local notification routing handles approvals, questions, blocked tasks, failed tasks, and review gates with duplicate-trigger prevention.
* [ ] Web Push subscribe/unsubscribe reports ready only when consent and VAPID readiness are present; default posture remains disabled or unavailable without hosted push claims.

### Testing Requirements

* [ ] Protocol tests cover metric kinds, notification channels, subscription/readiness fields, routing categories, payload categories, and blocked raw fields.
* [ ] Server tests cover metric aggregation, provider usage import handling, usage routes, notification preferences, subscription validation, readiness states, WebSocket updates, duplicate triggers, and no raw echo.
* [ ] Web tests cover API clients, store normalization, metrics panel, attention header, mobile filters, local notification routing, hidden-tab delivery, readiness copy, and accessibility labels.

### Non-Functional Requirements

* [ ] Metrics and notification payloads are bounded, redacted, and metadata-only in broad views.
* [ ] No analytics capture, push delivery, hosted identity, remote access, or production-hosted validation claim is introduced.
* [ ] UI controls remain dense, responsive, and product-facing with diagnostics confined to tests, docs, or dev-only detail.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.
* [ ] Primary user-facing surfaces contain product-facing copy only.
* [ ] `npm --workspace packages/protocol run typecheck` passes.
* [ ] `npm --workspace apps/server run typecheck` passes.
* [ ] `npm --workspace apps/web run typecheck` passes.
* [ ] Focused Vitest suites pass before broad workspace validation.

***

## 8. Implementation Notes

### Working Assumptions

* Session 15 is the next executable session: the analysis script reports Phase 19 in progress, Sessions 01-14 complete, no active current session, and Session 15 as the earliest unfinished candidate.
* This is a cross-cutting monorepo session: the candidate stub lists `apps/server` and `apps/web`, the existing metric and notification contracts live in `packages/protocol`, and conventions require protocol-led cross-package changes.
* Web Push work is readiness-gated rather than active hosted delivery by default: `.env.local.example`, `docs/api/README_api.md`, `apps/web/README_web.md`, and `SECURITY-COMPLIANCE.md` keep push/VAPID as disabled, reserved, or no-claim unless consent, config, auth, audit, tests, and docs exist.
* Usage metrics can be derived without analytics capture: existing command-center manager state, hero metrics, mission data, session imports, mission artifact estimates, and web cost projection helpers already expose bounded operational data.

### Conflict Resolutions

* The session stub includes Web Push VAPID subscribe/unsubscribe, while security and docs currently say push delivery is no-claim. The chosen interpretation is to implement consent/config-gated readiness and subscription management, with disabled or unavailable defaults and no hosted delivery claim unless all gates are satisfied.
* The existing server exposes usage list support, validation, manager storage, and WebSocket usage events, but only `notification-readiness` has a POST route. The chosen interpretation is to add the missing usage mutation/refresh path because the protocol and manager already model usage records and Session 15 owns metrics.
* The session stub package metadata is `null`, while the text names `apps/server` and `apps/web`. The plan records `Package: null` because protocol contracts must change and the work spans multiple packages.

### Key Considerations

* Protocol must lead metric and notification shape changes before server/web implementation.
* Notification routing is a mutating, user-visible side effect and needs duplicate-trigger prevention, consent checks, and permission-denied/revoked handling.
* Metrics must remain operational command-center state, not analytics capture or hosted telemetry.
* Broad UI surfaces must not show raw prompts, command bodies, terminal output, provider payloads, tokens, absolute paths, replay buffers, exports, or subscription internals.

### Potential Challenges

* Metric aggregation can drift from source state: keep aggregation manager-owned, deterministic, and covered by fixture tests.
* Web Push can overclaim product capability: keep readiness states explicit, disabled by default, and copy tied to consent/config evidence.
* Hidden-tab notification tests can be flaky: keep delivery helper pure enough to inject service-worker registration and permission stubs.
* Header and mobile filters can crowd the existing Orchestration surface: use compact counts, stable dimensions, and responsive overflow rather than large cards.

### Relevant Considerations

* \[P03] **Real executors remain unimplemented by design**: notification routing cannot imply executor action or automatic approval.
* \[P03-packages/protocol] **Protocol leads cross-package work**: metric and notification vocabulary belongs in `packages/protocol` before server and web wiring.
* \[P03-apps/server] **Local server boundary must stay conservative**: new routes inherit loopback defaults, auth, rate limits, body caps, validation, and explicit unavailable behavior.
* \[P07] **Redaction is boundary-specific**: metric, notification, subscription, WebSocket, and UI payloads each need bounded metadata and blocked raw fields.
* \[P07] **Hosted services ship as disabled-default guardrails only**: Web Push, VAPID, hosted diagnostics, analytics, and remote access cannot become active claims without scoped evidence.
* \[P18-apps/server] **Manager-owned persistence and snapshot emission**: aggregation and readiness updates should stay behind server managers and emit canonical snapshots.
* \[P18-apps/web] **Pure normalization before store mutation**: malformed usage or notification frames should be rejected before Zustand state changes.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Duplicate local or push notification triggers for the same attention item.
* Push/VAPID readiness copy being mistaken for active hosted push delivery.
* Aggregated metrics leaking raw prompts, paths, terminal output, provider payloads, or subscription data.
* Metrics refreshes or hidden-tab routing leaving stale, in-flight, error, offline, or permission-revoked states unclear.

***

## 9. Testing Strategy

### Unit Tests

* Protocol parser tests for metric kinds, rollup targets, notification channels, routing categories, subscription statuses, readiness requirements, and blocked raw fields.
* Server manager tests for deterministic aggregation across plans, tasks, attention, permissions, executions, reviews, channels, provider usage imports, queue age, blocked age, latency, and utilization.
* Server notification helper tests for local preference state, VAPID readiness, subscription validation, payload categories, consent, idempotency, and raw-field rejection.
* Web helper tests for metric view models, cost projection labels, attention risk/severity buckets, mobile filters, readiness cards, and notification routing dedupe.

### Integration Tests

* Server route tests for `POST /command-center/usage`, metrics refresh, `GET /command-center/usage`, notification readiness, preferences, subscribe, unsubscribe, duplicate triggers, and WebSocket usage updates.
* Web API tests for metrics refresh and notification routes with timeout, offline, invalid response, validation failure, and duplicate conflict mapping.
* Component tests for Metrics tab loading, empty, error, offline, unavailable, disabled, ready, denied, revoked, hidden-tab, and mobile filter states.

### Runtime Verification

* Start the local server on a test port and seed command-center plans, tasks, attention, permissions, executions, review gates, and notification readiness records.
* Refresh usage metrics and verify bounded metric records plus `command_center_usage_update` frames.
* Toggle local notifications in the web surface and verify only approved categories route through local OS notification helpers.
* Verify Web Push subscribe/unsubscribe returns unavailable or disabled without configured VAPID and consent, with no push delivery claim.

### Edge Cases

* No source records for a metric family.
* Negative, `NaN`, future, stale, malformed, or unbounded metric values.
* Attention item resolved before notification delivery.
* Duplicate attention update while local notification is in flight.
* Browser permission denied, default, revoked, unsupported, or constructor failure.
* Hidden tab with service worker registration unavailable.
* Subscription endpoint with absolute paths, secrets, raw payloads, oversized keys, or missing consent.
* VAPID public key present without private key or subject.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase19-session04-campaign-workbench`, `phase19-session05-attention-and-permissions`, `phase19-session06-executor-registry`, `phase19-session09-heroes-and-lineage`, `phase19-session10-mission-artifacts`, `phase19-session14-channels-and-scope`.
* Depended by: `phase19-session16-ergonomics-and-documentation`.

***

## 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-session15-metrics-and-notifications/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.
