> 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/phase20-session02-queue-terminal-execution/spec.md).

# Session Specification

**Session ID**: `phase20-session02-queue-terminal-execution` **Phase**: 20 - Orchestration Actionability Execution **Status**: Not Started **Created**: 2026-06-28 **Package**: null **Package Stack**: TypeScript across `packages/protocol`, `apps/server`, and `apps/web`; JavaScript for compact CLI diagnostics

***

## 1. Session Overview

This session delivers the first real queue execution slice: a local queue task can carry a terminal executable payload, dispatch through the server, run via the existing terminal runtime, record a command-center execution run, and show the result in the Command Center without leaking raw command text or terminal output into broad rows.

It is next because Session 01 made current metadata-only actions truthful. The Phase 20 PRD then names terminal queue execution as the first vertical actionability slice, and the repo already has the direct terminal runtime, terminal execution attachments, and command-center execution update event path needed to connect queue dispatch to real local execution.

The session keeps the product boundary narrow. Terminal command text may be accepted as a scoped executable payload and used by the coordinator, but broad task queue events, queue rows, run history summaries, diagnostics, exports, notifications, and docs must show only safe labels, states, result summaries, and links to scoped terminal detail.

***

## 2. Objectives

1. Add protocol-owned terminal executable queue request types, safe queue execution summaries, and mutation response links.
2. Add a server `TaskExecutionCoordinator` that dispatches terminal queue entries through `TerminalSessionManager` and `OrchestrationCommandCenterManager`.
3. Update queue routes so terminal dispatch emits both `task_queue_update` and `command_center_execution_update`, while metadata-only tracking remains truthfully named.
4. Update the Command Center queue UI, terminal drawer links, diagnostics, docs, and focused tests for success, unavailable, timeout, kill, and duplicate dispatch behavior.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase20-session01-truthful-capability-baseline` - Provides truthful record-only labels for metadata-only queue and campaign controls.
* [x] `phase19-session12-terminal-and-containers` - Provides `TerminalSessionManager`, terminal routes, terminal attachments, and scoped terminal UI.
* [x] `phase19-session06-executor-registry` - Provides command-center capability and execution-run vocabulary.
* [x] `phase19-session16-ergonomics-and-documentation` - Provides current Command Center docs, shortcuts, cross-links, and browser evidence baseline.

### Required Tools Or Knowledge

* Node 26.2.0+ and npm 11.16.0 from `.spec_system/CONVENTIONS.md`.
* Vitest for protocol, server, web, and CLI unit tests.
* Playwright for browser coverage under `tests/e2e/orchestration-command-center.e2e.ts`.
* Existing terminal runtime contracts in `packages/protocol/src/orchestrationCommandCenter.ts`.

### Environment Requirements

* No external credentials, hosted services, provider transfer, Docker, or live cloud services are required.
* Automated server tests should use fake PTY adapters; implementation must still preserve truthful `pty_unavailable` behavior for normal installs.
* Work stays local to the monorepo and all edited files must remain ASCII with Unix LF line endings.

***

## 4. Scope

### In Scope (MVP)

* Operators can create a queue task with a terminal executable payload - store a private executable command and expose only safe terminal summary metadata.
* Operators can preview or dispatch a terminal queue entry - route dispatch through a coordinator with duplicate-trigger prevention while in-flight.
* Operators see queue rows update through queued, executing, completed, failed, and unavailable result states - show safe result summaries, execution links, and terminal drawer links with explicit loading, empty, error, and offline states.
* Operators can recover from `pty_unavailable`, timeout, killed running command, and duplicate dispatch - return truthful queue and execution states with retry enabled where appropriate.
* Maintainers get protocol, server, web, CLI, browser, and docs evidence - prove `task_queue_update` and `command_center_execution_update` are emitted without raw command text or terminal output in broad payloads.

### Out Of Scope (Deferred)

* Git queue execution - Reason: owned by Phase 20 Session 03 after the terminal execution contract is proven.
* Campaign executable dispatch and DAG recovery - Reason: owned by Phase 20 Sessions 04 and 05 after queue execution exists.
* File mutation and file executor integration - Reason: owned by Phase 20 Sessions 06 and 07.
* Managed agent lifecycle control - Reason: owned by Phase 20 Session 08.
* Container queue dispatch, remote execution, Worker command bridges, hosted execution, and trusted inbound channel execution - Reason: each requires its own threat model, authorization, audit, redaction, recovery, tests, and docs.
* Broad display of terminal command text or output - Reason: command text and bounded output belong only in scoped executable payload handling and selected terminal session detail.

***

## 5. Technical Approach

### Architecture

Start in `packages/protocol/src/taskQueue.ts` with a minimal terminal executable contract. The public queue entry should expose a safe summary such as executor family, command label, execution run id, terminal session id, result status, result summary, unavailable reason, and failure code. The raw terminal command belongs in a scoped executable payload accepted by create, preview, update, and dispatch handling; it must not be emitted in `TaskQueueEventEntry` or rendered in broad queue rows.

Add `apps/server/src/managers/taskExecutionCoordinator.ts` as the server-owned boundary between queue records, `TerminalSessionManager`, and `OrchestrationCommandCenterManager`. The coordinator should resolve the queue entry, enforce terminal payload support, probe PTY readiness, create or update a `CommandCenterExecutionRun` with target `queue_item`, call `TerminalSessionManager.runAndWait()` for one-shot dispatch or preserve a running terminal attachment when the supported path is still active, update queue state and safe result metadata, and return idempotent duplicate responses for repeated dispatch keys.

Update `apps/server/src/routes/orchestration.ts` so `/task-queue/:id/dispatch` uses the coordinator. Preserve the old state-only transition behind a truthful `/task-queue/:id/start-tracking` route or equivalent server-visible naming, and keep command-center execution event emission next to queue event emission. Wire the coordinator from `apps/server/src/server.ts` using the existing terminal, command-center, task-queue, and broadcaster instances.

On the web, extend `apps/web/src/lib/orchestrationApi.ts`, `apps/web/src/lib/orchestrationUi.ts`, `apps/web/src/lib/commandCenterUi.ts`, and `apps/web/src/components/orchestration/QueueWorkbench.tsx` to create terminal executable queue entries, show terminal execution status and safe links, retry failed or unavailable terminal entries, and open the terminal runtime drawer to the linked session. The terminal output window remains owned by `TerminalRuntimeDrawer`.

### Design Patterns

* Protocol-first executable contract: shared queue request, response, and event shapes land in `packages/protocol` before server and web consumers.
* Manager-owned runtime boundary: task execution belongs in a coordinator and managers, not route-local state patches.
* Broad-summary/scoped-detail split: queue rows and events show safe labels and result metadata only; scoped terminal detail owns bounded output.
* Idempotent mutation keys: reuse queue and terminal idempotency keys so duplicate dispatches return the existing execution run instead of starting a second command.
* Product-facing UI states: normal cockpit surfaces show local execution, failed, unavailable, retry, and terminal-link states without debug copy.

***

## 6. Deliverables

### Files To Create

| File                                                   | Purpose                                                                                                                   | Est. Lines |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/server/src/managers/taskExecutionCoordinator.ts` | Coordinate terminal queue dispatch, idempotency, queue state, terminal sessions, execution runs, and safe event metadata. | \~260      |
| `apps/server/tests/taskExecutionCoordinator.test.ts`   | Focused fake-PTY tests for terminal queue success, unavailable, timeout, kill/result propagation, and duplicate dispatch. | \~220      |

