> 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/phases/phase_20/prd_phase_20.md).

# PRD\_phase\_20

## PRD Phase 20: Orchestration Actionability Execution

**Status**: Complete **Sessions**: 11 (initial estimate) **Estimated Duration**: 6-9 days

**Progress**: 11/11 sessions (100%)

***

### Overview

Phase 20 converts the command-center orchestration surface from metadata, proposal, preview, and audit scaffolding into truthful, executable product flows. The source-backed findings preserved in full as Appendix A identify the central defect: queue, campaign, template, file, hero lifecycle, and many guarded-action flows are labeled like actions while the backend often records local metadata instead of doing the requested work.

Proper delivery for this phase means every shipped feature proves the intended user outcome end to end in the product: create or approve the work, execute it through a real local runtime, observe a visible result, recover from supported failure modes, and pass automated protocol, server, web, and browser tests. Controls that cannot perform the action must be labeled as proposal-only, record-only, approved-not-executing, or unavailable before the user clicks.

***

### Progress Tracker

| Session | Name                               | Status   | Est. Tasks | Validated  |
| ------- | ---------------------------------- | -------- | ---------- | ---------- |
| 01      | Truthful Capability Baseline       | Complete | 18         | 2026-06-28 |
| 02      | Queue Terminal Execution           | Complete | 18         | 2026-06-28 |
| 03      | Queue Git Execution                | Complete | 20         | 2026-06-28 |
| 04      | Campaign Executable Dispatch       | Complete | 25         | 2026-06-28 |
| 05      | Campaign DAG Recovery              | Complete | 24         | 2026-06-28 |
| 06      | File Mutation Core                 | Complete | 22         | 2026-06-28 |
| 07      | File Executor Integration          | Complete | 24         | 2026-06-28 |
| 08      | Managed Agent Lifecycle Control    | Complete | 24         | 2026-06-28 |
| 09      | Container Dispatch Decision        | Complete | 23         | 2026-06-28 |
| 10      | Templates And Channel Intake       | Complete | 25         | 2026-06-29 |
| 11      | Release Evidence And Event Privacy | Complete | 25         | 2026-06-29 |

***

### Completed Sessions

* Session 01: Truthful Capability Baseline - Completed 2026-06-28. File executor readiness, guarded file approvals, queue/campaign controls, observed hero lifecycle controls, and docs now describe metadata-only behavior truthfully.
* Session 02: Queue Terminal Execution - Completed 2026-06-28. Terminal executable queue tasks now dispatch through the server coordinator, record safe execution summaries, link to scoped terminal detail, support retry and unavailable states, and pass protocol, server, web, CLI, browser, privacy, and documentation checks.
* Session 03: Queue Git Execution - Completed 2026-06-28. Git executable queue tasks now reuse the bounded Git workbench for status, stage, and unstage dispatch, return policy-blocked push as unavailable, record queue-targeted execution runs, expose compact result and recovery summaries, and pass protocol, server, web, CLI, browser, privacy, and documentation checks.
* Session 04: Campaign Executable Dispatch - Completed 2026-06-28. Approved campaign tasks with terminal or Git executable payloads now dispatch through the task execution coordinator, link campaign tasks to queue entries and execution-run evidence, keep planning-only work truthful, preserve partial-failure states, and pass protocol, server, web, browser, privacy, and documentation checks.
* Session 05: Campaign DAG Recovery - Completed 2026-06-28. Campaign dispatch now schedules executable tasks in dependency order, blocks dependents on failed, unavailable, unknown, cycle, or planning-only prerequisites, stages retry only for failed or unavailable executable work while preserving prior queue and execution history, and exposes product-facing graph recovery labels and links without raw command, output, diff, payload, token, or broad path leakage.
* Session 06: File Mutation Core - Completed 2026-06-28. Protocol-owned file mutation contracts and a server manager now preview, apply, audit, and roll back real workspace file changes with repo-relative path validation, stale-hash guards, backups, conflict checks, compact execution metadata, and redaction-safe documentation.
* Session 07: File Executor Integration - Completed 2026-06-28. Guarded file approvals, queue file tasks, and campaign file tasks now execute through the local file mutation manager with compact result metadata, rollback affordances, truthful capability probes, and redaction-safe protocol, server, web, browser, and documentation evidence.
* Session 08: Managed Agent Lifecycle Control - Completed 2026-06-28. Managed Hero/Lineage lifecycle controls now execute only for FactionOS-owned local process or PTY sessions, preserve observed-only records for hook-ingested sessions, expose compact execution evidence, and pass protocol, server, web, browser, privacy, and documentation checks.
* Session 09: Container Dispatch Decision - Completed 2026-06-28. Queue and campaign container tasks now use a bounded local isolated-spawn executor family with compact container run evidence, unavailable and retry handling, product-facing web controls, redaction-safe events, and protocol, server, web, browser, privacy, and documentation coverage.
* Session 10: Templates And Channel Intake - Completed 2026-06-29. Source-owned templates and local channel conversions now create reviewable executable queue tasks through bounded local executor metadata, keep webhook and remote intake proposal-first, preserve duplicate idempotency, and pass protocol, server, web, browser, privacy, and documentation checks.
* Session 11: Release Evidence And Event Privacy - Completed 2026-06-29. Phase 20 now has one release evidence ledger, release-level state semantics regressions, broad event/export/diagnostic/UI privacy coverage, browser evidence, and stable docs that separate shipped local execution from unavailable, proposal-only, approved-not-executing, and no-claim paths.

### Session 11 Release Evidence Inputs

Session 11 treats Sessions 01-10 as completed inputs and closes only the release-evidence and broad-event privacy layer. The validation files below are the evidence source for the release matrix; they do not broaden executor scope.

| Session | Release evidence available                                                                                                       | Validation source                                                                    |
| ------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| 01      | Truthful non-executing vocabulary for unavailable, proposal-only, approved-not-executing, record-only, and tracking states.      | `.spec_system/specs/phase20-session01-truthful-capability-baseline/validation.md`    |
| 02      | Terminal queue dispatch, scoped terminal detail links, retry, kill, timeout, and `pty_unavailable` behavior.                     | `.spec_system/specs/phase20-session02-queue-terminal-execution/validation.md`        |
| 03      | Git queue dispatch for status, stage, and unstage, with policy-blocked push unavailable and compact result summaries.            | `.spec_system/specs/phase20-session03-queue-git-execution/validation.md`             |
| 04      | Campaign executable dispatch through shared queue entries and execution runs, with planning-only and partial-failure boundaries. | `.spec_system/specs/phase20-session04-campaign-executable-dispatch/validation.md`    |
| 05      | Campaign DAG ordering, dependency blocking, retry for failed or unavailable executable work, and recovery labels.                | `.spec_system/specs/phase20-session05-campaign-dag-recovery/validation.md`           |
| 06      | File mutation preview, apply, audit, rollback, stale-hash, backup, and compact evidence behavior.                                | `.spec_system/specs/phase20-session06-file-mutation-core/validation.md`              |
| 07      | Guarded, queue, and campaign file execution through the local file mutation manager with rollback affordances.                   | `.spec_system/specs/phase20-session07-file-executor-integration/validation.md`       |
| 08      | Managed local process or PTY lifecycle controls, observed-only fallback, and unsupported provider action boundaries.             | `.spec_system/specs/phase20-session08-managed-agent-lifecycle-control/validation.md` |
| 09      | Bounded local isolated-spawn container dispatch with compact unavailable, failed, and executed evidence.                         | `.spec_system/specs/phase20-session09-container-dispatch-decision/validation.md`     |
| 10      | Source-owned template executable defaults and proposal-first channel conversion into local review or executable queue tasks.     | `.spec_system/specs/phase20-session10-templates-and-channel-intake/validation.md`    |

Candidate closeout gaps for Session 11:

* The release matrix must cite focused protocol, server, web, browser, and docs evidence in one artifact instead of relying on scattered validation prose.
* Queue and campaign state semantics need release-level regression coverage for completed, blocked, failed, unavailable, retry, and metadata-only paths.
* Broad rows, WebSocket updates, exports, diagnostics, docs examples, and UI rows need one final privacy pass for raw commands, command output, Git output, diffs, file contents, patch bodies, tokens, provider payloads, webhook bodies, secrets, and broad absolute paths.
* Release docs must keep hosted identity, trusted unified erasure, production-hosted validation, authorized Cloudflare deploy evidence, remote execution, Worker command bridges, and legal/privacy approval as no-claim unless separate evidence exists.

***

### Upcoming Sessions

* None. Phase 20 session work is complete.

***

### Objectives

1. Stop presenting metadata-only, proposal-only, preview-only, or audit-only paths as executable orchestration.
2. Add a shared executable task contract and coordinator so queue, campaign, template, channel, guarded-action, terminal, Git, file, and managed-agent flows converge on real execution semantics.
3. Prove terminal, Git, file mutation, campaign, and supported managed-agent paths through visible product results, recovery behavior, event privacy, and automated tests.

