> 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/phase03-session06-cli-diagnostics-and-recovery-controls/spec.md).

# Session Specification

**Session ID**: `phase03-session06-cli-diagnostics-and-recovery-controls` **Phase**: 03 - Agent Orchestration **Status**: Not Started **Created**: 2026-05-29 **Package**: Cross-cutting (`apps/cli`, `apps/hooks`, `apps/server`) **Package Stack**: Node 20, JavaScript CLI and hooks, TypeScript Express/WebSocket server, npm workspaces, Vitest

***

## 1. Session Overview

This session makes Phase 03 local orchestration diagnosable from the command line and hook runtime. Sessions 02 through 05 already define and expose queue, template, lineage, mission graph, guarded-action, and web cockpit behavior; Session 06 adds compact CLI and hook diagnostics so operators can understand local orchestration health without opening raw state files or browser tools.

The work updates `factionos status` and `factionos doctor` to report queue, template, mission graph, guarded-action, listener, hook, and spool posture. It also adds a small local server diagnostics snapshot, improves hook/listener logs with safe summaries, and introduces narrow recovery controls for stale local diagnostic state. These controls must not become unified erasure, hosted recovery, remote execution, or broad local file deletion.

The session is next because Session 05 is already implemented and validated, and Session 06 is the next remaining Phase 03 session before orchestration closeout. It prepares Session 07 by giving validation and documentation a clear local diagnostic surface to verify.

***

## 2. Objectives

