Execute task

From indigoai-us/hq-core · View interactive version

Execute task is an AI agent skill from the GitHub repository indigoai-us/hq-core. Execute one PRD story through coordinated worker phases with test, lint, and typecheck gates.

How to use this skill

Skill file

Execute Task - Worker-Coordinated Story Execution

Execute a single user story from a PRD through coordinated worker phases. Each worker handles their domain and passes context to the next via structured handoffs. Back pressure (typecheck, lint, tests) enforces correctness at every phase.

Usage: execute-task {project}/{task-id}

By default every assigned worker phase runs on a named in-session subagent

(step 6c-default): the Agent tool in Claude Code, spawn_agent / wait_agent

in Codex. The same worker's subagent is resumed across phases with

SendMessage to its agent id, and each phase returns its handoff JSON to this

session.

<!-- advanced-mode:start -->

Lanes are advanced mode: when conduct.runner is runner (set with

/conduct-runners), each phase runs through hq runners create instead (step

6c-lanes), with this session as senior and the story id on every lane.

<!-- advanced-mode:end -->

User's input: $ARGUMENTS

Ralph Principle

"Pick a task, complete it, commit it."

<!-- advanced-mode:start -->

senior does the phase work through hq runners create, continued across phases

<!-- advanced-mode:end -->

Return Contract (when invoked as a story sub-agent)

Canonical path (orchestrator-dispatched, e.g. /run-project --inline, /run-pipeline, or any caller injecting RETURN CONTRACT: json): emit ONLY this JSON object as the final message:

{
  "status": "passed" | "failed" | "blocked",
  "story_id": "<id>",
  "commits": ["<short-sha>", ...],
  "files_changed": <int>,
  "back_pressure": {
    "tests": "pass" | "fail" | "skip",
    "lint": "pass" | "fail" | "skip",
    "typecheck": "pass" | "fail" | "skip",
    "build": "pass" | "fail" | "skip"
  },
  "workers_run": ["<worker-id>", ...],
  "evidence": ["repo-path:<relative to repo>", "path:<hq-relative>", "branch:<name>", "url:<https://…>", ...],
  "notes": "<=240 chars; on non-passed status, name the blocker concisely>"
}

Hard formatting rules:

Field semantics:

All normal execute-task behavior still runs (task classification, worker sequence, back pressure, commits, prd.json passes:true on success). Only the shape of the final output message changes.

Opt-out (prose mode): when the prompt explicitly includes RETURN CONTRACT: prose, emit the normal human-readable summary. This path is reserved for direct CLI use (no orchestrator parent). Orchestrators MUST inject RETURN CONTRACT: json per ralph-orchestrator-context-discipline (hard policy).

Runtime Adapter: Phase Runner

Step 5 resolves the runner once with sh core/scripts/conduct-runner-resolve.sh

and records it in the execution state. It prints subagent (the default) or

runner (advanced mode, set with /conduct-runners).

Default (subagent): each phase runs on a named in-session subagent: the

Agent tool in Claude Code, spawn_agent / wait_agent in Codex. The

subagent receives the phase brief, does the work, commits it, and returns the

handoff JSON. The same worker's subagent is resumed for its later phases with

SendMessage to its agent id. No hq runners call is made in this mode.

<!-- advanced-mode:start -->

Advanced mode (runner): worker phases use hq runners create. The invoking

session is recorded as senior, and every phase carries the active company,

project, story, worker, and brief file. HQ lanes owns provider launch,

continuity, admission, and durable lane state. The caller reads the phase

result from the lane envelope and keeps the handoff file format documented

below. In advanced mode, do not substitute Task, spawn_agent, or a headless

builder for a phase lane. If hq runners is unavailable or refuses the request,

preserve the phase as queued or report the specific blocker.

<!-- advanced-mode:end -->

In both modes the parent never runs a phase itself. Do not simulate the worker

sequence in the parent. If this session cannot spawn a phase subagent (for

example, it is itself a subagent without the Agent tool), block the story

with NEEDS_RUNNER. A /run-project parent then runs /execute-task for

that story from its own session, one story at a time. Run directly, point

the user to running /execute-task from the top-level session,

/conduct-runners, or /run-project --interactive.

Work Mesh Live — trusted bind (do this first)

Before any other tool call that touches project work, bind the session per

.claude/skills/_shared/work-mesh-live-bind.md (US-011):

hq core work-mesh-bind-trusted \
  --company "{co}" --project "{project}" --task "{task}"

Omit --task when unknown. This writes workspace/sessions/<sid>/meta.yaml

and reconciles with observation.trustedContext (no --trusted CLI flag).

Process

1. Parse Arguments

Extract {project}/{task-id} from $ARGUMENTS.

Split on /: first token is project, second is task-id.

If no arguments or missing parts:

Usage: /execute-task {project}/{task-id}

Example: /execute-task campaign-migration/CAM-003

Stop here.

1.5 Trusted session bind (US-011)

Once {project} and {task-id} are parsed (and company {co} is known from

the PRD path companies/{co}/projects/... or session meta), bind immediately:

hq core work-mesh-bind-trusted \
  --company "{co}" --project "{project}" --task "{task-id}"

Do this before loading workers or editing files.

1.6 Claim the story on the Work Mesh

Right after the bind, claim the story so the team board shows who holds it:

hq mesh claim --company "{co}" --project "{project}" --story "{task-id}" --json

hq mesh claim sets the assignee to you and the status to in_progress.

Tell the user who holds it and ask whether to wait, pick another story, or

take it over. Re-run with --force only after the user says to take it over.

"unavailable" result: continue without a claim and say once that the story

was not claimed on the mesh. A mesh outage never blocks the story.

2. Load Task Spec

Resolve project location using qmd search (never Glob for prd.json):

qmd search "{project} prd.json" --json -n 5

From results, find the entry whose path includes /{project}/prd.json. If qmd is unavailable or returns nothing, fall back to direct Read at these paths in order:

  1. companies/{co}/projects/{project}/prd.json (company projects)
  2. personal/projects/{project}/prd.json (personal/HQ projects)

If no prd.json found:

ERROR: prd.json not found for {project}. Run /prd {project} first.

Stop.

Read prd.json. Validate structure strictly — no fallbacks:

  1. userStories array required: If userStories is missing or not an array:

```

ERROR: prd.json missing userStories array. Migrate legacy 'features' key to 'userStories'.

```

Stop.

  1. Required fields per story: Each story must have id, title, description, passes. Report any story with missing fields and stop.
  1. Find the target story: Match task-id against story.id. If not found:

```

Task {task-id} not found in {project} prd.json.

```

Stop.

  1. Check completion: If story.passes === true:

```

Task {task-id} already complete (passes: true). Skipping.

```

Stop.

  1. Check dependencies: If the story has dependsOn, verify each dependency story has passes: true. If any dependency is incomplete:

```

Task {task-id} blocked: depends on {dep-id} which is not yet complete.

```

Stop.

Extract from the matched story:

Also record from prd.metadata:

2.5 Check Codex CLI Availability

For any code-related task type, pre-flight check whether the Codex CLI is installed:

which codex >/dev/null 2>&1

```

Warning: Codex CLI not found. codex-reviewer will run as Claude-only review (no Codex model).

```

This enables graceful degradation — the pipeline continues without Codex but logs a warning.