***

### Prerequisites

* Phase 19 completed as Orchestration Command Center Execution.
* Appendix A reviewed as the source-backed actionability requirements.
* Phase 19 local-first, permission, audit, redaction, unavailable-state, and no-claim boundaries remain active.
* No session may claim completion unless its executable acceptance path passes with real runtime behavior or truthful unavailable states.

***

### Planning Assumptions And Resolutions

#### Working Assumptions

* The 2026-06-28 findings now preserved as Appendix A are the authoritative source for Phase 20 scope: they are current, source-backed, include an explicit 11-session split, and were the source supplied to the phasebuild command.
* The 11-session split is kept intact even though it is larger than the usual phase guideline because the sessions are dependency-ordered vertical slices for one objective: converting orchestration-shaped controls into executable, observable, recoverable workflows.
* A feature is not shipped from this phase unless the product outcome is proven end to end with real execution or a truthful unavailable path, visible UI result, recovery behavior, and automated tests.
* Existing direct Git, terminal, and container runtime paths are useful executor islands, but they do not satisfy production orchestration until queue, campaign, template, channel, and guarded-action flows reach them through shared contracts and visible evidence.

#### Conflict Resolutions

* The master PRD and `state.json` ended at Phase 19 complete with no future phase row, while the supplied findings document clearly defines remaining source-backed work. The chosen interpretation is to create Phase 20 as the next sequential phase and update both master PRD and state tracking.
* Phase 19 remains complete for command-center contracts, managers, routes, workbenches, capability surfaces, documentation, and validation. The Phase 20 findings do not reopen Phase 19; they define the next product bar for turning those surfaces into full actionability.
* Phase 19 carry-forward and security notes keep executor claims family-scoped, while the findings document requires full orchestration outcomes. The chosen interpretation is that Phase 20 can expand execution claims only where a specific family has contracts, permission, audit, redaction, unavailable states, tests, docs, visible result, and recovery evidence.

***

### Technical Considerations

#### Architecture

Phase 20 should add one protocol-owned executable task contract and one server-side execution coordinator instead of putting orchestration decisions in route handlers. Queue entries, campaign tasks, templates, channel conversions, and guarded actions should all produce or reference the same executable payload and execution-run evidence.

Candidate ownership:

* `packages/protocol`: executable task types, payload variants, response shapes, event summaries, and redaction parsers.
* `apps/server`: `TaskExecutionCoordinator`, file mutation manager, managed agent session manager, queue/campaign route integration, capability probes, and scoped execution attachments.
* `apps/web`: capability-aware verbs, queue/campaign/file/terminal/hero result surfaces, recovery controls, and browser evidence.

#### Technologies

* TypeScript across `packages/protocol`, `apps/server`, and `apps/web`
* Zod protocol and request validation
* Existing `TerminalSessionManager`, `GitWorkbenchManager`, command-center execution runs, and guarded-action patterns
* New `FileMutationManager` for guarded workspace mutation and rollback
* Vitest for protocol, server, and web tests
* Playwright for Command Center create, dispatch, observe, and recover flows

#### Risks

* More scaffolding could be mistaken for progress: every implementation session must start from an executable acceptance path and cannot complete on DTOs, panels, or audit records alone.
* Sensitive developer data could leak through broad rows or events: command text, terminal output, raw Git output, diffs, file contents, patch bodies, tokens, absolute paths, provider payloads, and webhook bodies must stay in scoped local detail only.
* File mutation can damage workspaces: require repo-relative validation, symlink escape rejection, traversal rejection, expected hashes, backups, conflict checks, rollback, and tests before enabling file execution.
* Agent lifecycle controls can overclaim authority: only FactionOS-owned managed processes or PTY sessions may show control verbs; observed hook sessions remain record-only or unavailable.
* Container and remote execution claims can drift: container dispatch must be either proven as a queue/campaign executor family or explicitly unsupported.

#### Relevant Considerations

* \[P19] **Executor claims are family-scoped**: Phase 20 must not mark any executor family ready until that family has a proved execution path.
* \[P19] **Scoped detail stays separate from broad rows**: The new coordinator and UI must keep raw commands, output, diffs, content, and provider payloads out of broad summaries and WebSocket snapshots.
* \[P19] **Channel intake is proposal-first**: Webhook and remote channel input may create reviewable local tasks but must not execute automatically.
* \[P03-packages/protocol] **Protocol leads cross-package work**: Executable queue, campaign, guarded-action, event, and command-center shapes must land in `packages/protocol` before server and web wiring.
* \[P19] **Command-center state is manager-owned**: Idempotency, revisions, cleanup, event emission, and bounded snapshots should stay in managers.

***

### Success Criteria

Phase complete when:

* [x] All 11 sessions completed
* [x] Queue terminal execution proves create -> dispatch -> execute -> observe -> recover in the product and tests.
* [x] Queue and campaign Git execution runs allowlisted Git operations and shows bounded result and rollback guidance.
* [x] Campaign dispatch runs executable tasks in truthful states and dependency order, with retry and failure recovery.
* [x] File operations preview, mutate, audit, and roll back real workspace files through guarded paths.
* [x] Managed agent controls execute only for FactionOS-owned supported sessions; observed sessions use record-only wording.
* [x] Templates and channel intake create reviewable executable local tasks without auto-executing untrusted input.
* [x] UI action verbs are used only for actions that perform the action.
* [x] `executor_ready` appears only for executor families with end-to-end proof.
* [x] Broad events, rows, exports, diagnostics, examples, and docs do not leak scoped sensitive execution content.
* [x] Focused protocol, server, web, browser e2e, `npm test`, and `git diff --check` commands pass for all shipped paths.

***

### Dependencies

#### Depends On

* Phase 19: Orchestration Command Center Execution
* Appendix A of this PRD
* Existing command-center execution run, guarded-action, terminal, Git, file intent, campaign, queue, template, channel, and hero lifecycle surfaces

#### Enables

* A future production-orchestration release claim limited to executor families with complete end-to-end evidence.
* Future hosted, remote, Worker-bridged, or additional executor-family phases only after the same permission, audit, redaction, recovery, and validation bar is met.

***

### Appendix A: Complete Folded Actionability Findings

The original source document `docs/ongoing-projects/orchestration-actionability-findings.md` is preserved verbatim below. This appendix is the durable Phase 20 source of truth, so the external ongoing project note can be deleted without losing session split details, product requirements, source-backed findings, dependency baselines, architecture notes, executable task contract details, slice plans, test matrix, state/event rules, and delivery guardrails.

## Orchestration Actionability Findings

### Session Split Plan

#### Session 01: Truthful Capability Baseline

**Objective**: Stop presenting metadata-only paths as executable orchestration.

**Scope**:

* Downgrade file executor readiness until real file mutation exists.
* Update guarded file approval behavior so metadata-only approvals do not report executed.
* Split queue, campaign, file, and hero UI copy between real actions and record-only state changes.
* Update capability matrix wording for unavailable, proposal-only, approved-not-executing, and executor-ready states.

**Outputs**:

* Registry, route, and UI changes that prevent false `executor_ready`, `Dispatch`, `Execute`, `Apply`, `Edit`, and `Stop` claims.
* Server and web tests proving metadata-only controls are labeled and handled truthfully.

**Dependencies / Notes**:

* Must run before adding more execution paths so users do not see false production claims during later slices.
* Assumption: this session may disable or rename controls, but it does not add new runtime execution behavior.

**Acceptance Checks**:

* File executor probe cannot promote metadata-only file capabilities to `executor_ready`.
* Guarded file approval returns a non-executing state until a real adapter is available.
* Queue and campaign controls without executable payloads do not use dispatch/action verbs.
* Observed-only hero sessions show record-only controls, not process-control verbs.
* Relevant server and web tests pass.

#### Session 02: Queue Terminal Execution

**Objective**: Deliver `create -> dispatch -> execute -> observe -> recover` for queue tasks that run terminal commands.

**Scope**:

* Add the minimal protocol-owned executable task contract needed for terminal queue tasks, event redaction, and execution-run links.
* Add `TaskExecutionCoordinator` enough to preview and dispatch a terminal queue entry through `TerminalSessionManager`.
* Change queue dispatch to create a command-center execution run, run the terminal command, update queue state, and emit execution and queue events.
* Preserve the old metadata-only transition only behind truthful naming such as `Start tracking`.
* Surface terminal execution state, result summary, unavailable guidance, retry, kill, and terminal-drawer links in the Command Center UI.
* Update terminal dependency diagnostics and `factionos doctor` output for normal-install readiness.

**Outputs**:

* Terminal executable payload types, coordinator path, queue route behavior, UI result surface, and diagnostic updates.
* Protocol, server, web, and browser tests for successful execution and failure recovery.

**Dependencies / Notes**:

