Skip to main content

Task Lifecycle — Creation & Execution Reference

This is the complete reference for how an AIFactory task is created and driven to completion, and every input, variable, option and setting that controls it. It is the contract a caller (a human in the portal, the CLI, or an upstream system like PFactory) needs in order to create a task with all the information AIFactory needs to run it all the way.

For the upstream signed handoff that lets AIFactory skip planning entirely, see Task Contract v2.


1. The pipeline at a glance

create task ─▶ SPEC (3–8 phases) ─▶ PLAN (implementation_plan.json)
─▶ review gate (tiered) ─▶ BUILD (coder, serial or parallel waves)
─▶ QA (review + fix loop) ─▶ done / human_review
  • Spec creation (apps/backend/runners/spec_runner.py): a dynamic 3–8 phase pipeline scaled to complexity.
  • Build (apps/backend/run.pyagents/coder.py:run_autonomous_agent): planner → coder (serial or parallel waves) → QA reviewer → QA fixer.
  • Status is tracked in implementation_plan.json (status, planStatus) and surfaced to the portal Kanban.

2. Creating a task

2.1 Web API

POST /api/tasks/create-and-run (apps/web-server/server/routes/execution.py) — CreateAndRunRequest:

FieldTypeReq?Notes
titlestrYesTask title
descriptionstrYesTask description (full; not truncated)
complexitysimple|standard|complexNoForces tier; else AI-assessed
auto_continueboolNoDefault true — spec→plan→build in one run
parallelboolNoEnable parallel waves (→ task_metadata.json)
workersintNoMax concurrent subtasks (default 3)
modelstrNoModel override (shorthand or full id)
modequick|fullNoDefault full; auto-quick for simple
baseBranchstrNoGit base for the worktree
provenanceobjectNoUpstream traceability (see below)

POST /api/tasks/from-planFromPlanRequest: ingest a signed implementation_plan.json and skip the spec pipeline. See Task Contract v2.

Provenance (TaskProvenance, optional but recommended for upstream callers): session_id, issue_number, repo, source (e.g. pfactory), trusted_plan, approved_by, approval_timestamp, plan_contract_version, signature.

2.2 CLI

# Spec creation
python runners/spec_runner.py --task "Add rate limiting" [--complexity simple|standard|complex] [--no-ai-assessment]
# Build
python run.py --spec 001 [--model sonnet|opus|haiku|<id>] [--parallel] [--workers N]
python run.py --spec 001 --review | --merge | --discard

3. On-disk task artifacts

Per spec under .aifactory/specs/<id>/:

FileProduced byCarries
requirements.jsonspec gatherertitle, description, workflow_type, services_involved, metadata, provenance
task_metadata.jsonweb-server on createthe execution settings (see §4)
context.jsondiscoverytask_description, scoped_services, files_to_modify/reference, patterns
spec.mdspec writerOverview, Workflow Type, Task Scope, Success Criteria, QA Acceptance Criteria
implementation_plan.jsonplannerthe plan (see §6)
qa_report.md / QA_FIX_REQUEST.mdQAacceptance results / fix requests
parallel_report.json, build_report.jsonexecutorwave/profile metrics
.aifactory/.aifactory-security.jsonanalyzerthe command allowlist (see §9)

4. task_metadata.json — execution settings

The single place execution options live (apps/backend/phase_config.py TaskMetadataConfig). All optional; sensible defaults apply.

FieldTypeMeaning
isAutoProfileboolUse per-phase model/thinking maps
phaseModels{phase: model}Per-phase model override (wins when auto-profile)
phaseThinking{phase: level}Per-phase thinking level
modelstrSingle model override (non-auto)
thinkingLevelstrSingle thinking level
fastModeboolFaster spec assessment
soloModeboolOne self-directed agent (skips planner + gates + QA loop)
parallelboolParallel waves
workersintMax concurrent subtasks
modequick|fullPrompt/context depth
complexitystrTier (drives phase count)
baseBranchstrGit base branch
selectedSkillslistUser-chosen skills
suggestedSkillslistAI-suggested skills (#394)

5. Model & provider selection

apps/backend/phase_config.py resolves the model per phase, in priority order: 1) per-phase phaseModels (if isAutoProfile) → 2) CLI --model3) single model4) DEFAULT_PHASE_MODELS.

  • Default phase models: spec/planning/coding/qa/qa_fixer = sonnet.
  • Shorthand → id (MODEL_ID_MAP): opus=claude-opus-4-8, sonnet=claude-sonnet-4-6, haiku=claude-haiku-4-5-….
  • Thinking (THINKING_BUDGET_MAP): none/low=1024/medium=4096/high=16384; default phase thinking = planning/qa high, coding/spec medium, qa_fixer low. Adaptive-thinking models (Opus 4.6+/Sonnet 4.6) use {"type":"adaptive"}.
  • Provider is inferred from the model string (phase_config.infer_provider_from_model) and resolved by providers/factory.pyclaude (default), codex, antigravity, ollama, copilot, opencode, openai-compatible, gemini. Never call the Anthropic SDK directly; route through core.client.create_client / providers.factory.

6. The implementation plan (implementation_plan.json)