1. Add compact CLI diagnostics for Phase 03 queue, template, mission graph, guarded-action, listener, hook, and spool state.
2. Add a local server diagnostics snapshot that reports orchestration counts and availability without raw prompts, commands, paths, tokens, terminal output, or state file contents.
3. Add explicit, narrow recovery controls for stale listener PID files and malformed spool entries without deleting unrelated archives, memory, browser settings, workspace files, or session exports.
4. Improve hook and listener diagnostic logs for orchestration events while preserving silent, timeout-bounded hook behavior.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase03-session02-task-queue-and-agent-template-contracts` - provides local queue and template contracts.
* [x] `phase03-session03-subagent-lineage-and-mission-graph-runtime` - provides typed lineage and mission graph runtime state.
* [x] `phase03-session04-guarded-local-action-runtime` - provides guarded-action routes, manager state, and decision contracts.
* [x] `phase03-session05-web-orchestration-cockpit-controls` - provides web cockpit expectations and compact hydration frame behavior.

### Required Tools/Knowledge

* Node 20+, npm workspaces, JavaScript ESM, TypeScript, Express, WebSocket, and Vitest.
* Current CLI lifecycle, status, doctor, local file inspection, and guarded-action helper patterns in `apps/cli`.
* Current hook quiet-failure, spool, listener PID, and JSON-line logging behavior in `apps/hooks`.
* Current server orchestration managers, routes, auth middleware, and WebSocket hydration behavior in `apps/server`.

### Environment Requirements

* No hosted service, analytics, Cloudflare, Anthropic, Discord, Telegram, generic webhook, Supabase, Docker, or database credential is required.
* The local server remains loopback-first and inherits existing auth, CORS, Origin, rate-limit, and body-size defaults.
* Historical `EXAMPLES/` content remains evidence only and must not be copied into diagnostics, fixtures, docs, or logs.

***

## 4. Scope

### In Scope (MVP)

* Operators can run `factionos status` and see compact local orchestration posture - include queue counts, template availability, mission graph counts, guarded-action counts, server reachability, listener PID state, and spool posture.
* Operators can run `factionos doctor` and see actionable local orchestration diagnostics - include healthy, missing, stale, malformed, server-unavailable, listener-unavailable, and recovery-available states.
* Operators can explicitly run a recovery mode for stale listener PID files and malformed spool entries - require an explicit flag, make the operation idempotent, and report only sanitized counts and file categories.
* The server exposes a compact diagnostics snapshot for CLI consumption - include manager counts and availability only, enforce auth at the existing boundary, and avoid raw queue titles, proposal rationale, prompts, command bodies, terminal output, file contents, tokens, transcript paths, and broad absolute paths.
* Hook handlers and the listener record safe orchestration diagnostics - include handler names, event families, status codes, durations, counts, sanitized IDs, and malformed-state summaries only.
* Tests cover malformed state, stale state, missing server, unavailable listener, auth forwarding, quiet hook behavior, recovery idempotency, and privacy boundaries.

### Out of Scope (Deferred)

* Unified erasure across archives, memory findings, browser settings, replay buffers, local session exports, workspace state, or all `~/.factionos` data - *Reason: release hardening owns trusted erase/reset workflow.*
* Hosted account, remote device, Worker room, analytics, public replay, inbound chat, or webhook command diagnostics - *Reason: Phase 03 remains local-only and later phases own those trust boundaries.*
* Executing queued tasks, file changes, git operations, terminal commands, Docker/container work, or remote actions - *Reason: diagnostics and recovery must not become hidden execution.*
* Broad raw state export or debug dump commands - *Reason: local diagnostics must summarize health without exposing sensitive payloads.*
* Public demo changes - *Reason: Session 06 targets local CLI, hooks, and server diagnostics only.*

***

## 5. Technical Approach

### Architecture

Keep server state ownership in the existing managers. Add a small diagnostics builder that reads compact counts from `TaskQueueManager`, `AgentTemplateManager`, `MissionGraphManager`, and `GuardedActionManager`, then returns a response suitable for CLI display. The route should be read-only and mounted behind the existing local auth, CORS, rate-limit, and body-size middleware.

Keep CLI presentation helper-owned. Add a CLI diagnostics helper that talks only to loopback FactionOS server URLs, forwards bearer auth when configured, uses bounded timeouts, maps unavailable or invalid responses to compact states, and never prints raw response bodies. `status` should remain a quick snapshot; `doctor` should provide deeper checks and an explicit recovery mode.

Keep local recovery narrow. Add local file helpers that identify stale listener PID files and malformed spool JSON files, then remove only those approved diagnostic artifacts when the user passes an explicit recovery flag. Recovery must not touch settings, lifecycle, project-root, archives, memory, sessions, browser storage, or workspace files.

Keep hooks quiet. Improve `hooks.log` and listener logs with safe event-family, status, duration, count, and sanitized ID summaries while preserving zero stdout/stderr in normal hook paths and bounded POST/listener behavior.

### Design Patterns

* Compact diagnostics snapshot: report counts, states, and availability instead of raw manager payloads.
* Boundary-owned sanitization: route all CLI and hook display/log text through existing or new sanitizers.
* Explicit recovery flag: no local deletion unless the operator intentionally requests recovery.
* Idempotent recovery: repeated recovery runs produce stable results and do not fail on already-removed stale artifacts.
* Existing middleware inheritance: mount server diagnostics where auth, CORS, Origin, rate-limit, and body-size defaults already apply.

### Technology Stack

* JavaScript ESM and Node built-ins in `apps/cli` and `apps/hooks`.
* TypeScript, Express, and `ws` in `apps/server`.
* Vitest for CLI, hooks, and server tests.
* Biome for formatting and linting.

***

## 6. Deliverables

### Files to Create

| File                                                 | Purpose                                                                                                   | Est. Lines |
| ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/server/src/lib/orchestrationDiagnostics.ts`    | Compact server-side diagnostics snapshot builder for queue, templates, mission graph, and guarded actions | \~140      |
| `apps/server/src/routes/diagnostics.ts`              | Read-only local diagnostics route for CLI consumption                                                     | \~80       |
| `apps/cli/src/lib/orchestrationDiagnostics.js`       | CLI HTTP and local-state diagnostic helpers with bounded errors and sanitized display models              | \~220      |
| `apps/cli/tests/orchestrationDiagnostics.test.js`    | CLI diagnostics, auth forwarding, unavailable server, and recovery tests                                  | \~240      |
| `apps/server/tests/orchestrationDiagnostics.test.ts` | Server diagnostics route and privacy-boundary tests                                                       | \~180      |
| `apps/hooks/tests/orchestrationDiagnostics.test.js`  | Hook/listener log summary and privacy-boundary tests                                                      | \~180      |