* Depends on Session 01.
* Use the existing `TerminalSessionManager`; add a dependency-free one-shot fallback only if the terminal slice proves it is needed.
* Terminal command text and output must stay in scoped detail views, not broad queue rows or WebSocket lists.

**Acceptance Checks**:

* A queue terminal task runs through dispatch, creates an execution run, records terminal attachment detail, completes or fails the queue row, and shows the result in the UI.
* `pty_unavailable`, timeout, running-command kill, and duplicate dispatch produce truthful states and recoverable results.
* Route tests prove both `task_queue_update` and `command_center_execution_update` events are emitted.
* Browser e2e proves the visible queue-to-terminal drawer flow.
* The focused protocol, server, web, e2e, and `git diff --check` commands for this slice pass.

#### Session 03: Queue Git Execution

**Objective**: Let an operator dispatch a queued Git action and see the real allowlisted Git result with rollback guidance.

**Scope**:

* Extend executable task payloads for Git using the existing `CommandCenterGitWorkbenchRequest`.
* Dispatch queue Git tasks through `TaskExecutionCoordinator` and `GitWorkbenchManager.preview()` / `execute()`.
* Attach execution run ids and compact Git result summaries to queue rows.
* Add recovery notes or inverse follow-up actions for supported stage, unstage, revert, and related operations.
* Keep policy-blocked push unavailable unless a deliberate policy change enables it.
* Optionally add `Create queue task` from the File/Git workbench when it helps the user orchestrate the same real Git action.

**Outputs**:

* Queue-to-Git protocol, server, and UI integration that reuses the bounded Git workbench execution path.
* Tests proving real argv construction, policy blocking, queue state updates, and visible results.

**Dependencies / Notes**:

* Depends on Sessions 01 and 02.
* Do not replace the existing bounded `GitWorkbenchManager` path just because Git libraries are installed.

**Acceptance Checks**:

* Queue dispatch for `status`, `stage`, and `unstage` creates execution runs and invokes the expected safe Git operations.
* Policy-blocked push returns unavailable and does not run Git.
* Failed Git commands surface bounded failure detail and rollback guidance without leaking broad raw output.
* Web tests prove Git results are visible from queue rows.
* The focused protocol, server, web, e2e, and `git diff --check` commands for this slice pass.

#### Session 04: Campaign Executable Dispatch

**Objective**: Make campaign dispatch run executable terminal and Git tasks while keeping planning-only tasks truthful.

**Scope**:

* Add executable payload support to campaign task inputs, drafts, responses, and queue records created from campaign tasks.
* Route campaign task dispatch through `TaskExecutionCoordinator` for supported terminal and Git payloads.
* Include execution run summaries in campaign dispatch responses.
* Mark tasks without executable payloads as planning-only, pending, or blocked instead of dispatched.
* Update campaign UI labels, rows, and task details to show executable readiness and execution links.

**Outputs**:

* Campaign task contract updates, server dispatch behavior, queue linkage, UI state, and tests.
* Replacement for old tests that asserted campaign dispatch only created queue records.

**Dependencies / Notes**:

* Depends on Sessions 02 and 03.
* Serial execution is acceptable here; dependency graph scheduling is handled in the next session.

**Acceptance Checks**:

* Campaign approve -> dispatch -> executable task run -> execution run -> task completed is proven for at least one terminal or Git task.
* Tasks without payloads are not reported as dispatched or executed.
* Partial failure does not falsely mark the whole campaign completed.
* Campaign and queue rows link to the same execution evidence.
* The focused protocol, server, web, e2e, and `git diff --check` commands for this slice pass.

#### Session 05: Campaign DAG Recovery

**Objective**: Execute campaign tasks in dependency order and give operators truthful retry and recovery controls.

**Scope**:

* Treat campaign tasks as a DAG and execute ready tasks serially in dependency order.
* Block dependent tasks until prerequisites finish successfully.
* Mark campaign state as in progress, completed, blocked, failed, or unavailable from actual task outcomes.
* Add retry for failed or unavailable executable tasks while preserving idempotency and previous run history.
* Add cancel or hold behavior for remaining queued tasks when a required dependency fails.
* Display campaign graph execution states, dependency blocks, retries, and execution detail links.

**Outputs**:

* Campaign scheduler behavior, retry/recovery behavior, state semantics, UI graph updates, and tests.

**Dependencies / Notes**:

* Depends on Session 04.
* Do not claim parallel campaign orchestration until concurrency is implemented and tested.

**Acceptance Checks**:

* Task B cannot run before required task A completes.
* A failed or unavailable task blocks dependents and prevents false campaign completion.
* Retry reruns only failed or unavailable executable tasks.
* Campaign state mirrors the actual execution and dependency state.
* Browser e2e proves the operator can inspect and retry a failed campaign task.

#### Session 06: File Mutation Core

**Objective**: Preview, apply, and roll back real workspace file mutations through guarded, audited paths.

**Scope**:

* Add protocol request and result types for read, write, edit, delete, move, and rename operations.
* Implement `FileMutationManager` with repo-relative path validation, symlink escape rejection, traversal rejection, NUL rejection, URL-like input rejection, and policy-based generated/ignored directory handling.
* Compute preflight hashes, require expected revision guards, create backups before mutations, mutate the filesystem, and record compact execution runs.
* Integrate active file intent conflict checks before mutating operations.
* Provide rollback for supported operations when a backup exists.

**Outputs**:

* Real file mutation manager, protocol types, backup/rollback metadata, conflict handling, and server tests.

**Dependencies / Notes**:

* Depends on Session 01.
* File contents and patch bodies must remain request-scoped or detail-scoped and must never appear in broad events, exports, diagnostics, or list rows.

**Acceptance Checks**:

* Temp-directory tests prove write, edit, delete, move, and rename mutate real files.
* Rollback restores prior content or prior path where supported.
* Conflict, stale hash, backup failure, path escape, absolute path, traversal, URL-like input, and NUL input do not mutate files.
* Execution runs record compact before/after metadata without leaking file contents.

#### Session 07: File Executor Integration

**Objective**: Make file capabilities executable only when guarded actions and queue or campaign tasks perform real file mutation.

**Scope**:

* Replace metadata-only file executor registry behavior with adapters backed by `FileMutationManager`.
* Wire guarded file approval to preview/apply real file mutations and update execution runs.
* Add queue and campaign file executable dispatch through `TaskExecutionCoordinator`.
* Add web preview, apply, conflict, result, and rollback states without exposing raw content in broad UI.
* Update capability probes so file entries become `executor_ready` only after the real adapter is available.

**Outputs**:

* Guarded file, queue file, campaign file, registry, route, and UI integration backed by real filesystem mutation.
* Server, web, and browser tests for apply, conflict, rollback, and redaction.

**Dependencies / Notes**:

* Depends on Session 06.
* File executor readiness must remain unavailable or approved-not-executing until this session proves real execution.

**Acceptance Checks**:

* Guarded file approval changes a real workspace file and records an executed run.
* Queue file task dispatch mutates a real file, surfaces the result, and offers rollback where supported.
* Conflict and stale hash paths stop before mutation and show the required recovery action.
* Broad rows and WebSocket events include compact metadata only, not content or patch bodies.
* Browser e2e proves visible apply and rollback for a file task.

#### Session 08: Managed Agent Lifecycle Control

**Objective**: Expose control verbs only for FactionOS-owned Claude/Codex sessions that can actually be controlled.

**Scope**:

* Add a managed agent session boundary with provider label, owned process or PTY id, cwd labels, readiness, supported actions, cleanup policy, and scoped IO.
* Implement narrow first controls: stop, restart, and message when the managed process or PTY adapter supports them.
* Keep change model, permission mode, and isolation mode unavailable unless a real provider-specific mechanism exists.
* Keep hook-ingested or observed external sessions record-only.
* Update Hero/Lineage UI verbs based on managed-session readiness and supported action list.

**Outputs**:

* Managed session manager or equivalent adapter, hero lifecycle integration, readiness-aware UI, and tests.

**Dependencies / Notes**:

* Depends on Session 01.
* External Claude Code and Codex CLI hook sessions are observed sessions unless FactionOS created and owns the process or PTY.

**Acceptance Checks**:

* A managed fixture process can be stopped and records an execution run.
* Restart failure preserves prior session history and reports unavailable or failed state.
* Unsupported model, permission, and isolation actions return unavailable before execution.
* Observed-only sessions show record-only intent and never claim execution.
* Browser e2e proves a managed stop result appears in the Hero/Lineage workbench.

#### Session 09: Container Dispatch Decision

**Objective**: Either prove container dispatch as an executable queue/campaign path or make it explicitly unsupported outside direct runtime controls.

**Scope**:

