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 preparing an execution-ready briefing document from the approved plan.
Implement Phase 1 (Kernel) of the ArtAgents orchestrator V1 design per the settled decisions in docs/orchestrator-v1-plan.md. Phase 1 scope: events.jsonl with plain sha256 hash chain (prev_hash + canonical_event_json, no HMAC); plan.json hash pinning; gate above dispatch as a single function checking active_run.json existence + plan.json hash match + events.jsonl chain integrity + incoming command matches plan[derived_cursor].command; active_run.json pointer at the project root. The runner becomes dumb; the gate is decorated/composed above runner dispatch. This is additive: existing OrchestratorDefinition JSON manifests and RUNTIME_KINDS={python,command} keep working, existing pack mechanism stays. No new step kinds yet (those are Phase 2). No produces-with-checks (Phase 3). No DSL (Phase 4). No new lifecycle verbs in this phase — that comes in Phase 5; for now, exercise the kernel through existing entry points so it can be verified end-to-end. Honor-based with strong logging — accidental-edit tripwire only. Single-host. Storage paths under ~/Documents/reigh-workspace/artagents-projects//. Add focused tests for: hash-chain append + verify; plan-hash pin + mismatch rejection; gate-rejects-non-canonical-command with the exact recovery error; gate is called from every dispatch entry point. Migration is mid-flight (recent commits T10-T13) so respect the current pack architecture.
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.
Assistant
Briefing finalized. 14 tasks (T1–T14) cover all 13 plan steps plus the validation sweep, with sense checks pinned to the FLAG-001 acceptance criteria (env contract centralized in prepare_project_run, no run.json written under env-set conditions, hype mirroring under <step_dir>/produces/) and the SD-011 verbatim recovery strings. FLAG-002 (canonical-JSON vs raw-byte plan hash) carried forward as a watch item, not a scope change.
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 1 of the Orchestrator V1 plan adds a kernel under artagents/core/task/ that gates every command dispatch against an immutable plan.json and a hash-chained events.jsonl, and plumbs the ARTAGENTS_TASK_RUN_ID env contract through the three prepare_project_run callers so that child orchestrator/executor/hype dispatches attach to the parent task run instead of creating sibling project runs. The kernel is additive — it activates only when an active_run.json pointer exists for the active project (or, for child processes, when ARTAGENTS_TASK_RUN_ID is inherited); otherwise the existing pipeline, orchestrator, executor, and hype paths run unchanged.
Repo dispatch surfaces (already present): artagents/pipeline.py:15 (top-level CLI gateway), artagents/core/orchestrator/runner.py:132 (run_orchestrator) with _prepare_project_request at line 397 calling prepare_project_run at 410, artagents/core/executor/runner.py:88 (run_executor) with its own _prepare_project_request calling prepare_project_run at 333, artagents/packs/builtin/hype/run.py:1447 (main) calling prepare_project_run at 1521, and artagents/core/project/run.py:59 (prepare_project_run). Storage root resolves through artagents/core/project/paths.py:20 → ~/Documents/reigh-workspace/artagents-projects/<slug>/. There is no artagents/core/task/ package yet.
Phase 1 explicitly does not add: new step kinds, the DSL, produces inline checks, repeat semantics, lifecycle verbs (next/ack/start), Stop-hook, or CAS. Those are Phases 2–7.
Key design decisions:
Hash chain: sha256(prev_hash + canonical_event_json), no HMAC (SD-004).
Plan hash: sha256 of the canonical-JSON re-serialized plan.json; active_run.json stores {"run_id", "plan_hash"} (SD-003).
Gate fires before_prepare_project_request() and thread_wrapper.begin_orchestrator_run() so a rejected command writes zero project-run side effects (SD-012, A7).
Single-host, honor-based, accidental-edit tripwire only (SD-025).
The "incoming command" matched against the plan cursor in Phase 1 is the canonical argv of the dispatch (no new verbs); cursor advances when step_completed is appended (SD-013).
ARTAGENTS_TASK_RUN_ID env contract is fully wired in Phase 1 (SD-017, A9; doc Section 12 Phase 1 exit criterion: "all three prepare_project_run() callers honor ARTAGENTS_TASK_RUN_ID"). When the env var is set, prepare_project_run does not create a child runs/<id>/run.json; instead it returns a ProjectRunContext whose run_root points at <projects_root>/<slug>/runs/<task-run-id>/steps/<plan-step-id>/ (SD-018). Standalone callers (env unset) keep generating fresh run dirs and run.json, preserving tests/test_project_runs.py.
Hype artifact mirroring under runs/<task-run-id>/steps/<step-id>/produces/ is included in Phase 1 because it is the SD-018 / A10 child-output preservation behavior tied to the env contract.
Verifyprepare_project_run body in artagents/core/project/run.py:59: it generates a fresh run id, makes runs/<id>/, writes run.json. This is the function whose body must become env-contract-aware.
Verifypaths.run_dir(slug, run_id) already produces <projects_root>/<slug>/runs/<run_id> — we will reuse it for the parent task run dir and add a sibling steps/<step-id>/ helper.
Implementcanonical_event_json(event) -> str: json.dumps(event, sort_keys=True, separators=(",", ":"), ensure_ascii=False), no trailing newline. The hash field is excluded from the canonicalization input (it is the output).
Implementverify_chain(events_path) -> tuple[bool, int, str | None] that streams lines, recomputing each hash. Missing file → (True, -1, None).
Implementread_events(events_path) -> list[dict] for cursor derivation.
Event helpers: make_run_started_event(run_id, plan_hash), make_step_dispatched_event(plan_step_id, command), make_step_completed_event(plan_step_id, returncode). Each carries kind and ISO-8601 UTC ts.
Step 4: Active-run pointer + plan hashing (artagents/core/task/active_run.py, artagents/core/task/plan.py)
step_dir_for(slug, run_id, plan_step_id, *, root=None) -> Path returns <projects_root>/<slug>/runs/<run_id>/steps/<plan_step_id>/. This is the join point for the env contract in Step 6.
Step 5: Env contract (artagents/core/task/env.py)
Scope: Small
Constants: TASK_RUN_ID_ENV = "ARTAGENTS_TASK_RUN_ID", TASK_PROJECT_ENV = "ARTAGENTS_TASK_PROJECT", TASK_STEP_ID_ENV = "ARTAGENTS_TASK_STEP_ID". The third constant is needed so child prepare_project_run callers can locate their step subdirectory; it is set by the gate when a step is dispatched and cleared after completion.
is_in_task_run(slug: str | None) -> bool returns True only when both TASK_RUN_ID_ENV is set and (slug is None or matches TASK_PROJECT_ENV).
apply_task_run_env(run_id, project_slug, step_id) -> None: mutates os.environ for in-process inheritance.
child_subprocess_env(*, base=None) -> dict[str, str]: returns a dict suitable for subprocess.run(env=...) that copies the three vars onto a base env. Phase 1 uses this only in the e2e smoke; full subprocess plumbing into code step launchers ships in Phase 2.
Step 6: prepare_project_run honors the env contract (artagents/core/project/run.py)
Scope: Medium
This step is the heart of FLAG-001 resolution. It teaches prepare_project_run itself to recognize ARTAGENTS_TASK_RUN_ID and reroute its output, so all three callers automatically honor it without per-caller branches.
Importfrom artagents.core.task import env as task_env and from artagents.core.task.plan import step_dir_for at the top of artagents/core/project/run.py.
Insideprepare_project_run (line 59), immediately after require_project(project_slug, root=root) and before effective_run_id = paths.validate_run_id(...):
If task_env.is_in_task_run(slug=project_slug):
Reject if task_env.task_project_env() != project_slug → raise ProjectRunError(f"task run is bound to project {task_env.task_project_env()!r}, refusing to prepare run for {project_slug!r}"). The gate enforces this on entry too; the inner check defends direct callers that bypass the gate.
Resolve parent_run_id = task_env.task_run_id_env(); step_id = task_env.task_step_id_env(). Both must be present; if step_id is missing, raise ProjectRunError("ARTAGENTS_TASK_STEP_ID must be set when ARTAGENTS_TASK_RUN_ID is set").
Build run_root = step_dir_for(project_slug, parent_run_id, step_id, root=projects_root), mkdir(parents=True, exist_ok=True). Do not write a child run.json. Do not call validate_run_id against a fresh id; the parent already owns provenance (SD-013, SD-018).
Build a stub record for the returned ProjectRunContext (filled with run_id=parent_run_id, status="attached", metadata={"task_step_id": step_id, "attached_to_task_run": True}) — the record is not written to disk. The return type stays ProjectRunContext so callers don't fork.
Return early with this context.
Else (env unset): execute the existing body unchanged. Standalone behavior is bit-identical, preserving tests/test_project_runs.py.
Insidefinalize_project_run (line 98+): when record["metadata"].get("attached_to_task_run") is truthy, skip the write_json_atomic(run_json_path, record) write at the end and skip the cumulative runs.json upsert (if any). Hype artifact mirroring via mirror_hype_artifacts(run_root, ...) still runs — this gives us the SD-018 mirror under runs/<task-run-id>/steps/<step-id>/produces/ for free, because run_root already points at the step dir. Confirm mirror_hype_artifacts writes into run_root/produces/ (or adjust the destination path so produces mirroring lands under <step_dir>/produces/).
Add focused unit tests in tests/test_task_env_contract.py:
With env set: prepare_project_run returns a context whose run_root is the step dir, no run.json exists on disk, and a second call for a different step_id reuses the same parent run dir.
With env set but slug != TASK_PROJECT_ENV: raises ProjectRunError.
With env unset: behavior is identical to today (existing tests/test_project_runs.py still passes).
With TASK_RUN_ID_ENV set but TASK_STEP_ID_ENV unset: raises ProjectRunError.
Step 7: The gate (artagents/core/task/gate.py)
Scope: Medium
TaskRunGateError(RuntimeError) with (reason, recovery). CLI prints recovery and exits non-zero.
Inactive: if read_active_run(slug) is None and not task_env.is_in_task_run(slug), return GateDecision(active=False).
Active: load active_run.json; locate runs/<run_id>/plan.json; recompute plan hash; mismatch → TaskRunGateError(reason="plan.json hash does not match active_run.json pin", recovery=f"artagents abort --project {slug}").
Chain integrity: verify_chain(events_path); failure → same abort recovery.
Cursor: cursor = sum(1 for e in read_events(events_path) if e["kind"] == "step_completed"). If cursor >= len(plan.steps) → abort recovery (run complete).
Reentry path: if reentry=True, accept iff the most recent event is step_dispatched for plan.steps[cursor].id and command == plan.steps[cursor].command. Do not append a new step_dispatched event.
Fresh dispatch path (reentry=False): if command != plan.steps[cursor].command → TaskRunGateError(reason="incoming command does not match plan[cursor]", recovery=f"artagents next --project {slug}"). Otherwise append make_step_dispatched_event(...) and call task_env.apply_task_run_env(run_id, slug, plan.steps[cursor].id).
record_dispatch_complete(decision, returncode): append make_step_completed_event(decision.plan_step_id, returncode). Top-level callers wrap their dispatch in try/finally.
command_for_argv(argv) -> str: drop argv[0] if it ends in artagents or matches python3 -m artagents; otherwise keep all. Join with " ".join(shlex.quote(a) for a in tokens). Document that plan.json step command strings must be the exact output of this function for the dispatch they expect.
Step 8: Wire gate into pipeline.py (artagents/pipeline.py)
Scope: Small
Insert an early gate hook in main() directly after the help short-circuit (pipeline.py:19), before any subcommand dispatch.
Slug resolution: helper _extract_project_slug(raw) scans raw for --project <slug> and --project=<slug>. If absent, skip the gate entirely (additive guarantee).
Callgate_command(slug, command_for_argv(raw), raw). On TaskRunGateError: print f"task-mode gate rejected: {e.reason}\nrecovery: {e.recovery}" to stderr, return 1. On decision.active: wrap the existing return … for the matched subcommand in try/finally so record_dispatch_complete(decision, returncode) always fires. On inactive: fall through.
Do not add new subcommands.
Step 9: Defensive re-check in run_orchestrator and run_executor (artagents/core/orchestrator/runner.py, artagents/core/executor/runner.py)
Scope: Small
run_orchestrator (line 132): at the very top, before active_registry = … (line 133), call gate_command(slug, command_for_argv(_request_argv_for_gate(request)), [], reentry=True) when request.project is truthy AND task_env.is_in_task_run(request.project). Helper _request_argv_for_gate rebuilds the canonical argv from ("orchestrators", "run", request.orchestrator_id, *request.orchestrator_args, "--project", request.project). On rejection raise OrchestratorRunnerError(decision.recovery).
Critical ordering: the guard is above _prepare_project_request() (line 135) and thread_wrapper.begin_orchestrator_run() (line 136). On rejection, zero project-run files are written.
run_executor (line 88): mirror with reentry=True semantics. Same ordering invariant — gate before _prepare_project_request (which calls prepare_project_run).
Step 10: Defensive re-check in hype.main (artagents/packs/builtin/hype/run.py)
Scope: Small
At the top of main() (line 1447), after argument parsing but before any prepare_project_run call, parse --project out of argv and call gate_command(slug, command_for_argv(argv_with_python_module_prefix), argv, reentry=True). On rejection, print recovery and return non-zero. Re-entry mode here matches what prepare_project_run will see: the gate has already accepted at top level, env is set, and this re-check is only a tripwire against direct invocation outside pipeline.main.
Step 11: Tests for the kernel (tests/test_task_kernel_events.py, tests/test_task_kernel_gate.py, tests/test_task_kernel_dispatch.py, tests/test_task_env_contract.py)
Scope: Medium
Add a tmp_projects_root fixture in tests/conftest.py that sets ARTAGENTS_PROJECTS_ROOT=tmp_path and clears ARTAGENTS_TASK_* env vars on entry/exit.
tests/test_task_kernel_events.py:
Append three events; verify_chain returns (True, 2, None).
Mutate a non-hash field on line 2; verify_chain returns (False, _, error).
Truncate mid-line; chain rejects.
Canonicalization is order-stable across permuted-key inputs.
tests/test_task_kernel_gate.py:
Hash-chain append + verify round-trip over 5 events.
Plan-hash pin + mismatch rejection: gate raises TaskRunGateError with recovery "artagents abort --project demo" after plan.json is mutated.
Gate rejects non-canonical command: recovery is "artagents next --project demo" exactly.
Inactive gate is transparent: no active_run.json and no env vars → returns GateDecision(active=False), no events written.
Cursor advance: after record_dispatch_complete, next gate accepts step 1.
Plan exhausted: dispatching past the last step → abort recovery.
Reentry mode: after fresh-dispatch accept (which appended step_dispatched), a reentry=True call for the same command does not append another step_dispatched and returns GateDecision(reentry=True).
Spy via unittest.mock.patch on artagents.core.task.gate.gate_command.
Pipeline: pipeline.main(["executors", "run", "builtin.noop", "--project", "demo"]) with active task run setup; spy is called at top-level (reentry=False) and again inside run_executor (reentry=True).
Orchestrator runner: run_orchestrator(OrchestratorRunRequest(orchestrator_id="builtin.hype", project="demo")) with mismatched plan; raises OrchestratorRunnerError and creates no run dir.
Executor runner: same shape on run_executor.
Hype runtime: hype.main(["--project", "demo", "--brief", "..."]) with mismatched plan; returns non-zero, no run.json written.
With ARTAGENTS_TASK_RUN_ID/TASK_PROJECT/TASK_STEP_ID set: prepare_project_run("demo", ...) returns ProjectRunContext whose run_root is <projects_root>/demo/runs/<task-run-id>/steps/<step-id>/, and no run.json is written (assert the file does not exist).
With env set but slug mismatched: raises ProjectRunError.
With TASK_RUN_ID_ENV set but no TASK_STEP_ID_ENV: raises ProjectRunError.
With env unset: standalone behavior is byte-identical (run dir + run.json appear).
Hype artifact mirroring: simulate a hype run completing with timeline/assets/metadata files in the step dir; assert mirror_hype_artifacts deposits them under <step_dir>/produces/ and not into a sibling child runs/<id>/.
All three callers honor the contract: spy prepare_project_run once and confirm it is the single function the orchestrator/executor/hype call paths flow through; assert each path under env-set conditions returns step-dir-rooted contexts.
tests/test_project_runs.py must still pass with no edits (env-unset standalone path).
Author a two-step plan.json whose command strings invoke python3 -c "print('ok')" (no real executors required).
Drive the kernel directly: write active_run.json; call gate_command (fresh dispatch); spawn the subprocess with child_subprocess_env(...) merged into os.environ; call record_dispatch_complete; repeat for step 2.
Assertevents.jsonl ends with step_completed (seq=3) after the second step (events: step_dispatched, step_completed, step_dispatched, step_completed — or 4 events total counting started; just verify the chain verifies and the step_completed count equals 2).
Assert a third dispatch is rejected with abort recovery.
This satisfies the doc's Phase 1 exit criterion: "hand-authored plan.json runs end-to-end".
Append a ~10-line "Phase 1 status" footnote: list the new kernel modules, the four entry points decorated, the three prepare_project_run callers honoring the env contract via the centralized check inside prepare_project_run, and the items deferred to later phases (full subprocess env propagation in Phase 2 step launchers, lifecycle verbs in Phase 5, CAS in Phase 7).
Do not create AUTHORING.md, AGENT.md template, or new READMEs — those are Phase 4/6 deliverables.
Execution Order
Land kernel modules (Steps 2–5) and event/gate unit tests (Step 11 parts 1–2). These are pure additions.
Land the env-contract change in prepare_project_run (Step 6) and its test file (Step 11 part 4) — this is the FLAG-001 fix; isolates the contract in one function so all three callers honor it.
Run pytest tests/test_project_runs.py to confirm env-unset path is byte-identical.
Wire pipeline.py top-level gate (Step 8); run pipeline tests.
Wire defensive re-checks into orchestrator/executor/hype runners (Steps 9–10) one at a time, running tests/test_canonical_cli.py after each.
Add dispatch-coverage tests (Step 11 part 3).
Run e2e smoke (Step 12).
Document (Step 13).
Validation Order
pytest tests/test_task_kernel_events.py tests/test_task_kernel_gate.py — events and gate unit tests.
pytest tests/test_task_env_contract.py — env-contract plumbing into prepare_project_run (FLAG-001).
pytest tests/test_project_runs.py — confirms env-unset standalone path is unchanged.
pytest tests/test_task_kernel_dispatch.py — confirms gate is called at all four dispatch entry points.
"version": 2,
"timestamp": "2026-05-04T11:56:44Z",
"hash": "sha256:309cf656b5b6429089a3a41bfb140b44f23d3eb72d270bcc2633caa45c09ba51",
"changes_summary": "Addressed FLAG-001 by promoting ARTAGENTS_TASK_RUN_ID plumbing from "deferred to Phase 2" to a first-class Phase 1 step. New Step 6 teaches prepare_project_run itself to recognize the env contract \u2014 when ARTAGENTS_TASK_RUN_ID/TASK_PROJECT/TASK_STEP_ID are set, it routes output to runs/<task-run-id>/steps/<step-id>/ instead of creating a child run.json. This makes all three prepare_project_run callers (orchestrator runner, executor runner, hype.main) honor the env contract without per-caller branches, satisfying the doc's Phase 1 exit criterion. Added a new TASK_STEP_ID_ENV constant in task/env.py so child callers can locate their step subdirectory. Added tests/test_task_env_contract.py covering env-set step-dir routing, env-unset byte-identical standalone behavior, slug-mismatch rejection, missing-step-id rejection, and hype artifact mirroring under <step_dir>/produces/. Updated success criteria to elevate the env-contract behavior from should to must and added new criteria for hype artifact mirroring and the prepare_project_run central-honor design. Updated execution order to land Step 6 right after the kernel modules so the FLAG-001 fix is verified before any dispatch wiring.",
"flags_addressed": [
{
"id": "FLAG-001",
"resolution": "addressed",
"reason": "Added Step 6 which centralizes the env-contract honor inside prepare_project_run itself, so all three callers (orchestrator, executor, hype) automatically honor ARTAGENTS_TASK_RUN_ID. Step 6 makes prepare_project_run route to runs/<task-run-id>/steps/<step-id>/ and skip child run.json when the env vars are set; standalone (env-unset) behavior stays byte-identical so tests/test_project_runs.py still passes. Introduced ARTAGENTS_TASK_STEP_ID so child callers can locate their step subdirectory. Added tests/test_task_env_contract.py with explicit coverage for each caller path and the SD-018 hype artifact mirroring under <step_dir>/produces/. Promoted the env-contract success criterion from should to must."
}
],
"questions": [
"The doc names only ARTAGENTS_TASK_RUN_ID in the env contract, but SD-018's mirroring requirement (steps/<step-id>/produces/) is not satisfiable without a step id known to the child. The plan introduces ARTAGENTS_TASK_STEP_ID as a sibling constant. Confirm this is acceptable as a Phase 1 addition, or do you want a different mechanism (e.g. derive step id from cursor by re-reading events.jsonl in the child)?",
"When the env contract is active and a child prepare_project_run is invoked twice for the same step (e.g. retry of the same step), the plan reuses <step_dir>/ and tolerates mkdir(parents=True, exist_ok=True) over an existing dir. Should retries instead route to <step_dir>/iterations/NNN/? That is closer to the Phase 3 iteration model but adds Phase-3 surface area; the plan currently keeps retries flat in Phase 1.",
"The plan still prints recovery strings (artagents abort --project <slug> / artagents next --project <slug>) that don't have CLI verbs until Phase 5. Confirm verbatim emission per SD-011, or substitute Phase-1-actionable instructions today (e.g. rm <slug>/active_run.json).",
"Plan-hash uses canonical-JSON re-serialization rather than raw-byte hashing. Confirm or pick raw-byte hashing for a strictest tripwire."
],
"success_criteria": [
{
"criterion": "artagents/core/task/{events.py,active_run.py,plan.py,gate.py,env.py,__init__.py} exist and import cleanly under python3 -m artagents without error",
"priority": "must",
"requires": [
"run_shell",
"read_files"
]
},
{
"criterion": "append_event followed by verify_chain returns ok=True for a freshly written events.jsonl, and verify_chain returns ok=False after any byte mutation of a recorded event field",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Hash chain uses sha256(prev_hash + canonical_event_json) with no HMAC and no secret key (verifiable by reading events.py)",
"priority": "must",
"requires": [
"read_files"
]
},
{
"criterion": "compute_plan_hash returns a stable sha256:<hex> value; gate rejects dispatch with the documented abort-recovery message when the live plan.json hash differs from the pin in active_run.json",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Gate rejects a non-canonical command (one that does not match plan[cursor].command) with recovery artagents next --project <slug> printed verbatim",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Gate is invoked at all four documented dispatch entry points (pipeline.main, run_orchestrator, run_executor, hype.main); spy-based tests confirm coverage",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "When the gate rejects a command, no project-run files are created \u2014 the run directory under <projects_root>/<slug>/runs/ does not appear and run.json is not written",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "When active_run.json does not exist for the project, no ARTAGENTS_TASK_RUN_ID is set, or no --project is supplied, every existing CLI path behaves identically to today: tests/test_project_runs.py, tests/test_canonical_cli.py, tests/test_pipeline_dispatch_aliases.py, and tests/test_pipeline_editor_loop.py all pass without modification",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Hand-authored Phase 1 e2e smoke: a two-step plan.json runs end-to-end through the gate, events.jsonl contains exactly two step_completed records, the chain verifies, and a third dispatch is rejected",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "All three prepare_project_run callers (orchestrator runner _prepare_project_request, executor runner _prepare_project_request, hype _prepare_project_main) honor ARTAGENTS_TASK_RUN_ID: when the env var is set, prepare_project_run returns a ProjectRunContext whose run_root is <projects_root>/<slug>/runs/<task-run-id>/steps/<step-id>/ and writes no child run.json",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "When ARTAGENTS_TASK_RUN_ID is unset, prepare_project_run produces a fresh run dir and run.json byte-identically to today's behavior (regression-checked by tests/test_project_runs.py passing without edits)",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "prepare_project_run raises ProjectRunError if ARTAGENTS_TASK_PROJECT is set and disagrees with the slug being prepared, and also if ARTAGENTS_TASK_RUN_ID is set without ARTAGENTS_TASK_STEP_ID",
"priority": "must",
"requires": [
"run_tests"
]
},
{
"criterion": "Hype artifact mirroring (mirror_hype_artifacts) deposits timeline/assets/metadata under <step_dir>/produces/ when running attached to a task run, instead of creating a sibling child runs/<id>/ directory (SD-018 child-output preservation)",
"priority": "must",
"requires": [
"run_tests",
"read_files"
]
},
{
"criterion": "Each new kernel module is under ~200 lines and has a single responsibility (events / active-run / plan / gate / env)",
"priority": "should",
"requires": [
"read_files"
]
},
{
"criterion": "No new top-level CLI subcommands are introduced in Phase 1 (Phase 5 scope); pipeline.py keeps its existing routing table intact",
"priority": "should",
"requires": [
"parse_diff"
]
},
{
"criterion": "No new step kinds (code/attested/nested) are introduced in Phase 1 (Phase 2 scope); RUNTIME_KINDS={python,command} in artagents/core/orchestrator/schema.py is unchanged",
"priority": "should",
"requires": [
"parse_diff"
]
},
{
"criterion": "No HMAC, keyed crypto, .index.db, daemon, web server, or shared CAS introduced (SD-029)",
"priority": "must",
"requires": [
"read_files",
"parse_diff"
]
},
{
"criterion": "Full pytest tests/ passes after Phase 1 lands",
"priority": "must",
"requires": [
"run_tests"
]
}
],
"assumptions": [
"The gate prints the doc-canonical recovery strings verbatim (artagents abort --project <slug> / artagents next --project <slug>) even though those verbs ship in Phase 5; this matches SD-011 and avoids changing the recovery copy later.",
"Plan-hash uses canonical-JSON re-serialization (tolerant to whitespace) rather than raw-byte hashing.",
"Command-string matching is exact equality on the canonical argv form; plan.json command strings include --project <slug> explicitly.",
"artagents/threads/wrapper.py:21-26 is referenced only because new env constants in task/env.py must coexist with RUN_ID_ENV/PARENT_RUN_ID_ENV; no code change in wrapper.py for Phase 1.",
"ARTAGENTS_TASK_STEP_ID is a new sibling env var introduced in Phase 1 because child prepare_project_run callers need to locate their step subdirectory under the parent task run; the doc names only ARTAGENTS_TASK_RUN_ID but the SD-018 mirroring requirement (steps/<step-id>/produces/) is not satisfiable without a step id, so adding this third var is in-scope for the env contract.",
"The kernel is opt-in: gate is fully transparent (returns active=False, writes no events) when no active_run.json exists and no ARTAGENTS_TASK_RUN_ID is inherited.",
"Cursor derivation in Phase 1 is count(step_completed events); richer cursor semantics (iterations, items, nested) arrive in Phases 2\u20133.",
"TOP_LEVEL_ARTAGENTS_DIRS is unchanged in Phase 1 because core/task/ lives under the existing core/ package; SD-016's orchestrate/verify additions belong to Phase 4.",
"Subprocess env propagation into code step launchers (so child python3 -m artagents invocations inherit the three env vars automatically) is Phase 2 scope; Phase 1 only provides the child_subprocess_env() helper and uses it directly in the e2e smoke."
],
"delta_from_previous_percent": 85.49,
"structure_warnings": []
}
code
Gate summary:
{
"recommendation": "ITERATE",
"rationale": "Light robustness: single revision pass to incorporate critique feedback.",
"signals_assessment": "",
"warnings": [],
"settled_decisions": []
}
code
Flag registry:
[
{
"id": "FLAG-001",
"concern": "Task run env: The plan does not actually make the three prepare_project_run callers honor ARTAGENTS_TASK_RUN_ID. It only proposes setting the env var in the gate and adding a slug-mismatch check in prepare_project_run, while explicitly deferring the project-run inheritance/body behavior to a later phase. In the current repo, all accepted --project executor/orchestrator/hype dispatches immediately call prepare_project_run and create a fresh project run directory/run.json, so the task run id in active_run.json is not used by those callers. That misses the Phase 1 exit criterion in docs/orchestrator-v1-plan.md that all three prepare_project_run callers honor ARTAGENTS_TASK_RUN_ID.",
"evidence": "Addressed FLAG-001 by promoting ARTAGENTS_TASK_RUN_ID plumbing from "deferred to Phase 2" to a first-class Phase 1 step. New Step 6 teaches prepare_project_run itself to recognize the env contract \u2014 when ARTAGENTS_TASK_RUN_ID/TASK_PROJECT/TASK_STEP_ID are set, it routes output to runs/<task-run-id>/steps/<step-id>/ instead of creating a child run.json. This makes all three prepare_project_run callers (orchestrator runner, executor runner, hype.main) honor the env contract without per-caller branches, satisfying the doc's Phase 1 exit criterion. Added a new TASK_STEP_ID_ENV constant in task/env.py so child callers can locate their step subdirectory. Added tests/test_task_env_contract.py covering env-set step-dir routing, env-unset byte-identical standalone behavior, slug-mismatch rejection, missing-step-id rejection, and hype artifact mirroring under <step_dir>/produces/. Updated success criteria to elevate the env-contract behavior from should to must and added new criteria for hype artifact mirroring and the prepare_project_run central-honor design. Updated execution order to land Step 6 right after the kernel modules so the FLAG-001 fix is verified before any dispatch wiring.",
"status": "addressed",
"severity": "significant"
},
{
"id": "FLAG-002",
"concern": "Plan hash pinning: The plan hashes a canonical JSON reserialization of plan.json, which allows whitespace-only edits to the supposedly immutable plan without tripping the pin. The design document describes plan.json as immutable runtime truth and Phase 1 as hash pinning for an accidental-edit tripwire. If the goal is to detect edits to plan.json, hashing raw file bytes is the simpler and stricter implementation.",
"evidence": "docs/orchestrator-v1-plan.md:36 says active_run.json stores the plan_hash, plan.json is immutable after start, and plan.json is the runtime truth the gate hashes. The submitted plan's Step 4 says compute_plan_hash parses plan.json, re-canonicalizes it, and intentionally tolerates editor reformatting.",
"status": "open",
"severity": "minor"
}
]
Requirements:
- Produce structured JSON only.
- `tasks` must be an ordered array of task objects. Every task object must include:
- `id`: short stable task ID like `T1`
- `description`: concrete work item
- `depends_on`: array of earlier task IDs or `[]`
- `status`: always `"pending"` at finalize time
- `executor_notes`: always `""` at finalize time
- `reviewer_verdict`: always `""` at finalize time
- `watch_items` must be an array of strings covering runtime risks, critique concerns, and assumptions to keep visible during execution.
- `sense_checks` must be an array with one verification question per task. Every sense-check object must include:
- `id`: short stable ID like `SC1`
- `task_id`: the related task ID
- `question`: reviewer verification question
- `verdict`: always `""` at finalize time
- `user_actions` must be an array of human-only setup or operational actions. Use IDs `U1`, `U2`, ... and include `description` plus `phase` (`before_execute` or `after_execute`). Use optional `blocks_task_ids` when an action blocks specific tasks, optional `rationale` when useful, and `requires_human_only_reason` ONLY when the user_action is the sole coverage for a plan step.
Include ONLY actions that require a human outside the executor's repo-editing work: env vars or secrets, infra access such as cloud accounts or VPN, DB migrations the human must trigger, manual UI/UX smoke tests, deploys, and out-of-band approvals.
Anything that touches code in the repo MUST be a task, not a user_action. Reading docs, editing files, running tests, and writing migration SQL are tasks. Negative example: writing the migration SQL is a task, not a user_action.
Positive examples: U1: Set ANTHROPIC_API_KEY in .env (before_execute); U2: Manually smoke test the production deploy in the browser (after_execute).
- meta_commentary must be a single string with execution guidance, gotchas, or judgment calls that help the executor succeed.
- validation must be an object that self-checks plan coverage:
- plan_steps_covered: enumerate EVERY step from the approved plan. For each step, provide a short plan_step_summary (the step's intent in one phrase) and finalize_item_ids (array of task IDs T* or user_action IDs U* that implement or cover it — a single plan step may map to multiple tasks and/or user_actions).
- orphan_tasks: task IDs that do not correspond to any plan step. Normally empty. If non-empty, explain in completeness_notes.
- completeness_notes: free-text explanation of any gaps, deviations, or deliberate omissions.
- coverage_complete: set to true only if every plan step has at least one finalize task or user_action AND you have verified the mapping by reviewing each entry. Set to false if any plan step is missing coverage.
- Example:
json "validation": { "plan_steps_covered": [ {"plan_step_summary": "Add retry logic to API client", "finalize_item_ids": ["T1", "T2"]}, {"plan_step_summary": "Set required production secret", "finalize_item_ids": ["U1"]} ], "orphan_tasks": [], "completeness_notes": "All plan steps mapped to tasks.", "coverage_complete": true }
- Preserve information that strong existing artifacts already capture well: execution ordering, watch-outs, reviewer checkpoints, and practical context.
- The structured output should be self-contained: an executor reading only finalize.json should have everything needed to work.
- Keep the task count proportional to the work. A simple 1-2 file fix should be 2 tasks: (1) apply the fix, (2) run tests. Do NOT create separate "inspect" or "read" tasks for simple changes — the executor can read and fix in one step. Only create more tasks when the work has genuinely independent stages.
- - The FINAL task MUST always be to run tests and verify the changes work. If specific test IDs or commands are mentioned in the original task, include them. Otherwise, the executor should find and run the tests most relevant to the files changed. If any test fails, read the error, fix the code, and re-run until they pass. Do NOT create new test files — run the project's existing test suite. Additionally, the executor should write a short throwaway script that reproduces the specific bug described in the task, run it to confirm the fix works, then delete the script.