* feat(system-prompt): admit section updates incrementally * docs(system-prompt): accept retirement restart gap * test(system-prompt): cover retirement and reentry before admission * test(system-prompt): align rebase fixtures and persistence history * fix: align section prompt consumers and CI fixtures * test: pin credentials for section snapshot fixtures * test: align remaining snapshots with section admission * test: preserve section metadata in Web and PowerShell replays * refactor(system-prompt): retire sections through Cordis cleanup * chore: refresh section admission history after rebase * fix(system-prompt): advance admission head after compaction * fix(system-prompt): trim sections before admission hashing * docs: move system upgrade guides to current version * docs: add system message contribution cookbook * perf(system-prompt): avoid indexing history for admission * refactor(system-prompt): derive admission from logged sections * test(system-prompt): update lifecycle and compaction consumers * test(system-prompt): refresh CLI section event expectations * test(system-prompt): refresh question composer section metadata * feat(system-prompt): resolve same-name sections by scope * refactor(persona): use ordinary section registrations * refactor(system-prompt): clarify assembly and related control flow * test(system-prompt): reconcile rebased section snapshots * test(python): use current system text helper after rebase * test(system-prompt): refresh CLI expected section blocks * test(system-prompt): reconcile latest master integration * test(agent-loop): seed tools before deferred addition assertion * refactor(compaction): replace system heads when compacting prefixes * refactor(system-prompt): separate source text and notice attribution * fix(system-prompt): preserve legacy instructions in compaction snapshots * refactor(compaction): build system snapshots while reading the summary prefix * refactor(compaction): rebuild current system instructions * refactor(system-prompt): defer compaction rebuild to admission * refactor(system-prompt): remove redundant fixtures and setup * fix(plan-mode): announce committed user transitions * docs(system-prompt): reconcile section lifecycle and compaction design * refactor(system-prompt): consolidate projection version increments * fix(system-prompt): reconcile master integration and replay fixtures * docs(system-prompt): align upgrade guide with current release * refactor(system-prompt): make admission operations explicit * fix(system-prompt): reconcile master API and release changes * docs(system-prompt): regenerate catalogs after master refresh * refactor(llm-pi-ai): delegate text rendering to pi-ai * fix(llm-pi-ai): preserve blank lines between system text parts * refactor(system-prompt): remove redundant retirement metadata * refactor(system-prompt): own admission and use canonical surface targets * refactor(system-prompt): compare captured sections at commitment Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears. After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step. * test: await the session read fixture and type a matcher for lint * test(tool-executor-ptc): describe same-name section override on executor replacement Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves. * docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3 The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory. * refactor(system-prompt): rebuild over system messages without sections A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice. Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions. * test(web): refresh the imported-conversation recording and drop a stray bytecode file The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge. * refactor(session): scan system nodes on read surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message. * refactor(session): rename SystemSurfaceNode.hasContent to isEmpty The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared. * refactor(llm): join system text through extractTextContent extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins. The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well. * test(snapshots): refresh the PowerShell and cordis-inspect recordings The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename. * test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs. * test(web): refresh Web recordings for section-attributed system messages Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line. plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row. The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line. * refactor(system-prompt): require the retry argument of systemUpdates The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is. * docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5 The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory. * test(web): refresh the mention path presence recording for section-attributed system messages * test: align two specs that master left failing The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies. * chore: remove a Python cache file committed by mistake
276 lines
15 KiB
Python
276 lines
15 KiB
Python
"""Native plan guidance, input timing and reviewed exit through the real SDK profile."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from deepseek_harness.models import CommandExecution
|
|
from deepseek_harness import RunResult, Session, UserQuestionRequest
|
|
from test_commands_runtime import (
|
|
_Completion, _Runtime, _SESSION_ID, _WAIT_SECONDS, _assert_request_permission,
|
|
_command_pair, _native_result, _of_type, _permission_facts, _read_events,
|
|
_request_texts, _runtime, _text_blocks, _wait_activity,
|
|
)
|
|
|
|
_PLAN = "# Implement the change\n\n- Inspect existing code.\n- Make the smallest change.\n- Run focused tests."
|
|
_PLAN_REVISED = "# Revised plan\n\n- Include a rollback procedure."
|
|
_GUIDANCE = "You are in plan mode."
|
|
|
|
|
|
def _command(runtime: _Runtime, session: Session, text: str) -> CommandExecution:
|
|
result = runtime.call(runtime.harness.client._query, session.id, text)
|
|
assert isinstance(result, CommandExecution)
|
|
assert result.result.kind == "success", result.result.text
|
|
return result
|
|
|
|
|
|
def _system_text(request: dict) -> str:
|
|
blocks = _text_blocks(request.get("system", ""))
|
|
for message in request["messages"]:
|
|
if message["role"] == "system":
|
|
blocks.extend(_text_blocks(message["content"]))
|
|
return "\n".join(blocks)
|
|
|
|
|
|
def _plan_active(request: dict) -> bool:
|
|
system = _system_text(request)
|
|
return system.rfind("Plan mode is active. Follow the plan-mode instructions.") > system.rfind(
|
|
"Plan mode is inactive. The plan-mode instructions no longer apply."
|
|
)
|
|
|
|
|
|
def _tool_names(request: dict) -> set[str]:
|
|
return {tool["name"] for tool in request.get("tools", [])}
|
|
|
|
|
|
def _review(plan: str = _PLAN) -> _Completion:
|
|
return _Completion("", tool_call=("exit_plan_mode", {"plan": plan}))
|
|
|
|
|
|
def _answer(request: UserQuestionRequest, choice: str, feedback: str | None = None) -> dict:
|
|
[question] = request.questions
|
|
assert question["intent"]["kind"] == "plan-review"
|
|
item = {"id": question["id"], "selected": [choice]}
|
|
if feedback is not None:
|
|
item["custom"] = feedback
|
|
return {"answers": [item]}
|
|
|
|
|
|
def test_bare_plan_and_off_change_only_plan_state_without_a_model_request(tmp_path: Path) -> None:
|
|
with _runtime(tmp_path, [], initial_permission="workspace-write") as runtime:
|
|
session = runtime.harness.start_session(_SESSION_ID)
|
|
on = _command(runtime, session, " \n/计划\t ")
|
|
off = _command(runtime, session, "/plan off")
|
|
repeated = _command(runtime, session, "/plan off")
|
|
assert runtime.model.captured() == []
|
|
assert "already inactive" in repeated.result.text
|
|
assert runtime.harness.config.env["DSH_PERMISSION_MODE"] == "workspace-write"
|
|
events = _read_events(runtime.logs)
|
|
for execution in [on, off, repeated]:
|
|
_command_pair(events, execution, "plan")
|
|
assert [e["data"] for e in _of_type(events, "plan/mode")] == [{"active": True}, {"active": False}]
|
|
assert not _of_type(events, "turn/start")
|
|
assert [e["data"] for e in _permission_facts(events)] == [
|
|
{"preset": "workspace-write"}, {"mode": "workspace-write"}, {"policy": "ask"},
|
|
]
|
|
|
|
|
|
def test_plan_body_uses_native_input_then_off_deactivates_guidance_but_keeps_exit_tool(tmp_path: Path) -> None:
|
|
with _runtime(tmp_path, [_Completion("PLAN_READY"), _Completion("AFTER_OFF")], initial_permission="workspace-write") as runtime:
|
|
session = runtime.harness.start_session(_SESSION_ID)
|
|
execution = _command(runtime, session, "/计划 Design this change without tools. ")
|
|
_wait_activity(runtime, session)
|
|
first = runtime.model.captured()[0]
|
|
assert "Design this change without tools." in _request_texts(first)
|
|
assert "/计划 Design this change without tools. " not in _request_texts(first)
|
|
assert _plan_active(first)
|
|
assert "The following instructions apply only while plan mode is active." in _system_text(first)
|
|
assert _GUIDANCE in _system_text(first)
|
|
assert "Do not edit or write files" in _system_text(first)
|
|
assert {"exit_plan_mode", "write", "edit"} <= _tool_names(first)
|
|
_assert_request_permission(first, "workspace-write", "ask")
|
|
_command(runtime, session, "/plan off")
|
|
result = runtime.call(session.run, "Continue after the user changed the mode.")
|
|
assert isinstance(result, RunResult) and result.final_response == "AFTER_OFF"
|
|
second = runtime.model.captured()[1]
|
|
assert not _plan_active(second)
|
|
assert _system_text(second).count(_GUIDANCE) == 1
|
|
assert "Plan mode is inactive. The plan-mode instructions no longer apply." in _system_text(second)
|
|
assert _tool_names(first) == _tool_names(second)
|
|
assert "The user switched this session back to the default mode." in _request_texts(second)
|
|
_assert_request_permission(second, "workspace-write", "ask")
|
|
events = _read_events(runtime.logs)
|
|
_command_pair(events, execution, "plan")
|
|
assert len(_of_type(events, "turn/start")) == 2
|
|
assert len(_permission_facts(events)) == 3
|
|
|
|
|
|
def test_plan_body_steers_the_next_step_of_a_running_turn(tmp_path: Path) -> None:
|
|
first = _Completion("FIRST_REPLY", blocked=True)
|
|
with _runtime(tmp_path, [first, _Completion("PLANNING_REPLY")], initial_permission="workspace-write") as runtime:
|
|
session = runtime.harness.start_session(_SESSION_ID)
|
|
observing = runtime.workers.submit(session.run, "Start this task without tools.")
|
|
assert first.entered.wait(_WAIT_SECONDS)
|
|
execution = _command(runtime, session, "/plan Design a smaller change.")
|
|
assert not first.release.is_set() and not observing.done()
|
|
first.release.set()
|
|
result = observing.result(timeout=_WAIT_SECONDS)
|
|
assert isinstance(result, RunResult) and result.final_response == "PLANNING_REPLY"
|
|
a, b = runtime.model.captured()
|
|
assert not _plan_active(a)
|
|
assert _plan_active(b)
|
|
assert "Design a smaller change." in _request_texts(b)
|
|
_assert_request_permission(b, "workspace-write", "ask")
|
|
events = _read_events(runtime.logs)
|
|
_command_pair(events, execution, "plan")
|
|
assert [e["data"] for e in _of_type(events, "step/start")] == [{"turn": 1, "step": 1}, {"turn": 1, "step": 2}]
|
|
assert len(_of_type(events, "turn/start")) == 1
|
|
|
|
|
|
@pytest.mark.parametrize("cancel", [False, True])
|
|
def test_running_bare_selection_does_not_force_a_step_and_can_be_cancelled(tmp_path: Path, cancel: bool) -> None:
|
|
first = _Completion("FIRST_REPLY", blocked=True)
|
|
with _runtime(tmp_path, [first, _Completion("NEXT_REPLY")], initial_permission="workspace-write") as runtime:
|
|
session = runtime.harness.start_session(_SESSION_ID)
|
|
observing = runtime.workers.submit(session.run, "Start without tools.")
|
|
assert first.entered.wait(_WAIT_SECONDS)
|
|
_command(runtime, session, "/plan")
|
|
if cancel:
|
|
cancelled = _command(runtime, session, "/plan off")
|
|
assert "cancelled" in cancelled.result.text
|
|
assert len(runtime.model.captured()) == 1
|
|
first.release.set()
|
|
assert isinstance(observing.result(timeout=_WAIT_SECONDS), RunResult)
|
|
assert len(runtime.model.captured()) == 1
|
|
assert isinstance(runtime.call(session.run, "Inspect the next task without tools."), RunResult)
|
|
assert _plan_active(runtime.model.captured()[1]) is (not cancel)
|
|
events = _read_events(runtime.logs)
|
|
assert len(_of_type(events, "turn/start")) == 2
|
|
assert len(_of_type(events, "step/start")) == 2
|
|
assert [e["data"] for e in _of_type(events, "plan/mode")] == ([] if cancel else [{"active": True}])
|
|
|
|
|
|
@pytest.mark.parametrize("first_choice", ["Approve", "Keep planning", "dismiss"])
|
|
def test_review_approval_feedback_and_dismissal_keep_native_model_behavior(tmp_path: Path, first_choice: str) -> None:
|
|
seen: list[str] = []
|
|
def answer(request: UserQuestionRequest, cancelled: threading.Event):
|
|
assert not cancelled.is_set()
|
|
seen.append(request.questions[0]["detail"])
|
|
if len(seen) == 1:
|
|
if first_choice == "dismiss":
|
|
return {"cancelled": True}
|
|
return _answer(request, first_choice, "Include rollback." if first_choice == "Keep planning" else None)
|
|
return _answer(request, "Approve")
|
|
completions = [_review()]
|
|
if first_choice == "Keep planning":
|
|
completions.append(_review(_PLAN_REVISED))
|
|
if first_choice != "dismiss":
|
|
completions.append(_Completion("AFTER_APPROVAL"))
|
|
with _runtime(tmp_path, completions, initial_permission="workspace-write", on_user_question=answer) as runtime:
|
|
session = runtime.harness.start_session(_SESSION_ID)
|
|
_command(runtime, session, "/plan Prepare a plan and present it for review.")
|
|
_wait_activity(runtime, session)
|
|
requests = runtime.model.captured()
|
|
assert seen == ([_PLAN, _PLAN_REVISED] if first_choice == "Keep planning" else [_PLAN])
|
|
assert _plan_active(requests[0])
|
|
if first_choice == "Keep planning":
|
|
assert _plan_active(requests[1])
|
|
assert "Include rollback." in str(requests[1]["messages"])
|
|
if first_choice != "dismiss":
|
|
assert not _plan_active(requests[-1])
|
|
assert _tool_names(requests[0]) == _tool_names(requests[-1])
|
|
else:
|
|
assert len(requests) == 1, "dismissal started another model request"
|
|
for request in requests:
|
|
_assert_request_permission(request, "workspace-write", "ask")
|
|
events = _read_events(runtime.logs)
|
|
assert [e["data"]["active"] for e in _of_type(events, "plan/mode")] == ([True] if first_choice == "dismiss" else [True, False])
|
|
assert len(_of_type(events, "turn/start")) == len(_of_type(events, "turn/end")) == 1
|
|
assert len(_permission_facts(events)) == 3
|
|
if first_choice == "dismiss":
|
|
results = _of_type(events, "tool/result")
|
|
assert len(results) == 1
|
|
assert "The user dismissed the plan review" in str(results[0]["data"])
|
|
|
|
|
|
def test_no_review_provider_keeps_plan_mode_and_reports_tool_failure(tmp_path: Path) -> None:
|
|
with _runtime(tmp_path, [_review(), _Completion("REVIEW_UNAVAILABLE")], initial_permission="workspace-write") as runtime:
|
|
session = runtime.harness.start_session(_SESSION_ID)
|
|
_command(runtime, session, "/plan Prepare a plan.")
|
|
_wait_activity(runtime, session)
|
|
first, second = runtime.model.captured()
|
|
assert _plan_active(first) and _plan_active(second)
|
|
assert "no user-questions answerer accepted the request" in str(second["messages"])
|
|
_command(runtime, session, "/plan off")
|
|
events = _read_events(runtime.logs)
|
|
[result] = _of_type(events, "tool/result")
|
|
assert result["data"]["message"]["isError"] is True
|
|
assert result["data"]["error"]["code"] == "NO_PROVIDER"
|
|
assert len(_permission_facts(events)) == 3
|
|
|
|
|
|
def test_plan_state_survives_resume_without_changing_permissions(tmp_path: Path) -> None:
|
|
with _runtime(tmp_path, [], initial_permission="workspace-write") as runtime:
|
|
session = runtime.harness.start_session(_SESSION_ID)
|
|
_command(runtime, session, "/plan")
|
|
with _runtime(tmp_path, [_Completion("RESTORED_PLAN")], initial_permission="workspace-write") as resumed:
|
|
session = resumed.call(resumed.harness.resume_session, _SESSION_ID)
|
|
assert isinstance(resumed.call(session.run, "Continue planning without tools."), RunResult)
|
|
[request] = resumed.model.captured()
|
|
assert _plan_active(request)
|
|
_assert_request_permission(request, "workspace-write", "ask")
|
|
events = _read_events(resumed.logs)
|
|
assert [e["data"] for e in _of_type(events, "plan/mode")] == [{"active": True}]
|
|
|
|
|
|
def test_top_level_plan_result_identifies_the_session_for_wait_continue_and_resume(tmp_path: Path) -> None:
|
|
first = _Completion("PLAN_READY", blocked=True)
|
|
with _runtime(tmp_path, [first, _Completion("CONTINUED_PLAN")], initial_permission="workspace-write") as runtime:
|
|
running = runtime.workers.submit(runtime.harness.run, "/plan Design this change without tools.")
|
|
assert first.entered.wait(_WAIT_SECONDS), runtime.model.failures
|
|
assert not running.done()
|
|
first.release.set()
|
|
execution = running.result(timeout=_WAIT_SECONDS)
|
|
assert isinstance(execution, RunResult)
|
|
assert execution.finish_reason == "completed" and execution.final_response == "PLAN_READY"
|
|
session = runtime.harness.start_session(execution.session_id)
|
|
continued = runtime.call(runtime.harness.run, "Continue this plan without tools.", session_id=execution.session_id)
|
|
assert isinstance(continued, RunResult)
|
|
assert continued.session_id == execution.session_id
|
|
assert continued.final_response == "CONTINUED_PLAN"
|
|
assert "Design this change without tools." in _request_texts(runtime.model.captured()[1])
|
|
with _runtime(tmp_path, [_Completion("RESTORED_PLAN")], initial_permission="workspace-write") as resumed:
|
|
session = resumed.call(resumed.harness.resume_session, execution.session_id)
|
|
result = resumed.call(session.run, "Finish reviewing this plan without tools.")
|
|
assert isinstance(result, RunResult) and result.session_id == execution.session_id
|
|
assert result.final_response == "RESTORED_PLAN"
|
|
[request] = resumed.model.captured()
|
|
assert _plan_active(request)
|
|
assert "Design this change without tools." in _request_texts(request)
|
|
assert "Continue this plan without tools." in _request_texts(request)
|
|
events = _read_events(resumed.logs, session_id=execution.session_id)
|
|
_command_pair(events, execution, "plan")
|
|
assert len(_of_type(events, "turn/start")) == 3
|
|
|
|
|
|
def test_plan_state_is_local_and_literal_prompts_do_not_toggle_it(tmp_path: Path) -> None:
|
|
with _runtime(tmp_path, [_Completion("OTHER"), _Completion("PLANNING"), _Completion("RAW_INPUT")],
|
|
initial_permission="workspace-write") as runtime:
|
|
session = runtime.harness.start_session(_SESSION_ID)
|
|
_command(runtime, session, "/plan")
|
|
other = runtime.harness.start_session("plan-other")
|
|
assert isinstance(runtime.call(other.run, "Inspect your own task without tools."), RunResult)
|
|
assert isinstance(runtime.call(session.run, "Inspect the plan without tools."), RunResult)
|
|
runtime.call(runtime.harness.client.session_prompt, session.id, [{"type": "text", "text": "/plan off"}])
|
|
_wait_activity(runtime, session)
|
|
first, second, third = runtime.model.captured()
|
|
assert not _plan_active(first)
|
|
assert _plan_active(second)
|
|
assert _plan_active(third)
|
|
assert "/plan off" in _request_texts(third)
|
|
assert not _of_type(_read_events(runtime.logs, session_id="plan-other"), "plan/mode")
|
|
assert [e["data"] for e in _of_type(_read_events(runtime.logs), "plan/mode")] == [{"active": True}]
|