Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions besser/spec_driven_agent/pipeline/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,7 @@ def is_regenerated(generator: str, rel_path: str) -> bool:
# recipe. Untruncated write-tool inputs go to TOOL_INPUTS_FILENAME.
_LOG_VALUE_BUDGET = 500
_WRITE_TOOLS_ON_RECORD = frozenset({"modify_file", "replace_file_lines", "write_file", "delete_file"})

# The stop detail of a Phase 2 the user ended with "Finish now" (``should_finish``).
# Phase 3 then checks and packages; it makes no repair turn.
FINISH_NOW_DETAIL = "finished early at the user's request"
67 changes: 65 additions & 2 deletions besser/spec_driven_agent/pipeline/orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ def _stopped_by(text: str) -> str:

from besser.spec_driven_agent.pipeline.constants import ( # noqa: F401
EXCLUDED_OUTPUT_NAMES,
FINISH_NOW_DETAIL,
WORKSPACE_SKIP_DIRS,
TOOL_INPUTS_FILENAME,
_LOG_VALUE_BUDGET,
Expand Down Expand Up @@ -329,6 +330,13 @@ def _stopped_by(text: str) -> str:
from besser.spec_driven_agent.pipeline.modify_run import MODEL_SYNC_ERRORS, ModifyRunMixin, model_sync_record
from besser.spec_driven_agent.pipeline.phase3_repair import Phase3RepairMixin, clip_finding, counted
from besser.spec_driven_agent.pipeline.regeneration import Regeneration
from besser.spec_driven_agent.pipeline.run_progress import (
PLANNING_STEP,
STARTING_STEP,
StepThrottle,
batch_step,
checklist_items,
)
from besser.spec_driven_agent.settings import AgentSettings

# History eviction (see history_eviction.py): stale file bodies are stubbed in
Expand Down Expand Up @@ -388,6 +396,7 @@ def __init__(
on_text: Callable[[str], None] | None = None,
on_phase_details: Callable[[str, str], None] | None = None,
on_findings: Callable[..., None] | None = None,
on_checklist: Callable[[list[dict]], None] | None = None,
use_streaming: bool = True,
object_model=None,
state_machines=None,
Expand All @@ -396,6 +405,7 @@ def __init__(
nn_model=None,
auto_fix_issues: bool = False,
should_continue: Callable[[], bool] | None = None,
should_finish: Callable[[], bool] | None = None,
primary_kind: str | None = None,
run_id: str = "",
enable_tracing: bool = True,
Expand Down Expand Up @@ -470,6 +480,9 @@ def __init__(
self.on_phase_details = on_phase_details
# Phase 3 reports each validation round: (attempt, issues, restored=False).
self.on_findings = on_findings
# The checklist each time it changes: ``run_progress.checklist_items`` rows.
self.on_checklist = on_checklist
self._checklist_shown: list[dict] | None = None
self.use_streaming = use_streaming
self.executor = ToolExecutor(
workspace=self.output_dir,
Expand Down Expand Up @@ -593,6 +606,9 @@ def __init__(
# to exit cleanly — used by the SSE runner to honour
# ``POST /cancel-smart-gen/{run_id}`` without killing the thread.
self._should_continue = should_continue
# True once the user asked to finish now: Phase 2 hands off to Phase 3 at its next
# turn boundary. Not read after Phase 2.
self._should_finish = should_finish
self.tool_calls_log: list[dict] = []
# ``tool_calls_log`` length at the last snapshot (None: none taken by this process).
self._snapshot_calls: int | None = None
Expand All @@ -615,6 +631,9 @@ def __init__(
# tool is observed.
self._last_modify_warning_path: str | None = None
self._phase2_inspection_handoff = ""
# What the run card says Phase 2 is doing (run_progress.py).
self._work_steps = StepThrottle(
lambda step: self._emit_progress(self.total_turns, "__work_step__", step))
# Escalation for an edit the executor has already rejected and the
# model sends again (see _escalate_repeat_rejection): per path the
# repeat count already acted on.
Expand Down Expand Up @@ -2129,7 +2148,7 @@ def _run_phase2_turns(self, instructions: str, extra_issues: list[str] | None =
domain_model=self.domain_model,
inventory=self._inventory,
llm_client=self.client,
on_progress=self.on_progress,
on_progress=self._planning_progress if self.on_progress else None,
on_phase_details=self.on_phase_details,
generator_failure=self._phase1_failure_reason,
modify_mode=self._modify_mode,
Expand Down Expand Up @@ -2215,6 +2234,7 @@ def _run_phase2_turns(self, instructions: str, extra_issues: list[str] | None =
)
if gap_tasks:
self.executor.set_tasks(gap_tasks)
self._report_checklist()

system = self._build_system_prompt(
instructions=instructions,
Expand Down Expand Up @@ -2271,6 +2291,9 @@ def _run_phase2_turns(self, instructions: str, extra_issues: list[str] | None =
logger.warning("Cancellation requested — stopping Phase 2 loop")
self._phase2_stop_reason = "cancelled"
break
if self._finish_requested():
self._hand_off_at_users_request()
break

# -- Phase 2's share of the time and spend ----------------------
if self.deadline.out_of_time():
Expand All @@ -2290,6 +2313,10 @@ def _run_phase2_turns(self, instructions: str, extra_issues: list[str] | None =
turn + 1, self._tool_calls_executed(), call_limit)

messages = self._maybe_compact(messages)
if turn == start_turn:
self._work_steps.say(STARTING_STEP)
else:
self._work_steps.flush()

try:
response = self._chat_turn(system, messages)
Expand Down Expand Up @@ -2441,9 +2468,13 @@ def _run_phase2_turns(self, instructions: str, extra_issues: list[str] | None =
messages.append({"role": "assistant", "content": response["content"]})

tool_blocks = _tool_use_blocks(response["content"])
self._work_steps.say(batch_step(
[(getattr(block, "name", ""), getattr(block, "input", None)) for block in tool_blocks],
self.executor.open_tasks()))
calls_before, shell_changes = len(self.tool_calls_log), self.executor.shell_edits.change_count()
tool_results = self._execute_tool_blocks(tool_blocks, turn)
messages.append({"role": "user", "content": tool_results})
self._report_checklist()
revision = self._workspace_revision()
source_changed = revision != last_progress_revision
if source_changed:
Expand Down Expand Up @@ -2498,7 +2529,10 @@ def _run_phase2_turns(self, instructions: str, extra_issues: list[str] | None =
+ "\n".join(f" {t['id']}. {t['text']}" for t in open_items) if open_items else "")
+ "</system-reminder>"
)}]})
if handoff:
if self._finish_requested():
handoff = True
self._hand_off_at_users_request()
elif handoff:
self._phase2_stop_reason = "validation_required"
self._phase2_stop_detail = (
f"inspection handoff (no source change for {no_source_progress} "
Expand Down Expand Up @@ -2608,6 +2642,35 @@ def _run_phase2_turns(self, instructions: str, extra_issues: list[str] | None =
self._phase2_stop_reason = "max_turns"
self._phase2_stop_detail = f"turn guard reached ({self._turn_guard()} turns)"

def _finish_requested(self) -> bool:
return self._should_finish is not None and bool(self._should_finish())

def _hand_off_at_users_request(self) -> None:
"""The user asked to finish now: Phase 2 hands off to Phase 3 as the edit handoff does."""
self._phase2_stop_reason = "validation_required"
self._phase2_stop_detail = FINISH_NOW_DETAIL
self._phase2_exited_cleanly = False
logger.warning("Phase 2: %s", self._phase2_stop_detail)

def _report_checklist(self) -> None:
"""Hand the checklist to ``on_checklist`` when it differs from the last one handed over."""
if not self.on_checklist:
return
items = checklist_items(self.executor.task_snapshot())
if items == self._checklist_shown:
return
self._checklist_shown = items
try:
self.on_checklist(items)
except Exception:
logger.debug("on_checklist callback raised; continuing", exc_info=True)

def _planning_progress(self, turn: int, tool: str, status: str, *rest) -> None:
"""``on_progress`` for the planning call: the run card then says what planning does."""
self._emit_progress(turn, tool, status, *rest)
if tool == "gap_analysis":
self._emit_progress(turn, "__planning_step__", PLANNING_STEP)

def _end_phase2_work_share(self, call_limit: int) -> None:
"""Phase 2 made the tool calls it may make: its share, or, with no share
kept for repair, the whole budget, a step limit."""
Expand Down
8 changes: 8 additions & 0 deletions besser/spec_driven_agent/pipeline/phase3_repair.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
from besser.spec_driven_agent.planning.mutation_inventory import build_mutation_manifest, route_serves
from besser.spec_driven_agent.model_serializer import serialize_domain_model, to_prompt_json
from besser.spec_driven_agent.pipeline.constants import (
FINISH_NOW_DETAIL,
_MAX_TOOLCHAIN_FIX_ITERATIONS,
_PHASE3_CREATE_EVIDENCE_REMINDER,
_PHASE3_FIX_CALLS,
Expand Down Expand Up @@ -373,6 +374,8 @@ def _report_findings(self, attempt: int, issues: list[ValidationIssue], restored

Best-effort: a failing listener never stops the repair loop.
"""
# A round settles checklist items from the current tree.
self._report_checklist()
if not self.on_findings:
return
try:
Expand Down Expand Up @@ -466,6 +469,11 @@ def _run_phase3_repair_cycle(self) -> None:
)
self._phase3_exit_reason = "auto-fix disabled"
return
# The user asked the run to stop working: its findings are reported, not repaired.
if self._phase2_stop_detail == FINISH_NOW_DETAIL:
logger.info("Phase 3: %s - issues recorded, no LLM fix loop.", FINISH_NOW_DETAIL)
self._phase3_exit_reason = FINISH_NOW_DETAIL
return

# Auto-fix only consumes BLOCKER issues. Style notes (truncation
# counts) and soft warnings (tsc type hints) are
Expand Down
112 changes: 112 additions & 0 deletions besser/spec_driven_agent/pipeline/run_progress.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""What the run card says the agent is doing while it plans and works.

Each sentence is built from facts the harness has: the phase, the kind of each
tool call, the file it edits and the checklist item that names that file. None
quotes the model's own text, and none needs a model call.
"""

from __future__ import annotations

import posixpath
import time
from typing import Callable

PLANNING_STEP = "Planning the work: making a checklist from the request"
STARTING_STEP = "Starting the work"

_EDIT_TOOLS = frozenset({"write_file", "modify_file", "replace_file_lines", "delete_file"})
_READ_TOOLS = frozenset({"read_file", "list_files", "search_in_files"})
# What a batch runs after its edits, most telling first.
_RUNS = (
("run_command", "running a command the agent wrote"),
("test_api", "testing the app through its API"),
("validate_app", "running the app's checks"),
)
_MAX_PATH_CHARS = 60
# The card lists a checklist this long at most, each item cut to this many characters.
MAX_CHECKLIST_ITEMS = 50
MAX_CHECKLIST_TEXT = 240
# A step stays on the card at least this long, so a fast run of turns does not flicker.
MIN_STEP_SECONDS = 2.0


def _path(args: object) -> str | None:
"""The workspace path a file tool call names, normalized, or None."""
if not isinstance(args, dict):
return None
raw = args.get("path", args.get("file_path"))
if not isinstance(raw, str) or not raw.strip():
return None
return posixpath.normpath(raw.strip().replace("\\", "/"))


def _short(path: str) -> str:
return path if len(path) <= _MAX_PATH_CHARS else "..." + path[-(_MAX_PATH_CHARS - 3):]


def batch_step(calls: list[tuple[str, object]], open_tasks: list[dict]) -> str | None:
"""The sentence for one turn's tool calls, ``(name, input)`` each; None when it says nothing new.

``open_tasks`` are the checklist's open items; an edit to a file one of them
names is said to be work on that item.
"""
names = {name for name, _ in calls}
edited = list(dict.fromkeys(path for name, args in calls if name in _EDIT_TOOLS and (path := _path(args))))
runs = next((text for tool, text in _RUNS if tool in names), None)
if edited:
step = f"Editing {_short(edited[0])}" + (
f" and {len(edited) - 1} more file{'s' if len(edited) > 2 else ''}" if len(edited) > 1 else "")
item = next((task["id"] for task in open_tasks if set(task.get("files") or ()) & set(edited)), None)
if item is not None:
step += f" (checklist item {item})"
return step + (f", then {runs}" if runs else "")
if runs:
return runs[0].upper() + runs[1:]
if any(name.startswith("generate_") for name in names):
return "Running a BESSER generator"
if names & _READ_TOOLS:
return "Reading the code"
return None


def checklist_items(snapshot: list[dict]) -> list[dict]:
"""The checklist as the run card shows it: ``{id, text, state}`` per item, ``state`` one of
``open``, ``done``, ``blocked`` or ``dropped`` (``ToolExecutor.task_snapshot`` rows in)."""
items = []
for task in snapshot[:MAX_CHECKLIST_ITEMS]:
text = str(task.get("text") or "")
state = ("dropped" if task.get("dropped") else "blocked" if task.get("blocked")
else "done" if task.get("done") else "open")
items.append({"id": task.get("id"), "state": state,
"text": text if len(text) <= MAX_CHECKLIST_TEXT else text[:MAX_CHECKLIST_TEXT - 3] + "..."})
return items


class StepThrottle:
"""Sends a step only when it differs from the one shown and that one has been
shown ``min_seconds``; a step held back is sent at the next ``flush``."""

def __init__(self, send: Callable[[str], None], min_seconds: float = MIN_STEP_SECONDS,
clock: Callable[[], float] = time.monotonic):
self._send, self._min, self._clock = send, min_seconds, clock
self._shown: str | None = None
self._shown_at = 0.0
self._pending: str | None = None

def say(self, step: str | None) -> None:
if not step:
return
if step == self._shown:
self._pending = None
elif self._shown is not None and self._clock() - self._shown_at < self._min:
self._pending = step
else:
self._show(step)

def flush(self) -> None:
if self._pending and self._clock() - self._shown_at >= self._min:
self._show(self._pending)

def _show(self, step: str) -> None:
self._shown, self._shown_at, self._pending = step, self._clock(), None
self._send(step)
11 changes: 11 additions & 0 deletions besser/utilities/web_modeling_editor/backend/models/spec_driven.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,15 @@ class RepoRecap(ResponseModel):
commit_count: int


class RunModelResponse(ResponseModel):
"""Body of ``GET /besser_api/spec-driven/download/{run_id}/model``."""

run_id: str
# The run's project with the class diagram its model sync changed: the generation
# request's project, which the push puts in the editor's envelope before it writes it.
project_export: dict


class PushSmartToGitHubResponse(ResponseModel):
"""Response of ``POST /besser_api/spec-driven/push-to-github``."""

Expand Down Expand Up @@ -712,6 +721,8 @@ class SpecDrivenFeaturesResponse(ResponseModel):
event_replay_enabled: bool
cancel_abandoned_runs: bool
disconnected_grace_seconds: int
finish_now_enabled: bool = Field(
description="POST /spec-driven/finish/{run_id} is served: a run can be told to finish now.")


class CatalogModelResponse(ResponseModel):
Expand Down
Loading