feat(explore): plan-reviewen kan besvares over DAGER (U12 + asynkron U13, rad 3)

F4 gjorde "be om svar, BRUKE svarene" naabar, men bare SYNKRONT: terminal_plan_reviewer
blokkerer loekka paa et menneske ved en terminal, saa svaret maa komme mens prosessen lever.
Maalbilde §3s tidsskala er den andre - eksperten svarer dager senere, i en prosess som aldri
saa kjoeringen.

--checkpoint-dir PARKERER reviewen (FileCheckpointStorage + {run_id}-plan-review.json) og
avslutter; --resume <run_id> leser svaret fra --review-inbox i en fersk interpreter. Det
eneste som krysser prosessgrensen er disk.

MAALT FELLE (Verifiseringsloven ansikt 4): list_checkpoints (_checkpoint.py:386-388) svelger
en blokkert deserialisering til en logger.warning og returnerer TOM liste. Uten BEGGE
MagenticPlanReviewRequest/Response i allowed_checkpoint_types feiler en resume som et FRAVAER,
ikke som en feil. _ALLOWED_CHECKPOINT_TYPES har derfor EN kopi, checkpoint_storage er eneste
konstruksjonssted, og en tom listing ved park raiser CheckpointUnreadable i stedet for aa
skrive et spoersmaal ingen kan besvare.

Budsjettet og revisjons-capen spenner over suspensjonen (meter.charge(parked.tokens_spent) +
trace.ledger.extend), ellers faar hver park et helt budsjett paa nytt. Fail-closed paa
ekspertens egen fil: request_id-mismatch, ord utenfor vokabularet og revise uten innhold
refuseres alle ved navn. hitl.pending_plan_reviews er registeret over hvem som venter.

Load-bearing MAALT: 17 tester, TRETTEN mutasjoner alle roede mot HELE suiten, groenn kontroll
1059 passed / 5 skipped, golden demo-transcript.stdout byte-uendret
(ea8c534773acdbe41ae68f2c55724d69aaf8be4f).

EN MUTASJON FALSIFISERTE SUITEN (vakuoes-gate-klassen, tiende gang): detach av
trace.plan_reviews.extend(parked.plan_reviews) lot HELE suiten staa groenn - capen leser
parked.plan_reviews DIREKTE, saa den binder uansett, og de to foerste legene er identiske
under begge implementasjoner. Gaten maatte bli det TREDJE leget, der artefaktet ellers taper
dag 1s revisjon og to ulike planer deler indeks 1. Ny test skrevet mot mutasjonen foerst.

Aerlighets-grenser: hostet flate NEKTER fortsatt (synkron review ville blokkert baade
requesten og event-loekka som svarer /readiness); en park midt i loepet etter en stall har
ingen naabar sti under det skriptede manuset, saa carry-overen som betjener den drives gjennom
en CRAFTED parkert tilstand.

Ordre 20260825T114645Z-6622513622-from-portfolio-optimiser.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Kjell Tore Guttormsen 2026-08-26 12:26:04 +02:00
commit c08ae91809
7 changed files with 1754 additions and 91 deletions

View file

