# Workflows

## Purpose

This framework runs work as a pipeline:

1. `task` creates or syncs `task.md`
2. `plan` creates or refines `plan.md`
3. `module` builds code and maintains `module.md`

Each run is anchored to a single `work_folder`. All state, artifacts, and logs live there.

## Core Model

- Workflow entrypoints wrap execution in `context_scope(...)`.
- Agents read context via `get_context()` and derive paths internally.
- Workflows return `None` on success. Failures are exceptions.
- `depth` is internal runtime context metadata. Public CLI invocations ignore `--depth`.

## Data Contracts

### `task.md`
- Frontmatter: `id`, `name`, `modules`, optional `assignee`, `cycle`, `status`.
- `modules` is the only targeting field. `target_modules` is not used.

### `plan.md`
- Technical implementation plan. Final format follows `refs/plan-template.md`.

### `module.md`
- Build report. Builder maintains `## What Changed` and `## Revision History`.
- Orchestrator prepends a `# Build Status` block with pass/fail metadata.

### Agent output format
```text
[RESULT]
status: PASS or FAIL or DONE
[NOTES]
Details here.
```

## Workflow: Task

- **File**: `workflows/task/create_task.py`
- **Required**: `work_folder`, `task_id`
- **Optional**: `task_prefix`, `size`, `description`, `title`, `modules`, `sync`/`sync_to_linear`, `api_key`, `team_id`

### Flow
1. Resolve Linear prefix from `.mixer/settings.json` (`linear.team_prefix`). Optional `task_prefix` must match it when provided.
2. Detect Linear ID by prefix: `task_id.startswith(f"{resolved_prefix}-")`.
3. If Linear: load issue from Linear into `task.md`.
4. If local and `task.md` is missing: require `description`, write `task.md` with title + description.
5. If local and `task.md` already exists and `description` is omitted: normalize frontmatter (`id`/`name`) without rewriting body.
6. Ensure modules: if provided, write directly. Otherwise run router agent.
7. If sync enabled: update Linear (if Linear source) or push to Linear and rename `work_folder` (if local source).

### Linear sync (`workflows/task/linear_sync.py`)
- `load(...)`: fetch Linear issue, write `task.md`.
- `push(...)`: create Linear issue from `task.md`.
- `update(...)`: update existing Linear issue title/description.
- API key resolved from `--api_key` or env (`LINEAR_API_KEY`).
- Team ID resolved from args, env (`LINEAR_TEAM_ID`), or `settings.json` (`linear.team_id`).

### Agents
- `router.py`: returns target `modules` from task + project context.
- `builder.py`: structures raw description into `task.md` (not used by current flow).

## Workflow: Plan

- **File**: `workflows/plan/create_plan.py`
- **Required**: `work_folder`
- **Optional**: `size`, `plan_builder_provider` (claude/gemini/codex), `branch_count` (default 1), `max_revisions` (default 2)

### Flow
1. **Build phase**:
   - `branch_count == 1`: run builder once.
   - `branch_count > 1`: create branch folders, run builders concurrently, merge into root `plan.md`.
2. **Review loop** (up to `max_revisions`): run checkers concurrently, resume builder/merger on failure.
3. **Format**: run formatter on final `plan.md`.

### Review aggregator (`workflows/plan/review.py`)
- Runs rules, completeness, and architecture checkers in parallel.
- Aggregates failures into one `FAIL`. Returns `PASS` if all pass.
- No synthesizer step.

### Agents
- `builder.py`: builds initial `plan.md`. `run_resume(...)` revises with feedback.
- `merger.py`: merges branch plans into root `plan.md`. `run_resume(...)` revises merged plan.
- `formatter.py`: reformats plan to match template.
- `rules_checker.py`: checks plan against project rules.
- `completeness_checker.py`: checks task requirement coverage.
- `architecture_checker.py`: checks architecture compliance.

## Workflow: Module

- **File**: `workflows/module/create_module.py`
- **Required**: `work_folder`
- **Optional**: `size`, `max_test_iterations` (default 5), `auto_commit` (default true), `auto_merge` (default false)