2.6 Check Story Checkout State

Guard against concurrent execution of the same story.

  1. Load config: Read core/settings/orchestrator.yaml → checkout.enabled and checkout.stale_timeout_minutes (defaults: true, 30).
  2. Skip if disabled: If checkout.enabled: false, skip this step entirely and proceed to step 3.
  3. Read state.json: Read workspace/orchestrator/{project}/state.json. If missing, skip — no checkout to check.
  4. Check for existing checkout: If current_task.id matches this story AND current_task.checkedOutBy is not null:

a. Extract checkout info:

```

checkedOutPid = state.current_task.checkedOutBy.pid

checkedOutSession = state.current_task.checkedOutBy.sessionId

checkedOutAt = state.current_task.checkedOutBy.startedAt

```

b. Check if PID is alive:

```bash

kill -0 {checkedOutPid} 2>/dev/null

```

c. If PID is ALIVE — ask the user via AskUserQuestion:

```

Story {task.id} is currently checked out by PID {checkedOutPid}

(session: {checkedOutSession}, started: {checkedOutAt}).

Another /execute-task may be running.

Proceed anyway (override) or abort?

Options: ["Proceed anyway", "Abort"]

```

d. If PID is DEAD — release the stale checkout:

  1. If no conflict: proceed normally.

Report:

Checkout check: clear (no active checkout for {task.id})

or after release:

Checkout check: released dead checkout for {task.id}, proceeding

3. Classify Task Type

Analyze the story's title, description, and acceptance criteria. Match against patterns:

| Type | Indicators |

|------|------------|

| schema_change | database, migration, schema, table, column, prisma, SQL |

| api_development | endpoint, API, REST, GraphQL, route, service |

| ui_component | component, page, form, button, React, UI, responsive |

| full_stack | Combination of backend + frontend indicators |

| codex_fullstack | codex, AI-generated, codex-powered full stack |

| enhancement | animation, polish, refactor, optimization, UX |

| content | copy, content, documentation, marketing text |

Codex worker routing:

| Pattern | Worker | Inclusion |

|---------|--------|-----------|

| "codex", "AI-generated" | codex-coder | Optional (hints match) |

| "auto-fix", "debug recovery" | codex-debugger | Optional (hints match) |

Report classification:

Task: {task.id} - {task.title}
Type: {type} (matched: {indicators})

4. Select Worker Sequence

Based on task type, determine the worker sequence:

schema_change:
  - product-planner (if spec unclear)
  - database-dev
  - backend-dev
  - acceptance-test-writer (if e2eTests non-empty)
  - code-reviewer
  - codex-reviewer
  - dev-qa-tester

api_development:
  - product-planner (if spec unclear)
  - backend-dev
  - codex-coder (optional, if worker_hints include codex)
  - acceptance-test-writer (if e2eTests non-empty)
  - code-reviewer
  - codex-reviewer
  - codex-debugger (optional, before QA if back-pressure issues)
  - dev-qa-tester

ui_component:
  - product-planner (if spec unclear)
  - frontend-dev
  - codex-coder (optional, if worker_hints include codex)
  - motion-designer
  - acceptance-test-writer (if e2eTests non-empty)
  - code-reviewer
  - codex-reviewer
  - codex-debugger (optional, before QA if back-pressure issues)
  - dev-qa-tester

full_stack:
  - product-planner
  - architect
  - database-dev
  - backend-dev
  - frontend-dev
  - codex-coder (optional, if worker_hints include codex)
  - acceptance-test-writer (if e2eTests non-empty)
  - code-reviewer
  - codex-reviewer
  - codex-debugger (optional, before QA if back-pressure issues)
  - dev-qa-tester

codex_fullstack:
  - product-planner (if spec unclear)
  - architect
  - database-dev
  - codex-coder
  - acceptance-test-writer (if e2eTests non-empty)
  - codex-reviewer
  - dev-qa-tester

content:
  - content-brand
  - content-product
  - content-sales
  - content-legal

enhancement:
  - (relevant dev based on files)
  - acceptance-test-writer (if e2eTests non-empty)
  - code-reviewer
  - codex-reviewer
  - codex-debugger (optional, if auto-fix needed)

Sequence rules:

Worker phase descriptions (for execution plan display):

| Worker | Phase Description |

|--------|-------------------|

| product-planner | Clarify spec and acceptance criteria |

| architect | Design system architecture |

| database-dev | Implement schema and migrations |

| backend-dev | Implement backend service |

| frontend-dev | Implement frontend UI |

| codex-coder | Generate code via Codex AI |

| motion-designer | Add animations and motion |

| code-reviewer | Review changes (Claude-based) |

| codex-reviewer | Mandatory second-opinion review via Codex AI |

| acceptance-test-writer | Write story-level acceptance tests from e2eTests |

| codex-debugger | Auto-fix issues via Codex AI |

| dev-qa-tester | Verify implementation |

| content-brand | Brand-aligned content creation |

| content-product | Product content and documentation |

Present the execution plan:

Execution Plan for {task.id}:

Phase 1: {worker} -> {phase description}
Phase 2: {worker} -> {phase description}
Phase 3: {worker} -> {phase description}

Phases: {N} | Type: {type}
Proceed? [Y/n]

5. Initialize Execution State

Create the execution tracking directory and file:

mkdir -p workspace/orchestrator/{project}/executions

Resolve the phase runner once with the shared resolver. Take the session id

from bash core/scripts/hq-session.sh current:

sh core/scripts/conduct-runner-resolve.sh --session-id {session-id}

It prints subagent (default, step 6c-default) or runner (advanced mode,

step 6c-lanes). Record the value as runner and use it for every phase of this

story.

Write to workspace/orchestrator/{project}/executions/{task-id}.json:

{
  "task_id": "{task.id}",
  "project": "{project}",
  "started_at": "{ISO8601}",
  "status": "in_progress",
  "runner": "subagent|runner",
  "current_phase": 1,
  "phases": [
    {"worker": "{worker1}", "status": "pending"},
    {"worker": "{worker2}", "status": "pending"}
  ],
  "handoffs": [],
  "codex_debug_attempts": []
}

5.0.5 Acquire Story Checkout

If checkout.enabled: true (from core/settings/orchestrator.yaml):

  1. Read state.json: Read workspace/orchestrator/{project}/state.json. If missing, create with minimal structure: {"version":1,"current_task":{},"updated_at":"{ISO8601}"}.
  1. Write checkout entry into current_task.checkedOutBy:

```json

{

"pid": {current_process_pid},

"startedAt": "{ISO8601}",

"sessionId": "{started_at from step 5}"

}

```

Also ensure current_task.id is set to this story's ID and updated_at is refreshed.

Getting the PID: Run echo $$ in bash to get the current shell's PID. Use that value as the pid field.

  1. Write state.json back with the updated checkedOutBy block.
  1. Report: Checkout acquired for {task.id} (PID: {pid})

If checkout.enabled: false: skip this step silently.

5.1 Audit: Task Started

hq core audit-log append \
  --event task_started \
  --project {project} \
  --story-id {task.id} \
  --company {company} \
  --session-id {started_at} \
  --action "Task execution started: {task.title}" || true

5.5 Acquire File Locks

