band-aider-pub/band_aider/loop/sovereign_loop.py
2026-10-17 11:57:37 -07:00

521 lines
20 KiB
Python

from __future__ import annotations
from pathlib import Path
from band_aider.ai_client import llm_logging
from band_aider.ai_client.openai_compatible_client import OpenAICompatibleClient
from band_aider.context.context_factory import context_factory
from band_aider.context.global_context import GlobalContext, SovereignState, StoryCursor
from band_aider.context.provenance import Provenance
from band_aider.context.resume_state import resume_settings
from band_aider.judgement.broad_or_narrow_check import BroadOrNarrowCheckFactory, SearchPolicy
from band_aider.judgement.code_editor import CodeEditor
from band_aider.judgement.code_parser import CodeParser
from band_aider.judgement.intent_check import IntentCheckFactory
from band_aider.judgement.parser_factory import ParserFactory
from band_aider.judgement.repo_exec import RepoExec
from band_aider.judgement.source_discovery_strategy import SourceDiscoveryStrategy
from band_aider.judgement.story_decomposition_check import PromptToStoriesCheckFactory
from band_aider.judgement.prompt_formatter import PromptFormatterBuilder
from band_aider.reporting.change_report_writer import ChangeReportWriter
from band_aider.loop.loop_gate import LoopGate
from band_aider.loop.mechanical_loop_gate import MechanicalLoopGate
from band_aider.loop.proto_loop import ProtoLoop
from band_aider.loop.supreme_loop import SupremeLoop
from band_aider.strategies import LanguageStrategySet, language_strategy_set_factory
from band_aider.ui.status import publish_story_status
class SovereignLoop(ProtoLoop[LoopGate, GlobalContext]):
"""Govern ordered stories and own one SupremeLoop child per active story."""
provenance: Provenance
@property
def story_cursor(self) -> StoryCursor:
"""Return the active story cursor."""
cursor = self.context.story_cursor
return cursor
def __init__(
self,
*,
original_prompt: str,
client: OpenAICompatibleClient,
repo_root: Path,
src_root: Path,
test_root: Path,
actor: str,
intent_check_factory: IntentCheckFactory,
aider_worker: CodeEditor | None,
repo_exec: RepoExec,
language: str,
prompt_formatter_builder: PromptFormatterBuilder,
logger=None,
) -> None:
"""Create a gated outer loop with a non-operational context until story setup begins."""
self.original_prompt = original_prompt
self.client = client
self.repo_root = repo_root
self.src_root = src_root
self.test_root = test_root
self.actor = actor
self.intent_check_factory = intent_check_factory
self.aider_worker = aider_worker
self.repo_exec = repo_exec
self.language = language
self.prompt_formatter_builder = prompt_formatter_builder
placeholder = GlobalContext(
goal=original_prompt,
parser=object(), # type: ignore[arg-type]
client=client,
repo_root=repo_root,
src_root=src_root,
test_root=test_root,
actor=actor,
prompt_formatter_builder=prompt_formatter_builder,
intent_check_factory=intent_check_factory,
original_prompt=original_prompt,
)
self._prepared = False
self.story_results: list[str] = []
self.story_tasks: list[str] = []
self.provenance = Provenance.open(
repo_root=repo_root,
repo_exec=repo_exec,
resume=resume_settings().hydrate,
)
super().__init__(
gate=MechanicalLoopGate(
context=placeholder,
may_enter=lambda: True,
should_continue=lambda: False,
),
context=placeholder,
logger=logger,
)
def run(self, logger_name: str | None = None) -> str:
"""Route resume before gate entry, then use normal gate control for each new story."""
if not self._logger_stack:
self._logger_stack.append(llm_logging.logger_for_loop(self))
if logger_name:
self._logger_stack.append(self.logger.getChild(llm_logging.safe_log_segment(logger_name)))
llm_logging.set_current_logger(self.logger)
try:
if not hasattr(self, "story_results"):
self.story_results = []
if not hasattr(self, "story_tasks"):
self.story_tasks = []
if resume_settings().hydrate:
resume_result = self._resume_existing_supreme()
if resume_result is not None:
return resume_result
while True:
result = super().run()
if self.context.supreme_completion_state not in (
SovereignState.BETWEEN_STORIES,
SovereignState.SUPREME_FINISHED_UNREPORTED,
):
return result
self.story_results.append(result)
self.story_tasks.extend(
record.task
for record in self.context.story_cursor.cot_task_records
if record.task.strip()
)
self._advance_story()
self._prepared = False
publish_story_status(self.context)
if self.story_cursor.sovereign_phase == SovereignState.COMPLETED:
final_result = self._aggregate_story_results()
self._write_final_report(final_result)
self.context.supreme_result = final_result
self.context.supreme_completion_state = (
SovereignState.SUPREME_FINISHED_UNREPORTED
)
self.context.persist()
self._consume_finished_supreme()
return final_result
finally:
if logger_name:
self._logger_stack.pop()
llm_logging.set_current_logger(self.logger if self._logger_stack else None)
def _resume_existing_supreme(self) -> str | None:
"""Hydrate the durable route and immediately run an active Supreme child once."""
checkpoint = context_factory.latest_payload_for(GlobalContext)
if checkpoint is None:
return None
self._restore_prompt(checkpoint)
active_checkpoint_matches = self._active_supreme_checkpoint_matches(checkpoint)
if active_checkpoint_matches:
thawed = self._thaw_supreme_loop(checkpoint)
if thawed is None:
return None
payload, child = thawed
self.context = payload
self.gate.context = payload
publish_story_status(payload)
self._run(child)
result = payload.supreme_result
if (
payload.supreme_completion_state
== SovereignState.SUPREME_FINISHED_UNREPORTED
):
self._consume_finished_supreme()
self._advance_story()
self._prepared = False
publish_story_status(self.context)
if payload.story_cursor.sovereign_phase == SovereignState.COMPLETED:
return result
return None
return result
payload = self._thaw_supreme_context(checkpoint)
if payload is None:
return None
self.context = payload
self.gate.context = payload
publish_story_status(payload)
if payload.story_cursor.sovereign_phase == SovereignState.COMPLETED:
return str(payload.supreme_result)
if (
payload.supreme_completion_state == SovereignState.BETWEEN_STORIES
or payload.story_cursor.sovereign_phase == SovereignState.BETWEEN_STORIES
):
self._advance_story()
self._prepared = False
publish_story_status(self.context)
if self.story_cursor.sovereign_phase == SovereignState.COMPLETED:
return None
return None
if payload.supreme_completion_state == SovereignState.SUPREME_FINISHED_UNREPORTED:
self._consume_finished_supreme()
self._advance_story()
self._prepared = False
publish_story_status(self.context)
if payload.story_cursor.sovereign_phase == SovereignState.COMPLETED:
return payload.supreme_result
return None
return None
def _prepare_work(self) -> ProtoLoop | None:
"""Create and persist one fresh story context and return its Supreme child."""
if self._prepared:
return None
stories = self._stories_for_new_run()
story_index = self.story_cursor.current_story_index
story = stories[story_index]
policy = self._classify_story(story)
parser_factory = self._parser_factory_for_policy(policy)
parser = parser_factory()
context = self._create_supreme_context(
story=story,
stories=stories,
story_index=story_index,
policy=policy,
parser=parser,
parser_factory=parser_factory,
)
context.logger = self.logger.getChild("supreme")
context.sync()
self.logger.info(
"[probe] SupremeLoop context.sync complete relevant=%s intent=%s",
len(getattr(context, "relevant_files", ())),
context.intent,
)
context.file_manager.capture_frozen_once()
context.story_cursor.sovereign_phase = SovereignState.SUPREME_ACTIVE
context.supreme_completion_state = SovereignState.SUPREME_ACTIVE
context.persist()
self.context = context
self.gate.context = context
child = self._create_supreme_loop(context, parser)
self._prepared = True
publish_story_status(context)
return child
def _post_run(self) -> str:
"""Return the durable Supreme result after the one gate-controlled child run."""
return str(getattr(self.context, "supreme_result", ""))
def _aggregate_story_results(self) -> str:
"""Aggregate all story summaries into one final run result."""
successful = all(
map(lambda result: result.lstrip().startswith("SUCCESS"), self.story_results)
)
outcome = "SUCCESS" if successful else "FAILED"
return f"{outcome}: " + " | ".join(self.story_results)
def _write_final_report(self, result: str) -> None:
"""Write exactly one report after every story has completed."""
writer = ChangeReportWriter(repo_root=self.context.repo_root)
writer.write(
original_job=self.original_prompt,
cot_tasks=self.story_tasks,
file_manager=self.context.file_manager,
final_summary=result,
)
def _stories_for_new_run(self) -> list[str]:
"""Decompose exactly once for a fresh outer context and retain source order."""
if self.context.stories:
return list(self.context.stories)
stories = PromptToStoriesCheckFactory(
self.client,
self.prompt_formatter_builder,
).create(self.original_prompt)()
if not stories:
stories = [self.original_prompt]
self.context.stories = list(stories)
self.story_cursor.current_story_index = 0
self.story_cursor.active_story = stories[0]
self.story_cursor.sovereign_phase = SovereignState.BETWEEN_STORIES
self.context.supreme_completion_state = SovereignState.BETWEEN_STORIES
self.context.persist()
publish_story_status(self.context)
return list(stories)
def _create_supreme_context(
self,
*,
story: str,
stories: list[str],
story_index: int,
policy: SearchPolicy,
parser: CodeParser,
parser_factory: ParserFactory,
) -> GlobalContext:
"""Create one fresh GlobalContext using the existing context factory."""
return context_factory.create(
GlobalContext,
goal=story,
parser=parser,
client=self.client,
repo_root=self.repo_root,
src_root=self.src_root,
test_root=self.test_root,
actor=self.actor,
prompt_formatter_builder=self.prompt_formatter_builder,
intent_check_factory=self.intent_check_factory,
original_prompt=self.original_prompt,
search_anchors=tuple(policy.anchors),
parser_factory=parser_factory,
repo_exec=self.repo_exec,
stories=stories,
current_story_index=story_index,
active_story=story,
search_policy_scope=policy.scope,
search_policy_reason=policy.reason,
)
def _thaw_supreme_context(
self,
checkpoint: dict[str, object],
) -> GlobalContext | None:
"""Thaw the matching GlobalContext exactly once for an active Supreme child."""
stories = self._normalized_stories(checkpoint)
if not stories:
return None
story_cursor = checkpoint["story_cursor"]
if not isinstance(story_cursor, StoryCursor):
return None
index = story_cursor.current_story_index
story = str(
story_cursor.active_story
or checkpoint["goal"]
or stories[index]
)
parser_factory = self._parser_factory_for_policy(checkpoint)
parser = parser_factory()
return context_factory.thaw(
GlobalContext,
goal=story,
parser=parser,
parser_factory=parser_factory,
client=self.client,
repo_root=self.repo_root,
src_root=self.src_root,
test_root=self.test_root,
actor=self.actor,
prompt_formatter_builder=self.prompt_formatter_builder,
intent_check_factory=self.intent_check_factory,
original_prompt=self.original_prompt,
search_anchors=tuple(checkpoint["search_anchors"]),
repo_exec=self.repo_exec,
)
def _create_supreme_loop(self, context: GlobalContext, parser: CodeParser) -> SupremeLoop:
"""Create Supreme around the exact context selected by Sovereign."""
return SupremeLoop(
context=context,
goal=context.goal,
parser=parser,
client=self.client,
repo_root=self.repo_root,
src_root=self.src_root,
test_root=self.test_root,
actor=self.actor,
intent_check_factory=self.intent_check_factory,
prompt_formatter_builder=self.prompt_formatter_builder,
original_prompt=self.original_prompt,
aider_worker=self.aider_worker,
search_anchors=tuple(context.search_anchors),
parser_factory=context.parser_factory,
provenance=self.provenance,
logger=self.logger.getChild("supreme"),
)
def _thaw_supreme_loop(
self,
checkpoint: dict[str, object],
) -> tuple[GlobalContext, SupremeLoop] | None:
"""Thaw one GlobalContext and create Supreme around that exact context once."""
context = self._thaw_supreme_context(checkpoint)
if context is None:
return None
return context, self._create_supreme_loop(context, context.parser)
def _parser_factory_for_policy(
self,
policy: SearchPolicy | dict[str, object],
) -> ParserFactory:
"""Build parser and discovery wiring from a fresh or persisted policy.
Fresh stories supply the normalized ``SearchPolicy`` returned by the
broad/narrow check. Hydration supplies the raw checkpoint only so the
persisted ``StoryCursor`` and anchors can be reused without running
classification again.
"""
if isinstance(policy, SearchPolicy):
scope = policy.scope
anchors_value = policy.anchors
else:
story_cursor = policy["story_cursor"]
scope = story_cursor.search_policy_scope
anchors_value = policy["search_anchors"]
anchors = tuple(str(anchor) for anchor in anchors_value)
builder = language_strategy_set_factory.build_language_set(self.language)
LanguageStrategySet.set_instance(
lambda file_manager, **overrides: builder(
file_manager,
repo_exec=self.repo_exec,
**overrides,
)
)
strategy_context = type(
"ParserStrategyContext",
(),
{
"repo_root": self.repo_root,
"src_root": self.src_root,
"test_root": self.test_root,
},
)()
discovery = LanguageStrategySet.get(strategy_context)[SourceDiscoveryStrategy]
return ParserFactory(
self.client,
self.repo_exec,
self.prompt_formatter_builder,
discovery,
scope,
anchors,
semantic_threshold=0.55,
)
def _classify_story(self, story: str) -> SearchPolicy:
"""Run broad/narrow classification exactly once for a newly entered story."""
check = BroadOrNarrowCheckFactory(
self.client,
self.prompt_formatter_builder,
).create(story)
check()
return check.policy
def _consume_finished_supreme(self) -> None:
"""Mark one durable Supreme completion consumed without invoking the child again."""
self.context.supreme_reported = True
def _advance_story(self) -> None:
"""Advance only the durable story coordinate and persist the transition."""
self.story_cursor.current_story_index += 1
self.story_cursor.active_story = (
self.context.stories[self.story_cursor.current_story_index]
if self.story_cursor.current_story_index < len(self.context.stories)
else ""
)
self.story_cursor.sovereign_phase = (
SovereignState.BETWEEN_STORIES
if self.story_cursor.active_story
else SovereignState.COMPLETED
)
self.context.supreme_completion_state = self.story_cursor.sovereign_phase
self.context.persist()
def _active_supreme_checkpoint_matches(
self,
checkpoint: dict[str, object] | None = None,
) -> bool:
"""Return whether one payload describes the current active Supreme story."""
if checkpoint is None:
checkpoint = context_factory.latest_payload_for(GlobalContext) or {}
if "story_cursor" not in checkpoint:
return False
story_cursor = checkpoint["story_cursor"]
if not isinstance(story_cursor, StoryCursor):
return False
if "supreme_completion_state" not in checkpoint:
return False
if "goal" not in checkpoint or "stories" not in checkpoint:
return False
return (
story_cursor.sovereign_phase
== SovereignState.SUPREME_ACTIVE
and SovereignState.coerce(
checkpoint["supreme_completion_state"],
SovereignState.SUPREME_ACTIVE,
)
== SovereignState.SUPREME_ACTIVE
and bool(story_cursor.active_story)
and checkpoint["goal"] == story_cursor.active_story
and isinstance(checkpoint["stories"], list)
)
def _restore_prompt(self, checkpoint: dict[str, object]) -> None:
"""Restore the original reporting prompt when resume omitted a task argument."""
if not self.original_prompt:
self.original_prompt = str(
checkpoint.get("original_prompt")
or checkpoint.get("goal")
or ""
)
def _normalized_stories(self, checkpoint: dict[str, object]) -> list[str]:
"""Return a non-empty persisted story list."""
if "stories" not in checkpoint:
return []
stories = checkpoint["stories"]
if not isinstance(stories, list) or not stories:
return []
return [str(story) for story in stories]