### Flow
1. Optional git checkpoint if `auto_commit=true`.
2. Run builder (run index 1).
3. Tester loop (up to `max_test_iterations`): if fail, resume builder with feedback. No extra builder pass after final failure.
4. Update `# Build Status` block in `module.md`.
5. On failure: raise `RuntimeError`. On success: optionally commit/push.

### Agents
- `builder.py`: implements code from plan, maintains `module.md`. `run_resume(...)` applies tester feedback.
- `tester.py`: validates implementation. Ignores `# Build Status` for verdicts.

## Branching and Context

- Plan workflow supports branching via `branch_count`. Branches run in separate folders, final plan in root.
- Module and task workflows are single-path.
- `asyncio.gather()` auto-isolates context. Sequential sub-orchestrators need `copy_context().run()`.

## Failure and Retry

- Parameter validation: raise immediately.
- Agent format issues: retry once when `expect_result=True`.
- Plan review: retries up to `max_revisions`.
- Module build: retries up to `max_test_iterations`, then hard-fails.

## Logging

Per `work_folder/logs/`:
- `trace.log`: flat start/end/error events for live tailing.
- `trace.md`: structured trace with depth headings.
- `raw.log`: full prompts/responses.

## End-to-End

1. `task` writes `task.md` and resolves `modules`.
2. `plan` reads `task.md`, builds `plan.md`, reviews, formats.
3. `module` reads `task.md` + `plan.md`, implements code, tests iteratively, maintains `module.md`.
4. Caller checks files in `work_folder`. Failures are exceptions.

<!-- SKILL_SYNC_WORKFLOW_GUIDE_START -->
<workflow-registry>
### Workflow: create_task
- Command: `python3 -m mixersystem run task`
- Required parameters:
  - `work_folder` (path)
  - `task_id` (string)
- Optional parameters and defaults:
  - `task_prefix` (optional; enables Linear routing only when it matches `.mixer/settings.json` `linear.team_prefix`)
  - `size` (default: `"M"`)
  - `description` (required for new local tasks when `task.md` does not already exist)
  - `title` (default local title: `"New Task"`)
  - `modules` (default: `None`; when missing, router resolves modules)
  - `sync` (default: `None`; alias for `sync_to_linear`)
  - `sync_to_linear` (default: `None`)
  - `api_key` (default: `None`, else env)
  - `team_id` (default: `None`, else settings/env)
- Behavior notes:
  - Linear IDs are detected only when `task_id` matches the configured team prefix in `.mixer/settings.json` (`linear.team_prefix`).
  - If `task_prefix` is provided, it must match the configured settings prefix.
  - Local task IDs require `description` only when creating a new `task.md`; existing task files can be normalized without description.
  - If `modules` is missing and task modules are `all`, router runs to resolve modules.
  - If sync is enabled:
    - Linear source -> update existing Linear issue.
    - Local source -> create Linear issue, update frontmatter `id`, rename `work_folder` to issue id.

### Workflow: create_plan
- Command: `python3 -m mixersystem run plan`
- Required parameters:
  - `work_folder` (path)
- Optional parameters and defaults:
  - `size` (default: `"M"`)
  - `plan_builder_provider` (default: `"claude"`, allowed: `claude|gemini|codex`)
  - `branch_count` (default: `1`)
  - `max_revisions` (default: `2`, allows `0`)
- Behavior notes:
  - `branch_count=1`: single plan builder flow.
  - `branch_count>1`: branch plans + merge in root work folder.
  - Review loop retries up to `max_revisions`.
  - Formatter always runs after build/review.

### Workflow: create_module
- Command: `python3 -m mixersystem run module`
- Required parameters:
  - `work_folder` (path)
- Optional parameters and defaults:
  - `size` (default: `"M"`)
  - `max_test_iterations` (default: `5`, must be `>=1`)
  - `auto_commit` (default: `true`)
  - `auto_merge` (default: `false`)
- Behavior notes:
  - Runs builder/test loop only (no module reviewer loop).
  - On final test failure, updates `module.md` status and raises error.
  - On success, updates `module.md` status and optionally commits/pushes if `auto_merge=true`.

### Expected artifacts per work folder
- `task.md` from `create_task`.
- `plan.md` from `create_plan`.
- `module.md` from `create_module`.
- Logs under `logs/` for traceability.

</workflow-registry>
<!-- SKILL_SYNC_WORKFLOW_GUIDE_END -->