### Files To Modify

| File                                                           | Changes                                                                                                                                                                  | Est. Lines |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- |
| `packages/protocol/src/taskQueue.ts`                           | Add terminal executable request payloads, safe queue execution summary fields, parser helpers, and mutation response links.                                              | \~180      |
| `packages/protocol/src/events.ts`                              | Ensure task queue and execution update event typing stays compact and excludes raw executable payload fields.                                                            | \~20       |
| `packages/protocol/tests/orchestration.test.ts`                | Cover queue executable payload types, safe event shape, and raw command/output exclusion.                                                                                | \~120      |
| `packages/protocol/tests/orchestrationCommandCenter.test.ts`   | Cover queue-targeted terminal execution runs and safe terminal attachments.                                                                                              | \~60       |
| `apps/server/src/lib/orchestrationValidation.ts`               | Validate terminal executable create, preview, update, and dispatch inputs with schema-validated input and explicit error mapping.                                        | \~140      |
| `apps/server/src/managers/taskQueue.ts`                        | Store safe queue execution summaries and private executable payload references with idempotency protection and deterministic ordering.                                   | \~140      |
| `apps/server/src/routes/orchestration.ts`                      | Route terminal dispatch through the coordinator, add truthful start-tracking compatibility, and emit queue plus execution events.                                        | \~140      |
| `apps/server/src/server.ts`                                    | Instantiate and inject `TaskExecutionCoordinator` with terminal, queue, command-center, and broadcaster dependencies.                                                    | \~30       |
| `apps/server/tests/orchestration.test.ts`                      | Cover route-level terminal dispatch, start-tracking compatibility, validation failures, privacy, and dual event emission.                                                | \~180      |
| `apps/server/tests/orchestrationDiagnostics.test.ts`           | Cover terminal execution counts and compact readiness diagnostics when queue dispatch runs or is unavailable.                                                            | \~70       |
| `apps/web/src/lib/orchestrationApi.ts`                         | Add terminal executable create/dispatch inputs, response parsing, execution links, and refresh behavior.                                                                 | \~140      |
| `apps/web/src/lib/orchestrationUi.ts`                          | Build safe queue execution and terminal-link view models without command text or output.                                                                                 | \~100      |
| `apps/web/src/lib/commandCenterUi.ts`                          | Update queue action labels and availability so terminal payloads use execution verbs while metadata-only rows keep tracking labels.                                      | \~80       |
| `apps/web/src/components/orchestration/QueueWorkbench.tsx`     | Add terminal task creation controls, result summaries, retry, and terminal drawer links with accessibility labels, focus support, and duplicate-trigger disabled states. | \~180      |
| `apps/web/src/components/orchestration/CommandCenterPanes.tsx` | Pass terminal drawer selection/open handlers from queue rows to the terminal runtime drawer.                                                                             | \~40       |
| `apps/web/src/store/useGameStore.ts`                           | Merge safe execution links from queue and command-center events and revalidate selected terminal session links on refresh.                                               | \~80       |
| `apps/web/tests/orchestrationApi.test.ts`                      | Cover terminal executable request/response parsing and raw command privacy in broad responses.                                                                           | \~90       |
| `apps/web/tests/orchestrationUi.test.ts`                       | Cover queue terminal result labels, retry copy, and terminal-link view models.                                                                                           | \~80       |
| `apps/web/tests/CommandCenterPanes.test.tsx`                   | Cover integrated queue terminal controls, result summary, retry, and drawer link rendering.                                                                              | \~110      |
| `apps/web/tests/TerminalRuntimeDrawer.test.tsx`                | Cover opening a linked queue terminal session and keeping output scoped to the drawer.                                                                                   | \~60       |
| `apps/web/tests/commandCenterStore.test.ts`                    | Cover task queue plus execution WebSocket reconciliation and in-flight key cleanup.                                                                                      | \~80       |
| `apps/cli/src/lib/orchestrationDiagnostics.js`                 | Add compact terminal queue/execution readiness summary while preserving redaction.                                                                                       | \~70       |
| `apps/cli/tests/orchestrationDiagnostics.test.js`              | Cover compact terminal diagnostics and privacy redaction for command text and output.                                                                                    | \~80       |
| `tests/e2e/orchestration-command-center.e2e.ts`                | Add visible queue-to-terminal drawer flow with mocked local routes and browser guard assertions.                                                                         | \~120      |
| `docs/api/README_api.md`                                       | Document terminal executable queue routes, response fields, event privacy, and recovery states.                                                                          | \~60       |
| `docs/api/event-api-hook-contracts.md`                         | Document queue terminal dispatch event contract and raw-field exclusions.                                                                                                | \~50       |
| `apps/web/README_web.md`                                       | Update Command Center queue UX contract for terminal execution, retry, and scoped terminal detail.                                                                       | \~40       |
| `apps/cli/README_cli.md`                                       | Update doctor/status diagnostics notes for terminal queue readiness and privacy.                                                                                         | \~30       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Creating a terminal queue task stores a scoped executable command while broad queue rows and `task_queue_update` events expose only safe execution summary metadata.
* [ ] Dispatching a terminal queue task creates or reuses a `CommandCenterExecutionRun` targeted to the queue item, runs through `TerminalSessionManager`, updates the queue row, and emits both `task_queue_update` and `command_center_execution_update`.
* [ ] `pty_unavailable`, timeout, killed command, terminal failure, stale revision, and duplicate dispatch produce truthful queue and execution states with recoverable retry or existing-run responses.
* [ ] The Command Center queue UI shows executor family, execution state, safe result summary, retry, and terminal drawer links without broad command text or output.
* [ ] `factionos doctor` and compact diagnostics summarize terminal queue readiness/results without raw command text, terminal output, tokens, or broad absolute paths.

