A thin wrapper that invokes the desplega:planning skill with autonomy controls.
When Invoked
Parse autonomy mode from arguments:
Check for --autonomy=autopilot|critical|verbose flag
If provided file has autonomy: in frontmatter, use that as default
Otherwise, ask the user via AskUserQuestion:
code
How much should I check in with you during planning?
- Autopilot: Research and create plan independently, present for final review
- Critical questions (Recommended): Ask only for major design decisions
- Verbose: Check in at each step, validate approach throughout
ALWAYS invoke the desplega:planning skill:
Pass any file paths or task descriptions
Pass the autonomy mode determined above
Let the skill handle all planning logic
If no input provided:
Respond with:
code
I'll help you create a detailed implementation plan. Please provide:
1. The task description
2. Any relevant context, constraints, or specific requirements
3. Links to related research or previous implementations
The research has autonomy: critical in its frontmatter. Let me invoke the planning skill.
Assistant
Let me start by gathering preferences and reading context files in parallel.
Assistant
Preferences noted: commits after each phase, file-review for the plan. Let me gather codebase context before formulating the plan structure.
Assistant
Launched 5 background research agents to analyze the codebase. Waiting for results before presenting the plan structure.
Assistant
Got the migration/DB analysis back. Key findings: latest migration is 012, next is 013. Config scope resolution is repo > agent > global. Waiting for the remaining agents.
User
How to Add a New Migration
Based on the runner's logic:
Create /Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/be/migrations/013_<descriptive_name>.sql (next number after 012).
Write forward-only SQL. Use IF NOT EXISTS on CREATE TABLE/CREATE INDEX for safety.
On next startup, runMigrations() will detect it as pending (not in _migrations table), execute the SQL inside a transaction, and record it in _migrations with a SHA-256 checksum.
Test with both a fresh database (rm agent-swarm-db.sqlite && bun run start:http) and an existing database to verify idempotency.
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-20-fet-template-registry/1737807a-29e7-4cf2-9870-f5fc07b93de7/tasks/a5fd7d14fe26e203a.output
The initial status is computed from the options via a ternary chain:
offeredTo is set --> "offered"
agentId is set --> "pending"
status === "backlog" --> "backlog"
Otherwise --> "unassigned"
Metadata Inheritance (lines 1789-1820)
Two layers of Slack/AgentMail metadata inheritance:
Parent task inheritance (lines 1789-1808): If parentTaskId is provided, the function fetches the parent task and copies over five fields (slackChannelId, slackThreadTs, slackUserId, agentmailInboxId, agentmailThreadId) -- but only if they are not already explicitly set in options. This is a "fill in the blanks" pattern.
Source task inheritance (lines 1813-1820): If creatorAgentId is set AND slackChannelId was still not filled (by explicit param or parent inheritance) AND sourceTaskId is set, it fetches the source task and copies its Slack metadata. The comment at line 1812 notes that sourceTaskId comes from the adapter's X-Source-Task-Id header.
The priority order for Slack metadata is: explicit params > parentTaskId > sourceTaskId.
Database Insert (lines 1822-1871)
A single INSERT ... RETURNING * with 36 positional parameters. JSON serialization is applied to tags (line 1842) and dependsOn (line 1844). The offeredAt timestamp is set to now only if offeredTo is present (line 1846).
Side Effects (lines 1875-1897)
Two fire-and-forget operations (both wrapped in try {} catch {}):
Log entry (lines 1876-1883): Creates an agent_log entry with event type "task_offered" or "task_created" depending on status.
Workflow event (lines 1885-1897): Dynamically imports the workflow event bus and emits a "task.created" event with the task's core fields. The dynamic import (import("../workflows/event-bus")) means the workflow module is lazily loaded.
CREATE TABLE IF NOT EXISTS swarm_config (
id TEXT PRIMARY KEY,
scope TEXT NOT NULL CHECK(scope IN ('global', 'agent', 'repo')),
scopeId TEXT,
key TEXT NOT NULL,
value TEXT NOT NULL,
isSecret INTEGER NOT NULL DEFAULT 0,
envPath TEXT,
description TEXT,
createdAt TEXT NOT NULL,
lastUpdatedAt TEXT NOT NULL,
UNIQUE(scope, scopeId, key)
);
Three scopes: global, agent, repo. For global scope, scopeId is NULL. For agent/repo, scopeId holds the agent or repo ID.
Row Mapping (db.ts:4858-4871)
rowToSwarmConfig() converts the raw SQLite row (with isSecret as integer 0/1) into the SwarmConfig type (with isSecret as boolean).
Secret Masking (db.ts:4876-4878)
maskSecrets() replaces value with "********" for any entry where isSecret is true.
Env File Sync (db.ts:4884-4918)
writeEnvFile() is called after upserts when envPath is set. It groups configs by envPath, reads the existing file, finds lines starting with KEY=, replaces them in-place (or appends), and writes back. This keeps .env files in sync with DB config values.
CRUD Operations
getSwarmConfigs(filters?) (lines 4923-4951): Dynamically builds a WHERE clause from optional scope, scopeId, key filters. Returns all matching rows ordered by key ASC.
getSwarmConfigById(id) (lines 4956-4961): Simple lookup by primary key.
The runMigrations(db) function at line 64 executes in five phases:
Phase 1: Tracking Table (lines 66-73)
Creates _migrations table (CREATE TABLE IF NOT EXISTS) with columns: version (integer PK), name, applied_at, checksum.
Phase 2: Load Migration Files (lines 76-109)
Resolves the migrations directory via import.meta.dir (line 79). If that path is unreadable (happens in compiled Bun binaries where import.meta.dir resolves to /$bunfs/root), falls back to process.env.MIGRATIONS_DIR (line 84).
Reads all .sql files from the directory, sorts them alphabetically (line 97).
For each file: parses the version number from the numeric prefix before the first _ (line 100), reads the SQL content, and computes a SHA-256 checksum (lines 102-103).
Phase 3: Get Applied Migrations (lines 112-122)
Queries _migrations table and builds a Map<number, AppliedMigration> of already-applied versions.
This handles pre-migration-system databases. If applied.size === 0 (no migrations recorded yet), it calls shouldBootstrapInitialMigration(db) (line 40). That function checks if all 18 BASELINE_TABLES (lines 19-38) already exist in sqlite_master. Two outcomes:
All baseline tables exist (line 52 returns true): The runner marks 001_initial as applied without executing it (lines 133-141). The schema already exists.
Tables are missing/incomplete (returns false): The runner logs that the DB is incomplete (line 149) and falls through, so 001_initial will be executed normally in Phase 5.
Note: If sqlite_master has zero non-_migrations tables (line 47-48), the function returns false -- this is a fresh database, so 001 should run normally.
Phase 5: Apply Pending Migrations (lines 156-187)
Iterates all migrations in order. For each:
Already applied: Verifies checksum matches (lines 161-167). On mismatch, logs a warning but does not fail or re-apply.
Not yet applied: Wraps the SQL execution + INSERT INTO _migrations in a single db.transaction() (lines 175-183). This makes each migration atomic -- if the SQL fails, the tracking row is also rolled back.
Performance is logged via performance.now() (lines 173, 185).
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/server.ts -- MCP server creation and tool registration (lines 105-149)
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/scripts/generate-openapi.ts -- OpenAPI spec generation with side-effect imports
<total_tokens>32263</total_tokens><tool_uses>14</tool_uses><duration_ms>94227</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-20-fet-template-registry/1737807a-29e7-4cf2-9870-f5fc07b93de7/tasks/a0a75509de2e9b760.output
User
Key Structural Conventions Summary
For a new REST endpoint file (src/http/<feature>.ts):
Define route constants at module level using route({...}) with method, path, pattern, summary, tags, and Zod schemas for params/query/body
Export a single handle<Feature>() async function returning Promise<boolean>
Chain if blocks: match() then parse() then business logic then json()/jsonError()
Return false at the end if nothing matched
Order specific patterns before wildcard patterns within the file
For registering the handler (src/http/index.ts):
Import the handler function
Add a () => handle<Feature>(req, res, pathSegments, queryParams) entry to the handlers array
For OpenAPI (scripts/generate-openapi.ts):
Add a side-effect import of the handler file
For a new MCP tool directory (src/tools/<feature>/):
One file per operation (set, get, list, delete)
Each exports register<Operation>Tool = (server: McpServer) => { createToolRegistrar(server)(...) }
Barrel index.ts re-exports all
Guard on requestInfo.agentId first
Return both content (text) and structuredContent (typed)
Set appropriate annotations hint
For registering tools (src/server.ts):
Import from the barrel
Call each register*Tool(server) in createServer()
User
Pattern 2: MCP Tools via createToolRegistrar()
2.1 Tool Registration Helper (src/tools/utils.ts)
createToolRegistrar(server) at line 95 returns a curried function that wraps server.registerTool(). The wrapper:
Accepts (name, config, callback) where config has title, description, inputSchema, outputSchema, and annotations.
Intercepts the MCP SDK's meta argument to extract RequestInfo via getRequestInfo(meta) at line 105 -- pulling sessionId, agentId (from x-agent-id header), and sourceTaskId (from x-source-task-id header).
Injects requestInfo as the second argument to the callback, so each tool gets (args, requestInfo, meta).
2.2 Tool File Structure (one tool per file)
Each tool file in src/tools/swarm-config/ exports a single register<Name>Tool function that takes McpServer and calls createToolRegistrar(server)(...).
The callback structure for every tool follows a consistent pattern:
Agent ID guard -- Check requestInfo.agentId, return error if missing. This is the first thing in every callback.
try/catch block -- All business logic inside try, with a catch that extracts error.message.
Dual response format -- Every return value includes both:
content: [{ type: "text", text: "..." }] -- human-readable text for LLM consumption
structuredContent: { success, message, ...data } -- machine-parseable structured data
yourAgentId -- Included in structuredContent on both success and error paths (except the missing-agent-id guard).
The annotations field on each tool config signals intent:
readOnlyHint: true -- for get/list tools (get-config.ts:14, list-config.ts:14)
idempotentHint: true -- for set/upsert tools (set-config.ts:14)
destructiveHint: true -- for delete tools (delete-config.ts:13)
These are registered in the "always registered" section (line 137 comment) -- not gated by any capability flag. Capability-gated tools use if (hasCapability("...")) checks visible later in the file.
User
Pattern 1: REST Endpoints via route() Factory
1.1 Route Definition (src/http/route-def.ts)
The route() factory at line 65 accepts a RouteDef object and returns a RouteHandle with two methods:
match(method, pathSegments) (line 77): Delegates to matchRoute() from src/http/utils.ts:69. Compares HTTP method (uppercased) and path segments against the route's pattern. The exact flag (default true) controls whether trailing segments are rejected.
parse(req, res, pathSegments, queryParams) (line 87): Extracts and validates three parts:
Path params (line 90-98): Dynamic segments are identified by null entries in pattern. Param names are extracted from the OpenAPI-style path string (e.g., {id} in /api/config/{id}). Each null in the pattern is paired with the next param name, and the corresponding pathSegments[i] value is assigned.
Query params (line 102): Parsed via Object.fromEntries(queryParams) and validated against the query Zod schema.
Body (line 103): Read via parseBody(req) from src/http/utils.ts:40 (buffers chunks, JSON.parse) and validated against the body Zod schema.
On ZodError, it calls jsonError(res, ..., 400) at line 112-117 and returns null.
Every call to route() also pushes the RouteDef into the global routeRegistry array at line 72. This registry is consumed by the OpenAPI generator.
1.2 Handler File Structure (src/http/config.ts)
The config handler file follows a two-section layout:
Section 1: Route definitions (lines 16-96) -- One const per route, each calling route({...}):
Route
Method
Path
Pattern
Key schemas
getResolvedConfigRoute
GET
User
Analysis: REST Endpoint and MCP Tool Patterns (Config as Precedent)
Overview
The codebase follows two parallel patterns for exposing functionality: (1) REST endpoints defined via a route() factory in src/http/ files, and (2) MCP tools defined via a createToolRegistrar() helper in src/tools/ files. Both patterns share the same underlying DB functions from src/be/db.ts but have distinct structural conventions. The config feature (src/http/config.ts + src/tools/swarm-config/) implements both sides and serves as the canonical template.
Assistant
Three agents back with solid findings. Let me review the remaining two while I process what I have. The key findings give me enough to surface the critical design decision.
Assistant
Got it, Taras. That's a better concept — a static header (code-defined, always-on, ensures the essential event reference like [GitHub PR #{{pr.number}}] is never lost) plus a customizable body template. The header lives in code with the event definition and is always prepended, never overridable.
Let me present the plan structure.
Decisions locked:
Scope precedence: agent > repo > global
Template shape: Code-defined header (always prepended, not in DB) + customizable body (in DB)
Interpolation: Wrap existing interpolate() from src/workflows/template.ts
Seeded defaults: Current hardcoded prompts seeded as is_default: true
Audit history: prompt_template_history table
Proposed phasing:
Foundation — DB schema (migration 013), types, CRUD functions, resolver core (interpolation + scope chain + {{@template[...]}} expansion). No behavior change.
API Surface — REST endpoints + MCP tools following the config pattern. Management ready before any refactor.
Default Template Seeding — Extract all current hardcoded prompts into EventTemplate definitions with headers + default bodies + variable contracts. Seed on startup. Browsable immediately.
Refactor: GitHub Handlers — Replace 12 hardcoded prompts with registry.resolve(). Highest-impact, tests the full pipeline.
Refactor: System Prompts — Replace base-prompt.ts constants with registry lookups. Most complex due to truncation/budgeting.
Each phase is independently testable and produces working code. Phases 4-6 are the progressive refactor — one source at a time.
Assistant
Let me check on the remaining background agents and then write the detailed plan.
Assistant
Both agents are still running but I have enough context from the research + 3 completed agents. Let me write the plan now.
Assistant
Plan written. Let me open it in file-review for your inline feedback.
Assistant
Taras, the plan is open in file-review at thoughts/taras/plans/2026-03-20-prompt-template-registry.md. Take your time adding inline comments — I'll be notified when you close it.
User
Key Differences Between the Two Engines
Aspect
template.ts (dot-path)
templates.ts (flat-key)
Regex
/\{\{([^}]+)\}\}/g
/\{\{(\w+)\}\}/g
Path resolution
Dot-separated traversal of nested objects
Single flat key lookup
Unresolved behavior
Replaced with "", tracked in unresolved[]
Left as-is ({{name}}), not tracked
Used by
Workflow engine + executors at runtime
Template instantiation (pre-execution)
Deep variant
deepInterpolate() walks trees
replaceVariables() walks trees
Context shape
Nested objects (workflow context with step outputs)
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/workflows/index.ts -- re-exports and initWorkflows() wiring
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/workflows/executors/base.ts -- ExecutorDependencies interface with string-only interpolate
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/workflows/engine.ts (lines 315-366) -- interpolation context building and deepInterpolate call site
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/types.ts (lines 670-686) -- WorkflowTemplateSchema / WorkflowTemplate type
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/tests/workflow-template.test.ts -- comprehensive test coverage for both functions
<total_tokens>29647</total_tokens><tool_uses>17</tool_uses><duration_ms>102547</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-20-fet-template-registry/1737807a-29e7-4cf2-9870-f5fc07b93de7/tasks/a1325031e25363442.output
User
How They Are Wired Into the System
Engine-level deep interpolation (engine.ts:355-366)
The workflow engine calls deepInterpolate(node.config, interpolationCtx) at line 356 before passing config to executors. The interpolationCtx is built at lines 316-340:
If node.inputs is defined, a scoped context is built by resolving each declared input via dot-path traversal of the global ctx. Built-ins trigger and input are always included.
If node.inputs is not defined, only trigger and input are exposed.
When unresolved.length > 0 (line 359), the engine logs a warning and stores the unresolved tokens in the step's diagnostics JSON field (lines 360-366). Execution still proceeds -- unresolved tokens do not block execution.
Executors that need to interpolate individual string fields (beyond the pre-interpolated config) use this dependency:
NotifyExecutor (executors/notify.ts:35): interpolates config.template against the full step context.
VcsExecutor (executors/vcs.ts:40-43): interpolates config.title and config.body.
ValidateExecutor (executors/validate.ts:109): interpolates the prompt.
RawLlmExecutor (executors/raw-llm.ts:35): interpolates the prompt.
Retry poller (retry-poller.ts:63-65)
The retry poller independently calls deepInterpolate(node.config, ctx) when re-executing a failed step. It does not check unresolved -- the return value is destructured but only value is used.
Template instantiation
instantiateTemplate and validateTemplateVariables are exported from workflows/index.ts:8 but have no import consumers in the src/ tree today. They are exposed as public API surface but not called internally by any other module.
export function validateTemplateVariables(
template: WorkflowTemplate,
provided: Record<string, unknown>,
): string[]
Iterates template.variables (typed as an array of {name, description, type, default?, required} per WorkflowTemplateSchema at types.ts:670-685). A variable is considered missing if: required === true AND the variable name is not a key in provided AND default is undefined. Returns the list of missing variable names.
2. instantiateTemplate() (templates.ts:31-54)
Signature:
typescript
export function instantiateTemplate(
template: WorkflowTemplate,
variables: Record<string, unknown>,
): WorkflowDefinition
Three-phase process:
Validate (line 36-39): Calls validateTemplateVariables(). Throws with the list of missing names if any are missing.
Resolve defaults (lines 42-49): Builds a resolved map. For each declared variable, uses the provided value if present, otherwise falls back to variable.default. Variables with neither are simply omitted from the resolved map.
Clone and replace (lines 52-53): Deep-clones template.definition via JSON.parse(JSON.stringify(...)), then calls replaceVariables().
3. replaceVariables() (templates.ts:59-74)
A private recursive function with the same tree-walk pattern as deepInterpolate:
function replaceStringPlaceholders(template: string, variables: Record<string, unknown>): string
Uses regex /\{\{(\w+)\}\}/g at line 80. Key differences from template.ts:
Flat keys only: The capture group (\w+) matches word characters only (no dots), so {{user.name}} would NOT match. This does flat variables[name] lookup, not dot-path resolution.
Unresolved tokens are preserved: If variables[name] is undefined, the original {{name}} placeholder is returned as-is (line 82: return _match), rather than being replaced with "".
Object values: JSON-stringified (line 83), same as template.ts.
No unresolved tracking: There is no unresolved[] array. Unresolved tokens silently remain in the output string.
Uses String.replace() with regex /\{\{([^}]+)\}\}/g at line 15. This matches anything inside double-curly braces that is not a } character.
For each match, the captured group (the path string) is trimmed and split on "." at line 16, producing an array of keys.
Walks the context object one key at a time (lines 18-24). At each step:
If the current value is null, undefined, or not an object, the path is pushed to unresolved and the token is replaced with "" (empty string) -- lines 19-21.
Otherwise, it descends: value = value[key] at line 23.
After walking all keys, if the final value is null or undefined, the path is added to unresolved and replaced with "" (lines 25-28).
If the final value is an object, it is passed through safeStringify() (line 29). Otherwise, it is coerced via String(value).
2. safeStringify() (template.ts:38-44)
A private helper that wraps JSON.stringify() in a try/catch. On circular reference errors (or any error), returns "[Circular]" instead of throwing.
3. Unresolved Token Tracking
Unresolved tokens are accumulated in a local string[] array (line 14). A token is considered unresolved in two cases:
The dot-path traversal hits a non-object (null, undefined, or primitive) before reaching the final key (lines 19-21).
The traversal completes but the final value is null or undefined (lines 25-27).
User
Analysis: Workflow Interpolation Engine
Overview
There are two distinct interpolation systems in the codebase. template.ts (singular) is the runtime interpolation engine used by the workflow execution engine -- it resolves {{dot.path.tokens}} against a nested context object and tracks unresolved tokens. templates.ts (plural) is the workflow template instantiation system -- it resolves {{flatKey}} tokens against a flat variables map when turning a WorkflowTemplate into a concrete WorkflowDefinition. They share the same {{...}} syntax but use fundamentally different resolution strategies.
Entry Points
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/workflows/template.ts:13 -- interpolate() function
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/workflows/template.ts:50 -- deepInterpolate() function
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/workflows/templates.ts:31 -- instantiateTemplate() function
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/workflows/templates.ts:7 -- validateTemplateVariables() function
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/workflows/index.ts:7-8 -- Both modules re-exported
User
Analysis: GitHub Event Handlers -- Task Description Assembly and Creation
Overview
src/github/handlers.ts contains seven exported handler functions that convert GitHub webhook events into agent tasks. Each handler follows an identical pattern: validate the event, deduplicate, find a lead agent, build a plaintext task description string by interpolating event data with hardcoded instruction constants, then persist via createTaskExtended() with structured VCS metadata.
Entry Points
All seven exported handlers share the same signature pattern:
handleComment -- :509 (takes an additional eventType parameter)
handlePullRequestReview -- :606
handleCheckRun -- :715
handleCheckSuite -- :793
handleWorkflowRun -- :870
Core Implementation
1. DELEGATION_INSTRUCTION and getCommandSuggestions() (lines 19-38)
DELEGATION_INSTRUCTION (line 19-20) is a static string constant:
code
"⚠️ As lead, DELEGATE this task to a worker agent - do not tackle it yourself."
Every task-creating handler appends this verbatim into the task description. It is always present -- there is no conditional logic around it.
getCommandSuggestions(taskType, targetType?) (lines 25-38) maps the taskType string to a hardcoded suggestion line:
taskType
targetType
Output
"github-pr"
(ignored)
"💡 Suggested: /review-pr or /respond-github"
"github-issue"
(ignored)
Assistant
All 5 background research agents completed. The GitHub handler analysis confirms the patterns described in the plan — every handler follows the same validate → deduplicate → find lead → build description → createTaskExtended → react flow.
Waiting for your file-review comments on the plan.
Assistant
Got 5 comments from your review. Let me address each one and update the plan.
Comment 1 (ddbd5e06) — History on delete: The ON DELETE CASCADE currently deletes history when the template is deleted. I'll change this: remove the CASCADE, and have deletePromptTemplate() keep history records (orphaned but queryable). No soft delete on the main table — deleting an override means "revert to default."
Comment 2 (1313e9a2) — Latest definition resolution: I'll add detail clarifying the two-layer lookup: the in-memory Map holds code-defined metadata (header, defaultBody, variables), while the DB holds overrides. The resolver always uses code-defined header + checks DB for body override, falling back to code-defined defaultBody.
Comment 3 (0a49e840) — Rollback → Checkout: Renaming to "checkout" and clarifying: it copies body/state from the target history version into the live record + creates a new history entry. Going to any version (forward or backward). To revert to the seeded default, just delete the override.
Comment 4 (d1fdae65) — Base prompt assembly: I'll add explicit documentation of the composite session template recipe — system.session.lead and system.session.worker as the authoritative definitions of assembly order, stored as templates with {{@template[...]}} references.
Comment 5 (3f1b7032) — E2E with all triggers: Template resolution happens at task creation, not worker execution. I'll update the E2E section to include curl-based simulation of all event types (GitHub webhooks, etc.) to verify the created task descriptions match expectations. No need for a Docker worker.
Assistant
Now let me apply all 5 review fixes.
Assistant
Now fix comment 2 — add detail on the two-layer resolution.
Assistant
Now fix comment 3 — rename "rollback" to "checkout" and explain the mechanics.
Assistant
Now update the remaining "rollback" references throughout the plan.
Assistant
Now fix comment 4 — add explicit composite session template recipe in Phase 6.
Assistant
Now fix comment 5 — expand E2E to test all event triggers at task creation time.
Assistant
Now add the webhook trigger testing section after the existing E2E commands.
Assistant
Also update the DB CRUD functions section to rename rollback → checkout, and the file manifest.
Assistant
Also add src/prompts/session-templates.ts to the file manifest since I referenced it in Phase 6.
Assistant
Finally, update the plan status from draft to ready.
Assistant
All 5 review comments addressed:
History on delete — Removed ON DELETE CASCADE, added explicit deletion behavior documentation
Two-layer resolution — Added table + flow explaining code registry vs DB layers
Rollback → Checkout — Renamed everywhere, explained bidirectional mechanics + reverting to default via DELETE
Base prompt assembly — Added explicit composite template recipe with {{@template[...]}} references, designated src/prompts/session-templates.ts as the single source of truth
E2E trigger testing — Clarified resolution happens at task creation, added webhook simulation section covering ALL event types
Assistant
Understood — I'll run the review, fix everything directly, and summarize when done. Let me spawn a codebase verification agent in parallel while I analyze the plan.
Assistant
While the verification agent runs, let me start applying fixes for the issues I've identified. I found several gaps during the structural and content analysis.
Issues found:
CRITICAL: Global-scope override collision — UNIQUE(eventType, scope, scopeId) prevents having both a seeded default AND a user override at global scope for the same eventType
Wildcard + scope chain interaction unspecified — does wildcard matching happen at each scope level or only after all exact matches fail?
Seeding invocation location missing — where exactly is seedDefaultTemplates() called in startup?
Header interpolation not explicit in resolver flow
Performance/caching strategy missing — every resolve = 3+ DB queries
Phase 3 curl example creates a global override that would collide with seeded default
handlePullRequest multi-action dispatch not addressed in refactor
Now add a "reset to default" endpoint to the REST API and MCP tools:
Assistant
Also add unit tests for the new behaviors:
Assistant
Now let me add the review errata section documenting what was found and fixed:
Assistant
Review complete. Here's a summary of what was found and fixed, Taras:
Critical (1 issue, fixed):
Global-scope override collision — The UNIQUE constraint prevented customizing a global default. Fixed by having upsert flip isDefault to false on customization, with resetToDefault() for immediate revert + POST .../reset endpoint.
Important (5 issues, fixed):
Wildcard + scope precedence — clarified two-pass resolution (exact at all scopes, then wildcard at all scopes)
Seeding location — specified: called from initDb() after migrations
Header interpolation — made explicit that header + body share the same variable context
Performance — added strategy section: no caching initially, deferred to follow-up
Multi-action dispatch — documented that handlePullRequest's action branches map to separate event types
Minor (6 issues, fixed):
Curl example, deletion/history behavior, rollback→checkout, two-layer model, session recipe, E2E webhooks — all previously addressed from your file-review + now documented in errata.
Assistant
Plan parked at thoughts/taras/plans/2026-03-20-prompt-template-registry.md with status ready. Pick it up anytime with /implement-plan thoughts/taras/plans/2026-03-20-prompt-template-registry.md.
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/slack/handlers.ts -- Slack user email/name caches
<total_tokens>51945</total_tokens><tool_uses>22</tool_uses><duration_ms>120304</duration_ms>
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-20-fet-template-registry/1737807a-29e7-4cf2-9870-f5fc07b93de7/tasks/aa042c36b679c636b.output
Layer 1 -- HTTP route matching (src/http/index.ts:98): The handleWebhooks function is registered in the handler chain. When a request comes in, the chain iterates at lines 113-115 until a handler returns true.
Layer 2 -- Event type dispatch (src/http/webhooks.ts:93-233): Inside handleWebhooks, the GitHub path is matched at line 99 via githubWebhook.match(req.method, pathSegments) which checks against the pattern ["api", "github", "webhook"].
The actual event routing uses a switch statement on the x-github-event header (lines 144-171):
code
const eventType = req.headers["x-github-event"] // line 106
Before the switch, the function:
Checks isGitHubEnabled() (line 100)
Reads the raw body for signature verification (lines 109-113)
handlePullRequestReview(body as PullRequestReviewEvent)
158
"check_run"
handleCheckRun(body as CheckRunEvent)
161
"check_suite"
handleCheckSuite(body as CheckSuiteEvent)
164
"workflow_run"
handleWorkflowRun(body as WorkflowRunEvent)
167
default
logs "Ignoring unsupported event type"
170
After the handler switch completes, a second switch at lines 174-219 emits workflow trigger events on the workflowEventBus for pull_request, issues, issue_comment, and pull_request_review event types. This is separate from the task-creation handlers above -- it feeds the workflow engine's trigger subscription system.
All handler functions are imported from src/github/handlers.ts via the barrel export at src/github/index.ts.
User
3. In-Memory Caching Patterns
getResolvedConfig() does NOT cache. At src/be/db.ts:5058-5084, every call executes fresh SQL queries via getSwarmConfigs() for each scope (global, agent, repo) and builds a new Map from scratch. No memoization, no TTL, no stale-while-revalidate. Pure DB read every time.
However, the codebase does have several other in-memory caching patterns using Map:
Cache
File:Line
Pattern
GitHub installation token cache
src/github/app.ts:7
Map<number, {token, expiresAt}> -- TTL-based (checks expiresAt at line 191). Cleared on resetGitHub() (line 24).
GitHub event dedup cache
src/github/handlers.ts:15
Map<string, number> -- 60-second TTL (EVENT_TTL = 60_000). Cleaned on each isDuplicate() call (lines 43-48).
GitLab event dedup cache
src/gitlab/handlers.ts:17
Same pattern as GitHub dedup -- Map<string, number> with 60s TTL.
AgentMail event dedup cache
src/agentmail/handlers.ts:42
Same pattern -- Map<string, number> with TTL-based cleanup.
Linear delivery dedup
src/linear/webhook.ts:10
Map<string, number> -- recentDeliveries with timestamp-based dedup.
Slack user email cache
src/slack/handlers.ts:33
Map<string, string|null> -- no TTL, grows unbounded. Used to avoid repeated Slack API calls for email lookups.
Slack user name cache
src/slack/handlers.ts:160
Map<string, string> -- no TTL, grows unbounded. getUserDisplayName() checks cache first at line 163 before calling client.users.info.
Slack rate limit map
src/slack/handlers.ts:282
Map<string, number> -- tracks timestamps for rate limiting.
Map<string, BufferedThread> -- buffers messages per thread.
The dominant caching pattern is Map<string, number> with a TTL constant and manual cleanup on each lookup (the dedup caches). The Slack caches are unbounded/permanent for the lifetime of the process.
User
2. Startup Sequence -- initDb and what follows
Entry point:src/http.ts (line 1) is just import "./http/index".
src/server.ts:108 -- initDb(process.env.DATABASE_PATH) is called inside createServer() at line 108. The createServer() function is the MCP server factory. But for the HTTP server path, the startup lives in src/http/index.ts.
src/http/index.ts -- The HTTP server startup sequence:
The createServer() call from src/server.ts is imported indirectly. The actual initDb() call happens inside createServer() at src/server.ts:108. The HTTP handler chain at src/http/index.ts:55 creates the raw node:http server and sets up routing.
The .listen() callback at line 165 runs the post-startup sequence:
Line 171:loadGlobalConfigsIntoEnv(false) -- reads all global-scope swarm_config rows from DB via getResolvedConfig() and sets them as process.env keys (only filling in keys not already set by infrastructure env vars).
Line 180:startSlackApp() -- starts Slack bot
Line 183:initGitHub() -- initializes GitHub webhook handler
Line 186:initGitLab() -- initializes GitLab webhook handler
Line 189:initAgentMail() -- initializes AgentMail webhook handler
Line 192:initLinear() -- initializes Linear tracker integration
handlePullRequest (lines 74-371) is structured as a sequential chain of if (action === "...") blocks with early returns -- not an if/else chain, and not separate sub-functions. Each action is handled inline within the single function body. The dispatch order is:
"closed" (line 241) -- finds related task via findTaskByVcs, deduplicates, creates a status-notification task (github-pr-status), returns
"synchronize" (line 283) -- finds related task, deduplicates using SHA in key, creates update-notification task (github-pr-update), returns
Fallthrough for "opened" / "edited" (line 320) -- a guard if (action !== "opened" && action !== "edited") return acts as the catch-all exit. The remaining code (lines 324-371) handles the mention-based flow: checks detectMention on title/body, deduplicates, creates task.
There are no sub-function calls for the per-action logic. All task creation calls createTaskExtended directly inline. Shared helpers used across actions are isDuplicate (line 40), findLeadAgent (line 62), getCommandSuggestions (line 25), and isBotAssignee (imported from ./mentions).
upsertSwarmConfig(data) (lines 4966-5043): This is the core write operation. Key detail at lines 4981-4994: it cannot rely on SQLite's ON CONFLICT for the UNIQUE(scope, scopeId, key) constraint because SQLite treats NULL != NULL. So for global scope (where scopeId is NULL), the uniqueness check ON CONFLICT never fires. Instead, it does a manual existence check:
Global scope (scopeId === null, line 4984): Uses WHERE scope = ? AND scopeId IS NULL AND key = ?
Agent/repo scope (scopeId !== null, line 4990): Uses WHERE scope = ? AND scopeId = ? AND key = ?
If an existing row is found, it does an UPDATE ... RETURNING * (lines 4999-5004). Otherwise, it generates a new UUID and does an INSERT ... RETURNING * (lines 5006-5026). After the upsert, if the config has an envPath, it calls writeEnvFile() (lines 5034-5039).
deleteSwarmConfig(id) (lines 5048-5051): Deletes by ID, returns boolean for whether a row was actually removed.
This is the merge function. The priority order is: repo > agent > global (most-specific wins).
The implementation uses a Map<string, SwarmConfig> keyed by config key:
Line 5062-5065: Load all global scope configs. Each is inserted into the map by its key.
Lines 5068-5073: If agentId is provided, load all agent scope configs for that agent. These overwrite any global entries with the same key.
Lines 5076-5081: If repoId is provided, load all repo scope configs for that repo. These overwrite any agent or global entries with the same key.
The final result (line 5083) is the map's values sorted alphabetically by key. Each unique key appears exactly once, with the most-specific scope's value.
Note that route ordering within the file matters for overlapping patterns. getResolvedConfigRoute (3-segment literal "resolved") is checked before getConfigById (3-segment with null wildcard) at lines 106 vs 118. More specific patterns go first.
Section 2: Single exported handler function (lines 100-191) -- handleConfig() with signature:
The request loop at lines 113-115 iterates through handlers in order. The first handler to return true wins. If none match, a 404 is returned at lines 118-119.
The handler function receives pathSegments and queryParams which are computed once at lines 87-88 via getPathSegments() and parseQueryParams() from src/http/utils.ts.
Note that handleCore() at line 85 runs before the handler array -- it handles OPTIONS, health, auth, and a few other core routes. Auth (API key check) is performed there, so by the time any handler in the array runs, the request is already authenticated.
The script at line 5 imports "../src/http/config" as a side-effect import. This triggers the module-level route() calls, which push into routeRegistry. Then generateOpenApiSpec() at line 21 reads the registry and produces openapi.json.
Adding a new handler file requires adding its import to this script (visible at lines 3-18 for all existing handlers).
Notably, empty string "", 0, and false are all considered resolved -- only null/undefined trigger unresolved. The tests at lines 161-177 of the test file confirm this.
Uses a recursive walk() closure (lines 56-71) that:
Strings: delegates to interpolate(), collects unresolved tokens into allUnresolved (lines 57-61).
Arrays: maps each element through walk() (line 62).
Objects (non-null): creates a new object, walks each value (lines 63-68).
Primitives (number, boolean, null, undefined): passes through unchanged (line 70).
The unresolved arrays from every string leaf are concatenated into a single flat allUnresolved array. The function returns both the transformed value tree and the aggregated unresolved list.
"💡 Suggested: /implement-issue or /respond-github"
"github-comment"
"PR"
"💡 Suggested: /respond-github or /review-pr"
"github-comment"
other
"💡 Suggested: /respond-github"
anything else
""
This function is only called by handlePullRequest, handleIssue, and handleComment. The review/CI handlers produce their own inline suggestion strings instead.
2. Common Handler Pattern (all handlers)
Every handler follows this sequence:
Guard on action -- e.g., action !== "submitted" at line 613, action !== "created" at line 516
Bot relevance check -- e.g., isBotAssignee() or detectMention() or findTaskByVcs()
Deduplication -- isDuplicate(eventKey) using a 60-second in-memory TTL cache (lines 14-56)
Find existing related task -- findTaskByVcs(repo, number) when applicable
Find lead agent -- findLeadAgent() at line 62-69 (prefers online lead, falls back to any lead, or null)
reviewBody: includes the review body text if present, otherwise empty string
suggestions: a ternary chain producing one of three hardcoded suggestion strings based on review.state (approved/changes_requested/other)
Step 3: Assemble the full description (line 653)
The entire prompt is a single template literal. Its structure:
code
{emoji} [GitHub PR #{number} Review] {label}
PR: {title}
Reviewer: {sender.login}
Repo: {repository.full_name}
URL: {review.html_url}{reviewBody}
---
{if existingTask: "Related task: {id}\n🔀 Consider routing to the same agent working on the related task.\n"}
⚠️ As lead, DELEGATE this task to a worker agent - do not tackle it yourself.
{suggestions}
Key observations about the template:
The header line combines emoji + bracketed section identifier + label
There is a metadata block (PR title, reviewer, repo, URL)
A --- separator divides metadata from instructions
The "related task" routing hint is conditional on existingTask (found at line 630 via findTaskByVcs)
DELEGATION_INSTRUCTION is always appended after the separator
Suggestions are the last line
4. How createTaskExtended() Is Called (line 656-666)
The first argument is always the full description string. The second is a CreateTaskOptions object (defined at /Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/be/db.ts:1707-1740).
Fields consistently used by GitHub handlers:
Field
Value pattern
Purpose
agentId
lead?.id ?? ""
Assigns to lead agent; empty string if no lead
source
Always "github"
Marks task origin (one of the AgentTaskSource enum values)
vcsProvider
Always "github"
VCS provider identifier
taskType
Varies per handler
Distinguishes event kind
vcsRepo
repository.full_name
e.g. "org/repo"
vcsEventType
Matches webhook event name
e.g. "pull_request_review", "issues", "check_run"
vcsNumber
PR or issue number
Used for findTaskByVcs lookups
vcsAuthor
sender.login
GitHub username who triggered the event
vcsUrl
URL to the specific resource
Review URL, comment URL, PR URL, etc.
vcsCommentId
Only in handleComment (line 558)
The comment ID for comment events
Fields NOT used by GitHub handlers:creatorAgentId, tags, priority, dependsOn, offeredTo, slackChannelId, slackThreadTs, slackUserId, parentTaskId, model, scheduleId, workflowRunId, workflowRunStepId, epicId, dir, agentmail*, mention*, sourceTaskId.
5. Inside createTaskExtended() (db.ts:1777-1900)
The function at /Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/be/db.ts:1777:
Generates a UUID for the task (line 1778)
Determines initial status (line 1780-1786): for GitHub tasks, agentId is lead?.id ?? "" -- when a lead exists, status becomes "pending"; when empty string, the truthiness check fails and it falls to "unassigned" (since no offeredTo or status: "backlog" is passed)
Parent task metadata inheritance (lines 1789-1808): not exercised by GitHub handlers since they never pass parentTaskId
Source task Slack inheritance (lines 1813-1820): also not exercised
Inserts a single row into agent_tasks with all 36 columns (lines 1822-1871)
Creates a log entry of type "task_created" (lines 1875-1883)
Emits a "task.created" event on the workflow event bus (lines 1885-1897)
Returns the created AgentTask via rowToAgentTask(row) (line 1899)
GitHub webhook arrives (routed by code outside this file)
Typed event object is passed to the appropriate handler (e.g., handlePullRequestReview(event))
Handler destructures event payload fields at the top of the function
Guard clauses filter irrelevant actions/states
findTaskByVcs() (db.ts:936-947) queries agent_tasks for an active task matching the repo+number
findLeadAgent() (handlers.ts:62-69) queries getAllAgents() for a lead agent
Task description assembled as a template literal string -- all prompt text is inline
createTaskExtended(description, metadata) persists to SQLite and emits events
Optional reaction added to the GitHub entity via the GitHub API
Handler returns { created: true, taskId } to caller
Key Patterns
Prompt-as-string: Every task description is a single template literal with no abstraction layer. The "prompt" to the agent is the task column in the database -- a flat string mixing structured metadata (PR number, repo, URL) with behavioral instructions (DELEGATION_INSTRUCTION, suggestions).
Two-layer metadata: Event information exists in two places simultaneously: embedded in the human-readable taskDescription string AND as structured fields in the CreateTaskOptions metadata object. The description is what agents read; the metadata enables programmatic queries like findTaskByVcs.
Conditional sections: Some handlers conditionally inject a "Related task" routing hint when existingTask is found (review handler at line 653, comment handler at line 547, CI handlers). Others never have this section (PR opened, issue opened).
Suggestion variance: getCommandSuggestions() covers PR/issue/comment types. Review and CI handlers produce their own inline suggestion text directly in the template literal rather than calling this function.
Uniform VCS metadata shape: All GitHub handlers pass the same core set of VCS fields (vcsProvider, vcsRepo, vcsEventType, vcsNumber, vcsAuthor, vcsUrl) plus source: "github". The only variance is vcsCommentId (comment handler only) and vcsAuthor being empty string for CI handlers.
Relevant Files
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/github/handlers.ts -- All handler functions, DELEGATION_INSTRUCTION, getCommandSuggestions()
/Users/taras/worktrees/agent-swarm/2026-03-20-fet/template-registry/src/types.ts -- AgentTaskSourceSchema (line 56), includes "github" as a valid source value
Full transcript available at: /private/tmp/claude-501/-Users-taras-worktrees-agent-swarm-2026-03-20-fet-template-registry/1737807a-29e7-4cf2-9870-f5fc07b93de7/tasks/a667cfb39c9f03ba5.output