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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 36 additions & 4 deletions src/foundation/services/file_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,38 @@ def _raise(
)


def _sibling_hint(resolved: Path) -> str:
"""List the entries in a missing file's parent dir, as a 'did you mean' hint."""
parent = resolved.parent
try:
if not parent.is_dir():
return ""
names = sorted(p.name + ("/" if p.is_dir() else "") for p in parent.iterdir())
except OSError:
return ""
if not names:
return ""
shown = names[:12]
more = f" (+{len(names) - 12} more)" if len(names) > 12 else ""
return f" Directory '{parent.name}/' contains: {', '.join(shown)}{more}."


def _raise_not_found(raw_path: str, resolved: Path) -> None:
"""Raise FILE_NOT_FOUND with a sibling listing so the model can self-correct."""
hint = _sibling_hint(resolved)
_raise(
FileErrorCode.FILE_NOT_FOUND,
f"File does not exist: {raw_path}.{hint}",
path=raw_path,
suggestion=(
"Discover the correct path with foundation.files, or read one of the "
"files listed in the message."
if hint
else None
),
)


def _sha256(content: str) -> str:
return hashlib.sha256(content.encode("utf-8")).hexdigest()

Expand Down Expand Up @@ -344,7 +376,7 @@ def read(self, request: FileReadRequest) -> FileReadResult:
"""Read one workspace text file up to 256 KB."""
resolved = self._resolve_read_path(request.path)
if not resolved.exists():
_raise(FileErrorCode.FILE_NOT_FOUND, "File does not exist.", path=request.path)
_raise_not_found(request.path, resolved)
file_size = resolved.stat().st_size
if file_size > _MAX_READ_BYTES:
_raise(
Expand All @@ -367,7 +399,7 @@ def read_chunk(self, request: FileReadChunkRequest) -> FileReadChunkResult:
"""Read a line-based chunk from a workspace text file."""
resolved = self._resolve_read_path(request.path)
if not resolved.exists():
_raise(FileErrorCode.FILE_NOT_FOUND, "File does not exist.", path=request.path)
_raise_not_found(request.path, resolved)

# Peek at the first 8 KB for binary detection
raw_head = resolved.read_bytes()[:8192]
Expand Down Expand Up @@ -452,7 +484,7 @@ def edit(self, request: FileEditRequest) -> FileMutationResult:
"""Rewrite an existing file with conflict detection."""
resolved = self._resolve_path(request.path)
if not resolved.exists():
_raise(FileErrorCode.FILE_NOT_FOUND, "File does not exist.", path=request.path)
_raise_not_found(request.path, resolved)
old_content, _ = self._read_raw(resolved)
actual_sha256 = _sha256(old_content)
if actual_sha256 != request.expected_sha256:
Expand All @@ -475,7 +507,7 @@ def apply_diff(self, request: FileApplyDiffRequest) -> FileMutationResult:
"""Apply a unified diff atomically to a workspace text file."""
resolved = self._resolve_path(request.path)
if not resolved.exists():
_raise(FileErrorCode.FILE_NOT_FOUND, "File does not exist.", path=request.path)
_raise_not_found(request.path, resolved)
old_content, _ = self._read_raw(resolved)
new_content = _parse_and_apply_diff(
old_content,
Expand Down
14 changes: 14 additions & 0 deletions tests/test_file_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -731,3 +731,17 @@ def test_read_grant_allows_out_of_scope_read_only(tmp_path: Path) -> None:
with pytest.raises(FileServiceError) as exc_write:
service.write(FileWriteRequest(path=str(outside / "new.md"), content="x"))
assert exc_write.value.error.code == FileErrorCode.PATH_OUTSIDE_WORKSPACE


def test_read_not_found_lists_sibling_files(tmp_path: Path) -> None:
service, workspace = _make_service(tmp_path)
(workspace / "res").mkdir()
(workspace / "res" / "anmolnoor-github-report.md").write_text("# Report\n", encoding="utf-8")

with pytest.raises(FileServiceError) as exc:
service.read(FileReadRequest(path="res/anmolnoor-report.md"))

assert exc.value.error.code == FileErrorCode.FILE_NOT_FOUND
# The error names the real sibling so the model can self-correct.
assert "anmolnoor-github-report.md" in exc.value.error.message
assert exc.value.error.suggestion is not None
38 changes: 38 additions & 0 deletions tests/test_orchestrator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2969,3 +2969,41 @@ def test_orchestrator_unwraps_plan_wrapped_generated_body(

# The plan-wrapped generation is unwrapped to the clean file body.
assert (workspace_root / "report.md").read_text(encoding="utf-8") == clean


def test_orchestrator_not_found_surfaces_siblings_for_self_correction(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
provider = StubProvider(
[
_provider_response(
{
"assistant_message": "Reading the report.",
"actions": [_read_action("read_wrong", "res/wrong-name.md")],
}
),
_provider_response(
{
"assistant_message": "Retrying with the real filename.",
"actions": [_read_action("read_right", "res/right-name.md")],
}
),
]
)
orchestrator, _, workspace_root = _orchestrator(tmp_path, monkeypatch, provider)
(workspace_root / "res").mkdir()
(workspace_root / "res" / "right-name.md").write_text("# Found me\n", encoding="utf-8")

result = orchestrator.orchestrate(UserRequest(message="read the report in res"))

# The not-found error from iteration 1 carried the real filename into
# iteration 2's planning context, enabling self-correction.
second_plan_text = "\n".join(m.content for m in provider.calls[1].messages)
assert "right-name.md" in second_plan_text
# The corrected read then succeeded.
assert any(
r.status is ExecutionStatus.EXECUTED
and r.artifact_type is ExecutionArtifactType.FILE_READ
for r in result.execution_results
)
Loading