convez.ai
AgenteAutomaçãoAvançado
Chonyoomin

AI Agent Claude-Codex

Chonyoomin/AI-Agent-Claude-Codex

Orquestração local Claude-Codex com fases auditáveis e aprovação humana

Ver no GitHub
InicialPluginScore · de 0 a 100

Agent 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-Codex

1 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

Estrelas
0
Forks
0
Acompanhando
0
Saúde
28%
Último commit
há 1 mês
Versão
—
Issues abertas
0
Contribuidores
1

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.md and active phase state
  • generate a focused Claude implementation prompt
  • let Claude implement the requested phase
  • capture Claude's structured summary
  • capture git diff and git 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.

  1. Human provides the project objective or updates the desired outcome.
  2. Codex updates TASK.md, .agent-loop/current-task.md, and .agent-loop/current-phase.md for the active phase.
  3. Codex writes .agent-loop/claude-prompt.md.
  4. Claude Code implements only the active phase and writes .agent-loop/claude-summary.md.
  5. The orchestrator captures diff, status, and validation logs.
  6. Codex writes .agent-loop/codex-review.md with one verdict:
    • APPROVED_FOR_HUMAN_REVIEW
    • NEEDS_FIXES
    • FAILED_REQUIRES_HUMAN
  7. 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.
  8. Claude applies targeted fixes within the same phase.
  9. The loop repeats until the phase is approved, escalated, or reaches max cycles.
  10. When a phase is approved, the system stops until the human starts the next phase.
  11. The system never commits without separate human approval.

Repository Files