If the story has a non-empty files array and prd metadata has repoPath:

  1. Load config: Read core/settings/orchestrator.yaml → file_locking.
  2. Skip if disabled: If file_locking.enabled: false, skip this step entirely.
  3. Read existing locks: Read {repoPath}/.file-locks.json (create if missing: {"version":1,"locks":[]}).
  4. Stale lock cleanup: For each existing lock, check if owner PID is running via kill -0 {pid} 2>/dev/null. If not running AND lock is older than stale_lock_timeout_minutes, remove it.
  5. Conflict check: For each file in task.files:
  1. Acquire locks: For each unlocked file, append to .file-locks.json:

```json

{"file": "{path}", "owner": {"project": "{project}", "story": "{task.id}", "pid": {$$}}, "acquired_at": "{ISO8601}"}

```

(Get PID via echo $$ in bash.)

  1. Update state.json: Update project's checkedOutFiles:

```json

[{"file": "{path}", "story": "{task.id}", "repo": "{repoPath}"}]

```

Report: File locks acquired: {N} files for {task.id}

5.5.5 Sync Linear Issue to In Progress (Best-Effort)

If the story has linearIssueId and prd metadata has linearCredentials:

  1. Cross-company guard: Before using linearCredentials, verify the path matches the active company per companies/manifest.yaml. If it points to a different company's settings, ABORT Linear sync and warn.
  1. Read API key:

```bash

LINEAR_KEY=$(node -e 'process.stdout.write(JSON.parse(require("node:fs").readFileSync(0, "utf8")).apiKey)' < "{prd.metadata.linearCredentials}")

ISSUE_ID="{task.linearIssueId}"

IN_PROGRESS_STATE="{prd.metadata.linearInProgressStateId}"

```

  1. Set issue to In Progress:

```bash

curl -s -X POST https://api.linear.app/graphql \

-H "Content-Type: application/json" \

-H "Authorization: $LINEAR_KEY" \

-d "{\"query\": \"mutation { issueUpdate(id: \\\"$ISSUE_ID\\\", input: { stateId: \\\"$IN_PROGRESS_STATE\\\" }) { success } }\"}"

```

  1. Comment on issue: "Started by HQ — task in progress."

Skip silently if no linearIssueId or no credentials configured. Never block execution on Linear sync failure.

5.6 Load Applicable Policies

Load policies through the frontmatter-only gate. Collect each applicable file set in stable order and divide it into consecutive chunks of at most 40 files. Invoke hq core policy frontmatter {file1} {file2} ... once per chunk, with each path as a separate argument. Keep each call under 30 KB of output. The first output block belongs to the chunk’s first file argument; each later block belongs to the path named by its preceding # --- policy-file: <path> --- separator. This reads frontmatter only and keeps each tool result bounded.

  1. Company policies: Determine the active company from prd.metadata.company or manifest repo lookup. Collect eligible files in companies/{co}/policies/, skipping example-policy.md, preserve their order, and read frontmatter using one complete ordered file list. For any policy with enforcement: hard whose trigger matches the current task, additionally read its ## Rule section via targeted Read + range.
  1. Repo policies: If working inside a repo, list files in {repoPath}/.claude/policies/ if it exists, preserve their order, and read all frontmatter using one complete ordered file list with each path as a separate argument.
  1. Global policies: Policy digest files are retired. Collect global policy files, preserve their order, and read their frontmatter using one complete ordered file list to filter by trigger; don't load full policy bodies. In the combined output, the initial unlabeled block belongs to its first path; subsequent results start with # --- policy-file: <path> ---. SessionStart injects matching policies via inject-policy-on-trigger; do not open a digest file.

Include applicable policy rules in worker prompts (step 6b) under ### Applicable Policies.

Enforcement distinction:

6. Execute Each Phase

For each worker in the sequence, run the phase on the runner recorded in step 5. By default that is the worker's named subagent (6c-default), resumed across phases. Each worker commits its work before returning and passes a structured handoff to the next phase.

<!-- advanced-mode:start -->

In advanced mode the runner is the worker's HQ lane (6c-lanes): create or continue it with hq runners create, passing the active company, project, story, worker, brief file, and invoking session as senior, and message a live lane with hq runners message.

<!-- advanced-mode:end -->

6a. Load Worker Config
  1. Read core/workers/registry.yaml (auto-generated, read-only index) to find the worker path:

```bash

grep -A 4 " - id: {worker-id}$" core/workers/registry.yaml | grep "path:"

```

Extract the path: value. This may resolve to core/workers/public/dev-team/{worker-id}/, core/workers/public/{worker-id}/, or companies/{co}/workers/{worker-id}/.

Resolve the core worker profile independently of the registry path: check core/workers/public/dev-team/{worker-id}/worker.yaml and then core/workers/public/{worker-id}/worker.yaml. The registry deduplicates IDs and may select a company profile lexicographically before the core profile. If either core file exists, use that core profile as the selected worker profile and set the registry variable worker_path to the core directory before step 2; treat same-ID company and personal profiles only as model overlays in step 4. If no core file exists, keep the registry-selected worker_path as the full worker profile.

  1. Read {worker_path}/worker.yaml to get:
  1. Resolve model for this phase:

```

model = task.model_hint || worker.execution.model || "opus"

```

Story-level model_hint (from prd.json) overrides worker default. Fallback: opus.

  1. Resolve Codex model (for codex workers only):

```

codex_model = task.codex_model_hint || worker.execution.codex_model

```

Story-level codex_model_hint overrides the model configured in the worker

profile. A missing worker.execution.codex_model is a configuration error;

stop and report it rather than selecting a model in this skill.

Users change a core worker's Codex model without editing core/ through

company or personal override files. Resolve the model with

core/scripts/worker-codex-model.sh, passing the company slug established

in step 1 (not an inherited HQ_COMPANY_SLUG, which may describe the

session launch company) and the story hint when present:

```bash

bash core/scripts/worker-codex-model.sh --company {active-company} [--story-hint {codex_model_hint}] {worker-id}

```

It prints <model><TAB><source>; use the model as codex_model.

Precedence: the story codex_model_hint, then

companies/{active-company}/workers/{worker-id}/overrides.yaml (or a same-id

worker.yaml there), then personal/workers/{worker-id}/overrides.yaml (or a

same-id worker.yaml there), then the core profile. An override file holds

only execution.codex_model. Overrides apply only when the selected profile

is under core/workers/; a worker already selected from a company or

personal path is not layered again. Exit 2 means no model is configured;

stop and report it. Keep execution.codex_flags from the selected worker

profile unchanged. Do not read or merge override execution.codex_flags.

  1. If the worker has a skill file relevant to the task, note its path so the sub-agent prompt can reference it.
6b. Build Worker Prompt

Construct the sub-agent prompt as a single markdown block:

## You are: {worker.name}
## Task: {task.id} - {task.title}

### Description
{task.description}

### Acceptance Criteria
{task.acceptance_criteria as checklist}

### Files to Focus On
{task.files or inferred from description}

### Context from Previous Phase
{handoff_context from previous worker, if any}

### Codebase Exploration
If the target repo has a qmd collection (check `qmd status`), prefer `qmd vsearch "<concept>" -c {collection} --json -n 10` for conceptual search (e.g. "where is auth handled", "billing service pattern"). Use Grep only for exact pattern matching (specific imports, function references, string literals).