* Decide whether isolated container spawn is an approved executor family for queue and campaign dispatch.
* If approved, add bounded container executable payload support, coordinator dispatch, image/runtime readiness checks, result surfacing, unavailable handling, and tests.
* If not approved for this release, reject container orchestration payloads truthfully and keep direct container runtime controls separate.
* Surface missing runtime, missing image, policy block, timeout, and duplicate dispatch states honestly.

**Outputs**:

* A tested container dispatch slice, or protocol/UI/server behavior that explicitly marks queue/campaign container dispatch unsupported.
* Documentation or release-note updates that prevent container readiness from being confused with full orchestration support.

**Dependencies / Notes**:

* Depends on the coordinator shape from Sessions 02 through 04.
* Open question: the source plan proves direct isolated spawn readiness, but does not require container queue/campaign dispatch as part of the terminal, Git, file, and agent-control acceptance bar.

**Acceptance Checks**:

* If supported, queue or campaign container dispatch runs isolated spawn, creates an execution run, shows output, and handles missing image/runtime recovery.
* If unsupported, users cannot create or dispatch a container orchestration task that appears executable.
* In both paths, capability labels and release claims distinguish direct container runtime readiness from queue/campaign orchestration readiness.

#### Session 10: Templates And Channel Intake

**Objective**: Let templates and inbound channels create reviewable executable local tasks without automatically executing untrusted input.

**Scope**:

* Add template executable defaults only for known local executors with bounded inputs.
* Keep webhook and remote channel content proposal-first by default.
* Allow channel conversion to executable queue tasks only after local operator approval.
* Let guarded channel proposals reference executable payloads, with execution still flowing through the coordinator and capability checks.
* Split UI labels among record inbound command, create review task, create executable local task, and execute.
* Preserve idempotent replay without re-execution.

**Outputs**:

* Template, channel intake, guarded proposal, UI, and test updates that converge on the executable task contract.

**Dependencies / Notes**:

* Depends on the relevant executor slices for the payload families being exposed.
* Untrusted remote input must never dispatch automatically.

**Acceptance Checks**:

* Webhook conversion cannot execute on arrival.
* Channel-to-queue executable payload remains queued until an operator dispatches it.
* Template preview -> create -> dispatch preserves executable defaults and produces a real execution result.
* Invalid or unsafe payloads become proposal or attention state, not runnable tasks.
* Duplicate delivery returns prior records without re-execution.

#### Session 11: Release Evidence And Event Privacy

**Objective**: Prove all shipped orchestration paths end to end and align state, event, docs, and release claims with real behavior.

**Scope**:

* Complete the required protocol, server, web, and browser e2e matrix for terminal, Git, campaign DAG, file mutation, guarded actions, hero lifecycle, and channel/template intake.
* Verify Command Center state semantics for queued, in progress, completed, blocked, failed, and unavailable across queue and campaign tasks.
* Audit WebSocket events, broad rows, exports, diagnostics, examples, and docs for secret, terminal output, raw Git output, diff, file content, patch, token, absolute path, provider payload, and webhook body leakage.
* Update documentation and release claims so unsupported features are explicitly unfinished rather than presented as production orchestration.
* Run the focused completion commands and record any remaining unsupported paths.

**Outputs**:

* Green focused validation for all shipped paths, event/privacy hardening, and truthful documentation/release wording.

**Dependencies / Notes**:

* Depends on the feature slices that are included in the release claim.
* A feature is not shipped from this plan unless the product outcome is proven with real execution, visible result, recovery path, and automated tests.

**Acceptance Checks**:

* Terminal, Git, file mutation, and supported managed-agent control each pass create -> dispatch or approve -> execute -> observe -> recover evidence in the product.
* Campaign and queue states match actual execution outcomes and never complete from metadata-only work.
* Required focused commands pass: protocol typecheck, server typecheck, web typecheck, `npm test`, the Command Center browser e2e, and `git diff --check`.
* Release docs and UI labels use action verbs only for working actions.
* Remaining unsupported executor families are clearly unavailable, proposal-only, or approved-not-executing.

**Date:** 2026-06-28 **Scope:** Local Command Center and orchestration surfaces across `apps/server`, `apps/web`, and `packages/protocol`.

### Product Requirement

The target is full production orchestration: the operator must be able to plan work, dispatch it, execute it, observe it, intervene, recover, and audit the result from the Command Center.

Metadata-only, proposal-only, audit-only, preview-only, unavailable, and approved-but-not-executing paths are not acceptable as shipped orchestration capability. They are unfinished implementation states. If a control does not cause the requested local or remote action to happen, the UI, protocol, docs, and release claims must say that the feature is not implemented.

The current implementation violates that product requirement in several places. FactionOS has a large orchestration surface, but much of it is still state, audit, preview, or proposal scaffolding. The product feels unusable because several controls are labeled like actions while the backend only records local metadata.

There are a few real execution paths, but they are narrow and isolated:

* Git workbench can run bounded local Git operations through `POST /command-center/git/execute`.
* Terminal routes can run scoped commands only when local PTY support is available.
* Container routes can run isolated spawn only when local runtime/image probes pass.

The central defect is that queue, campaign, template, file, hero lifecycle, and many guarded-action flows do not bridge into those execution paths. That means the Command Center currently records intent more often than it performs work.

### Required Outcome

This project must deliver full orchestration features, not another planning or proposal layer. The required product outcome is:

1. Queue dispatch executes real work.
2. Campaign dispatch creates runnable tasks and execution runs.
3. Queue, campaign, template, and channel intake share an executable task contract.
4. Terminal execution works in a normal install.
5. File operations actually mutate workspace files through guarded, audited, reversible paths.
6. Git execution is wired into queue and campaign dispatch.
7. Hero lifecycle controls actually control supported Claude/Codex sessions.
8. Guarded actions execute when approved whenever their executor is marked ready.
9. Capability labels are truthful: `executor_ready` means the action works end to end.
10. The UI uses action verbs only for real actions.
11. End-to-end tests prove create -> dispatch -> execute -> observe -> recover for terminal, Git, file mutation, and supported agent-control paths.

Anything less than the list above is not full orchestration.

### Do Not Ship As Orchestration

The following are not acceptable substitutes for production orchestration:

* `Dispatch` that only changes a row to `in_progress`.
* Campaign dispatch that only creates queue records.
* File capabilities marked ready while they do not edit files.
* Hero controls that only record operator intent.
* Guarded-action approval that records a decision but performs no runtime effect while claiming readiness.
* Terminal execution that is unavailable after a normal install.
* Git execution that exists only in an isolated workbench and is not reachable from higher-level dispatch.
* Capability matrices that use `executor_ready` for metadata-only behavior.
* UI buttons labeled `Run`, `Execute`, `Dispatch`, `Apply`, `Edit`, or `Stop` when they do not perform the action.
* More panels that only add state, preview, proposal, or audit records without wiring execution.

### Delivery Guardrails

These rules exist to prevent more sessions from producing orchestration-shaped scaffolding without working orchestration.

1. No implementation session starts without an executable acceptance test.
   * The test must prove a real path such as queue task -> dispatch -> executor runs -> execution record created -> result visible.
   * The test must be written or clearly specified before implementation work begins.
2. No implementation session is complete unless the executable acceptance test passes.
   * Docs, protocol types, route scaffolding, UI panels, empty managers, diagnostics, and audit records do not count as completion by themselves.
3. Every shipped feature must have a real user action.
   * If the UI says `Dispatch`, `Run`, `Execute`, `Apply`, `Edit`, or `Stop`, the backend must perform that action.
   * If the backend cannot perform the action, the UI must not use that verb.
4. No `executor_ready` state is allowed without end-to-end proof.
   * The proof must execute the action, record the execution, surface the result, and cover the failure/unavailable path.
5. Proposal-only behavior cannot be counted as orchestration.
   * Proposal-only is allowed only as an explicitly unfinished state.
   * It must not be presented as a production feature.
6. Build vertical execution slices, not more surfaces.
   * Slice 1: queue dispatch to terminal execution.
   * Slice 2: queue/campaign dispatch to Git execution.
   * Slice 3: guarded file mutation.
   * Slice 4: supported Claude/Codex lifecycle control.
7. Stop after one failed vertical slice.
   * If the next orchestration session does not produce one working executable path, pause the orchestration track and reassess.
   * Do not continue into more panels, docs, scaffolds, or preparatory sessions.
8. Definition of done is fixed.
   * `create -> dispatch -> execute -> observe -> recover` must work in the app.
   * Automated tests must prove the path.
   * The UI must show the real execution result.
   * Unsupported or unavailable states must be truthful before the user clicks.

### Source-Backed Findings

#### 1. Terminal execution is narrow and native-dependency gated

`apps/server/src/managers/terminalSessionManager.ts` dynamically imports `node-pty` and reports `pty_unavailable` when it cannot load or probe. `node-pty` is a required server dependency, so install and native-build failure must be treated as environment breakage with explicit diagnostics. Direct terminal routes are implemented and tested with an injected PTY adapter.