### Testing Requirements

* [ ] Protocol tests cover executable queue contracts, queue-targeted terminal execution runs, and raw-field rejection.
* [ ] Server tests cover coordinator success, unavailable, timeout, kill, duplicate dispatch, route validation, start-tracking compatibility, and dual event emission.
* [ ] Web tests cover API parsing, store reconciliation, UI labels, retry, terminal drawer links, and output scoping.
* [ ] Browser e2e proves the visible queue-to-terminal drawer flow.
* [ ] CLI diagnostics tests prove compact terminal queue summaries and redaction.

### Non-Functional Requirements

* [ ] Raw terminal command text and terminal output stay out of broad queue rows, WebSocket snapshots, run-history cards, diagnostics, exports, notifications, and docs examples.
* [ ] Terminal dispatch enforces idempotency, duplicate-trigger prevention, timeout handling, bounded output, and compensation on failure.
* [ ] Queue and execution updates use deterministic ordering, bounded payloads, and explicit error mapping.
* [ ] Product UI preserves keyboard, pointer, and screen-reader access for terminal queue actions and links.

### Quality Gates

* [ ] All files ASCII-encoded
* [ ] Unix LF line endings
* [ ] Code follows project conventions
* [ ] UI surfaces contain product-facing copy only
* [ ] `git diff --check` passes