@ -30,7 +30,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Final, Literal, TextIO
from agent_framework import Agent, BaseChatClient, FunctionTool, tool
from agent_framework import Agent, BaseChatClient, FileCheckpointStorage, FunctionTool, tool
from agent_framework.orchestrations import (
MagenticBuilder,
MagenticOrchestratorEventType,
@ -122,6 +122,24 @@ def exploration_notice(result: "ExplorationResult") -> str:
)
def parked_notice(parked: "ParkedExploration", *, run_id: str) -> str:
"""The ONE thing a parked exploration says at the terminal it stopped on.
Always a line, for the reason ``exploration_notice`` always is: it is printed only where the
asynchronous door was asked for. It names the run id, because that is the single coordinate
``--resume`` takes, and it is the one an operator will be looking for weeks later.
It does NOT print the plan. The plan is in the question artefact, where the expert who has to
read it will be looking and this terminal belongs to whoever STARTED the run, who is not
necessarily them.
"""
return (
f"Exploration parked: plan review {parked.index} of run {run_id!r} is waiting for a "
f"human. The question is in {run_id}-plan-review.json; answer it with "
f"{run_id}-plan-review-answer.json in a review inbox, then --resume {run_id}"
)
def load_exploration_contract(path: str | Path) -> ExplorationContract:
"""Fail-fast standalone loader for an exploration's bounds (mirrors ``mandate.load_mandate``).
@ -256,6 +274,11 @@ class ExplorationTrace:
ledger: list[LedgerEntry] = field(default_factory=list)
plan_reviews: list[PlanReview] = field(default_factory=list)
quick_validations: list[QuickValidation] = field(default_factory=list)
#: Tokens spent so far, refreshed as the loop turns rather than written once at the end. The
#: meter is internal to ``explore``, so this is the only way the artefact can report a spend —
#: and updating it per iteration is what makes it readable for a run a cap cut short, which is
#: the same reason the sink exists at all. Across a park it is what the resumed leg adds to.
tokens_spent: int = 0
def trace_payload(trace: ExplorationTrace, *, stop: str | None, completed: bool) -> dict[str, Any]:
@ -271,6 +294,7 @@ def trace_payload(trace: ExplorationTrace, *, stop: str | None, completed: bool)
return {
"completed": completed,
"stop": stop,
"tokens_spent": trace.tokens_spent,
"rounds": [
{
"round_index": entry.round_index,
@ -438,6 +462,202 @@ def terminal_plan_reviewer(
return review
# ---------------------------------------------------------------------------------------------
# U12 — the ASYNCHRONOUS half of the same door: a review answered days later, in another process.
# ---------------------------------------------------------------------------------------------
#: The two types a plan-review checkpoint carries, in ``"module:qualname"`` form.
#:
#: **This tuple is the whole of the measured trap** (plan § F, A4; re-measured against the
#: installed source, ``_workflows/_checkpoint.py:386-388``): ``FileCheckpointStorage`` runs a
#: restricted unpickler, and ``list_checkpoints`` swallows a blocked type into a ``logger.warning``
#: and returns an EMPTY list. Omit either name and the checkpoint is written but comes back
#: unreadable, so a resume fails as an ABSENCE — "nothing to resume" — rather than as an error.
#: ONE copy, used by every process that touches this storage, because both the writing process and
#: the resuming one must declare them and a second copy is the drift kø-(p) exists to prevent.
_ALLOWED_CHECKPOINT_TYPES: Final[tuple[str, ...]] = (
"agent_framework_orchestrations._magentic:MagenticPlanReviewRequest",
"agent_framework_orchestrations._magentic:MagenticPlanReviewResponse",
)
def checkpoint_storage(checkpoint_dir: str | Path) -> FileCheckpointStorage:
"""The ONE construction site for the exploration's checkpoint storage.
A caller that built its own ``FileCheckpointStorage`` would have to remember the allow-list
above, and forgetting it is invisible (see ``_ALLOWED_CHECKPOINT_TYPES``). Routing every
construction through here makes "both processes declare the types" a structural property
rather than a convention two call sites have to keep.
"""
return FileCheckpointStorage(
str(checkpoint_dir), allowed_checkpoint_types=list(_ALLOWED_CHECKPOINT_TYPES)
)
class CheckpointUnreadable(ExplorationError):
"""The exploration stopped at a review but left nothing a later process could resume from.
Raised where the framework is silent: an empty listing means the checkpoint could not be read
back, and parking anyway would hand an expert a question whose answer can never be applied.
Failing here is the fourth face of the verification law written into our own surface.
"""
class ParkedStateError(ExplorationError):
"""A parked-state file that cannot be read as one.
Fail-fast, NOT the tolerant RAW-inbox rule: this file is the run's own suspended state, the
same class as the spend file ``read_spend`` refuses to read loosely. Treating a malformed one
as "no parked run" would silently drop an exploration a human is waiting to answer.
"""
@dataclass(frozen=True)
class ParkedExploration:
"""Everything needed to resume one suspended exploration in a process that never saw it.
Two files cross the boundary and they own different halves. MAF's checkpoint holds the
WORKFLOW's state (the manager's ledgers, the pending request); this holds the EXPLORATION
LAYER's — what has been spent, what the loop has already found, and which question is open.
Neither can reconstruct the other, so both are named here rather than one being inferred.
``tokens_spent`` and ``ledger`` are carried for a reason that is not bookkeeping. Both budget
channels live in the process: a resume with a fresh ``TokenMeter`` and an empty ledger would
get the whole cap AGAIN, once per park unbounded consumption behind guards that all report
themselves satisfied, which is the class S3.4 split apart. Carrying them makes the cap span
the suspension.
``hypotheses`` are the marked turns the loop produced BEFORE parking. They are verbatim, and
they are carried for the same reason: minting the mandate from only what the resuming process
observed would silently drop everything found before a stalled re-review.
"""
prompt: str
request_id: str
checkpoint_id: str
index: int
plan: str
current_progress: str
is_stalled: bool
bundle_dirs: tuple[str, ...]
contract: ExplorationContract
ledger: tuple[LedgerEntry, ...]
plan_reviews: tuple[PlanReview, ...]
hypotheses: tuple[str, ...]
tokens_spent: int
replans: int
class PlanReviewParked(ExplorationError):
"""The exploration is suspended at a plan review, waiting for a human.
**A raise rather than a return, and the argument is the 429 one** (-(y), 14.08). A parked run
produced NO mandate: the loop is stopped mid-plan and nothing has been explored yet. Handing
back an ``ExplorationResult`` would let an automated caller book "explored" for a run that
explored nothing the same reason an exhausted budget is not a 200 even though it is not a
crash either. The coordinates travel as STRUCTURE on ``parked``, never as ``str(exc)``.
"""
def __init__(self, parked: ParkedExploration) -> None:
super().__init__(
f"exploration parked at plan review {parked.index} "
f"(request {parked.request_id}, checkpoint {parked.checkpoint_id})"
)
self.parked = parked
def parked_payload(parked: ParkedExploration) -> dict[str, Any]:
"""The ONE rendering of a parked exploration into plain data for ``outbox.write_plan_review``.
Plain mappings only, so the RAW output layer stays MAF-free the ``trace_payload`` precedent,
for the same reason: ``outbox.py`` may not import this module.
"""
return {
"prompt": parked.prompt,
"request_id": parked.request_id,
"checkpoint_id": parked.checkpoint_id,
"index": parked.index,
"plan": parked.plan,
"current_progress": parked.current_progress,
"is_stalled": parked.is_stalled,
"bundle_dirs": list(parked.bundle_dirs),
"contract": parked.contract.model_dump(),
"ledger": [
{
"round_index": entry.round_index,
"is_request_satisfied": entry.is_request_satisfied,
"is_in_loop": entry.is_in_loop,
"is_progress_being_made": entry.is_progress_being_made,
"next_speaker": entry.next_speaker,
"instruction_or_question": entry.instruction_or_question,
"speaker_known": entry.speaker_known,
}
for entry in parked.ledger
],
"plan_reviews": [
{
"index": review.index,
"plan": review.plan,
"is_stalled": review.is_stalled,
"decision": review.decision,
"feedback": review.feedback,
}
for review in parked.plan_reviews
],
"hypotheses": list(parked.hypotheses),
"tokens_spent": parked.tokens_spent,
"replans": parked.replans,
}
def load_parked(payload: Mapping[str, Any]) -> ParkedExploration:
"""Read a parked-state payload back, fail-fast (``ParkedStateError`` on anything missing).
Validation, never repair (the ``write_concept_file`` rule): a payload that has lost, say, its
``checkpoint_id`` describes a suspension nobody can lift, and defaulting it would produce a
resume that looks like one and is not.
"""
try:
return ParkedExploration(
prompt=str(payload["prompt"]),
request_id=str(payload["request_id"]),
checkpoint_id=str(payload["checkpoint_id"]),
index=int(payload["index"]),
plan=str(payload["plan"]),
current_progress=str(payload["current_progress"]),
is_stalled=bool(payload["is_stalled"]),
bundle_dirs=tuple(str(d) for d in payload["bundle_dirs"]),
contract=ExplorationContract.model_validate(payload["contract"]),
ledger=tuple(
LedgerEntry(
round_index=int(row["round_index"]),
is_request_satisfied=bool(row["is_request_satisfied"]),
is_in_loop=bool(row["is_in_loop"]),
is_progress_being_made=bool(row["is_progress_being_made"]),
next_speaker=str(row["next_speaker"]),
instruction_or_question=str(row["instruction_or_question"]),
speaker_known=bool(row["speaker_known"]),
)
for row in payload["ledger"]
),
plan_reviews=tuple(
PlanReview(
index=int(row["index"]),
plan=str(row["plan"]),
is_stalled=bool(row["is_stalled"]),
decision="revise" if row["decision"] == "revise" else "approve",
feedback=str(row["feedback"]),
)
for row in payload["plan_reviews"]
),
hypotheses=tuple(str(h) for h in payload["hypotheses"]),
tokens_spent=int(payload["tokens_spent"]),
replans=int(payload["replans"]),
)
except (KeyError, TypeError, ValueError, ValidationError) as exc:
raise ParkedStateError(f"parked exploration state is unreadable: {exc}") from exc
# ---------------------------------------------------------------------------------------------
# The tools. Level 1 of the three-guarantee table: real computation, ADVISORY verdicts.
# ---------------------------------------------------------------------------------------------
@ -619,6 +839,7 @@ def fresh_exploration_workflow(
bundle_dirs: Sequence[str] = (),
middleware: Sequence[Any] | None = None,
quick_validate_sink: list[QuickValidation] | None = None,
checkpoint_dir: str | None = None,
) -> Any:
"""Build a FRESH Magentic workflow with fresh agents and fresh clients (mirrors
``workflow.fresh_workflow``).
@ -668,14 +889,22 @@ def fresh_exploration_workflow(
middleware=middleware,
)
return MagenticBuilder(
builder = MagenticBuilder(
participants=participants,
manager_agent_factory=_manager_agent,
max_round_count=contract.max_rounds,
max_stall_count=contract.max_stall_count,
max_reset_count=contract.max_reset_count,
enable_plan_review=contract.enable_plan_review,
).build()
)
if checkpoint_dir is not None:
# Measured (spike S4, and re-measured in the plan's own E-table correction): it is the
# BUILDER's ``.with_checkpointing`` that is load-bearing, not ``checkpoint_storage=`` on
# ``run()`` — dropping the latter leaves the whole suite green. Both processes call THIS
# function, so the graph they build is identical, which is what lets a checkpoint written
# by one be restored by the other (``_runner.py:275-279`` matches on the graph signature).
builder = builder.with_checkpointing(checkpoint_storage(checkpoint_dir))
return builder.build()
def _truthy(answer: Any) -> bool:
@ -925,6 +1154,7 @@ async def explore(
meter: TokenMeter | None = None,
success_criteria: str = "",
trace: ExplorationTrace | None = None,
checkpoint_dir: str | None = None,
) -> ExplorationResult:
"""Explore the knowledge bases and return the ``Mandate`` the pipeline should evaluate.
@ -964,10 +1194,23 @@ async def explore(
produced: both budget channels destroy the ``ExplorationResult`` before it exists. When it is
omitted a private one is used, so the returned result is unchanged for every existing caller.
"""
if contract.enable_plan_review and plan_reviewer is None:
if plan_reviewer is not None and checkpoint_dir is not None:
raise ExplorationError(
"enable_plan_review is set but no plan_reviewer was given: the exploration would stop "
"at a review nobody can answer, which is a hang rather than a result"
"a plan_reviewer and a checkpoint_dir are two doors onto one review: the first answers "
"it in this process, the second parks it for another one. Refused rather than ranked, "
"because silently preferring either would block a caller that asked for the other"
)
if contract.enable_plan_review and plan_reviewer is None and checkpoint_dir is None:
raise ExplorationError(
"enable_plan_review is set but no plan_reviewer was given and no checkpoint_dir was "
"offered to park it: the exploration would stop at a review nobody can answer, which "
"is a hang rather than a result"
)
if checkpoint_dir is not None and not contract.enable_plan_review:
raise ExplorationError(
"a checkpoint_dir was given but enable_plan_review is false, so nothing would ever "
"park and the storage would be written and never read (a cap on an event that cannot "
"happen, refused for the reason max_plan_revisions is)"
)
if plan_reviewer is not None and not contract.enable_plan_review:
raise ExplorationError(
@ -1000,16 +1243,10 @@ async def explore(
bundle_dirs=bundle_dirs,
middleware=[BudgetMiddleware(meter)],
quick_validate_sink=trace.quick_validations,
checkpoint_dir=checkpoint_dir,
)
# ONE accumulator per fact, held by the caller (see ``ExplorationTrace``). The local names are
# aliases, never copies — a second list here is the kø-(p) drift this shape exists to prevent.
ledger_log = trace.ledger
plan_reviews = trace.plan_reviews
hypothesis_texts: list[str] = []
seen: set[int] = set()
replans = 0
stop: ExplorationStop | None = None
# ONE span for the whole exploration, opened before the first model call and closed however
# the loop ends — including on a BudgetExceeded, which the span records rather than swallows.
@ -1017,69 +1254,208 @@ async def explore(
# exactly what "tracing is off" has meant since U14.
with exploration_tracer().start_as_current_span(EXPLORATION_SPAN) as span:
result = await workflow.run(prompt)
while True:
replans += _absorb(
result,
ledger_log=ledger_log,
hypotheses=hypothesis_texts,
seen=seen,
span=span,
stop, _ = await _drive(
workflow,
result,
contract=contract,
trace=trace,
hypotheses=hypothesis_texts,
seen=set(),
replans=0,
span=span,
plan_reviewer=plan_reviewer,
checkpoint_dir=checkpoint_dir,
prompt=prompt,
bundle_dirs=bundle_dirs,
meter=meter,
)
return _finish(
prompt=prompt,
stop=stop,
trace=trace,
hypotheses=hypothesis_texts,
bundle_ids=bundle_ids,
seed_approaches=seed_approaches,
success_criteria=success_criteria,
)
async def _drive(
workflow: Any,
result: Any,
*,
contract: ExplorationContract,
trace: ExplorationTrace,
hypotheses: list[str],
seen: set[int],
replans: int,
span: Any,
plan_reviewer: PlanReviewer | None,
checkpoint_dir: str | None,
prompt: str,
bundle_dirs: Sequence[str],
meter: TokenMeter,
) -> tuple[ExplorationStop | None, int]:
"""Drive a built workflow from one ``run()`` result to an ending, answering plan reviews.
**ONE copy of this loop, shared by ``explore`` and ``resume_exploration``.** The asynchronous
door is not a second loop that happens to look like the first: a resumed exploration answers
reviews, absorbs ledgers, mints nothing, and classifies its stop by exactly the same rules, and
two copies of that would drift the moment one of them was corrected (-(p)).
Raises ``PlanReviewParked`` when the asynchronous door is armed the loop stops mid-plan and
the caller decides where to write the question.
"""
# ONE accumulator per fact, held by the caller (see ``ExplorationTrace``). The local names are
# aliases, never copies — a second list here is the kø-(p) drift this shape exists to prevent.
ledger_log = trace.ledger
plan_reviews = trace.plan_reviews
stop: ExplorationStop | None = None
while True:
trace.tokens_spent = meter.tokens
replans += _absorb(
result,
ledger_log=ledger_log,
hypotheses=hypotheses,
seen=seen,
span=span,
)
pending = _pending_plan_reviews(result)
if not pending:
break
request = pending[0]
review = request.data
if plan_reviewer is None:
# The asynchronous door (U12). ``checkpoint_dir`` is what armed it, and the guard in
# ``explore`` refused every other way of arriving here with no reviewer.
assert checkpoint_dir is not None
raise PlanReviewParked(
await _park(
workflow,
request,
checkpoint_dir=checkpoint_dir,
prompt=prompt,
bundle_dirs=bundle_dirs,
contract=contract,
trace=trace,
hypotheses=hypotheses,
meter=meter,
replans=replans,
)
)
pending = _pending_plan_reviews(result)
if not pending:
break
assert plan_reviewer is not None # guarded above; the review implies a reviewer
request = pending[0]
review = request.data
decision = plan_reviewer(
PlanReviewRequest(
decision = plan_reviewer(
PlanReviewRequest(
index=len(plan_reviews),
plan=str(review.plan),
current_progress=str(review.current_progress),
is_stalled=_truthy(review.is_stalled),
)
)
if decision.feedback is None:
plan_reviews.append(
PlanReview(
index=len(plan_reviews),
plan=str(review.plan),
current_progress=str(review.current_progress),
is_stalled=_truthy(review.is_stalled),
decision="approve",
)
)
if decision.feedback is None:
plan_reviews.append(
PlanReview(
index=len(plan_reviews),
plan=str(review.plan),
is_stalled=_truthy(review.is_stalled),
decision="approve",
)
response = MagenticPlanReviewResponse.approve()
else:
# The revision is recorded whether or not it is APPLIED: ``plan_reviews`` is the
# record of what the reviewer DECIDED, and ``stop`` is what says the last one was
# refused.
applied = sum(1 for entry in plan_reviews if entry.decision == "revise")
plan_reviews.append(
PlanReview(
index=len(plan_reviews),
plan=str(review.plan),
is_stalled=_truthy(review.is_stalled),
decision="revise",
feedback=decision.feedback,
)
response = MagenticPlanReviewResponse.approve()
else:
# The revision is recorded whether or not it is APPLIED: ``plan_reviews`` is the
# record of what the reviewer DECIDED, and ``stop`` is what says the last one was
# refused.
applied = sum(1 for entry in plan_reviews if entry.decision == "revise")
plan_reviews.append(
PlanReview(
index=len(plan_reviews),
plan=str(review.plan),
is_stalled=_truthy(review.is_stalled),
decision="revise",
feedback=decision.feedback,
)
)
if applied >= contract.max_plan_revisions:
# Measured (§ F, A3): a revise costs two manager calls, emits no progress
# ledger and consumes no round, then asks AGAIN. Under the round cap alone this
# loop never terminates. Stopping is the honest move — forcing an approve the
# reviewer did not give would be repair, and repair of a human's decision most
# of all.
stop = "plan_revisions_exhausted"
break
response = MagenticPlanReviewResponse.revise(decision.feedback)
result = await workflow.run(responses={request.request_id: response})
)
if applied >= contract.max_plan_revisions:
# Measured (§ F, A3): a revise costs two manager calls, emits no progress
# ledger and consumes no round, then asks AGAIN. Under the round cap alone this
# loop never terminates. Stopping is the honest move — forcing an approve the
# reviewer did not give would be repair, and repair of a human's decision most
# of all.
stop = "plan_revisions_exhausted"
break
response = MagenticPlanReviewResponse.revise(decision.feedback)
result = await workflow.run(responses={request.request_id: response})
if stop is None:
stop = _classify_stop(ledger_log, replans=replans, contract=contract)
trace.tokens_spent = meter.tokens
if stop is None:
stop = _classify_stop(ledger_log, replans=replans, contract=contract)
return stop, replans
discovered = (
_parse_hypotheses(hypothesis_texts, bundle_ids) if stop != "unknown_speaker" else []
async def _park(
workflow: Any,
request: Any,
*,
checkpoint_dir: str,
prompt: str,
bundle_dirs: Sequence[str],
contract: ExplorationContract,
trace: ExplorationTrace,
hypotheses: Sequence[str],
meter: TokenMeter,
replans: int,
) -> ParkedExploration:
"""Freeze the suspended exploration and name the checkpoint a later process resumes from.
``get_latest`` rather than the last entry of a listing: it picks by timestamp
(``_checkpoint.py:424``), while the listing's order is whatever ``Path.glob`` returned.
An EMPTY listing is refused (``CheckpointUnreadable``) rather than parked around. That is the
one place this layer is louder than the framework: a blocked deserialisation is swallowed into
a warning upstream, so the alternative to raising here is a question file whose answer can
never be applied an exploration that fails as an absence, days later, to somebody who has
already written their answer.
"""
latest = await checkpoint_storage(checkpoint_dir).get_latest(workflow_name=workflow.name)
if latest is None:
raise CheckpointUnreadable(
f"the exploration reached a plan review but no checkpoint could be read back from "
f"{checkpoint_dir!r}: without one the review can never be resumed, so it is refused "
f"here rather than written as a question nobody can answer"
)
review = request.data
return ParkedExploration(
prompt=prompt,
request_id=str(request.request_id),
checkpoint_id=str(latest.checkpoint_id),
index=len(trace.plan_reviews),
plan=str(review.plan),
current_progress=str(review.current_progress),
is_stalled=_truthy(review.is_stalled),
bundle_dirs=tuple(bundle_dirs),
contract=contract,
ledger=tuple(trace.ledger),
plan_reviews=tuple(trace.plan_reviews),
hypotheses=tuple(hypotheses),
tokens_spent=meter.tokens,
replans=replans,
)
def _finish(
*,
prompt: str,
stop: ExplorationStop | None,
trace: ExplorationTrace,
hypotheses: Sequence[str],
bundle_ids: Sequence[str],
seed_approaches: Sequence[Approach],
success_criteria: str,
) -> ExplorationResult:
"""Mint the mandate from a finished drive. Shared, for the reason ``_drive`` is."""
discovered = _parse_hypotheses(hypotheses, bundle_ids) if stop != "unknown_speaker" else []
return ExplorationResult(
mandate=Mandate(
objective=prompt,
@ -1087,9 +1463,133 @@ async def explore(
allow_own_proposals=True,
success_criteria=success_criteria,
),
ledger_log=tuple(ledger_log),
ledger_log=tuple(trace.ledger),
stop=stop,
plan_reviews=tuple(plan_reviews),
plan_reviews=tuple(trace.plan_reviews),
)
async def resume_exploration(
parked: ParkedExploration,
decision: PlanReviewDecision,
*,
checkpoint_dir: str,
profile: Profile | str = Profile.LOCAL,
client_factory: Callable[[str], BaseChatClient] | None = None,
seed_approaches: Sequence[Approach] = (),
success_criteria: str = "",
trace: ExplorationTrace | None = None,
) -> ExplorationResult:
"""Answer a parked plan review and drive the exploration onward, in a process that never ran it.
Everything about the workflow is rebuilt from ``parked`` rather than from argv: the prompt, the
bounds and the bases are what the suspended run used, and the graph must match the checkpoint's
signature (``_runner.py:275-279``) for the restore to be accepted at all. A caller that had to
re-supply them could get one of them wrong and would find out as a restore failure days later.
**The budget spans the suspension.** The meter starts at ``parked.tokens_spent`` and the ledger
at ``parked.ledger``, so the round cap and the token cap measure the whole exploration rather
than this leg of it. Without that a park would hand back a full budget every time it happened.
Parking AGAIN is a normal outcome, not a failure: a revision makes the manager replan and ask
about the NEW plan, which is the second half of "be om svar, BRUKE svarene" on this time-scale.
It leaves by ``PlanReviewParked`` exactly as the first park did.
"""
if trace is None:
trace = ExplorationTrace()
# The carried state is put back BEFORE anything runs: ``_drive`` reads these as its own running
# log, and ``_classify_stop`` counts the ledger to decide whether the ROUND cap bound.
trace.ledger.extend(parked.ledger)
trace.plan_reviews.extend(parked.plan_reviews)
hypothesis_texts = list(parked.hypotheses)
bundle_ids = tuple(_bundle_index(parked.bundle_dirs))
refuse_unroutable_seeds(seed_approaches, bundle_ids)
meter = TokenMeter(
Budget(max_tokens=parked.contract.max_tokens, max_rounds=parked.contract.max_rounds)
)
# Through ``charge``, not by assigning ``tokens``: charging re-tests the cap, so a suspension
# that already spent everything refuses HERE instead of buying one more leg of the loop.
meter.charge(parked.tokens_spent)
if client_factory is None:
from portfolio_optimiser.run import _default_factory
client_factory = _default_factory(profile)
workflow = fresh_exploration_workflow(
client_factory,
contract=parked.contract,
bundle_dirs=parked.bundle_dirs,
middleware=[BudgetMiddleware(meter)],
quick_validate_sink=trace.quick_validations,
checkpoint_dir=checkpoint_dir,
)
# The revision cap counted across the SUSPENSION, over the reviews carried in ``parked``.
# Measured, and it is why the carry-over is load-bearing rather than tidy: a revise costs two
# manager calls, emits no progress ledger and consumes no round (§ F, A3), so a cap that reset
# at every park would leave the asynchronous door with no bound at all — an expert could revise
# forever, one process at a time, under guards that all report themselves satisfied. The same
# arithmetic ``_drive`` does for the synchronous door, and the same refusal to repair: the
# decision is RECORDED and the loop stops, never forced into an approve nobody gave.
applied = sum(1 for entry in parked.plan_reviews if entry.decision == "revise")
trace.plan_reviews.append(
PlanReview(
index=parked.index,
plan=parked.plan,
is_stalled=parked.is_stalled,
decision="approve" if decision.feedback is None else "revise",
feedback=decision.feedback or "",
)
)
if decision.feedback is not None and applied >= parked.contract.max_plan_revisions:
return _finish(
prompt=parked.prompt,
stop="plan_revisions_exhausted",
trace=trace,
hypotheses=hypothesis_texts,
bundle_ids=bundle_ids,
seed_approaches=seed_approaches,
success_criteria=success_criteria,
)
response = (
MagenticPlanReviewResponse.approve()
if decision.feedback is None
else MagenticPlanReviewResponse.revise(decision.feedback)
)
with exploration_tracer().start_as_current_span(EXPLORATION_SPAN) as span:
result = await workflow.run(
responses={parked.request_id: response},
checkpoint_id=parked.checkpoint_id,
checkpoint_storage=checkpoint_storage(checkpoint_dir),
)
stop, _ = await _drive(
workflow,
result,
contract=parked.contract,
trace=trace,
hypotheses=hypothesis_texts,
seen=set(),
replans=parked.replans,
span=span,
plan_reviewer=None,
checkpoint_dir=checkpoint_dir,
prompt=parked.prompt,
bundle_dirs=parked.bundle_dirs,
meter=meter,
)
return _finish(
prompt=parked.prompt,
stop=stop,
trace=trace,
hypotheses=hypothesis_texts,
bundle_ids=bundle_ids,
seed_approaches=seed_approaches,
success_criteria=success_criteria,
)

View file

@ -165,6 +165,138 @@ def pending(outbox_dir: str, verdict_dir: str) -> list[PendingProposal]:
return sorted(unjudged, key=lambda p: (p.run_id, p.approach_id, p.verdict_id))
# --- U12: the pending PLAN REVIEWS of parked explorations, and the expert's answer ---------------
# The same registry shape as ``pending`` above, one time-scale earlier: there the outbox holds a
# PROPOSAL awaiting a verdict, here it holds a QUESTION awaiting a decision. Both live in this
# MAF-free module because both are read by an operator tool that must not drag the framework in.
#: The closed answer vocabulary, identical to the terminal door's (``explore.terminal_plan_reviewer``).
#: Two words, matched structurally — a file cannot be re-asked, so anything else is a refusal.
_PLAN_REVIEW_ANSWERS = frozenset({"approve", "revise"})
@dataclass(frozen=True)
class PendingPlanReview:
"""One parked exploration still waiting on a human. ``plan`` is carried because a registry that
only counted questions could not be used to answer one."""
run_id: str
request_id: str
index: int
plan: str
is_stalled: bool
@dataclass(frozen=True)
class PlanReviewAnswer:
"""The expert's decision, as read off a file. ``feedback`` is empty exactly when approving —
the same encoding ``explore.PlanReviewDecision`` uses, kept plain so this module stays
MAF-free and the adapter between them lives at ONE call site."""
run_id: str
request_id: str
decision: str
feedback: str
class PlanReviewAnswerError(ValueError):
"""An answer file that cannot be read as a decision.
Fail-closed, and deliberately NOT the tolerant rule the verdict inbox uses. A dropped verdict
that will not parse is one opinion missing from a fold; an unreadable plan-review answer is the
one thing standing between a suspended run and a plan nobody signed. A ``ValueError`` so the
CLI's existing structured-refusal arm surfaces it as ``rc 1`` rather than a traceback."""
def _answer_path(review_dir: str, run_id: str) -> Path:
return Path(review_dir) / f"{run_id}-plan-review-answer.json"
def read_plan_review_question(outbox_dir: str, run_id: str) -> dict[str, Any] | None:
"""The open question of ``run_id``, or ``None`` when there is none. Tolerant: an outbox with no
such file simply has no parked review."""
return _load_json_dict(Path(outbox_dir) / f"{run_id}-plan-review.json")
def load_plan_review_answer(review_dir: str, run_id: str, *, request_id: str) -> PlanReviewAnswer:
"""Read the expert's answer to ONE named review, fail-closed at every step.
``request_id`` is a required argument rather than something read off the file and trusted: two
reviews of one run share a file name, so an answer left over from the previous round would
otherwise be applied to a plan the expert never saw. A mismatch is REFUSED by name it is a
stale answer, not an absent one, and the two need different words.
A missing file raises rather than returning ``None``: "not answered yet" is the normal state of
this door, and the caller asking to resume has already said it believes otherwise."""
path = _answer_path(review_dir, run_id)
data = _load_json_dict(path)
if data is None:
raise PlanReviewAnswerError(
f"no answer for plan review {request_id} of run {run_id!r} in {review_dir!r} "
f"(expected {path.name}): the review is still waiting on a human"
)
found = str(data.get("request_id", ""))
if found != request_id:
raise PlanReviewAnswerError(
f"the answer in {path.name} answers plan review {found!r}, but the open review of run "
f"{run_id!r} is {request_id!r}. Refused: an answer to another question is not an "
f"answer to this one"
)
decision = str(data.get("decision", ""))
if decision not in _PLAN_REVIEW_ANSWERS:
raise PlanReviewAnswerError(
f"{path.name} answers {decision!r}, which is outside the vocabulary "
f"{sorted(_PLAN_REVIEW_ANSWERS)}. Refused, never read as a sign-off"
)
feedback = str(data.get("feedback", ""))
if decision == "revise" and not feedback.strip():
raise PlanReviewAnswerError(
f"{path.name} answers 'revise' with nothing to revise: the manager would be asked to "
f"replan against an empty instruction. Say what to change, or answer 'approve'"
)
return PlanReviewAnswer(
run_id=run_id, request_id=request_id, decision=decision, feedback=feedback
)
def pending_plan_reviews(outbox_dir: str, review_dir: str) -> list[PendingPlanReview]:
"""Every parked plan review whose OWN answer has not landed, sorted by ``run_id``.
Mirrors ``pending``: an outbox artefact joined against an inbox, with the join on the key each
side names. The key here is ``request_id`` an answer to a different review leaves this one
pending rather than quietly clearing it, which is the same fail-closed rule the resume path
applies and for the same reason.
Tolerant on the READ side (an unreadable file in either folder is not a question and not an
answer), fail-closed on the DECIDE side (``load_plan_review_answer``). The registry says who is
waiting; it never decides what they said."""
waiting: list[PendingPlanReview] = []
directory = Path(outbox_dir)
if not directory.is_dir():
return waiting
for file in sorted(directory.glob("*-plan-review.json")):
data = _load_json_dict(file)
if data is None:
continue
run_id = str(data.get("run_id", ""))
request_id = str(data.get("request_id", ""))
if not run_id or not request_id:
continue
answer = _load_json_dict(_answer_path(review_dir, run_id))
if answer is not None and str(answer.get("request_id", "")) == request_id:
continue
waiting.append(
PendingPlanReview(
run_id=run_id,
request_id=request_id,
index=int(data.get("index", 0)),
plan=str(data.get("plan", "")),
is_stalled=bool(data.get("is_stalled", False)),
)
)
return sorted(waiting, key=lambda p: (p.run_id, p.index))
# --- Routing config: self-contained dimension→expert table (fail-fast) ----------------------------
# A minimal MVP stand-in for the S3.5 dimension catalog (kept DISTINCT — see the plan's Non-Goals).
# Field names mirror ``dimension.Dimension`` so the two reconcile cleanly when S3.5 lands. No ``label``

View file

@ -189,6 +189,35 @@ def write_exploration(
return path
def write_plan_review(
outbox_dir: str,
run_id: str,
*,
payload: Mapping[str, Any],
) -> Path:
"""Write ``{run_id}-plan-review.json`` — the open question of a PARKED exploration (U12) — and
return its path.
This is the outbox half of the asynchronous HITL door: the run writes the question, the expert
writes the answer into a separate review INBOX, days later. The two folders are never the same
one, for the reason the verdict inbox is never the outbox a run that read its own output as
input would be answering itself.
Takes an already-rendered plain mapping (``explore.parked_payload``) for the reason
``write_exploration`` does: ``explore`` imports ``agent_framework`` and this layer stays
MAF-free. Byte-deterministic like its neighbours.
**Last write wins**, exactly one open question per run: a revision produces a NEW review of a
REPLANNED plan, and leaving the superseded one on disk would let an expert answer a question
the loop has already moved past. Staleness is caught anyway the answer names the
``request_id`` it answers but the file should not invite it."""
directory = Path(outbox_dir)
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"{run_id}-plan-review.json"
path.write_text(_dump({"run_id": run_id, **dict(payload)}), encoding="utf-8")
return path
def write_run_config(
config_dir: str,
run_id: str,

View file

@ -61,9 +61,16 @@ from portfolio_optimiser.explore import (
ExplorationContract,
ExplorationResult,
ExplorationTrace,
ParkedStateError,
PlanReviewDecision,
PlanReviewParked,
explore,
exploration_notice,
load_exploration_contract,
load_parked,
parked_notice,
parked_payload,
resume_exploration,
terminal_plan_reviewer,
trace_payload,
)
@ -92,7 +99,7 @@ from portfolio_optimiser.provenance import ProvenanceStamp
from portfolio_optimiser.reference_domain import Project, load_reference_projects
from portfolio_optimiser.tracing import TracingConfigError, configure_tracing, tracing_notice
from portfolio_optimiser.validator import Rejection, ValidatedProposal, baseline_from_project
from portfolio_optimiser import okf, outbox
from portfolio_optimiser import hitl, okf, outbox
from portfolio_optimiser.semretrieval import (
SEMANTIC_WEIGHT_DEFAULT,
Embedder,
@ -1647,6 +1654,37 @@ def main(argv: list[str] | None = None) -> int:
"round trip is recorded in {run_id}-exploration.json, feedback verbatim. Input that ends "
"without an answer is an error, NEVER a sign-off",
)
parser.add_argument(
"--checkpoint-dir",
default=None,
metavar="DIR",
help="U12 ASYNCHRONOUS HITL door (REQUIRES --explore, --explore-config with "
"enable_plan_review, --run-id and --outbox-dir; refused together with --plan-review): "
"instead of blocking on a human at this terminal, park the exploration's plan review to "
"disk. The workflow's checkpoints go here and the question goes to "
"{run_id}-plan-review.json in the outbox; an expert answers days later by dropping "
"{run_id}-plan-review-answer.json into a review inbox, and --resume picks it up",
)
parser.add_argument(
"--review-inbox",
default=None,
metavar="DIR",
help="where the expert drops their answer to a parked plan review (READ-only, and never "
"the same folder as --outbox-dir: a run that read its own output as input would be "
"answering itself). Required by --resume",
)
parser.add_argument(
"--resume",
default=None,
metavar="RUN_ID",
help="resume the exploration parked under RUN_ID (REQUIRES --checkpoint-dir and "
"--review-inbox): read the open question from the outbox, the answer from the review "
"inbox, and drive the exploration onward in THIS process. The prompt, the bounds and the "
"knowledge bases are read from the parked state, not from argv — the workflow has to be "
"rebuilt exactly as it was for the checkpoint to be accepted at all. A revision makes the "
"manager replan and park a NEW question; an approval lets the run continue into the "
"pipeline as usual",
)
parser.add_argument(
"--mcp-config",
default=None,
@ -1793,6 +1831,11 @@ def main(argv: list[str] | None = None) -> int:
# this list is silently dropped rather than refused — which is the whole reason the
# list enumerates every distinguishable flag instead of the ones that would misbehave.
"--plan-review": args.plan_review,
# The three U12 flags, listed for exactly that reason: report mode returns before the
# resume dispatch, so an omission here is a silent drop, not a refusal.
"--checkpoint-dir": args.checkpoint_dir is not None,
"--review-inbox": args.review_inbox is not None,
"--resume": args.resume is not None,
}
if any(report_forbidden.values()):
print(
@ -1843,6 +1886,11 @@ def main(argv: list[str] | None = None) -> int:
# --explore" would tell an operator who wrote --portfolio --plan-review to add the one
# flag this mode also refuses.
"--plan-review": args.plan_review,
# And the asynchronous half of the same door, on the same side of the partition and by
# NAME for the same reason.
"--checkpoint-dir": args.checkpoint_dir,
"--review-inbox": args.review_inbox,
"--resume": args.resume,
}
offending = [name for name, value in single_only.items() if value]
if offending:
@ -1952,6 +2000,108 @@ def main(argv: list[str] | None = None) -> int:
file=sys.stderr,
)
return 1
# --- U12, the asynchronous half. Every refusal names its flags, and every one of them fires
# BEFORE the first model call: a resume that is going to be refused must be refused while it
# is still free (the økt-57 hoist), and a park that cannot write its question must not run at
# all — the whole point of the door is that somebody can answer it afterwards.
if args.checkpoint_dir is not None and args.plan_review:
print(
"run refused: --plan-review and --checkpoint-dir are two doors onto one review — the "
"first answers it at this terminal, the second parks it for another process. Refused "
"rather than ranked: silently preferring either would block an operator who asked for "
"the other",
file=sys.stderr,
)
return 1
if args.resume is not None:
if args.explore is not None:
print(
"run refused: --resume and --explore are two sources of one exploration. --resume "
"continues the one recorded in the parked state (its own prompt, bounds and "
"bases); --explore starts a new one. Merging would silently drop a prompt",
file=sys.stderr,
)
return 1
if args.mandate is not None:
print(
"run refused: --resume and --mandate are two sources of one mandate — the resumed "
"exploration SHAPES one (the --explore + --mandate refusal, one time-scale later)",
file=sys.stderr,
)
return 1
if args.run_id is not None:
print(
"run refused: --resume and --run-id are two sources of one run id. --resume names "
"the parked run, and the resumed leg keeps writing under that same id",
file=sys.stderr,
)
return 1
if args.live_dry_run:
print(
"run refused: --resume and --live-dry-run contradict each other (the drill stops "
"before the first model call; resuming an exploration is model calls) — pick one",
file=sys.stderr,
)
return 1
if args.checkpoint_dir is None:
print(
"run refused: --resume requires --checkpoint-dir (the workflow state a resume "
"restores from lives there; without it there is nothing to resume)",
file=sys.stderr,
)
return 1
if args.review_inbox is None:
print(
"run refused: --resume requires --review-inbox (the expert's answer lives there, "
"and a resume with no answer would have to invent one)",
file=sys.stderr,
)
return 1
if not args.outbox_dir:
print(
"run refused: --resume requires --outbox-dir (the open question was written "
"there as {run_id}-plan-review.json, and it is what names the review to answer)",
file=sys.stderr,
)
return 1
if not args.bundle_dir:
print(
"run refused: --resume requires --bundle-dir (the resumed exploration navigates "
"knowledge bases, exactly as the parked one did)",
file=sys.stderr,
)
return 1
# ONE run id across the suspension. --run-id was refused above precisely so this
# assignment is the only source, and the resumed leg keeps writing under the id the parked
# leg used — an artefact set split across two ids would describe two runs that never were.
args.run_id = args.resume
elif args.checkpoint_dir is not None and args.explore is None:
print(
"run refused: --checkpoint-dir requires --explore (to park a plan review) or --resume "
"(to lift one); on its own it names a folder nothing would ever be written to",
file=sys.stderr,
)
return 1
if args.review_inbox is not None and args.resume is None:
print(
"run refused: --review-inbox requires --resume (the answers there are read by a "
"resume and by nothing else, so the folder would be named and never opened)",
file=sys.stderr,
)
return 1
if args.checkpoint_dir is not None and args.explore is not None:
# The HOIST again, and it is the one that matters most here: the question artefact IS the
# asynchronous door. Without somewhere to write it the exploration would spend its whole
# budget and then have no way to say what it stopped to ask — a park indistinguishable
# from a crash, days before anybody noticed.
if not args.outbox_dir or not args.run_id:
print(
"run refused: --checkpoint-dir requires --outbox-dir and --run-id, settled BEFORE "
"the exploration runs: the parked question is written as "
"{run_id}-plan-review.json, and without it the review could never be answered",
file=sys.stderr,
)
return 1
if args.explore_config is not None and args.explore is None:
print(
"run refused: --explore-config requires --explore (the bounds describe an exploration "
@ -2022,7 +2172,19 @@ def main(argv: list[str] | None = None) -> int:
# The two messages share the token ``enable_plan_review`` and must NOT share their
# distinguishing wording: a test asserting on the shared substring passes against a
# surface missing one of the branches entirely (measured in økt 57 on --explore).
if exploration_contract.enable_plan_review and not args.plan_review:
if args.checkpoint_dir is not None and not exploration_contract.enable_plan_review:
print(
"run refused: --checkpoint-dir was given but --explore-config sets "
"enable_plan_review false, so nothing would ever park and the checkpoints would "
"be written and never read (refused, never silently ignored)",
file=sys.stderr,
)
return 1
if (
exploration_contract.enable_plan_review
and not args.plan_review
and args.checkpoint_dir is None
):
# The refusal SURVIVES F4 — a run must never stop at a review nobody can answer — but
# its old wording ("the synchronous door is the library API") stopped being true the
# moment this CLI grew one, so it names the flag instead. A claim a surface makes about
@ -2030,7 +2192,8 @@ def main(argv: list[str] | None = None) -> int:
print(
"run refused: --explore-config sets enable_plan_review but no reviewer was "
"offered, so the run would stop at a review nobody can answer. Add --plan-review "
"to answer it at this terminal, or set enable_plan_review to false",
"to answer it at this terminal, or --checkpoint-dir to park it for an expert to "
"answer later, or set enable_plan_review to false",
file=sys.stderr,
)
return 1
@ -2093,7 +2256,13 @@ def main(argv: list[str] | None = None) -> int:
# door must know about them BEFORE loading the file, or a missing one crashes deep inside
# ``explore()`` instead of being refused here, at the door, by name.
required_scripted_roles: Sequence[str] = _SCRIPTED_ROLES
if args.explore is not None:
if args.explore is not None or args.resume is not None:
# ``--resume`` rebuilds the SAME workflow with the SAME three participants, so it needs
# the same three replies. Measured, not reasoned: without ``--resume`` here the child
# process died on ``KeyError: 'navigator'`` deep inside ``fresh_exploration_workflow``
# — the identical defect MAJOR-2 closed for ``--explore`` in økt 62, reappearing on the
# second surface that builds an exploration. A gate that names one door and not the
# other is the drift this comment exists to stop happening a third time.
required_scripted_roles = _SCRIPTED_ROLES + _EXPLORATION_SCRIPTED_ROLES
try:
replies = _load_scripted_replies(args.scripted_replies, required_scripted_roles)
@ -2120,27 +2289,86 @@ def main(argv: list[str] | None = None) -> int:
# marked hypothesis, an exhausted budget, and (since F4) a plan review the operator left
# unanswered — is the RUN failing, not the caller erring, and leaves as it does for the debate
# today.
if args.explore is not None:
assert (
exploration_contract is not None
) # guarded above: --explore requires --explore-config
# The resume's two loads happen HERE, before the trace block below: they are refusals, and a
# refusal must not first overwrite {run_id}-exploration.json with an empty trace — the record
# of what the PARKED leg did is the only evidence of the run so far. This is also the økt-57
# hoist in its purest form: not answered yet is the NORMAL state of this door, so it has to be
# free. Both errors are ``ValueError``s (``PlanReviewAnswerError``) or ``ExplorationError``
# (``ParkedStateError``), and both are caught by NAME rather than left to escape as tracebacks.
resumed: tuple[Any, PlanReviewDecision] | None = None
if args.resume is not None:
question = hitl.read_plan_review_question(args.outbox_dir, args.resume)
if question is None:
print(
f"run refused: no parked plan review for run {args.resume!r} in "
f"{args.outbox_dir!r} (expected {args.resume}-plan-review.json) — there is "
f"nothing to resume",
file=sys.stderr,
)
return 1
try:
parked_state = load_parked(question)
answer = hitl.load_plan_review_answer(
args.review_inbox, args.resume, request_id=parked_state.request_id
)
except (hitl.PlanReviewAnswerError, ParkedStateError) as exc:
print(f"run refused: {exc}", file=sys.stderr)
return 1
resumed = (
parked_state,
PlanReviewDecision.approve()
if answer.decision == "approve"
else PlanReviewDecision.revise(answer.feedback),
)
if args.explore is not None or resumed is not None:
exploration_trace = ExplorationTrace()
exploration: ExplorationResult | None = None
parked_now: PlanReviewParked | None = None
try:
exploration = asyncio.run(
explore(
args.explore,
contract=exploration_contract,
bundle_dirs=(args.bundle_dir,),
profile=args.profile,
client_factory=scripted_client_factory,
trace=exploration_trace,
# The F4 door. Built here and never inside ``explore()``: the loop owns the
# seam, the CLI owns which reviewer fills it, and a library that reached for
# stdin on its own would answer for a caller that never offered to.
plan_reviewer=terminal_plan_reviewer() if args.plan_review else None,
if resumed is not None:
# The parked state, not argv, is what rebuilds the workflow: the graph has to match
# the checkpoint's signature for the restore to be accepted at all, so an operator
# who had to re-supply the prompt and the bounds could get one wrong and find out
# as a restore failure days later.
parked_state, decision = resumed
exploration = asyncio.run(
resume_exploration(
parked_state,
decision,
checkpoint_dir=args.checkpoint_dir,
profile=args.profile,
client_factory=scripted_client_factory,
trace=exploration_trace,
)
)
)
else:
assert (
exploration_contract is not None
) # guarded above: --explore requires --explore-config
exploration = asyncio.run(
explore(
args.explore,
contract=exploration_contract,
bundle_dirs=(args.bundle_dir,),
profile=args.profile,
client_factory=scripted_client_factory,
trace=exploration_trace,
# The F4 door. Built here and never inside ``explore()``: the loop owns the
# seam, the CLI owns which reviewer fills it, and a library that reached
# for stdin on its own would answer for a caller that never offered to.
plan_reviewer=terminal_plan_reviewer() if args.plan_review else None,
# The U12 door. Mutually exclusive with the one above, refused at the top.
checkpoint_dir=args.checkpoint_dir,
)
)
except PlanReviewParked as parked_exc:
# NOT an error, and not a completed run either — the third channel, for the reason
# ``BudgetExceeded`` has its own: the exploration produced no mandate, so returning one
# would let a caller book "explored" for a loop suspended mid-plan. Caught here rather
# than left to escape, because parking is what the operator ASKED for by giving
# --checkpoint-dir; the artefact is where a machine reads that it happened.
parked_now = parked_exc
finally:
# From a ``finally``, exactly as ``write_parse_failures`` is (Fase 1b, funn 1): the run
# that most needs this evidence is the one a cap cut short, and that run returns
@ -2156,6 +2384,13 @@ def main(argv: list[str] | None = None) -> int:
completed=exploration is not None,
),
)
if parked_now is not None:
outbox.write_plan_review(
args.outbox_dir, args.run_id, payload=parked_payload(parked_now.parked)
)
print(parked_notice(parked_now.parked, run_id=args.run_id))
return 0
assert exploration is not None # the only other way out of the block above is an exception
print(exploration_notice(exploration))
mandate = exploration.mandate