Impact: direct terminal routes can run when PTY support is present, but queue and campaign dispatch do not target them. Production orchestration must either make the normal install reliably executable or show terminal dispatch as unavailable before the user attempts it.

#### 2. Queue dispatch is only a state transition

`apps/server/src/managers/taskQueue.ts` implements `dispatch()` by changing a queue entry to `in_progress`. `apps/server/src/routes/orchestration.ts` exposes that through `POST /task-queue/:id/dispatch`.

Impact: the queue workbench has a `Dispatch` button, but it does not execute a terminal command, run Git, start an agent, create a guarded action, or attach an execution run. It starts tracking, not doing. This is the wrong behavior for a production dispatch control.

#### 3. Campaign dispatch creates queue records, not running work

Campaign dispatch flows create or update local campaign/task/queue state. They do not hand off to terminal, Git, container, or agent execution.

Impact: a campaign can be approved and dispatched while no actual work starts. This is planning state, not production orchestration.

#### 4. File executor capability is misleading after registry probe

`apps/server/src/managers/executorRegistry.ts` marks file executor entries as `executor_ready`, but the executor summary explicitly says it records bounded file intent execution metadata only. The rollback note says repository content is not changed.

Command-center snapshots seed file capabilities as unavailable, but `POST /command-center/executors/probe` can promote `capability_file_file_edit` to `executor_ready`. Guarded file approval then returns `executed` while only recording audit metadata.

Impact: the capability matrix can imply file operations are executable after a probe even though file read/write/edit/delete/move do not mutate files. A capability must not be marked ready until it can perform the requested action end to end.

#### 5. Git execution is real but isolated from higher-level flows

`apps/server/src/managers/gitWorkbenchManager.ts` builds bounded argv and runs local `git` for status, stage, unstage, commit, stash, revert, and branch switch. The web `FileGitWorkbench` calls preview and execute directly.

Impact: Git is one of the few useful operator actions today, but queue and campaign dispatch do not automatically use it. Users must manually find the Git workbench and run operations there. Production orchestration needs this wired through higher-level dispatch.

#### 6. Guarded actions execute only for a subset

Guarded actions evaluate through `ExecutorRegistry`. Git can execute, terminal can execute if PTY is ready, and containers can execute if runtime probes pass. Many other families remain `approved_not_executing`, `proposal_only`, or `unavailable`.

Impact: approving a guarded action often records a decision without causing a runtime effect. That is not an implemented action. It must either execute or be shown as unfinished before the user clicks.

#### 7. Hero lifecycle controls are audit records

`apps/server/src/managers/heroLifecycleManager.ts` records lifecycle intents such as message, dismiss, model change, permission mode change, and isolation mode change. These do not currently control a running Claude/Codex process.

Impact: the UI can look like it can steer agents, but the shipped path records operator intent only. Production orchestration requires actual process/provider control or explicit unsupported-state wording.

#### 8. No common executable task contract

Queue entries have title, summary, priority, source, references, and attribution. They do not carry a normalized executable payload such as executor family, operation, argv/body, preview, required approval, timeout, or rollback metadata.

Impact: higher-level planning surfaces cannot dispatch into terminal/Git/file execution without ad hoc interpretation. This blocks full-featured orchestration.

### Non-Negotiable Acceptance Bar

The following must be true before orchestration is claimed as production-ready:

1. `Dispatch` starts real work or the control is not called dispatch.
2. Campaign dispatch creates runnable tasks and execution runs, not just queue rows.
3. Queue entries can carry executable payloads for terminal, Git, file, agent, container, and future remote/provider executors.
4. File operations mutate the workspace through guarded, audited, reversible paths.
5. Hero lifecycle controls actually steer supported agent sessions.
6. Terminal execution works in a normal install.
7. Every executor capability marked `executor_ready` performs real work.
8. Every non-implemented executor is shown as unfinished, not as shipped capability.
9. The UI uses action verbs only for controls that perform actions.
10. End-to-end tests prove create -> dispatch -> execute -> observe -> recover for at least terminal, Git, file, and agent-control paths.

### Required Fix Path

1. Make terminal execution work by default.
   * Keep `node-pty` as a reliably installed and diagnosed server dependency, and add a dependency-free non-interactive `child_process.spawn` fallback only if a later executor slice needs scoped one-shot commands without PTY support.
   * Update diagnostics and `factionos doctor` so the user sees the exact terminal execution state and repair step.
2. Rewire queue dispatch into real execution.
   * Add an explicit executable payload to queue entries.
   * Have dispatch create a command-center execution run.
   * Rename any remaining metadata-only transition to `Start tracking`.
3. Implement real guarded file operations.
   * Add preview, backup/rollback, path validation, conflict handling, audit, and tests.
   * Until this exists, file write/edit/delete/move must not appear as ready.
4. Add a shared executable task contract.
   * Minimal fields: executor family, operation/kind, safe args or scoped body, target refs, risk, timeout, approval requirement, rollback note, and idempotency key.
   * Queue, campaign, template, channel intake, and guarded actions should all converge on this contract.
5. Make campaign dispatch create runnable tasks.
   * A task with `executor=git` should dispatch to Git workbench.
   * A task with `executor=terminal` should dispatch to terminal runtime.
   * A task without an executor should stay as planning state and say so.
6. Split UI verbs by actual behavior.
   * Use `Record` for metadata-only flows.
   * Use `Preview` for non-mutating plans.
   * Use `Execute` only when a local runtime will actually run.
7. Add end-to-end proof for complete paths.
   * Example: create queue entry with terminal command -> preview -> dispatch -> execution run -> terminal output appears in drawer -> final state is executed/failed/unavailable.
   * Add the same proof for Git, file mutation, and supported agent lifecycle control.

### Planning Details

The implementation must be planned as vertical execution slices. A slice is not accepted because it adds DTOs, panels, rows, or audit records. It is accepted only when a user can start from an intended outcome in the Command Center, perform the action, see the actual result, recover from the supported failure mode, and the automated tests prove that path.

#### Current Source Map

The following code paths are the relevant source of truth for the next implementation sessions.