***

## 8. Implementation Notes

### Working Assumptions

* Cross-package session scope: The analyzer returned `package: null`, while the Session 02 stub explicitly names `packages/protocol`, `apps/server`, and `apps/web`; CLI diagnostics and docs are directly affected by the same user outcome. Planning can proceed as `Package: null` because the work is intentionally cross-cutting and every task uses repo-root-relative paths.
* Existing terminal runtime is sufficient for the first vertical slice: `TerminalSessionManager` already supports `probe`, `preview`, `start`, `runAndWait`, `kill`, `restart`, idempotency, timeouts, bounded output, and safe terminal attachments. The session can connect queue dispatch to those APIs instead of adding a new terminal engine.
* Queue command text must be stored outside broad event entries: the Session 02 stub requires command text and output to stay in scoped detail views, so public queue summaries should carry labels and links while the executable payload remains route/coordinator scoped.

### Conflict Resolutions

* Session 01 changed queue dispatch copy to `Start tracking` because the route was metadata-only, while the Session 02 stub requires real terminal queue dispatch. The chosen interpretation is to make `Dispatch` truthful only for entries with a terminal executable payload and preserve metadata-only behavior under `start-tracking` or equivalent tracking wording.
* `docs/api/README_api.md` already describes direct terminal routes as shipped, while Phase 20 says queue terminal execution is not shipped yet. The chosen interpretation is that direct terminal execution remains shipped evidence, but queue-to-terminal orchestration becomes the new deliverable.

### Key Considerations

* Add or change shared contracts before server or web behavior.
* Keep result summaries compact and redacted; never expose raw command text or terminal output in broad events.
* Use fake PTY tests for reliable success, unavailable, timeout, and kill paths.
* Preserve old metadata-only queue behavior with truthful naming so existing workflows do not become false execution claims.

### Potential Challenges

