You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
WRITE ACCESS CONTRACT: You are running with auto-approved writes inside a writable workspace. Treat the working directory as fully writable. Do NOT preemptively skip or block tasks on permission, sandbox, or read-only grounds. Attempt every required edit; only report failure AFTER a real OS-level rejection from a specific shell command. Do not infer 'read-only' from absence of activity; absence is not denial. If a single shell command unexpectedly fails, retry with a different invocation before concluding the environment is restricted.
You are creating an implementation plan for the following idea.
code
Idea:
Implement Phase 3 (produces-with-inline-checks + repeat:{until/for_each} as body attributes) of the ArtAgents orchestrator V1 design per docs/orchestrator-v1-plan.md sections 5-6. Phase 3 scope: replace separate verifier substep with inline checks on produces declarations. produces becomes a dict of name -> {path, check}, where check is a callable verifier (file_nonempty, json_schema, json_file, audio_duration_min, image_dimensions, all_of). The gate runs each check after step completion or ack; failure rewinds the cursor. Sentinel-existence-only checks are REJECTED at definition time for non-trivial attested produces - define what counts as non-trivial (e.g., produces with non-empty type signature). Add repeat as an attribute on any step or body block: repeat: {until: user_approves|verifier_passes|quorum, max_iterations, on_exhaust} writes attempts to iterations/NNN/; repeat: {for_each: <input_set>} expands at runtime, per-item state under items//, supports partial approval via --item . Phases 1 (kernel) and 2 (three step kinds) are already shipped - build on top. Do NOT implement DSL yet (Phase 4). Do NOT implement new lifecycle verbs (Phase 5). Keep additive: existing JSON manifests still work. Add focused tests for: produces with inline check rejects bad artifact and rewinds; produces sentinel-only is rejected at definition; repeat:until iterates correctly with cumulative feedback in iterations/NNN/; repeat:for_each expands runtime input set into items//; partial approval advances per-item state; on_exhaust escalate vs fail.
User notes and answers:
Ignored malformed settled decision line: SD-001 three step kinds: Task mode has exactly code, attested, and nested so execution, evidence, and delegation stay distinct.
Ignored malformed settled decision line: SD-002 repeat body attributes: Iteration and fan-out are and body attributes so they apply uniformly to steps and nested bodies.
Assistant
I have enough context now. Let me write the plan.
Assistant
Plan delivered. Phase 3 lands inline produces checks (with cursor rewind on failure), the new artagents.verify package of six check helpers, and repeat.until / repeat.for_each as body attributes — all additive on top of the existing kernel. Open questions cover for_each input source, the precise definition of "non-trivial attested produces", on_exhaust=escalate semantics, quorum scope, and whether the iterate --feedback CLI verb lands now or in Phase 5.
User
Assistant
Revision delivered. Three significant flags addressed: a new step_dir_for_path helper that takes a path tuple plus optional iteration/item suffix (FLAG-P3-001), explicit ARTAGENTS_TASK_ITEM_ID / ARTAGENTS_TASK_ITERATION env contract additions with corresponding tests for code-body dispatch (FLAG-P3-002), and an explicit omit-when-empty rule in _step_to_dict plus a frozen-hash regression test pinning legacy plan-hash invariance (FLAG-P3-003).
repeat.until
repeat.for_each
Ignored malformed settled decision line: SD-003 plan naming: Runtime uses immutable plan.json instead of checklist naming because the structure is a tree with nested bodies and loops.
Ignored malformed settled decision line: SD-004 event hash chain: events.jsonl uses plain sha256(prev_hash + canonical_event_json) with no HMAC because V1 needs an edit tripwire, not keyed tamper resistance.
Ignored malformed settled decision line: SD-005 no index database: V1 ships without .index.db because file walking and grep over events.jsonl are adequate until measured otherwise.
Ignored malformed settled decision line: SD-006 committed DSL: artagents.orchestrate Python DSL is the only committed authoring representation so source review happens in Python.
Ignored malformed settled decision line: SD-007 generated build JSON: <pack>/build/<orch>.json is gitignored and root .gitignore excludes pack build outputs because runtime pins generated artifacts.
Ignored malformed settled decision line: SD-008 per-project CAS: V1 uses only per-project <slug>/.cas/<sha256> storage because shared CAS adds coordination without current need.
Ignored malformed settled decision line: SD-009 code boundary: code is deterministic argv, a strict superset of RUNTIME_KINDS={python,command}, may target artagents executors run <name>, and must not target artagents orchestrators run.
Ignored malformed settled decision line: SD-010 nested boundary: Sub-orchestrator delegation is exclusively nested so the gate can hash and pin child structure.
Ignored malformed settled decision line: SD-011 gate checks: The gate validates active run presence, plan hash, event chain, and incoming command match before dispatch and prints the exact recovery command on rejection.
Ignored malformed settled decision line: SD-012 gate ordering: The gate runs before _prepare_project_request() and thread_wrapper.begin_orchestrator_run() so rejected commands create zero project-run side effects.
Ignored malformed settled decision line: SD-013 provenance surface: events.jsonl is the single write surface for task-mode provenance while thread provenance remains in runs/<id>/run.json.
Ignored malformed settled decision line: SD-015 task kernel namespace: New kernel modules live in artagents/core/task/ to isolate gate, events, active-run, and env logic from legacy runners.
Ignored malformed settled decision line: SD-016 structure guardrails: TOP_LEVEL_ARTAGENTS_DIRS adds orchestrate and verify, with tests/test_doctor_setup.py updated so doctor accepts the new packages.
Ignored malformed settled decision line: SD-017 task run env: ARTAGENTS_TASK_RUN_ID is the integration surface for orchestrator, executor, and hype child calls to attach to the parent task run.
Ignored malformed settled decision line: SD-018 child output preservation: Task mode preserves child output dirs and mirrors hype artifacts under runs/<task-run-id>/steps/<step-id>/produces/ while standalone behavior stays unchanged so tests/test_project_runs.py keeps passing.
Ignored malformed settled decision line: SD-019 attestor identity: Agent attestations require --agent, human attestations require --actor matching ARTAGENTS_ACTOR, and self-acks are rejected.
Ignored malformed settled decision line: SD-020 ack rules: approve advances, retry is only valid after verifier failure, iterate --feedback is only valid for repeat.until=user_approves, and abort ends the run.
Ignored malformed settled decision line: SD-021 inline produces checks: Produces inline checks replace verifier substeps while passes_test remains a normal code step.
Ignored malformed settled decision line: SD-022 semantic checks: author check rejects sentinel-only attested outputs because non-trivial artifacts need semantic validation.
Ignored malformed settled decision line: SD-023 stop-hook preamble: Every artagents next output includes the prohibition preamble verbatim because repeated injection fights context decay.
Ignored malformed settled decision line: SD-024 additive migration: Existing OrchestratorDefinition JSON manifests and RUNTIME_KINDS={python,command} keep working because V1 migration is additive.
Ignored malformed settled decision line: SD-025 honor model: V1 is single-host and honor-based with strong logging because it does not defend against malicious local agents.
Ignored malformed settled decision line: SD-026 cut points: Phase 3 is the frozen-plan runner ship point and Phase 5 is the author-friendly lifecycle ship point.
Ignored malformed settled decision line: SD-027 canonical migration: artagents/packs/builtin/hype/ is the canonical migration example because it exercises the existing executor pipeline and additive pack layout.
Ignored malformed settled decision line: SD-028 phasing order: V1 implementation follows build phases 1-9 so kernel, step semantics, authoring, lifecycle, nudge, CAS, inbox, and golden tests land in dependency order.
Ignored malformed settled decision line: SD-029 V1 infrastructure limits: V1 excludes daemon, web server, HMAC/keyed crypto, .index.db, and shared CAS so the implementation stays file-based, inspectable, and additive.
Prior doc imported via --from-doc:
docs/orchestrator-v1-plan.md
No ## Settled Decisions section found — path stored for reference only.
code
No prior clarification artifact exists. Identify ambiguities, ask clarifying questions, and state your assumptions inside the plan output.
Requirements:
- If the engineering brief suggests an approach, use it as your starting hypothesis — but before committing, consider if there's a simpler or more fundamental fix. The brief is well-researched input, not a final answer.
- If the brief is absent, incomplete, or says "skip", inspect the repository yourself before planning.
- Stay focused on the requested idea. If repo exploration surfaces unrelated issues or docs, ignore them and return to the task.
- Prefer source code, tests, and directly relevant config files. Avoid `.megaplan/`, prior plan artifacts, and unrelated `docs/` or ops/deployment material unless the task explicitly depends on them.
- Stop exploring once you have enough evidence to name the concrete touch points and validation path. Do not keep browsing after you can write the plan.
- Produce a concrete implementation plan in markdown.
- Define observable success criteria as objects with `criterion` (string) and `priority` (`must`, `should`, or `info`):
- `must` — hard gate. The reviewer will block on failure. Use for correctness, functional requirements, and verifiable outcomes (e.g., "all existing tests pass", "API returns 200 for valid input"). Every `must` criterion must have a clear yes/no answer.
- `should` — quality target. The reviewer flags but does not block. Use for subjective goals, numeric guidelines, and best-effort improvements (e.g., "file under ~300 lines", "no deeply nested conditionals", "each function has a single responsibility").
- `info` — documented for humans, reviewer skips. Use for criteria that cannot be verified in this pipeline (e.g., "13 manual smoke tests pass", "stakeholder sign-off obtained").
- Each success criterion should include a `requires` field listing the capabilities needed for verification. Valid capability strings: `run_shell`, `read_files`, `run_tests`, `parse_diff`, `read_build_output`, `run_linter` (container), `drive_browser`, `inspect_runtime_ui`, `observe_runtime_logs`, `subjective_judgment`, `verify_physical_device` (human). `must` criteria MUST have non-empty `requires`. Example: `{"criterion": "All tests pass", "priority": "must", "requires": ["run_tests"]}`.
- Use the `questions` field for ambiguities that would materially change implementation.
- Use the `assumptions` field for defaults you are making so planning can proceed now.
- Prefer cheap validation steps early.
- Keep the plan proportional to the task. A 1-line fix needs a 2-step plan (apply fix + run tests), not a 5-step investigation.
- If user notes answer earlier questions, incorporate them into the draft plan instead of re-asking them.
- Fix the problem fully. Do not limit scope just to avoid breaking existing tests — update the tests too if needed.
- Prefer the simplest, most direct fix. No fallbacks, type conversions, or defensive wrappers without concrete evidence they are needed.
- If the task or issue hints suggest a specific approach, follow it. Only deviate with concrete counter-evidence.
Plan template — simple format (adapt to the actual repo and scope):
md
# Implementation Plan: [Title]
## Overview
Summarize the goal, current repository shape, and the constraints that matter.
## Main Phase
### Step 1: Audit the current behavior (`megaplan/prompts.py`)
**Scope:** Small
1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`).
### Step 2: Add the first change (`megaplan/evaluation.py`)
**Scope:** Medium
1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`).
2. **Capture** any tricky behavior with a short example.
```python
issues = validate_plan_structure(plan_text)
```
### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`)
**Scope:** Medium
1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`).
### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`)
**Scope:** Small
1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`).
2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`).
## Execution Order
1. Update prompts and mocks before enforcing stricter validation.
2. Land higher-risk wiring after the validator and tests are ready.
## Validation Order
1. Start with focused unit tests.
2. Run the broader suite after the flow changes are in place.
For complex plans, use multiple phases:
md
## Phase 1: Foundation — Dependencies, DB, Types
### Step 1: Install dependencies (`package.json`)
...
### Step 2: Create database migration (`supabase/migrations/`)
...
## Phase 2: Core Integration
### Step 3: Port the main component (`src/components/`)
...
Template guidance:
Simple plans: use ## Main Phase with ### Step N: sections underneath.
Complex plans: use multiple ## Phase N: sections, each containing ### Step N: steps. Step numbers are global (not per-phase).
The flat ## Step N: format (without phases) also works for backwards compatibility.
Key invariants: one H1 title, one ## Overview, numbered step sections (### Step N: or ## Step N:), and at least one ordering section.
You are already running inside the megaplan harness for this step. Do the requested planning/review/execution work directly. Do NOT invoke the megaplan CLI, do NOT read or activate the megaplan skill, do NOT start nested megaplan plans, and do NOT recurse into another planning harness. Treat mentions of megaplan in the repository or environment as implementation context only.
WRITE ACCESS CONTRACT: You are running with auto-approved writes inside a writable workspace. Treat the working directory as fully writable. Do NOT preemptively skip or block tasks on permission, sandbox, or read-only grounds. Attempt every required edit; only report failure AFTER a real OS-level rejection from a specific shell command. Do not infer 'read-only' from absence of activity; absence is not denial. If a single shell command unexpectedly fails, retry with a different invocation before concluding the environment is restricted.
You are revising an implementation plan after critique and gate feedback.
Implement Phase 3 (produces-with-inline-checks + repeat:{until/for_each} as body attributes) of the ArtAgents orchestrator V1 design per docs/orchestrator-v1-plan.md sections 5-6. Phase 3 scope: replace separate verifier substep with inline checks on produces declarations. produces becomes a dict of name -> {path, check}, where check is a callable verifier (file_nonempty, json_schema, json_file, audio_duration_min, image_dimensions, all_of). The gate runs each check after step completion or ack; failure rewinds the cursor. Sentinel-existence-only checks are REJECTED at definition time for non-trivial attested produces - define what counts as non-trivial (e.g., produces with non-empty type signature). Add repeat as an attribute on any step or body block: repeat: {until: user_approves|verifier_passes|quorum, max_iterations, on_exhaust} writes attempts to iterations/NNN/; repeat: {for_each: <input_set>} expands at runtime, per-item state under items//, supports partial approval via --item . Phases 1 (kernel) and 2 (three step kinds) are already shipped - build on top. Do NOT implement DSL yet (Phase 4). Do NOT implement new lifecycle verbs (Phase 5). Keep additive: existing JSON manifests still work. Add focused tests for: produces with inline check rejects bad artifact and rewinds; produces sentinel-only is rejected at definition; repeat:until iterates correctly with cumulative feedback in iterations/NNN/; repeat:for_each expands runtime input set into items//; partial approval advances per-item state; on_exhaust escalate vs fail.
User notes and answers:
Ignored malformed settled decision line: SD-001 three step kinds: Task mode has exactly code, attested, and nested so execution, evidence, and delegation stay distinct.
Ignored malformed settled decision line: SD-002 repeat body attributes: Iteration and fan-out are repeat.until and repeat.for_each body attributes so they apply uniformly to steps and nested bodies.
Ignored malformed settled decision line: SD-003 plan naming: Runtime uses immutable plan.json instead of checklist naming because the structure is a tree with nested bodies and loops.
Ignored malformed settled decision line: SD-004 event hash chain: events.jsonl uses plain sha256(prev_hash + canonical_event_json) with no HMAC because V1 needs an edit tripwire, not keyed tamper resistance.
Ignored malformed settled decision line: SD-005 no index database: V1 ships without .index.db because file walking and grep over events.jsonl are adequate until measured otherwise.
Ignored malformed settled decision line: SD-006 committed DSL: artagents.orchestrate Python DSL is the only committed authoring representation so source review happens in Python.
Ignored malformed settled decision line: SD-007 generated build JSON: <pack>/build/<orch>.json is gitignored and root .gitignore excludes pack build outputs because runtime pins generated artifacts.
Ignored malformed settled decision line: SD-008 per-project CAS: V1 uses only per-project <slug>/.cas/<sha256> storage because shared CAS adds coordination without current need.
Ignored malformed settled decision line: SD-009 code boundary: code is deterministic argv, a strict superset of RUNTIME_KINDS={python,command}, may target artagents executors run <name>, and must not target artagents orchestrators run.
Ignored malformed settled decision line: SD-010 nested boundary: Sub-orchestrator delegation is exclusively nested so the gate can hash and pin child structure.
Ignored malformed settled decision line: SD-011 gate checks: The gate validates active run presence, plan hash, event chain, and incoming command match before dispatch and prints the exact recovery command on rejection.
Ignored malformed settled decision line: SD-012 gate ordering: The gate runs before _prepare_project_request() and thread_wrapper.begin_orchestrator_run() so rejected commands create zero project-run side effects.
Ignored malformed settled decision line: SD-013 provenance surface: events.jsonl is the single write surface for task-mode provenance while thread provenance remains in runs/<id>/run.json.
Ignored malformed settled decision line: SD-015 task kernel namespace: New kernel modules live in artagents/core/task/ to isolate gate, events, active-run, and env logic from legacy runners.
Ignored malformed settled decision line: SD-016 structure guardrails: TOP_LEVEL_ARTAGENTS_DIRS adds orchestrate and verify, with tests/test_doctor_setup.py updated so doctor accepts the new packages.
Ignored malformed settled decision line: SD-017 task run env: ARTAGENTS_TASK_RUN_ID is the integration surface for orchestrator, executor, and hype child calls to attach to the parent task run.
Ignored malformed settled decision line: SD-018 child output preservation: Task mode preserves child output dirs and mirrors hype artifacts under runs/<task-run-id>/steps/<step-id>/produces/ while standalone behavior stays unchanged so tests/test_project_runs.py keeps passing.
Ignored malformed settled decision line: SD-019 attestor identity: Agent attestations require --agent, human attestations require --actor matching ARTAGENTS_ACTOR, and self-acks are rejected.
Ignored malformed settled decision line: SD-020 ack rules: approve advances, retry is only valid after verifier failure, iterate --feedback is only valid for repeat.until=user_approves, and abort ends the run.
Ignored malformed settled decision line: SD-021 inline produces checks: Produces inline checks replace verifier substeps while passes_test remains a normal code step.
Ignored malformed settled decision line: SD-022 semantic checks: author check rejects sentinel-only attested outputs because non-trivial artifacts need semantic validation.
Ignored malformed settled decision line: SD-023 stop-hook preamble: Every artagents next output includes the prohibition preamble verbatim because repeated injection fights context decay.
Ignored malformed settled decision line: SD-024 additive migration: Existing OrchestratorDefinition JSON manifests and RUNTIME_KINDS={python,command} keep working because V1 migration is additive.
Ignored malformed settled decision line: SD-025 honor model: V1 is single-host and honor-based with strong logging because it does not defend against malicious local agents.
Ignored malformed settled decision line: SD-026 cut points: Phase 3 is the frozen-plan runner ship point and Phase 5 is the author-friendly lifecycle ship point.
Ignored malformed settled decision line: SD-027 canonical migration: artagents/packs/builtin/hype/ is the canonical migration example because it exercises the existing executor pipeline and additive pack layout.
Ignored malformed settled decision line: SD-028 phasing order: V1 implementation follows build phases 1-9 so kernel, step semantics, authoring, lifecycle, nudge, CAS, inbox, and golden tests land in dependency order.
Ignored malformed settled decision line: SD-029 V1 infrastructure limits: V1 excludes daemon, web server, HMAC/keyed crypto, .index.db, and shared CAS so the implementation stays file-based, inspectable, and additive.
Phase 3 turns the frozen-plan kernel (Phases 1 + 2 already shipped) into a useful runner by adding two orthogonal additions on top of the existing three step kinds (code, attested, nested):
Inline produces with checks.produces becomes a dict name -> {path, check} where check is a callable verifier from a new artagents.verify package (file_nonempty, json_schema, json_file, audio_duration_min, image_dimensions, all_of). The gate runs each check after step_completed (code) or step_attested (attested); failure records a produces_check_failed event and rewinds the cursor (does not advance). Sentinel-existence-only checks are rejected at definition time for non-trivial attested produces.
repeat as body attribute. Any step (code, attested, nested) can carry a repeat: {until: ...} or repeat: {for_each: ...} block. until retries the body and writes attempts under iterations/NNN/ with cumulative feedback.json. for_each expands a runtime input set and writes per-item state under items/<item-id>/, supporting partial approval via --item <id>. on_exhaust selects between escalate (park, require attested override) and fail (abort).
The work stays additive: existing Phase-1/2 plans (legacy produces: [...] list, no repeat, no check field) continue to load and run unchanged. No DSL (Phase 4). No new lifecycle verbs (Phase 5) — only data-model, gate plumbing, and event kinds. Tests cover: failed check rewinds; sentinel-only rejected at definition; repeat.until golden iteration with cumulative feedback; repeat.for_each golden with partial approval; on_exhaust escalate vs fail.
Key architectural notes from the existing kernel:
artagents/core/task/plan.py already has CodeStep, AttestedStep, NestedStep dataclasses and a _validate_* chain. Schema additions land here.
artagents/core/task/gate.py already has the _Frame / CursorPath / derive_cursor event-replay model. Iteration and fan-out add new frame kinds: an iteration frame (no path segment, iterations/NNN/) and a per-item frame (path segment items/<item-id>/). Both replay deterministically from new event kinds.
artagents/core/task/events.py already canonicalizes events via canonical_event_json + _event_hash; new make_*_event helpers are additive.
artagents/structure.py doctor guardrail must accept the new top-level verify package or python3 -m artagents doctor and tests/test_doctor_setup.py will fail.
Phase 1: Foundation — artagents.verify Package + Schema Extensions
Createartagents/verify/checks.py containing six callables. Each takes a (step_dir: Path, name: str, declared_path: str) triple and returns a CheckResult(ok: bool, reason: str | None, details: dict). Callables are dataclasses/closures so they serialize to a deterministic (check_id, params) pair for plan hashing — the callable identity itself must hash, not just the result.
file_nonempty() — (step_dir/declared_path).stat().st_size > 0. Marked sentinel=True on the returned check object.
json_file() — file exists, is valid UTF-8 JSON. sentinel=False.
json_schema(schema: dict) — json_file then validates against schema (use stdlib for type/required/properties shallow check; full jsonschema lib not required for Phase 3). sentinel=False.
audio_duration_min(seconds: float) — uses wave/audioop for .wav, falls back to ffprobe subprocess otherwise; sentinel=False.
image_dimensions(min_w: int = 0, min_h: int = 0) — reads PNG/JPEG header bytes (no Pillow dep); sentinel=False.
all_of(*checks) — runs all in order, fails on first failure. sentinel = all(c.sentinel for c in checks).
Define the public Check protocol in artagents/verify/__init__.py:
Re-export the six factories. The (check_id, params) tuple is what gets serialized into plan.json so plan-hash stability survives across helper-impl edits.
Add"verify" to TOP_LEVEL_ARTAGENTS_DIRS in artagents/structure.py:27 and update to expect it. (Phase 4 will add ; do not add it now.)
Step 2: Extend plan schema for inline checks (artagents/core/task/plan.py)
Scope: Medium
Replace the produces: tuple[str, ...] field on AttestedStep (and add to CodeStep/NestedStep) with a new typed mapping:
python
@dataclass(frozen=True)
class ProducesEntry:
name: str
path: str
check: dict[str, Any] # serialized {check_id, params, sentinel} — plan.json is JSON-only
# On every step kind:
produces: tuple[ProducesEntry, ...] = ()
The wire form in plan.json is {"name": {"path": "transcript.json", "check": {"check_id": "json_file", "params": {}, "sentinel": false}}}. We deserialize into tuple[ProducesEntry] for stable iteration.
Preserve the legacy list form (produces: ["a.json", "b.json"]) as a permitted shape for code steps only. Each list entry becomes a ProducesEntry(name=stem, path=entry, check={"check_id": "file_nonempty", "params": {}, "sentinel": True}). After normalization, to_dict() re-emits the canonical dict form. (This keeps Phase-1/2 plans loading and tests like test_legacy_plan_loads_as_single_code_step green.)
Reject sentinel-only checks on attested steps at _validate_attested_step. Definition of "non-trivial attested produces" (per assumption A1):
Every attested produces is non-trivial. Therefore: an attested step whose produces contains any entry with check.sentinel == True is rejected at load time with TaskPlanError("attested produces {name!r} requires a semantic check, got sentinel-only").
code steps may still use sentinel-only checks. nested steps inherit their child plan's attested checks.
Add a top-level repeat field on each step dataclass:
python
Step 3: Add new event kinds for checks and repeat (artagents/core/task/events.py)
Step 4: Run inline checks after each step (artagents/core/task/gate.py)
Scope: Medium
Insert a _run_inline_checks() helper that:
Locates step_dir = step_dir_for(slug, run_id, plan_step_path_for_dir) — for a step inside iterations/NNN/ or items/<item-id>/, the iteration/item suffix is appended to the produces directory.
Calls each Check callable; on first failure, appends produces_check_failed (containing {check_id, name, reason, details}) and returns False.
On all-pass, appends one produces_check_passed per name and returns True.
Hook the helper into two existing emission points:
record_dispatch_complete(): after appending step_completed (code), call checks. If failed, also append cursor_rewind and the cursor-replay logic in derive_cursor interprets produces_check_failed as a "do not advance" marker. Concretely: modify derive_cursor so that the pair (step_completed, produces_check_failed) does not advance top.child_index. (The simpler implementation: step_completed advances tentatively, and any subsequent produces_check_failed for the same plan_step_id decrements child_index. We chose the cleaner rule: advance only on a (step_completed | step_attested) AND produces_check_passed-for-each-declared-produces matched pair.)
_dispatch_attested(): after appending step_attested, call checks. Same advance/rewind rule.
Updatederive_cursor() to recognize a step as "advance-eligible" only when its terminal step_completed/step_attested event is followed (in the same plan-step-id contiguous block) by a successful set of produces_check_passed events covering every declared produces name. A produces_check_failed for that step blocks the advance and signals "rewind to redispatch". Re-dispatch of the same plan_step_id is allowed when the latest event for that path is produces_check_failed.
Update_dispatch_code reentry guard so that a redispatch after a failed check passes the "incoming command must match" check by inspecting the latest event for this step path rather than only events[-1] (insertion-order may now have between events from prior attempts).
Step 5: Add iteration frames for repeat.until (artagents/core/task/gate.py, artagents/core/task/plan.py)
Scope: Medium
Extend the _Frame model with two new optional fields without breaking the existing replay logic:
python
@dataclass
class _Frame:
plan: TaskPlan
path_prefix: tuple[str, ...]
child_index: int = 0
iteration: int | None = None # NNN when this frame is iterating a single step
item_id: str | None = None # set on for_each item subframes
repeat_step_id: str | None = None # the host step id, when iteration/item is active
For a step s2 with repeat.until, after we land on s2 we push a new frame whose plan is a synthetic single-step plan containing s2's body, with path_prefix = (..., "s2", f"iterations/{iteration:03d}"). This means produces and child events all carry the iteration-qualified path, which is what step_dir_for needs to write under iterations/NNN/.
Replay logic in derive_cursor: when an iteration_started event is seen, push the iteration frame; when iteration_failed is seen, pop the frame and advance the iteration counter on the parent host (do not advance host's child_index). When iteration_exhausted event is seen with on_exhaust=fail, raise TaskRunGateError (recovery: artagents abort --project <slug>). With on_exhaust=escalate, mark the host frame as "parked" — no advance until a follow-up step_attested event with --actor resolves the override (added as a synthetic attested gate inside the host).
Termination check for repeat.until:
verifier_passes: the host iteration's produces checks all pass on first try → advance host. (Effectively standard inline-check + repeat acts as a max_iterations bound.)
user_approves: requires an attested ack on the host step itself. The ack consumes the iteration frame and advances the host. Prior failed iterations stay on disk under iterations/NNN/ with feedback.json for the next iteration to read.
quorum: requires quorum_nstep_attested events from distinct attestors before advance. Phase 3 stub: validate at definition; runtime advances when N distinct attestor IDs have signed off in this host's iterations.
Step 6: Add per-item frames for repeat.for_each (artagents/core/task/gate.py, artagents/core/task/plan.py)
Scope: Medium
Resolve the item set lazily on first arrival at the host step:
items_source="static": use the literal tuple from the plan.
items_source="from": parse "<step-id>.produces.<name>", locate that step's produces JSON file at step_dir_for(...) / produces / <path> (resolved at the time we encounter the for_each host), and read it as a list of strings. Reject non-string items or duplicates with TaskRunGateError(reason="for_each items must be unique strings", abort=False).
Emit one for_each_expanded event the first time the host is reached. Replay treats this as the source of truth for which item ids exist (do not re-resolve from disk). This is critical: it keeps derive_cursor deterministic from events alone, matching the Phase 1/2 contract noted in gate.py:96.
Per-item frame: after for_each_expanded, push frames in declaration order. Each item frame has path_prefix = (..., host.id, f"items/{item_id}") and a synthetic single-step plan equal to the host body. item_started / item_completed / item_attested events advance the per-item frame.
Partial approval: support --item <id> on attested commands by extending match_attested_command() to strip --item. The gate routes the ack to that item's frame regardless of its insertion order in for_each_expanded. The host advances only after every item's frame is satisfied (or after explicit partial-acceptance escalation, deferred to Phase 5).
Test scenarios:
for_each with three items, two get acked individually, host does not advance until third arrives.
for_each_expanded is replay-deterministic: writing the events file by hand and calling derive_cursor reproduces the same frame stack.
on_exhaust=fail: when iteration count exceeds max_iterations, append iteration_exhausted and raise TaskRunGateError(reason="repeat.until max_iterations exhausted", recovery="artagents abort --project <slug>"). The next gate call sees the run as terminally aborted (active_run.json gets cleared by Phase 5's abort verb; for Phase 3 we leave it pinned so a subsequent gate call hits events.jsonl chain integrity OK and derive_cursor raises again).
on_exhaust=escalate: append iteration_exhausted with on_exhaust="escalate" and park the cursor on a synthetic attested step requiring --actor. The next acceptable command is ack --project <slug> --step <host-path>/exhaust-override --actor <name>. After ack, the host step advances (escalation is recorded, run continues). Test: assert escalate does not raise but fail does; assert events sequence differs.
Phase 3: Tests
Step 8: Verifier unit tests (tests/test_verify_helpers.py — new file)
Scope: Small
Cover each helper:
file_nonempty returns ok=False for empty, ok=True for 1-byte content; reports sentinel=True.
audio_duration_min(2.0) accepts a 2.5s .wav (synthesized via wave); rejects 1s.
image_dimensions(min_w=64) rejects a 32x32 PNG (write a tiny valid PNG header by hand or skip if no Pillow; gate-protect with pytest.importorskip — assumption A2).
all_of(file_nonempty, json_file) reports sentinel=False because at least one constituent is non-sentinel.
AssertCheck.params ordering is canonicalized so two equivalently-constructed checks hash identically.
test_code_produces_check_fails_rewinds_cursor: build a one-step plan with produces={"out": {"path": "out.json", "check": json_file()}}, dispatch the step, write garbage to out.json via record_dispatch_complete, assert the gate emitted produces_check_failed, assert next gate_command(same_command) re-dispatches the same step (cursor unchanged).
test_code_produces_check_passes_advances: same setup but write valid JSON; assert next gate_command(other_command) reaches step 2.
test_attested_sentinel_only_check_rejected_at_load: write a plan with attested produces using only file_nonempty; assert load_plan raises TaskPlanError("attested produces .* requires a semantic check").
test_attested_with_all_of_semantic_check_accepts: same plan but all_of(file_nonempty(), json_file()); assert it loads.
test_code_with_sentinel_only_check_accepts: code step with file_nonempty only loads fine.
test_legacy_produces_list_normalizes_to_sentinel_dict: legacy produces: ["a.json"] on a code step loads, to_dict() round-trips to canonical dict form, plan hash matches between identical legacy/canonical inputs.
Step 10: repeat.until golden run (tests/test_task_repeat_until.py — new file)
Scope: Small
test_repeat_until_user_approves_appends_cumulative_feedback: host attested step with repeat.until={condition: "user_approves", max_iterations: 3, on_exhaust: "fail"}. Iter 1: dispatch + simulate iterate --feedback "more energy" (direct append_event of step_attested carrying iterate_feedback). Assert iterations/001/feedback.json written, iteration_failed recorded. Iter 2: attest with iterate_feedback "less reverb". Assert iterations/002/feedback.json is ["more energy", "less reverb"]. Iter 3: attest with approve; assert host advances and no more iterations are written.
test_repeat_until_verifier_passes_advances_when_check_passes: code host step with repeat.until={condition: "verifier_passes", max_iterations: 2, on_exhaust: "fail"} and a json_file produces check. Iter 1: write garbage → produces_check_failed → iteration_failed. Iter 2: write valid JSON → checks pass → host advances.
test_repeat_until_max_exhaust_fail_raises: same plan with on_exhaust: "fail", max_iterations=1. Fail the only iteration; assert iteration_exhausted event and next gate call raises TaskRunGateError(recovery=~"abort --project").
test_repeat_until_max_exhaust_escalate_parks_for_attested_override: same plan with on_exhaust: "escalate". Fail max iterations; assert next gate call requires the synthetic exhaust-override attested command, and after --actor alice ack the host advances.
Step 11: repeat.for_each golden run + partial approval (tests/test_task_repeat_for_each.py — new file)
Scope: Small
test_for_each_static_expands_emits_for_each_expanded_once: host with repeat.for_each={items_source: "static", items: ("a", "b", "c")}. First gate call emits for_each_expanded with ["a", "b", "c"] and dispatches item "a". Subsequent gate calls cover items b and c.
test_for_each_partial_approval_via_item_flag: attested host body. Ack item "b" before item "a"; assert host does not advance until all three items are acked.
test_for_each_from_ref_resolves_at_runtime_from_prior_step_produces: prior code step list_videos produces videos.json containing ["v1", "v2"]. Host repeat.for_each={items_source: "from", from_ref: "list_videos.produces.videos"}. Assert for_each_expanded carries ["v1", "v2"] after the gate reaches the host.
test_for_each_replay_is_deterministic_from_events: hand-write events.jsonl containing only run_started + for_each_expanded(["a","b"]) + item_started("a") + item_completed("a"); call derive_cursor; assert it lands on item "b" without re-reading the prior step's produces JSON.
Runpytest tests/test_task_kernel_*.py tests/test_task_plan_schema.py tests/test_task_env_contract.py tests/test_doctor_setup.py tests/test_project_runs.py and assert every prior-phase test still passes. The legacy produces: tuple[str, ...] consumers need migration shims (Step 2 lists this); confirm test_attested_evidence_flags_recorded_and_canonical_match_succeeds still works because attested produces in that test was never declared.
Run the full suite once at the end to catch incidental couplings.
Execution Order
Build artagents/verify/ first (Step 1); its Check shape is the contract every other change relies on.
Extend plan.py schema and add event factories (Steps 2 + 3); these are pure data and run unit tests cheaply.
Wire inline-check execution into the gate (Step 4) before touching repeat — the rewind primitive is reused by repeat.until=verifier_passes.
Layer iteration frames (Step 5) on top of the rewind primitive, then per-item frames (Step 6), then on_exhaust (Step 7).
Land tests in the order they were authored (Steps 8–11), running each new file as it lands so failures localize to the just-added gate logic.
pytest tests/test_task_kernel_*.py (regression of Phase 1/2 kernel).
pytest tests/test_doctor_setup.py (verify guardrail for new verify/ dir).
pytest tests/ full sweep.
python3 -m artagents doctor — confirms structure check accepts verify.
code
Current plan metadata:
{
"version": 1,
"timestamp": "2026-05-04T18:52:34Z",
"hash": "sha256:b7bc42d251b6dba288c83ed583cb4fb7a4845cc4ce709ae213d94659fa4be682",
"questions": [
"repeat.for_each input source: should V1 support both a static items: [...] list AND a runtime from: \"<step-id>.produces.<name>\" reference into a prior step's JSON list output, or only the static form? (I assumed both, with from_ref resolved once on first arrival at the host and frozen into the for_each_expanded event so replay stays deterministic.)",
"Definition of "non-trivial attested produces" for the sentinel-only rejection: I assumed every attested produces is non-trivial \u2014 i.e., any Check whose sentinel=True (e.g., bare file_nonempty) is rejected for attested steps, but all_of(file_nonempty, json_file) is accepted. Confirm, or do you want a more nuanced rule (e.g., based on file extension)?",
"on_exhaust=escalate semantics: I assumed it parks the cursor on a synthetic attested-override step (ack --project <slug> --step <host>/exhaust-override --actor <name>) and continues after human attestation. Alternative: emit iteration_exhausted and silently advance (treat as recoverable). Which?",
"repeat.until=quorum Phase 3 scope: do you want full quorum implementation (advance after quorum_n distinct attestors sign off) or only definition-time validation with a TODO for full runtime support? (I assumed full implementation, since the data model is straightforward on top of step_attested.)",
"Should the iterate --feedback ack lifecycle verb itself be plumbed in Phase 3 or strictly deferred to Phase 5? (I assumed only the underlying event/data mechanism lands now; the CLI ships in Phase 5 per SD-020.)"
],
"success_criteria": [
{
"criterion": "All existing Phase 1/2 task-kernel tests pass unchanged: tests/test_task_kernel_events.py, test_task_kernel_gate.py, test_task_kernel_attested.py, test_task_kernel_nested.py, test_task_kernel_dispatch.py, test_task_kernel_e2e.py, test_task_plan_schema.py, test_task_env_contract.py.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_doctor_setup.py passes after verify is added to TOP_LEVEL_ARTAGENTS_DIRS.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "New tests/test_verify_helpers.py covers all six helpers (file_nonempty, json_file, json_schema, audio_duration_min, image_dimensions, all_of) and asserts canonical params hashing.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_task_inline_checks.py: code step with failing produces check rewinds the cursor (next gate_command of same command re-dispatches; events show step_dispatched -> step_completed -> produces_check_failed -> step_dispatched).",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_task_inline_checks.py: attested step with sentinel-only check (bare file_nonempty) is rejected at load_plan with TaskPlanError matching 'requires a semantic check'.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_task_inline_checks.py: code step with sentinel-only check loads cleanly; attested step with all_of(file_nonempty, json_file) loads cleanly.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_task_repeat_until.py: user_approves iteration writes attempts under iterations/NNN/, feedback.json accumulates, host advances on approve.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_task_repeat_until.py: verifier_passes iteration retries on produces_check_failed and advances when checks pass.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_task_repeat_until.py: on_exhaust='fail' raises TaskRunGateError with abort recovery; on_exhaust='escalate' parks for attested override and advances after --actor ack.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_task_repeat_for_each.py: static items expand, for_each_expanded event emitted exactly once, items dispatched in declaration order, per-item state lives under items//.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_task_repeat_for_each.py: partial approval via --item flag advances the targeted item's frame; host does not advance until every item is satisfied.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "tests/test_task_repeat_for_each.py: derive_cursor replay from a hand-written events.jsonl correctly resumes a partially-completed for_each without re-reading prior produces files.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Existing legacy produces-as-list plans (Phase 1/2 form) still load via load_plan and round-trip through to_dict() to a canonical dict form.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "events.jsonl hash chain remains intact (verify_chain returns ok=True) across all new event kinds: produces_check_failed/passed, iteration_started/failed/exhausted, for_each_expanded, item_started/completed/attested, cursor_rewind.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Full pytest suite passes: completes without regressions outside the task-kernel area.",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Phase 4 surface (artagents/orchestrate/, DSL) is NOT introduced; Phase 5 lifecycle verbs (next, ack, abort, etc.) are NOT introduced. Phase 3 stays additive.",
"priority": "must",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "Each new module stays focused: artagents/verify/checks.py under ~250 lines; gate.py growth bounded (no single helper >80 lines).",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": "New event-kind handling in derive_cursor remains pure-replay (no disk reads beyond what was already required for plan hash); for_each_expanded freezes the item set into the event so replay is deterministic.",
"priority": "should",
"requires": [
"read_files",
"subjective_judgment"
]
},
{
"criterion": " passes after adding the verify package.",
"priority": "should",
"requires": [
"run_shell"
]
}
],
"assumptions": [
"A1: "Non-trivial attested produces" = every attested produces. Concretely: an attested step whose contains any entry where is rejected at time. Code steps may use sentinel-only checks. Sentinel composition () is sentinel iff every constituent is sentinel.",
"A2: and use stdlib parsing (PNG/JPEG header bytes, module) when possible and fall back to subprocess for non-WAV audio. Tests or skip when ffprobe isn't on PATH.",
"A3: supports both (literal tuple) and ( reference resolved once on first arrival; the resolved item list is frozen into a event so cursor replay is deterministic from alone).",
"A4: parks on a synthetic attested-override step requiring ; raises with recovery. The step path for the synthetic override is .",
"A5: Cumulative feedback for is stored at as a JSON array of all prior strings. The Phase 3 mechanism is event-driven; the CLI verb arrives in Phase 5.",
"A6: keys are sorted in for stable plan-hash output. Each 's dict is also canonicalized (sorted keys) before serialization.",
"A7: ships fully in Phase 3 (advance after distinct values sign off), since the data model requires no new event kind.",
"A8: New top-level package is added to in Phase 3 (not deferred to Phase 4); remains a Phase 4 concern. is updated to expect .",
"A9: Existing legacy list on code steps is auto-normalized to so Phase-1/2 plans keep loading. Plan hash for a normalized legacy plan is required to match the original file's hash \u2014 hashes the canonical form."
],
"structure_warnings": []
}
code
Gate summary:
{
"recommendation": "ITERATE",
"rationale": "Light robustness: single revision pass to incorporate critique feedback.",
"signals_assessment": "",
"warnings": [],
"settled_decisions": []
}
code
Open significant flags:
[
{
"id": "FLAG-P3-001",
"severity": "significant",
"status": "open",
"concern": "step_dir_for path semantics: step_dir_for(slug, run_id, plan_step_id) at artagents/core/task/plan.py:82-92 validates plan_step_id with validate_run_id, which rejects '/'. Phase 3 needs the directory for nested step paths (e.g. 's1/c1') AND for iterations/NNN/ and items// subfolders, but the plan's Step 4 (_run_inline_checks) and Step 5/6 frame plumbing simply 'call step_dir_for' and 'append the iteration/item suffix' with no schema change. Without redesigning this helper (path-aware step id + optional iteration/item suffix), every produces-check call on a nested step or repeat host will raise ProjectPathError before any check runs.",
"evidence": "artagents/core/task/plan.py:82-92 calls validate_run_id on plan_step_id; _ID_RE in artagents/core/project/paths.py:50-55 disallows '/'. Plan Step 4 says step_dir = step_dir_for(slug, run_id, plan_step_path_for_dir) and Step 5/6 say append iterations/NNN / items// to the produces path without specifying a new helper signature."
},
{
"id": "FLAG-P3-002",
"severity": "significant",
"status": "open",
"concern": "for_each over a code body has no per-item dispatch contract. The plan defines --item only for attested partial approval (Step 6.4) and only describes per-item state directories. For a code step wrapped in repeat.for_each, the gate would dispatch the same command string for every item, but nothing tells the subprocess which item it is processing. Phase 1 ships ARTAGENTS_TASK_STEP_ID; Phase 3 needs an analogous ARTAGENTS_TASK_ITEM_ID (or per-item argv mutation) plumbed through apply_task_run_env / child_subprocess_env, otherwise for_each on code is unusable.",
"evidence": "Plan Step 6 only describes attested ack routing via --item. Step 5/6 produce per-item directories under items// but never extend the env contract that artagents/core/task/env.py:apply_task_run_env established in Phase 1 for STEP_ID/RUN_ID propagation. Without a per-item env var, the same code command runs identically N times."
},
{
"id": "FLAG-P3-003",
"severity": "significant",
"status": "open",
"concern": "Plan-hash stability for legacy plans: current _step_to_dict at artagents/core/task/plan.py:108-128 emits 'produces' on AttestedStep only when non-empty (line 119). The plan rewrites _step_to_dict to emit produces and repeat deterministically (sorted keys) but does not state that empty produces / absent repeat must still be omitted from the canonical dict. If the new code emits produces: {} or repeat: null for legacy steps, compute_plan_hash changes for already-active runs, breaking the active_run.json plan_hash pin and the existing tests that round-trip to_dict() (e.g. test_legacy_and_canonical_code_step_normalize_to_identical_to_dict). The plan should explicitly preserve omit-when-empty semantics for both fields.",
"evidence": "artagents/core/task/plan.py:119 currently gates produces emission on truthiness; tests/test_task_plan_schema.py:43-69 assert canonical to_dict equality between legacy and explicit forms. Plan Step 2.6 changes _step_to_dict but does not specify omit-when-empty."
}
]
code
Requirements:
- Before addressing individual flags, check: does any flag suggest the plan is targeting the wrong code or the wrong root cause? If so, consider whether the plan needs a new approach rather than adjustments. Explain your reasoning.
- Update the plan to address the significant issues.
- Keep the plan readable and executable.
- Return flags_addressed with the exact flag IDs you addressed.
- Include `changes_summary` as a short plain-English summary of what changed in the revision. If there were no concrete flags, say that explicitly (for example: `No critique flags were raised; refined wording and kept the plan aligned for execution.`).
- Preserve or improve success criteria quality. Each criterion must have a `priority` of `must`, `should`, or `info`. Promote or demote priorities if critique feedback reveals a criterion was over- or under-weighted.
- Each success criterion should include a `requires` field listing the capabilities needed for verification. Valid capability strings: `run_shell`, `read_files`, `run_tests`, `parse_diff`, `read_build_output`, `run_linter` (container), `drive_browser`, `inspect_runtime_ui`, `observe_runtime_logs`, `subjective_judgment`, `verify_physical_device` (human). `must` criteria MUST have non-empty `requires`. Example: `{"criterion": "All tests pass", "priority": "must", "requires": ["run_tests"]}`.
- Verify that the plan remains aligned with the user's original intent, not just internal plan quality.
- Remove unjustified scope growth. If critique raised scope creep, narrow the plan back to the original idea unless the broader work is strictly required.
- Maintain the structural template: H1 title, ## Overview, phase sections with numbered step sections, ## Execution Order or ## Validation Order.
- CRITICAL: Your entire revised plan markdown (all sections) must be output as the `plan` field in the structured output. The prose response must not contain the plan text.
- CRITICAL: Return only the structured JSON object for the schema fields `plan`, `changes_summary`, `flags_addressed`, `assumptions`, `success_criteria`, and `questions`. Do not add commentary before or after the JSON object.
Plan template — simple format (adapt to the actual repo and scope):
md
# Implementation Plan: [Title]
## Overview
Summarize the goal, current repository shape, and the constraints that matter.
## Main Phase
### Step 1: Audit the current behavior (`megaplan/prompts.py`)
**Scope:** Small
1. **Inspect** the current implementation and call out the exact insertion points (`megaplan/prompts.py:29`).
### Step 2: Add the first change (`megaplan/evaluation.py`)
**Scope:** Medium
1. **Implement** the smallest viable change with exact file references (`megaplan/evaluation.py:1`).
2. **Capture** any tricky behavior with a short example.
```python
issues = validate_plan_structure(plan_text)
```
### Step 3: Wire downstream behavior (`megaplan/handlers.py`, `megaplan/workers.py`)
**Scope:** Medium
1. **Update** the runtime flow in the touched files (`megaplan/handlers.py:400`, `megaplan/workers.py:199`).
### Step 4: Prove the change (`tests/test_evaluation.py`, `tests/test_megaplan.py`)
**Scope:** Small
1. **Run** the cheapest targeted checks first (`tests/test_evaluation.py:1`).
2. **Finish** with broader verification once the wiring is in place (`tests/test_megaplan.py:1`).
## Execution Order
1. Update prompts and mocks before enforcing stricter validation.
2. Land higher-risk wiring after the validator and tests are ready.
## Validation Order
1. Start with focused unit tests.
2. Run the broader suite after the flow changes are in place.
For complex plans, use multiple phases:
md
## Phase 1: Foundation — Dependencies, DB, Types
### Step 1: Install dependencies (`package.json`)
...
### Step 2: Create database migration (`supabase/migrations/`)
...
## Phase 2: Core Integration
### Step 3: Port the main component (`src/components/`)
...
Template guidance:
Simple plans: use ## Main Phase with ### Step N: sections underneath.
Complex plans: use multiple ## Phase N: sections, each containing ### Step N: steps. Step numbers are global (not per-phase).
The flat ## Step N: format (without phases) also works for backwards compatibility.
Key invariants: one H1 title, one ## Overview, numbered step sections (### Step N: or ## Step N:), and at least one ordering section.
Dataset releases
Not yet included in a published release.
tests/test_doctor_setup.py
"orchestrate"
Capture the canonical-serialization rule in a one-line module docstring on artagents/verify/__init__.py so authors know params ordering matters for plan hash determinism.
@dataclass(frozen=True)
class RepeatUntil:
condition: Literal["user_approves", "verifier_passes", "quorum"]
max_iterations: int
on_exhaust: Literal["escalate", "fail"]
quorum_n: int | None = None # only for condition="quorum"
@dataclass(frozen=True)
class RepeatForEach:
items_source: Literal["static", "from"]
items: tuple[str, ...] = () # items_source="static"
from_ref: str | None = None # items_source="from"; e.g. "list_videos.produces.videos"
Repeat = Union[RepeatUntil, RepeatForEach]
# On every step kind:
repeat: Repeat | None = None
Validaterepeat exclusivity (cannot have both until and for_each keys), max_iterations >= 1, and that from_ref strings parse as "<step-id>.produces.<name>" referencing a prior sibling step that produces JSON list output.
Update_step_to_dict to emit produces and repeat deterministically (sorted keys for produces names) so plan hash stays stable. Verify with the existing test_to_dict_emits_explicit_kind_for_every_step_recursively and add a new round-trip test.
produces_check_failed
step_dispatched
Add golden test: a code step with produces={"out": {"path": "out.json", "check": json_file()}} writes invalid JSON; gate emits step_completed + produces_check_failed; next gate_command with the same command succeeds (cursor did not advance) and writes a fresh step_dispatched event.
Cumulative feedback: when a step_attested event with iterate_feedback evidence string is seen on a user_approves host (only valid for repeat.until=user_approves per SD-020), write the feedback into iterations/NNN/feedback.json and emit iteration_failed. The next iteration starts with iterations/(NNN+1)/feedback.json containing the cumulative array of all prior feedback entries. (The iterate --feedback lifecycle verb itself ships in Phase 5; for Phase 3 we expose only the underlying mechanism via direct append_event from tests.)