Top-level project files:

  • README.md: public project overview
  • AGENTS.md: operating rules, review standards, and artifact formats
  • CLAUDE.md: Claude Code implementation contract
  • ROADMAP.md: phased delivery plan
  • TASK.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:

  1. Codex updates TASK.md, .agent-loop/current-task.md, and .agent-loop/current-phase.md for the active phase.
  2. Codex writes the implementation prompt to .agent-loop/claude-prompt.md using the required Claude task format.
  3. A human pastes that prompt into Claude Code.
  4. Claude Code implements only the active phase and writes .agent-loop/claude-summary.md using the required Claude implementation summary format.
  5. A human captures evidence into .agent-loop/:
    • git diff > .agent-loop/git-diff.patch
    • git 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).
  6. A human pastes the prompt, summary, diff, and logs into Codex.
  7. Codex writes .agent-loop/codex-review.md with exactly one verdict: APPROVED_FOR_HUMAN_REVIEW, NEEDS_FIXES, or FAILED_REQUIRES_HUMAN.
  8. If the verdict is NEEDS_FIXES, Codex-owned follow-up is applied first where supported, .agent-loop/fix-prompt.md is regenerated from the Claude-owned review issues, and the cycle repeats from step 3 within max_cycles.
  9. 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:

  1. Run python scripts/agent_loop.py plan to generate .agent-loop/proposed-phase.md. The planner enforces every Phase 4A refusal condition (unresolved NEEDS_FIXES, FAILED_REQUIRES_HUMAN, any halted_* status, orchestrator-in-flight statuses, cycle_count >= max_cycles on NEEDS_FIXES, stale evidence, unreadable evidence headers, prior approved proposal carrying APPROVED_FOR_ACTIVATION, malformed loop-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, no active-in-flight / pending dependency, no label collision against historical sub-phases, no APPROVED_FOR_ACTIVATION token authored by the planner itself, ## Exclusions enumerating later 4x / 5+ sub-phases). The planner writes only .agent-loop/proposed-phase.md and a note:-style line in .agent-loop/planner.log.
  2. A human reviews the proposal and, if accepted, appends a ## Approval section to .agent-loop/proposed-phase.md. The approval section must contain the literal APPROVED_FOR_ACTIVATION token on its own line within the section AND must reference the proposal's ## Label text. Token forgery (extra words on the line, alternate capitalization, surrounding characters) and stale-label approvals are refused at activation time.
  3. Run python scripts/agent_loop.py activate to consume the approved proposal. The activator parses the proposal, verifies the approval requirements exactly, refuses cleanly on every failure mode (missing ## Approval section, malformed token, label mismatch, missing/unreadable proposal, missing/malformed loop-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: rewriting TASK.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 Objective and ## Project Intent verbatim); rewriting .agent-loop/current-task.md and .agent-loop/current-phase.md; updating .agent-loop/phase-plan.md's ## Active Phase line, closing the previously-active sub-phase's ### Status opening line as a transition note, and APPENDING a new sub-phase section that mirrors the activated proposal; resetting .agent-loop/loop-state.json to status = awaiting_claude_implementation, cycle_count = 0, last_verdict = null, last_verdict_phase = null with phase / sub_phase / task set from the approved proposal and max_cycles / contract_version / claude_version / codex_version / orchestrator_version preserved per the Phase 3A write-ownership rules; writing .agent-loop/claude-prompt.md inside the same atomic-or-rollback activation transaction; appending a note:-style approval-source line (file path, mtime, literal approval line) to .agent-loop/planner.log; and appending a prompt 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.
  4. Phase 4D integration (shipped): after the orchestrator persists a terminal APPROVED_FOR_HUMAN_REVIEW verdict in _handle_verdict_loop, it invokes the standalone planner exactly once to refresh .agent-loop/proposed-phase.md, then logs a single note:-style line to .agent-loop/orchestrator.log recording 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 a note: 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.md and .agent-loop/planner.log may be written by the planner call); approval and activation remain the separate, human-controlled activate step 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.py covering the Phase 4A refusal paths, bounded-scope validation, and proposal-generation success path
  • tests/test_planner_activation.py covering the activation success path, approval-signal refusals, required-input refusals, and activation rollback behavior
  • tests/test_planner_integration.py covering 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 writes
  • tests/test_planner_adapter.py covering the Phase 4E adapter seam: the default factory returns the in-process LocalPlannerAdapter, the adapter delegates to run_planner and preserves the success behavior, the plan path and the post-approval refresh both dispatch through the seam, the post-approval path still contains an adapter exception, and the adapterized plan path performs no activation-owned writes and does not touch loop-state.json
  • tests/test_planner_adapter_selection.py covering 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 activation
  • tests/test_runtime_adapter.py covering the Phase 6N experimental LangGraph runtime mirror layer: runtime-selection coverage proves resolve_runtime_adapter_id returns the default local when both inputs are None or empty string, lets CLI override env, treats empty CLI as 'unset' and falls through to env, refuses fail-closed via HaltError("halted_input_missing", ...) on any unsupported runtime id from either CLI or env (e.g. crewai, openai_swarm), and accepts explicit local selection; factory coverage proves make_runtime_adapter("local") returns a LocalRuntimeAdapter, make_runtime_adapter("langgraph") returns a LangGraphExperimentalRuntimeAdapter with runtime_id = LANGGRAPH_RUNTIME_ID, and refuses on any other id; LocalRuntimeAdapter coverage proves the sentinel returns the local-default outcome dict, does NOT read loop-state (proven by succeeding when no loop-state.json is planted), does NOT mutate canonical state, emits one runtime adapter: local local_default_sentinel audit note when log_path is supplied, and writes nothing to the log when log_path is omitted (byte-equivalent); LangGraphExperimentalRuntimeAdapter success-shape coverage proves the returned dict carries runtime_id, node_names (matching LANGGRAPH_NODE_NAMES), and node_results (one entry per node in the fixed order), the per-node results capture the expected canonical-state subset (load_state records phase / sub_phase / cycle_count from loop-state, validate_state reports valid=True, consult_memory reports memory_entries_seen=0 when no memory is planted, consult_checkpoint reports active_checkpoint_present=False when no checkpoint is planted, evaluate records approval_mode / awaiting_human_for / last_verdict); audit-note coverage proves the adapter emits an evaluate_begin book-end note, one node=<name> note per node, and an evaluate_complete book-end note, and that every emitted line carries the runtime adapter: prefix and the langgraph_experimental runtime id; when log_path is omitted the orchestrator log is byte-equivalent across the call; refusal coverage proves the adapter refuses fail-closed on a missing loop-state.json (the shipped load_loop_state HaltError("halted_input_missing", ...) is re-raised verbatim), on an unsupported contract_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 on list_memory_entries and _load_active_checkpoint confirm they are not called); canonical-precedence coverage proves the adapter does NOT mutate loop-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 on load_loop_state confirms a call count equal to len(LANGGRAPH_NODE_NAMES), proving the 6M framework-state subordination rule that no caching crosses hops); checkpoint compatibility coverage proves the consult_checkpoint node routes through the shipped _load_active_checkpoint selector (spy-verified) and reports active_checkpoint_present=True when a checkpoint planted through the shipped write_checkpoint_entry exists on disk; CLI coverage proves the runtime-adapter-eval subcommand routes through main(argv) HANDLERS dispatch end-to-end, that the default invocation with no --runtime and no env var selects the local runtime (the log contains the local-sentinel note and no langgraph_experimental lines), that --runtime langgraph selects the mirror (the log contains the begin / complete book-ends), that the AGENT_LOOP_RUNTIME env var is honored when --runtime is omitted, that --runtime overrides the env var, that an unsupported --runtime value 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 the LangGraphExperimentalRuntimeAdapter (constructor spy never called), that the default-resolution path does not touch any canonical artifact (proven by succeeding when no loop-state.json is planted), and that running the local-sentinel CLI against a planted loop-state.json leaves it byte-equivalent across the call
  • tests/test_repeated_failure_synthesis.py covering the Phase 6L repeated-failure memory synthesis layer: success-shape coverage proves the call writes a new failure memory entry under .agent-loop/memory/failure/ whose body carries the synthesis_signal_version = "phase-6l-v1" marker, an ordered source_memory_entries list of repo-relative paths matching the planted failure entries in (cycle_count, created_at) order, source_count, source_cycle_counts, the active loop-state phase / sub_phase / task / cycle_count (so the synthesis is scoped to the current state, not the source entries' state), the knowledge_type = "failure" field, the literal REPEATED_FAILURE_CANONICAL_PRECEDENCE_NOTE, the applied min_entries_applied and max_source_entries_applied bounds (proven on a custom override), an audit-log line lands when log_path is supplied (carrying the signal version, phase, sub_phase, cycle_count, source count, and bounds), and the orchestrator log is byte-equivalent across the call when log_path is omitted; bounds validation coverage proves the synthesis refuses fail-closed on min_entries below 2, above REPEATED_FAILURE_MAX_MIN_ENTRIES, bool, and non-int; on max_source_entries below 2, above REPEATED_FAILURE_MAX_MAX_SOURCE_ENTRIES, and bool; on the contradictory max_source_entries < min_entries case; and that when more than max_source_entries matching 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 default min_entries = 2, when only 2 match under a custom min_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 distillation failure entries (which carry the 6I distillation_signal_version marker but NOT the 6L marker) ARE included in the source set; loop-state refusal coverage proves the synthesis refuses on a missing loop-state.json, on an unsupported contract_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_entries field (the malformed matching-identity branch is never silently skipped); canonical-precedence preservation proves the call does NOT mutate loop-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 the synthesize-repeated-failures subcommand routes through main(argv) HANDLERS dispatch end-to-end and writes the synthesis entry, honors the --min-entries override (refuses with rc=2 when only 2 sources are on disk but --min-entries 3 is requested), honors the --max-source-entries override (the recorded source_count on the on-disk synthesis entry reflects the operator's cap on a 5-entry candidate set), refuses via _halt on insufficient sources with rc=2, and refuses via _halt with rc=2 on an invalid --min-entries flag
  • tests/test_optional_context_prompt.py covering 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-level advisory_only flag is True, the two signal-version fields equal the shipped constants (phase-6k-v1 for the integration, phase-6j-v1 for 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_paths and files preserve declaration order, every file entry carries advisory_only = True as an is-True structural marker, the bound fields are passed through from the source payload (no integration-side widening), the rendered prompt_block contains every source path AND every excerpt verbatim, the audit log line lands when log_path is supplied and the log is byte-equivalent across the call when log_path is 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 source context_signal_version (e.g. phase-6z-vX), on a canonical_precedence_note that drifts from the shipped Phase 6J literal, on a files list whose length contradicts declared_paths, on a files length above max_files_applied, on max_files_applied above OPTIONAL_CONTEXT_MAX_MAX_FILES, on max_bytes_per_file_applied above OPTIONAL_CONTEXT_MAX_BYTES_PER_FILE, on max_files_applied zero, on max_bytes_per_file_applied negative, on a file entry whose advisory_only is False (the integration refuses any entry that is not explicitly advisory), on an excerpt_byte_size above max_bytes_per_file_applied, and on a source_path that does not match the matching declared_paths index; malformed / missing refusal coverage proves the integration refuses on a missing source artifact, a directory at the source path, an unreadable source (mocked OSError on Path.read_text), a non-JSON source, a top-level non-dict source, a missing required top-level key, a non-list files, a non-dict file entry, a file entry missing a required key, a non-list declared_paths, and a non-string declared_paths entry; 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 by declared_paths do 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-entry truncated flag is preserved from the 6J source, the per-entry excerpt_byte_size is preserved, the per-entry excerpt bytes equal the 6J source excerpt verbatim (the integration adds no expansion), and the rendered prompt_block reports the per-entry truncation flag explicitly; CLI coverage proves the integrate-optional-context subcommand routes through main(argv) HANDLERS dispatch end-to-end and writes the JSON payload to .agent-loop/optional-context-prompt.json by default, honors a repo-relative --output override, honors a repo-relative --source override (the default source path remains absent), refuses fail-closed via _halt on an absolute --output path (rc=2, no artifact written), refuses on a --output path that resolves outside the repo root via .., refuses on an absolute --source path, refuses on a --source path that resolves outside the repo root via .., refuses on a missing source artifact via _halt leaving 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 _halt on a contradictory source payload
  • tests/test_optional_context.py covering 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 both declared_paths and files, the canonical_precedence_note is 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 with truncated: True and an excerpt exactly the byte-limit length, an under-budget file is included verbatim with truncated: False, len(declared_paths) > max_files refuses, and each of the eight limit validation cases (max_files zero / above-cap / bool / and the matching three for max_bytes_per_file) refuses fail-closed; path-validation coverage proves the library refuses on an empty declared_paths list, a non-list declared_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 outside repo_root via .., a duplicate path in the declaration, a missing file, a directory (not a regular file), and an unreadable file (mocked OSError on Path.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 with advisory_only = True, and does not append to the orchestrator log when log_path is omitted; CLI coverage proves the load-optional-context subcommand routes through main(argv) HANDLERS dispatch end-to-end and writes the JSON payload to .agent-loop/optional-context.json by default, accepts the --declared-path flag repeated for multiple files in declaration order, honors the --output / --max-files / --max-bytes-per-file overrides, overwrites an existing artifact rather than appending (it is an audit artifact regenerable from the declaration), is rejected by argparse with SystemExit(2) when the required --declared-path flag is absent, and refuses via _halt on a missing declared path leaving no output artifact behind
  • tests/test_phase_boundary_distillation.py covering 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 the distillation_signal_version = "phase-6i-v1" marker, every entry body records the same source_artifacts list pointing at the canonical sources and the same claude_summary_excerpt / codex_review_excerpt bounded blocks, the three entries carry the matching knowledge_type strings (summary / decision / failure), and the phase-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 with truncated: True and an excerpt_byte_size exactly the byte-limit, an under-budget source is included without truncation, an excerpt_byte_limit of zero / negative / above DISTILLATION_MAX_EXCERPT_BYTE_LIMIT / bool refuses fail-closed; refusal coverage proves the library refuses when status is not phase_complete_awaiting_human_approval, when last_verdict is not APPROVED_FOR_HUMAN_REVIEW, when loop-state.json is missing, on unsupported contract_version (halted_contract_version_mismatch), when .agent-loop/claude-summary.md is missing (the existing validate_claude_summary validator surfaces it as halted_summary_malformed), when .agent-loop/codex-review.md is missing (the existing validator surfaces it as halted_review_*), when the on-disk codex-review verdict disagrees with loop-state last_verdict (defense-in-depth refusal whose message contains the word "contradict"), when the claude-summary ## Phase header references a DIFFERENT phase than loop-state (halted_summary_malformed), when a source artifact is unreadable (the existing OSError path 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 the decision write rolls back the already-written summary entry, a failure during the failure write rolls back BOTH the summary and the decision entries, 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 mutate loop-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 the distill-phase-boundary-memory subcommand routes through main(argv) HANDLERS dispatch end-to-end, writes the entries on success and lands the audit note, honors the --excerpt-byte-limit override (the recorded excerpt_byte_limit_applied field on the on-disk summary entry reflects the operator's choice), refuses via _halt on an ineligible status (loop-state.json carries halted_input_missing, no memory entries written), and refuses via _halt on an invalid limit flag
  • tests/test_continuation_prompt_context.py covering 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); the canonical_state subset mirrors loop-state's phase / sub_phase / task / cycle_count / approval_mode / halt_status / awaiting_human_for; the checkpoint subset 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 with truncated: True and an excerpt exactly the byte-limit length, an under-budget file is included verbatim with truncated: False, a missing evidence file is reported with absent: True rather than silently omitted, an evidence_byte_limit of zero / negative / non-int / bool / above CONTINUATION_CONTEXT_MAX_EVIDENCE_BYTE_LIMIT refuses fail-closed, an evidence file that exists on disk but raises OSError on read refuses via HaltError("halted_input_missing", ...) (no read_error schema branch ever appears in a success payload), and the CLI subcommand routes the same unreadable-evidence refusal through _halt so the structural failure vocabulary lands on disk and no output artifact is written; bounded-memory coverage proves every returned advisory entry carries the Phase 6C advisory_only = True structural marker, that the memory_truncated_at_limit flag flips True when more entries match than the limit allows back (including the load-bearing edge case where the caller's limit equals MEMORY_RETRIEVAL_MAX_LIMIT and 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 exactly MEMORY_RETRIEVAL_MAX_LIMIT entries match), that an out-of-bound memory_entry_limit is 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 in CONTINUATION_CONTEXT_ELIGIBLE_HALT_STATUSES (only HALTED_TOKEN_EXHAUSTION in this initial slice), refuses on a strict-gate halt (the strict-gate path has its own resume), refuses when no active checkpoint exists, refuses on cycle-identity mismatch (delegated to the Phase 6F validator), refuses on suspension_reason other than token_exhaustion, refuses on unsupported contract_version (halted_contract_version_mismatch), and refuses on missing loop-state.json; canonical-precedence preservation - building the context does NOT mutate loop-state.json, does NOT mutate the active checkpoint, does NOT create the output artifact (only the CLI handler does), the canonical_precedence_note is the literal named constant (consumers can rely on equality), the continuation context built: audit note lands when log_path is supplied, and the log content is byte-equivalent across a build call when log_path is omitted; CLI coverage proves the build-continuation-context subcommand routes through main(argv) HANDLERS dispatch end-to-end and writes the JSON payload to .agent-loop/continuation-context.json by default, honors the --output, --memory-entry-limit, and --evidence-byte-limit overrides, overwrites an existing artifact rather than appending (it is an audit artifact regenerable from canonical state), refuses via _halt on an ineligible halt status leaving the structural failure vocabulary on disk and writing no output artifact, and refuses via _halt on an invalid limit flag passed through to the library function
  • tests/test_auto_continuation_chaining.py covering the Phase 6G automatic continuation chaining layer: run_auto_continue(...) performs up to AUTO_CONTINUE_MAX_HOPS = 4 hops of the shipped Phase 6F single-hop run_token_exhaustion_resume(...) while loop-state re-enters HALTED_TOKEN_EXHAUSTION; a clean single-hop dispatch (the dispatched continuation does not re-record exhaustion) terminates the chain after one hop with the transitional evidence_capture left 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 like claude_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; the AUTO_CONTINUE_MAX_HOPS defense-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 the auto-continue subcommand proves the HANDLERS dispatch chain reaches run_auto_continue(...) end-to-end through main(argv) and proves a cmd_resume invocation on a HALTED_TOKEN_EXHAUSTION halt still dispatches the single-hop run_token_exhaustion_resume (the chain is opt-in via the dedicated subcommand, not an automatic widening of resume); canonical-precedence preservation - a successful chain does NOT advance cycle_count, does NOT mutate phase / 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 by validate_loop_state and refused with halted_input_missing written through _halt, a successful hop whose dispatched continuation leaves an unsupported contract_version is caught by check_contract_version and refused with halted_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 completion
  • tests/test_token_exhaustion_continuation.py covering 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 to HALTED_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 any halted_* status (no clobbering an existing recovery point), when the cycle is terminally complete (phase_complete_awaiting_human_approval), when the active_prompt_path is out of vocabulary, and when loop-state.json is missing, accepts both .agent-loop/claude-prompt.md and .agent-loop/fix-prompt.md as valid prompts, and emits a token exhaustion recorded: audit note; _validate_token_exhaustion_checkpoint(...) compares the cycle-identity subset (phase, sub_phase, task, cycle_count, approval_mode) and intentionally OMITS status / awaiting_human_for because 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 with continuation_budget - 1 and restoring loop-state to the pre-suspension status / awaiting_human_for, emits a token-exhaustion resume consumed: audit note showing budget N -> N-1, refuses with _halt only 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 outside TOKEN_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 (an awaiting_claude_implementation interruption dispatches _run_normal_cycle_from_increment and an awaiting_codex_review interruption dispatches _run_normal_cycle_codex_review_step with a transitional evidence_capture write 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 the record-token-exhaustion subcommand proves the orchestrator runtime actually enters HALTED_TOKEN_EXHAUSTION end-to-end (the HANDLERS dispatch chain), proves the optional --continuation-budget override is honored, proves both .agent-loop/claude-prompt.md and .agent-loop/fix-prompt.md are accepted while an unknown --active-prompt-path is rejected by argparse before the handler runs, proves a pre-existing halt is refused via _halt (no recovery point silently clobbered), and proves the full record-token-exhaustion then resume sequence reaches the token-exhaustion continuation entry-point end-to-end without advancing cycle_count; cmd_resume(...) routing inspects the persisted halt status BEFORE dispatch so HALTED_TOKEN_EXHAUSTION routes to run_token_exhaustion_resume (mocked) and a strict-gate halt or a missing loop-state file routes to run_strict_resume unchanged (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 state
  • tests/test_checkpoint_resume.py covering 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]}.json has 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-closed HaltError when the chosen active checkpoint is itself malformed; _validate_checkpoint_against_loop_state(...) accepts a fully matching checkpoint silently and refuses fail-closed with halted_input_missing for 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 a checkpoint 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 stale cycle_count / task / sub_phase checkpoint exists, refuses fail-closed when the checkpoint's suspension_reason contradicts the active strict-gate halt, refuses fail-closed when the active on-disk checkpoint is malformed (missing required field, unrecognized checkpoint_signal_version) and writes a strict resume refused: audit note; canonical-precedence preservation - every refusal leaves the saved strict-gate status / awaiting_human_for / approval_mode intact 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 bytes
  • tests/test_checkpoint_storage.py covering the shipped Phase 6D checkpoint artifact storage layer: a valid write_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 allowed suspension_reason values (the four base reasons token_exhaustion / human_interrupt / process_killed / orchestrator_restart plus the four Phase 5C strict-gate halt statuses), accepts both allowed active_prompt_path values (claude-prompt.md and fix-prompt.md), accepts a continuation_budget of zero, and accepts both None and a non-empty string for awaiting_human_for; malformed-checkpoint write refusal for empty task / status / approval_mode, wrong-type or empty-string awaiting_human_for, out-of-vocabulary active_prompt_path or suspension_reason, and continuation_budget that 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 unrecognized checkpoint_signal_version, an out-of-vocabulary active_prompt_path or suspension_reason, a bad continuation_budget, and (mirroring the write-side guards so a hand-edited artifact cannot bypass the checkpoint contract on read) empty / non-string task / status / approval_mode and an awaiting_human_for that 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 6B memory write: audit note with category='checkpoint' when a log_path is supplied (and creates no log file when it is omitted)
  • tests/test_memory_retrieval.py covering 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 above MEMORY_RETRIEVAL_MAX_LIMIT; malformed-entry refusal that halts the whole retrieval call on malformed JSON, missing required fields, unrecognized signal_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 carries MEMORY_RETRIEVAL_ADVISORY_FIELD = True so 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 by created_at; audit-note signature when log_path is supplied that names phase / sub_phase / categories / limit / matched / returned (and no log file created when it is omitted, and no task= field in the audit signature); and a required non-empty active phase string at the boundary
  • tests/test_memory_storage.py covering 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 empty phase / sub_phase / source_artifact_path and non-int cycle_count; unknown-category refusal at write time and at list_memory_entries time so the five-category set cannot be silently extended at runtime; append-mostly behavior - two writes create two distinct files and a supersedes reference 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_entries returns an empty list when the memory dir is absent and a category-filtered list when category is provided; the writer appends a memory write: audit note to .agent-loop/orchestrator.log when a log_path is supplied
  • tests/test_review_follow_up.py covering 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 explicit Owner: field is provided; an explicit Owner: 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.log before 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 preserved
  • tests/test_approval_modes.py covering the Phase 5B review-mode initial slice, the Phase 5C strict-mode pauses, AND the Phase 5D autonomous-mode initial slice: activation defaults approval_mode to "review" and resets awaiting_human_for to 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 sets awaiting_human_for = "phase_complete_awaiting_human_approval" on APPROVED_FOR_HUMAN_REVIEW and clears it on NEEDS_FIXES / FAILED_REQUIRES_HUMAN; .agent-loop/claude-done.json writes carry every required Phase 5A field for both implementation and fix completion and reject an invalid mode without leaving a partial file; a stale claude-done.json is 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 before pre_claude_prompt, no Codex adapter call before pre_codex_review in either the normal or fix cycle), the resume subcommand refuses from a non-strict-halt status, resume after pre_claude_prompt dispatches into the cycle_count-increment continuation, resume after pre_codex_review skips straight to Codex review without re-invoking Claude or re-incrementing the counter, resume after pre_fix_prompt runs one fix cycle, and review mode never fires any strict gate. Autonomous-mode coverage proves none of the four strict gates fires under autonomous (Claude/Codex adapters are reached without a halt) and each bypass is logged to .agent-loop/orchestrator.log; the autonomous continuation still halts on FAILED_REQUIRES_HUMAN, on the cycle_count >= max_cycles threshold for NEEDS_FIXES, on a missing-evidence halt, and on the APPROVED_FOR_HUMAN_REVIEW phase-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.

Ver o original no GitHub

Bom para

Relacionados