> For the complete documentation index, see [llms.txt](https://faction-os.gitbook.io/faction-os-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase03-session02-task-queue-and-agent-template-contracts/spec.md).

# Session Specification

**Session ID**: `phase03-session02-task-queue-and-agent-template-contracts` **Phase**: 03 - Agent Orchestration **Status**: Not Started **Created**: 2026-05-29 **Package**: Cross-cutting (`packages/protocol`, `apps/server`) **Package Stack**: TypeScript protocol contracts, Express routes, in-memory server managers, WebSocket events, Vitest

***

## 1. Session Overview

This session defines and implements the local task queue and agent template contracts that Phase 03 needs before subagent lineage, guarded actions, web controls, or CLI diagnostics can consume orchestration state. It starts in `packages/protocol` with shared queue, template, REST, and WebSocket shapes, then wires the approved subset through `apps/server` as bounded local contracts.

The session deliberately does not execute queued tasks, spawn agents, call a terminal, or create hosted queue behavior. Queue entries and templates are local planning state only: they can be created, listed, updated, rejected, and broadcast as redacted metadata so later sessions can build on a stable contract.

This work is next because `phase03-session01-orchestration-requirements-and-safety-baseline` is complete and its matrix routes task queue and agent template contract work to Session 02. Sessions 03 through 06 depend on these shared contracts being available before they add lineage, guarded action lifecycles, cockpit controls, or diagnostics.

***

## 2. Objectives

1. Define protocol-owned queue and agent template contracts with explicit state, validation, and rejection vocabularies.
2. Implement local server managers and route handlers for bounded queue and template state without running developer commands.
3. Emit compact WebSocket queue and template update frames with redacted, bounded payloads.
4. Preserve deterministic unsupported responses for queue-adjacent route families that remain outside the Session 02 MVP.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase03-session01-orchestration-requirements-and-safety-baseline` - provides the approved Phase 03 gap matrix, Session 02 ownership, and local-first safety baseline.
* [x] `phase02-session07-product-surface-validation-and-documentation-closeout` - provides browser and documentation closeout expectations for later Phase 03 consumers.
* [x] `phase01-session07-runtime-contract-documentation` - provides current REST, WebSocket, route-family, and privacy contract baselines.

### Required Tools/Knowledge

* Node 20+, npm workspaces, TypeScript, Express 4, `ws`, Biome, and Vitest.
* Existing protocol files in `packages/protocol/src/`, especially `events.ts`, `rest.ts`, `plans.ts`, and `index.ts`.
* Existing server patterns in `apps/server/src/server.ts`, `apps/server/src/lib/requestValidation.ts`, `apps/server/src/lib/unsupportedRoutes.ts`, `apps/server/src/ws/broadcaster.ts`, and current route tests.

### Environment Requirements

* No hosted service credentials are required.
* Local server auth, CORS, Origin, rate-limit, body-size, and loopback defaults must remain unchanged.
* Historical `EXAMPLES/` files remain evidence only and must not be copied into runtime code, stable docs, fixtures, or template defaults.

***

## 4. Scope

### In Scope (MVP)

* Maintainers can share queue state through protocol types - define entries, queue snapshots, queue transitions, queue events, and validation or rejection errors.
* Maintainers can share agent template state through protocol types - define templates, suggestions, constraints, defaults, and template validation errors.
* Local clients can create, list, update, and reject queue entries through schema-validated server contracts - keep entries bounded, ordered, and non-executing.
* Local clients can list approved local templates and receive template suggestions or validation failures - keep defaults compact and source-owned.
* Browser or future clients can receive queue and template WebSocket updates - emit counts and bounded metadata only.
* Implementers can verify local-only behavior with focused protocol and server tests - include validation failures and sensitive-field non-echo checks.

### Out of Scope (Deferred)

* Running queued tasks in a terminal or spawning agents - *Reason: Session 04 owns guarded actions and explicit permission boundaries.*
* Web orchestration panels or template picker UI - *Reason: Session 05 consumes the contracts after runtime behavior exists.*
* Subagent lineage or mission graph runtime - *Reason: Session 03 owns lineage after queue/template contracts exist.*
* CLI queue diagnostics and recovery commands - *Reason: Session 06 owns diagnostics after server state exists.*
* Hosted queues, shared queues, analytics, inbound webhook creation, War Room room relay, Docker isolation, or remote execution - *Reason: later phases require separate trust, consent, authorization, and audit models.*

***

## 5. Technical Approach

### Architecture

Protocol leads the change. Add queue and template domain types under `packages/protocol/src/`, export them from `packages/protocol/src/index.ts`, then reference them from REST and WebSocket contracts. The server imports those types and owns in-memory managers for local queue and template state.

Server route handlers should follow existing high-risk route patterns: `bodyValidator` for compact schema validation, bounded string and array fields, deterministic ordering for lists, no raw payload echo in errors, and no changes to auth, CORS, Origin, rate-limit, or body-size middleware. Mutating routes should emit WebSocket updates after state changes and treat duplicate or stale updates deterministically.

Unsupported queue-adjacent historical routes should remain explicit 501 responses unless the approved Session 02 subset implements them. This keeps the Phase 03 MVP honest while preserving the current route-family taxonomy.

### Design Patterns

* Protocol-first contracts: shared types live in `packages/protocol` before server behavior consumes them.
* In-memory bounded managers: server state stays local, deterministic, capped, and easy to reset in later recovery or erasure work.
* Compact validation envelopes: invalid queue and template requests return field-level errors without echoing prompts, commands, paths, tokens, or raw request bodies.
* Explicit unsupported taxonomy: queue-adjacent historical routes stay classified until intentionally implemented.

### Technology Stack

* TypeScript 5.9 in `packages/protocol` and `apps/server`.
* Express 4 route handlers and existing server middleware.
* WebSocket broadcasting through `apps/server/src/ws/broadcaster.ts`.
* Vitest tests in `packages/protocol/tests/` and `apps/server/tests/`.

***

## 6. Deliverables

### Files to Create

| File                                            | Purpose                                                                               | Est. Lines |
| ----------------------------------------------- | ------------------------------------------------------------------------------------- | ---------- |
| `packages/protocol/src/taskQueue.ts`            | Queue entry, snapshot, transition, event, request, response, and validation contracts | \~160      |
| `packages/protocol/src/agentTemplates.ts`       | Agent template, suggestion, constraint, default, and validation contracts             | \~150      |
| `apps/server/src/managers/taskQueue.ts`         | Bounded in-memory queue manager with create, list, update, and reject operations      | \~180      |
| `apps/server/src/managers/agentTemplates.ts`    | Local template catalog and suggestion validation manager                              | \~150      |
| `apps/server/src/routes/orchestration.ts`       | Queue and template REST routes plus WebSocket update emission                         | \~220      |
| `packages/protocol/tests/orchestration.test.ts` | Protocol contract tests for queue and template shapes                                 | \~140      |
| `apps/server/tests/orchestration.test.ts`       | Server route, validation, unsupported-route, and WebSocket tests                      | \~220      |

### Files to Modify

| File                                                                                                   | Changes                                                                                                                          | Est. Lines |
| ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `packages/protocol/src/index.ts`                                                                       | Export new queue and template modules                                                                                            | \~4        |
| `packages/protocol/src/events.ts`                                                                      | Add queue and template WebSocket event frames to `ServerEvent`                                                                   | \~40       |
| `packages/protocol/src/rest.ts`                                                                        | Add queue/template REST request and response contracts where shared by server and clients                                        | \~70       |
| `apps/server/src/server.ts`                                                                            | Instantiate managers and register orchestration routes after existing core routes                                                | \~20       |
| `apps/server/src/lib/unsupportedRoutes.ts`                                                             | Remove only implemented queue/template paths from planned catch-all classification and preserve unsupported queue-adjacent paths | \~30       |
| `docs/api/README_api.md`                                                                               | Document the local-only task queue and agent template contract boundaries                                                        | \~45       |
| `docs/api/event-api-hook-contracts.md`                                                                 | Record route-family and WebSocket contract status changes for Session 02                                                         | \~45       |
| `.spec_system/specs/phase03-session02-task-queue-and-agent-template-contracts/implementation-notes.md` | Implementation log, commands run, and validation notes                                                                           | \~90       |
| `.spec_system/specs/phase03-session02-task-queue-and-agent-template-contracts/security-compliance.md`  | Session security posture and sensitive-field validation notes                                                                    | \~80       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Queue and template protocol types are exported and covered by focused contract tests.
* [ ] Local queue entries can be created, listed, updated, and rejected through validated server routes.
* [ ] Local templates can be listed and used for bounded suggestions or validation failures without importing historical raw templates.
* [ ] Queue and template state changes emit compact WebSocket update frames.
* [ ] Queue-adjacent out-of-scope routes continue returning deterministic capability responses.

### Testing Requirements

* [ ] `npm --workspace packages/protocol run typecheck` passes.
* [ ] `npm --workspace apps/server run typecheck` passes.
* [ ] Focused Vitest coverage for protocol contracts and server routes passes.
* [ ] Manual validation confirms responses do not echo raw prompts, paths, commands, tokens, terminal output, or raw request bodies.

### Non-Functional Requirements

* [ ] All queue and template state remains local, in-memory, bounded, and non-executing.
* [ ] Existing auth, CORS, Origin, rate-limit, body-size, and loopback defaults are unchanged.
* [ ] List responses use bounded pagination or limits, validated filters where present, and deterministic ordering.
* [ ] Error responses remain compact and do not leak sensitive developer data.

### Quality Gates

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

***

## 8. Implementation Notes

### Key Considerations

* Session 02 is a contract and local state session, not an executor session.
* Queue entries should reference existing mission, hero, plan, or template IDs only as optional metadata; missing references should not crash route handlers.
* Template defaults must be project-owned, compact, and generic. Do not import or copy historical templates from `EXAMPLES/`.
* New WebSocket frames should carry IDs, state, counts, timestamps, and safe summaries rather than raw prompts, command bodies, file contents, terminal output, or transcripts.

### Potential Challenges

* Route scope creep: implement only approved task queue and agent template endpoints; keep broad historical queue, issue, usage, skill, and session routes classified as planned or unsupported.
* Contract drift: avoid defining duplicate queue or template shapes inside `apps/server`; import protocol types instead.
* Privacy drift: route validation and test fixtures must avoid raw sensitive examples and assert that invalid responses do not echo raw request content.
* Later-session coupling: design optional references for plans, missions, heroes, and templates without requiring Sessions 03 or 04 behavior.

### Relevant Considerations

* \[P01] **Redaction is boundary-specific**: queue, template, WebSocket, export, replay, adapter, and future external-transfer payloads must use boundary-appropriate redaction before leaving local manager state.
* \[P01-apps/server] **Local server boundary must stay conservative**: new routes and frames inherit auth, Origin/CORS, rate-limit, body-size, validation, and explicit failure defaults.
* \[P01-packages/protocol] **Protocol leads cross-package work**: queue and template types must be protocol-owned before server routes consume them.
* \[P01-apps/warroom+apps/web] **War Room is not wired into the web runtime yet**: queue and template work must not imply Worker federation or shared room state.
* \[P01] **Unified erasure still missing**: new local orchestration state should be bounded and easy to include in later reset or erasure workflows.
* \[P00-apps/adapters] **Chat adapters are outbound only**: queue and template contracts must not introduce inbound commands through webhook or chat paths.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Mutating queue routes could process duplicate create or update requests and create confusing state.
* WebSocket frames could expose too much request detail or unbounded metadata to broad clients.
* Queue-adjacent historical routes could accidentally appear shipped if unsupported classification changes are too broad.

***

## 9. Testing Strategy

### Unit Tests

* Protocol tests for queue entry, queue snapshot, transition, template, suggestion, validation error, and event discriminants.
* Server manager tests or route-level tests covering create, list, update, reject, template list, suggestion validation, bounds, and deterministic ordering.

### Integration Tests

* Server route tests for compact invalid request envelopes, no raw body echo, auth inheritance where existing server auth tests apply, and unsupported queue-adjacent route preservation.
* WebSocket test for queue/template update emission after mutating route calls.

### Manual Testing

* Start the server in test mode or use route tests to exercise the new local endpoints and verify they do not execute commands.
* Inspect docs and route responses to confirm local-only wording and no hosted queue, War Room, inbound webhook, or analytics claims.

### Edge Cases

* Empty, oversized, malformed, duplicate, stale, and unknown queue entries.
* Missing mission, hero, plan, or template references.
* Invalid template IDs, unsupported template constraints, and too many suggestion inputs.
* Unknown or broad historical queue-adjacent routes.
* WebSocket clients connecting after local queue state exists.

***

## 10. Dependencies

### External Libraries

* None expected. Use existing TypeScript, Express, `ws`, and Vitest tooling.

### Other Sessions

* **Depends on**: `phase03-session01-orchestration-requirements-and-safety-baseline`
* **Depended by**: `phase03-session03-subagent-lineage-and-mission-graph-runtime`, `phase03-session04-guarded-local-action-runtime`, `phase03-session05-web-orchestration-cockpit-controls`, `phase03-session06-cli-diagnostics-and-recovery-controls`, `phase03-session07-orchestration-validation-and-documentation-closeout`

***

## Next Steps

Run the implement workflow step to begin AI-led implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase03-session02-task-queue-and-agent-template-contracts/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.