### Applicable Policies
{policies loaded in step 5.6, if any}

### Codex CLI Model (codex workers only)
{codex_model} — the resolved value from the story override or worker profile. Pass it via `-c model="{codex_model}"` to all Codex exec/review commands.

### Your Instructions
{worker.instructions}

### Back Pressure (Run Before Completing)
{worker.verification.post_execute commands}

# Repo-specific back-pressure checks may be added here if needed
# e.g. coverage checks, manifest freshness, etc.

### Commit Your Work
Before returning, stage and commit the files you created or modified with a
descriptive message referencing {task.id}. If the orchestrator finds uncommitted
changes after your return, it keeps the phase incomplete and returns the commit
requirement to the same worker. The orchestrator does not commit work for you.

### Output Requirements
When complete, provide JSON:
{
  "summary": "What you accomplished",
  "files_created": ["paths"],
  "files_modified": ["paths"],
  "key_decisions": ["decision and rationale"],
  "context_for_next": "Instructions for next worker",
  "back_pressure": {
    "tests": "pass|fail",
    "lint": "pass|fail",
    "typecheck": "pass|fail",
    "build": "pass|fail"
  },
  "issues": ["any blocking issues"]
}
6c. Dispatch the Phase

Write the complete phase prompt from 6b to a phase brief file under

workspace/orchestrator/{project}/executions/{task-id}/phases/. Then run it on

the runner recorded in step 5: 6c-default for subagent, 6c-lanes for runner.

6c-default. Run the Phase on an Agent Subagent
  1. Hand the phase brief to a named subagent: the Agent tool in Claude Code

with name: "{task.id}-{worker.id}", or spawn_agent then wait_agent in

Codex. The prompt is the 6b phase prompt from the brief file, plus the

instruction to write its handoff JSON to

workspace/orchestrator/{project}/executions/{task-id}/phases/{phase}-{worker.id}.handoff.json

and return the same JSON as its final message.

  1. If this worker already ran an earlier phase of this story, resume that

subagent with SendMessage to its agent id instead of starting another one.

  1. Record the run in

workspace/orchestrator/conduct-subagents/{session-id}/runs.json

(story, worker, phase, agent id, status) so a resumed session can find it.

  1. Wait for the subagent to finish and read its handoff from the handoff file.

If the file is missing, use the JSON in its final message. Validate it

before continuing.

  1. If the subagent cannot be spawned (for example, this session is itself a

subagent without the Agent tool), do not run the phase in the parent.

Block the story with NEEDS_RUNNER, before any phase ran, so a

/run-project parent can run /execute-task from its own session.

Otherwise point the user to running /execute-task from the top-level

session, /conduct-runners, or /run-project --interactive.

<!-- advanced-mode:start -->

6c-lanes. Advanced Mode: Create or Continue the Worker's Lane, Then Dispatch

Only when the runner recorded in step 5 is runner (set with

/conduct-runners). Every phase assigned to a worker uses the same lane

mapping as /conduct:

  1. Use the phase brief file written above. The brief carries the envelope

line from Step 4 of .claude/skills/_shared/conduct-dispatch-core.md

verbatim, as one line:

```text

Envelope (hq-lane-envelope.v1): write one JSON object using only these keys: schema_version, decision, summary, story_status, artifacts, story_complete, story_complete_reason, questions, blocked_reason, next_check_at, fingerprint, outcome. schema_version is "hq-lane-envelope.v1". decision is one of "done", "ask", "blocked"; any other value, such as "complete", fails as envelope_invalid. story_status is one of "queued", "in_progress", "review", "done". summary is a non-empty string. artifacts is an array. questions is required and non-empty when decision is "ask", and absent otherwise. Each questions item is an object with question (a non-empty string), context (a non-empty string) and options (an array of strings), plus optional id and recommended (non-empty strings), and no other keys, for example {"id":"q1","question":"Which branch should the fix target?","context":"main and release both carry the bug.","options":["main","release"],"recommended":"main"}. blocked_reason is required and non-empty when decision is "blocked", and absent otherwise. story_complete is optional and is a boolean; story_complete_reason is required and non-empty when story_complete is present, and absent otherwise. story_complete true requires story_status "done" and a story_complete_reason that says what was delivered and how it was verified; story_complete false requires another story_status and a reason that says what is still missing. next_check_at is optional and is an ISO date-time. fingerprint is optional and is a non-empty string or null. outcome is optional; include it when the brief or the Executive standing rules (item 9) ask for it, as an object with only state ("done", "needs_decision" or "partial"), outcome (a non-empty string), gathered (an array of {"label","text"} objects with an optional "ref", all non-empty strings), next_steps (an array of non-empty strings, at least one when state is "partial") and an optional decision_id; state "needs_decision" requires decision_id or a non-empty questions array, and state "done" cannot accompany decision "blocked".

```

  1. Resolve the invoking session id with bash core/scripts/hq-session.sh current.

Create the lane with the bound company, project, story, worker id, brief path,

and --senior session:{session-id}:

```bash

hq runners create --company "{company}" --project "{project}" \

--story "{task.id}" --worker "{worker.id}" \

--brief-file "{phase brief path}" --senior "session:{session-id}" \

--account auto --json

```

Add --provider, --model, or --effort only when the selected worker

profile or an explicit /conduct --workers pin supplies that value.

Replace --account auto with --account {id} only when a

conduct_child_account session pin or a user --account flag names an

account. A no_account_with_room refusal leaves the phase queued; report

the soonest reset from next_reset in one line and never pick an account by

hand. Read the

JSON body, including ok, lane_id, and any admission/capacity error; do

not infer delivery from the command exit code.

  1. A repeated create for the same worker and senior continues that worker's

previous lane thread. If hq runners list --json shows that lane is still

live, deliver the follow-up brief with `hq runners message {lane-id}

--text-file {phase brief path} --json` instead of creating another lane.

An admission or capacity refusal leaves the phase queued for the next tick.

  1. Start and verify the policy-required detached watcher, then wait for an envelope, question, or state change with

`hq runners wait --any {lane-id} --for envelope --for question --for state

--timeout {seconds} --json`. Questions retain the existing user decision

path; answer them through hq runners questions answer.

  1. Read the lane's latest hq-lane-envelope.v1 from the reference reported by

