Repository navigation
fix(agent): normalize the workspace pin key to the resolved path #124787
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 10 commits
1088868
e1b2ed3
9fef6b1
f6871b3
6eb71ac
a52ee4c
4a90a34
dad6ca1
80deae4
35ab806
6e7f78d
bfe1be4
12cf1be
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -593,31 +593,219 @@ def _alibaba_identity_part(agent: Any) -> List[str]: | |
|
|
||
|
|
||
| def _workspace_pin_key() -> str: | ||
| """The directory the workspace probe inspects, which is also the prompt's ``Current working | ||
| directory``: a build with no cwd bound (launch dir) and a later one binding that same dir | ||
| (TUI ``/compress``) are one workspace, not two.""" | ||
| """The directory the workspace probe inspects, in resolved form — the prompt's | ||
| ``Current working directory`` line carries the session's own spelling of it. Under that | ||
| normalization a build with no cwd bound (launch dir) and a later one binding that same | ||
| dir (TUI ``/compress``) are one workspace, not two. | ||
|
|
||
| Normalized to the resolved real path: a launch-dir key comes from ``os.getcwd()`` (which | ||
| reports the physical path — ``/private/var/...`` on macOS) while a bound cwd arrives as the | ||
| session spelled it (``/var/...`` through the symlink). Comparing those spellings misses the | ||
| pin, the rebuild re-probes git live, and the session-start snapshot is rewritten mid-session | ||
| — invalidating the cached prompt prefix for a workspace that never changed.""" | ||
| try: | ||
| return str(resolve_context_cwd() or resolve_agent_cwd()) | ||
| except OSError: # deleted cwd | ||
| raw = str(resolve_context_cwd() or resolve_agent_cwd()) | ||
| return str(Path(raw).resolve()) if raw else "" | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Compare existing directories by filesystem identity. I reproduced this on the exact head through the real Please compare live paths with |
||
| except (OSError, RuntimeError): # deleted cwd, or a symlink loop in a bound spelling | ||
| return "" | ||
|
|
||
|
|
||
| def _same_live_dir(a: str, b: str) -> bool: | ||
| """Directory identity that survives spelling aliases a plain string comparison misses. | ||
|
|
||
| *Symlink* spellings: a launch-dir key comes from ``os.getcwd()`` (the physical path — | ||
| ``/private/var/...`` on macOS) while a bound cwd or a persisted ``- Root:`` line carries | ||
| the session's own spelling (``/var/...`` through the symlink); comparing those raw | ||
| misses the pin, the rebuild re-probes git live, and the session-start snapshot is | ||
| rewritten mid-session — invalidating the cached prompt prefix for a workspace that | ||
| never changed. | ||
| *Case* spellings: resolve() follows symlinks but keeps the caller's casing, so on a | ||
| case-insensitive filesystem (default macOS APFS) one directory spelled ``MixedCase`` | ||
| and ``mixedcase`` still yields two strings. | ||
|
|
||
| When both paths exist the filesystem itself (``samefile``) is the authority; a missing | ||
| path (deleted cwd, vanished root) falls back to the string comparison. Both inputs may | ||
| be persisted session bytes, so resolve() runs here under (OSError, RuntimeError): a | ||
| symlink loop raises the latter on Python <= 3.12, and letting it escape the pin seams | ||
| would drop the whole coding block to the blanket handler.""" | ||
| try: | ||
| pa, pb = Path(a).resolve(), Path(b).resolve() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Do not use a later filesystem mapping as proof of the captured workspace's identity. This helper correctly compares two current path spellings, but its callers also pass a historical path stored with a snapshot. The tuple retains the resolved pathname, not the directory identity at capture time. If physical directory The consequence follows through the changed caller: The persisted sibling has the same cause. Minimal failing identity assertion, runnable from an installed checkout on a POSIX host: from pathlib import Path
from tempfile import TemporaryDirectory
from agent.system_prompt import _same_pin_key
with TemporaryDirectory() as directory:
root = Path(directory).resolve()
old, new = root / "old", root / "new"
old.mkdir()
new.mkdir()
captured_key = str(old.resolve())
original_id = (old.stat().st_dev, old.stat().st_ino)
old.rename(root / "old-saved")
old.symlink_to(new, target_is_directory=True)
current_key = str(new.resolve())
assert original_id != (new.stat().st_dev, new.stat().st_ino)
assert captured_key != current_key
assert not _same_pin_key(captured_key, current_key) # fails: TrueObserved scope: executing the inspected head's exact comparison body on real Linux directories/Python 3.13.5 fails that final assertion. A separate paired base/head owner-boundary probe used the inspected cwd resolver, real Git repositories, and a controlled downstream renderer: base requested B's new snapshot; head forwarded A's old bytes, for both live replay and persisted adoption. No full-package or native macOS/Windows run is claimed. Stable symlink aliases of the unchanged directory still replay correctly at head, and an ordinary untouched A-to-B switch re-probes on both revisions. Repair: preserve capture-time directory identity for live pins rather than re-resolving a historical pathname as though it were immutable. For persisted snapshots, require evidence that the recorded workspace still denotes the captured directory; when that cannot be established after a historical physical root is rebound, take a fresh snapshot rather than treating today's Regression contract: capture through the actual session-cwd path; relocate the original directory and reuse its pathname as an alias to B; bind B and rebuild. Assert B's root/commit is emitted and A's bytes are not replayed. Repeat with a fresh agent reading persisted A bytes and with an initially empty live pin. Retain stable-alias replay, ordinary distinct-directory, empty-key, and loop-containment controls. |
||
| except (OSError, RuntimeError): | ||
| return False | ||
| if pa == pb: | ||
| return True | ||
| try: | ||
| return pa.samefile(pb) | ||
| except OSError: | ||
| return False | ||
|
|
||
|
|
||
| def _same_pin_key(a: str, b: str) -> bool: | ||
| """Pin-key equality; "" is a real pinned value (no workspace) and only equals itself.""" | ||
| return a == b or (bool(a) and bool(b) and _same_live_dir(a, b)) | ||
|
|
||
|
|
||
| def _dir_identity(path: str) -> Optional[Tuple[int, int]]: | ||
| """``(st_dev, st_ino)`` of a directory, recorded when a snapshot is pinned to it. | ||
|
|
||
| A pathname only proves which directory a snapshot was taken in until the path | ||
| is rebound: renaming the directory and reusing its old name for a symlink to | ||
| somewhere else makes today's resolution of the stored spelling land on the | ||
| new directory, and a current-filesystem comparison then replays the snapshot | ||
| there. Recording the identity at capture time lets the replay gate tell a | ||
| stable alias (same directory behind the spelling) from a rebound one. None | ||
| when the directory cannot be stat'd.""" | ||
| try: | ||
| st = Path(path).stat() | ||
| return (st.st_dev, st.st_ino) | ||
| except OSError: | ||
| return None | ||
|
|
||
|
|
||
| def _nearest_git_marker(path: str) -> Optional[Path]: | ||
| """The nearest ``.git`` (directory or linked-worktree pointer file) at or above | ||
| *path* — git's own discovery rule, derived by stat alone so the replay gate can | ||
| consult it on every rebuild without shelling out.""" | ||
| try: | ||
| start = Path(path).resolve() | ||
| except (OSError, RuntimeError): | ||
| return None | ||
| for candidate in (start, *start.parents): | ||
| marker = candidate / ".git" | ||
| try: | ||
| if marker.exists(): | ||
| return marker | ||
| except OSError: | ||
| continue | ||
| return None | ||
|
|
||
|
|
||
| def _workspace_generation(path: str) -> Optional[Tuple[int, int, Optional[Tuple[int, int]]]]: | ||
| """Directory identity bound to the workspace lifetime that owned it at capture: | ||
| ``(st_dev, st_ino)`` of *path* plus the identity of the ``.git`` marker that owns it | ||
| (None when no workspace marker sits above the path). | ||
|
|
||
| The bare directory pair alone cannot tell a directory lifetime from its successor: | ||
| a removed-and-recreated pathname can reuse the pair (observed on overlayfs), and a | ||
| pin recorded before the replacement then replays old bytes — or an old emptiness — | ||
| onto the new occupant. Ordinary git work never deletes ``.git``, so the marker's | ||
| identity is stable across a workspace's life and changes whenever a different | ||
| generation takes over the pathname (a fresh ``git init`` or clone among them); the | ||
| replay gate re-probes on any doubt. None when the path cannot be stat'd.""" | ||
| base = _dir_identity(path) | ||
| if base is None: | ||
| return None | ||
| marker = _nearest_git_marker(path) | ||
| marker_identity = _dir_identity(str(marker)) if marker is not None else None | ||
| return (base[0], base[1], marker_identity) | ||
|
|
||
|
|
||
| def _persisted_root_still_physical(root_line: str) -> bool: | ||
| """Provenance evidence carried by a persisted ``- Root:`` line. | ||
|
|
||
| The line is ``git rev-parse --show-toplevel`` output — the physical, fully | ||
| resolved spelling of the repo root on the day the snapshot was taken, so it | ||
| is a fixpoint of ``resolve()`` at capture. If resolving it today traverses a | ||
| symlink, the physical directory it named has been renamed or its pathname | ||
| rebound, and today's ``samefile`` agreement proves nothing about the | ||
| snapshot's origin; the gate must take a fresh snapshot instead of adopting | ||
| the bytes.""" | ||
| try: | ||
| return Path(root_line).resolve() == Path(root_line) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] The new provenance checks still do not bind the snapshot to a directory generation/lifetime. The deterministic persisted case needs no symlink. With two real temporary Git repos on this head's helper semantics:
Because the string is unchanged, this line still returns true: Observed: A/B root strings equal; A/B HEADs different; this fixpoint check The live sibling shows why These same-path shapes pre-exist this PR, but they show the prior provenance repair requirement is still open. Repair: persisted adoption needs capture-time workspace-generation evidence; do not manufacture provenance at resume by pairing historical bytes with today's occupant of the path. The live pin likewise needs a lifetime-stable reference/generation, or it must conservatively re-probe when the original lifetime cannot be proven. Regression: cover A-at-P → lifetime ends → independent B-at-P for both persisted reconstruction and a live empty/non-empty pin, and assert B is freshly probed while stable symlink/case aliases of an unchanged directory still replay. |
||
| except (OSError, RuntimeError): | ||
| return False | ||
|
|
||
|
|
||
| def _persisted_git_history(block: str) -> Optional[List[str]]: | ||
| """The snapshot's git-history tip as its bytes recorded it at capture: the | ||
| ``- Recent commits:`` entries when the block carries git state, ``[]`` for a | ||
| repository without commits, None when the block describes a workspace without | ||
| git (marker-only project). The tip is the bytes' own capture-time generation | ||
| evidence — it cannot be manufactured at resume.""" | ||
| lines = block.splitlines() | ||
| if not any(line.startswith("- Branch: ") for line in lines): | ||
| return None | ||
| history: List[str] = [] | ||
| in_commits = False | ||
| for line in lines: | ||
| if line.startswith("- Recent commits:"): | ||
| in_commits = True | ||
| continue | ||
| if in_commits: | ||
| if line.startswith(" "): | ||
| history.append(line.strip()) | ||
| else: | ||
| break | ||
| return history | ||
|
|
||
|
|
||
| def _persisted_generation_matches(block: str, owner: Path, expect_git: bool) -> bool: | ||
| """Whether the snapshot's capture-time evidence still describes today's occupant of | ||
| the workspace. A git workspace is identified by its captured HEAD: the first | ||
| ``- Recent commits:`` entry names the commit the snapshot was taken at, and that | ||
| object exists only in the repository that made it — an independent repository | ||
| created at the same pathname cannot contain it. Membership, not tip equality: the | ||
| pin exists so ordinary work (commits since session start) does NOT rewrite the | ||
| prompt, so a captured HEAD that has since gained descendants is the same | ||
| generation. A marker-only workspace is identified by its project facts.""" | ||
| from agent.coding_context import _facts_lines, _git, detect_project_facts | ||
| persisted_history = _persisted_git_history(block) | ||
| if (persisted_history is not None) != expect_git: | ||
| return False | ||
| if persisted_history is not None: | ||
| if not persisted_history: | ||
| # Captured before the first commit: no object to look up, and nothing a | ||
| # replacement could impersonate beyond an equally empty history. | ||
| return True | ||
| captured_head = persisted_history[0].split(" ", 1)[0] | ||
| # rev-parse prints the full hash when the object is present and unambiguous; | ||
| # "" (missing, ambiguous, or git failure) falls back to a fresh snapshot. | ||
| return bool(_git(owner, "rev-parse", "--verify", "--quiet", f"{captured_head}^{{commit}}")) | ||
| persisted_facts = [line for line in block.splitlines() | ||
| if line.startswith(("- Project: ", "- Verify: ", "- Context files: "))] | ||
| return persisted_facts == _facts_lines(detect_project_facts(owner)) | ||
|
|
||
|
|
||
| def _persisted_workspace_block(prompt: str, key: str) -> Optional[str]: | ||
| """The workspace snapshot inside ``prompt`` taken for ``key`` (its ``- Root:`` is ``key`` or an | ||
| ancestor); "" when the prompt has none; None when it has one for another root.""" | ||
| from agent.coding_context import WORKSPACE_BLOCK_HEADER | ||
| """The workspace snapshot inside ``prompt`` taken for ``key`` (its ``- Root:`` is | ||
| the workspace that owns ``key``); "" when the prompt has none; None when its only | ||
| candidate is not provably this workspace's snapshot. | ||
|
|
||
| Framing first: project context (repo-controlled AGENTS.md content) is rendered | ||
| before the canonical snapshot, so the LAST workspace-shaped block in the prompt is | ||
| the renderer's — earlier copies are project-context prose and are never adopted, | ||
| however exactly they imitate the frame (a context block can name the real root and | ||
| copy its history, but it cannot move itself after the canonical block). | ||
|
|
||
| The candidate then has to prove it still describes this workspace: | ||
| * the persisted ``- Root:`` line is git's physical spelling at capture — if it no | ||
| longer resolves to itself, the directory was renamed or rebound and today's | ||
| ``samefile`` agreement proves nothing (resolved here so a loop in persisted | ||
| bytes cannot escape into the caller's blanket handler); | ||
| * that root must be the workspace that OWNS the cwd today — the producer's own | ||
| git/marker-root resolution, not merely an ancestor: a nested independent | ||
| repository under the captured root is a different workspace; | ||
| * the bytes' git history tip (or project facts, for marker-only workspaces) must | ||
| still match the occupant's — a pathname reused by an independent workspace is a | ||
| new generation even when the spelling is unchanged.""" | ||
| from agent.coding_context import WORKSPACE_BLOCK_HEADER, _workspace_roots | ||
| head = f"\n\n{WORKSPACE_BLOCK_HEADER}\n- Root: " | ||
| start = prompt.find(head) | ||
| start = prompt.rfind(head) | ||
| if start < 0: | ||
| return "" | ||
| cwd = Path(key).resolve() | ||
| while start >= 0: | ||
| block = prompt[start + 2:].split("\n\n", 1)[0] | ||
| root = Path(block.split("\n", 2)[1][len("- Root: "):]).resolve() | ||
| if root == cwd or root in cwd.parents: | ||
| return block | ||
| start = prompt.find(head, start + 2) | ||
| return None | ||
| block = prompt[start + 2:].split("\n\n", 1)[0] | ||
| root_line = block.split("\n", 2)[1][len("- Root: "):] | ||
| if not _persisted_root_still_physical(root_line): | ||
| return None | ||
| try: | ||
| git_root, owner = _workspace_roots(key) | ||
| except (OSError, RuntimeError): # vanished key, or a symlink loop under Python <= 3.12 | ||
| return None | ||
| if owner is None or not _same_live_dir(root_line, str(owner)): | ||
| return None | ||
| if not _persisted_generation_matches(block, Path(owner), git_root is not None): | ||
| return None | ||
| return block | ||
|
|
||
|
|
||
| def _session_prompt(agent: Any) -> Optional[str]: | ||
|
|
@@ -647,13 +835,17 @@ def _seed_workspace_pin(agent: Any, key: str) -> None: | |
| if not prompt: | ||
| return | ||
| stored_cwd = runtime_host_value(prompt, "Current working directory") | ||
| if stored_cwd and stored_cwd != key: | ||
| return | ||
| if stored_cwd: | ||
| # Same spelling normalization as _workspace_pin_key: the persisted hints carry the | ||
| # cwd as that surface spelled it, which can be a symlink — or, on a case-insensitive | ||
| # filesystem, a case-alias — spelling of the same resolved workspace. | ||
| if not key or not _same_live_dir(stored_cwd, key): | ||
| return | ||
| block = _persisted_workspace_block(prompt, key) | ||
| # Only a real snapshot is adopted: a prompt without one (built on a surface without the | ||
| # coding posture, or with tools off) leaves the pin open so this build captures one. | ||
| if block: | ||
| agent._frozen_workspace_snapshot = (key, block) | ||
| agent._frozen_workspace_snapshot = (key, block, _workspace_generation(key)) | ||
|
|
||
|
|
||
| def _coding_parts(agent: Any) -> Tuple[List[str], List[str], List[str]]: | ||
|
|
@@ -677,11 +869,33 @@ def _coding_parts(agent: Any) -> Tuple[List[str], List[str], List[str]]: | |
| _seed_workspace_pin(agent, cwd_key) | ||
| pinned = getattr(agent, "_frozen_workspace_snapshot", None) | ||
| # "" is a real pinned value (no workspace here) — only a cwd mismatch re-probes. | ||
| replay = pinned[1] if pinned is not None and pinned[0] == cwd_key else None | ||
| # A key match alone is not provenance: the captured key names its directory only | ||
| # until the path is rebound (renamed + reused for a symlink), and the recorded | ||
| # directory identity alone does not prove a lifetime — a removed-and-recreated | ||
| # pathname can reuse the (st_dev, st_ino) pair. The generation adds the owning | ||
| # .git marker's identity, which ordinary git work never deletes and every new | ||
| # workspace generation changes; a pin whose recorded generation no longer | ||
| # matches today's replays as None and the build probes fresh. Legacy tuples | ||
| # carry no generation and keep the key-match contract. | ||
| replay = None | ||
| if pinned is not None and _same_pin_key(pinned[0], cwd_key): | ||
| identity = pinned[2] if len(pinned) > 2 else None | ||
| if identity is None or _workspace_generation(pinned[0]) == identity: | ||
| replay = pinned[1] | ||
| if replay is None: | ||
| # Pairing: the published pin must bind the collected bytes to the directory | ||
| # generation they were taken in. Sampling only after the producer runs lets a | ||
| # replacement that lands in between certify old bytes with the new | ||
| # occupant's identity, so the generation is sampled on both sides and a | ||
| # mismatched pairing publishes nothing — the pin stays unseeded and the | ||
| # next build probes fresh. | ||
| pre = _workspace_generation(cwd_key) | ||
| parts = coding_system_prompt_parts(platform=agent.platform, cwd=cwd, model=agent.model, | ||
| valid_tool_names=agent.valid_tool_names, workspace_block=replay) | ||
| if replay is None: | ||
| agent._frozen_workspace_snapshot = (cwd_key, parts[1][0] if parts[1] else "") | ||
| post = _workspace_generation(cwd_key) | ||
| if pre is not None and pre == post: | ||
| agent._frozen_workspace_snapshot = (cwd_key, parts[1][0] if parts[1] else "", post) | ||
| return parts | ||
| except Exception: | ||
| pass | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| lihongyuan99 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nonblocking] The same spelling comparison remains at the runtime-cwd sink.
agent/conversation_loop.py:877-878(_stored_prompt_matches_runtime) still compares the storedCurrent working directorytostr(resolve_agent_cwd())raw, andagent/prompt_builder.py:1001renders that line in the session's spelling.Probe on this head with real environment hints: build from the launch dir, add an untracked file, then
set_session_cwd(<symlink to the repo>)and rebuild. The workspace block now replays, and the first differing byte is 6407 of 6781, the hostCurrent working directory:line. On main it was 4878, the workspace block._stored_prompt_matches_runtime(agent, p1)is False on both, so a resumed or adopted session still fully rebuilds across a spelling-only change.Suggested fix in
_stored_prompt_matches_runtime:if stored_cwd and Path(stored_cwd).resolve() != resolve_agent_cwd().resolve(): return False. Please confirm whether that belongs here or in a follow-up.