LevelFieldNotes
Planfeature, workflow_type, phases (all required)services_involved, final_acceptance, required_commands, status fields
Phasephase, name, subtasks (all required)type, depends_on (int or slug), parallel_safe
Subtaskid, description (both required)status, depends_on, files_to_create/files_to_modify, model, patterns_from, verification, required_commands
Verificationtype (required)command/api/browser/component/manual/none/e2e + run/url/method/expect_*/scenario
  • depends_on accepts integer phase numbers or planner slugs ("phase-2-modules") — resolved to a phase number by the executor.
  • parallel_safe + per-subtask depends_on + file footprints drive wave scheduling (#376).
  • required_commands are verification command names seeded into the security allowlist before agents run (see §9).

7. Execution options

  • Parallel waves (--parallel --workers N, or task_metadata): the wave scheduler groups non-dependent subtasks (by depends_on + file footprint) into concurrent waves run in isolated sub-worktrees, merged sequentially. Metrics in parallel_report.json / build_report.json.
  • Solo mode (AIFACTORY_SOLO_MODE / soloMode): one agent plans+codes+ verifies; skips the planner session, plan-review gate, and QA loop.
  • Auto-continue (auto_continue, default on): runs spec→plan→build as one session; off pauses at gates.
  • Quick/full mode (mode): prompt + context depth; quick auto-derived for simple complexity.
  • Complexity (simple/standard/complex): controls the spec phase count (3 / 6–7 / 8). AI-assessed via complexity_assessor.md unless forced.

8. Agents, subagents & tools

Agent tool permissions are defined in apps/backend/agents/tools_pkg/models.py and applied by core/client.py.

AgentTools (summary)Thinking default
plannerRead/Write/Bash/Web + Context7 + Graphiti + aifactory MCPhigh
coderRead/Write/Bash/Web + Context7 + Graphiti + aifactory MCPnone
qa_reviewer+ browser; aifactory update_qa_statushigh
qa_fixer+ browser; update_subtask_statusmedium
spec agentsgatherer/researcher/writer/critic (scoped read/write/web)medium–high
  • BMad subagents (integrations/bmad/subagents/): requirements_analyst, codebase_analyzer, technical_evaluator — opt-in analysis helpers.
  • Skills (#394): a deterministic matcher suggests suggestedSkills from the task; the planner may refine into selectedSkills.

9. Security profile (command allowlist)

bash_security_hook gates every Bash call against the profile at the agent's cwd (<cwd>/.aifactory/.aifactory-security.json = base | stack | script | custom commands). The profile is generated by project/analyzer.py (cached, mtime- invalidated). A Python project always allowlists its verification toolchain (uv/pytest/ruff/mypy/…), and a plan's required_commands are seeded into custom_commands before agents run (serial/QA, each parallel sub-worktree, and on signed-plan ingest). The SDK runs bypassPermissions, which does not bypass this hook — the allowlist is the gate.


10. Review tiers & QA

  • Review tier (apps/backend/review_tier.py): auto (trusted/solo/trivial), async (build continues, human comments fold in), blocking (gate before coding/merge). High-risk paths (auth, secrets, migrations, infra, payments) or low planner confidence → blocking.
  • QA: qa_reviewer validates acceptance criteria → qa_report.md; on rejection qa_fixer resolves issues in a bounded loop. Gates use gate_runner.detect_gates/run_gates.
  • Agent red-flags (apps/backend/prompts/coder.md, qa_fixer.md): both prompts carry a "Red flags — STOP, do not claim success" block listing the silent-failure modes that have shipped dead builds as green (no real change, a failed tool/credential such as a 401, every generated test failing identically, skipping a step because it "probably works"). The closing rule is evidence ends the task — the diff plus the checks that pass over it.

11. Completion event & the evidence gate

When a task reaches a terminal state the web-server emits the RFC-0001 completion-event envelope (apps/web-server/server/services/completion.py, build_completion_event) keyed by correlation_key, so the cockpit (CFactory) and TFactory can thread the unit of work end to end.

  • Usage block (additive, schema v1.3): when token_usage.json records work, the event carries usage with the scalar token/cost aggregate plus, for parallel multi-provider builds, a per-worker usage.workers[] breakdown and usage.by_provider / usage.by_model rollups. An optional observe-only usage.budget{limit_usd, spent_usd, exceeded} block is attached when the contract set execution.budget_usd; it reports overspend but never aborts a build.
  • Evidence gate (RFC-0001a): a build may only claim a success status (completed, passed, verified, succeeded) if it carries proof it ran. A build event whose usage.total_tokens is 0 is downgraded to failed with halt_reason: "no_evidence: build emitted 0 tokens (did not run)", and the event gains an evidence{proof_kind, total_tokens, cost_usd} block. This closes the failure mode where an expired provider credential produced a stub plan that finished in seconds and was historically reported green. The gate is scoped to build events that carry usage — it never touches the legitimate failed path or non-build events.

12. Required vs optional — minimum to drive a task end to end

Required: title + description (creation); for a plan: feature, workflow_type, phases, and per subtask id + description. For the skip-planning fast-path: a valid approval signature + completeness (see Task Contract v2).

Optional but high-value: complexity, parallel/workers, model/ phaseModels, thinkingLevel, mode, per-subtask depends_on + files_to_* (wave scheduling), verification, required_commands, provenance.