* `TaskQueueManager` currently stores only public entry data; mitigate by introducing a safe public execution summary and private executable payload accessors for coordinator use.
* Terminal sessions can complete asynchronously; mitigate by updating queue and execution records when completion resolves and by testing both immediate and delayed PTY flows.
* Browser state can receive queue and execution events in either order; mitigate with store reconciliation tests that avoid blanking selected rows or leaving mutation keys stuck.
* CLI diagnostics historically expected isolation executors to remain unavailable; mitigate by keeping diagnostics compact and family-scoped rather than claiming broad execution readiness.

### Relevant Considerations

* \[P19] **Executor claims are family-scoped**: Only terminal queue execution may become ready in this session; Git, file, container, remote, Worker, hosted, and managed-agent families remain no-claim or separate scopes.
* \[P19] **Scoped detail stays separate from broad rows**: Raw command bodies and terminal output belong only in selected terminal detail, not broad summaries.
* \[P03-packages/protocol] **Protocol leads cross-package work**: Queue, execution-run, event, REST, and WebSocket shapes must land in `packages/protocol` first.
* \[P19] **Command-center state is manager-owned**: Idempotency, revisions, cleanup, event emission, and bounded snapshots should stay in managers and the coordinator.
* \[P19-apps/server] **`node-pty` is optional**: PTY paths must fail closed with structured unavailable states when native support is missing.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Raw command text or terminal output could leak into queue rows, events, run history, diagnostics, docs, or tests.
* Duplicate dispatch or delayed completion could start multiple terminal sessions or leave queue and execution state inconsistent.
* Unavailable, timeout, killed, and failed terminal paths could strand queue rows in `in_progress` without retry guidance.

***

## 9. Testing Strategy

### Unit Tests

* Update `packages/protocol/tests/orchestration.test.ts` for executable queue contracts, safe public summaries, and event privacy.
* Add `apps/server/tests/taskExecutionCoordinator.test.ts` for fake-PTY coordinator success, unavailable, timeout, kill, and duplicate dispatch.
* Update `apps/web/tests/orchestrationUi.test.ts` and `apps/web/tests/orchestrationApi.test.ts` for terminal queue labels, links, responses, and raw-field rejection.
* Update `apps/cli/tests/orchestrationDiagnostics.test.js` for compact terminal queue diagnostics and redaction.

### Integration Tests

* Update `apps/server/tests/orchestration.test.ts` so `/task-queue/:id/dispatch` creates a terminal execution run, updates queue state, returns idempotent duplicate results, and emits both queue and command-center execution events.
* Update `apps/web/tests/CommandCenterPanes.test.tsx`, `apps/web/tests/TerminalRuntimeDrawer.test.tsx`, and `apps/web/tests/commandCenterStore.test.ts` for rendered queue terminal flow, retry, terminal drawer linking, and event reconciliation.

### Runtime Verification

* Run focused Vitest coverage for protocol, server, web, and CLI files touched by this slice.
* Run Playwright for `tests/e2e/orchestration-command-center.e2e.ts` after adding the queue-to-terminal drawer flow.
* Run package typechecks for `packages/protocol`, `apps/server`, and `apps/web`.
* Run `git diff --check` and ASCII/LF verification over changed spec, source, test, and doc files.

### Edge Cases

* Missing or malformed terminal executable payload returns a compact validation error and does not mutate queue state.
* `pty_unavailable` marks queue and execution unavailable with repair guidance instead of leaving a row active.
* Timeout marks queue and execution failed, preserves terminal attachment metadata, and enables retry.
* Killing a running command finalizes the linked terminal session and queue execution result without starting a second session.
* Duplicate dispatch with the same idempotency key returns the existing queue and execution run.
* WebSocket execution and queue events arriving in either order reconcile to one visible row and clear in-flight mutation state.

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase20-session01-truthful-capability-baseline`, Phase 19 terminal/container runtime, command-center execution runs, and Phase 20 PRD.
* Depended by: `phase20-session03-queue-git-execution`, `phase20-session04-campaign-executable-dispatch`, `phase20-session05-campaign-dag-recovery`, and `phase20-session11-release-evidence-and-event-privacy`.

***

## 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/phase20-session02-queue-terminal-execution/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.
