CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
HITL Answer Ledger Implementation Plan
- Date: 2026-06-27
- Spec:
dev/specs/2026-06-27-hitl-answer-ledger.md - Status: Draft for review
Objective
Fix the ROOT-A deadlock where parallel two-phase tool preparation and the single-slot HITL resume channel can ping-pong between two approval-gated tool calls forever. The fix is a framework-level durable answer ledger keyed by thread, run, and question id.
Constraints
- Do not force approval-gated tools into
execution_mode="sequential". - Do not weaken the two-phase parallel executor's side-effect safety.
- Do not require hosts to classify HITL-gated tools.
- Keep the public visible HITL model as one pending request at a time.
- Run all repo commands through
uv.
Phase 1: Add the Checkpointer Ledger Contract
Files:
cubepi/checkpointer/base.pycubepi/checkpointer/memory.pytests/checkpointer/test_memory_checkpointer.pyor the nearest existing memory checkpointer test module
Steps:
- Import
IterableandStructuredValuewhere needed. - Add
save_hitl_answer,load_hitl_answer, andclear_hitl_answersto theCheckpointerprotocol. - Implement the methods in
MemoryCheckpointerwith a private dict keyed by(thread_id, run_id or "", question_id). - Copy answers on save/load if the existing message/pending code uses deep copies for comparable mutable state.
- Add focused unit tests:
- saving then loading returns the answer
- run id scopes answers
- clearing a single question id preserves other answers
- clearing all answers for a run removes only that run
Acceptance:
- Memory checkpointer tests pass.
- The protocol names match the spec exactly.
Phase 2: Add Durable Storage to SQL Checkpointers
Files:
cubepi/checkpointer/sqlite.pycubepi/checkpointer/postgres/checkpointer.pycubepi/checkpointer/postgres/models.pycubepi/checkpointer/mysql/checkpointer.pycubepi/checkpointer/mysql/models.py- existing SQL checkpointer tests under
tests/checkpointer/
Steps:
- Add a
cubepi_hitl_answerstable to each first-party SQL backend. - Use columns:
thread_idrun_id, stored as non-null text with""representingNonequestion_idanswer_jsonanswered_at
- Make
(thread_id, run_id, question_id)the primary key. - Implement upsert semantics for
save_hitl_answer. - Implement exact-key lookup for
load_hitl_answer. - Implement
clear_hitl_answerswith two modes:question_ids is None: delete all answers for(thread_id, run_id)question_idssupplied: delete only those ids for(thread_id, run_id)
- Add CRUD tests for SQLite. Extend Postgres/MySQL tests where the repo already runs backend-specific checkpointer HITL tests.
Acceptance:
- SQLite tests pass locally.
- Backend-specific tests are updated without adding hard dependencies to core.
Phase 3: Teach HITL Channels to Replay Ledger Answers
Files:
cubepi/hitl/channel.pytests/hitl/test_in_memory_channel.pytests/hitl/test_channel.pyor nearest existing checkpointed channel tests
Steps:
- Extend
_BaseChannelwith optional ledger hooks:_load_answer(question_id)_save_answer(question_id, answer)_clear_answers(...)only if channel-level abort cleanup is already centralized there
- Implement default no-op behavior for plain in-process channels, then override
as needed in
InMemoryChannelandCheckpointedChannel. - Add an in-memory answer dict to
InMemoryChannelso same-process behavior follows the same replay semantics. - Update
CheckpointedChannel.__init__validation to require the new ledger methods when used for detached HITL. - Change
_await_answer()resolution order:- load durable/in-memory ledger answer for
question_id - fall back to matching
_resume_slot - otherwise publish pending and wait/detach
- load durable/in-memory ledger answer for
- When
answer()resolves the currently pending request in process, save the answer before waking the waiter. - Do not clear a ledger answer when
_await_answer()returns it. - Add tests proving:
- replayed ledger answers do not create a new pending request
- stale process-local resume slots still do not satisfy the wrong question id
- in-process
answer()also records a replayable answer
Acceptance:
- Existing HITL channel tests still pass.
- New replay tests fail without the ledger lookup and pass with it.
Phase 4: Persist Answers in Agent.respond and Clear Them Safely
Files:
cubepi/agent/agent.pycubepi/agent/loop.pycubepi/hitl/channel.pyif abort cleanup belongs theretests/hitl/test_loop_hitl_passthrough.py- new or existing agent HITL resume tests
Steps:
- In
Agent.respond(), after validating pendingquestion_idand recovered run id, callsave_hitl_answer(thread_id, question_id, answer, run_id=...)before_run_hitl_resume(). - Keep
attach_resume_answer()as a same-process fast path, but make the ledger the durable source of truth. - Ensure resume detaching on the next pending request does not clear saved answers.
- Clear ledger answers for
(thread_id, active_run_id)only after the suspended tool cycle has completed and tool results have been appended. - Clear ledger answers when pending HITL is aborted/cancelled or when the run reaches a terminal cleanup path.
- Prefer clearing all answers for the run over clearing only tool call ids, so
ask_userquestion ids are covered. - Add tests for cleanup:
- after successful completion
- after abort
- no cleanup after detach on another request
Acceptance:
- A saved answer survives a detach on a later tool call.
- Saved answers are not left behind after successful completion or abort.
Phase 5: Add the ROOT-A Regression Test
Files:
tests/hitl/test_loop_hitl_passthrough.pyor a newtests/hitl/test_parallel_approval_ledger.py
Test shape:
- Define two tools that require approval and record executions.
- Use a provider response that requests both tools in the same assistant turn with parallel execution enabled.
- Start
Agent.prompt()and observe pendingA. - Call
Agent.respond(question_id=A, answer=approve). - Assert:
- no tool body has executed yet
- no tool results have been appended yet
- pending is now
B
- Call
Agent.respond(question_id=B, answer=approve). - Assert:
- both tool bodies executed exactly once
- two tool results were appended
- pending is cleared
- ledger answers for the run are cleared
- Repeat the same flow with a fresh
Agentinstance between the two approvals to prove durable replay works after process restart.
Acceptance:
- The test reproduces the current deadlock before the implementation.
- The test passes after the answer ledger implementation.
Phase 6: Cover Decision Variants
Files:
tests/hitl/test_loop_hitl_passthrough.py- approval middleware tests under
tests/hitl/
Steps:
- Add a deny/reject variant where
Ais denied, resume detaches onB, thenBis approved. Verify the replayed denial emits the expected tool result and no denied tool body executes. - Add an edit variant if the existing approval middleware supports edited tool arguments in tests. Verify the edited decision survives the second detach and the tool receives edited args.
- Add an
ask_userreplay case if the existingask_usertests can express a multi-question resume flow without building a large fixture.
Acceptance:
- The ledger stores and replays structured answers, not just boolean approvals.
Phase 7: Update Documentation
Files:
website/docs/HITL guide or recipe page- Chinese mirror if this docs tree keeps one for the changed page
Steps:
- Document the new guarantee: approval-gated tools can remain parallel.
- Explain that approving one request in a parallel batch records the decision, but execution waits until the remaining gates are answered.
- Remove or avoid guidance that tells users to mark gated tools sequential only to avoid HITL deadlocks.
- Add a short example flow with two parallel approval-gated tool calls.
Acceptance:
- User-facing docs match the runtime behavior.
- The feature is not considered complete until docs ship in the same PR.
Verification Commands
Run focused tests first:
uv run pytest tests/hitl/test_in_memory_channel.py -v
uv run pytest tests/hitl/test_loop_hitl_passthrough.py -v
uv run pytest tests/checkpointer/ -k "memory or sqlite or hitl" -v
Then run broader checks:
uv run pytest tests/
uv run ruff check cubepi/ tests/
uv run ruff format --check cubepi/ tests/
uv run mypy cubepi
Review Checkpoints
- Review the spec and this plan before coding.
- After code and docs are ready, ask before entering the local codex review
loop required by
AGENTS.md. - Open a PR from the worktree branch after implementation and documentation.
- Drive the PR codex review loop until review and CI are clean.