From 5d6c96231c05af38e9952b92680781df463cd42f Mon Sep 17 00:00:00 2001 From: GUOGUO Date: Mon, 23 Nov 2026 12:26:42 +0800 Subject: [PATCH 1/7] fix(apps): close six review defects in host, compare, delivery and views CUDA inspection matched the requested model as a substring, so L4 accepted an L40S. Inspection and qualification now share one whole-token match. compare --action status read every trial's job without error handling, so one damaged or locked job failed the command. An unreadable job now blocks only its trial, the same reading report already applies. after_final passed the unresolved session path to the exporter, which refuses symlinked ancestors; a session reached through a symlink committed its final but never published delivery. The path is resolved first. The service-reuse dashboard page lacked the generator tag the writer checks before replacing a page, so a second write was refused. The Codex search import unwrapped only [shell, -c, script]. Shell options before -c and a leading env are now unwrapped; other shells and script files count as incomplete coverage instead of no retrieval. The read agent listed the workspace before its failure handler, so a missing task or a symlinked workspace emitted no agent.failed event. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: GUOGUO --- src/inferrsi/apps/delivery/__init__.py | 6 ++- src/inferrsi/apps/host/platforms/cuda.py | 11 +++-- .../integrations/anthropic/anthropic_agent.py | 10 +++-- src/inferrsi/apps/views/codex_search.py | 41 +++++++++++++++++-- src/inferrsi/apps/views/dashboard.py | 3 +- .../apps/workflows/benchmark_compare.py | 7 +++- tests/test_anthropic_agent.py | 15 ++++++- tests/test_benchmark_compare.py | 2 + tests/test_codex_search_shell_forms.py | 26 ++++++++++++ tests/test_dashboard_service_page.py | 11 +++++ tests/test_inspection.py | 7 ++++ tests/test_module_boundaries.py | 4 ++ tests/test_project_optimization.py | 16 ++++++++ tests/test_project_service_reuse.py | 9 +++- 14 files changed, 150 insertions(+), 18 deletions(-) create mode 100644 tests/test_codex_search_shell_forms.py create mode 100644 tests/test_dashboard_service_page.py diff --git a/src/inferrsi/apps/delivery/__init__.py b/src/inferrsi/apps/delivery/__init__.py index 47d9b6cf9..e0d50e38c 100644 --- a/src/inferrsi/apps/delivery/__init__.py +++ b/src/inferrsi/apps/delivery/__init__.py @@ -274,9 +274,11 @@ def after_final(args, result): if args.session_action != "final": return result export_id = uuid.uuid4().hex - output = args.session / "delivery" / export_id + # The exporter refuses symlinked ancestors; Harness already resolved this session. + session = args.session.resolve() + output = session / "delivery" / export_id try: - delivery = export_bundle(args.session, output, export_id=export_id) + delivery = export_bundle(session, output, export_id=export_id) except Exception: # Presentation failure must never change the already committed execution outcome. delivery = { diff --git a/src/inferrsi/apps/host/platforms/cuda.py b/src/inferrsi/apps/host/platforms/cuda.py index 300f09599..062beef2d 100644 --- a/src/inferrsi/apps/host/platforms/cuda.py +++ b/src/inferrsi/apps/host/platforms/cuda.py @@ -7,6 +7,11 @@ import subprocess +def _names_model(name: str, device_model: str) -> bool: + # The requested model must be a whole token of the reported name: L4 is not L40S. + return re.search(rf"\b{re.escape(device_model)}\b", name, re.IGNORECASE) is not None + + def inspect_devices(*, device_ids, device_model, command): from . import tool_facts @@ -35,9 +40,7 @@ def inspect_devices(*, device_ids, device_model, command): ) if not device["selection_verified"]: device["status"] = "unavailable" - elif device_model and any( - device_model.casefold() not in row["name"].casefold() for row in selected - ): + elif device_model and any(not _names_model(row["name"], device_model) for row in selected): device["status"] = "device_model_mismatch" else: device["status"] = "available" @@ -70,7 +73,7 @@ def qualify_devices(*, count: int, device_model: str): ] selected = [gpu for gpu in devices if gpu["index"] in ids or gpu["uuid"] in ids] if len(selected) != count or any( - not re.search(r"\b" + re.escape(device_model) + r"\b", gpu["name"]) for gpu in selected + not _names_model(gpu["name"], device_model) for gpu in selected ): raise ValueError( f"The {count} requested physical devices must all be {device_model}; " diff --git a/src/inferrsi/apps/integrations/anthropic/anthropic_agent.py b/src/inferrsi/apps/integrations/anthropic/anthropic_agent.py index d5671bd07..b834e8663 100644 --- a/src/inferrsi/apps/integrations/anthropic/anthropic_agent.py +++ b/src/inferrsi/apps/integrations/anthropic/anthropic_agent.py @@ -456,7 +456,6 @@ def run_agent(workspace, schema, prompt, model, spec, timeout, emit, *, send, emit({"type": "agent.protocol", "client_kind": FULL_CONTEXT_KIND}) return run_full_context(workspace, schema, prompt, model, spec, timeout, emit, send=send, input_token_ceiling=input_token_ceiling) - files = exposed_files(workspace) tools = [ {"name": "read_file", "description": "Read one complete exposed UTF-8 file by relative path.", @@ -465,12 +464,15 @@ def run_agent(workspace, schema, prompt, model, spec, timeout, emit, *, send, {"name": "submit_answer", "description": "Submit a structured answer after reading task.json.", "input_schema": schema}] - messages = [{"role": "user", "content": prompt - + "\nUse read_file to read task.json; finish with submit_answer. " - "Plain text is not a submission. Exposed paths: " + canonical(sorted(files))}] deadline, task_read_at, tool_count = time.monotonic() + timeout, None, 0 totals = {"input_tokens": 0, "output_tokens": 0, "cached_input_tokens": 0} try: + # A rejected workspace is a retained failure like any later one. + files = exposed_files(workspace) + messages = [{"role": "user", "content": prompt + + "\nUse read_file to read task.json; finish with submit_answer. " + "Plain text is not a submission. Exposed paths: " + + canonical(sorted(files))}] for number in range(1, spec["max_requests"] + 1): remaining = deadline - time.monotonic() if remaining <= 0: diff --git a/src/inferrsi/apps/views/codex_search.py b/src/inferrsi/apps/views/codex_search.py index f87531d64..61c0eedf2 100644 --- a/src/inferrsi/apps/views/codex_search.py +++ b/src/inferrsi/apps/views/codex_search.py @@ -22,6 +22,8 @@ from .codex_tool_returns import _output_lines, _path, correlate_window _SHELLS = ("sh", "bash", "zsh", "dash") +# Interpreters whose inline code this reader does not tokenize. +_OPAQUE_SHELLS = ("pwsh", "powershell", "cmd", "fish") _TOOLS = ("rg", "cat", "sed", "nl") _SHELL_OPERATORS = {"|", "||", "&&", ";", ">", ">>", "<"} _MAX_PASSAGES = 12 @@ -196,17 +198,48 @@ def _rg_hits(output, cwd, corpus, scopes, mode, with_filename): return [{"ref": ref, "match_line": line} for ref, line in hits.items()], complete +def _without_env(argv): + """Drop a leading `env` and its NAME=value words; None for env options it cannot read.""" + if Path(argv[0]).name != "env": + return argv + rest = argv[1:] + while rest and "=" in rest[0] and not rest[0].startswith("-"): + rest = rest[1:] + return rest if rest and not rest[0].startswith("-") else None + + +def _shell_script(options): + """Return a shell's inline `-c` script, or None when it runs no inline script.""" + words = iter(options) + for word in words: + if word in ("-o", "+o"): + next(words, None) + elif word.startswith("-") and not word.startswith("--") and "c" in word[1:]: + return next(words, None) + elif not word.startswith(("-", "+")): + return None # A script file or another operand. + return None + + def _recorded_argv(item): original_argv = item.get("command") if (not isinstance(original_argv, list) or not original_argv or not all(isinstance(arg, str) for arg in original_argv)): return None, False - argv = original_argv + argv = _without_env(original_argv) + if not argv: + return None, False multiline = False - if (Path(argv[0]).name in _SHELLS and len(argv) == 3 - and argv[1] in ("-c", "-lc", "-ic", "-ilc")): + shell = Path(argv[0]).name.lower().removesuffix(".exe") + if shell in _OPAQUE_SHELLS: + return None, False + if shell in _SHELLS: + script = _shell_script(argv[1:]) + if script is None: + # Code this reader cannot see may still have searched. + return None, False try: - argv, multiline = _shell_argv(argv[2]) + argv, multiline = _shell_argv(script) except ValueError: return None, False compound = multiline or any(word in _SHELL_OPERATORS for word in argv) diff --git a/src/inferrsi/apps/views/dashboard.py b/src/inferrsi/apps/views/dashboard.py index 38254dd65..a566a5bcb 100644 --- a/src/inferrsi/apps/views/dashboard.py +++ b/src/inferrsi/apps/views/dashboard.py @@ -347,7 +347,8 @@ def render_dashboard(snapshot: dict, *, live: bool = False) -> str: return render_attempt(snapshot["data"]["fixed_attempt"], title="fixed attempt Dashboard") if snapshot["data"].get("evaluation_mode") == "service_reuse": refresh = '' if live else "" - return ('' + refresh + return ('' + + '' + refresh + 'Service-reuse optimization
' + snapshot["chart"] + '
') view = {**snapshot["data"], "live": live} diff --git a/src/inferrsi/apps/workflows/benchmark_compare.py b/src/inferrsi/apps/workflows/benchmark_compare.py index 7020e5839..83e980baf 100644 --- a/src/inferrsi/apps/workflows/benchmark_compare.py +++ b/src/inferrsi/apps/workflows/benchmark_compare.py @@ -335,7 +335,12 @@ def _status(root, plan, state, *, host_views=None): for trial in plan["trials"]: job = _job(root, trial) if host_views is None: - view = agent_sessions.status(job) if job.exists() else None + try: + view = agent_sessions.status(job) if job.exists() else None + except (OSError, ValueError) as error: + # As in report: unverifiable job evidence blocks only this trial. + view = {"state": "blocked", "native_session": None, + "error": type(error).__name__} else: view = host_views[trial["id"]] collection = state["collections"].get(trial["id"]) diff --git a/tests/test_anthropic_agent.py b/tests/test_anthropic_agent.py index 35ae87df3..866488940 100644 --- a/tests/test_anthropic_agent.py +++ b/tests/test_anthropic_agent.py @@ -140,10 +140,23 @@ def test_symlink_workspace_is_rejected_before_transport(workspace, spec): except OSError: pytest.skip("Host does not permit fixture symlinks") send, requests = scripted() + events = [] with pytest.raises(agent.AgentError, match="workspace_symlink"): agent.run_agent(workspace, SCHEMA_SMALL, "fixture", MODEL, spec, 30, - lambda _: None, send=send) + events.append, send=send) + assert not requests + assert events == [{"type": "agent.failed", "reason": "workspace_symlink"}] + + +def test_missing_task_is_retained_as_a_failure_before_transport(workspace, spec): + (workspace / "task.json").unlink() + send, requests = scripted() + events = [] + with pytest.raises(agent.AgentError, match="missing_task"): + agent.run_agent(workspace, SCHEMA_SMALL, "fixture", MODEL, spec, 30, + events.append, send=send) assert not requests + assert events == [{"type": "agent.failed", "reason": "missing_task"}] @pytest.mark.parametrize("field,value,reason,responses", [ diff --git a/tests/test_benchmark_compare.py b/tests/test_benchmark_compare.py index 2c1221514..c3d6b71aa 100644 --- a/tests/test_benchmark_compare.py +++ b/tests/test_benchmark_compare.py @@ -441,6 +441,8 @@ def test_bad_native_receipt_keeps_verified_arm_in_report(experiment, damage, fie for name in ("markdown", "html"): assert evidence_gap in Path(report["reports"][name]).read_text(encoding="utf-8") next_action = report["next_action"] + # The documented resume path reads the same damaged job without failing. + assert compare.status(root)["next_action"]["operation"] == next_action["operation"] if collected: assert next_action["operation"] == "completed" else: diff --git a/tests/test_codex_search_shell_forms.py b/tests/test_codex_search_shell_forms.py new file mode 100644 index 000000000..194344390 --- /dev/null +++ b/tests/test_codex_search_shell_forms.py @@ -0,0 +1,26 @@ +import pytest + +from inferrsi.apps.views.codex_search import _command, _recorded_argv + +PLAIN = ["bash", "-lc", "rg -n needle docs"] + + +@pytest.mark.parametrize("wrapped", [ + ["bash", "-o", "pipefail", "-lc", "rg -n needle docs"], + ["/usr/bin/env", "bash", "-lc", "rg -n needle docs"], + ["env", "LC_ALL=C", "bash", "-e", "-lc", "rg -n needle docs"], +]) +def test_wrapped_shell_forms_decode_like_the_plain_form(wrapped): + assert _recorded_argv({"command": PLAIN}) == (["rg", "-n", "needle", "docs"], False) + assert _recorded_argv({"command": wrapped}) == _recorded_argv({"command": PLAIN}) + + +@pytest.mark.parametrize("command", [ + ["pwsh", "-Command", "rg -n needle docs"], + ["bash", "search.sh"], + ["env", "-i", "bash", "-lc", "rg -n needle docs"], +]) +def test_unreadable_shell_forms_stay_incomplete(tmp_path, command): + # A search this reader cannot decode must not count as complete coverage. + item = {"command": command, "exit_code": 0, "aggregated_output": ""} + assert _command(item, tmp_path) == (None, False, None) diff --git a/tests/test_dashboard_service_page.py b/tests/test_dashboard_service_page.py new file mode 100644 index 000000000..85f6bc06c --- /dev/null +++ b/tests/test_dashboard_service_page.py @@ -0,0 +1,11 @@ +from inferrsi.apps.views.dashboard import _write_view_document, render_dashboard + + +def test_service_reuse_page_can_be_rewritten_by_the_dashboard_writer(tmp_path): + # write_dashboard renders this page and replaces only pages it recognizes as its own. + snapshot = {"data": {"evaluation_mode": "service_reuse"}, "chart": ""} + page = render_dashboard(snapshot) + output = tmp_path / "dashboard.html" + assert _write_view_document(output, page, generator="InferRSI dashboard") == output + assert _write_view_document(output, page, generator="InferRSI dashboard") == output + assert output.read_text(encoding="utf-8") == page diff --git a/tests/test_inspection.py b/tests/test_inspection.py index 76004ee74..65327a047 100644 --- a/tests/test_inspection.py +++ b/tests/test_inspection.py @@ -84,6 +84,13 @@ def test_requested_device_and_model_are_checked(self): mismatch = self.inspect_cuda(rows, ids=("0",), model="H200") self.assertEqual(mismatch["device"]["status"], "device_model_mismatch") + def test_cuda_model_must_be_a_whole_token_of_the_reported_name(self): + rows = "0, GPU-A, NVIDIA L40S, 999.0\n" + shorter = self.inspect_cuda(rows, model="L4") + self.assertEqual(shorter["device"]["status"], "device_model_mismatch") + exact = self.inspect_cuda(rows, model="l40s") + self.assertEqual(exact["device"]["status"], "available") + def test_successful_tool_without_requested_gpu_is_not_available(self): empty = self.inspect_cuda("") self.assertEqual(empty["device"]["status"], "unavailable") diff --git a/tests/test_module_boundaries.py b/tests/test_module_boundaries.py index 418548dc5..2282e8b3c 100644 --- a/tests/test_module_boundaries.py +++ b/tests/test_module_boundaries.py @@ -97,6 +97,10 @@ def test_cuda_qualification_accepts_campaign_supplied_count_and_sku(monkeypatch) with patch("inferrsi.apps.host.platforms.cuda.subprocess.run", side_effect=[device, busy]): with pytest.raises(ValueError, match="already has a compute process"): qualify_devices(count=1, device_model="H100") + # Inspection and qualification share one rule: H10 is not a token of H100. + with patch("inferrsi.apps.host.platforms.cuda.subprocess.run", side_effect=[device]): + with pytest.raises(ValueError, match="must all be H10"): + qualify_devices(count=1, device_model="H10") def test_shared_layers_do_not_import_campaigns_or_reverse_dependencies(): diff --git a/tests/test_project_optimization.py b/tests/test_project_optimization.py index 540fac993..1ed0ffd49 100644 --- a/tests/test_project_optimization.py +++ b/tests/test_project_optimization.py @@ -156,6 +156,22 @@ def test_project_runs_shared_rounds_and_final_from_retained_multifile_candidate( assert not (root / "rounds.jsonl").exists() # No second mutable control log. +def test_final_delivery_publishes_through_a_symlinked_session_path(project, capsys, tmp_path): + start(project, capsys) + submit(project, capsys, 20) + root = project[3] + alias = tmp_path / "alias" + try: + alias.symlink_to(root, target_is_directory=True) + except OSError: + pytest.skip("Host does not permit fixture symlinks") + assert main(["campaign", "final", "--directory", str(alias), + "--reason", "Caller ended the up-to-budget search"]) == 0 + receipt = json.loads(capsys.readouterr().out) + assert receipt["delivery"]["status"] == "published" + assert (root / "delivery" / receipt["delivery"]["export_id"] / "report.md").is_file() + + def test_quality_failure_is_retained_and_cannot_win(project, capsys): start(project, capsys) (project[0] / "engine.py").write_text("def compute(x):\n return 0\n", encoding="utf-8") diff --git a/tests/test_project_service_reuse.py b/tests/test_project_service_reuse.py index 6f40dc38d..79558e2be 100644 --- a/tests/test_project_service_reuse.py +++ b/tests/test_project_service_reuse.py @@ -409,13 +409,20 @@ def test_knowledge_and_dashboard_never_enter_legacy_fingerprint_readers(campaign assert context["context"]["contexts"] project_service.no_fingerprints(context) submit(campaign, version="selected", a=90) - from inferrsi.apps.views.dashboard import dashboard_snapshot, render_dashboard + from inferrsi.apps.views.dashboard import ( + dashboard_snapshot, + render_dashboard, + write_dashboard, + ) snapshot = dashboard_snapshot(campaign["root"]) project_service.no_fingerprints(snapshot) page = render_dashboard(snapshot) assert "Service-reuse optimization" in page and "Objective values" in page assert "sha256" not in page.lower() + # A refresh replaces the page this writer produced earlier. + output = write_dashboard(campaign["root"]) + assert write_dashboard(campaign["root"]) == output @pytest.mark.parametrize( From ef8cda3be8f570c4ad257c26de16030c6f8d1ada Mon Sep 17 00:00:00 2001 From: GUOGUO Date: Mon, 23 Nov 2026 17:56:38 +0800 Subject: [PATCH 2/7] fix(apps): export from the committed session root and read more shell forms after_final resolved the caller's session path again before its guarded export; if that path became unavailable after Harness committed final, the command failed instead of returning the committed result. Delivery now exports from the resolved session root that the committed result already carries, so nothing outside the export can fail. The Codex search import read the program name with the reader's path rules, so a Windows path recorded for env, bash or pwsh and read on POSIX was not recognized. Program names are now split on both separators. A -c after -- is a script file name, not inline code, so that form is recorded as incomplete. The changelog records the six fixes and that a service-reuse dashboard written before the marker existed needs a new output path or removal. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: GUOGUO --- CHANGELOG.md | 18 ++++++++++++++++++ src/inferrsi/apps/delivery/__init__.py | 6 ++++-- src/inferrsi/apps/views/codex_search.py | 11 +++++++++-- tests/test_codex_search_shell_forms.py | 14 ++++++++++++++ tests/test_project_optimization.py | 22 ++++++++++++++++++++++ 5 files changed, 67 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8777d67a9..bdf7c97e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ ## [Unreleased] +### Fixed + +- Six Apps defects from the 2026-11-23 repository review (Refs #595, group 2): + - CUDA inspection and qualification share one whole-token device-model match, so + `--device-model L4` no longer accepts an `L40S`. + - `benchmarks compare --action status` marks a trial whose job evidence cannot be read + as blocked instead of failing the whole command, as `report` already did. + - Delivery after `final` exports from the session root Harness committed under, so a + session reached through a symlinked directory publishes its report. + - The service-reuse dashboard page carries the generator marker the writer checks, so + it can be refreshed in place. A page written before this fix has no marker: write + the refreshed dashboard to a new output path or remove the old page first. + - `campaign import-search` unwraps shell options before `-c` and a leading `env`, on + either OS's path style. Other shells, script files and options it cannot read now + count as incomplete coverage instead of a complete record with no retrieval. + - The read agent records `agent.failed` when the workspace has no `task.json` or + contains a symbolic link. + ### Changed - `inferrsi.harness.scenarios` is now `inferrsi.harness.trials` (Refs #558). Its one diff --git a/src/inferrsi/apps/delivery/__init__.py b/src/inferrsi/apps/delivery/__init__.py index e0d50e38c..2ed812349 100644 --- a/src/inferrsi/apps/delivery/__init__.py +++ b/src/inferrsi/apps/delivery/__init__.py @@ -274,8 +274,10 @@ def after_final(args, result): if args.session_action != "final": return result export_id = uuid.uuid4().hex - # The exporter refuses symlinked ancestors; Harness already resolved this session. - session = args.session.resolve() + # Export from the resolved root Harness committed final under; resolving the + # caller's path again could fail after the commit, and the exporter refuses + # symlinked ancestors. + session = Path(result["session"]) output = session / "delivery" / export_id try: delivery = export_bundle(session, output, export_id=export_id) diff --git a/src/inferrsi/apps/views/codex_search.py b/src/inferrsi/apps/views/codex_search.py index 61c0eedf2..d00baf717 100644 --- a/src/inferrsi/apps/views/codex_search.py +++ b/src/inferrsi/apps/views/codex_search.py @@ -198,9 +198,14 @@ def _rg_hits(output, cwd, corpus, scopes, mode, with_filename): return [{"ref": ref, "match_line": line} for ref, line in hits.items()], complete +def _program(word): + """Program name of a recorded argv word from either OS, lower-cased, without .exe.""" + return re.split(r"[\\/]", word)[-1].lower().removesuffix(".exe") + + def _without_env(argv): """Drop a leading `env` and its NAME=value words; None for env options it cannot read.""" - if Path(argv[0]).name != "env": + if _program(argv[0]) != "env": return argv rest = argv[1:] while rest and "=" in rest[0] and not rest[0].startswith("-"): @@ -212,6 +217,8 @@ def _shell_script(options): """Return a shell's inline `-c` script, or None when it runs no inline script.""" words = iter(options) for word in words: + if word == "--": + return None # What follows is a script file, even if it looks like -c. if word in ("-o", "+o"): next(words, None) elif word.startswith("-") and not word.startswith("--") and "c" in word[1:]: @@ -230,7 +237,7 @@ def _recorded_argv(item): if not argv: return None, False multiline = False - shell = Path(argv[0]).name.lower().removesuffix(".exe") + shell = _program(argv[0]) if shell in _OPAQUE_SHELLS: return None, False if shell in _SHELLS: diff --git a/tests/test_codex_search_shell_forms.py b/tests/test_codex_search_shell_forms.py index 194344390..620659885 100644 --- a/tests/test_codex_search_shell_forms.py +++ b/tests/test_codex_search_shell_forms.py @@ -9,6 +9,9 @@ ["bash", "-o", "pipefail", "-lc", "rg -n needle docs"], ["/usr/bin/env", "bash", "-lc", "rg -n needle docs"], ["env", "LC_ALL=C", "bash", "-e", "-lc", "rg -n needle docs"], + # Recorded on Windows, read on any OS. + ["C:\\Program Files\\Git\\bin\\bash.exe", "-lc", "rg -n needle docs"], + ["C:\\Program Files\\Git\\usr\\bin\\env.exe", "bash", "-lc", "rg -n needle docs"], ]) def test_wrapped_shell_forms_decode_like_the_plain_form(wrapped): assert _recorded_argv({"command": PLAIN}) == (["rg", "-n", "needle", "docs"], False) @@ -19,8 +22,19 @@ def test_wrapped_shell_forms_decode_like_the_plain_form(wrapped): ["pwsh", "-Command", "rg -n needle docs"], ["bash", "search.sh"], ["env", "-i", "bash", "-lc", "rg -n needle docs"], + # After --, -c is a script file name, not inline code. + ["bash", "--", "-c", "rg -n needle docs"], + # Recorded on Windows, read on any OS. + ["C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command", "rg -n needle docs"], + ["C:\\Tools\\env.exe", "C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command", + "rg -n needle docs"], ]) def test_unreadable_shell_forms_stay_incomplete(tmp_path, command): # A search this reader cannot decode must not count as complete coverage. item = {"command": command, "exit_code": 0, "aggregated_output": ""} assert _command(item, tmp_path) == (None, False, None) + + +def test_dash_c_after_double_dash_names_a_script_file(): + # bash -- -c runs a script file named -c, so no inline code is visible. + assert _recorded_argv({"command": ["bash", "--", "-c", "rg -n needle docs"]}) == (None, False) diff --git a/tests/test_project_optimization.py b/tests/test_project_optimization.py index 1ed0ffd49..7e4a5271e 100644 --- a/tests/test_project_optimization.py +++ b/tests/test_project_optimization.py @@ -4,6 +4,7 @@ import os import subprocess import sys +from pathlib import Path import pytest @@ -172,6 +173,27 @@ def test_final_delivery_publishes_through_a_symlinked_session_path(project, caps assert (root / "delivery" / receipt["delivery"]["export_id"] / "report.md").is_file() +def test_final_delivery_never_resolves_the_session_path_after_commit(project, capsys, monkeypatch): + start(project, capsys) + submit(project, capsys, 20) + root = project[3] + original = Path.resolve + + def resolve(self, *args, **kwargs): + # The workspace becomes unavailable once final is committed. + state = json.loads((root / "state.json").read_text(encoding="utf-8")) + if self == root and state["final"] is not None: + raise OSError("Session path unavailable after commit") + return original(self, *args, **kwargs) + + monkeypatch.setattr(Path, "resolve", resolve) + assert main(["campaign", "final", "--directory", str(root), + "--reason", "Caller ended the up-to-budget search"]) == 0 + receipt = json.loads(capsys.readouterr().out) + assert receipt["state"] == "completed" + assert receipt["delivery"]["status"] == "published" + + def test_quality_failure_is_retained_and_cannot_win(project, capsys): start(project, capsys) (project[0] / "engine.py").write_text("def compute(x):\n return 0\n", encoding="utf-8") From a00314b12d211cbbd4f8eda6413c4ba8dabdb0c4 Mon Sep 17 00:00:00 2001 From: GUOGUO Date: Mon, 23 Nov 2026 21:18:15 +0800 Subject: [PATCH 3/7] fix(apps): read nested shells and Windows tool paths as the reader would After one shell unwrap, a shell, env or opaque interpreter in command position still runs code the import never decoded; the same command run directly was already incomplete, and now the wrapped form is too. A shell name used as a search pattern is not affected. The inner tool name used the reader's path rules and kept .exe, so a recorded C:/tools/rg.exe was not read as rg and counted as complete with no retrieval. Tool names now go through the same program-name normalization as the outer shell. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: GUOGUO --- src/inferrsi/apps/views/codex_search.py | 12 ++++++--- tests/test_codex_search_shell_forms.py | 36 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/inferrsi/apps/views/codex_search.py b/src/inferrsi/apps/views/codex_search.py index d00baf717..f782964a9 100644 --- a/src/inferrsi/apps/views/codex_search.py +++ b/src/inferrsi/apps/views/codex_search.py @@ -249,6 +249,12 @@ def _recorded_argv(item): argv, multiline = _shell_argv(script) except ValueError: return None, False + # A shell or env in command position after one unwrap runs code this reader did + # not decode, exactly as the same shell run directly would. + starts = [0, *(index + 1 for index, word in enumerate(argv) if word in _SHELL_OPERATORS)] + if any(index < len(argv) and _program(argv[index]) in (*_SHELLS, *_OPAQUE_SHELLS, "env") + for index in starts): + return None, False compound = multiline or any(word in _SHELL_OPERATORS for word in argv) return argv, compound @@ -260,16 +266,16 @@ def _command(item, corpus): return None, False, None if not argv: return None, True, None - tool = Path(argv[0]).name + tool = _program(argv[0]) if compound: - in_scope = any(Path(word).name in _TOOLS or knowledge_invocation(argv[index:]) + in_scope = any(_program(word) in _TOOLS or knowledge_invocation(argv[index:]) for index, word in enumerate(argv)) return None, not in_scope, None code, output = item.get("exit_code"), item.get("aggregated_output") if call := knowledge_invocation(argv): return decode_knowledge(call, code, output) if tool not in _TOOLS: - return None, not any(Path(word).name in _TOOLS for word in argv), None + return None, not any(_program(word) in _TOOLS for word in argv), None cwd = _path(item.get("cwd")) if cwd is None: return None, False, None diff --git a/tests/test_codex_search_shell_forms.py b/tests/test_codex_search_shell_forms.py index 620659885..efccf9eb2 100644 --- a/tests/test_codex_search_shell_forms.py +++ b/tests/test_codex_search_shell_forms.py @@ -1,3 +1,5 @@ +import shlex + import pytest from inferrsi.apps.views.codex_search import _command, _recorded_argv @@ -28,6 +30,12 @@ def test_wrapped_shell_forms_decode_like_the_plain_form(wrapped): ["C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command", "rg -n needle docs"], ["C:\\Tools\\env.exe", "C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command", "rg -n needle docs"], + # A shell inside the unwrapped script is as opaque as the same shell run directly. + ["bash", "-lc", "bash search.sh"], + ["bash", "-lc", "bash -- -c 'rg -n needle docs'"], + ["bash", "-lc", "pwsh -Command 'rg -n needle docs'"], + # A Windows-recorded tool outside the supported set is not proof of no retrieval. + ["C:/tools/rg.exe", "--json", "needle", "docs"], ]) def test_unreadable_shell_forms_stay_incomplete(tmp_path, command): # A search this reader cannot decode must not count as complete coverage. @@ -35,6 +43,34 @@ def test_unreadable_shell_forms_stay_incomplete(tmp_path, command): assert _command(item, tmp_path) == (None, False, None) +@pytest.mark.parametrize("direct", [ + ["bash", "search.sh"], + ["bash", "--", "-c", "rg -n needle docs"], + ["pwsh", "-Command", "rg -n needle docs"], +]) +def test_a_wrapped_shell_reads_like_the_same_shell_run_directly(tmp_path, direct): + wrapped = ["bash", "-lc", shlex.join(direct)] + for command in (direct, wrapped): + item = {"command": command, "exit_code": 0, "aggregated_output": ""} + assert _command(item, tmp_path) == (None, False, None), command + + +@pytest.mark.parametrize("tool", ["rg", "C:/tools/rg.exe", "C:\\tools\\rg.exe"]) +def test_a_windows_recorded_tool_is_read_as_that_tool(tmp_path, tool): + # rg exited 1 (no match) in scope: complete coverage with no material, on any reader OS. + corpus = tmp_path / "corpus" + corpus.mkdir() + item = {"command": [tool, "-n", "needle", "."], "cwd": corpus.as_uri(), + "exit_code": 1, "aggregated_output": ""} + event, complete, _ = _command(item, corpus) + assert event is not None and event["tool"] == "rg" and complete + + def test_dash_c_after_double_dash_names_a_script_file(): # bash -- -c runs a script file named -c, so no inline code is visible. assert _recorded_argv({"command": ["bash", "--", "-c", "rg -n needle docs"]}) == (None, False) + + +def test_a_shell_name_as_a_search_pattern_is_not_a_nested_shell(): + assert _recorded_argv({"command": ["bash", "-lc", "rg -n bash docs"]}) == ( + ["rg", "-n", "bash", "docs"], False) From 071cb6aefbf06f35550ae22c87b402adbcd437d3 Mon Sep 17 00:00:00 2001 From: GUOGUO Date: Tue, 24 Nov 2026 04:51:36 +0800 Subject: [PATCH 4/7] fix(apps): keep line boundaries when reading a multi-line shell script The shell script reader joined lines into one token stream and kept only a multiline flag, so only the first word and words after explicit operators were checked as command positions. A second line that started an opaque shell, such as "cd docs" followed by "bash search.sh", was counted as complete coverage. An unquoted newline between commands is now a ";" token, so the first word of every line is checked. A newline inside quotes, or at the start or end of the script, is not a boundary. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: GUOGUO --- src/inferrsi/apps/views/codex_search.py | 23 +++++++++++++++++++---- tests/test_codex_search_shell_forms.py | 25 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/src/inferrsi/apps/views/codex_search.py b/src/inferrsi/apps/views/codex_search.py index f782964a9..91612664b 100644 --- a/src/inferrsi/apps/views/codex_search.py +++ b/src/inferrsi/apps/views/codex_search.py @@ -33,9 +33,14 @@ _WINDOWS_RG_PATH = r"(?:[A-Za-z]:[/\\])?[^:]+" -def _shell_argv(source): - """Tokenize a shell command after removing comments and line continuations.""" +def _shell_argv(source, *, separate_lines=False): + """Tokenize a shell command after removing comments and line continuations. + + With ``separate_lines``, an unquoted newline between commands becomes a ``;`` + token, so the first word of every line stays a visible command position. + """ chars = [] + boundaries = [] quote = None escaped = comment = False word_start = True @@ -62,12 +67,22 @@ def _shell_argv(source): continue else: word_start = char in " \t\r\n;&|<>()" + if char == "\n" and not quote: + boundaries.append(len(chars)) chars.append(char) command = "".join(chars) + multiline = "\n" in command.strip() + if separate_lines: + first, end = len(command) - len(command.lstrip()), len(command.rstrip()) + for index in boundaries: + if first <= index < end: + # Spaces keep the token apart from a neighbouring operator such as &&. + chars[index] = " ; " + command = "".join(chars) lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|<>") lexer.whitespace_split = True lexer.commenters = "" - return list(lexer), "\n" in command.strip() + return list(lexer), multiline def _material(cwd: Path, name: str, corpus: Path) -> str | None: @@ -246,7 +261,7 @@ def _recorded_argv(item): # Code this reader cannot see may still have searched. return None, False try: - argv, multiline = _shell_argv(script) + argv, multiline = _shell_argv(script, separate_lines=True) except ValueError: return None, False # A shell or env in command position after one unwrap runs code this reader did diff --git a/tests/test_codex_search_shell_forms.py b/tests/test_codex_search_shell_forms.py index efccf9eb2..00c4008dd 100644 --- a/tests/test_codex_search_shell_forms.py +++ b/tests/test_codex_search_shell_forms.py @@ -14,6 +14,8 @@ # Recorded on Windows, read on any OS. ["C:\\Program Files\\Git\\bin\\bash.exe", "-lc", "rg -n needle docs"], ["C:\\Program Files\\Git\\usr\\bin\\env.exe", "bash", "-lc", "rg -n needle docs"], + # A trailing newline ends the only line; it is not a second command. + ["bash", "-lc", "rg -n needle docs\n"], ]) def test_wrapped_shell_forms_decode_like_the_plain_form(wrapped): assert _recorded_argv({"command": PLAIN}) == (["rg", "-n", "needle", "docs"], False) @@ -34,6 +36,10 @@ def test_wrapped_shell_forms_decode_like_the_plain_form(wrapped): ["bash", "-lc", "bash search.sh"], ["bash", "-lc", "bash -- -c 'rg -n needle docs'"], ["bash", "-lc", "pwsh -Command 'rg -n needle docs'"], + # A later line of a multi-line script is a command position too. + ["bash", "-lc", "cd docs\nbash search.sh"], + ["bash", "-lc", "cd docs\n\n pwsh -Command 'rg -n needle .'"], + ["bash", "-lc", "cd docs &&\nbash search.sh"], # A Windows-recorded tool outside the supported set is not proof of no retrieval. ["C:/tools/rg.exe", "--json", "needle", "docs"], ]) @@ -66,6 +72,25 @@ def test_a_windows_recorded_tool_is_read_as_that_tool(tmp_path, tool): assert event is not None and event["tool"] == "rg" and complete +def test_a_multi_line_script_keeps_its_line_boundaries(): + assert _recorded_argv({"command": ["bash", "-lc", "cd docs\nrg -n needle ."]}) == ( + ["cd", "docs", ";", "rg", "-n", "needle", "."], True) + + +def test_a_quoted_newline_is_not_a_line_boundary(): + assert _recorded_argv({"command": ["bash", "-lc", "rg -n 'a\nbash' docs"]}) == ( + ["rg", "-n", "a\nbash", "docs"], True) + + +def test_a_windows_recorded_shell_wrapper_decodes_end_to_end(tmp_path): + corpus = tmp_path / "corpus" + corpus.mkdir() + item = {"command": ["C:\\Program Files\\Git\\bin\\bash.exe", "-lc", "rg -n needle ."], + "cwd": corpus.as_uri(), "exit_code": 1, "aggregated_output": ""} + event, complete, _ = _command(item, corpus) + assert event is not None and event["tool"] == "rg" and complete + + def test_dash_c_after_double_dash_names_a_script_file(): # bash -- -c runs a script file named -c, so no inline code is visible. assert _recorded_argv({"command": ["bash", "--", "-c", "rg -n needle docs"]}) == (None, False) From 08cecd8909c4709b8178472ce118bd2bd06de20b Mon Sep 17 00:00:00 2001 From: GUOGUO Date: Tue, 24 Nov 2026 14:57:00 +0800 Subject: [PATCH 5/7] fix(apps): find a shell behind reserved words, wrappers and substitutions The command-position check looked only at the first word and the word after an explicit operator. A shell behind a reserved word, a NAME=value prefix, a wrapper such as nohup or command, a code builtin such as source, eval or ".", or a background "&" was not seen, so the command counted as complete coverage although it ran a script the import cannot read. A command substitution or a subshell had the same gap. Each simple command's program is now found after reserved words and assignments. A shell, env or code builtin there is incomplete, and so is a program outside the supported tools that is handed a shell. A command substitution or subshell in the script is incomplete. A compound command with neither a shell nor a supported tool still counts as no retrieval. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: GUOGUO --- src/inferrsi/apps/views/codex_search.py | 55 +++++++++++++++++++------ tests/test_codex_search_shell_forms.py | 27 ++++++++++++ 2 files changed, 70 insertions(+), 12 deletions(-) diff --git a/src/inferrsi/apps/views/codex_search.py b/src/inferrsi/apps/views/codex_search.py index 91612664b..8b1785009 100644 --- a/src/inferrsi/apps/views/codex_search.py +++ b/src/inferrsi/apps/views/codex_search.py @@ -26,6 +26,13 @@ _OPAQUE_SHELLS = ("pwsh", "powershell", "cmd", "fish") _TOOLS = ("rg", "cat", "sed", "nl") _SHELL_OPERATORS = {"|", "||", "&&", ";", ">", ">>", "<"} +# Words that start a simple command without being its program. +_SHELL_KEYWORDS = frozenset(("!", "{", "}", "[[", "if", "then", "elif", "else", "fi", "do", + "done", "while", "until", "for", "case", "esac", "select", + "function", "time", "coproc")) +_ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=") +# Builtins that run code or another command this reader does not decode. +_CODE_BUILTINS = ("eval", "source", ".", "exec", "command", "builtin") _MAX_PASSAGES = 12 _MAX_PASSAGE_CHARS = 400 _MAX_VISIBLE_REFS = 64 @@ -33,11 +40,13 @@ _WINDOWS_RG_PATH = r"(?:[A-Za-z]:[/\\])?[^:]+" -def _shell_argv(source, *, separate_lines=False): +def _shell_argv(source, *, for_commands=False): """Tokenize a shell command after removing comments and line continuations. - With ``separate_lines``, an unquoted newline between commands becomes a ``;`` - token, so the first word of every line stays a visible command position. + With ``for_commands``, the script is read for its command positions: an unquoted + newline between commands becomes a ``;`` token, and a command substitution or + subshell, whose commands have no position this reader can check, raises + ``ValueError``. """ chars = [] boundaries = [] @@ -57,6 +66,10 @@ def _shell_argv(source, *, separate_lines=False): word_start = False elif char == "\\" and quote != "'": escaped = True + elif for_commands and quote != "'" and ( + char == "`" or (char == "(" and (quote is None or chars[-1:] == ["$"])) + or (char == ")" and quote is None)): + raise ValueError("command substitution or subshell") elif quote: if char == quote: quote = None @@ -72,7 +85,7 @@ def _shell_argv(source, *, separate_lines=False): chars.append(char) command = "".join(chars) multiline = "\n" in command.strip() - if separate_lines: + if for_commands: first, end = len(command) - len(command.lstrip()), len(command.rstrip()) for index in boundaries: if first <= index < end: @@ -243,6 +256,20 @@ def _shell_script(options): return None +def _runs_unread_code(words): + """True when one simple command runs code this reader did not decode. + + A shell, `env` or code-running builtin as the program does. So does a program + outside the supported tools that is handed a shell, as in `nohup bash search.sh`. + """ + program = _program(words[0]) + if program in (*_SHELLS, *_OPAQUE_SHELLS, "env", *_CODE_BUILTINS): + return True + return program not in _TOOLS and any( + _program(word) in (*_SHELLS, *_OPAQUE_SHELLS, "env", "eval", "source") + for word in words[1:]) + + def _recorded_argv(item): original_argv = item.get("command") if (not isinstance(original_argv, list) or not original_argv @@ -261,16 +288,20 @@ def _recorded_argv(item): # Code this reader cannot see may still have searched. return None, False try: - argv, multiline = _shell_argv(script, separate_lines=True) + argv, multiline = _shell_argv(script, for_commands=True) except ValueError: return None, False - # A shell or env in command position after one unwrap runs code this reader did - # not decode, exactly as the same shell run directly would. - starts = [0, *(index + 1 for index, word in enumerate(argv) if word in _SHELL_OPERATORS)] - if any(index < len(argv) and _program(argv[index]) in (*_SHELLS, *_OPAQUE_SHELLS, "env") - for index in starts): - return None, False - compound = multiline or any(word in _SHELL_OPERATORS for word in argv) + # After one unwrap, each simple command is checked as the same command run + # directly would be. Its program follows any reserved words and NAME=value words. + command = [] + for word in [*argv, ";"]: + if word in _SHELL_OPERATORS or word == "&": + if command and _runs_unread_code(command): + return None, False + command = [] + elif command or not (word in _SHELL_KEYWORDS or _ASSIGNMENT.match(word)): + command.append(word) + compound = multiline or any(word in _SHELL_OPERATORS or word == "&" for word in argv) return argv, compound diff --git a/tests/test_codex_search_shell_forms.py b/tests/test_codex_search_shell_forms.py index 00c4008dd..a01f819c5 100644 --- a/tests/test_codex_search_shell_forms.py +++ b/tests/test_codex_search_shell_forms.py @@ -40,6 +40,20 @@ def test_wrapped_shell_forms_decode_like_the_plain_form(wrapped): ["bash", "-lc", "cd docs\nbash search.sh"], ["bash", "-lc", "cd docs\n\n pwsh -Command 'rg -n needle .'"], ["bash", "-lc", "cd docs &&\nbash search.sh"], + # Reserved words, NAME=value prefixes, wrappers, code builtins and `&` hide a shell too. + ["bash", "-lc", "if true; then bash search.sh; fi"], + ["bash", "-lc", "cd docs\ncommand bash search.sh"], + ["bash", "-lc", "X=1 bash search.sh"], + ["bash", "-lc", "nohup bash search.sh"], + ["bash", "-lc", "cd docs && . ./search.sh"], + ["bash", "-lc", "source search.sh"], + ["bash", "-lc", "eval \"$SEARCH\""], + ["bash", "-lc", "cd docs & bash search.sh"], + ["command", "bash", "search.sh"], + # Commands in a substitution or subshell have no command position this reader sees. + ["bash", "-lc", "echo $(bash search.sh)"], + ["bash", "-lc", "echo \"`bash search.sh`\""], + ["bash", "-lc", "(bash search.sh)"], # A Windows-recorded tool outside the supported set is not proof of no retrieval. ["C:/tools/rg.exe", "--json", "needle", "docs"], ]) @@ -96,6 +110,19 @@ def test_dash_c_after_double_dash_names_a_script_file(): assert _recorded_argv({"command": ["bash", "--", "-c", "rg -n needle docs"]}) == (None, False) +@pytest.mark.parametrize("script, argv", [ + ("rg -n if docs", ["rg", "-n", "if", "docs"]), + ("rg -n '$(bash x)' docs", ["rg", "-n", "$(bash x)", "docs"]), +]) +def test_shell_syntax_inside_a_quoted_or_tool_argument_still_decodes(script, argv): + assert _recorded_argv({"command": ["bash", "-lc", script]}) == (argv, False) + + +def test_a_compound_command_without_a_shell_or_tool_is_still_no_retrieval(tmp_path): + item = {"command": ["bash", "-lc", "cd docs && ls"], "exit_code": 0, "aggregated_output": ""} + assert _command(item, tmp_path) == (None, True, None) + + def test_a_shell_name_as_a_search_pattern_is_not_a_nested_shell(): assert _recorded_argv({"command": ["bash", "-lc", "rg -n bash docs"]}) == ( ["rg", "-n", "bash", "docs"], False) From 3876021c5881a667847434962ecbac967f39178e Mon Sep 17 00:00:00 2001 From: GUOGUO Date: Tue, 24 Nov 2026 23:46:51 +0800 Subject: [PATCH 6/7] fix(apps): keep a literal ampersand an argument when reading shell commands A lone "&" word was treated as a background operator after tokenization, which had already dropped the quoting. A search for a literal "&", in a direct argv or as '&' in a script, was marked compound and lost its decodable retrieval event. The script reader now turns only an unquoted, unescaped "&" that is not part of "&&", "&>", ">&", "<&" or "|&" into a command separator before tokenizing, as it already does for newlines. A direct argv is not read as shell source, so a literal "&" there stays an argument. A background command between two commands is still a command boundary. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: GUOGUO --- src/inferrsi/apps/views/codex_search.py | 18 ++++++++++----- tests/test_codex_search_shell_forms.py | 29 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/src/inferrsi/apps/views/codex_search.py b/src/inferrsi/apps/views/codex_search.py index 8b1785009..eb25d50fb 100644 --- a/src/inferrsi/apps/views/codex_search.py +++ b/src/inferrsi/apps/views/codex_search.py @@ -44,12 +44,13 @@ def _shell_argv(source, *, for_commands=False): """Tokenize a shell command after removing comments and line continuations. With ``for_commands``, the script is read for its command positions: an unquoted - newline between commands becomes a ``;`` token, and a command substitution or - subshell, whose commands have no position this reader can check, raises - ``ValueError``. + newline or background ``&`` between commands becomes a ``;`` token, and a command + substitution or subshell, whose commands have no position this reader can check, + raises ``ValueError``. A quoted or escaped ``&`` stays an argument. """ chars = [] boundaries = [] + operators = {} quote = None escaped = comment = False word_start = True @@ -80,6 +81,8 @@ def _shell_argv(source, *, for_commands=False): continue else: word_start = char in " \t\r\n;&|<>()" + if char in "&|<>": + operators[len(chars)] = char if char == "\n" and not quote: boundaries.append(len(chars)) chars.append(char) @@ -91,6 +94,11 @@ def _shell_argv(source, *, for_commands=False): if first <= index < end: # Spaces keep the token apart from a neighbouring operator such as &&. chars[index] = " ; " + for index, char in operators.items(): + # A lone & starts a background command. &&, &>, >&, <& and |& are other operators. + if (char == "&" and operators.get(index - 1) not in ("&", ">", "<", "|") + and operators.get(index + 1) not in ("&", ">")): + chars[index] = " ; " command = "".join(chars) lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|<>") lexer.whitespace_split = True @@ -295,13 +303,13 @@ def _recorded_argv(item): # directly would be. Its program follows any reserved words and NAME=value words. command = [] for word in [*argv, ";"]: - if word in _SHELL_OPERATORS or word == "&": + if word in _SHELL_OPERATORS: if command and _runs_unread_code(command): return None, False command = [] elif command or not (word in _SHELL_KEYWORDS or _ASSIGNMENT.match(word)): command.append(word) - compound = multiline or any(word in _SHELL_OPERATORS or word == "&" for word in argv) + compound = multiline or any(word in _SHELL_OPERATORS for word in argv) return argv, compound diff --git a/tests/test_codex_search_shell_forms.py b/tests/test_codex_search_shell_forms.py index a01f819c5..cb6984af5 100644 --- a/tests/test_codex_search_shell_forms.py +++ b/tests/test_codex_search_shell_forms.py @@ -123,6 +123,35 @@ def test_a_compound_command_without_a_shell_or_tool_is_still_no_retrieval(tmp_pa assert _command(item, tmp_path) == (None, True, None) +@pytest.mark.parametrize("command", [ + ["rg", "-n", "&", "."], + ["bash", "-lc", "rg -n '&' ."], + ["bash", "-lc", "rg -n \\& ."], + ["bash", "-lc", "rg -n \"a & b\" ."], +]) +def test_a_literal_ampersand_is_an_argument_not_a_background_operator(tmp_path, command): + corpus = tmp_path / "corpus" + corpus.mkdir() + item = {"command": command, "cwd": corpus.as_uri(), "exit_code": 1, "aggregated_output": ""} + event, complete, _ = _command(item, corpus) + assert event is not None and event["tool"] == "rg" and complete + + +@pytest.mark.parametrize("script", [ + "rg -n needle docs 2>&1", + "rg -n needle docs &> out.txt", + "rg -n needle docs |& cat", +]) +def test_ampersand_inside_a_redirection_is_not_a_background_operator(script): + argv, compound = _recorded_argv({"command": ["bash", "-lc", script]}) + assert ";" not in argv and argv[0] == "rg" + + +def test_a_background_ampersand_between_commands_is_a_command_boundary(): + assert _recorded_argv({"command": ["bash", "-lc", "rg -n needle docs & cd ."]}) == ( + ["rg", "-n", "needle", "docs", ";", "cd", "."], True) + + def test_a_shell_name_as_a_search_pattern_is_not_a_nested_shell(): assert _recorded_argv({"command": ["bash", "-lc", "rg -n bash docs"]}) == ( ["rg", "-n", "bash", "docs"], False) From 8ffb1536de588ade8b1bf39c6a7bfabee5510fa6 Mon Sep 17 00:00:00 2001 From: GUOGUO Date: Wed, 25 Nov 2026 03:05:31 +0800 Subject: [PATCH 7/7] fix(apps): normalize an unquoted redirection before tokenizing a shell script An unquoted redirection or pipe operator such as "2>&1", "&>" or "|&" was left as one token that the operator set does not list. The command was then read as a plain search whose scope included the redirection target or file descriptor, and it counted as complete coverage. The script reader now handles these operators while quoting is still known. A run of adjacent operator characters that is not already a supported operator becomes one plain operator: a run with "|" becomes "|", one with ">" becomes ">", one with "<" becomes "<". The command is then compound and its target is not read as a search scope. A quoted or escaped "&>", "2>&1" or "|&" stays an argument, and a lone "&" is still a command boundary. Agent-assisted-by: Claude Code / claude-opus-5-5 [effort=xhigh] (author) Signed-off-by: GUOGUO --- src/inferrsi/apps/views/codex_search.py | 44 ++++++++++++++++++---- tests/test_codex_search_shell_forms.py | 49 ++++++++++++++++++++++--- 2 files changed, 79 insertions(+), 14 deletions(-) diff --git a/src/inferrsi/apps/views/codex_search.py b/src/inferrsi/apps/views/codex_search.py index eb25d50fb..a57a52797 100644 --- a/src/inferrsi/apps/views/codex_search.py +++ b/src/inferrsi/apps/views/codex_search.py @@ -40,13 +40,26 @@ _WINDOWS_RG_PATH = r"(?:[A-Za-z]:[/\\])?[^:]+" +def _operator_runs(operators): + """Group the positions of adjacent unquoted operator characters.""" + runs = [] + for index in operators: + if runs and runs[-1][-1] == index - 1: + runs[-1].append(index) + else: + runs.append([index]) + return runs + + def _shell_argv(source, *, for_commands=False): """Tokenize a shell command after removing comments and line continuations. With ``for_commands``, the script is read for its command positions: an unquoted - newline or background ``&`` between commands becomes a ``;`` token, and a command - substitution or subshell, whose commands have no position this reader can check, - raises ``ValueError``. A quoted or escaped ``&`` stays an argument. + newline or background ``&`` between commands becomes a ``;`` token, an unquoted + redirection or pipe operator such as ``&>`` or ``|&`` becomes one plain operator, + and a command substitution or subshell, whose commands have no position this + reader can check, raises ``ValueError``. A quoted or escaped ``&`` or ``&>`` stays + an argument. """ chars = [] boundaries = [] @@ -94,11 +107,26 @@ def _shell_argv(source, *, for_commands=False): if first <= index < end: # Spaces keep the token apart from a neighbouring operator such as &&. chars[index] = " ; " - for index, char in operators.items(): - # A lone & starts a background command. &&, &>, >&, <& and |& are other operators. - if (char == "&" and operators.get(index - 1) not in ("&", ">", "<", "|") - and operators.get(index + 1) not in ("&", ">")): - chars[index] = " ; " + for positions in _operator_runs(operators): + run = "".join(operators[index] for index in positions) + if run in _SHELL_OPERATORS: + continue + # A lone & starts a background command. Any other run, such as &>, >&, <&, + # |& or <<, is a redirection or pipe; it becomes one plain operator so the + # command is compound and its target is never read as a search scope. + if run == "&": + separator = " ; " + elif run.startswith("|"): + separator = " | " + elif ">" in run: + separator = " > " + elif "<" in run: + separator = " < " + else: + continue + chars[positions[0]] = separator + for index in positions[1:]: + chars[index] = "" command = "".join(chars) lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|<>") lexer.whitespace_split = True diff --git a/tests/test_codex_search_shell_forms.py b/tests/test_codex_search_shell_forms.py index cb6984af5..35f3efa05 100644 --- a/tests/test_codex_search_shell_forms.py +++ b/tests/test_codex_search_shell_forms.py @@ -1,4 +1,5 @@ import shlex +from pathlib import Path import pytest @@ -137,19 +138,55 @@ def test_a_literal_ampersand_is_an_argument_not_a_background_operator(tmp_path, assert event is not None and event["tool"] == "rg" and complete +@pytest.mark.parametrize("script, argv", [ + ("rg -n needle docs 2>&1", ["rg", "-n", "needle", "docs", "2", ">", "1"]), + ("rg -n needle docs &> out.txt", ["rg", "-n", "needle", "docs", ">", "out.txt"]), + ("rg -n needle docs |& cat", ["rg", "-n", "needle", "docs", "|", "cat"]), + ("rg -n needle docs <&0", ["rg", "-n", "needle", "docs", "<", "0"]), +]) +def test_an_unquoted_redirection_becomes_one_plain_operator(script, argv): + assert _recorded_argv({"command": ["bash", "-lc", script]}) == (argv, True) + + +@pytest.mark.parametrize("script, argv", [ + ("rg -n '&>' docs", ["rg", "-n", "&>", "docs"]), + ("rg -n '2>&1' docs", ["rg", "-n", "2>&1", "docs"]), + ("rg -n '|&' docs", ["rg", "-n", "|&", "docs"]), +]) +def test_a_quoted_redirection_is_an_argument(script, argv): + assert _recorded_argv({"command": ["bash", "-lc", script]}) == (argv, False) + + +def test_a_background_ampersand_between_commands_is_a_command_boundary(): + assert _recorded_argv({"command": ["bash", "-lc", "rg -n needle docs & cd ."]}) == ( + ["rg", "-n", "needle", "docs", ";", "cd", "."], True) + + @pytest.mark.parametrize("script", [ "rg -n needle docs 2>&1", "rg -n needle docs &> out.txt", + "rg -n needle docs &>> out.txt", "rg -n needle docs |& cat", + "rg -n needle docs >&2", + "rg -n needle docs <&0", + "rg -n needle docs >| out.txt", + "rg -n needle docs <> out.txt", + "rg -n needle docs <<< input", ]) -def test_ampersand_inside_a_redirection_is_not_a_background_operator(script): - argv, compound = _recorded_argv({"command": ["bash", "-lc", script]}) - assert ";" not in argv and argv[0] == "rg" +def test_a_redirection_is_not_decoded_as_search_scope(tmp_path, script): + # The redirection target or file descriptor is not a path the search covered, so the + # command yields no event and no complete coverage, even though docs/a.md matched. + corpus = tmp_path / "corpus" + (corpus / "docs").mkdir(parents=True) + (corpus / "docs" / "a.md").write_text("needle\n", encoding="utf-8") + item = {"command": ["bash", "-lc", script], "cwd": corpus.as_uri(), + "exit_code": 0, "aggregated_output": "docs/a.md:1:needle\n"} + assert _command(item, corpus) == (None, False, None) -def test_a_background_ampersand_between_commands_is_a_command_boundary(): - assert _recorded_argv({"command": ["bash", "-lc", "rg -n needle docs & cd ."]}) == ( - ["rg", "-n", "needle", "docs", ";", "cd", "."], True) +def test_a_redirection_does_not_hide_the_next_command_position(): + assert _command({"command": ["bash", "-lc", "rg -n needle . |& bash search.sh"], + "exit_code": 0, "aggregated_output": ""}, Path("/")) == (None, False, None) def test_a_shell_name_as_a_search_pattern_is_not_a_nested_shell():