AI Agent Claude-Codex
Chonyoomin/AI-Agent-Claude-Codex
Orquestração local Claude-Codex com fases auditáveis e aprovação humana
Ver no GitHubAgent que orquestra um fluxo de trabalho controlado entre Claude e Codex para desenvolvimento de código em fases. Mantém auditoria completa, valida mudanças localmente e requer aprovação humana em cada etapa, eliminando cópia manual entre ferramentas.
Instalação
npx convez-ai Chonyoomin/AI-Agent-Claude-Codex1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Desenvolvimento de software com revisão estruturada entre dois agentes
- Workflows de build-review-fix automatizados e auditáveis
- Projetos que exigem validação e aprovação humana entre fases
Veredito

Sistema bem pensado para orquestração segura de agentes com foco em auditoria e controle humano. Reduz fricção entre Claude e Codex mantendo guardrails críticos (sem auto-commit, sem push automático). Adequado para equipes que precisam de workflows estruturados e rastreáveis.
README
A tradução para o português deste README ainda está na fila.
Agentic AI Coding Loop
Agentic AI Coding Loop is a local orchestration project for running a controlled, phase-gated build-review-fix workflow between Codex and Claude Code.
Codex acts as the planner, task-state manager, reviewer, validator, and fix-prompt generator. Claude Code acts as the implementation agent for the active phase only. A local orchestrator manages prompts, artifacts, validation logs, and loop state. A human approves movement between phases and separately approves any eventual commit.
Goal
Reduce manual copy/paste between Codex and Claude Code while keeping the workflow auditable, scoped, and safe.
MVP
The first version focuses on a small local loop:
- read a human-provided objective
- let Codex maintain
TASK.mdand active phase state - generate a focused Claude implementation prompt
- let Claude implement the requested phase
- capture Claude's structured summary
- capture
git diffandgit status - run validation commands and save logs
- let Codex review the prompt, summary, diff, and logs
- generate a fix prompt if needed
- stop after each approved phase until the human starts the next one
Workflow
This section describes the intended end-to-end workflow once the orchestrator (Phase 3) is built. Until then, the same loop runs by hand - see ## Running The Loop Manually (Phase 1) below.
- Human provides the project objective or updates the desired outcome.
- Codex updates
TASK.md,.agent-loop/current-task.md, and.agent-loop/current-phase.mdfor the active phase. - Codex writes
.agent-loop/claude-prompt.md. - Claude Code implements only the active phase and writes
.agent-loop/claude-summary.md. - The orchestrator captures diff, status, and validation logs.
- Codex writes
.agent-loop/codex-review.mdwith one verdict:APPROVED_FOR_HUMAN_REVIEWNEEDS_FIXESFAILED_REQUIRES_HUMAN
- If fixes are required, Codex classifies review findings by ownership: supported Codex-owned follow-up is handled directly, and Claude-owned fixes are synchronized into
.agent-loop/fix-prompt.md. - Claude applies targeted fixes within the same phase.
- The loop repeats until the phase is approved, escalated, or reaches max cycles.
- When a phase is approved, the system stops until the human starts the next phase.
- The system never commits without separate human approval.
Repository Files
Top-level project files:
README.md: public project overviewAGENTS.md: operating rules, review standards, and artifact formatsCLAUDE.md: Claude Code implementation contractROADMAP.md: phased delivery planTASK.md: Codex-maintained task and phase record derived from the human objective
Loop artifacts:
.agent-loop/
phase-plan.md
current-task.md
current-phase.md
claude-prompt.md
claude-summary.md
git-diff.patch
git-status.log
test-output.log
lint-output.log
typecheck-output.log
build-output.log
codex-review.md
fix-prompt.md
loop-state.json
Safety
- no auto-commit
- no auto-push
- no hidden validation failures
- no trusting summary text over actual diffs and logs
- no phase advancement without human approval
- no final commit without human approval
Ownership Rules
- Claude Code is the default implementation editor for code, tests, scripts, configuration, and other non-state repository files during an active phase
- Codex should normally route implementation changes to Claude Code and edit directly only when the issue has been intentionally assigned to Codex
- planning-state hygiene issues should be treated as Codex-resolved and fixed directly by Codex
.agent-loop/loop-state.json,.agent-loop/orchestrator.log, and the evidence files are owned by the orchestrator or the scripts that generate them; they must not be fabricated by hand outside explicitly assigned implementation work- if ownership is ambiguous, the change should be routed to Claude Code or escalated for human clarification rather than guessed
- when continuing an active implementation phase, Codex should first summarize the remaining implementation gap, classify it as Claude-resolved or Codex-resolved, and if it is Claude-resolved write the precise Claude Code task prompt before implementation proceeds
- when the human starts a new phase or sub-phase, Codex should first provide a rundown of what will be implemented, split the work into Codex-resolved and Claude-resolved responsibilities, send the Claude-resolved portion as a precise Claude Code task prompt, and then perform only the Codex-resolved portion directly
Running The Loop Manually (Phase 1)
While the orchestrator is not yet built, the loop runs by hand against the artifact formats defined in AGENTS.md. One full manual cycle:
- Codex updates
TASK.md,.agent-loop/current-task.md, and.agent-loop/current-phase.mdfor the active phase. - Codex writes the implementation prompt to
.agent-loop/claude-prompt.mdusing the required Claude task format. - A human pastes that prompt into Claude Code.
- Claude Code implements only the active phase and writes
.agent-loop/claude-summary.mdusing the required Claude implementation summary format. - A human captures evidence into
.agent-loop/:git diff > .agent-loop/git-diff.patchgit status > .agent-loop/git-status.log- test, lint, typecheck, and build output to
.agent-loop/test-output.log,.agent-loop/lint-output.log,.agent-loop/typecheck-output.log,.agent-loop/build-output.log(or record "Not run" explicitly).
- A human pastes the prompt, summary, diff, and logs into Codex.
- Codex writes
.agent-loop/codex-review.mdwith exactly one verdict:APPROVED_FOR_HUMAN_REVIEW,NEEDS_FIXES, orFAILED_REQUIRES_HUMAN. - If the verdict is
NEEDS_FIXES, Codex-owned follow-up is applied first where supported,.agent-loop/fix-prompt.mdis regenerated from the Claude-owned review issues, and the cycle repeats from step 3 withinmax_cycles. - The cycle stops for human approval before any commit, and again before the next phase begins.
.agent-loop/loop-state.json records the active phase, task, cycle count, max cycles, and last verdict by hand.
Current Status
The instruction contract, prompt formats, review formats, task and phase ownership rules, and safety model are in place. Phase 1 (Manual File-Based Loop), Phase 2A (Evidence Collection Contract), Phase 2B (scripts/run_checks.sh), Phase 3 (Scripted Orchestrator MVP, delivered as sub-phases 3A through 3E), Phase 4A (Planning Contract), Phase 4B (Planner Initial Slice; the plan subcommand), Phase 4C (Planner Activation Writes; the activate subcommand), Phase 4D (Planner-Orchestrator Integration; the contained post-approval planner refresh), Phase 4E (Planner Adapter Seam; routing both planner call sites through make_planner_adapter()), Phase 4F (Planner Adapter Selection; adding one alternate adapter path while preserving the planner write boundary), Phase 5A (Approval Modes Contract), Phase 5B (Review Mode Initial Slice), Phase 5C (Strict Mode Pauses), Phase 5D (Autonomous Mode Initial Slice), Phase 5E (Post-Review Artifact Reconciliation), Phase 5F (Automatic Phase-Start Claude Prompt Bootstrap), Phase 6A (Durable Memory Contract), Phase 6B (Structured Durable Memory Storage), Phase 6C (Selective Memory Retrieval Initial Slice), Phase 6D (Checkpoint Artifact Storage Initial Slice), Phase 6E (Checkpoint Resume Initial Slice), Phase 6F (Token Exhaustion Continuation Initial Slice), Phase 6G (Automatic Continuation Chaining Initial Slice), and Phase 6H (Bounded Continuation Prompt Construction Initial Slice) are complete; the historical sub-phase record is preserved in .agent-loop/phase-plan.md. Phase 6I (Phase-Boundary Memory Distillation Initial Slice) is the current active sub-phase. All three Phase 5A approval modes (review, strict, autonomous) have shipped runtime behavior, and Phase 6I is now focused on distilling durable summary, decision, and failure knowledge from canonical phase-boundary artifacts plus bounded review/evidence context into append-mostly memory entries while still preserving the shipped Phase 5 approval-mode and strict-gate routing semantics; review remains the default-on-init/activation mode.
The operator flow across Phase 4B + Phase 4C is:
- Run
python scripts/agent_loop.py planto generate.agent-loop/proposed-phase.md. The planner enforces every Phase 4A refusal condition (unresolvedNEEDS_FIXES,FAILED_REQUIRES_HUMAN, anyhalted_*status, orchestrator-in-flight statuses,cycle_count >= max_cyclesonNEEDS_FIXES, stale evidence, unreadable evidence headers, prior approved proposal carryingAPPROVED_FOR_ACTIVATION, malformedloop-state.json) and the bounded-scope rules (max 10 files, max 1 contract revision, testable Definition-of-done bullet, no vague Objective language, cycle-size estimate <= 3 without justification, noactive-in-flight/pendingdependency, no label collision against historical sub-phases, noAPPROVED_FOR_ACTIVATIONtoken authored by the planner itself,## Exclusionsenumerating later 4x / 5+ sub-phases). The planner writes only.agent-loop/proposed-phase.mdand anote:-style line in.agent-loop/planner.log. - A human reviews the proposal and, if accepted, appends a
## Approvalsection to.agent-loop/proposed-phase.md. The approval section must contain the literalAPPROVED_FOR_ACTIVATIONtoken on its own line within the section AND must reference the proposal's## Labeltext. Token forgery (extra words on the line, alternate capitalization, surrounding characters) and stale-label approvals are refused at activation time. - Run
python scripts/agent_loop.py activateto consume the approved proposal. The activator parses the proposal, verifies the approval requirements exactly, refuses cleanly on every failure mode (missing## Approvalsection, malformed token, label mismatch, missing/unreadable proposal, missing/malformedloop-state.json, empty required-proposal-section bodies), and on success performs the activation write set plus the Phase 5F phase-start prompt bootstrap in one fail-closed path: rewritingTASK.md's## Active Phase/## Active Sub-Phase/## Phase Status/## Active Task/## Phase Outcome Required Now/## Next-Phase Gate/## Out Of Scope For Current Phase(preserving## Human Objectiveand## Project Intentverbatim); rewriting.agent-loop/current-task.mdand.agent-loop/current-phase.md; updating.agent-loop/phase-plan.md's## Active Phaseline, closing the previously-active sub-phase's### Statusopening line as a transition note, and APPENDING a new sub-phase section that mirrors the activated proposal; resetting.agent-loop/loop-state.jsontostatus = awaiting_claude_implementation,cycle_count = 0,last_verdict = null,last_verdict_phase = nullwithphase/sub_phase/taskset from the approved proposal andmax_cycles/contract_version/claude_version/codex_version/orchestrator_versionpreserved per the Phase 3A write-ownership rules; writing.agent-loop/claude-prompt.mdinside the same atomic-or-rollback activation transaction; appending anote:-style approval-source line (file path, mtime, literal approval line) to.agent-loop/planner.log; and appending aprompt bootstrap:audit note to.agent-loop/orchestrator.log. The activator exits 0 on success and 2 on any refusal; refusals never partially write any activation file. - Phase 4D integration (shipped): after the orchestrator persists a terminal
APPROVED_FOR_HUMAN_REVIEWverdict in_handle_verdict_loop, it invokes the standalone planner exactly once to refresh.agent-loop/proposed-phase.md, then logs a singlenote:-style line to.agent-loop/orchestrator.logrecording the planner's exit code. The hook is fully contained: a planner refusal (exit 2) is logged but does not convert the already-approved cycle into a halt, and any unexpected exception from planner code is caught and logged as anote:line rather than allowed to crash or halt the cycle. The orchestrator still returns 0 after the terminal approval in all of those cases. The hook never auto-activates a proposal and never widens the planner's write boundary (only.agent-loop/proposed-phase.mdand.agent-loop/planner.logmay be written by the planner call); approval and activation remain the separate, human-controlledactivatestep described above.
Phase 4E adds a planner-adapter seam. Both the plan path (step 1) and the post-approval planner refresh (step 4) now dispatch planner execution through make_planner_adapter().run(...) instead of calling the planner in-process directly. The default adapter (LocalPlannerAdapter) runs the same in-process planner, so behavior, refusal handling, the exception-containment guarantees on the post-approval path, and the planner's write boundary (.agent-loop/proposed-phase.md and .agent-loop/planner.log only) are all unchanged; the seam exists so a later slice can supply an alternate planner adapter without touching the call sites. The adapter is purely a dispatch boundary: it never widens the planner write boundary and never activates a proposal. Activation stays the separate, human-controlled activate step - planning (proposal generation and refresh) and activation remain distinct.
Phase 5B (Review Mode Initial Slice, shipped) makes review the explicit default approval mode and adds the first machine-readable Claude completion handoff artifact. New / freshly activated Phase 5+ runtime state in .agent-loop/loop-state.json carries approval_mode = "review" and awaiting_human_for = null by default (a pre-existing non-review approval_mode is preserved across activation; awaiting_human_for is always reset by activation). During a normal cycle the orchestrator backfills the same defaults on any loaded state that pre-dates Phase 5B, and on the implemented review path it sets awaiting_human_for = "phase_complete_awaiting_human_approval" on APPROVED_FOR_HUMAN_REVIEW and leaves it null everywhere else. After Claude returns a fresh claude-summary.md for either an implementation or fix cycle and evidence succeeds, the orchestrator writes .agent-loop/claude-done.json (signal_version, phase, sub_phase, task, cycle_count, mode of "implementation" or "fix", source_prompt_path, and status = "ready_for_codex_review") as a routing/timing signal only; it never substitutes for claude-summary.md, the git diff, or validation evidence in review. Each new prompt or fix-prompt issuance clears any prior claude-done.json so a stale completion signal cannot drive the wrong review cycle. The shipped review-mode baseline is preserved unchanged by Phase 5C.
Phase 5C (Strict Mode Pauses, shipped) implements the three strict-mode human checkpoints defined in the Phase 5A contract. When approval_mode = "strict", the orchestrator pauses at: (1) before a new implementation prompt dispatches to Claude (gate name pre_claude_prompt, halt status halted_awaiting_human_pre_claude_prompt); (2) before a new fix prompt dispatches to Claude (pre_fix_prompt, halted_awaiting_human_pre_fix_prompt); (3) after Claude completion and evidence validation but before Codex review begins (pre_codex_review, halted_awaiting_human_pre_codex_review_normal for the implementation cycle and halted_awaiting_human_pre_codex_review_fix for the fix cycle - two halt-status flavors so resume can route to the right continuation). At each gate the orchestrator persists awaiting_human_for = <gate name> plus the matching halt status in a single atomic write, logs a note: line to .agent-loop/orchestrator.log, and exits cleanly with code 2. After the human approves the paused step they run python scripts/agent_loop.py resume, which refuses unless status is one of the four strict-gate halts, then clears awaiting_human_for, restores a ready-to-continue status, and dispatches to the continuation matched by the persisted gate halt-status so no earlier work is re-done and the next gate (if any) still fires.
Phase 5D (Autonomous Mode Initial Slice, shipped) implements the first narrow autonomous runtime continuation path. When approval_mode = "autonomous", the orchestrator bypasses each of the four Phase 5C strict-mode human gates (pre_claude_prompt, pre_codex_review for the implementation cycle, pre_fix_prompt, pre_codex_review for the fix cycle) and continues directly through the existing implementation step, the existing Claude-completion-to-Codex-review handoff, and bounded NEEDS_FIXES fix cycles within the existing cycle_count / max_cycles threshold. Each gate bypass writes a single autonomous mode: bypassing <gate> gate at <where> note to .agent-loop/orchestrator.log so the mode is auditable from repo artifacts and not hidden in transient control flow. Every existing hard stop is preserved: FAILED_REQUIRES_HUMAN still halts immediately, malformed evidence or summaries still fail closed, the cycle_count >= max_cycles threshold on NEEDS_FIXES still halts, and the APPROVED_FOR_HUMAN_REVIEW terminal still persists status = phase_complete_awaiting_human_approval and awaiting_human_for = phase_complete_awaiting_human_approval because the Phase 5A contract requires human approval before phase progression. The shipped review (Phase 5B) and strict (Phase 5C) behavior is unchanged.
Phase 5E (Post-Review Artifact Reconciliation, shipped) makes the post-review follow-up step deterministic and ownership-aware. Every review issue is classified Codex-owned vs Claude-owned: an explicit Owner: field is honored if present, otherwise inference is based on the issue's File(s) partition. Inference returns Codex when every listed file is in CODEX_OWNED_REVIEW_PATHS, Claude when every listed file is outside that set, and refuses at parse time (halted_review_parse_failed) when the file list mixes Codex-owned planning paths with Claude-owned implementation paths (the contract's "refuse when ownership is ambiguous" rule). Each supported Codex auto-fix action declares a per-action allow-list of paths it may touch (CODEX_ACTION_ALLOWED_FILES); a Codex-owned issue whose File(s) list extends outside its action's allow-list is refused at reconciliation time (halted_input_missing) before any side-effect, which is the contract guarantee that a Codex auto-fix cannot overwrite Claude-owned implementation work. Reconciliation writes an up-front review reconciliation: codex_owned_issues=N (actions=[...]) claude_owned_issues=N summary to .agent-loop/orchestrator.log, keeps the per-action and fix-prompt-synchronization notes from earlier phases, and now reloads loop-state from disk on the reconciliation halt path so a successful Codex auto-fix (e.g. sync_phase5_runtime_defaults) persists across the subsequent halt instead of being clobbered by the pre-reconciliation snapshot. The shipped review (Phase 5B), strict (Phase 5C), and autonomous (Phase 5D) runtime behavior is unchanged; Claude-owned findings still drive .agent-loop/fix-prompt.md regeneration in the required handoff format.
Phase 6G (Automatic Continuation Chaining Initial Slice, shipped) builds on the shipped 6D / 6E / 6F primitives by adding bounded automatic continuation chaining over the existing single-hop token-exhaustion resume. The operator runtime entry is the new auto-continue subcommand (python scripts/agent_loop.py auto-continue): while .agent-loop/loop-state.json is at halted_awaiting_token_exhaustion_continuation, the chain repeatedly applies the shipped Phase 6F run_token_exhaustion_resume hop until one of these stop conditions: (a) a hop's return code is non-zero (a refusal - budget exhausted, malformed checkpoint, unsupported saved stage, cycle-identity mismatch - or a non-token halt inside the dispatched continuation), in which case the chain propagates the rc unchanged; (b) the cycle has cleared the token-exhaustion halt after a successful hop (no fresh exhaustion event was recorded during the dispatched continuation), in which case the chain returns 0; or (c) AUTO_CONTINUE_MAX_HOPS = 4 hops have run, in which case the chain refuses fail-closed as a defense-in-depth bound independent of the per-checkpoint continuation_budget. Each chain hop logs an auto-continue chain hop N begin audit line so the chain is reconstructable from .agent-loop/orchestrator.log after the fact. After every successful hop the chain re-runs the same validate_loop_state and check_contract_version structural / contract checks the chain entry used BEFORE branching on the persisted halt status, so a dispatched continuation that left loadable-but-invalid loop-state on disk (missing required field, unsupported contract_version, etc.) is refused fail-closed via _halt rather than logged as a chain completion or silently advanced into another hop. The initial "status is not the token-exhaustion halt" check uses the recovery-preserving refusal pattern (NOT _halt), so running auto-continue against a strict-gate halt by mistake does not clobber the strict-gate recovery point. The chain is OPT-IN: the existing resume subcommand still dispatches the single-hop resume on a HALTED_TOKEN_EXHAUSTION halt; only the dedicated auto-continue subcommand enters the chain. Phase-boundary memory distillation, repeated-failure memory synthesis, and broader optional-context file loading remain deferred. Every shipped Phase 5 behavior (review, strict, autonomous, post-review reconciliation, and the phase-start prompt baseline) remains unchanged.
Phase 6H (Bounded Continuation Prompt Construction Initial Slice, shipped) builds on the shipped 6B (storage), 6C (advisory-only retrieval), 6D (checkpoint storage), 6E (checkpoint resume), 6F (token-exhaustion continuation), and 6G (auto-continuation chaining) primitives. The new build_continuation_prompt_context(repo_root, *, memory_entry_limit=None, evidence_byte_limit=None, log_path=None) -> dict library function assembles a structured continuation-context payload from canonical loop-state + the active Phase 6F/6G token-exhaustion checkpoint + bounded evidence excerpts + advisory durable-memory entries. The dict carries a top-level context_signal_version = "phase-6h-v1", a canonical_state subset of loop-state (phase / sub_phase / task / cycle_count / approval_mode / halt_status / awaiting_human_for), a checkpoint subset of the active checkpoint (suspension_reason, active_prompt_path, continuation_budget, pre_suspension_status, pre_suspension_awaiting_human_for, source_path, source_artifact_path, created_at), an evidence map of each EVIDENCE_FILES rel path -> bounded excerpt metadata ({absent: True} for a missing file, otherwise the full readable-file block {absent: False, byte_size_on_disk, excerpt, excerpt_byte_size, truncated}; an evidence file that exists but cannot be read refuses fail-closed rather than emitting an undocumented read_error branch), a memory_advisory list of Phase 6C-retrieved entries (each carrying advisory_only = True; the checkpoint memory category is intentionally excluded because the active checkpoint is already on the dedicated checkpoint key), memory_limit_applied / memory_truncated_at_limit flags, evidence_byte_limit_applied, and an explicit canonical_precedence_note reminder that canonical artifacts win over advisory memory. The operator runtime entry is the new build-continuation-context subcommand which persists the JSON payload to .agent-loop/continuation-context.json (override with --output) so the construction is auditable from on-disk artifacts; it accepts --memory-entry-limit (default CONTINUATION_CONTEXT_DEFAULT_MEMORY_LIMIT = 8, capped at MEMORY_RETRIEVAL_MAX_LIMIT = 32) and --evidence-byte-limit (default CONTINUATION_CONTEXT_DEFAULT_EVIDENCE_BYTE_LIMIT = 4096 per file, capped at CONTINUATION_CONTEXT_MAX_EVIDENCE_BYTE_LIMIT = 65536). Refusal modes (all fail-closed): missing / malformed loop-state.json, unsupported contract_version, halt status outside the eligible set (only HALTED_TOKEN_EXHAUSTION in this initial slice; strict-gate halts continue using their existing resume path), no active checkpoint on disk, cycle-identity mismatch between checkpoint and loop-state, suspension_reason other than token_exhaustion, out-of-bound memory or evidence limits (zero, negative, non-int, bool, above the cap), and an evidence file that exists on disk but cannot be read. The library function never writes to canonical artifacts and is byte-equivalent on loop-state and the checkpoint across a build call. Prompt string serialization, phase-boundary memory distillation, repeated-failure synthesis, and broader optional context-file loading beyond the existing EVIDENCE_FILES set remain deferred. Every shipped Phase 5 behavior remains unchanged.
Phase 6I (Phase-Boundary Memory Distillation Initial Slice, shipped) builds on the shipped 6B (storage), 6C (retrieval), 6D (checkpoint storage), 6E (resume), 6F (token-exhaustion continuation), 6G (auto-continue), and 6H (continuation context) primitives. The new distill_phase_boundary_memory(repo_root, *, excerpt_byte_limit=None, log_path=None) -> list[Path] library function writes append-mostly durable memory entries in three of the five Phase 6A categories - summary, decision, and conditionally failure - at a successfully APPROVED phase boundary, sourced from canonical loop-state plus bounded excerpts of the canonical source artifacts .agent-loop/claude-summary.md and .agent-loop/codex-review.md. Each entry body carries an explicit distillation_signal_version = "phase-6i-v1" marker plus a source_artifacts list pointing at the canonical sources so a later retrieval can trace provenance. The summary and decision entries always land; the failure entry lands only when cycle_count > 1, codifying "phase required N-1 fix cycle(s) before reaching APPROVED" without parsing internal markdown. The operator runtime entry is the new distill-phase-boundary-memory subcommand which accepts --excerpt-byte-limit (default DISTILLATION_DEFAULT_EXCERPT_BYTE_LIMIT = 4096 per source file, capped at DISTILLATION_MAX_EXCERPT_BYTE_LIMIT = 65536) and prints the list of new memory-entry paths plus a phase-boundary distillation: audit note. Refusal modes (all fail-closed): missing / malformed loop-state.json, unsupported contract_version, status not phase_complete_awaiting_human_approval, last_verdict not APPROVED_FOR_HUMAN_REVIEW, missing or malformed claude-summary.md (halted_summary_malformed from validate_claude_summary), missing or malformed codex-review.md (halted_review_malformed / halted_review_parse_failed from validate_codex_review_and_parse_verdict), on-disk codex-review verdict disagreeing with loop-state last_verdict, an unreadable source artifact (raises OSError on read_bytes), an already-distilled-marker summary entry on disk for this exact (phase, sub_phase, cycle_count) identity (idempotency check), a summary entry whose envelope is unreadable / not JSON / not a dict (identity-unknown branch of the idempotency probe), a matching-identity summary entry whose body is unreadable / non-string / non-JSON / not a dict (matching-identity branch of the idempotency probe), and out-of-bound excerpt_byte_limit. The library function never mutates loop-state.json or any canonical source artifact; only .agent-loop/memory/<category>/ is written. A re-run is refused fail-closed rather than silently producing duplicate entries. The multi-entry write is atomic: a failure during the decision or failure write rolls back any entries already written in that call before the exception propagates, so a failed distillation never leaves a partial set on disk and never blocks a clean retry. Broader optional context-file loading, repeated-failure synthesis beyond the narrow phase-boundary helper, and orchestrator-side automatic invocation from the verdict-handling path remain deferred. Every shipped Phase 5 behavior remains unchanged.
Phase 6L (Repeated-Failure Memory Synthesis Initial Slice, shipped) builds on the shipped 6B / 6C / 6D / 6E / 6F / 6G / 6H / 6I / 6J / 6K primitives by distilling recurring failure patterns into a NEW durable advisory failure memory entry. The new synthesize_repeated_failures(repo_root, *, min_entries=None, max_source_entries=None, log_path=None) -> Path library function reads ONLY the existing failure-category memory entries that match the active loop-state (phase, sub_phase) (bounded, on-disk, structurally validated by the shipped Phase 6B read_memory_entry), skips any entry already carrying the 6L body marker so the synthesis layer stays flat (no synthesis-of-syntheses), and writes a new failure memory entry through the shipped Phase 6B write_memory_entry plumbing carrying a synthesis_signal_version = "phase-6l-v1" body marker plus the ordered list of source memory entry paths so a later retrieval can trace provenance. The body also records source_count, source_cycle_counts, a per-source bounded excerpt list (source_path / cycle_count / created_at / knowledge_type / failure), min_entries_applied, max_source_entries_applied, synthesized_at, the literal REPEATED_FAILURE_CANONICAL_PRECEDENCE_NOTE, and the canonical task/phase/sub_phase/cycle_count/approval_mode passed through from loop-state. The operator runtime entry is the new synthesize-repeated-failures subcommand which accepts --min-entries (default REPEATED_FAILURE_DEFAULT_MIN_ENTRIES = 2, must be >= 2 and capped at REPEATED_FAILURE_MAX_MIN_ENTRIES = 32) and --max-source-entries (default REPEATED_FAILURE_DEFAULT_MAX_SOURCE_ENTRIES = 8, must be >= 2 and capped at REPEATED_FAILURE_MAX_MAX_SOURCE_ENTRIES = 32); when more than the cap match, the newest entries by (cycle_count, created_at) are kept. Refusal modes (all fail-closed): missing / malformed loop-state.json; unsupported contract_version (halted_contract_version_mismatch); fewer than min_entries matching non-synthesis source entries on disk for the active (phase, sub_phase); an existing 6L synthesis entry already on disk for the same (phase, sub_phase, source-set) identity; out-of-bound min_entries or max_source_entries (zero, negative, below 2, non-int, bool, above the cap); max_source_entries < min_entries (contradictory); a matching-identity probe envelope whose body is 6L-marked but has a non-list source_memory_entries value (matching-identity malformed branch never silently skipped). The library function never reads arbitrary repo files, raw logs, transcripts, or anything outside .agent-loop/memory/failure/; never mutates loop-state.json; never mutates any source memory entry; and writes only to .agent-loop/memory/failure/ through the Phase 6B append-mostly guarantee. A Phase 6I distillation failure entry (which carries the 6I distillation_signal_version marker but NOT the 6L marker) IS a valid source for the 6L synthesis. Arbitrary repo-file ingestion, raw-transcript-as-memory, framework-backed runtime paths, and orchestrator-side automatic invocation from the verdict-handling / continuation / prompt-bootstrap paths remain deferred. Every shipped Phase 5 behavior remains unchanged.
Phase 6M (Runtime Adapter Contract For Framework Evaluation, shipped) defined the adapter boundary any future framework-backed runtime must satisfy before it can be evaluated against the shipped local orchestrator. That contract pins the canonical source-of-truth artifact set, allowed reads through the shipped validators only, allowed writes through the shipped writer surfaces only, forbidden-write boundaries, Codex/Claude/human ownership preservation, approval-mode and halt/refusal vocabulary preservation, checkpoint/continuation rules, durable-memory boundaries, audit expectations, default-runtime/evaluation constraints, and the load-bearing rule that canonical repo artifacts always win over framework-managed state.
Phase 6N (Experimental LangGraph Runtime Mirror, shipped) adds a narrow opt-in runtime-adapter seam that exercises the Phase 6M contract in code while preserving the existing local orchestrator at scripts/agent_loop.py as the default runtime. The seam consists of (1) the constants RUNTIME_ADAPTER_DEFAULT = "local", RUNTIME_ADAPTER_LANGGRAPH = "langgraph", RUNTIME_ADAPTERS_SUPPORTED = frozenset({"local", "langgraph"}), RUNTIME_ADAPTER_ENV_VAR = "AGENT_LOOP_RUNTIME", RUNTIME_ADAPTER_AUDIT_NOTE_PREFIX = "runtime adapter:", LANGGRAPH_RUNTIME_ID = "langgraph_experimental", and LANGGRAPH_NODE_NAMES = ("load_state", "validate_state", "consult_memory", "consult_checkpoint", "evaluate"); (2) resolve_runtime_adapter_id(cli_value, env_value) which returns the default local when both inputs are unset / empty, lets CLI override env, and refuses fail-closed via HaltError("halted_input_missing", ...) on any id outside the supported set; (3) LocalRuntimeAdapter (the default sentinel - the shipped in-process flow IS the local runtime; selecting local and calling evaluate(...) returns {"runtime_id": "local", "outcome": "local_default_unchanged"} and emits one runtime adapter: local local_default_sentinel audit note when log_path is supplied, never reading or mutating any canonical artifact); (4) LangGraphExperimentalRuntimeAdapter - the opt-in mirror, a pure-stdlib structural emulation of LangGraph's StateGraph pattern that walks LANGGRAPH_NODE_NAMES in fixed order, re-loads loop-state from disk on every node entry (no caching across hops per the 6M framework-state subordination rule), inspects canonical state through the shipped load_loop_state / validate_loop_state / check_contract_version / list_memory_entries / _load_active_checkpoint validators, emits a runtime adapter: langgraph_experimental ... audit note per node plus begin / complete book-end notes, never writes to canonical artifacts, and re-raises every shipped-validator HaltError verbatim (no new halt status); (5) make_runtime_adapter(runtime_id) factory that returns the matching adapter or refuses fail-closed; (6) the runtime-adapter-eval CLI subcommand with --runtime flag that resolves the runtime id, instantiates the matching adapter, calls evaluate(...), routes refusals through _halt (rc=2), and on success prints a summary plus a pointer to the audit log; (7) the persisted default-off runtime-selection artifact at .agent-loop/runtime-config.json (signal_version phase-6n-v1; absence = default off; written through write_runtime_config(repo_root, selected_runtime) and cleared through clear_runtime_config(repo_root); the structural reader read_runtime_config(repo_root) returns the selected id on success or refuses fail-closed via HaltError("halted_input_missing", ...) on every malformed shape (non-file, unreadable, non-JSON, top-level not dict, missing required key, unrecognized signal_version, selected_runtime outside the supported set)); (8) the set-runtime-config CLI subcommand with a mutually-exclusive --runtime <id> / --clear flag pair (operators MAY pin a long-running selection without re-typing the CLI flag on each invocation; clearing is idempotent rc=0; both paths emit runtime adapter: audit notes); (9) the new _resolve_runtime_with_persisted(repo_root, cli_value, env_value) precedence resolver that chains CLI > env > persisted config > default local; (10) wiring through _apply_runtime_selection(repo_root, args, *, hop_kind) in the actual operator entry points cmd_run / cmd_resume / cmd_auto_continue plus a new --runtime flag on each, so the alternate runtime is genuinely opt-in and runtime-backed rather than evaluation-only - when local (or unset) is resolved the helper returns None immediately and the shipped in-process flow runs byte-equivalent to the pre-6N path; when langgraph is resolved the helper instantiates the mirror, emits a runtime adapter: langgraph_experimental dispatch hop_kind=<run|resume|auto-continue> audit note, runs the mirror's evaluate(...) pre-pass (which inspects canonical state, refuses fail-closed on contradictions, and emits the per-node audit notes), then returns None so the cycle work still runs through the shipped writers (canonical-artifact precedence preserved). Default-runtime preservation: when --runtime is absent, AGENT_LOOP_RUNTIME is unset, AND no persisted runtime-config exists, the default local runtime is selected and no LangGraph code runs; the shipped local orchestrator's in-process flow is unaffected by any of the wired entry points. Refusal vocabulary: every refusal goes through HaltError with the existing halt-status vocabulary (halted_input_missing, halted_contract_version_mismatch) and is routed through _halt; no new halt status is introduced. The mirror is a pure-stdlib structural emulation; the real langgraph package is intentionally NOT a runtime dependency in this slice, so the new code path is stdlib-only and adds no third-party requirement. A future slice can swap the implementation behind the same adapter interface to wire the real langgraph package without changing the contract surface. LangChain support-layer work, CrewAI evaluation, broader multi-framework orchestration, driving an actual Claude/Codex cycle THROUGH the mirror (the mirror currently runs as a pre-pass and then delegates to the shipped writers), and any promotion of the alternate runtime to default remain deferred.
Focused tests live in:
tests/test_planner.pycovering the Phase 4A refusal paths, bounded-scope validation, and proposal-generation success pathtests/test_planner_activation.pycovering the activation success path, approval-signal refusals, required-input refusals, and activation rollback behaviortests/test_planner_integration.pycovering the Phase 4D post-approval hook: a successful planner invocation after terminal approval, a planner-refusal path that still leaves the orchestrator returning 0, an unexpected-planner-exception path that is logged and still leaves the orchestrator returning 0, and a proof that the integration path performs no activation-owned writestests/test_planner_adapter.pycovering the Phase 4E adapter seam: the default factory returns the in-processLocalPlannerAdapter, the adapter delegates torun_plannerand preserves the success behavior, theplanpath and the post-approval refresh both dispatch through the seam, the post-approval path still contains an adapter exception, and the adapterizedplanpath performs no activation-owned writes and does not touchloop-state.jsontests/test_planner_adapter_selection.pycovering the Phase 4F adapter-selection behavior: local fallback selection, alternate adapter selection, planner-boundary enforcement with rollback on out-of-bound writes, and the continued separation between planning and activationtests/test_runtime_adapter.pycovering the Phase 6N experimental LangGraph runtime mirror layer: runtime-selection coverage provesresolve_runtime_adapter_idreturns the defaultlocalwhen both inputs are None or empty string, lets CLI override env, treats empty CLI as 'unset' and falls through to env, refuses fail-closed viaHaltError("halted_input_missing", ...)on any unsupported runtime id from either CLI or env (e.g.crewai,openai_swarm), and accepts explicitlocalselection; factory coverage provesmake_runtime_adapter("local")returns aLocalRuntimeAdapter,make_runtime_adapter("langgraph")returns aLangGraphExperimentalRuntimeAdapterwithruntime_id = LANGGRAPH_RUNTIME_ID, and refuses on any other id;LocalRuntimeAdaptercoverage proves the sentinel returns the local-default outcome dict, does NOT read loop-state (proven by succeeding when noloop-state.jsonis planted), does NOT mutate canonical state, emits oneruntime adapter: local local_default_sentinelaudit note whenlog_pathis supplied, and writes nothing to the log whenlog_pathis omitted (byte-equivalent);LangGraphExperimentalRuntimeAdaptersuccess-shape coverage proves the returned dict carriesruntime_id,node_names(matchingLANGGRAPH_NODE_NAMES), andnode_results(one entry per node in the fixed order), the per-node results capture the expected canonical-state subset (load_staterecords phase / sub_phase / cycle_count from loop-state,validate_statereportsvalid=True,consult_memoryreportsmemory_entries_seen=0when no memory is planted,consult_checkpointreportsactive_checkpoint_present=Falsewhen no checkpoint is planted,evaluaterecords approval_mode / awaiting_human_for / last_verdict); audit-note coverage proves the adapter emits anevaluate_beginbook-end note, onenode=<name>note per node, and anevaluate_completebook-end note, and that every emitted line carries theruntime adapter:prefix and thelanggraph_experimentalruntime id; whenlog_pathis omitted the orchestrator log is byte-equivalent across the call; refusal coverage proves the adapter refuses fail-closed on a missingloop-state.json(the shippedload_loop_stateHaltError("halted_input_missing", ...)is re-raised verbatim), on an unsupportedcontract_version(halted_contract_version_mismatch), and on loop-state missing a required field, AND proves a refusal at the first node does NOT run later nodes (spies onlist_memory_entriesand_load_active_checkpointconfirm they are not called); canonical-precedence coverage proves the adapter does NOT mutateloop-state.json, does NOT mutate any planted source memory entry, writes only to.agent-loop/orchestrator.log(every file outside the log is byte-equivalent across the call, verified by a snapshot-and-compare), and re-loads loop-state on every node entry (a spy onload_loop_stateconfirms a call count equal tolen(LANGGRAPH_NODE_NAMES), proving the 6M framework-state subordination rule that no caching crosses hops); checkpoint compatibility coverage proves theconsult_checkpointnode routes through the shipped_load_active_checkpointselector (spy-verified) and reportsactive_checkpoint_present=Truewhen a checkpoint planted through the shippedwrite_checkpoint_entryexists on disk; CLI coverage proves theruntime-adapter-evalsubcommand routes throughmain(argv)HANDLERS dispatch end-to-end, that the default invocation with no--runtimeand no env var selects the local runtime (the log contains the local-sentinel note and nolanggraph_experimentallines), that--runtime langgraphselects the mirror (the log contains the begin / complete book-ends), that theAGENT_LOOP_RUNTIMEenv var is honored when--runtimeis omitted, that--runtimeoverrides the env var, that an unsupported--runtimevalue returns rc=2 via_halt, and that the langgraph adapter run without loop-state on disk returns rc=2 via_halt; default-runtime-preservation coverage proves the local-runtime selection path never instantiates theLangGraphExperimentalRuntimeAdapter(constructor spy never called), that the default-resolution path does not touch any canonical artifact (proven by succeeding when noloop-state.jsonis planted), and that running the local-sentinel CLI against a plantedloop-state.jsonleaves it byte-equivalent across the calltests/test_repeated_failure_synthesis.pycovering the Phase 6L repeated-failure memory synthesis layer: success-shape coverage proves the call writes a newfailurememory entry under.agent-loop/memory/failure/whose body carries thesynthesis_signal_version = "phase-6l-v1"marker, an orderedsource_memory_entrieslist of repo-relative paths matching the planted failure entries in(cycle_count, created_at)order,source_count,source_cycle_counts, the active loop-statephase/sub_phase/task/cycle_count(so the synthesis is scoped to the current state, not the source entries' state), theknowledge_type = "failure"field, the literalREPEATED_FAILURE_CANONICAL_PRECEDENCE_NOTE, the appliedmin_entries_appliedandmax_source_entries_appliedbounds (proven on a custom override), an audit-log line lands whenlog_pathis supplied (carrying the signal version, phase, sub_phase, cycle_count, source count, and bounds), and the orchestrator log is byte-equivalent across the call whenlog_pathis omitted; bounds validation coverage proves the synthesis refuses fail-closed onmin_entriesbelow 2, aboveREPEATED_FAILURE_MAX_MIN_ENTRIES, bool, and non-int; onmax_source_entriesbelow 2, aboveREPEATED_FAILURE_MAX_MAX_SOURCE_ENTRIES, and bool; on the contradictorymax_source_entries < min_entriescase; and that when more thanmax_source_entriesmatching sources exist, the newest entries by(cycle_count, created_at)are kept (proven by planting 5 entries and capping to 3); source-set selection coverage proves the synthesis refuses when no failure entries are on disk, when only 1 matches under the defaultmin_entries = 2, when only 2 match under a custommin_entries = 3, that entries from a different phase are excluded, that entries from a different sub_phase are excluded, that prior 6L synthesis entries are skipped (the synthesis layer stays flat - proven by planting two regular failure entries + one 6L-marked entry and asserting source_count == 2 with only the two regulars), AND that Phase 6I distillationfailureentries (which carry the 6Idistillation_signal_versionmarker but NOT the 6L marker) ARE included in the source set; loop-state refusal coverage proves the synthesis refuses on a missingloop-state.json, on an unsupportedcontract_version(halted_contract_version_mismatch), and on loop-state missing a required field; idempotency coverage proves a repeat call against the same source-set refuses, a fresh call succeeds after a new non-synthesis failure entry is added (the source-set differs), and the idempotency probe refuses fail-closed when an existing 6L entry has a malformed (non-list)source_memory_entriesfield (the malformed matching-identity branch is never silently skipped); canonical-precedence preservation proves the call does NOT mutateloop-state.json, does NOT mutate any of the source memory entries (byte-equivalent across the call), and writes only under.agent-loop/memory/failure/(every file outside that directory is byte-equivalent across the call); CLI coverage proves thesynthesize-repeated-failuressubcommand routes throughmain(argv)HANDLERS dispatch end-to-end and writes the synthesis entry, honors the--min-entriesoverride (refuses with rc=2 when only 2 sources are on disk but--min-entries 3is requested), honors the--max-source-entriesoverride (the recordedsource_counton the on-disk synthesis entry reflects the operator's cap on a 5-entry candidate set), refuses via_halton insufficient sources with rc=2, and refuses via_haltwith rc=2 on an invalid--min-entriesflagtests/test_optional_context_prompt.pycovering the Phase 6K optional-context prompt-integration layer: success-shape coverage proves the returned dict carries every schema-stable top-level key (integration_signal_version,integrated_at,source_artifact,source_signal_version,source_loaded_at,max_files_applied,max_bytes_per_file_applied,advisory_only,canonical_precedence_note,source_canonical_precedence_note,declared_paths,files,prompt_block), the top-leveladvisory_onlyflag isTrue, the two signal-version fields equal the shipped constants (phase-6k-v1for the integration,phase-6j-v1for the source), both the Phase 6K and the passed-through Phase 6J canonical precedence notes are the literal named constants (consumers can rely on equality),declared_pathsandfilespreserve declaration order, every file entry carriesadvisory_only = Trueas anis-True structural marker, the bound fields are passed through from the source payload (no integration-side widening), the renderedprompt_blockcontains every source path AND every excerpt verbatim, the audit log line lands whenlog_pathis supplied and the log is byte-equivalent across the call whenlog_pathis omitted, and a structurally-valid 6J payload with zero declared files renders an explicit "no optional-context files" block instead of an empty / silent prompt block; contradictory / out-of-bound refusal coverage proves the integration refuses on an unsupported sourcecontext_signal_version(e.g.phase-6z-vX), on acanonical_precedence_notethat drifts from the shipped Phase 6J literal, on afileslist whose length contradictsdeclared_paths, on afileslength abovemax_files_applied, onmax_files_appliedaboveOPTIONAL_CONTEXT_MAX_MAX_FILES, onmax_bytes_per_file_appliedaboveOPTIONAL_CONTEXT_MAX_BYTES_PER_FILE, onmax_files_appliedzero, onmax_bytes_per_file_appliednegative, on a file entry whoseadvisory_onlyis False (the integration refuses any entry that is not explicitly advisory), on anexcerpt_byte_sizeabovemax_bytes_per_file_applied, and on asource_paththat does not match the matchingdeclared_pathsindex; malformed / missing refusal coverage proves the integration refuses on a missing source artifact, a directory at the source path, an unreadable source (mockedOSErroronPath.read_text), a non-JSON source, a top-level non-dict source, a missing required top-level key, a non-listfiles, a non-dict file entry, a file entry missing a required key, a non-listdeclared_paths, and a non-stringdeclared_pathsentry; canonical-precedence preservation proves the library function does NOT create the default output artifact (only the CLI handler does), does NOT mutate the source 6J artifact across the call, does NOT re-read any of the declared source files (the integration succeeds even when the underlying repo files referenced bydeclared_pathsdo not exist on disk - the bounded 6J excerpts are the only data consumed), and does NOT mutate a planted.agent-loop/loop-state.json; bounded-inclusion coverage proves the per-entrytruncatedflag is preserved from the 6J source, the per-entryexcerpt_byte_sizeis preserved, the per-entryexcerptbytes equal the 6J source excerpt verbatim (the integration adds no expansion), and the renderedprompt_blockreports the per-entry truncation flag explicitly; CLI coverage proves theintegrate-optional-contextsubcommand routes throughmain(argv)HANDLERS dispatch end-to-end and writes the JSON payload to.agent-loop/optional-context-prompt.jsonby default, honors a repo-relative--outputoverride, honors a repo-relative--sourceoverride (the default source path remains absent), refuses fail-closed via_halton an absolute--outputpath (rc=2, no artifact written), refuses on a--outputpath that resolves outside the repo root via.., refuses on an absolute--sourcepath, refuses on a--sourcepath that resolves outside the repo root via.., refuses on a missing source artifact via_haltleaving no output artifact behind, overwrites an existing output artifact rather than appending (it is an audit artifact regenerable from the 6J payload), and refuses fail-closed via_halton a contradictory source payloadtests/test_optional_context.pycovering the Phase 6J declared optional-context file loading layer: success-shape coverage proves the returned dict carries every schema-stable top-level key (context_signal_version,loaded_at,max_files_applied,max_bytes_per_file_applied,declared_paths,files,canonical_precedence_note), the order of declared paths is preserved in bothdeclared_pathsandfiles, thecanonical_precedence_noteis the literal named constant (consumers can rely on equality), and the default limits land on the payload when the caller does not override them; bounded-excerpt coverage proves a file larger than the per-file byte cap is included withtruncated: Trueand anexcerptexactly the byte-limit length, an under-budget file is included verbatim withtruncated: False,len(declared_paths) > max_filesrefuses, and each of the eight limit validation cases (max_fileszero / above-cap / bool / and the matching three formax_bytes_per_file) refuses fail-closed; path-validation coverage proves the library refuses on an emptydeclared_pathslist, a non-listdeclared_paths, a non-string path entry, an empty-string path entry, an absolute path, paths containing each of the three glob characters (*,?,[), a path that resolves outsiderepo_rootvia.., a duplicate path in the declaration, a missing file, a directory (not a regular file), and an unreadable file (mockedOSErroronPath.read_bytes); canonical-precedence preservation proves the library function does NOT create the default output artifact (only the CLI handler does), does NOT mutate any source file across a load call, marks every loaded file withadvisory_only = True, and does not append to the orchestrator log whenlog_pathis omitted; CLI coverage proves theload-optional-contextsubcommand routes throughmain(argv)HANDLERS dispatch end-to-end and writes the JSON payload to.agent-loop/optional-context.jsonby default, accepts the--declared-pathflag repeated for multiple files in declaration order, honors the--output/--max-files/--max-bytes-per-fileoverrides, overwrites an existing artifact rather than appending (it is an audit artifact regenerable from the declaration), is rejected by argparse withSystemExit(2)when the required--declared-pathflag is absent, and refuses via_halton a missing declared path leaving no output artifact behindtests/test_phase_boundary_distillation.pycovering the Phase 6I phase-boundary memory distillation layer: success-shape coverage proves a first-cycle phase boundary (cycle_count == 1) writes exactly two entries (summary + decision) and no failure directory is created, a multi-cycle phase boundary (cycle_count > 1) writes three entries (summary + decision + failure), every entry body carries thedistillation_signal_version = "phase-6i-v1"marker, every entry body records the samesource_artifactslist pointing at the canonical sources and the sameclaude_summary_excerpt/codex_review_excerptbounded blocks, the three entries carry the matchingknowledge_typestrings (summary/decision/failure), and thephase-boundary distillation:audit note records the signal version, phase, sub_phase, cycle_count, excerpt byte limit, and entries-written count; bounded-excerpt coverage proves a source file larger than the per-file byte cap is included withtruncated: Trueand anexcerpt_byte_sizeexactly the byte-limit, an under-budget source is included without truncation, anexcerpt_byte_limitof zero / negative / aboveDISTILLATION_MAX_EXCERPT_BYTE_LIMIT/ bool refuses fail-closed; refusal coverage proves the library refuses when status is notphase_complete_awaiting_human_approval, whenlast_verdictis notAPPROVED_FOR_HUMAN_REVIEW, whenloop-state.jsonis missing, on unsupportedcontract_version(halted_contract_version_mismatch), when.agent-loop/claude-summary.mdis missing (the existingvalidate_claude_summaryvalidator surfaces it ashalted_summary_malformed), when.agent-loop/codex-review.mdis missing (the existing validator surfaces it ashalted_review_*), when the on-disk codex-review verdict disagrees with loop-statelast_verdict(defense-in-depth refusal whose message contains the word "contradict"), when the claude-summary## Phaseheader references a DIFFERENT phase than loop-state (halted_summary_malformed), when a source artifact is unreadable (the existingOSErrorpath mirrors the Phase 6H fix-slice unreadable-evidence refusal), idempotently when a second call is made against the same(phase, sub_phase, cycle_count)identity, when the idempotency probe encounters a summary entry whose envelope is unreadable / non-JSON / non-dict (identity-unknown branch), and when the probe finds a matching-identity entry whose body is unreadable / non-string / non-JSON / non-dict (matching-identity branch - a malformed entry that could collide with this boundary is never silently skipped); atomic-write coverage proves a failure during thedecisionwrite rolls back the already-writtensummaryentry, a failure during thefailurewrite rolls back BOTH thesummaryand thedecisionentries, a clean retry after rollback succeeds (the rollback removed the marker so the idempotency probe finds no matching entry), and the rollback never touches a pre-existing unrelated memory entry that was on disk before the call; canonical-precedence preservation proves the call does NOT mutateloop-state.json, does NOT mutate the canonical source artifacts, and writes only inside.agent-loop/memory/<category>/(every file outside that directory is byte-equivalent across the call), and an idempotency refusal does NOT add additional memory entries beyond the original write; CLI coverage proves thedistill-phase-boundary-memorysubcommand routes throughmain(argv)HANDLERS dispatch end-to-end, writes the entries on success and lands the audit note, honors the--excerpt-byte-limitoverride (the recordedexcerpt_byte_limit_appliedfield on the on-disk summary entry reflects the operator's choice), refuses via_halton an ineligible status (loop-state.json carrieshalted_input_missing, no memory entries written), and refuses via_halton an invalid limit flagtests/test_continuation_prompt_context.pycovering the Phase 6H bounded continuation prompt construction layer:build_continuation_prompt_context(...)returns a structured dict with the schema-stable top-level keys (context_signal_version,built_at,canonical_state,checkpoint,evidence,evidence_byte_limit_applied,memory_advisory,memory_limit_applied,memory_truncated_at_limit,canonical_precedence_note); thecanonical_statesubset mirrors loop-state'sphase/sub_phase/task/cycle_count/approval_mode/halt_status/awaiting_human_for; thecheckpointsubset preserves the pre-suspension cycle vocabulary (suspension_reason, active_prompt_path, continuation_budget, pre_suspension_status, pre_suspension_awaiting_human_for, source_path under.agent-loop/memory/checkpoint/, source_artifact_path, created_at) so the halt and pre-suspension vocabularies are clearly separated; bounded-evidence coverage proves a file larger than the per-file byte cap is included withtruncated: Trueand anexcerptexactly the byte-limit length, an under-budget file is included verbatim withtruncated: False, a missing evidence file is reported withabsent: Truerather than silently omitted, anevidence_byte_limitof zero / negative / non-int / bool / aboveCONTINUATION_CONTEXT_MAX_EVIDENCE_BYTE_LIMITrefuses fail-closed, an evidence file that exists on disk but raisesOSErroron read refuses viaHaltError("halted_input_missing", ...)(noread_errorschema branch ever appears in a success payload), and the CLI subcommand routes the same unreadable-evidence refusal through_haltso the structural failure vocabulary lands on disk and no output artifact is written; bounded-memory coverage proves every returned advisory entry carries the Phase 6Cadvisory_only = Truestructural marker, that thememory_truncated_at_limitflag flips True when more entries match than the limit allows back (including the load-bearing edge case where the caller's limit equalsMEMORY_RETRIEVAL_MAX_LIMITand additional matches still exist on disk - the truncation flag is computed by directly counting in-scope entries with the same category/phase/sub_phase filters the retrieval primitive uses, not by re-running a capped retrieval) and stays False under the limit (including the boundary case where exactlyMEMORY_RETRIEVAL_MAX_LIMITentries match), that an out-of-boundmemory_entry_limitis delegated to the Phase 6C limit validator and refused, and that an entry for a DIFFERENT phase is excluded from the active phase's advisory list; refusal coverage proves the builder refuses when status is not inCONTINUATION_CONTEXT_ELIGIBLE_HALT_STATUSES(onlyHALTED_TOKEN_EXHAUSTIONin this initial slice), refuses on a strict-gate halt (the strict-gate path has its ownresume), refuses when no active checkpoint exists, refuses on cycle-identity mismatch (delegated to the Phase 6F validator), refuses onsuspension_reasonother thantoken_exhaustion, refuses on unsupportedcontract_version(halted_contract_version_mismatch), and refuses on missingloop-state.json; canonical-precedence preservation - building the context does NOT mutateloop-state.json, does NOT mutate the active checkpoint, does NOT create the output artifact (only the CLI handler does), thecanonical_precedence_noteis the literal named constant (consumers can rely on equality), thecontinuation context built:audit note lands whenlog_pathis supplied, and the log content is byte-equivalent across a build call whenlog_pathis omitted; CLI coverage proves thebuild-continuation-contextsubcommand routes throughmain(argv)HANDLERS dispatch end-to-end and writes the JSON payload to.agent-loop/continuation-context.jsonby default, honors the--output,--memory-entry-limit, and--evidence-byte-limitoverrides, overwrites an existing artifact rather than appending (it is an audit artifact regenerable from canonical state), refuses via_halton an ineligible halt status leaving the structural failure vocabulary on disk and writing no output artifact, and refuses via_halton an invalid limit flag passed through to the library functiontests/test_auto_continuation_chaining.pycovering the Phase 6G automatic continuation chaining layer:run_auto_continue(...)performs up toAUTO_CONTINUE_MAX_HOPS = 4hops of the shipped Phase 6F single-hoprun_token_exhaustion_resume(...)while loop-state re-entersHALTED_TOKEN_EXHAUSTION; a clean single-hop dispatch (the dispatched continuation does not re-record exhaustion) terminates the chain after one hop with the transitionalevidence_captureleft on disk; a multi-hop chain (the dispatched continuation records a fresh token-exhaustion event for the first N hops via the orchestrator's own writer) walks exactly N+1 hops and then terminates cleanly; refusal coverage proves the chain refuses fail-closed on the initial "status is not the token-exhaustion halt" check via the recovery-preserving pattern (NOT_halt) so a planted strict-gate halt is preserved byte-for-byte across the refusal, refuses on exhausted budget (rc=2, halt preserved, continuation never called), refuses on an unsupported saved stage likeclaude_implementing(delegated to the underlying Phase 6F refusal), refuses on a malformed active checkpoint, and propagates a non-token halt from inside the dispatched continuation; theAUTO_CONTINUE_MAX_HOPSdefense-in-depth cap fires when the dispatched continuation records a FRESH exhaustion event on every hop with an increasing budget (so the per-checkpoint budget bound never trips first), refuses with the recovery-preserving pattern, and leaves the saved halt intact; CLI coverage of theauto-continuesubcommand proves theHANDLERSdispatch chain reachesrun_auto_continue(...)end-to-end throughmain(argv)and proves acmd_resumeinvocation on aHALTED_TOKEN_EXHAUSTIONhalt still dispatches the single-hoprun_token_exhaustion_resume(the chain is opt-in via the dedicated subcommand, not an automatic widening ofresume); canonical-precedence preservation - a successful chain does NOT advancecycle_count, does NOT mutatephase/sub_phase/task/approval_mode, and does NOT log any autonomous-mode bypass (the chain does not widen Phase 5 autonomy); a refused initial chain leaves on-disk checkpoint bytes unchanged; post-hop validation coverage - a successful hop whose dispatched continuation overwrites loop-state.json with a JSON object that is loadable but missing required keys is caught byvalidate_loop_stateand refused withhalted_input_missingwritten through_halt, a successful hop whose dispatched continuation leaves an unsupportedcontract_versionis caught bycheck_contract_versionand refused withhalted_contract_version_mismatch, and the structural validation runs BEFORE the post-hop status branch so a malformed state cannot silently advance the chain into another hop or log a chain completiontests/test_token_exhaustion_continuation.pycovering the Phase 6F token-exhaustion continuation layer:record_token_exhaustion(...)writes a token-exhaustion checkpoint capturing the PRE-suspension cycle context (phase / sub_phase / task / cycle_count / approval_mode / status / awaiting_human_for plus the active prompt path and the bounded continuation budget) and transitions loop-state toHALTED_TOKEN_EXHAUSTION+awaiting_human_for = "token_exhaustion_continuation"so the halt is auditable from the canonical state artifacts, refuses when loop-state is already at anyhalted_*status (no clobbering an existing recovery point), when the cycle is terminally complete (phase_complete_awaiting_human_approval), when theactive_prompt_pathis out of vocabulary, and whenloop-state.jsonis missing, accepts both.agent-loop/claude-prompt.mdand.agent-loop/fix-prompt.mdas valid prompts, and emits atoken exhaustion recorded:audit note;_validate_token_exhaustion_checkpoint(...)compares the cycle-identity subset (phase,sub_phase,task,cycle_count,approval_mode) and intentionally OMITSstatus/awaiting_human_forbecause the halt vocabulary on the loop-state side diverges from the pre-suspension vocabulary inside the checkpoint, accepting a matching identity silently and refusing fail-closed for each individual mismatch dimension;run_token_exhaustion_resume(...)consumes the active checkpoint by writing a new superseding checkpoint withcontinuation_budget - 1and restoring loop-state to the pre-suspensionstatus/awaiting_human_for, emits atoken-exhaustion resume consumed:audit note showingbudget N -> N-1, refuses with_haltonly on the "status is not the token-exhaustion halt" case (where no recovery point can be destroyed) and uses the recovery-preserving stderr+log+exit-2 pattern for every other refusal (no checkpoint on disk, malformed checkpoint, suspension_reason mismatch, cycle-identity mismatch, exhausted budget, saved status outsideTOKEN_EXHAUSTION_SUPPORTED_RESUME_STATUSES), proves two consecutive consumptions take a budget of 2 to 0 and a third refuses; end-to-end dispatch coverage proves a successful resume actually drives the interrupted cycle into the matching continuation entry-point (anawaiting_claude_implementationinterruption dispatches_run_normal_cycle_from_incrementand anawaiting_codex_reviewinterruption dispatches_run_normal_cycle_codex_review_stepwith a transitionalevidence_capturewrite mirroring the strict-resume HALTED_PRE_CODEX_REVIEW_NORMAL pattern), proves an unsupported saved status (e.g.claude_implementing) is refused fail-closed BEFORE budget consumption, and propagates the continuation's exit code unchanged through the resume layer; CLI coverage of therecord-token-exhaustionsubcommand proves the orchestrator runtime actually entersHALTED_TOKEN_EXHAUSTIONend-to-end (the HANDLERS dispatch chain), proves the optional--continuation-budgetoverride is honored, proves both.agent-loop/claude-prompt.mdand.agent-loop/fix-prompt.mdare accepted while an unknown--active-prompt-pathis rejected by argparse before the handler runs, proves a pre-existing halt is refused via_halt(no recovery point silently clobbered), and proves the fullrecord-token-exhaustionthenresumesequence reaches the token-exhaustion continuation entry-point end-to-end without advancingcycle_count;cmd_resume(...)routing inspects the persisted halt status BEFORE dispatch soHALTED_TOKEN_EXHAUSTIONroutes torun_token_exhaustion_resume(mocked) and a strict-gate halt or a missing loop-state file routes torun_strict_resumeunchanged (the load-bearing safety property that prevents the strict-resume status check from clobbering the token-exhaustion recovery point); canonical-precedence preservation - a refused token-exhaustion resume does not mutate the on-disk checkpoint bytes, a successful resume does NOT advance cycle_count (no phase progression, no autonomy widening), the active phase / sub_phase / task / approval_mode are preserved across the resume, and a strict-gate halt with a token-exhaustion checkpoint on disk still refuses via the Phase 6E suspension_reason mismatch path without clobbering the strict-gate statetests/test_checkpoint_resume.pycovering the Phase 6E checkpoint-backed resume layer:_load_active_checkpoint(...)returns None when no checkpoint directory exists, returns the single payload when one exists, selects the active checkpoint by filesystem mtime (the most recently WRITTEN file wins, which actually tracks write order rather than filename order - the Phase 6D filename{YYYYMMDDTHHMMSSZ}-{sha256_short(body)[:8]}.jsonhas a second-granularity timestamp and a body-hash tail uncorrelated with write order, so same-second writes could otherwise pick the wrong file by lexical order; lexical filename remains a deterministic secondary tie-breaker only when two files share an identical mtime), reads ONLY the active checkpoint so a malformed historical entry does not block resume when a newer valid checkpoint exists, and still propagates the Phase 6D fail-closedHaltErrorwhen the chosen active checkpoint is itself malformed;_validate_checkpoint_against_loop_state(...)accepts a fully matching checkpoint silently and refuses fail-closed withhalted_input_missingfor every individual mismatch dimension (phase,sub_phase,task,cycle_count,approval_mode,awaiting_human_for, and - when the loop is paused at a strict-gate halt -suspension_reason);run_strict_resume(...)integration coverage proves backward compatibility (no checkpoint on disk still dispatches the existing Phase 5C strict-gate continuation), proves the matching-checkpoint case dispatches and writes acheckpoint validated for resume:audit note, proves the most-recently-written-checkpoint-among-many is the one consulted, proves a malformed older checkpoint alongside a newer valid one still dispatches (only the active entry is read), refuses fail-closed when a stalecycle_count/task/sub_phasecheckpoint exists, refuses fail-closed when the checkpoint'ssuspension_reasoncontradicts the active strict-gate halt, refuses fail-closed when the active on-disk checkpoint is malformed (missing required field, unrecognizedcheckpoint_signal_version) and writes astrict resume refused:audit note; canonical-precedence preservation - every refusal leaves the saved strict-gatestatus/awaiting_human_for/approval_modeintact so a corrected operator state allows a fresh resume to dispatch, never calls any of the four strict-gate dispatch helpers, and a successful resume does not mutate the on-disk checkpoint bytestests/test_checkpoint_storage.pycovering the shipped Phase 6D checkpoint artifact storage layer: a validwrite_checkpoint_entry(...)call creates a file under.agent-loop/memory/checkpoint/, populates every Phase 6A required memory-metadata field plus every Phase 6D required checkpoint-body field (checkpoint_signal_version,task,status,approval_mode,awaiting_human_for,active_prompt_path,suspension_reason,continuation_budget), accepts each of the eight allowedsuspension_reasonvalues (the four base reasonstoken_exhaustion/human_interrupt/process_killed/orchestrator_restartplus the four Phase 5C strict-gate halt statuses), accepts both allowedactive_prompt_pathvalues (claude-prompt.md and fix-prompt.md), accepts acontinuation_budgetof zero, and accepts bothNoneand a non-empty string forawaiting_human_for; malformed-checkpoint write refusal for emptytask/status/approval_mode, wrong-type or empty-stringawaiting_human_for, out-of-vocabularyactive_prompt_pathorsuspension_reason, andcontinuation_budgetthat is bool / non-int / negative; read-side schema validation refuses a non-checkpoint category, a missing or non-JSON or non-dict body, a body missing any required checkpoint field, an unrecognizedcheckpoint_signal_version, an out-of-vocabularyactive_prompt_pathorsuspension_reason, a badcontinuation_budget, and (mirroring the write-side guards so a hand-edited artifact cannot bypass the checkpoint contract on read) empty / non-stringtask/status/approval_modeand anawaiting_human_forthat is the wrong type or an empty string (None remains accepted); write-boundary enforcement - checkpoint entries live only under.agent-loop/memory/checkpoint/, a write does not mutate a planted.agent-loop/loop-state.json, and a forced filename collision is refused rather than overwritten (the Phase 6B append-mostly guarantee is inherited);list_checkpoint_entries(...)returns[]when the checkpoint subdirectory is absent and returns only checkpoint entries when other memory categories are also present; the writer still emits the Phase 6Bmemory write:audit note withcategory='checkpoint'when alog_pathis supplied (and creates no log file when it is omitted)tests/test_memory_retrieval.pycovering the shipped Phase 6C selective durable memory retrieval layer: relevant-entry filtering across phase / sub_phase / category dimensions and their combined intersection (task-level scoping is implicit in the (phase, sub_phase) match per the 6C contract narrowing because the canonical state model assigns one active task per active (phase, sub_phase) pair); bounded result limits including the default limit, custom-limit-below-max, and fail-closed refusals for limits that are zero, negative, non-int, bool, or aboveMEMORY_RETRIEVAL_MAX_LIMIT; malformed-entry refusal that halts the whole retrieval call on malformed JSON, missing required fields, unrecognizedsignal_version, and unknown on-disk category (no silent skipping of bad entries); unknown-category refusal for caller-supplied category filters, both alone and mixed with a valid category; advisory-only marker - every returned payload structurally carriesMEMORY_RETRIEVAL_ADVISORY_FIELD = Trueso a consumer can assert advisory status without relying on docstrings, the marker is present on entries returned for every one of the five Phase 6A categories, and the marker is never written back to disk; canonical-precedence preservation - retrieval never mutates.agent-loop/loop-state.json, never creates any new file on disk, mutating a returned payload does not write through to disk, and empty-memory / no-matching-phase return an empty list rather than halting; newest-first ordering bycreated_at; audit-note signature whenlog_pathis supplied that names phase / sub_phase / categories / limit / matched / returned (and no log file created when it is omitted, and notask=field in the audit signature); and a required non-empty active phase string at the boundarytests/test_memory_storage.pycovering the shipped Phase 6B structured durable memory storage layer: a valid write for each of the five Phase 6A categories (decision,failure,preference,summary,checkpoint) populates every required metadata field (signal_version,category,phase,sub_phase,cycle_count,source_artifact_path,created_at) and writes the entry under.agent-loop/memory/<category>/; missing-metadata refusal for emptyphase/sub_phase/source_artifact_pathand non-intcycle_count; unknown-category refusal at write time and atlist_memory_entriestime so the five-category set cannot be silently extended at runtime; append-mostly behavior - two writes create two distinct files and asupersedesreference is recorded on the new entry without mutating the prior entry's bytes; a file-collision at the deterministic filename target is refused rather than overwritten; write-boundary enforcement - the scope guard refuses any path that resolves outside.agent-loop/memory/while accepting in-scope paths, and a full write+list cycle never mutates any canonical artifact like.agent-loop/loop-state.json; read-side schema validation refuses missing-field, unknown-category, unrecognized-signal_version, empty-or-malformed-JSON, and missing-file entries;list_memory_entriesreturns an empty list when the memory dir is absent and a category-filtered list whencategoryis provided; the writer appends amemory write:audit note to.agent-loop/orchestrator.logwhen alog_pathis suppliedtests/test_review_follow_up.pycovering the Phase 5E post-review reconciliation: path-based inference returns Codex for all-Codex-path issues and Claude for all-non-Codex-path issues; parse-time refusal when the file list mixes Codex-owned planning paths with Claude-owned implementation paths and no explicitOwner:field is provided; an explicitOwner:line overrides path-based inference (including the Claude-overrides-Codex-path direction); supported Codex-owned auto-fixes apply when File(s) is a subset of the action's allow-list and the same action is refused at reconciliation time when File(s) extends outside that allow-list; a reconciliation classification summary lands in.agent-loop/orchestrator.logbefore any side-effect; the per-action note and the fix-prompt synchronization note still land in the success path; and the pre-Phase-5E behavior on the existing mixed-review and codex-only-review tests is preservedtests/test_approval_modes.pycovering the Phase 5B review-mode initial slice, the Phase 5C strict-mode pauses, AND the Phase 5D autonomous-mode initial slice: activation defaultsapproval_modeto"review"and resetsawaiting_human_forto null while preserving a pre-existing non-review mode; the normal-cycle backfill applies the same defaults to pre-Phase-5B state; the verdict handler setsawaiting_human_for = "phase_complete_awaiting_human_approval"onAPPROVED_FOR_HUMAN_REVIEWand clears it onNEEDS_FIXES/FAILED_REQUIRES_HUMAN;.agent-loop/claude-done.jsonwrites carry every required Phase 5A field for both implementation and fix completion and reject an invalid mode without leaving a partial file; a staleclaude-done.jsonis superseded by a new implementation cycle and cleared by a new fix-prompt issuance; the baseline pre-Phase-5B terminal status / verdict writes still hold. Strict-mode coverage proves each of the three gates fires at the right point (no Claude adapter call beforepre_claude_prompt, no Codex adapter call beforepre_codex_reviewin either the normal or fix cycle), the resume subcommand refuses from a non-strict-halt status, resume afterpre_claude_promptdispatches into the cycle_count-increment continuation, resume afterpre_codex_reviewskips straight to Codex review without re-invoking Claude or re-incrementing the counter, resume afterpre_fix_promptruns one fix cycle, andreviewmode never fires any strict gate. Autonomous-mode coverage proves none of the four strict gates fires underautonomous(Claude/Codex adapters are reached without a halt) and each bypass is logged to.agent-loop/orchestrator.log; the autonomous continuation still halts onFAILED_REQUIRES_HUMAN, on thecycle_count >= max_cyclesthreshold forNEEDS_FIXES, on a missing-evidence halt, and on theAPPROVED_FOR_HUMAN_REVIEWphase-complete gate (autonomy never auto-progresses phases); NEEDS_FIXES within threshold runs exactly one fix cycle (one Claude invocation, one Codex review) and terminates correctly on the subsequent APPROVED verdict
Deferred to later phases generally: later Phase 6 implementation slices that build on the active Phase 6N experimental LangGraph runtime mirror (including broader framework evaluation and support-layer work), editor integration (Phase 7), and documentation / project polish (Phase 8). Phase 4D was the first slice that intentionally extended the Phase 3 orchestrator surface with the contained post-approval planner hook; Phases 4E and 4F completed the planner-adapter seam and one alternate adapter path while keeping the planner write boundary and the separate human-controlled approval/activation steps unchanged; Phase 5B shipped the default review runtime path plus the machine-readable completion handoff artifact, Phase 5C shipped the strict-mode pauses plus the resume subcommand, Phase 5D shipped the narrow autonomous continuation path with auditable gate-bypass logging while preserving the existing review and strict behavior, Phase 5E shipped deterministic ownership-aware post-review reconciliation with per-action allow-list enforcement and audit-log classification summaries while preserving every shipped runtime mode, Phase 5F shipped automatic phase-start Claude prompt generation from the canonical phase/task artifacts, Phase 6A documented the durable memory rules later 6x implementation slices must follow, Phase 6B shipped the storage foundation for that memory layer, Phase 6C shipped selective advisory-only retrieval, Phase 6D shipped checkpoint artifact storage, Phase 6E shipped checkpoint-backed resume handling, Phase 6F shipped token-exhaustion continuation handling, Phase 6G shipped automatic continuation chaining, Phase 6H shipped continuation-prompt construction, Phase 6I shipped phase-boundary memory distillation, Phase 6J shipped declared optional-context file loading, Phase 6K shipped the prompt-integration surface that consumes that payload into a deterministic advisory-only prompt block, Phase 6L shipped the repeated-failure memory synthesis surface that distills recurring failure patterns from prior failure-category entries into a new append-mostly advisory failure entry, Phase 6M shipped the runtime adapter contract future framework-backed runtimes must satisfy, and Phase 6N shipped the first opt-in experimental LangGraph runtime mirror under that contract as a pure-stdlib structural emulation that preserves the local runtime as the default and exercises every 6M contract dimension without adding a third-party runtime dependency.