| Area                    | Current files                                                                                                                                                                                                                                      | Planning consequence                                                                                                                                                                                                                                                    |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Queue contract          | `packages/protocol/src/taskQueue.ts`                                                                                                                                                                                                               | `TaskQueueEntry` has title, summary, state, priority, source, references, attribution, and revision. It has no executable payload, execution run link, approval policy, timeout, rollback metadata, or result summary.                                                  |
| Queue behavior          | `apps/server/src/managers/taskQueue.ts`, `apps/server/src/routes/orchestration.ts`                                                                                                                                                                 | `dispatch()` only transitions \`queued                                                                                                                                                                                                                                  |
| Campaign contract       | `packages/protocol/src/orchestrationCommandCenter.ts`                                                                                                                                                                                              | `CommandCenterPlanTask` has campaign, dependency, owner, expected result, state, and verification fields. It has no executable payload or execution result link.                                                                                                        |
| Campaign behavior       | `apps/server/src/managers/planCampaignManager.ts`, `apps/server/src/routes/commandCenter.ts`                                                                                                                                                       | Campaign `dispatch()` creates legacy queue rows and marks plan tasks `queued`; it does not call Git, terminal, file, container, or agent executors. Existing tests assert this old bridge behavior.                                                                     |
| Execution run model     | `packages/protocol/src/orchestrationCommandCenter.ts`, `apps/server/src/managers/orchestrationCommandCenter.ts`                                                                                                                                    | `CommandCenterExecutionRun` can represent queued/executing/executed/failed/unavailable runs. Guarded actions, direct Git, terminal, and container routes already store runs. Queue and campaign need to attach to this model instead of inventing another result store. |
| Guarded execution spine | `apps/server/src/routes/guardedActions.ts`, `apps/server/src/managers/executorRegistry.ts`                                                                                                                                                         | Approval already follows the right shape: evaluate capability, store run, mark executing, execute adapter, complete run, update guarded result. Queue and campaign dispatch should reuse this pattern or a common coordinator built from it.                            |
| Git executor            | `apps/server/src/managers/gitWorkbenchManager.ts`, `apps/server/src/routes/commandCenter.ts`, `apps/web/src/components/orchestration/FileGitWorkbench.tsx`                                                                                         | Git operations are real local `git` commands except policy-blocked push. They are reachable from the File/Git workbench and guarded Git approvals, but not from queue or campaign dispatch.                                                                             |
| Terminal executor       | `apps/server/src/managers/terminalSessionManager.ts`, `apps/server/src/routes/terminalContainers.ts`, `apps/web/src/components/orchestration/TerminalRuntimeDrawer.tsx`                                                                            | Direct terminal run/kill/restart exists behind PTY readiness and writes execution attachments. Queue and campaign need to dispatch into this manager, handle `pty_unavailable`, and surface the terminal session detail.                                                |
| File intent manager     | `apps/server/src/managers/fileIntentManager.ts`, `apps/server/src/routes/commandCenter.ts`                                                                                                                                                         | File intent declaration, conflict checks, TTL, and resolution audit exist. There is no workspace file mutation, preview, backup, or rollback manager.                                                                                                                   |
| File executor registry  | `apps/server/src/managers/executorRegistry.ts`                                                                                                                                                                                                     | Default file executor entries can be probed to `executor_ready` while executing audit metadata only. This must be downgraded or replaced by a real file mutation adapter.                                                                                               |
| Hero lifecycle          | `apps/server/src/managers/heroLifecycleManager.ts`, `apps/web/src/components/orchestration/HeroLineageWorkbench.tsx`                                                                                                                               | Lifecycle actions record `approved_not_executing` or `unavailable` states. The UI action reason admits it records local intent without direct process control. Product labels must match that until a managed agent control adapter exists.                             |
| Channel intake          | `apps/server/src/managers/channelCommandManager.ts`, `apps/server/src/routes/channelCommands.ts`                                                                                                                                                   | Inbound channel commands are proposal-first and can convert to record, queue, attention, or guarded proposal. They must not become trusted remote execution; they may create local executable tasks only after local approval.                                          |
| Web action labels       | `apps/web/src/lib/commandCenterUi.ts`, `QueueWorkbench.tsx`, `CampaignWorkbench.tsx`, `HeroLineageWorkbench.tsx`                                                                                                                                   | Queue and campaign action availability says the action records state changes while the visible labels still use `Dispatch`. Labels and enabled states must become capability-aware.                                                                                     |
| Existing tests          | `apps/server/tests/orchestration.test.ts`, `commandCenterRoutes.test.ts`, `guardedActions.test.ts`, `terminalContainerRoutes.test.ts`, `gitWorkbenchManager.test.ts`, `fileIntentManager.test.ts`, `tests/e2e/orchestration-command-center.e2e.ts` | Current tests heavily cover metadata, redaction, idempotency, and direct executor islands. New tests must replace old queue/campaign bridge assertions with execution assertions.                                                                                       |

#### Installed Dependency And Runtime Baseline

The dependency/setup pass removed the immediate "missing package" excuse for the execution slices. The following packages and host requirements are now installed or declared, but they do not by themselves make queue, campaign, file, or lifecycle actions real. The implementation slices below still must wire these capabilities through executable payloads, execution runs, visible results, recovery paths, and tests.

| Capability                      | Installed or declared baseline                                                                                                                                                                                                                                                                                                                    | Remaining product requirement                                                                                                                                                                                     |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Terminal execution              | `apps/server/package.json` declares `node-pty` as a normal dependency, not an optional dependency. Native install scripts are approved and rebuilt. Live probe evidence showed `TerminalSessionManager.probe()` returning `executor_ready`.                                                                                                       | Queue and campaign dispatch must route to `TerminalSessionManager`, attach execution runs, surface scoped output, and handle `pty_unavailable`, timeout, kill, and retry states.                                  |
| File diff and validation        | `apps/server`, `apps/web`, and `packages/protocol` declare `zod`; `apps/server` and `apps/web` declare `diff`.                                                                                                                                                                                                                                    | Define the executable-task runtime schema, shared parsers, file preview contract, file mutation manager, backup, rollback, conflict handling, and UI result surfaces.                                             |
| Process lifecycle control       | `apps/server` declares `tree-kill`. The package has no separate `@types/tree-kill` package on npm, so no types package was added.                                                                                                                                                                                                                 | Use only for FactionOS-owned managed processes after a process adapter exists. Observed external Claude/Codex sessions must stay record-only or unavailable for stop/restart.                                     |
| Container execution             | `apps/server` declares `dockerode` and Docker CLI is available locally. The default image `factionos-isolated:latest` was built from `docker/factionos-isolated/Dockerfile`; `npm run isolation:image:build` rebuilds it. Live evidence showed `ContainerRuntimeManager.probe()` returning `ready` and `runIsolatedSpawn()` returning `executed`. | Queue/campaign dispatch must decide whether container execution is an approved executor family, pass image/runtime choices through the executable payload, and surface unavailable image/runtime states honestly. |
| Git execution libraries         | `apps/server` declares `simple-git` and `isomorphic-git`, although the current production Git path still uses bounded `child_process.spawn` calls in `GitWorkbenchManager`. Host `git` is installed.                                                                                                                                              | Do not replace the bounded Git workbench path just because packages exist. Queue/campaign Git dispatch should reuse `GitWorkbenchManager` unless a specific implementation proves a library-based path is safer.  |
| Rich terminal UI                | `apps/web` declares `@xterm/xterm`.                                                                                                                                                                                                                                                                                                               | Only introduce a full terminal surface if the slice needs interactive terminal behavior. Scoped output in `TerminalRuntimeDrawer` remains enough for one-shot queue execution.                                    |
| Rich file/code UI               | `apps/web` declares `monaco-editor@0.53.0`. This version was selected by `npm audit fix --force` to avoid the vulnerable transitive `dompurify` range in newer Monaco releases.                                                                                                                                                                   | Use Monaco only when it improves file review or editing. First delivery can still ship a simpler diff/result view if it proves the outcome end to end.                                                            |
| Provider and analytics adapters | `apps/server` still keeps `@anthropic-ai/sdk` and `@umami/node` in `optionalDependencies`; both are installed and load locally.                                                                                                                                                                                                                   | Provider transfer and analytics must remain explicitly configured and are not prerequisites for local execution. Do not make queue dispatch depend on external provider credentials.                              |

Verification completed for this baseline:

* `npm approve-scripts --allow-scripts-pending` reported no unreviewed install scripts.
* `npm audit --audit-level=moderate` reported zero vulnerabilities.
* `npm run typecheck`, `npm run build`, `npm run format:check`, and `npm run lint` passed.
* `npm test` passed with 263 files and 2982 tests, with one skipped Wrangler dev test.
* `docker run --rm factionos-isolated:latest echo ready` returned `ready`.
* Live built-manager checks showed terminal `executor_ready`, container `ready`, and isolated spawn `executed`.

#### Target Architecture

Add one shared executable task contract and one server-side execution coordinator. Queue entries, campaign tasks, templates, channel conversions, and guarded-action bridges should all produce or reference the same contract.

The target flow is:

```
user intent
  -> executable task payload
  -> preview/capability check
  -> approval when required
  -> execution run created
  -> executor adapter runs or returns unavailable
  -> queue/task/campaign state updates
  -> result appears in Command Center UI
  -> recovery action is available for supported failures
