> For the complete documentation index, see [llms.txt](https://faction-os.gitbook.io/faction-os-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase19-session11-templates-and-planning-context/spec.md).

# Session Specification

**Session ID**: `phase19-session11-templates-and-planning-context` **Phase**: 19 - Orchestration Command Center Execution **Status**: Not Started **Created**: 2026-06-26 **Package**: null **Package Stack**: mixed

***

## 1. Session Overview

This session makes templates and planning context actionable inside the Orchestration command center. It expands the current static local template catalog into detailed role blueprints with workflow instructions, constraints, model labels, prompt previews, read-only/tool-scope badges, and source-aware suggestions from mission, queue, Quest Board, analysis, project scan, and memory context.

It is next because Phase 19 Sessions 03 and 04 completed the web shell, store, campaign workbench, and queue mutation foundations. Sessions 05 through 10 added attention, permissions, executor posture, file/git, lineage, and mission artifacts, so Session 11 can now connect templates to queue creation, campaign planning inputs, source attribution, and auto-improvement attention without skipping prerequisites.

The session keeps execution local-first and guarded. Templates may create queue entries and seed planning context, but they do not execute commands, spawn heroes, transfer transcripts, or claim custom template storage. Raw prompts, transcript text, file contents, diffs, terminal output, broad absolute paths, and provider payloads remain out of broad Orchestration surfaces.

***

## 2. Objectives

1. Expand shared template and queue-source contracts so template details, suggestion rationale, safe source attribution, and memory context can move across protocol, server, and web boundaries.
2. Add server-owned planning-context behavior for template suggestions, queue-from-template preview/create, source links, memory category filters, and failed-work auto-improvement proposals.
3. Add a web Template Workbench and planning-context controls with searchable templates, preview, duplicate-trigger protection, loading/empty/error/offline states, and product-facing copy only.
4. Cover protocol, server, API, store, and UI behavior with focused tests plus validation commands.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase19-session03-web-shell-and-store` - command-center API helpers, Zustand slices, shell components, and drawer state
* [x] `phase19-session04-campaign-workbench` - campaign preview/create/refine flows and queue mutation controls
* [x] `phase19-session05-attention-and-permissions` - attention records and bounded decision behavior for follow-up proposals
* [x] `phase19-session09-heroes-and-lineage` - mission graph and hero lifecycle links used by selected context
* [x] `phase19-session10-mission-artifacts` - workpad, evidence, verification, and review links for failed-work context

### Required Tools Or Knowledge

* Node 26.2.0+ and npm workspaces
* Vitest root test runner
* Existing `AgentTemplateManager`, `TaskQueueManager`, and command-center route patterns
* Existing Quest Board suggestion snapshot and memory store shapes
* Existing web Orchestration panes, drawer, API, and store slices

### Environment Requirements

* Local workspace dependencies installed with `npm install`
* No database, hosted account, provider credential, War Room Worker, remote executor, or custom template storage required

***

## 4. Scope

### In Scope (MVP)

* Operators can search and inspect local templates with description, role, category, model label, workflow instruction, constraints, default priority, approval requirement, max queue items, context label, prompt preview, read-only badge, and tool-scope badge.
* Operators can request template suggestions from selected mission, queue item, Quest Board issue, analysis item, project scan item, session follow-up, auto-improvement candidate, and transcript-mined memory context with bounded rationale and deterministic ordering.
* Operators can preview and create queue entries from templates with idempotency protection, source links, duplicate-trigger prevention while in-flight, and explicit error mapping.
* Queue items and campaign details can show safe source attribution for suggestions, scan issues, analysis results, project scan items, session follow-ups, auto-improvement candidates, and memory records.
* Campaign preview/create/refine flows can include or exclude memory categories before plan generation, with freshness, confidence, category, and source task attribution in detail views.
* Failed verification, review, execution, or task context can produce bounded auto-improvement proposals in the attention queue without running any executor behavior.

### Out Of Scope (Deferred)

* Custom template storage - Reason: the Session 11 stub defers this unless a current settings schema owns it, and no such schema was found in the current route and manager surfaces.
* Raw transcript display inside Orchestration rows - Reason: the stub excludes it and the privacy boundary blocks raw transcript text outside scoped local detail surfaces.
* Template-driven hero spawn execution - Reason: executor readiness, permission, audit, and lifecycle execution remain guarded; this session may show spawn readiness metadata but must not execute or imply spawn availability.
* Hosted or shared template catalogs - Reason: hosted services and War Room transfer remain disabled-default guardrails without consent, minimization, authorization, tests, and docs.
* Full plan-decomposer LLM integration - Reason: campaign preview/create currently accepts structured tasks; this session adds memory filters and context metadata without requiring provider transfer.

***

## 5. Technical Approach

### Architecture

Protocol contracts will lead the cross-package work. `packages/protocol` will extend the agent template and task queue types with bounded metadata, source attribution, and memory context fields so server responses and web store normalization cannot drift. Existing parser helpers should reject raw fields and unsafe ids before data reaches UI state.

The server will keep template and planning-context behavior behind manager/helper boundaries. `AgentTemplateManager` remains the source for built-in local templates, while a new planning-context helper derives suggestion inputs from selected queue, mission, Quest Board, analysis, scan, session summary, mission artifact, and memory records. Queue-from-template uses `TaskQueueManager` idempotency and route-level in-flight locks. Auto-improvement proposals use the existing command-center attention model and safe target refs.

The web app will add a focused `TemplateWorkbench` inside the Orchestration command panes. It will consume typed API helpers, render searchable templates and source badges, preview queue items before creation, and expose memory include/exclude controls before campaign planning. Existing store reducers must normalize event and REST payloads before mutation so malformed template or source frames cannot blank the cockpit.

### Design Patterns

* Protocol-first contracts: shared template/source/memory fields are declared and parsed before package-specific behavior.
* Manager-owned state: suggestion scoring, queue preview/create, idempotency, and attention proposals stay behind server boundaries.
* Pure normalization before store mutation: web reducers and helpers sanitize partial or malformed payloads before touching Zustand state.
* Product-surface UI: broad surfaces show safe labels, badges, counts, and summaries, with diagnostics confined to tests and docs.

***

## 6. Deliverables

### Files To Create

| File                                                          | Purpose                                                                                                                                  | Est. Lines |
| ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `apps/server/src/lib/templatePlanningContext.ts`              | Server helper for safe source links, memory filters, template suggestion inputs, queue preview payloads, and auto-improvement candidates | \~260      |
| `apps/web/src/lib/templatePlanningContext.ts`                 | Web view models for template cards, source badges, memory context controls, prompt previews, and queue preview summaries                 | \~220      |
| `apps/web/src/components/orchestration/TemplateWorkbench.tsx` | Searchable Template Workbench with details, source links, memory filters, preview, create action, and complete UI states                 | \~320      |
| `apps/server/tests/templatePlanningContext.test.ts`           | Unit coverage for source normalization, memory filters, template scoring inputs, queue preview, and auto-improvement proposals           | \~240      |
| `apps/web/tests/TemplateWorkbench.test.tsx`                   | UI coverage for template details, source badges, memory controls, preview/create actions, and failure states                             | \~240      |

### Files To Modify

| File                                                                  | Changes                                                                                                                                         | Est. Lines |
| --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ---------- |
| `packages/protocol/src/agentTemplates.ts`                             | Add bounded template detail, prompt preview, category/model/tool-scope/read-only metadata, suggestion rationale, and planning context contracts | \~170      |
| `packages/protocol/src/taskQueue.ts`                                  | Add safe source attribution references for template-created queue entries and planning context links                                            | \~110      |
| `packages/protocol/src/orchestrationCommandCenter.ts`                 | Add memory context, source target, and auto-improvement target shapes where command-center records need shared parsing                          | \~150      |
| `packages/protocol/tests/orchestration.test.ts`                       | Cover template metadata, queue source references, and blocked raw planning-context fields                                                       | \~130      |
| `apps/server/src/managers/agentTemplates.ts`                          | Expand built-in templates, scoring, details, event templates, and queue preview support                                                         | \~220      |
| `apps/server/src/managers/taskQueue.ts`                               | Preserve source attribution on create/update/event entries and enforce safe bounded references                                                  | \~90       |
| `apps/server/src/managers/planCampaignManager.ts`                     | Accept memory category filters and carry safe context metadata through preview/create/refine responses                                          | \~120      |
| `apps/server/src/managers/orchestrationCommandCenter.ts`              | Save auto-improvement attention items and source-linked command-center metadata for failed-work context                                         | \~120      |
| `apps/server/src/lib/orchestrationValidation.ts`                      | Parse template suggestion, queue preview, queue-from-template, and source attribution request bodies                                            | \~160      |
| `apps/server/src/lib/commandCenterValidation.ts`                      | Parse memory include/exclude filters on campaign preview/create/refine inputs                                                                   | \~90       |
| `apps/server/src/routes/orchestration.ts`                             | Add template detail, suggestion, preview, and queue-from-template routes with schema validation and duplicate-trigger handling                  | \~150      |
| `apps/server/src/routes/commandCenter.ts`                             | Pass memory filters into campaign preview/create/refine and emit source-aware response metadata                                                 | \~70       |
| `apps/server/src/server.ts`                                           | Wire suggestion and memory context dependencies into the orchestration routes without adding hosted transfer                                    | \~50       |
| `apps/server/tests/orchestration.test.ts`                             | Cover template detail, suggestion, preview, create, idempotency, source links, and memory filters                                               | \~220      |
| `apps/server/tests/planCampaignManager.test.ts`                       | Cover memory category include/exclude behavior in campaign preview/create/refine                                                                | \~140      |
| `apps/server/tests/commandCenterRoutes.test.ts`                       | Cover auto-improvement attention proposals and source-linked command-center responses                                                           | \~120      |
| `apps/web/src/lib/orchestrationApi.ts`                                | Add template detail/suggestion/preview/create clients plus memory filter fields on campaign calls                                               | \~180      |
| `apps/web/src/lib/orchestrationUi.ts`                                 | Add product-facing copy helpers for template metadata, source badges, memory freshness, and queue preview state                                 | \~120      |
| `apps/web/src/store/useGameStore.ts`                                  | Normalize template detail updates, planning context state, source badges, memory filters, and stale selections                                  | \~160      |
| `apps/web/src/components/orchestration/CommandCenterPanes.tsx`        | Wire `TemplateWorkbench` into the campaigns/planning area with queue and campaign callbacks                                                     | \~90       |
| `apps/web/src/components/orchestration/CampaignWorkbench.tsx`         | Add memory category include/exclude controls before preview/create/refine with accessible labels                                                | \~140      |
| `apps/web/src/components/orchestration/OrchestrationCurrentState.tsx` | Show compact source attribution and template details in current-state summaries                                                                 | \~90       |
| `apps/web/src/components/orchestration/OrchestrationDrawer.tsx`       | Render template, queue source, memory, and auto-improvement detail rows with safe metadata only                                                 | \~120      |
| `apps/web/tests/orchestrationApi.test.ts`                             | Cover new API clients, in-flight duplicate guards, and parser failures                                                                          | \~160      |
| `apps/web/tests/commandCenterStore.test.ts`                           | Cover template/source/memory reducer normalization and malformed frame handling                                                                 | \~120      |
| `apps/web/tests/OrchestrationPanel.test.tsx`                          | Cover Template Workbench integration, queue-from-template, memory filter plumbing, and product-facing copy                                      | \~220      |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Template details include safe description, model, category, workflow instruction, constraints, default priority, approval requirement, max queue items, max context label, prompt preview, read-only badge, and tool-scope badge.
* [ ] Template suggestions can be requested from selected mission, queue, Quest Board issue, analysis, project scan, session follow-up, auto-improvement, and memory context.
* [ ] A template can preview and create a queue item with an idempotency key and source attribution.
* [ ] Queue and campaign details show why an item exists and which safe signal or memory record informed it.
* [ ] Memory category filters affect campaign preview/create/refine requests and display freshness, confidence, category, and source task labels.
* [ ] Failed work can produce a bounded auto-improvement attention proposal without executing any command or spawning a hero.

### Testing Requirements

* [ ] Unit tests written and passing for protocol parsers, server planning-context helpers, managers, and web view models.
* [ ] Route tests written and passing for template detail, suggestion, preview, queue-from-template, campaign memory filters, and auto-improvement attention proposals.
* [ ] Component and store tests written and passing for Template Workbench rendering, source links, memory controls, queue preview, in-flight duplicate guards, and malformed event handling.
* [ ] Verification scenarios completed for loading, empty, error, offline, disconnected, duplicate, stale, unsupported spawn, blocked raw payload, and no-memory states.

### Non-Functional Requirements

* [ ] Raw prompts, command bodies, diffs, terminal output, file contents, transcript text, provider payloads, tokens, secrets, broad absolute paths, logs, replay buffers, and export payloads stay blocked from broad template and source-attribution surfaces.
* [ ] Template suggestion and memory context lists are bounded, deterministically ordered, and safe when source records are missing or malformed.
* [ ] UI controls have accessible names, visible focus states, keyboard support, and product-facing copy only.
* [ ] Existing queue, campaign, attention, Quest Board, and command-center behavior remains backward compatible.

### Quality Gates

* [ ] All files ASCII-encoded
* [ ] Unix LF line endings
* [ ] Code follows project conventions
* [ ] Primary user-facing surfaces contain product-facing copy only
* [ ] Focused protocol, server, and web tests pass
* [ ] Workspace typecheck passes
* [ ] Root format check passes

***

## 8. Implementation Notes

### Working Assumptions

* Cross-package session scope: The analysis script reports the selected candidate package as `null`, while the stub names `apps/server` and `apps/web`; planning can proceed with `Package: null` because the work intentionally spans protocol, server, and web.
* Protocol updates are required: `CONSIDERATIONS.md` says protocol leads cross-package queue and event work, and current `agentTemplates.ts` and `taskQueue.ts` lack the fields needed for template details and source attribution.
* Memory context can use the existing local memory store: `apps/server/src/lib/memoryStore.ts` exposes transcript-mined findings with type, confidence, tags, and source task IDs, so Session 11 can expose bounded metadata without displaying raw transcript text.
* Custom template storage remains deferred: the current inspected settings and template surfaces do not define schema ownership for custom templates, so built-in local templates remain source-owned in this session.

### Conflict Resolutions

* The stub says templates can support queue item creation and later hero spawn, while current executor and hero lifecycle behavior remains guarded. The chosen interpretation is to implement queue-from-template now and show spawn readiness or unavailable metadata only; actual spawn execution stays out of scope until executor-ready lifecycle work supports it.
* The Phase 19 appendix references rich historical template artifacts, while the master PRD says `EXAMPLES/` is evidence only. The chosen interpretation is to reproduce the needed behavior and metadata shape in current source-owned contracts without importing historical code or prompts verbatim.
* The current template route emits compact `agent_template_update` frames, while Session 11 needs detail metadata. The chosen interpretation is to keep compact events compatible and hydrate full details through REST and normalized store state.

### Key Considerations

* Queue entries should preserve both legacy `references.templateId` compatibility and the new source attribution fields.
* Memory filter defaults should be conservative and local-only; unavailable memory must not block template or campaign workflows.
* Auto-improvement proposals must be attention items with safe summaries, not executor runs.
* Source links should prefer safe ids and relative labels over absolute paths or raw payloads.

### Potential Challenges

* Template suggestions can become noisy when many sources are selected: cap suggestions, cap source badges, and sort deterministically by score, recency, and id.
* Campaign memory filters can drift between preview and create: include the selected categories and generated idempotency key in both requests.
* Queue-from-template can duplicate work: use route locks plus manager idempotency keys and surface duplicate results clearly.
* Source records may be stale or deleted: render missing references as unavailable source labels without blanking panels.

### Relevant Considerations

* \[P03] **Real executors remain unimplemented by design**: Template spawn stays metadata/unavailable until capability, authorization, audit, tests, and docs exist.
* \[P03-packages/protocol] **Protocol leads cross-package work**: Add shared template/source/memory contracts before server and web behavior.
* \[P03-apps/server] **Local server boundary must stay conservative**: New routes need validation, auth/rate-limit inheritance, compact errors, and explicit unavailable behavior.
* \[P07] **Redaction is boundary-specific**: Source attribution must minimize queue, template, Quest Board, analysis, memory, attention, and command-center payloads separately.
* \[P18-apps/server] **Manager-owned persistence and snapshot emission**: Keep suggestion and queue state behind manager boundaries so broadcasts and filtering stay aligned.
* \[P18-apps/web] **Pure normalization before store mutation**: Normalize template/source/memory payloads before updating Zustand.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Queue-from-template or campaign preview actions could double-submit without in-flight and idempotency protection.
* Template, memory, or source payloads could leak raw prompts, transcripts, broad paths, or file contents into broad UI rows.
* Missing or malformed source records could blank the Template Workbench or queue details.
* Memory filter state could persist incorrectly across reopened campaign/template contexts.

***

## 9. Testing Strategy

### Unit Tests

* Protocol parser tests for template metadata, source attribution references, memory context, and blocked raw planning fields.
* Server helper tests for source normalization, memory include/exclude filtering, template scoring, queue preview creation, and auto-improvement proposal generation.
* Web helper tests for template card view models, prompt preview labels, source badges, memory freshness labels, and deterministic ordering.

### Integration Tests

* REST route tests for `/agent-templates`, `/agent-templates/:id`, template suggestions, template queue preview/create, and duplicate idempotency behavior.
* Campaign route tests for memory category include/exclude fields on preview, create, and refine.
* Command-center route/manager tests for auto-improvement attention proposals and safe source-linked metadata.
* Store reducer tests for compact template events, full template detail hydration, source badges, memory filters, and malformed payload handling.

### Runtime Verification

* Start from an empty queue and create a queue entry from a template preview; verify duplicate create returns the existing queue item.
* Select Quest Board/analysis/project-scan style context and verify suggestion rationale uses safe labels only.
* Toggle memory categories before campaign preview/create and verify request payloads carry the selected categories.
* Simulate failed verification or task context and verify an auto-improvement attention item is created without executor activity.
* Toggle offline/disconnected and malformed-response states and confirm the Template Workbench stays readable.

### Edge Cases

* Unknown template id
* Missing selected source record
* No memory findings
* Excluded memory category
* Duplicate idempotency key
* Queue capacity reached
* Malformed source attribution
* Unsupported template spawn
* Raw prompt, transcript, file content, terminal output, diff, token, or absolute path in request payload
* Reopening campaign or template context after state changes

***

## 10. Dependencies

### Other Sessions

* Depends on: `phase19-session03-web-shell-and-store`, `phase19-session04-campaign-workbench`, `phase19-session05-attention-and-permissions`, `phase19-session09-heroes-and-lineage`, `phase19-session10-mission-artifacts`
* Depended by: `phase19-session12-terminal-and-containers`, `phase19-session13-collaboration-and-handoff`, `phase19-session14-channels-and-scope`, `phase19-session15-metrics-and-notifications`, `phase19-session16-ergonomics-and-documentation`

***

## Next Steps

Run the `implement` workflow step to begin implementation.


---

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

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

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

```
GET https://faction-os.gitbook.io/faction-os-docs/.spec_system/archive/sessions/phase19-session11-templates-and-planning-context/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.