### Files to Modify

| File                                                                                                 | Changes                                                                             | Est. Lines |
| ---------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | ---------- |
| `apps/server/src/server.ts`                                                                          | Mount diagnostics route with existing manager dependencies                          | \~25       |
| `apps/cli/src/commands/status.js`                                                                    | Print compact orchestration diagnostics and unavailable states                      | \~120      |
| `apps/cli/src/commands/doctor.js`                                                                    | Add orchestration health checks and explicit recovery flag handling                 | \~180      |
| `apps/cli/src/index.js`                                                                              | Document recovery flag in help output if added to doctor                            | \~20       |
| `apps/cli/src/lib/localFiles.js`                                                                     | Add approved stale listener PID and malformed spool recovery primitives             | \~140      |
| `apps/hooks/src/_lib.js`                                                                             | Add safe orchestration diagnostic summaries for hook log entries                    | \~100      |
| `apps/hooks/src/ws-listener.js`                                                                      | Improve listener spool, reconnect, and malformed-frame diagnostics with safe counts | \~100      |
| `apps/cli/README_cli.md`                                                                             | Document diagnostics output and recovery boundaries                                 | \~80       |
| `apps/hooks/README_hooks.md`                                                                         | Document hook/listener diagnostic summaries and privacy limits                      | \~60       |
| `apps/server/README_server.md`                                                                       | Document local diagnostics snapshot behavior                                        | \~45       |
| `docs/api/README_api.md`                                                                             | Add concise diagnostics route and Phase 03 CLI diagnostics boundary                 | \~60       |
| `.spec_system/specs/phase03-session06-cli-diagnostics-and-recovery-controls/implementation-notes.md` | Implementation log and validation notes                                             | \~120      |
| `.spec_system/specs/phase03-session06-cli-diagnostics-and-recovery-controls/security-compliance.md`  | Session privacy, security, and GDPR posture                                         | \~100      |

***

## 7. Success Criteria

### Functional Requirements

* [ ] `factionos status` reports server orchestration posture with compact queue, template, mission graph, guarded-action, listener, and spool summaries.
* [ ] `factionos doctor` reports healthy, missing, stale, malformed, server-unavailable, listener-unavailable, and recovery-available states without crashing.
* [ ] The diagnostics route returns manager counts and availability only, and does not echo raw prompts, commands, paths, tokens, terminal output, transcript values, file contents, or raw state files.
* [ ] Recovery mode removes only stale listener PID files and malformed spool files, is explicit, is idempotent, and does not touch unrelated local state.
* [ ] Hook and listener diagnostics remain silent on stdout/stderr and write only sanitized JSON-line summaries.

### Testing Requirements

* [ ] Focused CLI diagnostics and recovery tests pass.
* [ ] Focused hook and listener diagnostics tests pass.
* [ ] Focused server diagnostics route tests pass.
* [ ] Existing CLI lifecycle, hook runtime, listener runtime, server orchestration, and guarded-action tests remain green.

### Non-Functional Requirements

* [ ] Diagnostics remain local-first and work without hosted services, provider keys, analytics, Docker, or Cloudflare.
* [ ] CLI and hook output avoid raw prompts, command bodies, terminal output, file contents, tokens, broad absolute paths, transcript paths, raw spool payloads, and raw state file contents.
* [ ] Server diagnostics inherit existing auth, CORS, Origin, rate-limit, and body-size protections.
* [ ] Recovery controls are narrow, auditable, and safe to repeat.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.

***

## 8. Implementation Notes

### Key Considerations

* Keep `status` concise and `doctor` actionable. `status` should show the operator what is happening now; `doctor` should explain what is unhealthy and whether explicit recovery is available.
* The diagnostics route should expose counts and availability, not debug dumps. If a future workflow needs raw manager state, it must define a separate privacy review and route contract.
* Recovery mode should be opt-in and narrow. Removing stale PID files and malformed spool files is acceptable; deleting archives, memory, settings, lifecycle state, project roots, session exports, or browser state is not.
* Hook handlers must remain silent and timeout-bounded even when diagnostics are added.