```

Do not make route handlers the orchestration brain. Keep routes thin and put dispatch decisions in a manager so REST, WebSocket, future CLI, campaign, and channel intake cannot drift.

Proposed server manager:

* `apps/server/src/managers/taskExecutionCoordinator.ts`
* Dependencies: `OrchestrationCommandCenterManager`, `TaskQueueManager`, `ExecutorRegistry`, `GitWorkbenchManager`, `TerminalSessionManager`, `FileMutationManager` once created, and optionally `ContainerRuntimeManager`.
* Public methods:
  * `previewQueueEntry(entryId, input)`
  * `dispatchQueueEntry(entryId, input)`
  * `dispatchCampaignTask(campaignId, taskId, input)`
  * `dispatchCampaign(campaignId, input)`
  * `retryExecution(target, input)`
  * `recoverExecution(runId, action, input)`
* Responsibilities:
  * validate executable payloads and expected revisions;
  * reject missing payloads before state changes;
  * evaluate executor capability immediately before dispatch;
  * create a `CommandCenterExecutionRun` before runtime execution;
  * mark executing/completed/failed/unavailable consistently;
  * update queue and campaign task states from the execution result;
  * emit command-center execution, queue, task, and plan updates;
  * enforce idempotency across duplicate dispatches;
  * keep raw commands, terminal output, diffs, and file contents out of broad rows and WebSocket snapshots.

#### Executable Task Contract

Add protocol-owned types before server or web work:

* `CommandCenterExecutableTask`
  * `executorFamily`: one of existing `CommandCenterExecutorFamily`.
  * `executorKind`: one of existing `CommandCenterExecutorKind`.
  * `operation`: concrete operation label, such as `terminal_command`, `git_status`, `file_edit`, or `message_hero`.
  * `input`: discriminated bounded input. Use typed variants, not arbitrary JSON.
  * `target`: existing `CommandCenterTargetRef`.
  * `risk`: existing `CommandCenterRisk`.
  * `approval`: `not_required`, `permission_required`, or `guarded_action`.
  * `timeoutMs`.
  * `idempotencyKey`.
  * `rollback`: summary, strategy label, and optional follow-up executable reference.
  * `outputPolicy`: summary-only, scoped-terminal-output, or scoped-file-diff.
  * `createdAt`, `updatedAt`, and optional `createdBy`.
* Input variants:
  * `terminal`: `commandText`, `ownerId`, `timeoutMs`.
  * `git`: existing `CommandCenterGitWorkbenchRequest`.
  * `file`: `operation`, `path`, optional `newPath`, optional bounded content or patch body, `expectedSha256`, `backupRequired`.
  * `container`: existing isolated-spawn fields.
  * `hero_lifecycle`: existing lifecycle command fields plus required `managedSessionId` for real control.
  * `guarded_action_ref`: guarded action id when approval owns dispatch.
* Attachments:
  * `TaskQueueEntry.executable?: CommandCenterExecutableTask`.
  * `TaskQueueEntry.executionRunIds?: string[]` or a bounded equivalent.
  * `TaskQueueMutationResponse.execution?: CommandCenterExecutionRun`.
  * `CommandCenterPlanTask.executable?: CommandCenterExecutableTask`.
  * `CommandCenterPlanTask.executionRunIds?: string[]`.
  * Campaign responses should include `executions?: CommandCenterExecutionRun[]`.
  * Event entries should expose only executor family/kind, readiness/result labels, and execution ids, never raw executable input.

Validation rules:

* Unknown executor family/kind is invalid.
* Missing executable payload means the UI cannot call the action `Dispatch`.
* Terminal command text stays request-scoped or scoped-detail only.
* Git request reuses existing path and branch guards.
* File paths must be repo-relative, inside the approved root, not symlink escapes, not absolute, not URLs, not traversal, and not NUL-containing.
* File content and patch bodies are never included in broad list responses, WebSocket event entries, docs examples, replay, export, diagnostics, or Worker transfer.
* `executor_ready` is legal only after a probe and a passing execute-path test for that exact executor family/kind.

#### Slice 0: Truthful Capability And Verbs

Purpose: stop presenting metadata-only paths as executable before adding new runtime behavior.

Required changes:

* Downgrade file executor registry entries from `executor_ready` to `approved_not_executing` or `unavailable` until real file mutation exists.
* Update tests that currently expect `capability_file_file_edit` to probe as `executor_ready`.
* Update guarded file approval tests that currently expect `state: "executed"` for metadata-only file approval.
* Change queue and campaign action copy when no executable payload exists: `Start tracking` or `Queue for review`, not `Dispatch`.
* Change hero lifecycle buttons to make the visible action intent truthful for observed-only sessions, for example `Record message intent`, unless a managed session controller is attached and ready.
* Capability matrix copy must distinguish:
  * `Unavailable`: cannot execute.
  * `Proposal only`: can create review/proposal state.
  * `Approved, not executing`: approval records a decision but runtime control is absent.
  * `Executor ready`: proved execution path exists.

Acceptance tests:

* `apps/server/tests/executorRegistry.test.ts` proves file executor entries are not ready until a real file adapter is injected.
* `apps/server/tests/commandCenterRoutes.test.ts` proves executor probe does not promote metadata-only file entries to `executor_ready`.
* `apps/web/tests/commandCenterUi.test.ts` proves queue/campaign labels do not say `Dispatch` for metadata-only records.
* `apps/web/tests/CommandCenterPanes.test.tsx` proves hero lifecycle controls communicate record-only behavior when no managed session is ready.

#### Slice 1: Queue Dispatch To Terminal Execution

User outcome: an operator creates a queue task with a terminal command, clicks dispatch, the command runs locally, the queue row shows the final result, and the terminal drawer shows scoped output or a truthful unavailable state.

Required changes:

* Add terminal executable payload support to queue create/preview/update requests.
* Add `POST /task-queue/:id/preview-dispatch` if the UI needs a non-mutating preflight before dispatch.
* Change `POST /task-queue/:id/dispatch` to call `TaskExecutionCoordinator.dispatchQueueEntry`.
* Keep the old state-only transition only behind a renamed route or action such as `POST /task-queue/:id/start-tracking`.
* For terminal payloads, coordinator should:
  * call `TerminalSessionManager.probe()`;
  * create a `CommandCenterExecutionRun` with target `queue_item`;
  * call `TerminalSessionManager.start()` for interactive runs or `runAndWait()` for one-shot dispatch;
  * store the terminal attachment;
  * update queue state to `in_progress`, then `completed`, `failed`, or `unavailable`;
  * preserve kill and restart recovery through existing terminal session routes.
* Web queue rows should show executor family, run state, result summary, and a link to the execution run or terminal session. Scoped terminal output remains in `TerminalRuntimeDrawer`, not broad rows.

Recovery paths:

* `pty_unavailable`: queue becomes `unavailable`, execution run records unavailable reason, UI shows repair guidance.
* timeout: execution run and queue become failed, terminal attachment remains inspectable, retry is enabled.
* running command: user can kill through terminal session control.
* duplicate dispatch: idempotent response returns existing execution run.

Acceptance tests:

* New `apps/server/tests/taskExecutionCoordinator.test.ts` with injected fake PTY proves `create -> dispatch -> execute -> completed queue -> execution detail -> terminal attachment`.
* Server route test proves `/task-queue/:id/dispatch` creates an execution run and emits both `task_queue_update` and `command_center_execution_update`.
* Failure test proves `pty_unavailable` does not leave the row stuck `in_progress`.
* Web component/store tests prove result summary and terminal link render.
* Browser e2e proves the visible Command Center flow from queue row to terminal drawer.

#### Slice 2: Queue And Campaign Dispatch To Git Execution

User outcome: an operator queues or campaigns a Git action, dispatches it, the allowlisted Git command runs, and the Command Center shows the real Git result with rollback guidance.

Required changes:

* Add Git executable payload support to queue entries and campaign tasks using existing `CommandCenterGitWorkbenchRequest`.
* Make `PlanCampaignTaskInput` accept an optional executable payload.
* Update `PlanCampaignManager.buildCampaignDraft` to preserve executable payloads on tasks.
* Change campaign dispatch so tasks with executable payloads dispatch through the coordinator. Tasks without payloads stay planning state and the UI must not call them dispatched.
* For Git payloads, coordinator should:
  * call `GitWorkbenchManager.preview()` for preflight;
  * create execution run target `queue_item` or `task`;
  * call `GitWorkbenchManager.execute()`;
  * update queue/campaign task based on result;
  * preserve rollback notes from the Git plan.
* The File/Git workbench can keep direct `Preview` and `Execute`, but it should also offer `Create queue task` or `Attach to campaign` when the user wants higher-level orchestration.

Recovery paths:

* validation failure: no Git process runs; queue/task becomes blocked or unavailable with safe validation reason.
* policy-blocked push: execution run is unavailable with `policy_blocked`; UI offers no push retry unless policy is enabled.
* failed Git command: execution run failed with bounded stderr/stdout summary; rollback/follow-up action is visible.
* stage/unstage/revert recovery should create the inverse Git executable where one exists.

Acceptance tests:

* Server coordinator test with injected `GitCommandRunner` proves exact argv for `status`, `stage`, `unstage`, and blocked `push`.
* Route test replaces old campaign dispatch expectation. It must assert `campaign -> task executable -> dispatch -> execution run -> task completed` for a successful Git task.
* Partial failure campaign test proves one failed Git task does not falsely mark the full campaign completed.
* Web tests prove Git execution result is visible from campaign and queue rows.

#### Slice 3: Real File Mutation With Backup And Rollback

User outcome: an operator previews a file change, approves it, the workspace file actually changes, the UI shows the result, and rollback restores the prior content when rollback is supported.

Required changes:

* Add `apps/server/src/managers/fileMutationManager.ts`.
* Add protocol file mutation request/result types:
  * read, write, edit, delete, move, rename;
  * `expectedSha256` or revision guard;
  * optional bounded content/patch body in request only;
  * backup id, before hash, after hash, changed byte count, and rollback state in result metadata.
* The file manager must:
  * resolve paths under the approved workspace root;
  * reject symlink escape, absolute path, traversal, URL-like input, NUL, and generated or ignored directories where policy requires;
  * compute preflight hashes;
  * create local backups under FactionOS state before mutating write/edit/delete operations;
  * perform actual filesystem mutation;
  * record a compact execution run;
  * provide rollback for write/edit/delete/move/rename where a backup exists.
* File intent conflict checks remain a coordination layer, but real mutation must call them before write/edit/delete/move and require an override or clear decision when conflicts exist.
* Replace file executor registry entries with real adapters backed by `FileMutationManager`. Only then may file entries probe as `executor_ready`.
* Broad UI rows show path labels, operation, hashes/counts, and result status. File content or patch bodies stay out of broad views.

Recovery paths:

* conflict: no mutation runs; guarded action or queue task waits for explicit clear/override.
* stale hash: no mutation runs; UI asks user to refresh preview.
* backup failure: no mutation runs.
* mutation failure after backup: execution failed and rollback action is offered if possible.
* rollback failure: execution remains failed with manual recovery guidance.

Acceptance tests:

* Temp-directory server test proves write/edit/delete/move mutate real files.
* Rollback test proves before content is restored.
* Conflict test proves mutation is blocked by active file intent until cleared or overridden.
* Guarded file approval test proves approve -> file changes -> execution run executed.
* Queue file task test proves queue dispatch mutates file and surfaces result.
* Web test proves preview, apply, conflict, and rollback states render without file content leakage.

#### Slice 4: Campaign Dispatch As Executable DAG

User outcome: a campaign with executable tasks dispatches runnable work in dependency order, records each execution, marks task and campaign outcomes truthfully, and lets the operator retry failed tasks.

Required changes:

* Treat campaign tasks as a DAG. Initial implementation can execute serially in dependency order; do not claim parallel orchestration until concurrency is implemented and tested.
* Campaign dispatch should:
  * skip tasks without executable payload and mark them `blocked` or keep them `pending` with a planning-only reason;
  * dispatch ready executable tasks;
  * block dependents until dependencies finish successfully;
  * mark campaign `completed` only when all executable tasks completed and all required verification passed;
  * mark campaign `failed` or `blocked` on failed/unavailable tasks;
  * include `executions` in the response.
* `retryFailed()` should re-dispatch failed or unavailable executable tasks only, preserving idempotency and prior run history.
* Queue rows created from campaign tasks should carry the same executable payload and link back to campaign/task ids.

Recovery paths:

* retry failed task;
* cancel remaining queued tasks;
* mark planning-only tasks as non-dispatchable;
* inspect execution detail for each task;
* create follow-up rollback executable for Git/file tasks when available.

Acceptance tests:

* Campaign route test proves create -> approve -> dispatch -> task execution runs -> campaign completed.
* Dependency test proves task B does not run before task A completes.
* Failure test proves dependent tasks are blocked and retry only reruns failed tasks.
* Web test proves campaign graph displays per-task execution states and links.

#### Slice 5: Supported Agent Lifecycle Control

User outcome: only managed Claude/Codex sessions that FactionOS can actually control show control verbs. Clicking a supported control performs process or PTY action; observed-only sessions show record-only intent.

Current source reality:

* Hook-ingested Claude Code and Codex CLI sessions are observed, not controlled.
* `HeroLifecycleManager` records lifecycle commands only.
* No current manager can send a prompt to an arbitrary external Claude/Codex process, change its model, change its permission mode, or dismiss it.

Required changes:

* Add a managed agent session boundary before claiming lifecycle control. Candidate manager: `apps/server/src/managers/managedAgentSessionManager.ts`.
* A managed session must have:
  * provider label (`claude-code` or `codex-cli`);
  * process id or PTY session id created by FactionOS;
  * command line and cwd labels kept compact;
  * readiness state;
  * supported action list;
  * kill/restart cleanup policy;
  * output/input scoping.
* Supported first actions should be narrow:
  * `stop`: kill a managed FactionOS-owned process or PTY session.
  * `restart`: restart the same managed command if configured.
  * `message`: write scoped input only when the managed PTY is running and the provider action is explicitly supported.
* `change_model`, `change_permission_mode`, and `change_isolation_mode` must remain unavailable unless a real provider-specific mechanism is implemented.
* Observed hook sessions continue to show `Record intent`, not `Stop`, `Dismiss`, `Change model`, or similar control verbs.

Recovery paths:

* stop timeout escalates to kill and records cleanup state;
* restart failure leaves the prior session history and an unavailable run;
* unsupported action returns unavailable before execution.

Acceptance tests:

* Manager test with a real spawned fixture process or injected process adapter proves stop kills an owned process and records an execution run.
* Route test proves observed-only hero action records intent but does not claim executed.
* Web test proves buttons switch between record-only and control verbs based on supported action readiness.
* Browser e2e proves a managed session stop result appears in the Hero/Lineage workbench.

#### Slice 6: Templates And Channel Intake Into Executable Tasks

User outcome: templates and inbound channels can create reviewable executable local tasks, but they never execute remote or untrusted input automatically.

Required changes:

* Template queue preview can include an executable payload only when the template declares a known local executor and bounded inputs.
* Channel intake with `conversion: "queue"` may create an executable task only when the payload is locally authored or explicitly operator-approved. Webhook content must stay proposal-first by default.
* Channel guarded proposals may reference executable payloads, but approval must go through the same coordinator and capability checks.
* UI must separate:
  * `Record inbound command`;
  * `Create review task`;
  * `Create executable local task`;
  * `Execute`, only after local approval and capability readiness.

Recovery paths:

* invalid or unsafe executable payload becomes attention/proposal state, not a runnable queue entry;
* duplicate delivery replays prior record without re-execution;
* operator can edit or reject the generated executable payload before dispatch.

Acceptance tests:

* Channel route test proves webhook conversion cannot execute on arrival.
* Channel-to-queue test proves executable payload stays queued until operator dispatch.
* Template test proves executable defaults survive preview -> create -> dispatch.
* Web tests prove labels and disabled states are truthful.

#### Required Test Matrix

Every implementation session must update or add the relevant row before code work is considered complete.

| Path                    | Protocol tests                                | Server tests                                                                   | Web tests                                         | Browser e2e                                  |
| ----------------------- | --------------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------- | -------------------------------------------- |
| Queue terminal          | executable payload parser and event redaction | fake PTY success, `pty_unavailable`, timeout, kill/restart, duplicate dispatch | queue row result, terminal link, unavailable copy | queue create/dispatch/result/terminal drawer |
| Queue Git               | Git payload parser and path validation        | fake Git runner success/failure/policy block                                   | Git result from queue row                         | dispatch visible result                      |
| Campaign executable DAG | task executable payload and response shape    | dependency order, partial failure, retry failed, no-payload planning state     | campaign graph execution states                   | campaign approve/dispatch/result             |
| File mutation           | file mutation request/result parser           | temp-dir mutation, backup, rollback, conflict, stale hash                      | preview/apply/rollback/conflict states            | file task apply and rollback visible         |
| Guarded actions         | capability states and run result parser       | approve -> execution for Git/file/terminal, non-ready unavailable              | capability matrix truthfulness                    | approve result visible                       |
| Hero lifecycle          | managed-session action parser                 | owned process stop/restart, observed-only unavailable/record-only              | readiness-based button verbs                      | managed stop result visible                  |
| Channel/template intake | executable task source parser                 | no auto-execute, idempotent replay, template executable survives               | labels split review/create/execute                | generated task dispatch result               |

Minimum focused commands for a completed slice:

```bash
npm --workspace packages/protocol run typecheck
npm --workspace apps/server run typecheck
npm --workspace apps/web run typecheck
npm test
npm run test:e2e -- --project=app-desktop tests/e2e/orchestration-command-center.e2e.ts
git diff --check
```

Use narrower Vitest invocations during development, but the slice is not done until the focused server, protocol, web, and browser evidence for that path is green.

#### State And Event Requirements

Execution must be visible and recoverable through the existing Command Center data model.

* Queue row states:
  * `queued`: has not started.
  * `in_progress`: execution run is queued or executing.
  * `completed`: execution run finished `executed`.
  * `blocked`: validation, dependency, or approval blocks dispatch.
  * `failed`: execution run finished failed.
  * `unavailable`: capability was unavailable before or during dispatch.
* Campaign task states should mirror queue semantics and keep dependency blocking explicit.
* Campaign state should be:
  * `in_progress` while any executable task is running or queued;
  * `completed` only when all dispatchable executable tasks finished and required verification passed;
  * `blocked` when dependencies or approvals block progress;
  * `failed` when one or more required executable tasks failed and no retry is currently in flight.
* WebSocket events must include compact updates for:
  * queue transition;
  * execution run create/executing/complete;
  * campaign task update;
  * campaign plan update.
* Broad event rows must never include terminal command text, terminal output, raw Git output, diffs, file contents, patch bodies, tokens, secrets, broad absolute paths, provider payloads, or webhook raw bodies.

#### Do Not Implement Around The Core Problem

The next sessions must not add more broad panels, metrics, diagnostics, or planning records before at least one vertical execution path is complete.

Allowed preparatory work:

* protocol fields required by the vertical slice;
* one coordinator manager;
* parser and redaction tests;
* UI changes needed to make the executable path visible.

Disallowed as completion:

* a new queue field that is never executed;
* a campaign response that includes executable metadata but does not run it;
* a file mutation preview without apply and rollback;
* a capability probe that returns `executor_ready` without a passing runtime execution test;
* an e2e test that only mocks a successful result without any server-side integration test proving execution;
* a UI label change that still routes to metadata-only behavior.

### Product Interpretation

The current implementation is a local control-plane scaffold with a few real executor islands. It is not full production orchestration yet.

The next work must stop adding more panels that record intent and instead wire the existing surfaces into real execution. Anything else increases surface area without increasing user agency.


---

# 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/phases/phase_20/prd_phase_20.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.
