Skip to content
Open
Show file tree
Hide file tree
Changes from 10 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
23 changes: 16 additions & 7 deletions agent/coding_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,21 @@ def project_facts_for(cwd: Optional[str | Path] = None) -> Optional[dict[str, An
}


def _facts_lines(facts: ProjectFacts) -> list[str]:
"""The workspace-block lines that carry project facts, rendered exactly as
``build_coding_workspace_block`` emits them — the evidence a pin re-derives to tell
a marker-only workspace's generation from its successor's."""
lines: list[str] = []
if facts.manifests:
managers = f" ({'/'.join(facts.package_managers)})" if facts.package_managers else ""
lines.append(f"- Project: {', '.join(facts.manifests[:6])}{managers}")
if facts.verify_commands:
lines.append(f"- Verify: {'; '.join(facts.verify_commands)}")
if facts.context_files:
lines.append(f"- Context files: {', '.join(facts.context_files)}")
return lines


WORKSPACE_BLOCK_HEADER = "Workspace (snapshot at session start — re-check with `git` before acting on it):"


Expand Down Expand Up @@ -553,13 +568,7 @@ def build_coding_workspace_block(cwd: Optional[str | Path] = None) -> str:
lines.extend(["- Recent commits:", *(f" {c}" for c in recent.splitlines())])

f = detect_project_facts(root)
if f.manifests:
managers = f" ({'/'.join(f.package_managers)})" if f.package_managers else ""
lines.append(f"- Project: {', '.join(f.manifests[:6])}{managers}")
if f.verify_commands:
lines.append(f"- Verify: {'; '.join(f.verify_commands)}")
if f.context_files:
lines.append(f"- Context files: {', '.join(f.context_files)}")
lines.extend(_facts_lines(f))
return "\n".join(lines)


Expand Down
258 changes: 236 additions & 22 deletions agent/system_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ""

Copy link
Copy Markdown
Contributor

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 stored Current working directory to str(resolve_agent_cwd()) raw, and agent/prompt_builder.py:1001 renders 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 host Current 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Compare existing directories by filesystem identity. Path.resolve() follows symlinks, but on default case-insensitive macOS APFS it preserves the casing supplied by the caller. As a result, .../MixedCase and .../mixedcase refer to the same directory (os.path.samefile() returns true) but still produce different keys here. _coding_parts() then misses the pin and probes Git again.

I reproduced this on the exact head through the real set_session_cwd() path: build in MixedCase, add an untracked file, invalidate the prompt, then bind mixedcase. The rebuilt workspace snapshot changed from Status: clean to Status: 1 untracked. That is the same mid-session snapshot drift this change is meant to prevent.

Please compare live paths with Path.samefile() or an equivalent filesystem-identity check, with a safe fallback when a persisted path is no longer available. Apply the same equivalence in _seed_workspace_pin(), and add a macOS case-alias regression through the real session-cwd resolver.

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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 A is renamed to A-saved, A is replaced with a directory symlink to an independent repository B, and the same session is then explicitly bound to B, both arguments resolve to B here. _same_pin_key(old_A_key, new_B_key) returns True even though the original directory still exists at A-saved and has a different filesystem identity from B.

The consequence follows through the changed caller: _coding_parts supplies A's frozen workspace block as workspace_block, so the consumer bypasses its fresh probe. The prompt can retain A's root/commit information after the explicit switch to B. If A's live pin was empty, B's workspace snapshot stays absent. This is not the intended retention of old Git status inside an unchanged workspace: the captured directory and current directory are distinct.

The persisted sibling has the same cause. _seed_workspace_pin and _persisted_workspace_block reinterpret both the historical cwd and historical physical - Root: against the replacement symlink, so a fresh agent can adopt A's bytes for B too. At base 28e6496, the unequal cwd strings reject this adoption and unequal live keys request a fresh snapshot.

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: True

Observed 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 samefile result as provenance. Apply this at both replay and adoption, without reverting the intended stable-symlink/case-alias behavior.

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)

@andrexibiza andrexibiza Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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:

  1. Build/persist repo A at pathname P.
  2. Remove A and create independent repo B at the exact same P (different HEAD).
  3. Resume a fresh agent at P.

Because the string is unchanged, this line still returns true: Path(P).resolve() == Path(P). _same_live_dir(stored_cwd, key) also succeeds, so _persisted_workspace_block returns A's historical block. Then _seed_workspace_pin records B's current (st_dev, st_ino) next to A's old bytes. The subsequent replay check passes by construction and the production consumer sees a non-None workspace_block, so it skips B's Git probe.

Observed: A/B root strings equal; A/B HEADs different; this fixpoint check True; old A block adopted True; seeded identity equals current B True; fresh-probe decision False. The symlink-rebind scenario is the positive control: once the old path resolves through a symlink, this check is False and the new repair rejects it correctly.

The live sibling shows why _dir_identity is also insufficient as the sole lifetime proof. On Linux/Python 3.13.5/overlayfs, I captured an empty pin for a plain directory, removed/recreated that pathname, and the same (st_dev, st_ino) was recycled on the first recreation. After git init made the new directory repo B, the key and identity checks both still passed, replay == "", and B's workspace probe was suppressed. This is a real filesystem/Git probe of the exact guard semantics, not a claim that every filesystem recycles immediately.

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]:
Expand Down Expand Up @@ -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]]:
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions contributors/emails/982026408@qq.com
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
lihongyuan99
Loading
Loading