### Potential Challenges

* Mission graph has WebSocket hydration but no current public REST route: use a compact diagnostics snapshot instead of broad graph detail.
* CLI server probes can fail for normal local reasons: map timeouts, auth failures, invalid JSON, and connection errors to explicit unavailable states.
* Malformed spool entries may contain sensitive values: count and remove by category without printing contents.
* Recovery must be idempotent across concurrent or repeated runs: tolerate already-deleted files and stale process checks.

### Relevant Considerations

* \[P01] **Unified erasure still missing**: This session must not pretend recovery is trusted erase/reset.
* \[P01-apps/cli+apps/hooks] **Lifecycle state is local and file-based**: Keep crash recovery and stale-state tests in CLI and hook work.
* \[P01] **Redaction is boundary-specific**: Diagnostics must keep prompts, paths, commands, transcripts, exports, replay, and adapter privacy boundaries intact.
* \[P01-apps/server] **Local server boundary must stay conservative**: Server diagnostics must inherit local auth, Origin/CORS, rate limits, validation, and explicit failure behavior.
* \[P01] **Local-first boundary is architectural**: Diagnostics should degrade cleanly when the server, listener, hooks, local state, hosted services, and remote relays are unavailable.
* \[P02] **Honest stub wording matters for deferred surfaces**: CLI and docs must not imply hosted queues, Worker federation, inbound commands, public sharing, analytics, Docker isolation, or remote execution.

### Behavioral Quality Focus

Checklist active: Yes

Top behavioral risks for this session:

* Recovery controls deleting too much local state or running without explicit operator intent.
* CLI diagnostics leaking raw hook payloads, prompts, command bodies, paths, tokens, terminal output, or malformed spool contents.
* Server diagnostics route accidentally exposing raw manager entries instead of compact counts.
* Hook diagnostics breaking quiet handler behavior or adding unbounded work to hook execution.

***

## 9. Testing Strategy

### Unit Tests

* Test CLI diagnostics helper timeout, auth header, invalid JSON, non-loopback URL, unavailable server, compact display model, and sensitive text redaction.
* Test local recovery helpers for stale listener PID detection, malformed spool file detection, idempotent removal, and non-deletion of settings, lifecycle, archives, memory, sessions, and valid spool files.
* Test hook diagnostic summary sanitization for prompts, commands, paths, tokens, transcript-like values, and object payloads.

### Integration Tests

* Test server diagnostics route against live `createFactionOsServer` handles with empty, populated, expired, and unavailable orchestration state.
* Test `factionos status` and `factionos doctor` captured output with fake local server responses and fixture local state.
* Test listener spool pump and malformed-frame logs preserve safe counts and do not include raw payload contents.

### Manual Testing

* Run `factionos status` with server online and offline.
* Run `factionos doctor` with valid state, stale listener PID files, malformed spool entries, and auth-protected server settings.
* Run explicit recovery mode twice and verify the second run is clean and no unrelated local state is removed.

### Edge Cases

* Missing `~/.factionos` directory.
* Malformed `settings.json`, `lifecycle.json`, listener PID files, and spool entries.
* Server unreachable, auth required, invalid JSON response, or diagnostics route unavailable.
* Queue, template, mission graph, and guarded-action managers empty or at capacity.
* Expired guarded actions when diagnostics are requested.
* Hook logs with sensitive text fields and unknown object payloads.

***

## 10. Dependencies

### External Libraries

* Node 20 built-ins: `fs`, `path`, `http`, `https`, `net`, `os`, and timers.
* Express 4 in `apps/server`.
* Vitest 4.1.7 for focused tests.

### Other Sessions

* **Depends on**: `phase03-session02-task-queue-and-agent-template-contracts`, `phase03-session03-subagent-lineage-and-mission-graph-runtime`, `phase03-session04-guarded-local-action-runtime`, `phase03-session05-web-orchestration-cockpit-controls`.
* **Depended by**: `phase03-session07-orchestration-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/phase03-session06-cli-diagnostics-and-recovery-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.