hq runners list --json (or the lane's last_envelope.ref). Read the lane's

state with hq runners show {lane-id} --json. Validate the envelope and phase

handoff before continuing.

<!-- advanced-mode:end -->

6c (both modes). Record the Handoff

In default mode the subagent's handoff file carries the phase result; in

advanced mode the lane envelope carries it. Keep the existing handoff JSON

format between phases, including from_worker, to_worker, timestamp,

summary, files_created, files_modified, key_decisions,

context_for_next, and back_pressure. Append each validated handoff as one

line to workspace/orchestrator/{project}/executions/{task-id}/handoffs.jsonl.

In advanced mode the lane envelope's artifacts includes the handoff object so

the next phase can be built from the envelope rather than process state.

The senior remains responsible for the current quality gates, retries, commit

checks, lock release, execution state, and user-facing reports. A malformed

phase handoff or envelope gets the existing single retry with a stricter

reminder. A second malformed result blocks the story; do not guess from logs,

subagent transcripts, or lane state.

6c.5 Inline Codex Review (when worker == codex-reviewer)

Instead of spawning a sub-agent for codex-reviewer, run the Codex review directly via CLI. This is deterministic — cannot be skipped by sub-agent discretion.

If codex_available == true:

  1. Collect files_modified + context_for_next from the previous worker's handoff (code-reviewer).
  2. Run Codex CLI review:

```bash

cd {target_repo} && codex review --uncommitted -c model="{codex_model}" \

"Review changed files for: security, correctness, performance, style. Focus: {context_for_next from code-reviewer}" 2>&1

```

  1. Capture full output (markdown-formatted review).
  2. If output contains "critical" or "high" severity findings:
  1. Build handoff context from Codex output (add review findings to context_for_next).
  2. Log to model-usage.jsonl: {"worker":"codex-reviewer","model":"codex-cli"}.
  3. Continue to next phase (dev-qa-tester).

If codex_available == false:

Skip this step entirely for non-codex-reviewer workers; they use the normal 6c flow. The codex-reviewer runs inline in the parent and takes no pool slot or HQ worker lane.

When iterating through the worker sequence in step 6, check if the current worker is codex-reviewer:

6c.7 Acceptance Test Writer (when worker == acceptance-test-writer)

Purpose: Write executable acceptance tests from the story's e2eTests descriptions. These tests persist across stories — when story N+1 runs the full test suite, story N's acceptance tests act as regression guards.

Skip conditions (do NOT add this worker to the sequence if any are true):

When this worker runs:

  1. Read task.e2eTests from prd.json — array of test descriptions.
  2. Read all existing story test files in {repo}/__tests__/stories/ to understand the established pattern (imports, helpers, framework).
  3. Detect test framework: Check package.json for vitest/jest/bun test. Check qualityGates for test runner command. Fall back to bun test.
  4. Dispatch on the phase runner — place the prompt below in the phase brief and run it with 6c: the worker's subagent (6c-default) by default, or the 6c-lanes create-or-continue flow in advanced mode. Prompt:
## You are: acceptance-test-writer
## Task: Write acceptance tests for {task.id} - {task.title}

### Test Descriptions (from PRD)
{task.e2eTests as numbered list}

### Acceptance Criteria
{task.acceptanceCriteria as checklist}

### Context from Previous Phase
{handoff_context — what was implemented and where}

### Test Convention
- Write tests to: `{repo}/__tests__/stories/{task.id}.test.ts`
- One `describe("{task.id}: {task.title}")` block per story
- One `it()` or `test()` per e2eTests entry
- Import from the actual implementation — use real modules, not mocks
- Tests must verify the BEHAVIOR described in e2eTests, not implementation details
- Tests must be deterministic and fast (no network calls, no timers)
- If the story involves API endpoints: test request/response contracts
- If the story involves UI: test component rendering + user interactions
- If the story involves data: test transformations and edge cases

### Existing Story Tests (follow this pattern)
{contents of existing __tests__/stories/*.test.ts files, if any}

### Test Framework
{detected framework: vitest | jest | bun:test}

### Back Pressure
After writing tests, run them:
{test runner command, e.g. "bun test __tests__/stories/{task.id}.test.ts"}

All tests MUST pass before this phase completes. If a test fails, fix the test
(if the test is wrong) or flag the issue (if the implementation is wrong).

Also run ALL existing story tests to verify no regressions:
{test runner command, e.g. "bun test __tests__/stories/"}

### Output Requirements
{
  "summary": "Tests written for {task.id}",
  "files_created": ["__tests__/stories/{task.id}.test.ts"],
  "files_modified": [],
  "test_count": N,
  "all_story_tests_pass": true|false,
  "context_for_next": "Acceptance tests added: {N} tests in __tests__/stories/{task.id}.test.ts",
  "back_pressure": { "tests": "pass|fail" },
  "issues": []
}
  1. Process output: If all_story_tests_pass is false, this is a regression — the current story broke a prior story's behavior. Handle like a back-pressure failure (6d auto-recovery flow).
  2. Continue to code-reviewer with the test files included in the review scope.

Key principle: The test-writer runs AFTER implementation but BEFORE review. Tests validate the implementation against the spec. If they fail, the implementation is wrong — not the tests.

6d. Process Worker Output

In default mode, read the phase handoff from the subagent's handoff file

(phases/{phase}-{worker.id}.handoff.json, written in 6c-default) or, if the

file is missing, from the subagent's final message. Update its row in

conduct-subagents/{session-id}/runs.json.

<!-- advanced-mode:start -->

In advanced mode, read the completed lane's latest envelope from

hq runners list --json and its last_envelope.ref. The lane records its own

state; there is no record or pool-release call.

<!-- advanced-mode:end -->

In both modes, validate the worker's phase handoff before branching on success

or failure.

Then parse the worker's JSON output.

If back pressure failed:

  1. Auto-recover via codex-debugger (max 1 attempt per phase):

```bash

cd {target_repo_path} && HQ_WELCOME_BRIEF_HOOK=0 codex exec --dangerously-bypass-hook-trust --sandbox danger-full-access -c model="{codex_model}" --cd {target_repo_path} \

"Diagnose and fix back-pressure failure. Check: {failed_check_name}. Error: {stdout_stderr_from_failed_check}. Then re-run: {verification.post_execute commands}" 2>&1

```

failure details and run it with 6c: a codex-debugger subagent (6c-default) by default, or the 6c-lanes create-or-continue flow in advanced mode. This is the

existing single recovery attempt, not an additional parallel phase.

```json

{ "phase": N, "worker": "{worker}", "check": "{failed_check}", "timestamp": "ISO8601" }

```

  1. Re-run back-pressure checks after codex-debugger completes.
  2. If they pass → mark phase completed, continue pipeline (skip normal retry).
  3. If they still fail → fall back to normal retry (retry once with error context).
  4. If the retry also fails → pause and report.

If success:

workspace/orchestrator/{project}/executions/{task-id}/handoffs.jsonl. The

record keeps the established handoff format. In advanced mode it is also

included in the lane envelope artifacts for the next phase.

6d.5 Expand File Locks (Dynamic)

If file locking is enabled and worker output contains files_created or files_modified:

  1. Compute new_files = files in worker output NOT already in .file-locks.json for this story.
  2. If new_files is non-empty: acquire locks for them (same as step 5.5 item 6) — append to .file-locks.json and state.json checkedOutFiles.
  3. Also update the story's files array in prd.json with the new paths (so future sessions know the full scope).

This ensures stories that touch more files than predicted still get proper lock coverage.

6e. Update Execution State

After each phase, update workspace/orchestrator/{project}/executions/{task-id}.json:

{
  "phases": [
    {"worker": "backend-dev", "model": "opus", "status": "completed", "completed_at": "{ISO8601}"},
    {"worker": "code-reviewer", "model": "sonnet", "status": "in_progress"}
  ],
  "handoffs": [
    {
      "from": "backend-dev",
      "to": "code-reviewer",
      "context": {
        "summary": "...",
        "files_created": [],
        "files_modified": [],
        "key_decisions": [],
        "context_for_next": "..."
      }
    }
  ]
}
6e.5 Audit: Phase Completed
hq core audit-log append \
  --event phase_completed \
  --project {project} \
  --story-id {task.id} \
  --worker {worker.id} \
  --model {resolved_model} \
  --result {success|fail} \
  --duration-ms {phase_duration_ms} \
  --action "Phase {N} completed: {worker.id}" || true
6e.7 Verify the worker committed its work

After each worker returns (its subagent by default, its lane in advanced mode), verify the commit and changed-file references reported in its handoff or envelope:

cd {target_repo_path} && git status --porcelain

If the handoff or envelope reports changed files without a commit, keep the phase incomplete and return the missing commit requirement to the same worker: SendMessage to its subagent by default, or its lane in advanced mode. Do not create a parent-side commit that claims the worker completed its commit step. The orchestrator does not commit work for you.

This enforces the HQ sub-agent rule: each sub-agent MUST commit its own work before completing. The orchestrator is the safety net.

6f. Log Model Usage

<!-- Schema (all fields):

ts string (ISO8601) — timestamp of the log entry

project string — project slug (from prd.json metadata.name or directory name)

task string — story/task ID (e.g. "US-002")

worker string — worker ID (e.g. "backend-dev")

model string — resolved model name (e.g. "sonnet", "opus")

phase number — execution phase number (1-based)

company string (required) — company slug resolved from prd.metadata.company; if absent,

look up manifest.yaml entry matching the project's directory path

session_id string (optional) — ISO8601 timestamp of task start, taken from started_at

recorded in the execution state (step 5); omit if unavailable

-->

Append one line per phase to workspace/metrics/model-usage.jsonl:

{"ts":"ISO8601","project":"{project}","task":"{task.id}","worker":"{worker.id}","model":"{resolved model}","phase":N,"company":"{company}","session_id":"{session_id}"}

Resolving company: Use prd.metadata.company if present. Otherwise find the company by matching the project's path (companies/{co}/projects/…) against companies/manifest.yaml — use the matching {co} slug.

Resolving session_id: Use the started_at ISO8601 value written to the execution state in step 5. If no started_at is available, omit the field entirely.

Backward compatibility: Existing entries that lack company or session_id remain valid — parsers must treat both fields as optional when reading historical data.

Create workspace/metrics/ if it doesn't exist. This is append-only — no reads during execution.

6g. Repeat for Next Worker

Advance current_phase and repeat from 6a for the next worker in the sequence.

7. Complete Task

When all phases complete successfully:

7.0 Release File Locks and Checkout

If file locking is enabled and locks were acquired in step 5.5:

  1. Read {repoPath}/.file-locks.json.
  2. Remove all entries where owner.project === "{project}" && owner.story === "{task.id}".
  3. Write updated .file-locks.json.
  4. Read orchestrator state.json, remove matching entries from project's checkedOutFiles.
  5. Write state.json.

Release story checkout (if checkout.enabled: true):

  1. Read workspace/orchestrator/{project}/state.json.
  2. Safety check: Only release if the current session holds the checkout — verify current_task.checkedOutBy.pid matches the PID acquired in step 5.0.5.
  3. If it matches: set current_task.checkedOutBy = null, update updated_at, write state.json back.
  4. If it does NOT match (another session took over): log warning "Checkout held by different PID — not releasing" and skip.
  5. Report: Checkout released for {task.id}

This entire step runs BEFORE PRD update so locks and checkout are released even if later steps fail.

7a. Update PRD

Determine invocation mode:

// Only if NOT invoked by orchestrator:
// Update resolved prd.json (at companies/{co}/projects/{project}/prd.json)
task.passes = true

// If invoked by orchestrator: skip this write. Output status JSON instead.
// The orchestrator reads your output.json and writes passes itself.

Sub-agents may only update the current story's passes, notes, and linearIssueId fields. Never restructure, rename, add, or remove stories.

7a.2 Record Evidence (what this story actually produced)

A done-mark should mean "work exists", not "a step ran". At completion, list what the story produced — the same things you would show a reviewer — as evidence: path:<hq-relative or absolute>, repo-path:<relative to repoPath>, branch:<name>, url:<https://…>. Commits are evidence automatically. List only things that exist; the check below fails on a claim that does not.

hq core verify-story-deliverables --prd "{prd.json path}" --story "{task-id}" [--repo "{repoPath}"] \
  --evidence-json '["repo-path:…", "path:…"]' --commits-json '["<short-sha>", …]' --write
7a.3 Run Quality Gates

Before marking passes: true, run any custom quality gates from prd.metadata.qualityGates:

qualityGates:
  - "bun typecheck"
  - "bun lint"
  - "bun test"
  - "bun run build"

Run each command in the target repo. If any fail, do NOT mark the story complete — fall through to the failure path in step 8.

7a.5 Sync to Linear (if configured)

If the story has linearIssueId and prd metadata has linearCredentials:

  1. Cross-company guard: Same validation as step 5.5.5.
  2. Set issue to Done:

```bash

LINEAR_KEY=$(node -e 'process.stdout.write(JSON.parse(require("node:fs").readFileSync(0, "utf8")).apiKey)' < "{prd.metadata.linearCredentials}")

ISSUE_ID="{task.linearIssueId}"

DONE_STATE="{prd.metadata.linearDoneStateId}"

curl -s -X POST https://api.linear.app/graphql \

-H "Content-Type: application/json" \

-H "Authorization: $LINEAR_KEY" \

-d "{\"query\": \"mutation { issueUpdate(id: \\\"$ISSUE_ID\\\", input: { stateId: \\\"$DONE_STATE\\\" }) { success } }\"}"

```

Skip silently if no linearIssueId on the story or no credentials configured. Linear sync is best-effort — never block task completion on it.

7a.6 Comment on Linear Issue (if configured)

After the state sync, add a comment to the Linear issue:

COMMENT="Completed by HQ. Ready for review."

# If prd.metadata has linearReviewers (member keys from config.json members block),
# look up member name from config.json and append @mention:
# e.g. "Completed by HQ. Ready for review. cc @{reviewer-name}"

curl -s -X POST https://api.linear.app/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: $LINEAR_KEY" \
  -d "{\"query\": \"mutation { commentCreate(input: { issueId: \\\"$ISSUE_ID\\\", body: \\\"$COMMENT\\\" }) { success } }\"}"

When a task is blocked or needs resolution, comment with blocker context + @mention the relevant team member. Skip silently if not configured.

7b. Update Documentation

If the task introduced new features, changed behavior, or modified APIs, update the project's user-facing docs.

Step 1: Resolve docs location

Check PRD metadata for docsPath:

const docsPath = prd.metadata?.docsPath

If docsPath is set, use it. If not, ask the user via AskUserQuestion:

This task changed functionality. Where do docs live for this project?
(e.g., src/app/docs/, docs/, README.md, or "none")

Save the answer back to prd.metadata.docsPath so future tasks skip this question.

Step 2: Identify what needs updating

Based on files_modified, files_created, and key_decisions from worker outputs:

Step 3: Apply updates

Read the existing doc files, match the project's doc format/conventions, and edit in place. For new features with no existing doc page, create one following the project's doc conventions.

Skip this step if:

7b.5 Capture Learnings via /learn

Run /learn with structured input from execution:

{
  "task_id": "{task.id}",
  "project": "{project}",
  "source": "task-completion",
  "severity": "medium",
  "scope": "auto",
  "workers_used": ["list of workers that ran"],
  "back_pressure_failures": [{"worker": "...", "check": "...", "error": "..."}],
  "retries": N,
  "key_decisions": ["aggregated from worker outputs"],
  "issues_encountered": ["from worker outputs"],
  "patterns_discovered": ["success patterns worth preserving"]
}

/learn handles: policy file creation, event logging, dedup.

If task completed cleanly with no failures/retries/notable patterns, /learn will log the event only (no policy created).

7b.6 Reindex

Run: qmd update 2>/dev/null || true

Ensures any knowledge, worker instructions, or command rules modified during execution are immediately searchable.

7b.7 Document Release (standalone only)

When invoked standalone (not by /run-project), run /document-release {company} {project}. Skip when invoked as a sub-agent — the orchestrator runs it in its own completion flow.

Best-effort — never block task completion. Log and continue on failure.

7c.0 Audit: Task Completed
hq core audit-log append \
  --event task_completed \
  --project {project} \
  --story-id {task.id} \
  --company {company} \
  --session-id {started_at} \
  --files "{comma_separated_files_touched}" \
  --duration-ms {total_duration_ms} \
  --action "Task completed: {total_phases} phases, {files_touched_count} files" \
  --result success || true
7c. Report Completion
Task Complete: {task.id} - {task.title}

Phases: {N} completed
Workers: {list}
Files touched: {count}

Key decisions:
- {decision 1}
- {decision 2}

Learning captured: workspace/learnings/{project}/{task-id}.json
PRD updated: passes: true
7c.5 iMessage Notify (if configured)

Check core/settings/contacts.yaml for contacts whose context list includes the current project name. For each matching contact, send a brief completion update via iMessage:

# Count completed vs total stories
COMPLETED=$(grep -c '"passes": true' "${prdPath}" || echo 0)
TOTAL=$(node -e 'process.stdout.write(String(JSON.parse(require("node:fs").readFileSync(0, "utf8")).userStories.length))' < "${prdPath}")
PCT=$((COMPLETED * 100 / TOTAL))

~/scripts/imessage.sh "{contact.imessage}" \
  "{project} update: {task.title} is done! $COMPLETED/$TOTAL stories complete ($PCT%)"

Best-effort — never block task completion on iMessage delivery. Log and continue if Messages.app errors.

7d. Structured Output for Orchestrator

When invoked as a sub-agent by /run-project, end with this JSON so the orchestrator can parse results without absorbing full context:

{
  "task_id": "{task.id}",
  "status": "completed",
  "summary": "1-sentence summary of what was accomplished",
  "workers_used": ["{worker1}", "{worker2}"],
  "models_used": {"worker1": "opus", "worker2": "sonnet"},
  "back_pressure": {
    "tests": "pass|fail|skipped",
    "lint": "pass|fail|skipped",
    "typecheck": "pass|fail|skipped",
    "build": "pass|fail|skipped",
    "e2e_manifest": "pass|fail|skipped"
  }
}

8. Handle Failures

If any phase fails after retry:

8.0 Release Locks and Checkout on Failure

Same as step 7.0 — release all file locks for this story from both .file-locks.json and state.json. Also release the story checkout: read state.json, verify current_task.checkedOutBy.pid matches the PID acquired in step 5.0.5, and if so set current_task.checkedOutBy = null and write state.json back. Never orphan locks or checkouts on failure.

8.0.5 Auto-Capture Failure as Learning

Run /learn with:

{
  "source": "back-pressure-failure",
  "severity": "high",
  "scope": "worker:{failed-worker-id}",
  "back_pressure_failures": [{"worker": "...", "check": "...", "error": "..."}],
  "task_id": "{task.id}",
  "project": "{project}"
}

This ensures the failure becomes a rule BEFORE asking the user what to do.

8.0.6 Audit: Task Failed
hq core audit-log append \
  --event task_failed \
  --project {project} \
  --story-id {task.id} \
  --company {company} \
  --session-id {started_at} \
  --worker {failed_worker} \
  --error "{error_message}" \
  --action "Task failed at phase {N}: {failed_worker}" \
  --result fail || true
8.1 Update Execution State

Write status: "paused" to the execution tracking file with error details.

8.2 Report Failure
Phase {N} ({worker}) failed: {error}

Options:
1. Fix manually and resume: /execute-task {project}/{task-id} --resume
2. Skip this worker and continue
3. Abort execution

When invoked as a sub-agent, also output structured JSON on failure:

{
  "task_id": "{task.id}",
  "status": "failed",
  "summary": "Phase {N} ({worker}) failed: {brief error}",
  "workers_used": ["{workers that ran}"],
  "back_pressure": {}
}

9. Auto-Checkpoint

After task completion (or failure), write a thread checkpoint file:

{
  "thread_id": "T-{YYYYMMDD}-{HHMMSS}-auto-{task-id}",
  "version": 1,
  "type": "auto-checkpoint",
  "created_at": "{ISO8601}",
  "updated_at": "{ISO8601}",
  "workspace_root": "/Users/{your-name}/Documents/HQ",
  "cwd": "{current working directory}",
  "git": {
    "branch": "{current branch from git branch --show-current}",
    "current_commit": "{short hash from git rev-parse --short HEAD}",
    "dirty": false
  },
  "conversation_summary": "Executed {task.id} ({task.title}): {1-sentence outcome}",
  "files_touched": ["{list of files created or modified across all phases}"],
  "metadata": {
    "title": "Auto: execute-task {project}/{task-id}",
    "tags": ["auto-checkpoint", "execute-task", "{project}", "{task-id}"],
    "trigger": "worker-completion"
  }
}

Write to: workspace/threads/{thread_id}.json

Get git state with:

git rev-parse --short HEAD 2>/dev/null
git branch --show-current 2>/dev/null
git status --short 2>/dev/null

Handoff Context Format

Context passed between workers:

{
  "from_worker": "backend-dev",
  "to_worker": "code-reviewer",
  "timestamp": "ISO8601",
  "summary": "1-2 sentence description",
  "files_created": ["src/services/foo.ts"],
  "files_modified": ["src/index.ts"],
  "key_decisions": [
    "Used strategy pattern for flexibility",
    "Added caching for performance"
  ],
  "context_for_next": "Focus review on cache invalidation logic",
  "back_pressure": {
    "tests": "pass",
    "lint": "pass",
    "typecheck": "pass"
  }
}

Worked Example: Complete End-to-End Task Execution

This example shows a real task execution from start to finish, demonstrating task loading, classification, worker sequencing, phase execution, and completion.

Scenario: API Endpoint Implementation

Task: POST /api/v1/orders/{id}/cancel endpoint to allow customers to cancel pending orders.

Step 1: Parse Arguments & Load Task

Input: /execute-task order-system/US-003

Task spec loaded:

{
  "id": "US-003",
  "title": "Implement Cancel Order Endpoint",
  "description": "Add POST /api/v1/orders/{id}/cancel endpoint that cancels pending orders and notifies customer",
  "acceptance_criteria": [
    "Endpoint returns 400 if order not in 'pending' state",
    "Endpoint sends cancellation email to customer",
    "Endpoint logs action with order ID and timestamp",
    "All code passes lint and tests"
  ],
  "passes": false,
  "files": [
    "apps/api/src/routes/orders.ts",
    "apps/api/src/services/order-service.ts",
    "apps/api/src/emails/order-cancelled.ts"
  ]
}

Step 2: Classify Task Type

Analyzing task indicators:
- "endpoint" -> api_development
- "POST /api" -> REST endpoint
- "services" -> backend service
- "emails" -> integration

Classification: api_development
Matched indicators: endpoint, service, email notification

Step 3: Select Worker Sequence

Task Type: api_development
Spec Clarity: clear acceptance criteria

Worker Sequence:
Phase 1: backend-dev -> Implement service
Phase 2: code-reviewer -> Review changes
Phase 3: codex-reviewer -> Mandatory security/quality review
Phase 4: dev-qa-tester -> Verify implementation

Proceeding with 4-phase pipeline.

Step 4: Initialize Execution State

Creating execution file: workspace/orchestrator/order-system/executions/US-003.json

{
  "task_id": "US-003",
  "project": "order-system",
  "started_at": "2026-03-08T14:35:22Z",
  "status": "in_progress",
  "current_phase": 1,
  "phases": [
    {"worker": "backend-dev", "status": "pending"},
    {"worker": "code-reviewer", "status": "pending"},
    {"worker": "codex-reviewer", "status": "pending"},
    {"worker": "dev-qa-tester", "status": "pending"}
  ],
  "handoffs": [],
  "codex_debug_attempts": []
}

Step 5: Phase 1 — backend-dev

Worker output (JSON):

{
  "summary": "Implemented POST /api/v1/orders/{id}/cancel endpoint with state validation and email notification",
  "files_created": [
    "apps/api/src/emails/order-cancelled.ts"
  ],
  "files_modified": [
    "apps/api/src/routes/orders.ts",
    "apps/api/src/services/order-service.ts"
  ],
  "key_decisions": [
    "Used order state machine pattern (pending -> cancelled transition only)",
    "Email notification async to prevent timeout on customer signal path",
    "Added database transaction to ensure order + audit log atomicity"
  ],
  "context_for_next": "Focus review on transaction semantics. Verify email template vars match order schema (customer_name, order_id, created_at). Check cancellation reasons logged to audit table.",
  "back_pressure": {
    "tests": "pass",
    "lint": "pass",
    "typecheck": "pass",
    "build": "pass"
  },
  "issues": []
}

Files created/modified summary:

apps/api/src/emails/order-cancelled.ts (52 new lines)
apps/api/src/routes/orders.ts (+18 lines, cancel route added)
apps/api/src/services/order-service.ts (+31 lines, cancelOrder method added)

All back pressure checks pass:
npm test (42 passed, 0 failed)
npm run lint (0 issues)
npm run check (0 TS errors)

Step 6: Phase 2 — code-reviewer

Worker receives handoff context:

From: backend-dev
Summary: Implemented cancel endpoint with state validation and email

Key files: orders.ts, order-service.ts, order-cancelled.ts
Decision: Used state machine pattern for order transitions
Focus: Verify transaction semantics and email template vars

Worker output (JSON):

{
  "summary": "Code review passed. State machine pattern correct. Transaction boundaries validated. Email template vars match schema.",
  "files_created": [],
  "files_modified": [],
  "key_decisions": [
    "Confirmed transaction includes both order update and audit log insert",
    "Email template correctly references order.customer_name (not customer.name)",
    "Error handling appropriate: 400 for non-pending orders, 500 for service errors"
  ],
  "context_for_next": "Code changes are production-ready. Codex will provide additional security perspective. QA should test: cancel pending order (success), cancel completed order (400 error), email delivery timing.",
  "back_pressure": {
    "tests": "pass",
    "lint": "pass",
    "typecheck": "pass",
    "build": "pass"
  },
  "issues": []
}

Step 7: Phase 3 — codex-reviewer (Inline Execution)

Running Codex CLI directly:

cd repos/private/order-system && codex review --uncommitted \
  "Review changed files for: security, correctness, performance, style. Focus: API endpoint security, transaction safety, email delivery reliability"

Codex output:

CODEX REVIEW: order-system (uncommitted changes)

Files analyzed: 3 (73 total lines changed)

SECURITY:
- No SQL injection (using parameterized queries)
- No auth bypass (endpoint checks user.id ownership)
- Email rate limiting OK (uses queue, not inline)

CORRECTNESS:
- Transaction boundary correct (both operations in same transaction)
- Error messages don't leak internal state
- Idempotency: calling twice won't double-cancel (state check before update)

PERFORMANCE:
- Minor: Email sending is async but no timeout (could hang indefinitely)
  Suggestion: Add 30s timeout to email task

Code Quality: A
Severity: info (not critical path)

Handoff for next phase:

Codex review completed. One informational finding: email timeout.
Ready for QA testing. All critical checks pass.

Step 8: Phase 4 — dev-qa-tester

Receives full handoff context:

Implemented: POST /api/v1/orders/{id}/cancel endpoint
Code review: Passed, state machine pattern correct
Codex security: Passed, email timeout noted as info-level
Test coverage: All unit tests passing

Your tasks:
1. Test cancel pending order -> returns 200, email sent, audit logged
2. Test cancel completed order -> returns 400, email NOT sent
3. Test auth: Verify user can only cancel own orders

QA Worker Output:

{
  "summary": "All acceptance criteria verified. E2E tests pass: cancel pending (200), cancel completed (400), auth check (403 for other user orders)",
  "files_created": [
    "apps/api/tests/e2e/cancel-order.e2e.ts"
  ],
  "files_modified": [
    "apps/api/tests/cancel-order.test.ts"
  ],
  "key_decisions": [
    "Added E2E test covering auth boundary (user A cannot cancel user B's orders)",
    "Email delivery tested via mock SES (no actual email sent)",
    "Tested idempotency: cancelling twice returns 200 both times (same result)"
  ],
  "context_for_next": "All acceptance criteria met. Endpoint ready for production.",
  "back_pressure": {
    "tests": "pass",
    "lint": "pass",
    "typecheck": "pass",
    "build": "pass"
  },
  "issues": []
}

Step 9: Complete Task

Update prd.json:

{
  "id": "US-003",
  "title": "Implement Cancel Order Endpoint",
  "passes": true,
  "linearIssueId": "ORD-42",
  "notes": "Completed 2026-03-08. All phases passed (backend -> review -> codex -> qa)."
}

Sync Linear:

Issue ORD-42 -> Done state
Comment: "Completed by HQ. Ready for production. Codex flagged email timeout (info-level)."

Final Report:

Task Complete: US-003 - Implement Cancel Order Endpoint

Phases: 4 completed
Workers: backend-dev, code-reviewer, codex-reviewer, dev-qa-tester
Files touched: 5 (3 modified, 2 created with tests)

Key decisions:
- Used state machine pattern for order transitions
- Email notification async with rate limiting
- Added comprehensive auth + idempotency tests

Back pressure summary:
All tests pass (84 total)
All lint checks pass
All TypeScript checks pass
Build succeeds

Learning captured: workspace/learnings/order-system/US-003.json
PRD updated: passes: true
Linear synced: issue -> Done state

Examples

execute-task campaign-migration/US-003    # Execute a specific story
execute-task order-system/CAM-001         # Full-stack story
execute-task landing-page/US-001          # UI component story

Rules

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.