Pipeline Authoring Guide
Audience: Users — Pipeline authors designing stages, contracts, and routing.
I. Hard Rules (Enforced by hpilot validate)
These constraints are non-negotiable and will block execution if violated:
- One Executor: Each stage is either an harness-backed stage or a command stage. Use
promptfor agent instructions orcommandfor a trusted shell command, never both.promptis the preferred alias for the legacyprompt_templatespelling. Defining both prompt spellings is also invalid, even if either value is null. - Contract Routing: Stages with a
contractmust definecontract.routesand must not define a top-levelnext_stage. Every route target must match a configured stage. Runhpilot validatebefore execution. - Local Contract Validation: Contract-enabled stages are validated locally from their YAML artifact. A valid recognized
Statusdrives routing without the verifier LLM. Invalid artifacts produce local repair guidance. Contract-only and command-only effective slices do not requirellm.api_key; any effective non-contract agent stage does. - Field Integrity: Every injected field must be defined in
contract.fieldswith a realistic example.contract.field_definitionsalso supports descriptions and one or more examples. - Self-Referencing Routes: A route back to the same stage should use
max_iterationsandmax_iterations_next_stageto prevent unbounded loops. - Tracked Documentation: Copy durable usage and workflow guidance into tracked files under
docs/and, when relevant,README.md. Do not leave guidance only in ignored directories. - No Route Instructions in
prompt: Contract guidance is appended automatically after the rendered prompt and injection appendix. Do not author route instructions, artifact emit directives, or judgment directives inprompt. Behavioral constraints may refer to a status, such as prohibitingAPPROVEDafter the stage edits files. - Contract Artifact Status Key: Contract artifacts must use capitalized
Status. Lowercasestatusis rejected. - Artifact corrections. When a contract artifact is missing or invalid, the correction names the artifact path and tells the agent how to write a valid result. For a readable YAML mapping, hpilot reports the task, status, and field issues it can identify together. Only fields required by the selected route belong alongside
Statusand, when configured,Completed Tasks. - Safe Stage Names: Stage names may contain normal text and spaces, but must not be
.or..and must not contain path separators or control characters. hpilot uses stage names in generated artifact and log paths. - Contract Schema: A stage
contractaccepts onlyfields,field_definitions,field_descriptions,required_tasks, androutes; unknown keys are rejected at load time with a message naming the offending field(s).
Pipeline-wide instructions
For an agent stage, max_retries is the total budget of completed agent turns in one stage visit. The first turn and every in-session continuation each use one slot; a failed launch before a completed turn also uses one slot. Once the budget is exhausted, hpilot reports the stage failure without sending another repair prompt. A new routed visit follows the stage's existing retry-counter rules.
When the same short execution-context rule belongs in every harness-backed stage prompt, define the optional top-level instructions string once instead of duplicating it in each stage. hpilot prepends the resulting <instructions> block to every stage attempt and routed revisit while preserving each stage's authored prompt; literal command stages are unchanged. See Global Instructions: instructions for normalization, canonical prompt ordering, retry behavior, hpilot-only scope, diagnostics, and the distinction between advisory instructions and write enforcement.
Command stages
Command stages run a non-empty shell string from the workspace root. Pipeline configuration is trusted executable input. POSIX shell features such as pipes, globs, and && are supported, and normal context placeholders such as {stage_name} and {objective} are rendered before launch.
stages:
- name: Test
command: uv run pytest | tee test-output.txt
max_retries: 2
cleanup:
- .pytest_cache
backup_artifacts:
- test-output.txt
next_stage: Package
- name: Package
command: uv buildLiteral braces must be doubled. For example, write awk '{{print $1}}' so the shell receives awk '{print $1}'. Unknown, syntactically valid placeholders are checked at runtime because routed context can add keys.
| Field | Command-stage rule |
|---|---|
max_retries | Allowed; caps total command launches or, for an agent stage, completed agent turns across launches and in-session continuations. |
next_stage | Allowed; list order is the default. Command cycles are invalid. |
cleanup | Allowed; runs before every launch. |
backup_artifacts | Allowed; runs after success. |
prompt, prompt_template | Rejected; a stage has one executor. |
contract | Rejected; exit status is the gate result. |
max_iterations, max_iterations_next_stage | Rejected; commands do not join refinement loops. |
reset_iterations | Rejected; commands do not manage iteration state. |
keep_artifacts | Rejected; post-run contract enforcement does not apply. |
read_only_paths | Rejected; commands may write workspace files. |
Exit zero succeeds. Non-zero exits and start or placeholder-rendering failures use the normal retry cap. Combined stdout and stderr are stored without rewriting in .hpilot/logs/stages/<stage>.jsonl and mirrored to stderr with stage and command attribution. A command-only effective slice needs no objective, coding agent, agent executable, or verifier API key.
Command stages cannot participate in routing cycles. Unlike harness-backed stages, they cannot declare max_iterations, so hpilot rejects direct and indirect command-stage cycles while loading the pipeline.
Pipeline lifecycle hooks
Use the active global configuration for user- or machine-level preparation, telemetry, or reporting shared across workspaces:
# ~/.hpilot/config.yaml or .hpilot/config.yaml
hooks:
before_stage: scripts/lifecycle.sh
after_stage: scripts/lifecycle.shUse root-level plural hooks in hpilot.yaml only when the pipeline needs to replace or disable a global phase:
hooks:
before_stage: scripts/project-lifecycle.sh
after_stage: null
stages:
- name: Implement
- name: Test
command: uv run pytestAn omitted pipeline phase inherits its global command, a pipeline string replaces it, and a phase-level null disables it. An omitted, empty, or whole-mapping null pipeline section inherits both phases. Global and pipeline commands never run as an automatic chain.
The plural name is distinct from the singular verifier mapping. A lifecycle field under an individual stage is rejected. Put conditional logic inside the script when only selected stages need an action. Each hook value is a literal shell command: hpilot does not render placeholders or otherwise interpret braces in it.
The commands run from the pipeline workspace on every retry and routed revisit. Attempt numbers are one-based within a visit. Iteration numbers are one-based across visits, and retries keep the same iteration number. hpilot reloads global defaults and resolves one immutable pair before each attempt. An edit during an attempt cannot change that attempt's after hook; the edit applies at the next attempt boundary.
Both phases define all of these variables:
HPILOT_HOOK_PHASE,HPILOT_STAGE_NAME, andHPILOT_STAGE_EXECUTORHPILOT_STAGE_ATTEMPT,HPILOT_STAGE_MAX_RETRIES,HPILOT_STAGE_ITERATION, andHPILOT_STAGE_MAX_ITERATIONSHPILOT_STAGE_SUCCESS,HPILOT_STAGE_EXIT_CODE, andHPILOT_STAGE_ERRORHPILOT_WORKSPACE_ROOTandHPILOT_OBJECTIVEHPILOT_ROUTED_CONTEXT_JSON
Before-hook success, exit, and error values are empty. After-hook success is true or false; exit and error are empty when unavailable. The objective is the rendered stage prompt or objective text. Routed context is exposed as one JSON object whose keys are routed names and whose values are strings. An empty routed context is {}. The JSON preserves non-ASCII text and key insertion order.
Hook variables override inherited values with the same names while every other user environment variable remains available. Routed context can contain sensitive values, so only use trusted hook commands and scripts.
Braces require no escaping in lifecycle hooks. For example, awk '{print $1}', JSON literals, {missing}, and {{literal}} all reach the shell exactly as configured. This differs from a stage command, which remains a template and still requires doubled literal braces.
Migrating placeholder-based hooks
This is a breaking change. A legacy command passed rendered values as positional arguments:
hooks:
before_stage: scripts/lifecycle.sh {stage_name}
after_stage: scripts/lifecycle.sh {stage_name} {stage_success}Replace it with an argument-free command:
hooks:
before_stage: scripts/lifecycle.sh
after_stage: scripts/lifecycle.shRead the metadata in the script:
#!/usr/bin/env bash
set -euo pipefail
stage_name="${HPILOT_STAGE_NAME}"
stage_success="${HPILOT_STAGE_SUCCESS}"
if [[ "${HPILOT_HOOK_PHASE}" == "before_stage" ]]; then
printf 'starting %s\n' "${stage_name}"
else
printf 'finished %s (success=%s)\n' "${stage_name}" "${stage_success}"
fiA before-hook failure consumes the ordinary retry budget and skips the stage and after hook. An after-hook failure converts stage success to failure. If the stage and after hook both fail, the stage error remains primary and the hook error is appended. Consequently, an after failure prevents backup, completion, context injection, and routing.
Hook output is appended chronologically to the stage log and attributed as hook:before_stage or hook:after_stage. Structured logs use HookRunning, HookCompleted, and HookFailed; no hook-specific WebSocket events are emitted. Each entry records the literal configured command. Interruption uses the normal process-group cancellation path, skips any later after hook, and terminates the pipeline.
Pipeline lifecycle hooks are trusted, unsandboxed shell commands. They inherit the user environment and may run repeatedly. Author idempotent scripts and never interpolate untrusted routed values without appropriate shell handling.
Maintenance note: this guide is approaching the preferred size. Split command and contract authoring into audience-preserving guides in a future documentation-only change.
II. Detailed Contract Example: Review Spec
This example demonstrates a complex routing structure with targeted context injections.
stages:
- name: Review Spec
max_iterations: 3
max_iterations_next_stage: Plan
prompt: |
Review the current specification against:
{objective}
If refinements are needed, edit the canonical spec files directly.
Do not use `PLANNING_READY` status if this review run edited the specification.
contract:
fields:
Approved Specification:
description: A concise approved spec snapshot for downstream planning.
example: |
Build an approval workflow that lets reviewers accept or reject submissions with visible status history.
Findings:
description: Specific review findings explaining why the spec cannot advance.
example: |
- The reviewer role is not defined clearly enough.
Required Changes:
description: Concrete edits the refine stage must make.
example: |
- Clarify which user roles can approve or reject.
Replanning Reason:
description: Why the current specification cannot be repaired by another focused review pass.
example: |
The requested workflow conflicts with the approved product scope and requires a new plan.
routes:
PLANNING_READY:
description: Specification is complete enough for planning.
next_stage: Plan
injections: [Approved Specification]
CHANGES_MADE:
description: This review run edited the specification and another review pass is required.
next_stage: Review Spec
REPLAN_REQUIRED:
description: The specification requires broader replanning instead of another review pass.
next_stage: Plan
injections: [Replanning Reason]
ignore_max_iterations: trueWhat the agent receives
The guidance tells the agent to finish the review and its required checks, then write .hpilot/contracts/artifacts/Review Spec.yaml. The status table shows how the review outcome determines the required fields and the next stage.
| Status | Meaning | Required route fields | Next stage |
|---|---|---|---|
PLANNING_READY | Specification is complete enough for planning. | Approved Specification | Plan |
CHANGES_MADE | This review run edited the specification and another review pass is required. | None | Review Spec |
REPLAN_REQUIRED | The specification requires broader replanning instead of another review pass. | Replanning Reason | Plan |
Each status has a complete YAML example using the exact field names from the contract. For example, a review that selects REPLAN_REQUIRED writes its reason alongside the status.
Status: REPLAN_REQUIRED
Replanning Reason: |
The requested workflow conflicts with the approved product scope and requires a new plan.Run hpilot validate --show-guidance to preview the full guidance for your configuration.
Contract route fields
| Field | Type | Required | Description |
|---|---|---|---|
next_stage | str or null | No | Configured stage to enter after the route is selected. Omit it for a terminal route. |
description | str | No | Human-readable meaning used in generated contract guidance. |
injections | list[str] | No | Contract fields to promote into the selected target stage's latest routed context. Default []. |
ignore_max_iterations | bool | No | When true, prevents max_iterations_next_stage from replacing this route on the limiting completion. Default false. |
Nonempty injected fields appear after the target stage's authored prompt as a single <handoff> block headed Messages from previous stage:. hpilot retains their configured order, field headings, and text; it omits the block when the selected fields contain no messages. Template variables such as {latest_contract_findings} still expose the plain field value.
ignore_max_iterations accepts only a YAML boolean. Quoted strings and integers are rejected, as are unknown route keys. An ignoring route may target another stage or terminate, but it cannot route directly back to its containing stage because that would bypass the stage's maximum iteration limit indefinitely. The field is accepted but inert on a stage without max_iterations.
Routing follows this precedence:
- Resolve the normal contract route from the artifact
Status. - Determine whether the stage has reached
max_iterations. - If the limit has not been reached, use the normal route.
- If the limit has been reached, honor the normal route when it sets
ignore_max_iterations: true; otherwise replace it withmax_iterations_next_stageor sequential advance when that field is absent.
An ignoring route uses the complete normal-success path: injections are preserved, reset_iterations runs, and terminal and end_after handling remain unchanged. The field never resets, decrements, or disables iteration counters; a later visit continues from the accumulated count. Indirect cycles can therefore remain unbounded, so protect any target-stage route-back with its own iteration design. This orchestration-only field is not included in agent-facing contract guidance.
field_definitions
| Field | Type | Required | Description |
|---|---|---|---|
contract.field_definitions | dict[str, str | dict] | No | Alternative to contract.fields for defining contract artifact fields. Each key is a field name; each value is either a string (used as the description) or a dict with description (required) and example or examples (optional). |
Behavior:
field_definitionsis parsed alongsidefields. When both are present,field_definitionsentries with richer dict values take precedence for description and example rendering.- Descriptions explain what each field should contain. The example for a status uses the first configured example for each field on that route. Give every injected field a realistic example to pass strict validation.
- Like
fields, every field referenced ininjectionsmust have a corresponding entry in eitherfieldsorfield_definitions.
Example:
stages:
- name: Review Code
contract:
field_definitions:
Findings:
description: Specific review findings explaining why the code cannot advance.
example: |
- The error handling in process_request() is incomplete.
Required Changes:
description: Concrete edits the fix stage must make.
examples:
- "Add null check for user_input in process_request()"
- "Replace bare except with except ValueError in validate_config()"
routes:
CHANGES_REQUESTED:
next_stage: Fix Code
injections: [Findings, Required Changes]III. Stage Design & Patterns
1. Responsibility Isolation
- Drafting: Produces an initial artifact. Emits
REVIEW_REQUESTED. - Reviewing: Judges and routes. Avoids implementation work.
- Verifying: Validates against requirements. Avoids silent patching.
2. Common Flow Patterns
- Draft -> Review -> Refine:
Specify->Review Spec->Refine Spec->Review Spec. - Draft -> Self-Refining Review: Review stage edits the doc directly (e.g.,
spec.md) then emits routing YAML. Useful for token conservation. Common status names for self-refining loops includeNEEDS_REFINEMENT(spec/plan/task reviews) andCHANGES_MADE(code/doc reviews). - Changed-On-Review Loop: A self-refining review can emit
CHANGES_MADEto trigger another pass over the revised artifacts before implementation continues. - Implement -> Self-Refining Review:
Implement->Review Code->Review Codewhen the review stage applies targeted fixes directly before approving.
3. Repository-Specific Context
- Speckit/OpenSpec: Use
.specify/scripts/bash/check-prerequisites.shfor discovery. Use--paths-onlywhen a stage needs the active feature directory and canonical file paths. - Simple: Use
injectionsto pass structured data forward (e.g.,Approved Spec).
IV. Authoring Checklist
- [ ] Every contract stage has
fieldsentries for every injected field. - [ ] Route instructions, emit directives, and judgment-production directives are not in
prompt(auto-injected by the runner for contract stages). - [ ] Contract stages do not define a top-level
next_stage. - [ ] Early spec stages stay product-focused ("What/Why"), not technical ("How").
- [ ]
speckitnon-draft stages explain how to use.specify/scripts/bash/check-prerequisites.sh. - [ ] Any lasting usage or specification guidance has been promoted into tracked docs instead of being left only in
specs/or.hpilot/artifacts/. - [ ] Config has been verified via
hpilot validate --show-guidance.
V. Anti-Patterns
- One stage doing everything: A stage both reviewing and editing the same artifact without the "Self-Refining" pattern.
- Generic Injections: Using
SummaryorDetailsinstead of specific fields likeFindingsorRequired Changes. - Status Drift: Renaming a route key without updating the
promptbehavioral constraints that reference it. Auto-injected guidance eliminates drift for route descriptions and artifact-writing instructions, but authored status references must still be updated manually. - Over-Injection: Passing large doc bodies through artifacts in
speckitrepos instead of using script-based discovery. - Unbounded self-refining loops: A self-referencing stage that loops back to itself without a
max_iterationscap. Whilehpilot validatedoes not enforce iteration caps, unbounded loops risk exhausting retries and budget. Always addmax_iterations(withmax_iterations_next_stage) to stages that have self-referencing contract routes.
VI. Stage Field Reference
Per-Stage Harness, Model, Effort, and Goal Overrides
Harness-backed runtime settings are user-specific and live in the active global config, not in hpilot.yaml. Use stage_overrides to set any subset of harness, model, effort, and Codex-only goal for a named stage, with an optional cumulative iterations mapping for progressive stage visits. An empty mapping is valid. Command stages bypass this resolution entirely. See the Codex Harness Guide for goal setup and limits.
harness: claude
model_effort: medium
stage_overrides:
Plan:
harness: codex
model: gpt-5.6
effort: xhigh
Review Code:
model: openai/gpt-5.6-mini
iterations:
2:
model: openai/gpt-5.6-codex
4:
model: openai/gpt-5.6-pro
effort: highIteration thresholds are cumulative and use the stage's successful visit count: the example escalates the review model at iterations 2 and 4, inherits medium effort until iteration 4, and retains each selected value on later visits. Retries do not advance the schedule, command stages remain outside runtime resolution, and the active config still reloads at every attempt boundary. Resolution, strict threshold syntax, adapter switching, diagnostics, cumulative preflight, hpilot use preservation, and legacy migration are in the configuration reference.
backup_artifacts
| Field | Type | Required | Description |
|---|---|---|---|
backup_artifacts | list[str] | No | List of artifact file paths to copy to .hpilot/backups/<stage_name>/<timestamp>/ after the stage completes successfully. |
Behavior:
- A stage with
backup_artifacts: []or without the field performs no backup. - Backup is best-effort — missing source files are skipped with a warning log; the stage continues.
- Paths must be relative children of the task workspace and must not contain
... Sources or backup destinations that resolve outside the workspace through symbolic links are skipped. - Relative paths are resolved against the task workspace at backup time.
- Each successful stage completion creates a new timestamped backup directory (format:
YYYY-MM-DDTHH-MM-SS, UTC). Previous backups are preserved — no overwrite. .hpilot/backups/is never wiped by the pipeline's artifact reset..hpilot/artifacts/cleanup is skipped when files are present, preserving pre-written or seeded artifacts across pipeline restarts.- Backup occurs only after successful stage completion (approved evaluation and valid artifact). Failures and retries do not trigger a backup.
Daemon-mode behavior: Backup paths resolve against the submitting task's workspace, independently of the daemon process working directory.
Usage note: Declare backup_artifacts on stages that produce canonical delivery artifacts (e.g., specs, plans) that subsequent stages may overwrite. Backing up before the next stage runs preserves the output for review.
Example:
stages:
- name: Spec
backup_artifacts:
- .hpilot/artifacts/spec.md
- .hpilot/artifacts/plan.mdkeep_artifacts
| Field | Type | Required | Description |
|---|---|---|---|
keep_artifacts | list[str] | No | List of file paths the stage must not delete. Post-run evaluation checks each path. Missing paths block completion with remediation guidance. |
Behavior:
keep_artifacts: [](empty list) is identical to omitting the field — a no-op check.keep_artifacts: nullin YAML is coerced to[]during config parsing (not an error).- Duplicate entries (exact string match, case-sensitive) are deduplicated during parsing; order of remaining entries is preserved.
- Each entry must be a non-empty string. Non-list values or non-string entries raise a config error.
- Paths must be relative children of the task workspace and must not contain
... They resolve against that workspace in both standalone and daemon mode. A symbolic link that resolves outside the workspace does not satisfy the preservation check. - The check uses
Path.exists()only — it does not validate content. Declaring a directory passes as long as the directory entry exists.
Block message format: When artifacts are missing, evaluation returns:
{
"decision": "block",
"reason": "Required artifact(s) missing: .hpilot/artifacts/plan.md, .hpilot/artifacts/tasks.md. Recreate each file with its expected content before completing."
}Usage note: Declare keep_artifacts on any stage that downstream stages depend on. If an agent accidentally deletes one, post-run evaluation blocks completion and asks it to recreate the file.
Example:
stages:
- name: Review Spec
keep_artifacts:
- .hpilot/artifacts/spec.md
- .hpilot/artifacts/plan.md
contract:
fields:
Findings:
description: Review findings
example: |
- Clarify the target user.
routes:
PLANNING_READY:
next_stage: Plan
NEEDS_REFINEMENT:
next_stage: Review Spec
injections: [Findings]Daemon-mode behavior: Each attempt receives its own immutable evaluation context, so keep_artifacts cannot leak between stages or tasks.
cleanup
| Field | Type | Required | Description |
|---|---|---|---|
cleanup | list[str] | No | List of relative paths to sweep before the stage's agent starts. For declared directories, all contents (files, symlinks, and subdirectories) are removed recursively; the directory itself is preserved. Declared file paths are removed directly. |
When to use: cleanup is appropriate for stages that produce their own artifacts and need a clean slate from a previous run — for example, Spec (to discard stale specs before regenerating). Avoid cleanup on stages that depend on upstream artifacts (such as Review, Implement, or Verify), since sweeping those paths would destroy the inputs the stage needs to read.
Behavior:
cleanup: [](empty list) or absent means no cleanup for that stage.cleanup: nullin YAML is coerced to[]during config parsing.- Paths must be relative to the workspace root.
- Absolute paths are rejected.
- Paths that escape the workspace root via
..are rejected. .and equivalent paths that target the workspace root are rejected.
- If a declared path is a directory, all contents (files, symlinks, and subdirectories) are removed recursively, preserving only the directory itself. If a declared path is a regular file or symlink, it is removed directly.
- Cleanup runs once after stage-input rendering and stage start, before the lifecycle before hook or stage executor.
- If a path does not exist, it is skipped with a debug log. If deletion of an existing file fails, the attempt fails, both lifecycle hooks and the executor are skipped, and the normal retry policy applies.
Validation warnings:
- Config validation emits a warning when
.hpilot/contracts/(or any subpath) appears incleanup, since that directory is managed by the existing contract artifact cleanup mechanism.
Example:
stages:
- name: Implement
cleanup:
- .hpilot/artifacts
- .hpilot/backupsmax_iterations
| Field | Type | Required | Description |
|---|---|---|---|
max_iterations | int | No | Maximum number of times a stage may be visited (across all visits, including contract route-backs). Default 0 (disabled / no cap). |
Behavior:
max_iterationscounts visits per stage (including contract route-backs). A singleiteration_countsarray tracks visits per stage: it increments on fresh visits only (whenretry_counts == 0, not on retries) and never resets on success. This means retries within the same visit do not inflate the count, while route-backs correctly accumulate for enforcement.- Default is
0(disabled / no cap), preserving backward compatibility. - The iteration count is incremented on fresh entry (before the agent subprocess starts), not on retries. The max-iterations check runs after the stage completes successfully and its contract is valid. When
iteration_count >= max_iterations, the pipeline forces a route. This meansmax_iterations: 3allows exactly 3 full agent executions; the limit route fires after the 3rd successful completion. - When the limit is reached, the pipeline routes to
max_iterations_next_stageinstead of following the normal contract route unless the selected contract route setsignore_max_iterations: true. A non-ignoring limit route suppresses the stage's normal contract route, including a terminal contract route, top-levelnext_stage, outgoing injections, andreset_iterationseffects for that completion. Validated artifact fields remain available in stage-specific context, but fields selected only by the losing route are not promoted as latest routed context. - An ignoring route at the limit behaves like the same route below the limit: its target or terminal decision and injections are preserved, and
reset_iterationsruns normally. The option affects only route replacement and never resets or decrements the accumulated iteration counter. - When
max_iterationsis exceeded, the pipeline logs the event withdecision_source: "max_iterations_exceeded"and includesiteration_count(the completed count, notcount + 1) in the log. - Failed attempts follow the existing retry policy. They neither force an early limit route nor receive another iteration count. The limit route fires only after a successful, contract-valid completion at the configured count.
- When
max_iterations > 0, the iteration count and max are logged at stage start: stderr shows[{stage.name}] Running attempt {attempt} (iteration {count}/{max}), JSON logs includeiteration_countandmax_iterationskeys in the "Running" entry, and stage-start events includeiteration_countandmax_iterationsfields. Whenmax_iterations == 0(the default), no iteration info is added — the behavior is backward compatible.
Example:
stages:
- name: Review Code
max_retries: 3
max_iterations: 5
max_iterations_next_stage: Verify
contract:
routes:
CHANGES_REQUESTED:
next_stage: Fix Code
- name: Fix Code
- name: Verifymax_iterations_next_stage
| Field | Type | Required | Description |
|---|---|---|---|
max_iterations_next_stage | str or null | No | Stage to route to when max_iterations is exceeded. Must reference an existing stage name. |
Behavior:
- When
max_iterations > 0andmax_iterations_next_stageis absent, no warning is emitted. At runtime, the pipeline falls back to sequential advance (current_index + 1) unless the selected contract route setsignore_max_iterations: true. - The existing
next_stagefield is NOT used as a fallback for iteration exhaustion. Iteration exhaustion is an escape hatch with an explicit destination or sequential advance. - If the resolved next stage exceeds the number of defined stages, the pipeline terminates successfully.
- After resolving the forced-route target, the
end_stage_nameboundary is checked: ifend_stage_nameis set and the resolved next stage position is strictly greater than the end-stage boundary position, the pipeline terminates successfully. - When
max_iterations == 0,max_iterations_next_stageis ignored even if provided. - A route-level
ignore_max_iterations: trueis the only exception to replacement by this field; the selected contract route remains authoritative for that completion.
Example:
stages:
- name: Review Code
max_iterations: 5
max_iterations_next_stage: Verifyreset_iterations
| Field | Type | Required | Description |
|---|---|---|---|
reset_iterations | list[str] | No | List of stage names whose visit counters are reset to 0 after this stage completes successfully. Default [] (no resets). |
Behavior:
reset_iterationslets a pipeline author clear the iteration history of downstream review stages when a broader delivery stage succeeds. This is useful in review loops where one stage validates the overall delivery and then sends work back through narrower review stages that would otherwise retain stale visit counts from prior cycles.- Reset occurs only on the successful-completion path — after lifecycle after-stage execution and artifact validation pass and route resolution succeeds. Reset does not run on stage failure, retry, evaluation block, missing/invalid contract route, interrupted execution, or
max_iterationsforced routing. - The declaring stage's own
iteration_countsentry is not reset by this field. A stage cannot include its own name inreset_iterations(self-reset is invalid because success already clears that stage's retry count). - Resetting a target stage's visit counter does not change that stage's failure retry counter (
max_retries); onlyiteration_countsfor the named stages are set to0. - Each entry must reference an existing configured stage name (case-sensitive). Unknown targets and self-targets are rejected at config validation time.
- Duplicate entries are deduplicated during parsing while preserving first-seen order.
- Empty or absent lists are no-ops.
- When resets fire, the pipeline logs an
IterationResetJSON entry with the previous and new iteration counts, emits a human-readable message to stderr naming the reset targets, and sends astage_iteration_resetevent to any active stage event callback. - When
reset_iterationsis non-empty, the Running and Success JSON log entries include the field so downstream tooling can inspect configured reset behavior without waiting for the reset event.
Example:
stages:
- name: Review Plan
max_iterations: 3
max_iterations_next_stage: Implement
reset_iterations:
- Review Code
- Review Docs
contract:
routes:
APPROVED:
next_stage: Review Code
CHANGES_MADE:
next_stage: Implement
- name: Review Code
max_iterations: 10
max_iterations_next_stage: Review Docscontract.required_tasks
| Field | Type | Required | Description |
|---|---|---|---|
contract.required_tasks | list[str] | No | List of fixed work items the agent must complete before the stage artifact is accepted. Every configured task must appear in the artifact's Completed Tasks YAML list before any status route may pass. |
Behavior:
required_tasksis optional; absent means no task-completion enforcement.- Each entry must be a non-empty string. Surrounding whitespace is trimmed during parsing.
- Duplicate entries (exact match after trim) are removed while preserving first-seen order.
- Non-list values, non-string entries, and empty-after-trim entries produce a clear configuration error at load time.
- When configured, the agent's contract artifact must include a
Completed Tasksfield containing a YAML list. Every configured task string must appear in that list (exact string match, any order). - Extra entries in
Completed Tasksare allowed — only the configured tasks are required. Completed Tasksis reserved contract evidence. It is never routed or injected into a downstream prompt.- For a partial list, the correction names each missing task in configuration order. If the field is absent or its value is not a list, the correction names all configured tasks.
- Required-task validation applies to every status and coexists with route injections.
- Shared evaluation and final pipeline validation enforce identical rules.
- Contracts without
required_tasksretain their current artifact shape and behavior.
The initial <contract_guidance> block starts with the stage work and lists each configured task on its own line. It directs the agent to finish the work, fix known mistakes within the stage's scope, and run the required checks before writing the artifact. Every status example includes the expected Completed Tasks list when tasks are configured.
If the result needs correction, the agent receives the outstanding tasks first, followed by the artifact details it can fix in the same turn. For a missing or invalid Status, the status table shows the available outcomes and their fields. For a recognized status, the correction lists each missing, blank, or wrongly typed field in a table alongside its configured description and identifies any extra keys. Each correction includes a single <contract_guidance> block with the full writing instructions and YAML examples, including on a fresh or resumed retry. If an external prerequisite prevents further progress, the agent reports the blocker and remaining work.
Example:
stages:
- name: Implement
contract:
required_tasks:
- "Write unit tests"
- "Pass mypy --strict"
- "Pass ruff check"
fields:
Summary:
description: Implementation summary
example: |
Implemented the feature with full test coverage.
routes:
IMPLEMENTATION_COMPLETE:
description: Implementation is done and all checks pass.
next_stage: Review Code
injections: [Summary]Rendered artifact example:
Status: IMPLEMENTATION_COMPLETE
Summary: |
Implemented the feature with full test coverage.
Completed Tasks:
- Write unit tests
- Pass mypy --strict
- Pass ruff checkIf the artifact lists only Write unit tests, the correction begins “You still have work to finish in this stage.” The agent sees the two outstanding tasks in their original wording.
- Pass mypy --strict
- Pass ruff check
If the same artifact also omits Summary under IMPLEMENTATION_COMPLETE, the correction includes a row for Summary with its description, “Implementation summary.” Once the agent has finished the work, it can write the complete result in one pass.
read_only_paths
| Field | Type | Required | Description |
|---|---|---|---|
read_only_paths | list[str] | No | Per-stage list of glob patterns that harness-backed stages must not modify. Claude, Cursor, Codex, and Antigravity use Git-backed detect-only enforcement; OpenCode enforces ordered native and session permission rules plus programmatic MCP write admission through a process-local configuration overlay. The pipeline also tells the agent about protected paths in the stage prompt. When empty or absent, no adapter read-only enforcement is active. |
Behavior:
read_only_paths: [](empty list) or absent — no write protection for that stage, and no read-only section is appended to the prompt. Adapter-level read-only enforcement is skipped.read_only_pathsis a per-stage field. Stages that need write protection (e.g., design or review stages) specify their own patterns; implementation stages typically omit it to allow full write access.- Git-backed detection protects matching Git-visible working-tree files but excludes Git administration and ignored paths. A broad pattern such as
service/**therefore protects visible files under the service working tree without inspecting.git/FETCH_HEAD, refs, indexes, objects, or locks. Use a read-only mount or disposable checkout when those paths must be immutable. - Patterns are resolved relative to the workspace root and matched using path-segment glob semantics.
*matches within one path segment, while**matches zero or more path segments. For example,src/*.pymatchessrc/foo.py,src/**/*.pyalso matchessrc/sub/bar.py, andsrc/**matches everything undersrc/. - Each entry must be a non-empty, relative path string. Absolute paths and paths containing
..are rejected at config validation time. - Each adapter enforces read-only protection through its own mechanism (Git-backed change detection or native permission rules plus MCP write admission).
- Post-run verifier evaluation is independent of
read_only_paths. - If a
read_only_pathspattern matches akeep_artifactsentry for the same stage, a warning is emitted at config validation time.
When a stage lists protected paths, hpilot adds a <read_only_paths> block after the stage prompt and any <handoff>. The block tells the agent to leave matching files untouched and lists each pattern on its own line. Any retry feedback and contract guidance follow the closing tag.
Event logging: Post-run verifier and contract events are recorded in .hpilot/logs/evaluation-events.jsonl. Adapter stage logs contain read-only enforcement failures.
Example:
stages:
- name: Spec
prompt: "Generate a specification for: {objective}"
read_only_paths:
- "src/**"
- "pyproject.toml"
- "tests/**"Runtime lifecycle details such as post-run evaluation, logs, signals, and single-instance enforcement are documented in Runtime and Daemon — Developer Reference, not in this authoring guide, because they are built-in runtime mechanics rather than hpilot.yaml authoring concerns.