From 004eddfb69ee2d862481d4fa245ec8145ce721ec Mon Sep 17 00:00:00 2001 From: ArmSL Date: Wed, 2 Dec 2026 21:55:33 +0100 Subject: [PATCH 1/9] feat(spec-driven): say what the agent is doing while it plans and works The run card named a step only during validation; while the agent planned and worked it showed "Working..." and the last file touched, so a user could not tell editing from writing and running its own scripts. Planning now sends a step, and each Phase 2 turn sends one built from its tool calls: reading the code, editing a named file (with the checklist item that names it), running the app's checks, testing it through its API, running a command the agent wrote. No sentence quotes the model's text. A step stays at least two seconds before the next replaces it. The steps are the existing `step` event on the `gap` and `customize` rows. --- .../pipeline/orchestrator.py | 19 ++- .../pipeline/run_progress.py | 96 ++++++++++++ .../backend/services/spec_driven/runner.py | 23 ++- .../test_run_progress_steps.py | 146 ++++++++++++++++++ .../spec_driven/test_run_trace_events.py | 36 +++++ 5 files changed, 311 insertions(+), 9 deletions(-) create mode 100644 besser/spec_driven_agent/pipeline/run_progress.py create mode 100644 tests/spec_driven_agent/test_run_progress_steps.py diff --git a/besser/spec_driven_agent/pipeline/orchestrator.py b/besser/spec_driven_agent/pipeline/orchestrator.py index 46226f57c..73de78d59 100644 --- a/besser/spec_driven_agent/pipeline/orchestrator.py +++ b/besser/spec_driven_agent/pipeline/orchestrator.py @@ -328,6 +328,7 @@ 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 from besser.spec_driven_agent.settings import AgentSettings # History eviction (see history_eviction.py): stale file bodies are stubbed in @@ -614,6 +615,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. @@ -2120,7 +2124,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, @@ -2281,6 +2285,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) @@ -2432,6 +2440,9 @@ 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}) @@ -2599,6 +2610,12 @@ 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 _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.""" diff --git a/besser/spec_driven_agent/pipeline/run_progress.py b/besser/spec_driven_agent/pipeline/run_progress.py new file mode 100644 index 000000000..e442c2ccb --- /dev/null +++ b/besser/spec_driven_agent/pipeline/run_progress.py @@ -0,0 +1,96 @@ +"""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 +# 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 + + +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) diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py index d6983d840..73abc80a0 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py @@ -2083,6 +2083,12 @@ def on_findings(attempt: int, issues: list, restored: bool = False) -> None: restored=restored, )) + def open_customize_row() -> None: + """Emit the ``customize`` phase marker once, before anything that belongs to it.""" + if not phase_state["customize_sent"]: + phase_state["customize_sent"] = True + _put(PhaseEvent(phase="customize", message="LLM customising generator output")) + def on_progress(turn: int, tool: str, status: str, detail: str | None = None) -> None: # Any tool/phase activity ends the current turn's prose; the @@ -2125,6 +2131,14 @@ def on_progress(turn: int, tool: str, status: str, # What Phase 3 is doing now (a check round, a judge call, a fix attempt). _put(StepEvent(phase="validate", message=status)) return + if tool == "__planning_step__": + _put(StepEvent(phase="gap", message=status)) + return + if tool == "__work_step__": + # What Phase 2 is doing now, on its own row: open it if no tool call has yet. + open_customize_row() + _put(StepEvent(phase="customize", message=status)) + return if tool == "gap_analysis": # Sentinel emitted by gap_analyzer.analyze_gaps_via_llm # right before the planning LLM call. Surfaces the gap @@ -2181,14 +2195,7 @@ def on_progress(turn: int, tool: str, status: str, # turn >= 1 means we're inside the LLM customization loop. # Emit the `customize` phase marker once, before the first # tool_call, so the frontend can show the transition. - if not phase_state["customize_sent"]: - phase_state["customize_sent"] = True - _put( - PhaseEvent( - phase="customize", - message="LLM customising generator output", - ) - ) + open_customize_row() _put(ToolCallEvent(turn=turn, tool=tool, status="executing", detail=detail or None)) diff --git a/tests/spec_driven_agent/test_run_progress_steps.py b/tests/spec_driven_agent/test_run_progress_steps.py new file mode 100644 index 000000000..0003c2a63 --- /dev/null +++ b/tests/spec_driven_agent/test_run_progress_steps.py @@ -0,0 +1,146 @@ +"""The run card says what the agent is doing while it plans and works, not only while it validates. + +An edit run finished its styling in three minutes and spent five more writing and running +its own test scripts; the card showed "Working..." and a file name the whole time. Phase 2 +now names each step from the tool calls it makes: reading the code, editing a named file +(and the checklist item that names it), running the app's checks, running a command the +agent wrote. No sentence quotes the model's own text. +""" + +from __future__ import annotations + +from besser.spec_driven_agent.pipeline import orchestrator as module +from besser.spec_driven_agent.pipeline.orchestrator import LLMOrchestrator +from besser.spec_driven_agent.pipeline.run_progress import ( + PLANNING_STEP, + STARTING_STEP, + StepThrottle, + batch_step, +) +from besser.spec_driven_agent.providers.llm_client import UsageTracker +from tests.spec_driven_agent.test_modify_quiet_handoff import PAGES, STYLES, TASKS, _Block, _Shell, _workspace + +OPEN = [{"id": 2, "text": f"Restyle {STYLES}.", "files": [STYLES]}, {"id": 3, "text": "Add a footer.", "files": []}] + + +def test_an_edit_names_the_file_and_the_checklist_item_that_names_it(): + assert batch_step([("modify_file", {"path": STYLES})], OPEN) == f"Editing {STYLES} (checklist item 2)" + assert batch_step([("write_file", {"path": "frontend/td1.mjs"})], OPEN) == "Editing frontend/td1.mjs" + + +def test_several_edits_and_what_runs_after_them_are_one_sentence(): + calls = [("write_file", {"path": "a.py"}), ("modify_file", {"path": "./b.py"}), ("modify_file", {"path": "a.py"}), + ("validate_app", {})] + assert batch_step(calls, []) == "Editing a.py and 1 more file, then running the app's checks" + assert batch_step([("write_file", {"path": p}) for p in "abc"], []) == "Editing a and 2 more files" + + +def test_what_runs_names_its_kind_never_its_text(): + command = ("run_command", {"command": "node rendercheck.mjs --all"}) + assert batch_step([command], OPEN) == "Running a command the agent wrote" + assert batch_step([("test_api", {"scenario": {"name": "orders"}})], OPEN) == "Testing the app through its API" + assert batch_step([("validate_app", {})], OPEN) == "Running the app's checks" + assert batch_step([("generate_fastapi_backend", {})], OPEN) == "Running a BESSER generator" + assert batch_step([("read_file", {"path": "x"}), ("search_in_files", {"pattern": "y"})], OPEN) == "Reading the code" + + +def test_bookkeeping_alone_changes_nothing(): + assert batch_step([("task_list", {"done": [2]})], OPEN) is None + assert batch_step([], OPEN) is None + + +def test_a_long_path_keeps_its_end(): + path = "frontend/src/" + "nested/" * 12 + "Card.jsx" + step = batch_step([("modify_file", {"path": path})], []) + assert step.endswith("nested/Card.jsx") and len(step) < 80 + + +class _Clock: + now = 0.0 + + def __call__(self): + return self.now + + +def test_the_throttle_holds_a_fast_change_back_until_the_shown_step_has_had_its_time(): + clock, sent = _Clock(), [] + throttle = StepThrottle(sent.append, min_seconds=2.0, clock=clock) + throttle.say("Reading the code") + clock.now = 0.5 + throttle.say("Editing a.py") + throttle.say("Editing b.py") + throttle.flush() + assert sent == ["Reading the code"] + clock.now = 2.5 + throttle.flush() + throttle.say("Editing b.py") + clock.now = 9.0 + throttle.say("Editing b.py") + throttle.flush() + assert sent == ["Reading the code", "Editing b.py"] + + +def test_a_step_back_to_the_shown_one_drops_the_held_one(): + clock, sent = _Clock(), [] + throttle = StepThrottle(sent.append, min_seconds=2.0, clock=clock) + throttle.say("Reading the code") + throttle.say("Editing a.py") + throttle.say("Reading the code") + clock.now = 5.0 + throttle.flush() + assert sent == ["Reading the code"] + + +def _phase2(model, tmp_path, monkeypatch, turns): + """Phase 2 on ``turns``; the ``(tool, status)`` progress it reported.""" + _workspace(tmp_path) + reported: list[tuple[str, str]] = [] + calls = {"n": 0} + + class Client: + model = "mock-model" + usage = UsageTracker("mock-model") + + def chat(self, system, messages, tools): + calls["n"] += 1 + if calls["n"] > len(turns): + return {"stop_reason": "end_turn", "content": []} + return {"stop_reason": "tool_use", "content": [ + _Block(name=name, input=args, id=f"t{calls['n']}c{n}") for n, (name, args) in enumerate(turns[calls["n"] - 1])]} + + def plan(**kw): + kw["on_progress"](0, "gap_analysis", "analyzing") + return list(TASKS) + + orch = LLMOrchestrator(llm_client=Client(), domain_model=model, output_dir=str(tmp_path), max_turns=60, + enable_tracing=False, enable_checkpointing=False, allow_shell_tools=True, + on_progress=lambda turn, tool, status, *rest: reported.append((tool, status))) + orch.executor._shell = _Shell(tmp_path) + orch._work_steps._min = 0 # every change is sent; the throttle has its own tests + monkeypatch.setattr(module, "analyze_gaps_via_llm", plan) + monkeypatch.setattr(orch, "_deterministic_gap_tasks", lambda: []) + monkeypatch.setattr(orch, "_validate_app", lambda: {"issues": [], "blocker_count": 0}) + monkeypatch.setattr(orch, "_build_system_prompt", lambda **kw: "Edit the app") + monkeypatch.setattr(orch, "_maybe_compact", lambda messages: messages) + orch._run_phase2("Make the pages nicer.") + return reported + + +def test_phase2_names_its_planning_and_each_step_of_its_work(simple_library_book_model, tmp_path, monkeypatch): + turns = [[("read_file", {"path": STYLES}), ("read_file", {"path": PAGES[0]})], + [("modify_file", {"path": STYLES, "old_text": "body {}", "new_text": "body { margin: 0 }"})], + [("task_list", {"done": [1]})], + [("run_command", {"command": "printf check > frontend/check.mjs"})], + [("read_file", {"path": PAGES[1]})]] + + reported = _phase2(simple_library_book_model, tmp_path, monkeypatch, turns) + + planning = [status for tool, status in reported if tool == "__planning_step__"] + work = [status for tool, status in reported if tool == "__work_step__"] + assert planning == [PLANNING_STEP] + assert reported.index(("__planning_step__", PLANNING_STEP)) == reported.index(("gap_analysis", "analyzing")) + 1 + assert work == [STARTING_STEP, "Reading the code", f"Editing {STYLES} (checklist item 1)", + "Running a command the agent wrote", "Reading the code"] + # Each step is said before the calls it describes run. + assert reported.index(("__work_step__", "Running a command the agent wrote")) < reported.index( + ("run_command", "executing")) diff --git a/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_trace_events.py b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_trace_events.py index b8cc10e57..684d8e31a 100644 --- a/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_trace_events.py +++ b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_trace_events.py @@ -191,3 +191,39 @@ def test_each_validation_step_is_a_step_event_on_the_validate_row(monkeypatch): assert steps[0][1]["elapsedSeconds"] >= events[opened]["elapsedSeconds"] # A step is not a tool call: the fix attempt's calls are its repairs, nothing else. assert [e["tool"] for e in events if e.get("event") == "tool_call"] == ["read_file", "modify_file", "modify_file"] + + +class _WorkingOrchestrator(_StubOrchestrator): + """Plans, then works: the planning and work steps the orchestrator reports.""" + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self._on_progress = kwargs["on_progress"] + + def run(self, instructions: str) -> str: + progress = self._on_progress + progress(0, "gap_analysis", "analyzing") + progress(0, "__planning_step__", "Planning the work: making a checklist from the request") + progress(0, "__work_step__", "Starting the work") + self.total_turns = 1 + progress(1, "__work_step__", "Editing backend/main.py") + progress(1, "modify_file", "executing", "path=backend/main.py") + progress(1, "__validating__", "") + return self._finish("run") + + +def test_planning_and_work_steps_are_step_events_on_their_own_rows(monkeypatch): + monkeypatch.setattr(runner_module, "LLMOrchestrator", _WorkingOrchestrator) + monkeypatch.setattr(runner_module, "create_llm_client", lambda **_: _FakeClient()) + runner = SmartGenerationRunner(_build_request(), runtime=current_runtime()) + events = [_parse(frame) for frame in asyncio.run(_collect_frames(runner))] + rows = [(i, e["phase"]) for i, e in enumerate(events) if e.get("event") == "phase"] + steps = [(i, e["phase"], e["message"]) for i, e in enumerate(events) if e.get("event") == "step"] + assert [(phase, message) for _, phase, message in steps] == [ + ("gap", "Planning the work: making a checklist from the request"), + ("customize", "Starting the work"), ("customize", "Editing backend/main.py")] + # Each step comes after the row it belongs to opened; the first work step opens the customize row. + for index, phase, _ in steps: + assert max(i for i, p in rows if i < index and p in ("gap", "customize")) == next( + i for i, p in reversed(rows) if i < index and p == phase) + assert [p for _, p in rows].count("customize") == 1 From 0acffe6e239666beebb95ce5b751196bac91baee Mon Sep 17 00:00:00 2001 From: ArmSL Date: Wed, 2 Dec 2026 21:57:00 +0100 Subject: [PATCH 2/9] feat(spec-driven): stream the agent's checklist to the run card The agent works through a checklist (the task_list tool), but the editor only saw it as the planner's text behind a chevron and never learned which items were done, blocked or dropped. A new `checklist` stream event carries the whole checklist, each item with its id, text and state (open, done, blocked, dropped), when planning seeds it, after each Phase 2 turn that changed it, and after a validation round that settled items from the code. It is sent only when the list changed. Older editors ignore the event. --- .../pipeline/orchestrator.py | 27 ++++++++++- .../pipeline/phase3_repair.py | 2 + .../pipeline/run_progress.py | 16 +++++++ .../backend/services/spec_driven/runner.py | 7 +++ .../services/spec_driven/sse_events.py | 20 ++++++++ .../test_run_progress_steps.py | 47 +++++++++++++++++-- .../spec_driven/test_run_trace_events.py | 20 ++++++++ 7 files changed, 135 insertions(+), 4 deletions(-) diff --git a/besser/spec_driven_agent/pipeline/orchestrator.py b/besser/spec_driven_agent/pipeline/orchestrator.py index 73de78d59..ea228cea0 100644 --- a/besser/spec_driven_agent/pipeline/orchestrator.py +++ b/besser/spec_driven_agent/pipeline/orchestrator.py @@ -328,7 +328,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 +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 @@ -388,6 +394,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, @@ -470,6 +477,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, @@ -2210,6 +2220,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, @@ -2446,6 +2457,7 @@ def _run_phase2_turns(self, instructions: str, extra_issues: list[str] | None = 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: @@ -2610,6 +2622,19 @@ 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 _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) diff --git a/besser/spec_driven_agent/pipeline/phase3_repair.py b/besser/spec_driven_agent/pipeline/phase3_repair.py index f3c9bf462..ed76a5cd1 100644 --- a/besser/spec_driven_agent/pipeline/phase3_repair.py +++ b/besser/spec_driven_agent/pipeline/phase3_repair.py @@ -373,6 +373,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: diff --git a/besser/spec_driven_agent/pipeline/run_progress.py b/besser/spec_driven_agent/pipeline/run_progress.py index e442c2ccb..3f7c40797 100644 --- a/besser/spec_driven_agent/pipeline/run_progress.py +++ b/besser/spec_driven_agent/pipeline/run_progress.py @@ -23,6 +23,9 @@ ("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 @@ -66,6 +69,19 @@ def batch_step(calls: list[tuple[str, object]], open_tasks: list[dict]) -> str | 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``.""" diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py index 73abc80a0..09568c4b5 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py @@ -147,6 +147,8 @@ from besser.utilities.web_modeling_editor.backend.services.spec_driven import run_evidence from besser.utilities.web_modeling_editor.backend.services.spec_driven.sse_events import ( BaseSseEvent, + ChecklistEvent, + ChecklistItem, CostEvent, DoneEvent, ErrorEvent, @@ -2071,6 +2073,10 @@ def on_phase_details(phase: str, details: str) -> None: "PhaseUpdateEvent emission failed (phase=%s)", phase, exc_info=True ) + def on_checklist(items: list[dict]) -> None: + """The agent's checklist, for the run card.""" + _put(ChecklistEvent(items=[ChecklistItem(**item) for item in items if isinstance(item.get("id"), int)])) + def on_findings(attempt: int, issues: list, restored: bool = False) -> None: """One Phase 3 validation round, for the run card's findings and repairs.""" # The done event's definition, so the last round and the run's blocker count agree. @@ -2255,6 +2261,7 @@ def should_continue() -> bool: on_text=on_text, on_phase_details=on_phase_details, on_findings=on_findings, + on_checklist=on_checklist, use_streaming=True, should_continue=should_continue, # Carry through the assembled primary so the orchestrator diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py index 924a72392..291ed3503 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py @@ -99,6 +99,26 @@ class StepEvent(BaseSseEvent): elapsedSeconds: Optional[float] = None +ChecklistState = Literal["open", "done", "blocked", "dropped"] + + +class ChecklistItem(BaseModel): + """One item of the agent's checklist (the ``task_list`` tool's items).""" + + id: int + text: str + state: ChecklistState + + +class ChecklistEvent(BaseSseEvent): + """The agent's checklist, whole, each time it changes: when planning seeds it, after a + Phase 2 turn that changed it, and after a validation round settled items from the code. + ``items`` is capped (``run_progress.MAX_CHECKLIST_ITEMS``) and each text clipped.""" + + event: Literal["checklist"] = "checklist" + items: list[ChecklistItem] = Field(default_factory=list) + + class TextDeltaEvent(BaseSseEvent): """A streaming text delta from the underlying LLM response. diff --git a/tests/spec_driven_agent/test_run_progress_steps.py b/tests/spec_driven_agent/test_run_progress_steps.py index 0003c2a63..deed9a310 100644 --- a/tests/spec_driven_agent/test_run_progress_steps.py +++ b/tests/spec_driven_agent/test_run_progress_steps.py @@ -91,8 +91,9 @@ def test_a_step_back_to_the_shown_one_drops_the_held_one(): assert sent == ["Reading the code"] -def _phase2(model, tmp_path, monkeypatch, turns): - """Phase 2 on ``turns``; the ``(tool, status)`` progress it reported.""" +def _phase2(model, tmp_path, monkeypatch, turns, checklists=None): + """Phase 2 on ``turns``; the ``(tool, status)`` progress it reported. Each checklist it + reported is appended to ``checklists``.""" _workspace(tmp_path) reported: list[tuple[str, str]] = [] calls = {"n": 0} @@ -114,7 +115,8 @@ def plan(**kw): orch = LLMOrchestrator(llm_client=Client(), domain_model=model, output_dir=str(tmp_path), max_turns=60, enable_tracing=False, enable_checkpointing=False, allow_shell_tools=True, - on_progress=lambda turn, tool, status, *rest: reported.append((tool, status))) + on_progress=lambda turn, tool, status, *rest: reported.append((tool, status)), + on_checklist=None if checklists is None else checklists.append) orch.executor._shell = _Shell(tmp_path) orch._work_steps._min = 0 # every change is sent; the throttle has its own tests monkeypatch.setattr(module, "analyze_gaps_via_llm", plan) @@ -144,3 +146,42 @@ def test_phase2_names_its_planning_and_each_step_of_its_work(simple_library_book # Each step is said before the calls it describes run. assert reported.index(("__work_step__", "Running a command the agent wrote")) < reported.index( ("run_command", "executing")) + + +def test_the_checklist_is_reported_when_planning_seeds_it_and_each_time_a_turn_changes_it( + simple_library_book_model, tmp_path, monkeypatch): + turns = [[("read_file", {"path": STYLES})], + [("task_list", {"done": [1], "drop": [{"id": 5, "reason": "not asked for"}]})], + [("read_file", {"path": PAGES[0]})], + [("task_list", {"blocked": [{"id": 2, "reason": "the page has no list"}]})]] + checklists: list = [] + + _phase2(simple_library_book_model, tmp_path, monkeypatch, turns, checklists) + + states = [[item["state"] for item in checklist] for checklist in checklists] + assert states == [["open"] * 5, + ["done", "open", "open", "open", "dropped"], + ["done", "blocked", "open", "open", "dropped"]] + assert [item["text"] for item in checklists[0]] == TASKS + assert [item["id"] for item in checklists[0]] == [1, 2, 3, 4, 5] + + +def test_a_long_item_is_clipped_for_the_card(): + from besser.spec_driven_agent.pipeline.run_progress import MAX_CHECKLIST_TEXT, checklist_items + + [item] = checklist_items([{"id": 1, "text": "x" * 1000, "done": False, "blocked": False}]) + assert len(item["text"]) == MAX_CHECKLIST_TEXT and item["text"].endswith("...") + + +def test_a_validation_round_reports_the_items_it_settled(simple_library_book_model, tmp_path): + checklists: list = [] + orch = LLMOrchestrator(llm_client=object(), domain_model=simple_library_book_model, output_dir=str(tmp_path), + enable_tracing=False, enable_checkpointing=False, on_checklist=checklists.append) + orch.executor.set_tasks(["Add a stats route.", "Add a footer."]) + orch._report_findings(0, []) + orch._report_findings(1, []) + orch.executor._tasks[0]["done"] = True # a round closes an item whose check now passes + orch._report_findings(2, []) + + assert [[item["state"] for item in checklist] for checklist in checklists] == [["open", "open"], + ["done", "open"]] diff --git a/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_trace_events.py b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_trace_events.py index 684d8e31a..e9d6afe23 100644 --- a/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_trace_events.py +++ b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_trace_events.py @@ -227,3 +227,23 @@ def test_planning_and_work_steps_are_step_events_on_their_own_rows(monkeypatch): assert max(i for i, p in rows if i < index and p in ("gap", "customize")) == next( i for i, p in reversed(rows) if i < index and p == phase) assert [p for _, p in rows].count("customize") == 1 + + +def test_the_checklist_is_a_checklist_event(monkeypatch): + class _Listing(_StubOrchestrator): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self._on_checklist = kwargs["on_checklist"] + + def run(self, instructions: str) -> str: + self._on_checklist([{"id": 1, "text": "Add a stats route.", "state": "done"}, + {"id": 2, "text": "Add a footer.", "state": "open"}]) + return self._finish("run") + + monkeypatch.setattr(runner_module, "LLMOrchestrator", _Listing) + monkeypatch.setattr(runner_module, "create_llm_client", lambda **_: _FakeClient()) + runner = SmartGenerationRunner(_build_request(), runtime=current_runtime()) + events = [_parse(frame) for frame in asyncio.run(_collect_frames(runner))] + [event] = [e for e in events if e.get("event") == "checklist"] + assert event["items"] == [{"id": 1, "text": "Add a stats route.", "state": "done"}, + {"id": 2, "text": "Add a footer.", "state": "open"}] From 675f245bd1a4ebe94377b51965917d1a38ab8a90 Mon Sep 17 00:00:00 2001 From: ArmSL Date: Wed, 2 Dec 2026 22:03:07 +0100 Subject: [PATCH 3/9] feat(spec-driven): let the user tell a run to finish now A user who saw a run keep working after the asked change was done could only cancel it, and a cancelled run is neither checked nor packaged as a finished result. POST /spec-driven/finish/{run_id} sets a flag the Phase 2 loop reads at its next turn boundary; Phase 2 then hands off to Phase 3 through the same path as the edit handoff, with its own stop detail, so the result is still validated and packaged. It works for create and edit runs and changes nothing once validation has started. The run record says "finished early at the user's request" and lists the checklist items left not done, as does BESSER_GENERATION.md; the done event carries `finishedEarly`. The config advertises the endpoint as `features.finish_now_enabled`. --- .../pipeline/orchestrator.py | 26 ++++++- .../backend/models/spec_driven.py | 2 + .../backend/routers/spec_driven_router.py | 29 ++++++++ .../services/spec_driven/run_record.py | 24 +++++- .../backend/services/spec_driven/runner.py | 18 ++++- .../backend/services/spec_driven/runtime.py | 17 +++++ .../services/spec_driven/sse_events.py | 3 + tests/spec_driven_agent/scripted_rig.py | 3 +- tests/spec_driven_agent/test_finish_now.py | 60 +++++++++++++++ .../backend/spec_driven/test_run_record.py | 73 +++++++++++++++++++ .../backend/test_app_state.py | 25 +++++++ 11 files changed, 273 insertions(+), 7 deletions(-) create mode 100644 tests/spec_driven_agent/test_finish_now.py diff --git a/besser/spec_driven_agent/pipeline/orchestrator.py b/besser/spec_driven_agent/pipeline/orchestrator.py index ea228cea0..5dbdeb204 100644 --- a/besser/spec_driven_agent/pipeline/orchestrator.py +++ b/besser/spec_driven_agent/pipeline/orchestrator.py @@ -350,6 +350,10 @@ def _stopped_by(text: str) -> str: ) +# The stop detail of a Phase 2 the user ended with "Finish now" (``should_finish``). +FINISH_NOW_DETAIL = "finished early at the user's request" + + class LLMOrchestrator(ModifyRunMixin, Phase3RepairMixin, EditLoopGuardsMixin): """ Three-phase orchestrator for LLM-augmented code generation. @@ -403,6 +407,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, @@ -603,6 +608,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 @@ -2277,6 +2285,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(): @@ -2512,7 +2523,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 "") + "" )}]}) - 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} " @@ -2622,6 +2636,16 @@ 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: diff --git a/besser/utilities/web_modeling_editor/backend/models/spec_driven.py b/besser/utilities/web_modeling_editor/backend/models/spec_driven.py index 310aac152..99df0202f 100644 --- a/besser/utilities/web_modeling_editor/backend/models/spec_driven.py +++ b/besser/utilities/web_modeling_editor/backend/models/spec_driven.py @@ -712,6 +712,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): diff --git a/besser/utilities/web_modeling_editor/backend/routers/spec_driven_router.py b/besser/utilities/web_modeling_editor/backend/routers/spec_driven_router.py index dabb9b31c..0d8c6917f 100644 --- a/besser/utilities/web_modeling_editor/backend/routers/spec_driven_router.py +++ b/besser/utilities/web_modeling_editor/backend/routers/spec_driven_router.py @@ -572,6 +572,7 @@ async def smart_gen_config(settings: SettingsDep) -> dict: "event_replay_enabled": True, "cancel_abandoned_runs": settings.llm_cancel_abandoned_runs, "disconnected_grace_seconds": settings.llm_disconnected_grace_seconds, + "finish_now_enabled": True, }, "supported_providers": ["anthropic", "openai", "mistral", "nebius"], # The key dialog's providers and models, from the model catalog @@ -814,6 +815,34 @@ async def cancel_smart_gen( return {"status": "cancelled" if cancelled else "not_found", "runId": run_id} +# --------------------------------------------------------------------- +# POST /besser_api/spec-driven/finish/{run_id} +# --------------------------------------------------------------------- + + +@router.post("/spec-driven/finish/{run_id}") +@handle_endpoint_errors("finish_smart_gen") +async def finish_smart_gen( + runtime: SpecDrivenRuntimeDep, + run_id: str = Path( + ..., + pattern=r"^[a-f0-9]{32}$", + description="Hex run ID returned in the `start` SSE event", + ), +) -> dict: + """Ask a live spec-driven run to stop working and run its final checks on what it has. + + At its next turn boundary the run's work phase hands off to validation, which checks and + packages the result as usual; the run ends with a ``done`` event carrying + ``finishedEarly: true``. Once validation has started the request changes nothing. + + Returns ``{"status": "finishing"}`` when a live run was found and asked, + ``{"status": "not_found"}`` when none is live under that ID. + """ + asked = await runtime.active_runs.request_finish(run_id) + return {"status": "finishing" if asked else "not_found", "runId": run_id} + + # --------------------------------------------------------------------- # GET /besser_api/spec-driven/download/{run_id} # --------------------------------------------------------------------- diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/run_record.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/run_record.py index 73e6c1c9c..999556e00 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/run_record.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/run_record.py @@ -92,9 +92,11 @@ def enable_run_log() -> None: PROVIDER_ERROR, INTERNAL_ERROR, CANCELLED = "provider error", "internal error", "cancelled" STUCK, HANDED_OFF = "repeated edits did not land", "handed off to validation" OUTPUT_LIMIT = "output limit" +FINISHED_EARLY = "finished early at the user's request" _STOP_REASONS = {"max_turns": TURN_LIMIT, "api_error": PROVIDER_ERROR, "cancelled": CANCELLED, "cost_cap": COST_LIMIT, "timeout": TIME_LIMIT, "stuck_edit_loop": STUCK, - "validation_required": HANDED_OFF, "output_limit": OUTPUT_LIMIT} + "validation_required": HANDED_OFF, "output_limit": OUTPUT_LIMIT, + "finished_early": FINISHED_EARLY} # ``stop_message``: the run card's sentence for each way a run ends, without its variable parts. _STOP_MESSAGES = { @@ -106,6 +108,8 @@ def enable_run_log() -> None: CANCELLED: "The run was cancelled before it finished.", STUCK: "The customization loop stopped because repeated edits to the same file were not landing.", HANDED_OFF: "The customization loop handed off to validation before finishing every requested change.", + FINISHED_EARLY: ("The run finished early at the user's request: it stopped working and ran its final " + "checks on what it had."), OUTPUT_LIMIT: ("The model's replies were cut off at its output limit too often, so the customization " "loop stopped before finishing every requested change."), } @@ -194,6 +198,8 @@ def not_verified_message(gaps, *, updated: bool = False) -> Optional[str]: _GENERATOR_IDS = {spec.agent_tool.name: spec.id for spec in GENERATORS if spec.agent_tool is not None} _MAX_INPUT_DIAGRAMS = 16 _MAX_TITLE_CHARS = 120 +# The checklist items a run finished early lists as not done. +_MAX_NOT_DONE = 20 _WRITE_TOOLS = frozenset({"write_file"}) _EDIT_TOOLS = frozenset({"modify_file", "replace_file_lines"}) @@ -312,8 +318,9 @@ def phase_usage(self, usage: Any) -> dict: def stop(self, *, stop_reason: str, cancelled: bool, cap_breach: bool, timed_out: bool, incomplete: bool, blocker_count: int, cost: float, not_confirmed: int = 0, - gaps=()) -> None: - """Record why a run that produced output ended, in the run card's fixed words.""" + gaps=(), work_left: bool = False) -> None: + """Record why a run that produced output ended, in the run card's fixed words. + ``work_left``: a run finished early still had checklist items open when its checks ended.""" if self.late_error: self.stopped_by = self.late_error elif cancelled or stop_reason == "cancelled": @@ -342,6 +349,7 @@ def stop(self, *, stop_reason: str, cancelled: bool, cap_breach: bool, timed_out self.outcome = ("completed_with_blockers" if incomplete or blocker_count # Work handed off unfinished is never plain "completed". else "completed_unverified" if run_gaps(gaps) or self.stopped_by == HANDED_OFF + or (self.stopped_by == FINISHED_EARLY and work_left) else "completed") @@ -387,6 +395,14 @@ def _app_name(orchestrator: Any) -> dict: return {"name": redact_text(name)[0][:_MAX_TITLE_CHARS], "source": source} +def _not_done(orchestrator: Any) -> list[dict]: + """The checklist items neither done nor dropped: ``{id, text}`` each, capped.""" + executor = getattr(orchestrator, "executor", None) + tasks = executor.task_snapshot() if callable(getattr(executor, "task_snapshot", None)) else [] + return [{"id": task.get("id"), "text": str(task.get("text") or "")} for task in tasks + if not task.get("done") and not task.get("dropped")][:_MAX_NOT_DONE] + + def run_section(facts: RunFacts, orchestrator: Any, *, provider: str, models: list, request_chars: int, request: Optional[str] = None, diagrams=(), usage: Any = None) -> dict: """The recipe's ``run`` section, from this run's own orchestrator: never from a recipe on disk, @@ -433,6 +449,8 @@ def run_section(facts: RunFacts, orchestrator: Any, *, provider: str, models: li }, "stopped_by": facts.stopped_by, "stop_message": facts.recorded_stop_message(), + # A run finished early at the user's request: the checklist items it left not done. + "not_done": _not_done(orchestrator) if facts.stopped_by == FINISHED_EARLY else None, "outcome": facts.recorded_outcome(), "outcome_before_no_change": facts.outcome if facts.recorded_outcome() == NO_CHANGE else None, "warnings": list(facts.warnings), diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py index 09568c4b5..c0f8fa086 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py @@ -67,7 +67,7 @@ is_excluded_output_file as _is_excluded_output_file, ) from besser.spec_driven_agent.pipeline.modify_run import MODEL_SYNC_ERRORS -from besser.spec_driven_agent.pipeline.orchestrator import LLMOrchestrator +from besser.spec_driven_agent.pipeline.orchestrator import FINISH_NOW_DETAIL, LLMOrchestrator from besser.spec_driven_agent.planning.model_rules import DROPPED, is_dropped_by_model_change from besser.spec_driven_agent.planning.requirements_ledger import ( ABSENCE_KIND, @@ -619,6 +619,9 @@ def one_line(text: object) -> str: lines.append(f"- Run: {run.get('mode')}, {run.get('mode_reason')}; ended: {run.get('stopped_by')}") if run.get("models"): lines.append(f"- Model: {', '.join(map(one_line, run['models']))} ({run.get('key_tier')})") + if isinstance(run.get("not_done"), list): + items = [one_line(item.get("text")) for item in run["not_done"] if isinstance(item, dict)] + lines.append("- Not done: " + ("; ".join(items) if items else "nothing, every checklist item was closed")) unverified = "completed_unverified" in (run.get("outcome"), run.get("outcome_before_no_change")) why = str(run.get("stop_message") or "").removeprefix(run_record.NO_CHANGE_MESSAGE).strip() if unverified and why: @@ -2226,6 +2229,12 @@ def on_progress(turn: int, tool: str, status: str, def should_continue() -> bool: return not cancel_event.is_set() + # ``POST /spec-driven/finish/{run_id}`` sets it; Phase 2 then hands off to Phase 3. + finish_event = self._runtime.active_runs.finish_event(self.run_id) + + def should_finish() -> bool: + return finish_event is not None and finish_event.is_set() + target_generator = getattr( self.request, "target_generator_override", None ) @@ -2264,6 +2273,7 @@ def should_continue() -> bool: on_checklist=on_checklist, use_streaming=True, should_continue=should_continue, + should_finish=should_finish, # Carry through the assembled primary so the orchestrator # doesn't re-detect it. ``assembled.primary_kind`` already # honours the user's override (if any) courtesy of @@ -2854,8 +2864,11 @@ async def cancel_relay() -> None: )) self._trace_status = _run_status(exited_cleanly, stop_reason) + # Phase 3 records a handoff whose checklist it found closed as completed; the stop detail stays. + finished_early = getattr(orchestrator, "_phase2_stop_detail", "") == FINISH_NOW_DETAIL self._facts.stop( - stop_reason=stop_reason, cancelled=cancel_event.is_set(), cap_breach=bool(_cap_breach), + stop_reason="finished_early" if finished_early else stop_reason, cancelled=cancel_event.is_set(), + work_left=stop_reason == "validation_required", cap_breach=bool(_cap_breach), timed_out=elapsed > effective_runtime_cap, incomplete=incomplete, blocker_count=len(_unfixed_blockers), not_confirmed=_not_confirmed, cost=final_cost, gaps=_gaps, @@ -2878,6 +2891,7 @@ async def cancel_relay() -> None: done_event.incomplete = incomplete done_event.incompleteReason = incomplete_reason_msg done_event.cancelled = cancelled + done_event.finishedEarly = self._facts.stopped_by == run_record.FINISHED_EARLY # A whole class of checks that left no evidence: reported as its own # state, never as incomplete (which is for a known defect). # A class the server has switched off is reported apart (``checksOff``): it is diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runtime.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runtime.py index 967811864..fd22fc369 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runtime.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runtime.py @@ -66,6 +66,8 @@ class ActiveRuns: def __init__(self) -> None: self._events: dict[str, asyncio.Event] = {} + # ``run_id`` -> "finish now" event: the run stops working and goes to its final checks. + self._finish: dict[str, asyncio.Event] = {} self._lock = asyncio.Lock() async def reserve(self, run_id: str) -> Optional[asyncio.Event]: @@ -75,6 +77,7 @@ async def reserve(self, run_id: str) -> Optional[asyncio.Event]: if run_id in self._events: return None self._events[run_id] = event + self._finish[run_id] = asyncio.Event() return event async def release(self, run_id: str, event: asyncio.Event) -> bool: @@ -83,6 +86,7 @@ async def release(self, run_id: str, event: asyncio.Event) -> bool: if self._events.get(run_id) is not event: return False self._events.pop(run_id, None) + self._finish.pop(run_id, None) return True async def request_cancellation(self, run_id: str) -> bool: @@ -94,6 +98,19 @@ async def request_cancellation(self, run_id: str) -> bool: event.set() return True + def finish_event(self, run_id: str) -> Optional[asyncio.Event]: + """The "finish now" event of a reserved run, or None.""" + return self._finish.get(run_id) + + async def request_finish(self, run_id: str) -> bool: + """Ask a live run to finish now; False when no such run is live.""" + async with self._lock: + event = self._finish.get(run_id) + if event is None: + return False + event.set() + return True + @dataclass class SpecDrivenRuntime: diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py index 291ed3503..6fbf80b22 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py @@ -309,6 +309,9 @@ class DoneEvent(BaseSseEvent): # True when the run ended because a cancel request was honoured after it # had written files: the output is what it had made by then. cancelled: bool = False + # True when the user asked the run to finish early ("Finish now"): it stopped working, + # ran its final checks on what it had, and its open checklist items are not done. Additive. + finishedEarly: bool = False # 0 on a run that was cut short (the loop did not finish, or a cancel stopped # Phase 3), so clients use their cut-short copy. Otherwise, with # ``incomplete`` true: the unresolved blockers. With ``incomplete`` false: diff --git a/tests/spec_driven_agent/scripted_rig.py b/tests/spec_driven_agent/scripted_rig.py index 6fd76e584..477f1b773 100644 --- a/tests/spec_driven_agent/scripted_rig.py +++ b/tests/spec_driven_agent/scripted_rig.py @@ -107,7 +107,7 @@ def reply(self, kind: str): def run_scripted(workspace, agent: ScriptedAgent, *, max_turns: int | None = None, max_runtime_seconds: int = 1200, auto_fix: bool = True, - on_findings=None) -> LLMOrchestrator: + on_findings=None, should_finish=None) -> LLMOrchestrator: """One whole run of the shelf app (FastAPI scaffold) driven by ``agent``.""" client, fake = claude_run_client(MODEL_ID, agent, with_thinking=False) agent.transport = fake @@ -115,6 +115,7 @@ def run_scripted(workspace, agent: ScriptedAgent, *, max_turns: int | None = Non llm_client=client, domain_model=shelf_model(), output_dir=str(workspace), max_turns=max_turns, max_runtime_seconds=max_runtime_seconds, use_streaming=False, enable_requirements_ledger=False, auto_fix_issues=auto_fix, on_findings=on_findings, + should_finish=should_finish, ) agent.orchestrator = orchestrator orchestrator.run(REQUEST) diff --git a/tests/spec_driven_agent/test_finish_now.py b/tests/spec_driven_agent/test_finish_now.py new file mode 100644 index 000000000..19d1b7a7a --- /dev/null +++ b/tests/spec_driven_agent/test_finish_now.py @@ -0,0 +1,60 @@ +""""Finish now": the user tells a run to stop working and go to its final checks. + +A run spent five minutes after its asked edits writing and running its own test scripts; +the user could only cancel it, and a cancelled run is not checked. Finish now ends Phase 2 +at its next turn boundary through the same handoff the edit-handoff rule uses, so Phase 3 +still checks and packages what the run made, and the record says the user asked for it. +""" + +from __future__ import annotations + +from besser.spec_driven_agent.pipeline.orchestrator import FINISH_NOW_DETAIL +from tests.spec_driven_agent.scripted_rig import ScriptedAgent, run_scripted +from tests.spec_driven_agent.test_scripted_loop_structure import TASKS, _no_app_boot, shelf_script + + +def _run(tmp_path, finish_after_turns: int | None, finish_in_phase3: bool = False): + attempts: list[int] = [] + agent = ScriptedAgent(str(tmp_path), shelf_script(), TASKS) + + def should_finish() -> bool: + if finish_in_phase3: + return agent.orchestrator.phase3_started_at is not None + return finish_after_turns is not None and len(agent.sent["phase2"]) >= finish_after_turns + + run_scripted(tmp_path, agent, max_turns=30, should_finish=should_finish, + on_findings=lambda attempt, issues, restored=False: attempts.append(attempt)) + return agent, attempts + + +def test_finish_now_ends_phase2_at_the_next_turn_and_phase3_still_runs(tmp_path, monkeypatch): + _no_app_boot(monkeypatch) + + agent, attempts = _run(tmp_path, finish_after_turns=5) + orchestrator = agent.orchestrator + + # The fifth turn's calls ran; no sixth request was answered with work. + assert len(agent.sent["phase2"]) == 5 and sum(map(len, agent.sent["phase2"])) == 5 + assert orchestrator._phase2_stop_reason == "validation_required" + assert orchestrator._phase2_stop_detail == FINISH_NOW_DETAIL + # Phase 3 checked what the run had made. + assert orchestrator.phase3_started_at is not None and attempts and attempts[0] == 0 + assert orchestrator._phase3_exit_reason != "not reached" + + +def test_finish_now_before_the_first_turn_hands_off_without_a_work_call(tmp_path, monkeypatch): + _no_app_boot(monkeypatch) + + agent, attempts = _run(tmp_path, finish_after_turns=0) + + assert agent.sent["phase2"] == [] + assert agent.orchestrator._phase2_stop_detail == FINISH_NOW_DETAIL and attempts[0] == 0 + + +def test_finish_now_once_phase3_has_started_changes_nothing(tmp_path, monkeypatch): + _no_app_boot(monkeypatch) + + agent, _ = _run(tmp_path, finish_after_turns=None, finish_in_phase3=True) + + assert agent.orchestrator._phase2_stop_reason == "completed" + assert agent.orchestrator._phase2_stop_detail != FINISH_NOW_DETAIL diff --git a/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_record.py b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_record.py index ab9464316..74efbab46 100644 --- a/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_record.py +++ b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_record.py @@ -944,3 +944,76 @@ class _Seeded(_Orchestrator): with open(os.path.join(runner.temp_dir, "README.md"), encoding="utf-8") as fh: assert fh.readline().strip() == "# Order Hub" + + +class _FinishedEarly(_Orchestrator): + """Phase 2 ended by "Finish now" with one checklist item done, one open and one dropped.""" + + stop_reason = "validation_required" + tasks = [{"id": 1, "text": "Restyle the order list.", "done": True}, + {"id": 2, "text": "Add a footer with the shop's address.", "done": False}, + {"id": 3, "text": "Add a sitemap.", "done": False, "dropped": "not asked for"}] + + def __init__(self, **kwargs): + super().__init__(**kwargs) + from besser.spec_driven_agent.pipeline.orchestrator import FINISH_NOW_DETAIL + + self._phase2_stop_detail = FINISH_NOW_DETAIL + self.executor = SimpleNamespace(task_snapshot=lambda: [dict(task) for task in type(self).tasks]) + + +def test_a_run_finished_early_records_the_users_request_and_what_was_not_done(monkeypatch): + monkeypatch.setattr(runner_module, "LLMOrchestrator", _FinishedEarly) + monkeypatch.setattr(runner_module, "create_llm_client", lambda **_: _Client()) + runner = SmartGenerationRunner(_build_request(), runtime=current_runtime()) + done = [_parse(frame) for frame in asyncio.run(seed._collect_frames(runner))][-1] + run = done["recipe"]["run"] + + assert done["finishedEarly"] is True and done["cancelled"] is False + assert run["stopped_by"] == "finished early at the user's request" + assert run["stop_message"].startswith("The run finished early at the user's request") + assert run["outcome"] == "completed_unverified" + assert run["not_done"] == [{"id": 2, "text": "Add a footer with the shop's address."}] + entry = asyncio.run(current_runtime().registry.get(done["runId"])) + [summary_path] = [os.path.join(folder, "BESSER_GENERATION.md") for folder, _, names in os.walk(entry.temp_dir) + if "BESSER_GENERATION.md" in names] + summary = open(summary_path, encoding="utf-8").read() + assert "ended: finished early at the user's request" in summary + assert "- Not done: `Add a footer with the shop's address.`" in summary + + +def test_a_run_finished_early_whose_checks_closed_every_item_is_completed(monkeypatch): + monkeypatch.setattr(_FinishedEarly, "stop_reason", "completed") # Phase 3 found the checklist closed + monkeypatch.setattr(_FinishedEarly, "tasks", [{"id": 1, "text": "Restyle the order list.", "done": True}]) + monkeypatch.setattr(runner_module, "LLMOrchestrator", _FinishedEarly) + monkeypatch.setattr(runner_module, "create_llm_client", lambda **_: _Client()) + run = _run(SmartGenerationRunner(_build_request(), runtime=current_runtime())) + + assert run["stopped_by"] == "finished early at the user's request" + assert run["outcome"] == "completed" and run["not_done"] == [] + + +def test_a_run_not_finished_early_lists_no_items(orchestrator): + run = _run(SmartGenerationRunner(_build_request(), runtime=current_runtime())) + assert run["not_done"] is None + + +def test_the_runs_finish_now_request_reaches_its_orchestrator(monkeypatch): + seen: list[bool] = [] + + class _Asked(_Orchestrator): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.should_finish, self.run_id = kwargs["should_finish"], kwargs["run_id"] + + def run(self, instructions): + seen.append(self.should_finish()) + current_runtime().active_runs.finish_event(self.run_id).set() + seen.append(self.should_finish()) + return super().run(instructions) + + monkeypatch.setattr(runner_module, "LLMOrchestrator", _Asked) + monkeypatch.setattr(runner_module, "create_llm_client", lambda **_: _Client()) + runner = SmartGenerationRunner(_build_request(), runtime=current_runtime()) + _run(runner) + assert seen == [False, True] diff --git a/tests/utilities/web_modeling_editor/backend/test_app_state.py b/tests/utilities/web_modeling_editor/backend/test_app_state.py index e1b9563bd..f500635aa 100644 --- a/tests/utilities/web_modeling_editor/backend/test_app_state.py +++ b/tests/utilities/web_modeling_editor/backend/test_app_state.py @@ -128,3 +128,28 @@ async def scenario(): finally: one.spec_driven.durable_runs.store.close() two.spec_driven.durable_runs.store.close() + + +def test_finish_now_asks_only_the_live_run_and_the_config_advertises_it(quiet_lifespan): + app = _spec_driven_app() + run_id, other = "d" * 32, "e" * 32 + + async def scenario(): + async with app.router.lifespan_context(app): + runtime = app.state.spec_driven + cancel_event = await runtime.active_runs.reserve(run_id) + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url=BASE_URL) as client: + finish = (await client.post(f"/besser_api/spec-driven/finish/{run_id}")).json() + missing = (await client.post(f"/besser_api/spec-driven/finish/{other}")).json() + features = (await client.get("/besser_api/spec-driven/config")).json()["features"] + asked = runtime.active_runs.finish_event(run_id).is_set() + await runtime.active_runs.release(run_id, cancel_event) + return finish, missing, features, asked, cancel_event.is_set(), runtime.active_runs.finish_event(run_id) + + finish, missing, features, asked, cancelled, after_release = asyncio.run(scenario()) + assert finish == {"status": "finishing", "runId": run_id} and asked + assert not cancelled, "finish now is not a cancel" + assert missing == {"status": "not_found", "runId": other} + assert features["finish_now_enabled"] is True + assert after_release is None From 3b459da7cfc07fb6ecf00d4243f82aee5f087f94 Mon Sep 17 00:00:00 2001 From: ArmSL Date: Wed, 2 Dec 2026 22:13:08 +0100 Subject: [PATCH 4/9] docs(spec-driven): document run steps, the checklist event and Finish now The run section says what the run card shows in every phase and how "Finish now" ends a run: Phase 2 hands off at its next turn, Phase 3 still checks and packages the result, and the record and BESSER_GENERATION.md say the run finished early at the user's request with the items not done. The API reference lists POST /spec-driven/finish/{run_id}, the `finish_now_enabled` feature flag, the `step` event in every phase, the new `checklist` event and the done event's `finishedEarly`. --- docs/source/guides/build-with-ai.rst | 5 ++- docs/source/spec_driven_agent/api.rst | 45 ++++++++++++++++++++------ docs/source/spec_driven_agent/runs.rst | 34 +++++++++++++++++-- docs/source/web_editor_backend.rst | 4 +-- 4 files changed, 72 insertions(+), 16 deletions(-) diff --git a/docs/source/guides/build-with-ai.rst b/docs/source/guides/build-with-ai.rst index a38da8e18..f30a068c5 100644 --- a/docs/source/guides/build-with-ai.rst +++ b/docs/source/guides/build-with-ai.rst @@ -25,7 +25,10 @@ Describe, review, generate 4. Choose a provider if prompted. A saved provider key can start the requested run immediately and incur provider charges; set the per-run budget in the key dialog before starting. -5. Follow the run card. Use **Stop** to cancel or wait for the result. +5. Follow the run card: it says what the agent is doing and shows its checklist. + Wait for the result, use **Finish now** when the change you asked for is done + (the run stops working and checks what it has), or **Stop** to end it at once + (the files it wrote are kept, unchecked). 6. Download the archive and read its README. Review its verification findings before running or deploying it. diff --git a/docs/source/spec_driven_agent/api.rst b/docs/source/spec_driven_agent/api.rst index 8763f4bc4..c397239dc 100644 --- a/docs/source/spec_driven_agent/api.rst +++ b/docs/source/spec_driven_agent/api.rst @@ -34,7 +34,9 @@ Endpoints - Caps, the workspace and download lifetimes (``download_ttl_seconds``, ``archive_ttl_seconds``), cost-tick interval, concurrency, feature flags, the model catalog's providers and models (``providers``), provider - default models, and free-tier availability. + default models, and free-tier availability. ``features.finish_now_enabled`` + is true when the server serves ``/spec-driven/finish/{run_id}``: a client + shows its "Finish now" control only then. * - ``/spec-driven/runs/{run_id}`` - GET - Durable lifecycle metadata for a run (never the request or the key). @@ -63,6 +65,13 @@ Endpoints - POST - Cancel an in-flight run: the command or streaming LLM call it is running is stopped at once (see :doc:`runs`). + * - ``/spec-driven/finish/{run_id}`` + - POST + - Ask an in-flight run to finish now: it stops working at its next turn + and runs its final checks on what it has (see + :ref:`Finish now `). Answers ``{"status": "finishing"}``, or + ``{"status": "not_found"}`` when no run is live under that ID. Once the + final checks have begun it changes nothing. * - ``/spec-driven/download/{run_id}`` - GET - Download the generated ZIP/file (re-fetchable for @@ -349,14 +358,28 @@ SSE event types ``validate``, the first check's result as ``message`` (``"2 blockers / 5 total"``). * - ``step`` - - What the current phase is doing now, sent during ``validate`` because - one check round, requirement judge call or fix attempt can take - minutes: ``phase``, ``message`` (for example ``"First check: checking - 35 requirements against the code"``, ``"Fix attempt 2: fixing 24 - blockers (20 about requirements)"``, ``"Packaging the result"``) and - ``elapsedSeconds``, the run's elapsed time when the step started. A - step lasts until the next ``step``, ``phase`` or terminal event; the - ``cost`` ticks tell how long it has been running. + - What the current phase is doing now: ``phase``, ``message`` and + ``elapsedSeconds``, the run's elapsed time when the step started. Sent + during ``gap`` (``"Planning the work: making a checklist from the + request"``), during ``customize`` for each turn, built from its tool + calls and never from the model's text (``"Reading the code"``, + ``"Editing frontend/src/App.jsx (checklist item 3)"``, ``"Editing + backend/main_api.py, then running the app's checks"``, ``"Running a + command the agent wrote"``), at most one change every two seconds, and + during ``validate``, where one check round, requirement judge call or fix + attempt can take minutes (``"First check: checking 35 requirements + against the code"``, ``"Fix attempt 2: fixing 24 blockers (20 about + requirements)"``, ``"Packaging the result"``). A step lasts until the + next ``step``, ``phase`` or terminal event; the ``cost`` ticks tell how + long it has been running. + * - ``checklist`` + - The agent's checklist (the ``task_list`` tool's items), whole, each + time it changes: when planning seeds it, after a Phase 2 turn that + changed it, and after a validation round that settled items from the + code. ``items`` holds ``{id, text, state}`` per item, ``state`` one of + ``open``, ``done``, ``blocked`` or ``dropped`` (at most 50 items, each + text clipped to 240 characters). Additive: a client that ignores it is + unaffected. * - ``findings`` - One Phase 3 validation round: ``attempt`` (0 for the first check, n for the re-check after fix attempt n), ``blockers`` (at most 20 messages, @@ -400,7 +423,9 @@ SSE event types additive: a warning a check observed, such as a screen that reported an error, one item per finding), with true totals in ``counts``; a finding counted as a blocker is never in ``notVerified``), - ``incomplete`` / ``incompleteReason``, ``cancelled`` (true + ``incomplete`` / ``incompleteReason``, ``finishedEarly`` (true when the + user asked the run to finish now, see :ref:`Finish now `; + additive), ``cancelled`` (true when a cancel request was honoured after the run had written files, so the output is what it had made by then; a run the server stopped because nobody followed it reads the same; it is stored with the event, so a diff --git a/docs/source/spec_driven_agent/runs.rst b/docs/source/spec_driven_agent/runs.rst index ba1e5a39d..50d2949c7 100644 --- a/docs/source/spec_driven_agent/runs.rst +++ b/docs/source/spec_driven_agent/runs.rst @@ -122,6 +122,29 @@ the download start no command and take seconds; they may end a few seconds past the cap, which the watchdog's grace (``BESSER_LLM_WATCHDOG_GRACE_SECONDS``) covers. +The run card says what the run is doing in every phase (the ``step`` event, +see :doc:`api`): planning, each Phase 2 turn named from its tool calls (reading +the code, editing a named file and the checklist item that names it, running +the app's checks, testing it through its API, running a command the agent +wrote), and each Phase 3 check, judge call and fix attempt. No sentence quotes +the model's own text. The agent's checklist reaches the card as the +``checklist`` event, with each item's state. + +.. _spec-driven-finish-now: + +**Finish now.** ``POST /besser_api/spec-driven/finish/{run_id}`` tells a run to +stop working and go to its final checks with what it has. Phase 2 reads the +request at its next turn boundary (the tool calls of the turn in progress still +run) and hands off to Phase 3 the way the edit handoff does, with the stop +detail ``finished early at the user's request``; Phase 3 then validates, +repairs blockers when auto-fix is on, and packages the result as usual. It +works for create and edit runs and changes nothing once Phase 3 has started. +The run record's ``stopped_by`` is ``finished early at the user's request`` and +its ``not_done`` lists the checklist items neither done nor dropped; +``BESSER_GENERATION.md`` says the same (``ended: finished early at the user's +request`` and a ``Not done`` line), and the ``done`` event carries +``finishedEarly: true``. Unlike a cancel, the result is checked. + A cancellation — from ``POST /besser_api/spec-driven/cancel/{run_id}``, a closed connection, the abandonment timer or the runtime watchdog — takes effect at once: the command running at that moment is killed with every process it @@ -683,9 +706,14 @@ keys, always in this order: - ``limits`` (``time_seconds``, ``cost_usd``, ``turns``), ``stopped_by`` (``finished``, ``time limit``, ``cost limit``, ``turn limit``, ``provider error``, ``internal error``, ``cancelled``, ``repeated edits did not land``, - ``output limit`` or ``handed off to validation``), ``stop_message`` (the run - card's sentence for that ending, without its variable parts), ``outcome`` and - ``outcome_before_no_change`` (see ``changed_files``). + ``output limit``, ``handed off to validation`` or ``finished early at the + user's request``), ``stop_message`` (the run card's sentence for that ending, + without its variable parts), ``outcome`` and ``outcome_before_no_change`` + (see ``changed_files``). ``not_done`` lists, for a run finished early at the + user's request (see :ref:`Finish now `), the checklist items + neither done nor dropped as ``{id, text}`` (at most 20); ``null`` on any + other run. Such a run's ``outcome`` is never ``completed`` while one of them + is left. ``turn limit`` means the customization loop made every tool call of the budget (auto-fix off, so no share was kept) or reached the runaway guard on turns; ``time limit`` and ``cost limit`` mean the cap itself, never only diff --git a/docs/source/web_editor_backend.rst b/docs/source/web_editor_backend.rst index ebd1271ab..b34d7815b 100644 --- a/docs/source/web_editor_backend.rst +++ b/docs/source/web_editor_backend.rst @@ -527,12 +527,12 @@ have no safe place for one and are returned unchanged. Spec-Driven Agent ^^^^^^^^^^^^^^^^^ -Twelve endpoints under ``/spec-driven/*`` back the +Thirteen endpoints under ``/spec-driven/*`` back the :doc:`Spec-Driven Agent ` -- the hybrid pipeline that runs a deterministic generator, lets an LLM customise its output, then validates and repairs the result: ``generate``, ``preview``, ``config``, ``runs/{run_id}``, ``runs/{run_id}/events``, ``runs/{run_id}/events.json``, -``resume/{run_id}``, ``cancel/{run_id}``, ``download/{run_id}``, +``resume/{run_id}``, ``cancel/{run_id}``, ``finish/{run_id}``, ``download/{run_id}``, ``push-to-github``, ``import-github-run`` and ``import-generated-code``. They are documented once, with the agent, rather than twice: see From 9e6ee01665ef60687d742c86d32ba0bdad5952dd Mon Sep 17 00:00:00 2001 From: ArmSL Date: Wed, 2 Dec 2026 22:37:36 +0100 Subject: [PATCH 5/9] fix(spec-driven): make no repair turn after Finish now With auto-fix on, Phase 3 sent an open checklist item whose deterministic check fails (an action-contract item) to a repair turn as a "task incomplete" blocker, so the run went on implementing work after the user had asked it to finish. After a Finish now handoff Phase 3 now checks and packages only: its findings are recorded and reported, and the fix loop does not start. FINISH_NOW_DETAIL moves to pipeline/constants.py so the Phase 3 mixin can read it; the orchestrator still exports it. --- .../spec_driven_agent/pipeline/constants.py | 4 +++ .../pipeline/orchestrator.py | 5 +-- .../pipeline/phase3_repair.py | 6 ++++ docs/source/spec_driven_agent/runs.rst | 6 ++-- tests/spec_driven_agent/test_finish_now.py | 32 +++++++++++++++++++ 5 files changed, 47 insertions(+), 6 deletions(-) diff --git a/besser/spec_driven_agent/pipeline/constants.py b/besser/spec_driven_agent/pipeline/constants.py index 05cae5c7a..2cb8a7b78 100644 --- a/besser/spec_driven_agent/pipeline/constants.py +++ b/besser/spec_driven_agent/pipeline/constants.py @@ -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" diff --git a/besser/spec_driven_agent/pipeline/orchestrator.py b/besser/spec_driven_agent/pipeline/orchestrator.py index 5dbdeb204..432ffadf3 100644 --- a/besser/spec_driven_agent/pipeline/orchestrator.py +++ b/besser/spec_driven_agent/pipeline/orchestrator.py @@ -281,6 +281,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, @@ -350,10 +351,6 @@ def _stopped_by(text: str) -> str: ) -# The stop detail of a Phase 2 the user ended with "Finish now" (``should_finish``). -FINISH_NOW_DETAIL = "finished early at the user's request" - - class LLMOrchestrator(ModifyRunMixin, Phase3RepairMixin, EditLoopGuardsMixin): """ Three-phase orchestrator for LLM-augmented code generation. diff --git a/besser/spec_driven_agent/pipeline/phase3_repair.py b/besser/spec_driven_agent/pipeline/phase3_repair.py index ed76a5cd1..ae237efcd 100644 --- a/besser/spec_driven_agent/pipeline/phase3_repair.py +++ b/besser/spec_driven_agent/pipeline/phase3_repair.py @@ -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, @@ -468,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 diff --git a/docs/source/spec_driven_agent/runs.rst b/docs/source/spec_driven_agent/runs.rst index 50d2949c7..7a867defd 100644 --- a/docs/source/spec_driven_agent/runs.rst +++ b/docs/source/spec_driven_agent/runs.rst @@ -136,8 +136,10 @@ the model's own text. The agent's checklist reaches the card as the stop working and go to its final checks with what it has. Phase 2 reads the request at its next turn boundary (the tool calls of the turn in progress still run) and hands off to Phase 3 the way the edit handoff does, with the stop -detail ``finished early at the user's request``; Phase 3 then validates, -repairs blockers when auto-fix is on, and packages the result as usual. It +detail ``finished early at the user's request``; Phase 3 then validates and +packages the result as usual, but makes no repair turn even when auto-fix is +on: its findings, unfinished checklist items among them, are reported as they +are. It works for create and edit runs and changes nothing once Phase 3 has started. The run record's ``stopped_by`` is ``finished early at the user's request`` and its ``not_done`` lists the checklist items neither done nor dropped; diff --git a/tests/spec_driven_agent/test_finish_now.py b/tests/spec_driven_agent/test_finish_now.py index 19d1b7a7a..38469cf4e 100644 --- a/tests/spec_driven_agent/test_finish_now.py +++ b/tests/spec_driven_agent/test_finish_now.py @@ -51,6 +51,38 @@ def test_finish_now_before_the_first_turn_hands_off_without_a_work_call(tmp_path assert agent.orchestrator._phase2_stop_detail == FINISH_NOW_DETAIL and attempts[0] == 0 +def test_finish_now_checks_and_packages_without_repairing_the_open_work(tmp_path, monkeypatch): + """An open item whose deterministic check fails (as action-contract items have) is a + ``task incomplete`` blocker; with auto-fix on, Phase 3 used to send it to a repair turn + that implemented it, so the run kept working after the user asked it to stop.""" + _no_app_boot(monkeypatch) + agent = ScriptedAgent(str(tmp_path), shelf_script(), TASKS) + requests_at_first_check: list[int] = [] + findings: list[str] = [] + + def should_finish() -> bool: + if len(agent.sent["phase2"]) < 3: + return False + for task in agent.orchestrator.executor._tasks: + if task["id"] == 1: + task["verify"] = lambda: False + return True + + def on_findings(attempt, issues, restored=False): + requests_at_first_check.append(len(agent.transport.requests)) + findings.extend(str(getattr(issue, "message", issue)) for issue in issues) + + run_scripted(tmp_path, agent, max_turns=30, auto_fix=True, should_finish=should_finish, + on_findings=on_findings) + orchestrator = agent.orchestrator + + assert orchestrator._phase2_stop_detail == FINISH_NOW_DETAIL + assert any(f.startswith("task incomplete: task 1") for f in findings) # still reported + assert agent.sent["phase3"] == [] + assert len(agent.transport.requests) == requests_at_first_check[0] # no LLM request after the check + assert orchestrator._phase3_exit_reason == FINISH_NOW_DETAIL + + def test_finish_now_once_phase3_has_started_changes_nothing(tmp_path, monkeypatch): _no_app_boot(monkeypatch) From c96db3e61db5b21a905bfbc475bc758b42e983d4 Mon Sep 17 00:00:00 2001 From: ArmSL Date: Wed, 2 Dec 2026 22:58:46 +0100 Subject: [PATCH 6/9] feat(spec-driven): offer the model an edit run's model sync changed An edit run that adds to the data model updates the project model on the server, but the editor only received it through a GitHub push, so a user who downloaded the result kept a diagram without the new classes and their next run started from it. The run now keeps that model with its download (same lifetime), and its done event carries `updatedModel` ({url, changes}) when model sync changed the model: where to fetch it and what it adds. GET /spec-driven/download/{run_id}/model returns {run_id, project_export}, the export the push writes. Both read the copy kept on disk, so a process that did not run the edit serves them too; this also makes a push served by the backend write the run's synced model instead of the request's. --- .../backend/models/spec_driven.py | 9 ++ .../backend/routers/spec_driven_router.py | 24 +++ .../services/spec_driven/github_sync.py | 3 +- .../backend/services/spec_driven/runner.py | 28 ++++ .../services/spec_driven/sse_events.py | 12 ++ .../spec_driven/test_push_model_sync.py | 27 ++++ .../spec_driven/test_run_model_offer.py | 138 ++++++++++++++++++ 7 files changed, 240 insertions(+), 1 deletion(-) create mode 100644 tests/utilities/web_modeling_editor/backend/spec_driven/test_run_model_offer.py diff --git a/besser/utilities/web_modeling_editor/backend/models/spec_driven.py b/besser/utilities/web_modeling_editor/backend/models/spec_driven.py index 99df0202f..34a6c1fe4 100644 --- a/besser/utilities/web_modeling_editor/backend/models/spec_driven.py +++ b/besser/utilities/web_modeling_editor/backend/models/spec_driven.py @@ -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``.""" diff --git a/besser/utilities/web_modeling_editor/backend/routers/spec_driven_router.py b/besser/utilities/web_modeling_editor/backend/routers/spec_driven_router.py index 0d8c6917f..97d09c8a9 100644 --- a/besser/utilities/web_modeling_editor/backend/routers/spec_driven_router.py +++ b/besser/utilities/web_modeling_editor/backend/routers/spec_driven_router.py @@ -42,6 +42,7 @@ ImportGitHubRunResponse, PushSmartToGitHubRequest, PushSmartToGitHubResponse, + RunModelResponse, SmartGenerateRequest, SmartPreviewRequest, SmartPreviewResponse, @@ -74,6 +75,7 @@ archived_recipe_text, modify_base, run_download_dir, + run_updated_project_export, ) from besser.utilities.workspace_fs import open_plain from besser.utilities.web_modeling_editor.backend.services.spec_driven.github_sync import ( @@ -917,6 +919,28 @@ async def _iter_file() -> AsyncIterator[bytes]: ) +@router.get("/spec-driven/download/{run_id}/model", response_model=RunModelResponse) +@handle_endpoint_errors("download_smart_model") +async def download_smart_model( + runtime: SpecDrivenRuntimeDep, + run_id: str = Path( + ..., + pattern=r"^[a-f0-9]{32}$", + description="Hex run ID of a `done` SSE event that carried `updatedModel`", + ), +) -> dict: + """The project model a modify run's model sync changed, for the editor to offer. + + The same export the GitHub push writes for the run, kept as long as its + download. 404 when the run is unknown or expired, or changed no model. + """ + entry = await runtime.registry.get(run_id) + export = await asyncio.to_thread(run_updated_project_export, entry) if entry is not None else None + if export is None: + raise HTTPException(status_code=404, detail="This run changed no model, or it has expired") + return {"run_id": run_id, "project_export": export} + + # --------------------------------------------------------------------- # POST /besser_api/spec-driven/push-to-github # --------------------------------------------------------------------- diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/github_sync.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/github_sync.py index f54d3a128..39e94cb37 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/github_sync.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/github_sync.py @@ -82,6 +82,7 @@ create_run_workspace, run_changes, run_download_dir, + run_updated_project_export, ) from besser.utilities.web_modeling_editor.backend.services.spec_driven.workspace_tree import ( read_run_json, @@ -275,7 +276,7 @@ async def push_run_to_github( # instruction added domain entities stores it on the registry # entry) so the pushed buml/ matches the code. Fall back to the # request's projectExport for every other run. - synced_export = getattr(entry, "updated_project_export", None) + synced_export = run_updated_project_export(entry) # The run's export is the bare generation payload: put it in the editor's envelope # (trace, versions, assistant chat and usage; BESSER#853). run_export = repo_model.in_editor_envelope(synced_export, req.projectExport) if synced_export else None diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py index c0f8fa086..81aa7b5ea 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py @@ -160,6 +160,7 @@ StepEvent, TextDeltaEvent, ToolCallEvent, + UpdatedModel, VerificationCounts, VerificationItem, VerificationReport, @@ -191,6 +192,8 @@ _DOWNLOAD_DIR_SUFFIX = ".download" _DOWNLOAD_MANIFEST_NAME = "manifest.json" _DOWNLOAD_ARTIFACT_NAME = "artifact" +# The run's ``updated_project_export``, for a process that did not run it (the push, the model endpoint). +_UPDATED_PROJECT_NAME = "updated_project.json" _DOWNLOAD_DIR_RE = re.compile( re.escape(LLM_TEMP_DIR_PREFIX) + r"(?P[a-f0-9]{32})_[a-z0-9_]+" + re.escape(_DOWNLOAD_DIR_SUFFIX) ) @@ -1099,6 +1102,15 @@ class SmartRunEntry: packaged: bool = False +def run_updated_project_export(entry: SmartRunEntry) -> Optional[dict]: + """The run's ``updated_project_export``; an entry another process registered reads + the copy kept with the download. None when the run's model sync changed no model.""" + if isinstance(entry.updated_project_export, dict): + return entry.updated_project_export + export = read_run_json(os.path.join(run_download_dir(entry.temp_dir), _UPDATED_PROJECT_NAME)) + return export if isinstance(export, dict) else None + + class SmartRunRegistry: """In-memory, TTL-bounded map of ``run_id → SmartRunEntry``. @@ -1137,6 +1149,13 @@ def _store_download(run_id: str, entry: SmartRunEntry) -> SmartRunEntry: artifact = os.path.join(download_dir, _DOWNLOAD_ARTIFACT_NAME) if os.path.abspath(entry.file_path) != os.path.abspath(artifact): copy_plain_file(entry.file_path, artifact, root=entry.temp_dir, dst_root=download_dir) + updated_project = os.path.join(download_dir, _UPDATED_PROJECT_NAME) + if isinstance(entry.updated_project_export, dict): + write_atomic_plain(updated_project, json.dumps(entry.updated_project_export, separators=(",", ":")), + root=download_dir) + else: + with contextlib.suppress(FileNotFoundError): + os.remove(updated_project) write_atomic_plain(os.path.join(download_dir, _DOWNLOAD_MANIFEST_NAME), json.dumps({ "version": 2, "runId": run_id, @@ -2946,6 +2965,15 @@ async def cancel_relay() -> None: os.path.join(run_download_dir(entry.temp_dir), _DOWNLOAD_ARTIFACT_NAME), root=run_download_dir(entry.temp_dir)) self._packaged_workspace = entry.temp_dir + # Offered only once it is kept where every process serving the run can read it. + if entry.updated_project_export is not None and is_plain_file( + os.path.join(run_download_dir(entry.temp_dir), _UPDATED_PROJECT_NAME), + root=run_download_dir(entry.temp_dir), + ): + done_event.updatedModel = UpdatedModel( + url=f"/besser_api/spec-driven/download/{self.run_id}/model", + changes=_model_sync_changes(done_event.recipe or {}), + ) yield self._sse(done_event) except _EmptyGenerationError as exc: # Raised inside _package_result when the orchestrator diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py index 6fbf80b22..27d43b778 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/sse_events.py @@ -273,6 +273,16 @@ class VerificationReport(BaseModel): counts: VerificationCounts = Field(default_factory=VerificationCounts) +class UpdatedModel(BaseModel): + """The project model a modify run's model sync changed, offered to the editor.""" + + # ``GET`` it for ``{run_id, project_export}``: the generation request's project with the + # synced class diagram, the model the GitHub push writes. Kept as long as the download. + url: str + # What model sync added, the ``modelChanges`` lines ending "added from the request". + changes: list[str] = Field(default_factory=list) + + class DoneEvent(BaseSseEvent): """Terminal event on successful completion. @@ -384,6 +394,8 @@ class DoneEvent(BaseSseEvent): changedFiles: list[str] = Field(default_factory=list) changedFileCount: int = 0 modelChanges: list[str] = Field(default_factory=list) + # Set only when model sync changed the project model; older editors ignore it. Additive. + updatedModel: Optional[UpdatedModel] = None ErrorCode = Literal[ diff --git a/tests/utilities/web_modeling_editor/backend/spec_driven/test_push_model_sync.py b/tests/utilities/web_modeling_editor/backend/spec_driven/test_push_model_sync.py index 50e3611a6..4c0cc4573 100644 --- a/tests/utilities/web_modeling_editor/backend/spec_driven/test_push_model_sync.py +++ b/tests/utilities/web_modeling_editor/backend/spec_driven/test_push_model_sync.py @@ -25,6 +25,7 @@ spec_driven_router as router_module, ) from besser.utilities.web_modeling_editor.backend.services.spec_driven import github_sync +from besser.utilities.web_modeling_editor.backend.services.spec_driven import runner as runner_module from besser.utilities.web_modeling_editor.backend.services.spec_driven.runner import ( SmartRunEntry, ) @@ -174,6 +175,32 @@ def test_push_prefers_updated_project_export(monkeypatch): assert r.json()["project_export"]["name"] == "UPDATED_PROJECT" +def test_push_from_a_process_that_did_not_run_it_writes_the_synced_export(monkeypatch, tmp_path): + """The worker runs the edit and the backend serves the push: the backend + finds the run on disk, and must still write and return the synced model.""" + run_id = "c" * 32 + workspace = tmp_path / f"{runner_module.LLM_TEMP_DIR_PREFIX}{run_id}_abcd1234" + workspace.mkdir() + (workspace / "main.py").write_text("print('hi')\n") + monkeypatch.setattr(runner_module, "_run_workspace_root", lambda: str(tmp_path)) + asyncio.run(current_runtime().registry.put(run_id, SmartRunEntry( + file_path=str(workspace / "main.py"), file_name="main.py", is_zip=False, + temp_dir=str(workspace), created_at=time.time(), updated_project_export=_export("UPDATED_PROJECT")))) + current_runtime().registry._entries.pop(run_id) + fake = _CapturingGitHubService() + _install(monkeypatch, fake) + + r = _post({ + "run_id": run_id, + "projectExport": _export("REQUEST_PROJECT"), + "deploy_config": {"repo_name": "my-generated-app"}, + }, headers={"X-GitHub-Session": "sess"}) + + assert r.status_code == 200 + assert fake.pushed_diagrams_json["name"] == "UPDATED_PROJECT" + assert r.json()["project_export"]["name"] == "UPDATED_PROJECT" + + def test_push_falls_back_to_request_export_when_no_delta(monkeypatch): """No stored delta (generate/resume, or a no-op modify) → diagrams.json is written from the request's projectExport.""" diff --git a/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_model_offer.py b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_model_offer.py new file mode 100644 index 000000000..34e2aa6a8 --- /dev/null +++ b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_model_offer.py @@ -0,0 +1,138 @@ +"""A modify run whose model sync changed the model offers that model to the editor (#845). + +The done event says a model is available and what it adds; ``GET +/spec-driven/download/{run_id}/model`` returns the export the GitHub push writes, +from any process that serves the run, for as long as the download. +""" +import asyncio +import json +import os +import time + +import httpx +from httpx._transports.asgi import ASGITransport + +from besser.utilities.web_modeling_editor.backend.backend import app +from besser.utilities.web_modeling_editor.backend.services.spec_driven import runner as runner_module +from besser.utilities.web_modeling_editor.backend.services.spec_driven.runner import ( + SmartGenerationRunner, + SmartRunEntry, +) +from tests.utilities.web_modeling_editor.backend._runtime import current_runtime +from tests.utilities.web_modeling_editor.backend.spec_driven.test_runner import ( + _build_request, + _collect_frames, + _FakeClient, + _MultiFileOrchestrator, + _parse_frame, +) + +BASE_URL = "http://testserver" + + +def _synced_export() -> dict: + export = _build_request().project.model_dump(mode="json") + export["diagrams"]["ClassDiagram"][0]["title"] = "Synced" + return export + + +class _SyncingOrchestrator(_MultiFileOrchestrator): + """A modify run whose model sync added a class and an attribute.""" + + def run(self, instructions: str) -> str: + out = super().run(instructions) + self._updated_project_export = _synced_export() + recipe_path = os.path.join(out, ".besser_recipe.json") + with open(recipe_path, encoding="utf-8") as fh: + recipe = json.load(fh) + recipe["model_sync"] = {"status": "synced", "added_classes": ["Payment"], + "added_attributes": ["Order.total"]} + with open(recipe_path, "w", encoding="utf-8") as fh: + json.dump(recipe, fh) + return out + + +class _PlainOrchestrator(_MultiFileOrchestrator): + _updated_project_export = None + + +def _run(monkeypatch, orchestrator) -> tuple[str, dict]: + monkeypatch.setattr(runner_module, "LLMOrchestrator", orchestrator) + monkeypatch.setattr(runner_module, "create_llm_client", lambda **_: _FakeClient()) + runner = SmartGenerationRunner(_build_request(), runtime=current_runtime()) + events = [_parse_frame(frame) for frame in asyncio.run(_collect_frames(runner))] + return runner.run_id, next(e for e in events if e["event"] == "done") + + +def _get(path: str) -> httpx.Response: + async def go(): + async with httpx.AsyncClient(transport=ASGITransport(app=app), base_url=BASE_URL) as ac: + return await ac.get(path) + + return asyncio.run(go()) + + +def _forget_in_memory(run_id: str) -> None: + """What a process that did not run ``run_id`` holds: nothing in memory, the run's dirs on disk.""" + current_runtime().registry._entries.pop(run_id) + + +def _cleanup(run_id: str) -> None: + entry = asyncio.run(current_runtime().registry.get(run_id)) + if entry is not None: + runner_module._remove_run_dir(entry.temp_dir) + current_runtime().registry._entries.pop(run_id, None) + + +def test_done_offers_the_synced_model_and_its_additions(monkeypatch): + run_id, done = _run(monkeypatch, _SyncingOrchestrator) + try: + assert done["updatedModel"] == { + "url": f"/besser_api/spec-driven/download/{run_id}/model", + "changes": ["class Payment added from the request", "Order.total added from the request"], + } + response = _get(done["updatedModel"]["url"]) + assert response.status_code == 200 + assert response.json() == {"run_id": run_id, "project_export": _synced_export()} + finally: + _cleanup(run_id) + + +def test_a_process_that_did_not_run_it_serves_the_same_model(monkeypatch): + """The worker runs the edit; the backend serves the push and may serve this endpoint.""" + run_id, done = _run(monkeypatch, _SyncingOrchestrator) + try: + _forget_in_memory(run_id) + response = _get(done["updatedModel"]["url"]) + assert response.status_code == 200 + assert response.json()["project_export"] == _synced_export() + finally: + _cleanup(run_id) + + +def test_a_run_that_changed_no_model_offers_none(monkeypatch): + run_id, done = _run(monkeypatch, _PlainOrchestrator) + try: + assert done["updatedModel"] is None + assert _get(f"/besser_api/spec-driven/download/{run_id}/model").status_code == 404 + finally: + _cleanup(run_id) + + +def test_the_model_expires_with_the_download(monkeypatch, tmp_path): + run_id = "e" * 32 + workspace = tmp_path / f"{runner_module.LLM_TEMP_DIR_PREFIX}{run_id}_abcd1234" + workspace.mkdir() + (workspace / "main.py").write_text("print('hi')\n") + monkeypatch.setattr(runner_module, "_run_workspace_root", lambda: str(tmp_path)) + entry = SmartRunEntry(file_path=str(workspace / "main.py"), file_name="main.py", is_zip=False, + temp_dir=str(workspace), created_at=time.time() - 10 * 365 * 24 * 3600, + updated_project_export=_synced_export()) + asyncio.run(current_runtime().registry.put(run_id, entry)) + _forget_in_memory(run_id) + + assert _get(f"/besser_api/spec-driven/download/{run_id}/model").status_code == 404 + + +def test_an_unknown_run_has_no_model(): + assert _get("/besser_api/spec-driven/download/" + "0" * 32 + "/model").status_code == 404 From 72f00ab5c2058afe75c4a28015ab78b985530986 Mon Sep 17 00:00:00 2001 From: ArmSL Date: Wed, 2 Dec 2026 22:59:30 +0100 Subject: [PATCH 7/9] docs(spec-driven): document the run model offer and its endpoint The API page lists GET /spec-driven/download/{run_id}/model and the done event's updatedModel field; the model sync section says where the synced model is kept and how the editor gets it. --- docs/source/spec_driven_agent/api.rst | 14 ++++++++++++++ docs/source/spec_driven_agent/configuration.rst | 4 +++- docs/source/web_editor_backend.rst | 4 ++-- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/source/spec_driven_agent/api.rst b/docs/source/spec_driven_agent/api.rst index c397239dc..81025fcdc 100644 --- a/docs/source/spec_driven_agent/api.rst +++ b/docs/source/spec_driven_agent/api.rst @@ -76,6 +76,15 @@ Endpoints - GET - Download the generated ZIP/file (re-fetchable for ``BESSER_LLM_ARCHIVE_TTL_SECONDS``). + * - ``/spec-driven/download/{run_id}/model`` + - GET + - The project model a modify run's model sync changed, for a run whose + ``done`` event carried ``updatedModel``: ``{"run_id", "project_export"}``, + where ``project_export`` is the generation request's project with the + class diagram model sync changed, the model the GitHub push writes to + ``buml/``. Kept, like the download, for ``BESSER_LLM_ARCHIVE_TTL_SECONDS`` + and served by any process that shares the run workspace; ``404`` when + the run is unknown or expired, or changed no model. * - ``/spec-driven/push-to-github`` - POST - Push a finished run's code — plus the re-importable model under @@ -445,6 +454,11 @@ SSE event types it (``class Category added from the request``, ``Recommendation.rating added from the request``, ``enumeration Status: Paused added from the request``) (modify runs). + ``updatedModel`` (additive) is set only when model sync changed the + model: ``url``, where to ``GET`` it (``/spec-driven/download/{run_id}/model``), + and ``changes``, what it adds (the ``modelChanges`` lines model sync + wrote). The editor offers it on the run card instead of loading it + unasked; an older editor ignores the field. ``blockerCount`` is 0 on a run cut short (by a limit, an error or a cancel). On an ``incomplete`` run it is the unresolved blockers. On a run diff --git a/docs/source/spec_driven_agent/configuration.rst b/docs/source/spec_driven_agent/configuration.rst index bbecd9f1c..bdc743058 100644 --- a/docs/source/spec_driven_agent/configuration.rst +++ b/docs/source/spec_driven_agent/configuration.rst @@ -344,7 +344,9 @@ never changes: ``associations``, ``new_enumerations``, ``llm_error``, the ``error_code`` above. A failure and the elements added are also a line of the *This run* section of ``BESSER_GENERATION.md``, and the elements a synced run added are listed in the ``done`` event's ``modelChanges`` (see -:doc:`api`). +:doc:`api`). The synced model itself is kept with the run's download: the +``done`` event's ``updatedModel`` says where to fetch it, so the editor can +offer it to a project that is not pushed to GitHub. Every recipe also says, in ``model_drift``, what the delivered code has that the run's class model (after model sync) lacks, so a regeneration from the model would diff --git a/docs/source/web_editor_backend.rst b/docs/source/web_editor_backend.rst index b34d7815b..cbd018b20 100644 --- a/docs/source/web_editor_backend.rst +++ b/docs/source/web_editor_backend.rst @@ -527,13 +527,13 @@ have no safe place for one and are returned unchanged. Spec-Driven Agent ^^^^^^^^^^^^^^^^^ -Thirteen endpoints under ``/spec-driven/*`` back the +Fourteen endpoints under ``/spec-driven/*`` back the :doc:`Spec-Driven Agent ` -- the hybrid pipeline that runs a deterministic generator, lets an LLM customise its output, then validates and repairs the result: ``generate``, ``preview``, ``config``, ``runs/{run_id}``, ``runs/{run_id}/events``, ``runs/{run_id}/events.json``, ``resume/{run_id}``, ``cancel/{run_id}``, ``finish/{run_id}``, ``download/{run_id}``, -``push-to-github``, ``import-github-run`` and ``import-generated-code``. +``download/{run_id}/model``, ``push-to-github``, ``import-github-run`` and ``import-generated-code``. They are documented once, with the agent, rather than twice: see :doc:`spec_driven_agent/api` for the endpoint table, the request contract, the From 862d8022ef06b4010bb058a08ecceeb2ccbf4c98 Mon Sep 17 00:00:00 2001 From: ArmSL Date: Wed, 2 Dec 2026 23:48:28 +0100 Subject: [PATCH 8/9] fix(spec-driven): redact agent credentials from a run's kept model A run's synced model is the generation request's project, Agent diagram configuration included. It was written in plain text next to the run's download and returned as is by GET /spec-driven/download/{run_id}/model, so an LLM key or bot token in an agent's config reached anyone holding the run id, while the zip's and the repository's model files redact them. The kept copy and every read of the run's model now go through the same credential redaction as the repository's model files. --- .../backend/services/spec_driven/runner.py | 18 ++++++++--- docs/source/spec_driven_agent/api.rst | 3 +- .../spec_driven/test_run_model_offer.py | 32 +++++++++++++++++++ 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py index 81aa7b5ea..3e0c5229c 100644 --- a/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py +++ b/besser/utilities/web_modeling_editor/backend/services/spec_driven/runner.py @@ -167,6 +167,7 @@ format_sse, ) from besser.utilities.secret_redaction import ( + redact_credentials, redact_data, redact_text, scrub_secret_files, @@ -1102,11 +1103,16 @@ class SmartRunEntry: packaged: bool = False +def _redacted_project_export(export: dict) -> dict: + """``export`` without the agent's runtime credentials, as the repo's model files carry it.""" + return redact_credentials(export, yaml_fields=repo_model.AGENT_CONFIG_YAML_FIELDS)[0] + + def run_updated_project_export(entry: SmartRunEntry) -> Optional[dict]: - """The run's ``updated_project_export``; an entry another process registered reads - the copy kept with the download. None when the run's model sync changed no model.""" + """The run's ``updated_project_export``, credentials redacted; an entry another process + registered reads the copy kept with the download. None when model sync changed no model.""" if isinstance(entry.updated_project_export, dict): - return entry.updated_project_export + return _redacted_project_export(entry.updated_project_export) export = read_run_json(os.path.join(run_download_dir(entry.temp_dir), _UPDATED_PROJECT_NAME)) return export if isinstance(export, dict) else None @@ -1151,8 +1157,10 @@ def _store_download(run_id: str, entry: SmartRunEntry) -> SmartRunEntry: copy_plain_file(entry.file_path, artifact, root=entry.temp_dir, dst_root=download_dir) updated_project = os.path.join(download_dir, _UPDATED_PROJECT_NAME) if isinstance(entry.updated_project_export, dict): - write_atomic_plain(updated_project, json.dumps(entry.updated_project_export, separators=(",", ":")), - root=download_dir) + write_atomic_plain( + updated_project, + json.dumps(_redacted_project_export(entry.updated_project_export), separators=(",", ":")), + root=download_dir) else: with contextlib.suppress(FileNotFoundError): os.remove(updated_project) diff --git a/docs/source/spec_driven_agent/api.rst b/docs/source/spec_driven_agent/api.rst index 81025fcdc..bd7460c7d 100644 --- a/docs/source/spec_driven_agent/api.rst +++ b/docs/source/spec_driven_agent/api.rst @@ -82,7 +82,8 @@ Endpoints ``done`` event carried ``updatedModel``: ``{"run_id", "project_export"}``, where ``project_export`` is the generation request's project with the class diagram model sync changed, the model the GitHub push writes to - ``buml/``. Kept, like the download, for ``BESSER_LLM_ARCHIVE_TTL_SECONDS`` + ``buml/``. Agent credentials (LLM keys, bot tokens) are redacted, as + in the repository's model files. Kept, like the download, for ``BESSER_LLM_ARCHIVE_TTL_SECONDS`` and served by any process that shares the run workspace; ``404`` when the run is unknown or expired, or changed no model. * - ``/spec-driven/push-to-github`` diff --git a/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_model_offer.py b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_model_offer.py index 34e2aa6a8..89a318fa4 100644 --- a/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_model_offer.py +++ b/tests/utilities/web_modeling_editor/backend/spec_driven/test_run_model_offer.py @@ -136,3 +136,35 @@ def test_the_model_expires_with_the_download(monkeypatch, tmp_path): def test_an_unknown_run_has_no_model(): assert _get("/besser_api/spec-driven/download/" + "0" * 32 + "/model").status_code == 404 + + +def test_the_kept_and_served_model_carries_no_agent_credentials(monkeypatch, tmp_path): + """The run's model is the request's project, agent config included: keep and serve it redacted, + as the zip's model files and the GitHub push do.""" + key = "sk-proj-ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcd" + export = _synced_export() + export["diagrams"]["AgentDiagram"] = [{ + "id": "agent-1", "title": "Agent", "model": {"elements": {}}, + "config": {"llm": {"provider": "openai", "api_key": key}}, + "configYaml": f"llm:\n api_key: {key}\n", + }] + run_id = "f" * 32 + workspace = tmp_path / f"{runner_module.LLM_TEMP_DIR_PREFIX}{run_id}_abcd1234" + workspace.mkdir() + (workspace / "main.py").write_text("print('hi')\n") + monkeypatch.setattr(runner_module, "_run_workspace_root", lambda: str(tmp_path)) + entry = SmartRunEntry(file_path=str(workspace / "main.py"), file_name="main.py", is_zip=False, + temp_dir=str(workspace), created_at=time.time(), updated_project_export=export) + asyncio.run(current_runtime().registry.put(run_id, entry)) + try: + kept = (tmp_path / f"{workspace.name}.download" / "updated_project.json").read_text() + assert key not in kept + served = _get(f"/besser_api/spec-driven/download/{run_id}/model") + assert served.status_code == 200 + assert key not in served.text + # The class diagram the editor takes is unchanged. + assert served.json()["project_export"]["diagrams"]["ClassDiagram"] == export["diagrams"]["ClassDiagram"] + _forget_in_memory(run_id) + assert key not in _get(f"/besser_api/spec-driven/download/{run_id}/model").text + finally: + current_runtime().registry._entries.pop(run_id, None) From 5e1fe0efc6f7da16b573ef9beed48c24871f633d Mon Sep 17 00:00:00 2001 From: ArmSL Date: Fri, 4 Dec 2026 09:55:06 +0100 Subject: [PATCH 9/9] chore(submodule): editor to develop (af747176) --- besser/utilities/web_modeling_editor/frontend | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/besser/utilities/web_modeling_editor/frontend b/besser/utilities/web_modeling_editor/frontend index f32bb7ff4..af747176e 160000 --- a/besser/utilities/web_modeling_editor/frontend +++ b/besser/utilities/web_modeling_editor/frontend @@ -1 +1 @@ -Subproject commit f32bb7ff46db62b6e4a5e47ff618dd292eb686f7 +Subproject commit af747176e5b0be35156b29da20b618e11b6c0918