From 2052dc4e5534dbc5a4bf7692869092a47b5cb04e Mon Sep 17 00:00:00 2001 From: Dominique Vernier <28610057+itdove@users.noreply.github.com> Date: Sun, 22 Nov 2026 11:55:10 -0500 Subject: [PATCH 1/2] fix(agent): bound OpenCode lookup and preserve reopen identity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Extend OpenCode capture and verification to a 10-second budget - Refuse unverified reopen attempts without replacing saved session identity - Add recovery guidance and regression coverage for timeout scenarios - Update documentation and changelog entries 🤖 Generated with [OpenCode](https://opencode.ai) Co-Authored-By: OpenCode --- AGENTS.md | 10 +- CHANGELOG.md | 4 + devflow/agent/factory.py | 7 +- devflow/cli/commands/open_command.py | 45 +++++-- devflow/cli_skills/daf-workflow/SKILL.md | 11 +- docs/guides/troubleshooting.md | 18 +-- docs/reference/ai-agent-support-matrix.md | 5 +- docs/reference/commands.md | 13 +- tests/test_kilo_capture_budget.py | 5 +- tests/test_opencode_capture_budget.py | 139 ++++++++++++++++++---- 10 files changed, 197 insertions(+), 60 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 256e451..1522cd9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1837,7 +1837,7 @@ class Session(BaseModel): - ✓ Bounded OpenCode capture and launch-proven native identity (itdove/devaiflow#648) - Retains created IDs and persists them before `daf open` starts the child, avoiding post-exit rediscovery of known IDs - - Shares a two-second fallback query deadline across polling, version detection, and subprocess execution, with content-free failure diagnostics + - Shares a bounded fallback query deadline across polling, version detection, and subprocess execution, with content-free failure diagnostics - Refuses unresolved pending/missing-ID reopen instead of silently replacing conversations; preserves project scoping, ambiguity, and clone guards - ✓ Retry cancelled first OpenCode setup without weakening identity guards (itdove/devaiflow#650) @@ -1860,7 +1860,7 @@ class Session(BaseModel): - Revalidates session/worktree/source identity and active process use before removal - ✓ Kilo interactive native session capture budget (itdove/devaiflow#693) - - Gives Kilo version detection and session-list startup a bounded 10-second budget independent of OpenCode's 2-second budget + - Gives Kilo version detection and session-list startup its own bounded 10-second budget - Preserves exact project-scoped ID capture, post-exit DAF title updates, and fail-closed timeout/ambiguity handling - Adds slow-query, timeout, title, project-scope, and reopen-budget regression coverage @@ -1881,6 +1881,12 @@ class Session(BaseModel): - Documents that manual Git operations do not complete sessions or update status/time tracking - Verifies completion skips redundant commit/push work for pre-committed and pre-pushed changes +- ✓ Bounded OpenCode lookup and verified reopen recovery (itdove/devaiflow#699) + - Gives fallback capture and reopen verification a bounded 10-second budget for slow successful queries + - Preserves saved identity and metadata on timeout or failed/ambiguous verification; never launches a replacement + - Shows recovery steps tied to the recorded project/worktree path and verified native ID + - Adds slow-reopen, timeout, and metadata-preservation regression coverage + ## Release Management ### Overview diff --git a/CHANGELOG.md b/CHANGELOG.md index 708ae08..bf1718f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- **Bounded OpenCode session lookup and verified reopen recovery** (#699) + - Extends fallback capture and reopen verification to a bounded 10-second query budget + - Keeps timeouts and failed/ambiguous verification fail-closed without replacing saved identity + - Shows recovery guidance using the recorded project/worktree path and verified `daf update` flow - **Issue-aware completed worktree cleanup** (#675) - Requires explicit issue-closure approval and a fresh tracker-confirmed closed status before `daf complete` removes a worktree - Adds `daf worktree clean ` to retry cleanup for completed sessions without repeating completion operations diff --git a/devflow/agent/factory.py b/devflow/agent/factory.py index 9e8939b..cf41c5f 100644 --- a/devflow/agent/factory.py +++ b/devflow/agent/factory.py @@ -316,10 +316,9 @@ PENDING_CAPTURE_PLACEHOLDER = "pending-capture" _SESSION_CAPTURE_POLL_ATTEMPTS = 10 _SESSION_CAPTURE_POLL_INTERVAL = 0.1 -OPENCODE_CAPTURE_TIMEOUT = 2.0 -# Kilo session queries include version detection and a fresh CLI startup. Keep -# that backend-specific startup allowance separate from OpenCode's tighter -# fallback-capture budget. +OPENCODE_CAPTURE_TIMEOUT = 10.0 +# Keep separate backend budgets so startup-latency changes for one CLI do not +# silently change the other adapter's bounded session-capture behavior. KILO_CAPTURE_TIMEOUT = 10.0 diff --git a/devflow/cli/commands/open_command.py b/devflow/cli/commands/open_command.py index 0206f4a..c1d06c7 100644 --- a/devflow/cli/commands/open_command.py +++ b/devflow/cli/commands/open_command.py @@ -81,7 +81,6 @@ ) - class _JsonAwareConsole: """Suppress Rich output while a command is producing JSON.""" @@ -360,25 +359,40 @@ def _extract_repository_from_issue_key(issue_key: str, issue_tracker: Optional[s def _refuse_unverified_opencode_session( - session_name: str, reason: str, output_json: bool, backend: str = "opencode" + session_name: str, + reason: str, + output_json: bool, + backend: str = "opencode", + project_path: Optional[str] = None, ) -> NoReturn: """Preserve unresolved native identity instead of silently launching a replacement.""" if backend == "kilo": agent_name = "Kilo" - list_guidance = "Kilo's `kilo session list --format json --all`" + list_guidance = "`kilo session list --format json --all`" else: agent_name = "OpenCode" - list_guidance = "OpenCode's session list" + list_guidance = ( + "`opencode session list --format json` (add `--standalone` on v2)" + ) + recorded_location = ( + f"the recorded project/worktree `{project_path}`" + if project_path + else "the recorded project/worktree" + ) message = ( f"Cannot safely resume {agent_name}: {reason}. No replacement conversation was launched. " - "If a native conversation exists, verify its ID and project directory with " - f"{list_guidance}, then run " - f"`daf update {session_name} --session-id VERIFIED_ID` outside the agent session. " + f"If a native conversation exists, from a regular terminal in {recorded_location}, " + f"inspect {list_guidance} and verify its ID and project directory. Then run " + f"`daf update {session_name} --session-id VERIFIED_ID` outside the agent session " + f"and retry `daf open {session_name}`. " "To explicitly archive this record and start over (even without a saved branch), " f"use `daf open {session_name} --new-conversation`." ) if output_json: - emit_json(success=False, error={"code": "AGENT_SESSION_UNVERIFIED", "message": message}) + emit_json( + success=False, + error={"code": "AGENT_SESSION_UNVERIFIED", "message": message}, + ) else: console.print(f"[yellow]{escape(message)}[/yellow]") raise click.exceptions.Exit(1) @@ -617,8 +631,6 @@ def refuse(message: str) -> bool: return True - - @require_outside_claude @_json_output_scope def open_session( @@ -1085,6 +1097,11 @@ def open_session( "or explicit never-launched provenance; automatic recovery is unavailable", output_json, backend=effective_agent_backend, + project_path=( + active_conv.temp_directory + or active_conv.worktree_path + or active_conv.project_path + ), ) if ( @@ -1096,6 +1113,7 @@ def open_session( # Check if the session exists using the agent-aware check # This handles both Claude (.jsonl file) and OpenCode (database query) correctly from devflow.agent import create_agent_client + agent_client = create_agent_client(effective_agent_backend) agent_name = agent_client.get_agent_name() @@ -1118,7 +1136,8 @@ def open_session( else OPENCODE_CAPTURE_TIMEOUT ) conversation_exists = ( - active_conv.ai_agent_session_id in agent_client.get_existing_sessions( + active_conv.ai_agent_session_id + in agent_client.get_existing_sessions( check_path, timeout=capture_timeout, strict=True ) ) @@ -1128,6 +1147,7 @@ def open_session( str(exc), output_json, backend=effective_agent_backend, + project_path=check_path, ) if not conversation_exists: _refuse_unverified_opencode_session( @@ -1135,6 +1155,7 @@ def open_session( "the saved native ID was not found in this project", output_json, backend=effective_agent_backend, + project_path=check_path, ) else: conversation_exists = agent_client.session_exists(active_conv.ai_agent_session_id, check_path) @@ -4762,8 +4783,6 @@ def _handle_temp_directory_for_ticket_creation(session, session_manager, config= return True - - def _display_conflict_resolution_help(project_path: str, session_name: str, agent_name: str = "Claude Code") -> None: """Display detailed help for resolving merge conflicts. diff --git a/devflow/cli_skills/daf-workflow/SKILL.md b/devflow/cli_skills/daf-workflow/SKILL.md index ae17f17..e94368d 100644 --- a/devflow/cli_skills/daf-workflow/SKILL.md +++ b/devflow/cli_skills/daf-workflow/SKILL.md @@ -263,12 +263,15 @@ session metadata are preserved on refusal. OpenCode retains native IDs returned by titled launch rather than rediscovering them on exit; `daf open` saves that identity before starting the child. Fallback -capture has a two-second total query deadline and fails closed on query errors or -same-project ambiguity. A legacy `pending-capture` reopen cannot prove ownership +capture and saved-ID reopen verification use a bounded 10-second total query +deadline and fail closed on query errors or same-project ambiguity. A legacy +`pending-capture` reopen cannot prove ownership without a saved launch ID/baseline, so it stops with verification guidance rather than silently replacing the conversation. The user can verify the native ID and -canonical directory, then run `daf update --session-id ` -outside the agent, or deliberately use `daf open --new-conversation`. +canonical directory from the recorded project/worktree path, then run +`daf update --session-id ` outside the agent and retry +`daf open `, or deliberately use +`daf open --new-conversation`. Do not guess an ID from ordering/titles or edit backend storage to recover it. Cancelled first-open setup is retryable with ordinary `daf open` when DAF saved diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md index ab621c3..a949b52 100644 --- a/docs/guides/troubleshooting.md +++ b/docs/guides/troubleshooting.md @@ -1928,9 +1928,10 @@ If you can't resolve the issue: DAF retains IDs returned by titled creation and `daf open` saves them before starting OpenCode. Known IDs are not rediscovered after exit. When fallback -discovery is necessary, a two-second deadline covers queries, version detection, -and polling sleeps, rather than allowing ten independent ten-second queries. -This deadline does not bypass completion's directory-holder checks. +discovery or saved-ID reopen verification is necessary, a bounded 10-second +deadline covers queries, version detection, and polling sleeps, rather than +allowing ten independent queries. This deadline does not bypass completion's +directory-holder checks. Warnings distinguish a failed query (timeout, CLI exit, invalid JSON, or version detection), no new project-scoped sessions, and multiple new candidates. A failed @@ -1954,11 +1955,14 @@ a replacement. A missing saved native ID or failed verification also stops safel From a regular terminal, after exiting the agent: -1. If a native conversation exists, inspect `opencode session list --format json --standalone` on v2 (omit - `--standalone` on v1). Verify the intended ID and canonical project directory; - do not infer ownership from timestamps or titles alone. +1. A timeout is not proof that the saved session is missing. In the exact + project/worktree path recorded for the DAF conversation, inspect + `opencode session list --format json --standalone` on v2 (omit `--standalone` + on v1). Verify the intended ID and canonical project directory; do not infer + ownership from timestamps or titles alone. 2. Restore a verified association with - `daf update --session-id `, then reopen. + `daf update --session-id `, then retry + `daf open `. 3. If you deliberately want a fresh conversation instead, run `daf open --new-conversation`. This archives the previous conversation and its identity/history metadata; it is not recovery of the diff --git a/docs/reference/ai-agent-support-matrix.md b/docs/reference/ai-agent-support-matrix.md index 3ff7742..762ca15 100644 --- a/docs/reference/ai-agent-support-matrix.md +++ b/docs/reference/ai-agent-support-matrix.md @@ -852,8 +852,9 @@ ID after their title is synchronized to the current DAF session name. Native IDs returned by titled creation are retained instead of being rediscovered after exit. `daf open` persists that launch-proven ID before starting the child. Known IDs are never replaced by polling results. Fallback discovery has a -two-second total deadline, including CLI execution and lazy version detection; -query errors, empty results, and ambiguity have different content-free diagnostics. +bounded 10-second total deadline, including CLI execution and lazy version +detection; query errors, empty results, and ambiguity have different content-free +diagnostics. An unavailable pre-launch snapshot cannot be treated as an empty baseline. Commit-message generation also adapts the `run` flags by major version: v1 diff --git a/docs/reference/commands.md b/docs/reference/commands.md index f0e0db4..ce844e0 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -1252,13 +1252,16 @@ inactive sessions alone do not prove exclusive workspace ownership. See [temporary-clone troubleshooting](../guides/troubleshooting.md#temporary-clone-still-in-use-after-agent-exit). OpenCode launch-proven native IDs are retained rather than rediscovered on exit; -`daf open` saves them before starting the child. Fallback post-exit capture has a -two-second total query deadline and distinguishes query failure, no new sessions, -and ambiguous same-project candidates. Legacy `pending-capture` reopen, missing +`daf open` saves them before starting the child. Fallback capture and saved-ID +reopen verification use a bounded 10-second total query deadline, distinguishing +query failures, no new sessions, and ambiguous same-project candidates. Legacy `pending-capture` reopen, missing native IDs, and failed verification stop without selecting a replacement -(`AGENT_SESSION_UNVERIFIED` in JSON). Verify the ID and directory before using +(`AGENT_SESSION_UNVERIFIED` in JSON). Verify the ID and directory in the recorded +project/worktree path, then use `daf update --session-id ` outside the agent, -or explicitly archive/start fresh with `daf open --new-conversation`. +and retry `daf open `. Use `--standalone` to inspect the session list +on OpenCode v2. Alternatively, explicitly archive/start fresh with +`daf open --new-conversation`. This explicit start-over also supports OpenCode records without a saved branch; the old identity/history is archived and initial branch setup runs for the new conversation. New first-open setup records carry explicit never-launched diff --git a/tests/test_kilo_capture_budget.py b/tests/test_kilo_capture_budget.py index 5c0d8d3..1be1baf 100644 --- a/tests/test_kilo_capture_budget.py +++ b/tests/test_kilo_capture_budget.py @@ -34,7 +34,7 @@ def advance(seconds): def test_slow_kilo_queries_capture_project_session_with_backend_budget( monkeypatch, clock ): - """Version detection and slow listing stay within Kilo's larger bounded budget.""" + """Version detection and slow listing stay within Kilo's bounded budget.""" agent = KiloAgent() list_calls = 0 list_timeouts = [] @@ -91,7 +91,8 @@ def launch(**kwargs): ) assert list_calls == 3 assert list_timeouts[1] == pytest.approx(KILO_CAPTURE_TIMEOUT) - assert KILO_CAPTURE_TIMEOUT > OPENCODE_CAPTURE_TIMEOUT + assert KILO_CAPTURE_TIMEOUT == 10.0 + assert KILO_CAPTURE_TIMEOUT >= OPENCODE_CAPTURE_TIMEOUT assert clock.now < KILO_CAPTURE_TIMEOUT + 1 diff --git a/tests/test_opencode_capture_budget.py b/tests/test_opencode_capture_budget.py index 13dec2f..1ce1cfa 100644 --- a/tests/test_opencode_capture_budget.py +++ b/tests/test_opencode_capture_budget.py @@ -47,7 +47,9 @@ def native_agent(monkeypatch): return agent -def test_slow_queries_share_one_wall_clock_budget(native_agent, monkeypatch, clock, capsys): +def test_slow_queries_share_one_wall_clock_budget( + native_agent, monkeypatch, clock, capsys +): """Even a visible candidate is not accepted after a later query times out.""" timeouts = [] @@ -61,29 +63,35 @@ def query(command, **kwargs): monkeypatch.setattr("devflow.agent.opencode_agent.subprocess.run", query) conversation = SimpleNamespace(ai_agent_session_id=PENDING_CAPTURE_PLACEHOLDER) - assert not capture_agent_session_id(native_agent, "opencode", "/project", conversation, set()) - assert clock.now == pytest.approx(OPENCODE_CAPTURE_TIMEOUT) + assert not capture_agent_session_id( + native_agent, "opencode", "/project", conversation, set(), timeout=2 + ) + assert clock.now == pytest.approx(2) assert len(timeouts) == 2 assert timeouts == sorted(timeouts, reverse=True) assert conversation.ai_agent_session_id == PENDING_CAPTURE_PLACEHOLDER assert "timed out" in capsys.readouterr().out -def test_slow_successful_queries_cover_grace_without_ten_commands(native_agent, monkeypatch, clock): - """Ordinary half-second CLI starts count as observation time, not extra latency.""" +def test_slow_successful_queries_exceed_old_budget_without_ten_commands( + native_agent, monkeypatch, clock +): + """Slow successful CLI starts fit the extended bound and count as observation time.""" calls = [] def query(command, **kwargs): calls.append(kwargs["timeout"]) - assert kwargs["timeout"] >= 0.65 - clock.now += 0.65 + assert kwargs["timeout"] >= 1.25 + clock.now += 1.25 return Mock(returncode=0, stdout='[{"id":"ses_new","directory":"/project"}]') monkeypatch.setattr("devflow.agent.opencode_agent.subprocess.run", query) conversation = SimpleNamespace(ai_agent_session_id=PENDING_CAPTURE_PLACEHOLDER) - assert capture_agent_session_id(native_agent, "opencode", "/project", conversation, set()) + assert capture_agent_session_id( + native_agent, "opencode", "/project", conversation, set() + ) assert len(calls) == 2 - assert clock.now == pytest.approx(1.4) + assert clock.now == pytest.approx(2.6) assert conversation.ai_agent_session_id == "ses_new" @@ -132,7 +140,9 @@ def test_exhausted_query_budget_does_not_start_process(native_agent, monkeypatch run.assert_not_called() -@pytest.mark.parametrize("duration", [2.0, 2.1]) +@pytest.mark.parametrize( + "duration", [OPENCODE_CAPTURE_TIMEOUT, OPENCODE_CAPTURE_TIMEOUT + 0.1] +) def test_one_expensive_observation_is_not_enough_to_accept_identity( native_agent, monkeypatch, clock, duration ): @@ -144,7 +154,9 @@ def query(*args, **kwargs): monkeypatch.setattr(native_agent, "get_existing_sessions", query) conversation = SimpleNamespace(ai_agent_session_id=PENDING_CAPTURE_PLACEHOLDER) - assert not capture_agent_session_id(native_agent, "opencode", "/project", conversation, set()) + assert not capture_agent_session_id( + native_agent, "opencode", "/project", conversation, set() + ) assert conversation.ai_agent_session_id == PENDING_CAPTURE_PLACEHOLDER @@ -278,7 +290,9 @@ def test_version_failure_diagnostics_do_not_repeat_cli_contents(native_agent, mo "devflow.agent.opencode_agent.subprocess.run", Mock(return_value=Mock(returncode=1, stdout="private session text", stderr="")), ) - with pytest.raises(OpenCodeSessionQueryError, match="version detection failed") as caught: + with pytest.raises( + OpenCodeSessionQueryError, match="version detection failed" + ) as caught: native_agent.get_existing_sessions("/project", strict=True) assert "private session text" not in str(caught.value) @@ -290,7 +304,9 @@ def open_session_case(temp_daf_home, tmp_path, native_agent, monkeypatch): loader = ConfigLoader() loader.save_config( Config( - jira=JiraConfig(url="https://jira.example.com", user="test-user", transitions={}), + jira=JiraConfig( + url="https://jira.example.com", user="test-user", transitions={} + ), repos=RepoConfig(), agent_backend="opencode", ) @@ -318,7 +334,10 @@ def open_session_case(temp_daf_home, tmp_path, native_agent, monkeypatch): "should_launch_claude_code", ): monkeypatch.setattr(prefix + name, lambda *args, **kwargs: True) - monkeypatch.setattr(prefix + "_detect_working_directory_from_cwd", lambda *args: None) + monkeypatch.setattr(prefix + "Confirm.ask", Mock(return_value=False)) + monkeypatch.setattr( + prefix + "_detect_working_directory_from_cwd", lambda *args: None + ) monkeypatch.setattr(prefix + "get_active_profile", lambda *args, **kwargs: None) monkeypatch.setattr(prefix + "setup_signal_handlers", lambda *args: None) monkeypatch.setattr(prefix + "is_cleanup_done", lambda: False) @@ -364,7 +383,9 @@ def spawn(command, **kwargs): assert agent.get_existing_sessions.call_count == 2 -def test_fallback_capture_finishes_before_completion_prompt(open_session_case, monkeypatch, clock): +def test_fallback_capture_finishes_before_completion_prompt( + open_session_case, monkeypatch, clock +): """Actual CLI query duration counts toward the bounded post-exit observation window.""" loader, _, session, agent = open_session_case events = [] @@ -381,7 +402,12 @@ def query(command, **kwargs): sessions = ( [] if not exited - else [{"id": "ses_captured", "directory": session.active_conversation.project_path}] + else [ + { + "id": "ses_captured", + "directory": session.active_conversation.project_path, + } + ] ) return Mock(returncode=0, stdout=json.dumps(sessions)) @@ -399,7 +425,9 @@ def complete_prompt(*args): events.append("prompt") assert clock.now - exited[0] <= OPENCODE_CAPTURE_TIMEOUT assert ( - SessionManager(loader).get_session(session.name).active_conversation.ai_agent_session_id + SessionManager(loader) + .get_session(session.name) + .active_conversation.ai_agent_session_id == "ses_captured" ) @@ -407,7 +435,8 @@ def complete_prompt(*args): monkeypatch.setattr("devflow.agent.opencode_agent.subprocess.Popen", spawn) monkeypatch.setattr(agent, "wait_for_exit", wait) monkeypatch.setattr( - "devflow.cli.commands.open_command._prompt_for_complete_on_exit", complete_prompt + "devflow.cli.commands.open_command._prompt_for_complete_on_exit", + complete_prompt, ) result = CliRunner().invoke(cli, ["open", session.name]) assert result.exit_code == 0, result.output @@ -415,6 +444,58 @@ def complete_prompt(*args): assert "Warning" not in result.output +def test_slow_successful_reopen_resumes_saved_opencode_identity( + open_session_case, monkeypatch, clock +): + """A lookup slower than the former bound can still verify and resume the saved ID.""" + loader, manager, session, agent = open_session_case + conversation = session.active_conversation + conversation.ai_agent_session_id = "ses_existing" + conversation.agent_launch_started = True + manager.update_session(session) + query_calls = [] + + def slow_query(project_path, *, timeout, strict): + query_calls.append((project_path, timeout, strict)) + clock.now += 2.5 + return {"ses_existing"} + + monkeypatch.setattr(agent, "get_existing_sessions", slow_query) + real_popen = subprocess.Popen + spawned_commands = [] + + def spawn(command, **kwargs): + if command[0] != "opencode": + return real_popen(command, **kwargs) + spawned_commands.append(command) + return Mock(returncode=0) + + monkeypatch.setattr("devflow.agent.opencode_agent.subprocess.Popen", spawn) + monkeypatch.setattr(agent, "wait_for_exit", Mock()) + monkeypatch.setattr(agent, "update_session_title", Mock(return_value=True)) + monkeypatch.setattr( + "devflow.cli.commands.open_command._prompt_for_complete_on_exit", Mock() + ) + + result = CliRunner().invoke(cli, ["open", session.name]) + + assert result.exit_code == 0, result.output + assert clock.now == pytest.approx(2.5) + assert query_calls == [(conversation.project_path, OPENCODE_CAPTURE_TIMEOUT, True)] + assert OPENCODE_CAPTURE_TIMEOUT > 2 + assert len(spawned_commands) == 1 + assert ( + spawned_commands[0][spawned_commands[0].index("--session") + 1] + == "ses_existing" + ) + assert ( + SessionManager(loader) + .get_session(session.name) + .active_conversation.ai_agent_session_id + == "ses_existing" + ) + + @pytest.mark.parametrize("invalid_id", ["ses_different", "not-a-native-id"]) def test_launch_callback_cannot_replace_known_native_identity( native_agent, monkeypatch, invalid_id @@ -439,7 +520,9 @@ def bad_launch(**kwargs): @pytest.mark.parametrize("json_mode", [False, True]) -@pytest.mark.parametrize("state", ["pending", "missing", "query-failure"]) +@pytest.mark.parametrize( + "state", ["pending", "missing", "query-failure", "query-timeout"] +) def test_unverified_reopen_never_replaces_identity( open_session_case, monkeypatch, json_mode, state ): @@ -451,15 +534,29 @@ def test_unverified_reopen_never_replaces_identity( manager.update_session(session) query = Mock(return_value=set()) if state == "query-failure": - query.side_effect = OpenCodeSessionQueryError("OpenCode session list returned invalid JSON") + query.side_effect = OpenCodeSessionQueryError( + "OpenCode session list returned invalid JSON" + ) + elif state == "query-timeout": + query.side_effect = OpenCodeSessionQueryError( + "OpenCode session query timed out within its time budget" + ) monkeypatch.setattr(agent, "get_existing_sessions", query) spawn = Mock() monkeypatch.setattr("devflow.agent.opencode_agent.subprocess.Popen", spawn) original = SessionManager(loader).get_session(session.name).model_dump() - result = CliRunner().invoke(cli, ["open", session.name, *(["--json"] if json_mode else [])]) + result = CliRunner().invoke( + cli, ["open", session.name, *(["--json"] if json_mode else [])] + ) assert result.exit_code == 1, result.output assert "No replacement conversation was launched" in " ".join(result.output.split()) assert "--new-conversation" in result.output + assert str(session.active_conversation.project_path) in result.output + assert "opencode session list --format json" in result.output + assert f"daf open {session.name}" in result.output + if state == "query-timeout": + assert "timed out" in result.output + assert query.call_args.kwargs["timeout"] == OPENCODE_CAPTURE_TIMEOUT if json_mode: assert json.loads(result.output)["error"]["code"] == "AGENT_SESSION_UNVERIFIED" spawn.assert_not_called() From 432ec060bd9ee4bf53e99da95cc208b7f3fa5063 Mon Sep 17 00:00:00 2001 From: Dominique Vernier <28610057+itdove@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:38:32 -0500 Subject: [PATCH 2/2] fix: clarify Kilo session list guidance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Prefix Kilo session list command with the agent name - Preserve existing OpenCode guidance behavior 🤖 Generated with [OpenCode](https://opencode.ai) Co-Authored-By: OpenCode --- devflow/cli/commands/open_command.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/devflow/cli/commands/open_command.py b/devflow/cli/commands/open_command.py index c1d06c7..08e6b76 100644 --- a/devflow/cli/commands/open_command.py +++ b/devflow/cli/commands/open_command.py @@ -368,7 +368,7 @@ def _refuse_unverified_opencode_session( """Preserve unresolved native identity instead of silently launching a replacement.""" if backend == "kilo": agent_name = "Kilo" - list_guidance = "`kilo session list --format json --all`" + list_guidance = "Kilo's `kilo session list --format json --all`" else: agent_name = "OpenCode" list_guidance = (