Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(vibey): persist tiered prompt snapshots and warm fork prefixes (#3117)
Call White4c6567074ddf
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.pyindex 2ba6bf775..723c51b02 100644--- a/core/agent_core/agent/loop.py+++ b/core/agent_core/agent/loop.py@@ -107,7 +107,7 @@ from core.agent_core.harness.context import (StateRequest,add_usage,budget,- cache_ttl_s,+ cache_cold,checkpoint_block,checkpoint_max_tokens,checkpoint_repair,@@ -434,6 +434,11 @@ class Agent:self._last_model_at: dict[tuple[str, str], float] = {}self._seq = 0+ @property+ def tools(self) -> tuple[Tool, ...]:+ """The configured tools, before a run takes its own fixed set."""+ return tuple(self._tools.values())+def set_tools(self, tools: Sequence[Tool]) -> None:names = [tool.spec.name for tool in tools]if len(names) != len(set(names)):@@ -1703,13 +1708,7 @@ class Agent:row also retains the served Source identity for canonical replay and scrubbing, but this C-9 clock intentionallykeys by provider/model."""- used = dict(self._last_model_at)- for row in self._rows:- if row.kind == "response" and row.created_at is not None:- cache = _cache_of(row.message.origin)- used[cache] = max(used.get(cache, row.created_at), row.created_at)- last = used.get(_cache_of(endpoint_origin(request.endpoint)), max(used.values(), default=None))- return last is not None and self.context.clock() - last > cache_ttl_s(request.endpoint, request=request)+ return cache_cold(request, self._rows, now=self.context.clock(), last_model_at=self._last_model_at)async def _prepare_conversation(self, system: str, selected: ModelSelection) -> _PreparedConversation:"""Compose and budget before any context transition; also used by dry_tick."""diff --git a/core/agent_core/harness/context.py b/core/agent_core/harness/context.pyindex 310eee8bf..7e6f10614 100644--- a/core/agent_core/harness/context.py+++ b/core/agent_core/harness/context.py@@ -234,7 +234,7 @@ What the user ultimately wants from this conversation, and why it matters to the## What I ownWhat I am responsible for seeing through, and where that ends.## Agreements-How to report, when to ask, what I may decide on my own, and the scope of what I am authorized to do, written as principles. Do not redefine who I am: my identity and this Session's id come from the system prompt; when mentioning another Session, give its id and how it relates to this one.+How to report, when to ask, what I may decide on my own, and the scope of what I am authorized to do, written as principles. Keep my identity from the system prompt and Session id from the environment; when mentioning another Session, give its id and how it relates to this one.# 2. Goals## MissionIn your own words, the ultimate purpose of this conversation and its status; its scope is the user's, neither wider nor narrower.@@ -679,6 +679,25 @@ def cache_ttl_s(endpoint: ModelEndpoint, *, request: ModelRequest | None = None)return CACHE_TTL_UNKNOWN_S if family is None else CACHE_TTLS[family]+def cache_cold(+ request: ModelRequest, entries: Sequence[ContextEntry], *, now: float,+ last_model_at: Mapping[tuple[str, str], float] | None = None,+) -> bool:+ """C-9's route clock, shared with the adapter's Turn-start prompt policy.++ Unknown use leans warm; a route without its own use takes the latest use of any route.+ """+ used = dict(last_model_at or {})+ for row in entries:+ if row.kind == "response" and row.created_at is not None:+ origin = row.message.origin+ key = (origin.provider, origin.model)+ used[key] = max(used.get(key, row.created_at), row.created_at)+ key = (request.endpoint.provider, request.endpoint.model_id)+ last = used.get(key, max(used.values(), default=None))+ return last is not None and now - last > cache_ttl_s(request.endpoint, request=request)++def _cache_family(endpoint: ModelEndpoint) -> Optional[str]:"""The route's cache family from its provider, protocol, and whole model id; None unless unambiguous."""if endpoint.protocol == "anthropic":diff --git a/core/agent_core/tools/edit.py b/core/agent_core/tools/edit.pyindex 380c58ce5..26dd53fd4 100644--- a/core/agent_core/tools/edit.py+++ b/core/agent_core/tools/edit.py@@ -39,7 +39,7 @@ from core.agent_core.tools.paths import ()from core.agent_core.tools.text import decode_file, encode_file, model_textfrom core.agent_core.tools.truncate import format_size-from core.agent_core.tools.write import FileChanged, FileIdentity, NotReplaceable, may_write, write_bytes+from core.agent_core.tools.write import FileChanged, FileIdentity, NotReplaceable, may_write, write_bytes, write_receipt#: Avibe: larger files are refused rather than loaded whole; the display diff stops at a smaller size.MAX_EDIT_BYTES = 10 * 1024 * 1024@@ -284,11 +284,12 @@ class EditTool:return error_result(f"Could not edit file: {path}. Error code: {errno_name(exc)}.")result = edit_summary(path, edits, counts, changed)+ details = {"file_write": await to_thread_joined(write_receipt, absolute, data)}if max(size, len(data)) > MAX_DIFF_BYTES:# The diff is for display only, and difflib is superlinear on large inputs.- return text_result(result, details={"diff_skipped": True})+ return text_result(result, details={**details, "diff_skipped": True})shown_diff = await asyncio.to_thread(display_diff, path, base, new_content)if shown_diff is None:- return text_result(result, details={"diff_skipped": True})+ return text_result(result, details={**details, "diff_skipped": True})diff, first_changed_line, patch = shown_diff- return text_result(result, details={"diff": diff, "patch": patch, "first_changed_line": first_changed_line})+ return text_result(result, details={**details, "diff": diff, "patch": patch, "first_changed_line": first_changed_line})diff --git a/core/agent_core/tools/write.py b/core/agent_core/tools/write.pyindex c79a349c0..279c61b46 100644--- a/core/agent_core/tools/write.py+++ b/core/agent_core/tools/write.py@@ -7,6 +7,7 @@ Ported from Pi ``packages/coding-agent/src/core/tools/write.ts`` (MIT, Copyrightfrom __future__ import annotationsimport contextlib+import hashlibimport errnoimport osimport secrets@@ -81,7 +82,13 @@ class WriteTool:return error_result(f"Cannot write {path}: {KIND_REASON[exc.kind]}.")except OSError as exc:return error_result(f"Cannot write {path}: {os_reason(exc)}.")- return text_result(f"Successfully wrote to {path}")+ receipt = await to_thread_joined(write_receipt, absolute, content)+ return text_result(f"Successfully wrote to {path}", details={"file_write": receipt})+++def write_receipt(path: str, data: bytes | str) -> dict[str, str]:+ """Evidence for this exact successful write, not a later reread somebody else may have changed."""+ return {"path": path, "revision": hashlib.sha256(data.encode("utf-8") if isinstance(data, str) else data).hexdigest()}def _prepare_target(absolute: str) -> Optional[str]:diff --git a/core/services/session_fork.py b/core/services/session_fork.pyindex 3459d5b5b..f7f273b1f 100644--- a/core/services/session_fork.py+++ b/core/services/session_fork.py@@ -477,6 +477,13 @@ def reserve_forked_session(require_workdir=False,)+ if source_backend == "vibey":+ from modules.agents.vibey.prompt_snapshot import SnapshotStore++ # This service already runs on its callers' worker paths. Copy now: a+ # source may refresh again before the child's first Turn begins.+ SnapshotStore(paths.get_state_dir() / "agent_core").inherit(str(source_session_id), session_id)+fork = SessionForkSpec(source_session_id=str(source_session_id),source_native_session_id=source_native,diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex d16937047..d3fe55f08 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -208,7 +208,7 @@ def build_system_prompt_blocks(render_prompt_block("base-capabilities-intro"),render_prompt_block("agent-working-principles"),]- if context is not None:+ if context is not None and backend != "vibey":blocks.append(render_prompt_block("session-start-prompt", default_session_id=_extract_default_session_id(context)))correction = build_forked_session_correction_prompt(context)if correction:diff --git a/docs/plans/agent-core-contracts/context.md b/docs/plans/agent-core-contracts/context.mdindex d3178c511..ae0316075 100644--- a/docs/plans/agent-core-contracts/context.md+++ b/docs/plans/agent-core-contracts/context.md@@ -419,8 +419,8 @@ is written, so projection stays a pure function of the rows:of two real first consolidations, a seven-part edit dropped a heading, and the structure repair it took doubledthe checkpoint's requests. The model revises what is under the headings, never the lines themselves, and may add headings of its own beneath them. Text before the first heading counts toward thefirst section's limit and is cut with it. A mind still the template keeps no mind- (`mind` is empty), and the next checkpoint starts from the template again. My identity and the Session's id are the- system prompt's; the mind never restates them.+ (`mind` is empty), and the next checkpoint starts from the template again. My identity is the system prompt's and the Session's id is the current environment's; the+ mind never restates them.- **The memo** (`memo`: `{seq, text, truncated}`, in `context_seq` order): the messages a person typed that the nextcontext carries verbatim, whitespace included, each cut to 300 tokens (head kept), at most 3,000 tokens together, counted as thecheckpoint shows them, each entry's `(#<seq>)` line and cut note included. Its list, `memo.md`,@@ -467,10 +467,10 @@ is written, so projection stays a pure function of the rows:(`kept_inputs`, §5): a mid-turn checkpoint may misstate the Turn (as finished, or as more than was asked), and theverbatim inputs placed before it must win.- `state`: texts the adapter rendered from their own stores when the checkpoint was written: the environment's core- fields (C-7 §8: cwd, os, shell; no Watches; each field displayed as every input's block displays it,- the cwd escaped and never cut, every other field cut to 160 UTF-8 bytes (`display`), so the block is the cwd, which- the OS bounds, plus at most about 2 x 40 tokens; a checkpoint always happens inside- a run, and a Turn's own input carries only the fields that changed). Pending work is the now's own "Waiting on",+ fields (C-7 §8: session, cwd, os, shell, instructions; no Watches; each field displayed as every input's block+ displays it). The Session id and pending revisions remain available after a checkpoint. The cwd and pending+ notice are escaped and never cut; other fields use the 160-byte display bound. A checkpoint always happens inside+ a run, and a Turn's own input carries only the fields that changed. Pending work is the now's own "Waiting on",and the in-flight Turn's inputs stay as they were (§5).- Projection (C-5 §3): the system prompt, hook-rehydrated messages, the kept inputs (§5), one user messageholding `summary` and then each `state` text as its own text block, then the rows from `first_kept_seq` on, with@@ -767,7 +767,7 @@ What the user ultimately wants from this conversation, and why it matters to the## What I ownWhat I am responsible for seeing through, and where that ends.## Agreements-How to report, when to ask, what I may decide on my own, and the scope of what I am authorized to do, written as principles. Do not redefine who I am: my identity and this Session's id come from the system prompt; when mentioning another Session, give its id and how it relates to this one.+How to report, when to ask, what I may decide on my own, and the scope of what I am authorized to do, written as principles. Keep my identity from the system prompt and Session id from the environment; when mentioning another Session, give its id and how it relates to this one.# 2. Goals## MissionIn your own words, the ultimate purpose of this conversation and its status; its scope is the user's, neither wider nor narrower.diff --git a/docs/plans/agent-core-contracts/fork.md b/docs/plans/agent-core-contracts/fork.mdindex d828c2503..7985ad4a8 100644--- a/docs/plans/agent-core-contracts/fork.md+++ b/docs/plans/agent-core-contracts/fork.md@@ -192,14 +192,19 @@ because they are rendered into the prompt (C-9 §6).upstream, so the policy cannot deny it at execution: a side turn may make one, billed like any other. A side turn'sprompt asks for its reply, and a warm prefix on every checkpoint is worth more than that rare call.-**A fork Session is cache-cold today.**+**Warm fork Sessions.**-- Vibey's system prompt carries the Session's own id, plus a fork note (`core/system_prompt_injection.py:228-231`,- `core/prompts/forked-session.md`). So a child's first request shares only the tool definitions with its source.-- For a user's fork, correct identity is worth one cold prefix.-- For N teammates forked from one large context, it is N cold copies of that context.-- The remedy is a Session-invariant system prompt, with the Session id moved into the environment block of the- first input (C-7 §8). That is left to the teams design (§17).+Vibey's cached prefix is Session-invariant: the Session id travels in the first own input's environment block+(C-7 §8), and the existing fork notice stays in that input (§8), never in the system prompt. Reservation copies+its source's optional prompt snapshot byte for byte, before either Session can use a later source snapshot. The+child's Turn-start policy compares current candidates with this inherited prefix using the same tiers and deadlines+as any other Turn (`../system-prompt-cache-tiers.md`). A warm same-route fork with no immediately due change can+therefore reuse the source's cached system, tools, and inherited conversation prefix. A route/Agent override or a+required tier refresh may deliberately make the fork cold; an absent/corrupt snapshot renders fresh.++The snapshot contains rendered instructions and declarations only, never credentials or execution grants. Live tool+executors, provider refusals, and route fallback behavior remain authoritative. Native backends keep their existing+Session/fork prompts.## 4. Storage: by reference@@ -545,8 +550,8 @@ already provide, plus work outside fork.now or a tool later. They run in the background with one task message each. Each shares the prefix by referenceand runs concurrently as its own Session, and their replies come back as Harness inputs (§9).- Needs from fork: nothing more.- - Needs elsewhere, left to the teams design: the descendant lookup (§5) and a Session-invariant system prompt, so- that N forks of one large context hit the cache (§3). No depth or descendant bound (O-4).+ - Needs elsewhere, left to the teams design: the descendant lookup (§5). The Session-invariant cached prefix+ now supports warm forks (§3). No depth or descendant bound (O-4).- **Self context management.**- Explore and come back: a background fork Session with full tools, because exploring needs `bash`. Its replyreturns as a message.diff --git a/docs/plans/agent-core-contracts/tools.md b/docs/plans/agent-core-contracts/tools.mdindex d31b5cedb..743f0e241 100644--- a/docs/plans/agent-core-contracts/tools.md+++ b/docs/plans/agent-core-contracts/tools.md@@ -345,10 +345,12 @@ the projected context no longer shows, because the inputs that carried the earli```text<environment>+session: ses_examplecwd: /absolute/pathos: macOS 26.0 (arm64)shell: /bin/bashwatches: wch_8f2k "nightly sync" command running; wch_3c1d job running+instructions: current</environment>```@@ -356,14 +358,28 @@ The date and time are not fields: every input's `[Now: ...]` line (`core/agent_itime, and UTC offset. Blocks stored while the block still had `date` and `timezone` keep replaying; those two linesare ignored when the loop reads back what the model was last told.+`session` is the authoritative Session id. It is delivered on the first own input (including a fork's),+then only when the projected context no longer carries it. Vibey's system prompt contains neither the id nor+its fork correction; native backends keep their existing prompts.++`instructions` is `current`, or `pending <path-or-catalog>@<short-revision>; ...`. It names changed components,+never their contents, and is sent only when its value changes. A later revision of an already pending component+changes the notice again; application sends `current` once. Changes proven to be this Session's own successful+`write`/`edit` are omitted only while the candidate still matches that exact byte revision. Unattributed changes+(including arbitrary shell commands) are treated as external, never guessed to be self-authored. A fixed sentence+in the system prompt tells the Agent to read the current file or query the catalog before relying on a listed part.+The pending field is escaped and not cut, so revisions after a long path remain visible and send-on-change remains+exact. Its names are bounded by the prompt's component set, not by conversation history.+`shell` is the shell the commands run in: the job host's on POSIX (`/bin/bash`, else `bash` on `PATH`, else `sh`), andon Windows `PowerShell 7 ({path})` or `Windows PowerShell 5.1 ({path})`.`watches` names the Session's enabled Watches by id, name, and kind, never a command: at most 20, then `and N more`.A field's identity is its raw value; only the block displays it, through the one display helper (`display`, C-9`context.md` §7): one line of plain text, escaped injectively (a backslash doubled, control characters and `<`, `>`as `\uXXXX`), then cut in the middle to 160 UTF-8 bytes, each Watch's line on its own. The cwd is escaped and never-cut: the model builds absolute paths from it, so a cut one would be false, and the OS bounds its length. So the block-stays bounded on every input whatever the script, and no value can add a line, forge a field, or close the block.+cut: the model builds absolute paths from it, so a cut one would be false, and the OS bounds its length. The+`instructions` field is likewise never cut (above). Every value is escaped, so none can add a line, forge a field,+or close the block.The rows hold only what the model read, so a field counts as unchanged only when its display equals what the modellast read and is not cut: escaping is injective, but a cut display can look the same after its value changed, so acut field is sent on every input rather than taken for unchanged.@@ -437,11 +453,21 @@ A directory below the working directory may hold its own instruction file with mown facts, so the provider's cache shares the longer prefix across Sessions.- The Agent's own definition, in Avibe's sections, is more specific than a repository's guidance, and comes later.-**Read every Turn, cache-stable.** The files are read again at the start of every Turn, from that Turn's cwd, so an-edit takes effect on the next Turn. The section depends only on the files' paths and contents, never on times or-modification stamps, so the system prompt changes only when a file does. What uses the Turn's system prompt gets the-same section: the checkpoint turn and the request after a checkpoint (C-9), and a side turn (C-10). A fork Session reads-its own at its first Turn.+**Read every Turn, apply by tier.** Files and prompt catalogs are read again at each Turn start, but the whole+cached prefix (system prompt components and tool definitions) is retained in the Session's optional+`<state>/agent_core/prompts/<session_id>/snapshot.json`. `pending.json` independently keeps each changed+component's latest revision and its first-detected time. Missing, malformed, unreadable, or inconsistent files+mean fresh rendering; failures to persist never fail the Turn. All these reads and writes run off the controller loop.++The policy is [`../system-prompt-cache-tiers.md`](../system-prompt-cache-tiers.md): global instructions, Agent+identity/definition and changed Avibe code are tier 1 (next Turn); project instructions and catalogs are tier 2+(next free moment or after 30 minutes continuously pending); a Bot's own memory file and environment+details are tier 3 (free moments only). Authorship only suppresses the notice; it never changes a component's tier+or resets its deadline. Removing or downgrading a native hosted tool is an immediate route change: a cached+declaration cannot restore execution authority. A changed model/route/Agent, the existing C-9 cold-cache clock, or a checkpoint+since application is a free moment. One qualifying change applies all pending components together. There is no+explicit refresh action. The prefix remains fixed for the whole Turn, including checkpoint/side requests; a fork+inherits its source's saved prefix at reservation (C-10 §3). Native CLIs' prompt behavior is unchanged.**Bound.** The section carries at most 65,536 bytes (64 KiB), about 16,000 tokens. That count includes the header,each file's path and markup, the files' text, and the notices, so the bound holds by construction, whatever thediff --git a/docs/plans/system-prompt-cache-tiers.md b/docs/plans/system-prompt-cache-tiers.mdindex 070769812..6cd5f5a18 100644--- a/docs/plans/system-prompt-cache-tiers.md+++ b/docs/plans/system-prompt-cache-tiers.md@@ -81,7 +81,9 @@ module id, each instruction file by path) and the tool definitions.it changed to and when it was first seen (`pending_since`). The pendingrecord is written whenever it changes, independently of the appliedsnapshot, so a restart keeps the original `pending_since` and cannot extend- a tier-2 deadline.+ a tier-2 deadline. It also keeps the checkpoint sequence last observed at a+ Turn-start decision, even when the prefix stayed unchanged, so that a+ checkpoint's refresh opportunity cannot be reused by a later warm Turn.- A fork copies its source's snapshot byte for byte, so its first requesthits the source's cache. This and moving the Session id out of the systemprompt (`agent-core-contracts/fork.md` §3) are both needed for warm forks.@@ -100,8 +102,9 @@ holds:- the route's conversation cache has expired (the existing`_cache_cold` clock, by the route's lifetime);- the model or route changed;- - a checkpoint ran since the snapshot was applied (the context was just- condensed, so the re-read is small);+ - a checkpoint ran since the previous Turn-start decision (the context+ was just condensed, so the re-read is small); this opportunity is+ consumed even if the prefix is unchanged, and remains consumed after a restart;3. a tier-2 change has been pending for at least `N` minutes.Otherwise keep the snapshot and tell the model what is pending (below).@@ -122,13 +125,20 @@ free instead of cheap.| Tier | Meaning | Reserved for || --- | --- | --- || 1 Immediate | Replace at the next Turn start | Who the Agent is; the user's global rules, saved deliberately and rarely; Avibe's own contract after an upgrade |-| 2 Bounded | Replace at the next free moment, or after `N` minutes | Instructions and capabilities someone else changed for this Session |-| 3 Natural | Replace at the next free moment only | The Session's own writing, and environment details |+| 2 Bounded | Replace at the next free moment, or after `N` minutes | Project instructions, shared memory, and capability catalogs |+| 3 Natural | Replace at the next free moment only | A Bot's own memory file, and environment details |The pending notice makes tiers 2 and 3 semantically immediate: the modellearns of the change on the next input and can read the current version. Atier decides only when the system prompt itself is replaced.+The component fixes its tier; authorship only controls the pending notice (orchestrator clarification,+2026-11-01). A project's `AGENTS.md` stays tier 2 even after a proven self-edit; a Bot's own `AGENTS.md`+stays tier 3 even when somebody else edits it. Unattributed shell or concurrent edits count as external.+Capability revocation takes effect immediately: removing or downgrading an enabled native hosted tool is a+route change and refreshes at the next Turn, since the provider executes its declaration without a local+function-tool gate. Added or non-revoking declarations remain tier 2; function tools retain live execution checks.+### Component table| Component | Source | Changed by | Tier |@@ -141,7 +151,7 @@ tier decides only when the system prompt itself is replaced.| Agents and Bots roster | database | the user (create, enable, rename, set as Bot) | 2 || Skills catalog | Skill directories | the user (install, remove, enable) | 2 || MCP catalog | MCP Hub | the user (connect, remove), or a login expiring | 2 |-| Hosted tool declarations | Model Hub service configuration | the user (enable a search service) | 2 |+| Hosted tool declarations | Model Hub service configuration | the user (enable a search service) | 2; removal or downgrade of an enabled native tool is an immediate route change (above) || Platform switches (quick replies, session title section) | configuration | the user | 2 || A Bot's own `AGENTS.md` | file | the Bot itself; others' edits get the notice | 3 || Tool list details (ripgrep found on `PATH`) | environment | the runtime | 3 |@@ -169,8 +179,9 @@ instructions: pending ~/.avibe/AGENTS.md@3f9a2c; skills@81be07`agents`), never their contents. Each name carries a short revision of thecomponent's current content, so a second edit to an already pendingcomponent changes the value and is announced again.-- It omits changes this Session made itself (its own edits are already in the- conversation).+- It omits changes proven to be this Session's own successful `write`/`edit`, only while the current content+ matches the exact written revision (its own edits are already in the conversation). This does not change the+ component's tier or restart its deadline; arbitrary shell edits are not attributed by guessing.- When a snapshot is applied the value becomes `current`, sent once.- The field name is lowercase letters, as the block's parser requires.- A fixed sentence in the system prompt explains the field once: the listeddiff --git a/docs/plans/system-prompt-snapshots-implementation.md b/docs/plans/system-prompt-snapshots-implementation.mdnew file mode 100644index 000000000..1cc554174--- /dev/null+++ b/docs/plans/system-prompt-snapshots-implementation.md@@ -0,0 +1,17 @@+# PR 3a implementation contract++Scope: Vibey only. Implements the Snapshot / replacement / Tiers / Pending notice / Persisted shape sections of `system-prompt-cache-tiers.md`; metrics follow after this PR merges.++Invariants:+- The cached system/tool prefix is a durable per-Session snapshot, compared by module id / instruction path. Unknown components are tier 2. Tier 1, a cold route, a route/model/Agent change, a checkpoint, or a 30-minute tier-2 deadline replaces the whole snapshot at Turn start only.+- Pending revisions and first-detected times persist separately; repeated edits do not extend a continuously pending tier-2 deadline. All optional-state failures degrade to fresh rendering, never block a Turn or recovery.+- Session identity travels in the input environment, never the Vibey system prompt. A fork copies its source snapshot at reservation. Native backend prompts and fork behavior remain unchanged.+- Pending names/revisions are send-on-change, without contents. Proven successful direct file writes are suppressed only for that exact revision; an outside edit remains visible.+- Filesystem work stays off the controller loop. Stored tools contain declarations, never routes' credentials. Live execution/refusal boundaries remain authoritative.++Primary validation boundaries:+- Pure snapshot decisions: each tier/free moment, deadline through restart, malformed snapshot and pending files, exact stable rendered bytes.+- Adapter integration: two Turns and an adapter restart, own versus external file revisions, pending/current environment deltas, real fork reservation and child/source prefix equality.+- Shared prompt regressions prove non-Vibey behavior unchanged; existing request-preview and checkpoint tests cover consumers.++No refresh UI/CLI, no database migration, no cache metrics in this PR, no deployment or service restart.diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 617e7fe90..169950008 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -60,12 +60,14 @@ from core.agent_core.agent.loop import Agentfrom core.agent_core.agent.preview import RequestPreviewfrom core.agent_core.agent.models import ModelSelection, RetryPolicyfrom core.agent_core.agent.recovery import settle_open_calls-from core.agent_core.harness.context import ContextConfig+from core.agent_core.harness.context import ContextConfig, cache_cold+from core.agent_core.ai.provider import ModelRequestfrom core.agent_core.harness.projection import open_tool_callsfrom core.agent_core.hosted_continuations import pending_hostedfrom core.agent_core.ai.request_artifacts import RequestArtifactStore, capture_model_requestsfrom core.agent_core.ai.transform import in_flight_positionfrom core.agent_core.tools.base import CallInstance+from core.agent_core.tools.paths import to_thread_joinedfrom core.agent_core.tools.jobs import call_instancefrom core.agent_core.messages import (HOSTED_RENDER_EPOCH,@@ -107,7 +109,9 @@ from modules.agents.vibey.context import (mark_skill_loads,)from modules.agents.vibey.errors import error_text+from core.prompt_registry import RenderedPromptBlock, join_prompt_blocksfrom modules.agents.vibey.instructions import load_instruction_files, project_context+from modules.agents.vibey.prompt_snapshot import State as PromptState, SnapshotStore, candidate_prefix, decide, frozen_tools, route_identityfrom modules.agents.vibey.media import MediaSnapshotsfrom modules.agents.vibey.models import HubModelRouter, ProviderFactory, registry_providers, selection_from_hopfrom modules.agents.vibey.native_search_recovery import (@@ -164,12 +168,6 @@ def _relative_to(cwd: str) -> Callable[[str], str]:return relative-def _project_instructions(cwd: str) -> str:- """The ``<project_context>`` section for a Turn in ``cwd``: the user's global file, then the instruction files from- the filesystem root down to ``cwd`` (C-7 tools.md section 9)."""- return project_context(load_instruction_files(cwd, paths.get_global_instructions_path()))--#: ``Agent.max_tokens`` for every Turn: the resolved hop's budgeted maximum decides the output (``budgeted``)._NO_OUTPUT_CAP = 1 << 30#: A failure's diagnostic in the service log: one redacted line, bounded, never a payload.@@ -202,6 +200,7 @@ class _Run:agent: Optional[Agent] = Nonerouter: Optional[HubModelRouter] = Nonecwd: str = ""+ instructions_notice: Optional[str] = Nonesettled: bool = Falsereason: Optional[str] = None# The error that decided ``reason`` (``RunEnded.cause``): the failure's kind, text, and Model Hub attribution.@@ -270,6 +269,7 @@ class VibeyAgent(BaseAgent):self._engine = engine or get_cached_sqlite_engine()state = Path(state_dir) if state_dir is not None else paths.get_state_dir() / "agent_core"self._state_dir = state+ self.prompt_snapshots = SnapshotStore(state)self.media = MediaSnapshots(self._engine, state / "media")# The exact bytes of every model request a Turn sends, kept when it does not succeed (``request_artifacts``).self.request_artifacts = RequestArtifactStore(state / "model-requests")@@ -282,6 +282,7 @@ class VibeyAgent(BaseAgent):environment=self._environment,on_response=self._on_response,response_metadata=self._response_metadata,+ file_write=self._record_instruction_write,)self._providers = providers or registry_providers(media_loader=self.media)# The client of the Turn's other gateway calls (the hosted-tool executor); None opens one per call.@@ -404,9 +405,13 @@ class VibeyAgent(BaseAgent):sections, skill_catalog = await self._avibe_sections(request, cwd)builtin_agent = await asyncio.to_thread(self._is_builtin_agent, request)environment = await asyncio.to_thread(self._turn_environment, request, cwd)- # Read again every Turn, so an edit takes effect on the next one (C-7 tools.md section 9).- instructions = await asyncio.to_thread(_project_instructions, cwd)- self._start_agent(turn, cwd, sections, environment, builtin_agent=builtin_agent, instructions=instructions)+ files = await asyncio.to_thread(load_instruction_files, cwd, paths.get_global_instructions_path(), include_empty=True)+ self._start_agent(turn, cwd, join_prompt_blocks(sections), environment,+ builtin_agent=builtin_agent, instructions=project_context(files))+ prompt_state = await self._prepare_prompt(+ turn.agent, request, turn.router, sections, files, environment, builtin_agent=builtin_agent, catalog=skill_catalog,+ )+ turn.instructions_notice = prompt_state.noticeruntime.cwd = cwd# Prepared before anything is dispatched (``core.native_dispatch_phase``).message = await self._render_input(session_id, request.message, request.files, request.input_metadata)@@ -419,7 +424,7 @@ class VibeyAgent(BaseAgent):if indicator is not None:# The ack message goes once the native write is accepted, as for the other backends.await indicator.delete_ack_message(request)- accept_catalog(self.controller, context, skill_catalog, backend=BACKEND)+ accept_catalog(self.controller, context, prompt_state.snapshot.prefix.catalog, backend=BACKEND)agent_input: Optional[AgentInput] = AgentInput(input_id, message)platform_specific = context.platform_specific or {}transcript_resume = platform_specific.get("vibey_resume") is True@@ -1013,6 +1018,45 @@ class VibeyAgent(BaseAgent):)return agent+ async def _prepare_prompt(+ self, agent: Agent, request: AgentRequest, router: HubModelRouter,+ blocks: Sequence[RenderedPromptBlock], files: Sequence[Any], environment: Mapping[str, str], *,+ builtin_agent: bool, persist: bool = True, catalog: Optional[dict] = None,+ ) -> PromptState:+ """Read, compare and publish optional prefix state off the loop, once per Turn."""+ entries = await self.store.load(agent.session_id)+ endpoint = router.preflight.endpoint++ def prepare():+ candidate = candidate_prefix(+ agent.system, agent.tools, endpoint, blocks, files, builtin_agent=builtin_agent,+ rg=shutil.which("rg", path=environment.get("PATH", "")) is not None, catalog=catalog,+ )+ previous = self.prompt_snapshots.load(agent.session_id)+ prefix = previous.snapshot.prefix if previous is not None else candidate+ probe = ModelRequest(endpoint=endpoint, system=prefix.system, tools=prefix.tools, messages=(), max_tokens=1)+ now = agent.context.clock()+ decision = decide(+ previous, candidate, now=now,+ route=route_identity(endpoint, agent=request.vibe_agent_id or "", model=request.subagent_model or request.vibe_agent_model or "",+ effort=request.subagent_reasoning_effort or request.vibe_agent_reasoning_effort or ""),+ checkpoint_seq=max((entry.context_seq for entry in entries if entry.kind == "compaction"), default=0),+ cold=cache_cold(probe, entries, now=now),+ )+ if persist and decision.state != previous:+ if not self.prompt_snapshots.save(agent.session_id, decision.state, snapshot=decision.reason is not None):+ # Without a durable first-seen time, retaining a warm prefix could+ # reset a tier-2 deadline forever. Lose the optimization, not freshness.+ return decide(None, candidate, now=now, route=decision.state.snapshot.route,+ checkpoint_seq=decision.state.observed_checkpoint_seq, cold=False).state+ return decision.state++ state = await to_thread_joined(prepare)+ agent.system = state.snapshot.prefix.system+ agent.set_tools(frozen_tools(state.snapshot.prefix.tools, agent.tools))+ router.prefix_declarations = (route_identity(endpoint), state.snapshot.prefix.hosted)+ return state+async def preview_request(self, session_id: str, request: AgentRequest, *, context_seq: int | None = None,) -> RequestPreview:@@ -1031,13 +1075,15 @@ class VibeyAgent(BaseAgent):sections, _ = await self._avibe_sections(request, cwd)builtin_agent = await asyncio.to_thread(self._is_builtin_agent, request)environment = await asyncio.to_thread(self._turn_environment, request, cwd)- instructions = await asyncio.to_thread(_project_instructions, cwd)+ files = await asyncio.to_thread(load_instruction_files, cwd, paths.get_global_instructions_path(), include_empty=True)agent = self._build_agent(- request, session_id, router, cwd, sections, environment,- builtin_agent=builtin_agent, instructions=instructions,+ request, session_id, router, cwd, join_prompt_blocks(sections), environment,+ builtin_agent=builtin_agent, instructions=project_context(files),)+ await self._prepare_prompt(agent, request, router, sections, files, environment,+ builtin_agent=builtin_agent, persist=False)return await agent.dry_tick(- selected=selected, context_seq=context_seq, gateway=True, media_loader=self.media,+ selected=router.prompt_route(selected), context_seq=context_seq, gateway=True, media_loader=self.media,)async def _on_event(self, run: _Run, event: AgentEvent) -> None:@@ -1609,21 +1655,21 @@ class VibeyAgent(BaseAgent):body = strip_silent_blocks(value)return self._with_images(body, images) if final else body- async def _avibe_sections(self, request: AgentRequest, cwd: str) -> tuple[str, Optional[dict]]:+ async def _avibe_sections(self, request: AgentRequest, cwd: str) -> tuple[list[RenderedPromptBlock], Optional[dict]]:"""Avibe's injected prompt sections and the skill catalog they offered.Built off the event loop as the other backends build them: skill resolutionscans the ordinary static Skill directories."""from core.managed_skills import managed_skill_project_base- from core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt+ from core.system_prompt_injection import build_system_prompt_blocks, get_enabled_agents_for_promptcontext = request.contextskill_catalog_sink: list[dict] = []- def build() -> str:+ def build() -> list[RenderedPromptBlock]:# Every lookup runs here, off the loop: the enabled-Agent list reads SQLite.- return build_system_prompt_injection(+ return build_system_prompt_blocks(agent_instructions=request.vibe_agent_system_prompt or "",backend=BACKEND,include_quick_replies=getattr(self.config, "reply_enhancements", True)@@ -1686,10 +1732,24 @@ class VibeyAgent(BaseAgent):prepend_managed_tools_to_path(environment, base_env=environment, working_dir=cwd or None)return environment+ def _record_instruction_write(self, session_id: str, path: str, revision: str) -> None:+ """Only the instruction chain can affect this prefix; never accumulate unrelated file history."""+ runtime = self._runtimes.get(session_id)+ cwd = runtime.run.cwd if runtime is not None and runtime.run is not None else ""+ target = Path(path)+ directory = Path(cwd).absolute() if cwd else None+ if target == paths.get_global_instructions_path() or (+ directory is not None and target.parent in (directory, *directory.parents)+ ):+ self.prompt_snapshots.record_write(session_id, path, revision)+def _environment(self, session_id: str) -> dict[str, EnvironmentValue]:runtime = self._runtimes.get(session_id)cwd = ((runtime.run.cwd if runtime.run is not None else "") or runtime.cwd) if runtime is not None else ""- return current_environment(cwd, self._watch_lines(session_id), shell=self._tools().shell)+ fields = {"session": session_id, **current_environment(cwd, self._watch_lines(session_id), shell=self._tools().shell)}+ if runtime is not None and runtime.run is not None and runtime.run.instructions_notice is not None:+ fields["instructions"] = runtime.run.instructions_notice+ return fieldsdef _watch_lines(self, session_id: str) -> list[str]:service = getattr(self.controller, "watch_service", None)diff --git a/modules/agents/vibey/instructions.py b/modules/agents/vibey/instructions.pyindex 08166e81d..b806ef3e4 100644--- a/modules/agents/vibey/instructions.py+++ b/modules/agents/vibey/instructions.py@@ -11,6 +11,7 @@ files left out, unreadable files skipped silently, and a precedence line.from __future__ import annotations+import hashlibimport osfrom dataclasses import dataclassfrom pathlib import Path@@ -51,6 +52,8 @@ class InstructionFile:is_global: bool = False#: The file's size in bytes, without a byte-order mark; None means the size of ``content``.size: Optional[int] = None+ #: Exact bytes when the bounded read got the whole file; used only for proven self-write attribution.+ source_revision: Optional[str] = None@propertydef byte_size(self) -> int:@@ -62,7 +65,7 @@ _BOM = b"\xef\xbb\xbf"_GIT_LINE = 8192-def _read(path: str) -> Optional[tuple[str, int]]:+def _read(path: str) -> Optional[tuple[str, int, Optional[str]]]:"""A candidate's text and size, or None when it is not a readable file. Symlinks are followed.Reads no more than the section can hold (plus a character's worth, so a cut still falls on a whole one): every@@ -76,11 +79,12 @@ def _read(path: str) -> Optional[tuple[str, int]]:data = handle.read(len(_BOM) + LIMIT + 4)except OSError:return None+ source_revision = hashlib.sha256(data).hexdigest() if len(data) == size else Noneif data.startswith(_BOM):data, size = data[len(_BOM) :], size - len(_BOM)text = data[: LIMIT + 4].decode("utf-8", "replace")# Read whole, its size is the text's: each undecodable byte became a three-byte replacement character.- return text, (len(text.encode("utf-8")) if len(data) >= size else size)+ return text, (len(text.encode("utf-8")) if len(data) >= size else size), source_revisiondef _from_dir(directory: str) -> Optional[InstructionFile]:@@ -88,7 +92,7 @@ def _from_dir(directory: str) -> Optional[InstructionFile]:path = os.path.join(directory, name)read = _read(path)if read is not None:- return InstructionFile(path, read[0], size=read[1])+ return InstructionFile(path, read[0], size=read[1], source_revision=read[2])return None@@ -141,7 +145,7 @@ def _shadowed(cwd: str) -> Optional[tuple[str, str]]:return (main_root, os.path.basename(own.path)) if own is not None else None-def load_instruction_files(cwd: str, global_path: Path) -> list[InstructionFile]:+def load_instruction_files(cwd: str, global_path: Path, *, include_empty: bool = False) -> list[InstructionFile]:"""The global file, then each directory's from the filesystem root down to ``cwd``.A file is loaded once per real path: as the global file, or else at the directory nearest ``cwd`` that reaches it.@@ -152,8 +156,8 @@ def load_instruction_files(cwd: str, global_path: Path) -> list[InstructionFile]read = _read(str(global_path))if read is not None:seen.add(os.path.realpath(global_path))- if read[0].strip():- files.append(InstructionFile(str(global_path), read[0], is_global=True, size=read[1]))+ if read[0].strip() or include_empty:+ files.append(InstructionFile(str(global_path), read[0], is_global=True, size=read[1], source_revision=read[2]))if not cwd:return filesdirectory = os.path.abspath(cwd)@@ -165,7 +169,7 @@ def load_instruction_files(cwd: str, global_path: Path) -> list[InstructionFile]at_shadow = found is not None and (os.path.realpath(directory), os.path.basename(found.path)) == shadowedif found is not None and not at_shadow and real not in seen:seen.add(real)- if found.content.strip():+ if found.content.strip() or include_empty:chain.insert(0, found)parent = os.path.dirname(directory)if parent == directory:@@ -203,12 +207,13 @@ def _not_loaded(files: Sequence[InstructionFile]) -> str:return "\n\n" + NOT_LOADED.format(files="; ".join([*named, MORE.format(count=rest)] if rest else named))-def project_context(files: Sequence[InstructionFile]) -> str:+def project_context(files: Sequence[InstructionFile], *, components: dict[str, str] | None = None) -> str:"""The ``<project_context>`` section, at most ``LIMIT`` bytes, all of it counted; with no file, only ``SUBTREE``.The room goes first to the global file, then to the files from the cwd upward, so the most specific one is the lastcut. A file that gets no room is named in the closing notice. The section keeps the files' order either way."""+ files = [file for file in files if file.content.strip()]if not files:return f"<project_context>\n{SUBTREE}\n</project_context>"opening, closing = f"<project_context>\n{HEADER}\n{PRECEDENCE}\n{SUBTREE}", "\n</project_context>"@@ -231,5 +236,8 @@ def project_context(files: Sequence[InstructionFile]) -> str:blocks[index] = start + text + endleft -= _bytes(blocks[index])omitted = [file for index, file in enumerate(files) if index not in blocks]+ if components is not None:+ components.update({file.path: blocks.get(index, f"{escape(file.path)} ({file.byte_size} bytes)")+ for index, file in enumerate(files)})body = "".join(blocks[index] for index in sorted(blocks))return opening + body + (_not_loaded(omitted) if omitted else "") + closingdiff --git a/modules/agents/vibey/models.py b/modules/agents/vibey/models.pyindex e79f4e30f..22a3290f9 100644--- a/modules/agents/vibey/models.py+++ b/modules/agents/vibey/models.py@@ -19,6 +19,7 @@ is ``native``, and pins that request to the hop's Sourcefrom __future__ import annotationsimport logging+from dataclasses import replaceimport refrom typing import Any, Awaitable, Callable, Mapping, Optional@@ -232,6 +233,7 @@ class HubModelRouter:#: The hop the Turn runs on now, its latest resolution. The gateway answers the Turn's requests only on that#: hop's credential (C-6 item 3), so the Turn's hosted calls go out on it too.self.current = first+ self.prefix_declarations: tuple[tuple[str, ...], Mapping[str, Any]] | None = Noneself._adapters: dict[str, ProviderAdapter] = {}async def resolve(self) -> ModelSelection:@@ -239,9 +241,20 @@ class HubModelRouter:selection, self._first = self._first, Noneelse:selection = await self._resolve()+ selection = self.prompt_route(selection)self.current = selectionreturn selection+ def prompt_route(self, selection: ModelSelection) -> ModelSelection:+ """Only the saved route's declarations are cached; fallbacks and live refusals remain authoritative."""+ from modules.agents.vibey.prompt_snapshot import frozen_hosted, route_identity++ if self.prefix_declarations is not None:+ route, hosted = self.prefix_declarations+ if route_identity(selection.endpoint) == route:+ selection = replace(selection, endpoint=replace(selection.endpoint, hosted_tools=frozen_hosted(selection.endpoint, hosted)))+ return selection+def provider_for(self, protocol: ProtocolName) -> ProviderAdapter:adapter = self._adapters.get(protocol)if adapter is None:diff --git a/modules/agents/vibey/prompt.py b/modules/agents/vibey/prompt.pyindex 662e2165a..c1d2cca6e 100644--- a/modules/agents/vibey/prompt.py+++ b/modules/agents/vibey/prompt.py@@ -61,6 +61,11 @@ TOOL_GUIDELINES: dict[str, tuple[str, ...]] = {"write": ("Use write only for new files or complete rewrites.",),}TOOL_ORDER = ("read", "bash", "powershell", "edit", "write")+INSTRUCTIONS_RULE = (+ "The environment's session field is this Session's authoritative id; its instructions field lists parts that "+ "changed since the cached instructions were loaded: read the current file, `vibe skill list`, `vibe mcp --list`, "+ "or `vibe agent list` before relying on a listed part."+)FINAL_REPLY_RULE = "Only your final reply is reliably shown to the user; put anything the user must see in it"#: Avibe's: the loop runs a response's neighbouring read and bash calls at the same time (C-3 loop-control.md section 2).CONCURRENT_CALLS_RULE = (@@ -101,7 +106,7 @@ def coding_prompt(tool_names: Iterable[str], *, builtin_agent: bool, rg: bool) -rules.extend(TOOL_GUIDELINES.get(name, ()))if names:rules.append(CONCURRENT_CALLS_RULE)- rules += ["Be concise in your responses", "Show file paths clearly when working with files", FINAL_REPLY_RULE]+ rules += ["Be concise in your responses", "Show file paths clearly when working with files", INSTRUCTIONS_RULE, FINAL_REPLY_RULE]return "\n\n".join((preamble(builtin_agent),@@ -120,7 +125,7 @@ def system_prompt(# --- environment block ----------------------------------------------------------ENVIRONMENT_FIELDS = ("cwd", "os", "shell", "watches")+ENVIRONMENT_FIELDS = ("session", "cwd", "os", "shell", "watches", "instructions")_BLOCK = re.compile(r"\A<environment>\n(?P<body>(?:[a-z]+: [^\n]*\n)*)</environment>\Z")@@ -170,7 +175,7 @@ def displayed_environment(fields: Mapping[str, EnvironmentValue]) -> dict[str, sdef _shown(name: str, value: EnvironmentValue) -> str:if name != "watches":- return escape(str(value)) if name == "cwd" else display(str(value))+ return escape(str(value)) if name in ("cwd", "instructions") else display(str(value))# Bounded on every input, and so in every checkpoint: the first ones, then how many more (tools.md section 8).listed = [display(line) for line in value[:_WATCHES_LISTED]]if len(value) > _WATCHES_LISTED:diff --git a/modules/agents/vibey/prompt_snapshot.py b/modules/agents/vibey/prompt_snapshot.pynew file mode 100644index 000000000..850671f46--- /dev/null+++ b/modules/agents/vibey/prompt_snapshot.py@@ -0,0 +1,461 @@+"""Vibey's durable cached prefix and Turn-start freshness policy.++This optional state is deliberately outside the transcript. All disk operations+are synchronous and called on the adapter's worker threads (or the fork service's+existing synchronous path). Corruption or write failure only loses the optimization.+"""++from __future__ import annotations++import hashlib+import json+import logging+import math+import os+import tempfile+from dataclasses import asdict, dataclass, field, replace+from pathlib import Path+from typing import Any, Mapping, Sequence++from core.agent_core.ai.provider import HostedToolRoute, ModelEndpoint+from core.agent_core.messages import TextBlock+from core.agent_core.tools.base import Tool, ToolContext, ToolResult, ToolSpec++logger = logging.getLogger(__name__)+DEADLINE_S = 30 * 60+VERSION = 1++# IDs are the extension point for future modules (including Bots). Unknown = 2.+# Presence changes of optional static modules describe configuration, not upgrades.+COMPONENT_TIERS = {+ "agent-identity": 1,+ "coding-rules": 1,+ "instruction-contract": 1,+ "prefix-contract": 1,+ "local-tools": 1,+ "tool-environment": 3,+ "base-capabilities-intro": 1,+ "agent-working-principles": 1,+ "base-capabilities-body": 1,+ "show-pages-prompt": 1,+ "quick-replies-prompt": 1,+ "vault-routing-prompt": 1,+ "harness-routing-prompt": 1,+ "project-context-prompt": 1,+ "skills-prompt": 1,+ "skills-manual-prompt": 1,+ "skills-catalog-heading": 1,+ "skills-pagination-prompt": 1,+ "mcp-capabilities-prompt": 1,+ "mcp-pagination-prompt": 1,+ "session-title-prompt": 1,+ "agent-instructions": 1,+ "harness-agents-prompt": 2,+ "skills-catalog": 2,+ "skills-more-notice": 2,+ "mcp-catalog": 2,+ "mcp-more-notice": 2,+ "hosted-tools": 2,+}+OPTIONAL_MODULES = frozenset({+ "quick-replies-prompt", "session-title-prompt", "vault-routing-prompt",+ "skills-prompt", "skills-manual-prompt", "skills-catalog-heading", "skills-pagination-prompt",+ "mcp-capabilities-prompt", "mcp-pagination-prompt",+})+CATALOG_NAMES = {+ "harness-agents-prompt": "agents",+ "skills-catalog": "skills",+ "skills-more-notice": "skills",+ "mcp-catalog": "mcp",+ "mcp-more-notice": "mcp",+ "hosted-tools": "hosted-tools",+}+++def revision(value: Any) -> str:+ return hashlib.sha256(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode()).hexdigest()+++@dataclass(frozen=True)+class Component:+ id: str+ content: str+ # Instruction path identity stays separate from the human-readable notice name.+ path: str | None = None+ global_file: bool = False+ source_revision: str | None = None+ # The authored template, distinguished from its live catalog values.+ contract_revision: str | None = None++ @property+ def revision(self) -> str:+ return revision(self.content)++ @property+ def name(self) -> str:+ return self.path or CATALOG_NAMES.get(self.id, self.id)+++@dataclass(frozen=True)+class Prefix:+ system: str+ components: tuple[Component, ...]+ tools: tuple[ToolSpec, ...]+ # Only rendered declaration facts, never auth, URLs, or credential-bearing headers.+ hosted: Mapping[str, Any] = field(default_factory=dict)+ # Observation of the catalog actually offered, not the deferred candidate.+ catalog: Mapping[str, Any] | None = None++ @property+ def revision(self) -> str:+ return revision([self.system, [asdict(tool) for tool in self.tools], self.hosted])+++@dataclass(frozen=True)+class Snapshot:+ prefix: Prefix+ applied_at: float+ route: tuple[str, ...]+ checkpoint_seq: int+++@dataclass(frozen=True)+class Pending:+ component: str+ name: str+ revision: str+ tier: int+ pending_since: float+ own: bool = False+++@dataclass(frozen=True)+class State:+ snapshot: Snapshot+ pending: tuple[Pending, ...] = ()+ written: Mapping[str, str] = field(default_factory=dict)+ # A checkpoint is a one-Turn opportunity, even when the prefix stayed identical.+ observed_checkpoint_seq: int = 0++ @property+ def notice(self) -> str:+ names: dict[str, list[str]] = {}+ for item in self.pending:+ if not item.own:+ names.setdefault(item.name, []).append(item.revision)+ if not names:+ return "current"+ return "pending " + "; ".join(+ f"{name}@{(revs[0] if len(revs) == 1 else revision(revs))[:6]}"+ for name, revs in sorted(names.items())+ )+++@dataclass(frozen=True)+class Decision:+ state: State+ reason: str | None+ # Changes first observed or revised this Turn; future metrics consume these facts.+ detected: tuple[Pending, ...] = ()+ applied: tuple[Pending, ...] = ()+++def component_tier(before: Component | None, after: Component | None) -> int:+ component = after or before+ if component.path:+ return COMPONENT_TIERS.get(component.id, 1 if component.global_file else 2)+ if (before is not None and after is not None and component.id in COMPONENT_TIERS+ and before.contract_revision != after.contract_revision):+ return 1+ if component.id in OPTIONAL_MODULES and (before is None or after is None):+ return 2+ return COMPONENT_TIERS.get(component.id, 2)+++def decide(+ previous: State | None, candidate: Prefix, *, now: float, route: tuple[str, ...],+ checkpoint_seq: int, cold: bool,+) -> Decision:+ """Replace the whole prefix, never individual components; continuous edits keep their deadline."""+ if previous is None:+ return Decision(State(Snapshot(candidate, now, route, checkpoint_seq), observed_checkpoint_seq=checkpoint_seq), "session_start")+ if previous.snapshot.route == route and previous.snapshot.prefix.revision == candidate.revision:+ return Decision(replace(previous, pending=(), observed_checkpoint_seq=checkpoint_seq), None)+ old = {item.id: item for item in previous.snapshot.prefix.components}+ fresh = {item.id: item for item in candidate.components}+ prior = {item.component: item for item in previous.pending}+ pending = []+ for key in dict.fromkeys([*old, *fresh]):+ before, after = old.get(key), fresh.get(key)+ if before is not None and after is not None and before.content == after.content:+ continue+ component = after or before+ rev = after.revision if after is not None else revision(None)+ own = bool(after and after.path and after.source_revision+ and previous.written.get(after.path) == after.source_revision)+ tier = component_tier(before, after)+ earlier = prior.get(key)+ # Authorship controls the notice only; it cannot restart a component's deadline.+ since = earlier.pending_since if earlier else now+ pending.append(Pending(key, component.name, rev, tier, since, own))+ shared = old.keys() & fresh.keys()+ if [key for key in old if key in shared] != [key for key in fresh if key in shared]:+ pending.append(Pending("prefix-order", "prompt-order", revision(list(fresh)), 1, now))+ pending = tuple(pending)+ detected = tuple(item for item in pending if prior.get(item.component) != item)+ reason = None+ if previous.snapshot.route != route or native_revoked(previous.snapshot.prefix.hosted, candidate.hosted):+ reason = "route_change"+ elif any(item.tier == 1 for item in pending):+ reason = "tier1"+ elif pending and cold:+ reason = "cold"+ elif pending and checkpoint_seq > previous.observed_checkpoint_seq:+ reason = "checkpoint"+ elif any(item.tier == 2 and now - item.pending_since >= DEADLINE_S for item in pending):+ reason = "deadline"+ if reason is not None:+ return Decision(State(Snapshot(candidate, now, route, checkpoint_seq), observed_checkpoint_seq=checkpoint_seq), reason, detected, pending)+ return Decision(replace(previous, pending=pending, observed_checkpoint_seq=checkpoint_seq), None, detected)+++def route_identity(endpoint: ModelEndpoint, *, agent: str = "", model: str = "", effort: str = "") -> tuple[str, ...]:+ return (endpoint.provider, endpoint.protocol, endpoint.model_id, endpoint.source_id or "",+ endpoint.source_identity or "", agent, model, effort)+++def _number(value: Any) -> float:+ if type(value) not in (int, float) or not math.isfinite(value) or value < 0:+ raise ValueError("invalid prompt timestamp")+ return float(value)+++def _text(value: Any) -> str:+ if not isinstance(value, str):+ raise ValueError("invalid prompt text")+ return value+++def _strings(value: Any) -> dict[str, str]:+ if not isinstance(value, dict):+ raise ValueError("invalid prompt mapping")+ return {_text(key): _text(item) for key, item in value.items()}+++def candidate_prefix(+ system: str, tools: Sequence[Tool], endpoint: ModelEndpoint, blocks: Sequence[Any],+ files: Sequence[Any], *, builtin_agent: bool, rg: bool, catalog: Mapping[str, Any] | None = None,+) -> Prefix:+ from core.prompt_registry import prompt_module+ from modules.agents.vibey import instructions+ from modules.agents.vibey.prompt import coding_prompt, preamble, system_prompt++ rendered: dict[str, str] = {}+ instructions.project_context(files, components=rendered)+ names = [tool.spec.name for tool in tools]+ hosted_names = {*endpoint.hosted_tools, "image_generate"}+ specs = tuple(tool.spec for tool in tools)+ hosted = hosted_declarations(endpoint)+ components = [+ Component("agent-identity", preamble(builtin_agent)),+ Component("coding-rules", coding_prompt(names, builtin_agent=False, rg=False)),+ Component("prefix-contract", system_prompt((), "<modules>", builtin_agent=False, rg=False, project_context="<instructions>")),+ Component("tool-environment", str(rg)),+ Component("instruction-contract", "\n".join((instructions.HEADER, instructions.PRECEDENCE, instructions.SUBTREE,+ instructions.TRUNCATED, instructions.NOT_LOADED,+ str(instructions.LIMIT), str(instructions.OMITTED_ROOM)))),+ Component("local-tools", json.dumps([asdict(tool) for tool in specs if tool.name not in hosted_names])),+ Component("hosted-tools", json.dumps([hosted, [asdict(tool) for tool in specs if tool.name in hosted_names]])),+ *(Component("file:" + file.path, rendered.get(file.path, ""), file.path, file.is_global, file.source_revision) for file in files),+ *(Component(block.module_id, block.text, contract_revision=revision(prompt_module(block.module_id).source())) for block in blocks),+ ]+ return Prefix(system, tuple(components), specs, hosted, catalog)+++def hosted_declarations(endpoint: ModelEndpoint) -> dict[str, Any]:+ return {name: {"mode": tool.mode, "declaration": tool.declaration, "include": list(tool.include)}+ for name, tool in endpoint.hosted_tools.items()}+++def native_revoked(saved: Mapping[str, Any], live: Mapping[str, Any]) -> bool:+ """A cached native tool executes upstream: losing its live route cannot be deferred."""+ return any(raw["mode"] == "native" and live.get(name, {}).get("mode") != "native" for name, raw in saved.items())+++def frozen_hosted(endpoint: ModelEndpoint, saved: Mapping[str, Any]) -> dict[str, HostedToolRoute]:+ """Keep the declared prefix, but never undo a live provider refusal or recovery decision."""+ routes = {}+ for name, raw in saved.items():+ live = endpoint.hosted_tools.get(name)+ if raw["mode"] == "native" and (live is None or live.mode != "native"):+ # A declaration is not an execution grant. This also covers a fresh+ # resolution inside the Turn, where the system snapshot cannot change.+ if live is not None:+ routes[name] = live+ continue+ if live is not None and (live.refused or live.route_switch):+ routes[name] = live+ else:+ routes[name] = HostedToolRoute(+ mode=raw["mode"], declaration=raw["declaration"], include=tuple(raw["include"]),+ replay=live.replay if live is not None else False,+ )+ return routes+++class FrozenTool:+ """A saved declaration with the live executor; the snapshot grants no execution authority."""++ def __init__(self, spec: ToolSpec, tool: Tool | None) -> None:+ self.spec, self._tool = spec, tool+ self.concurrent = getattr(tool, "concurrent", False)++ async def execute(self, arguments: Mapping[str, Any], ctx: ToolContext) -> ToolResult:+ if self._tool is None:+ return ToolResult((TextBlock(f"Tool {self.spec.name} is no longer available; check the current configuration."),), True)+ return await self._tool.execute(arguments, ctx)+++def frozen_tools(saved: Sequence[ToolSpec], live: Sequence[Tool]) -> tuple[Tool, ...]:+ executors = {tool.spec.name: tool for tool in live}+ return tuple(FrozenTool(spec, executors.get(spec.name)) for spec in saved)+++class SnapshotStore:+ def __init__(self, root: Path) -> None:+ self.root = root++ def directory(self, session_id: str) -> Path:+ if not session_id or any(char not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-" for char in session_id):+ raise ValueError("invalid snapshot Session id")+ return self.root / "prompts" / session_id++ def load(self, session_id: str) -> State | None:+ try:+ directory = self.directory(session_id)+ raw = json.loads((directory / "snapshot.json").read_text(encoding="utf-8"))+ waiting = json.loads((directory / "pending.json").read_text(encoding="utf-8"))+ if raw["version"] != VERSION or waiting["version"] != VERSION:+ raise ValueError("unknown prompt state version")+ data = raw["prefix"]+ components = []+ for item in data["components"]:+ component = Component(**item)+ _text(component.id)+ _text(component.content)+ if component.path is not None:+ _text(component.path)+ if component.source_revision is not None:+ _text(component.source_revision)+ if component.contract_revision is not None:+ _text(component.contract_revision)+ if type(component.global_file) is not bool:+ raise ValueError("invalid global instruction flag")+ components.append(component)+ if len({item.id for item in components}) != len(components):+ raise ValueError("duplicate prompt component")+ tools = []+ for item in data["tools"]:+ tool = ToolSpec(**item)+ _text(tool.name)+ _text(tool.description)+ if not isinstance(tool.input_schema, dict):+ raise ValueError("invalid tool schema")+ tools.append(tool)+ if len({item.name for item in tools}) != len(tools):+ raise ValueError("duplicate tool")+ hosted = data["hosted"]+ if not isinstance(hosted, dict):+ raise ValueError("invalid hosted declarations")+ for name, item in hosted.items():+ _text(name)+ if set(item) != {"mode", "declaration", "include"} or not isinstance(item["include"], list):+ raise ValueError("invalid hosted declaration fields")+ HostedToolRoute(mode=item["mode"], replay=False, declaration=item["declaration"], include=tuple(item["include"]))+ catalog = data.get("catalog")+ if catalog is not None and not isinstance(catalog, dict):+ raise ValueError("invalid prompt catalog observation")+ prefix = Prefix(_text(data["system"]), tuple(components), tuple(tools), hosted, catalog)+ if raw["revision"] != prefix.revision or waiting["snapshot_revision"] != prefix.revision:+ raise ValueError("inconsistent prompt state")+ if not isinstance(raw["route"], list):+ raise ValueError("invalid prompt route")+ route = tuple(_text(item) for item in raw["route"])+ seq = raw["checkpoint_seq"]+ observed_seq = waiting["observed_checkpoint_seq"]+ if any(type(value) is not int or value < 0 for value in (seq, observed_seq)):+ raise ValueError("invalid checkpoint seq")+ pending = []+ for item in waiting["components"]:+ change = Pending(**item)+ for value in (change.component, change.name, change.revision):+ _text(value)+ if type(change.tier) is not int or change.tier not in (1, 2, 3) or type(change.own) is not bool:+ raise ValueError("invalid prompt tier")+ _number(change.pending_since)+ pending.append(change)+ return State(Snapshot(prefix, _number(raw["applied_at"]), route, seq), tuple(pending),+ _strings(waiting["written"]), observed_seq)+ except (OSError, ValueError, TypeError, KeyError, AttributeError, RecursionError, OverflowError):+ return None++ def save(self, session_id: str, state: State, *, snapshot: bool) -> bool:+ try:+ directory = self.directory(session_id)+ if snapshot:+ self._write(directory / "snapshot.json", {+ "version": VERSION, **asdict(state.snapshot), "revision": state.snapshot.prefix.revision,+ })+ self._write(directory / "pending.json", {+ "version": VERSION, "snapshot_revision": state.snapshot.prefix.revision,+ "components": [asdict(item) for item in state.pending], "written": dict(state.written),+ "observed_checkpoint_seq": state.observed_checkpoint_seq,+ })+ return True+ except (OSError, ValueError, TypeError, RecursionError, OverflowError):+ logger.warning("Could not persist optional prompt state for Session %s", session_id)+ return False++ def record_write(self, session_id: str, path: str, revision: str) -> None:+ from modules.agents.vibey.instructions import CANDIDATES++ if Path(path).name not in CANDIDATES:+ return+ state = self.load(session_id)+ if state is not None:+ written = {**state.written, path: revision}+ self.save(session_id, replace(state, written=written), snapshot=False)++ def inherit(self, source: str, target: str) -> None:+ """Copy at reservation, not first use (the source may advance before then)."""+ state = self.load(source)+ if state is None:+ return+ try:+ # Read once more as bytes to preserve the source file exactly; atomic replacement+ # plus the revision link makes a concurrent source update degrade to fresh.+ data = (self.directory(source) / "snapshot.json").read_bytes()+ self._write_bytes(self.directory(target) / "snapshot.json", data)+ self.save(target, replace(state, written={}), snapshot=False)+ except (OSError, ValueError):+ logger.warning("Could not inherit optional prompt snapshot for Session %s", target)++ @staticmethod+ def _write(path: Path, data: Any) -> None:+ SnapshotStore._write_bytes(path, json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode())++ @staticmethod+ def _write_bytes(path: Path, data: bytes) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ descriptor, name = tempfile.mkstemp(prefix=".prompt-", dir=path.parent)+ try:+ with os.fdopen(descriptor, "wb") as handle:+ handle.write(data)+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(name, path)+ finally:+ try:+ os.unlink(name)+ except FileNotFoundError:+ passdiff --git a/modules/agents/vibey/store.py b/modules/agents/vibey/store.pyindex e03c54824..babf292b2 100644--- a/modules/agents/vibey/store.py+++ b/modules/agents/vibey/store.py@@ -32,6 +32,7 @@ from sqlalchemy.engine import Enginefrom core.agent_core.harness.projection import context_viewfrom core.agent_core.harness.store import ContextEntryfrom core.agent_core.messages import AssistantMessage, HostedImage, ToolResultMessage, UserMessage+from core.agent_core.tools.paths import to_thread_joinedfrom modules.agents.vibey.prompt import (EnvironmentValue,displayed_environment,@@ -64,6 +65,7 @@ class AdapterTranscriptStore:environment: EnvironmentSource,on_response: ResponseObserver,response_metadata: Optional[ResponseMetadata] = None,+ file_write: Optional[Callable[[str, str, str], None]] = None,input_row_timeout_s: float = INPUT_ROW_TIMEOUT_S,) -> None:self._store = store@@ -71,6 +73,7 @@ class AdapterTranscriptStore:self._environment = environmentself._on_response = on_responseself._response_metadata = response_metadata+ self._file_write = file_writeself._input_row_timeout_s = input_row_timeout_s# Per Session, the environment the projected context shows; evicted by ``forget`` when# the adapter retires the Session's runtime, and when a checkpoint commits.@@ -137,7 +140,7 @@ class AdapterTranscriptStore:if not any(entry.session_id == session_id for entry in entries):# No row of its own yet: a fork's first own input carries the notice, an empty prefix included.message = await asyncio.to_thread(self._with_fork_notice, session_id, message)- current = dict(self._environment(session_id))+ current = self._environment(session_id)rendered = with_environment(message, environment_delta(previous, current))entry = await self._store.consume_input(session_id, message_id, rendered)self._env_state[session_id] = {**previous, **displayed_environment(current)}@@ -172,6 +175,10 @@ class AdapterTranscriptStore:async def append_tool_result(self, session_id: str, message: ToolResultMessage, *, details: Mapping[str, Any]) -> ContextEntry:+ receipt = details.get("file_write")+ if (not message.is_error and self._file_write is not None and isinstance(receipt, Mapping)+ and isinstance(receipt.get("path"), str) and isinstance(receipt.get("revision"), str)):+ await to_thread_joined(self._file_write, session_id, receipt["path"], receipt["revision"])return await self._store.append_tool_result(session_id, message, details=details, agent_name=self._agents.get(session_id),turn_id=self._turns.get(session_id),diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.pyindex 3fdec4db6..57afc773a 100644--- a/tests/agent_core/tools/test_write_edit.py+++ b/tests/agent_core/tools/test_write_edit.py@@ -911,7 +911,7 @@ async def test_the_display_diff_and_patch_are_pis(tmp_path, make_ctx, original,result = await _edit(make_ctx, "f.txt", edit)assert not result.is_error, result_text(result)- assert result.details == {+ assert {key: result.details[key] for key in ("diff", "patch", "first_changed_line")} == {"diff": diff,"patch": "--- f.txt\n+++ f.txt\n" + patch,"first_changed_line": first_changed_line,@@ -1096,7 +1096,7 @@ async def test_the_display_diff_never_splits_a_result_with_too_many_lines(tmp_pafinally:tracemalloc.stop()- assert result.details == {"diff_skipped": True}+ assert result.details["diff_skipped"] is Trueassert peak < 8 * 1024 * 1024@@ -1111,7 +1111,7 @@ async def test_a_large_changed_middle_skips_the_display_diff(tmp_path, make_ctx))assert not result.is_error, result_text(result)- assert result.details == {"diff_skipped": True}+ assert result.details["diff_skipped"] is Trueasync def test_a_planned_result_over_the_limit_is_refused_and_its_diff_skipped(tmp_path, make_ctx, monkeypatch):@@ -1122,7 +1122,7 @@ async def test_a_planned_result_over_the_limit_is_refused_and_its_diff_skipped(tgrown = await _edit(make_ctx, "small.txt", {"oldText": "seed", "newText": "x" * 600})too_big = await _edit(make_ctx, "small.txt", {"oldText": "x" * 600, "newText": "y" * 2000})- assert grown.details == {"diff_skipped": True}+ assert grown.details["diff_skipped"] is Trueassert too_big.is_errorassert result_text(too_big) == ("File small.txt would be over the 1000B edit limit after this edit. "@@ -1149,7 +1149,7 @@ async def test_files_over_the_edit_limit_are_refused_and_large_diffs_skipped(tmpedited = await _edit(make_ctx, "big.log", {"oldText": "line", "newText": "x", "replaceAll": True})assert not edited.is_error, result_text(edited)- assert edited.details == {"diff_skipped": True}+ assert edited.details["diff_skipped"] is True@pytest.mark.parametrize("ending", ["\r\n", "\r"])diff --git a/tests/test_session_request_preview.py b/tests/test_session_request_preview.pyindex 513706b7a..6510db62d 100644--- a/tests/test_session_request_preview.py+++ b/tests/test_session_request_preview.py@@ -224,8 +224,8 @@ async def test_preview_uses_stored_project_base_over_current_scope(preview_host,request = request_preview.build_preview_request(host.controller, context)assert request.context.platform_specific["agent_run_target"]["project_base"] == str(stored_project)sections, _ = await host.harness.agent._avibe_sections(request, cwd=str(cwd))- assert "stored-bound-skill" in sections- assert "scope-skill" not in sections+ assert any("stored-bound-skill" in block.text for block in sections)+ assert all("scope-skill" not in block.text for block in sections)remove = deny_effects(host, monkeypatch)try:response = await invoke(host)diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex 17bd216cd..e2db3b9f1 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -529,7 +529,7 @@ async def test_a_turn_commits_its_context_once_and_shows_the_reply_once(rows = await harness.context_rows()assert [entry.kind for entry in rows] == ["input", "response", "tool_result", "response"]environment, typed = rows[0].message.content- assert environment.text.startswith("<environment>\ncwd: ") and typed == TextBlock(text="看一下目录")+ assert environment.text.startswith(f"<environment>\nsession: {session}\ncwd: ") and typed == TextBlock(text="看一下目录")# The shell is the one the commands run in, the job host's, not the user's login shell.assert f"\nshell: {harness.suite.shell}\n" in environment.text# The steer identity existed when the Turn owner bound the native start.@@ -599,7 +599,7 @@ async def test_a_setup_failure_after_the_route_resolved_fails_the_turn_and_not_tdef broken(**_kwargs):raise RuntimeError("the skills directory could not be read")- monkeypatch.setattr(injection, "build_system_prompt_injection", broken)+ monkeypatch.setattr(injection, "build_system_prompt_blocks", broken)harness = _Harness(engine, tmp_path, "telegram", [[Done(assistant("unreachable"))]])harness.controller.model_hub_runtime.record_native_failure = record_native_failure@@ -2703,8 +2703,8 @@ async def test_another_agent_on_the_backend_is_not_told_it_is_vibey(engine, sessasync def test_the_instruction_files_enter_between_the_head_and_avibes_sections_and_are_read_every_turn(engine, session, tmp_path, published, monkeypatch) -> None:- # C-7 tools.md section 9: the global file in the Avibe home, then the files from the root down to the Session's- # cwd. They are read every Turn, and the system prompt changes only when one of them does, so the cache holds.+ # C-7: global edits refresh immediately; project edits are read every Turn but+ # stay pending while the conversation cache is warm.from config import pathsfrom modules.agents.vibey.prompt import FINAL_REPLY_RULE@@ -2745,7 +2745,194 @@ async def test_the_instruction_files_enter_between_the_head_and_avibes_sections_assert without[head_end:].startswith(empty)assert first == f"{without[:head_end]}\n\n{section}{without[head_end + len(empty):]}"assert again == first- assert edited != first and "Never push to master." in edited+ assert edited == first and "Never push to master." not in edited+ rows = await harness.context_rows()+ last_input = [row.message for row in rows if row.kind == "input"][-1]+ assert f"instructions: pending {tmp_path / 'AGENTS.md'}@" in last_input.content[0].text++[email protected]("own_content", ["My own revision.", "", " \n", "\ufeff"])+async def test_snapshot_notice_tracks_exact_own_and_external_revisions_across_restart(+ engine, session, tmp_path, published, own_content,+) -> None:+ # The tool receipt proves the exact own revision; rereading after a write would+ # misattribute an intervening outside edit. Prior environment tests had no pending field.+ from config import paths+ from core.agent_core.tools.write import WriteTool+ from modules.agents.vibey.prompt import parse_environment++ file = tmp_path / "AGENTS.md"+ file.write_text("Original instructions.")+ write = ToolCallBlock(id="self_write", name="write", arguments={"path": "AGENTS.md", "content": own_content})+ harness = _Harness(engine, tmp_path, "avibe", [+ [Done(assistant("updating", calls=(write,)))], [Done(assistant("done"))],+ *[[Done(assistant("next"))] for _ in range(6)],+ ], tools=[WriteTool()])+ await harness.agent.handle_message(harness.request("write it"))+ first = harness.provider.requests[0].system+ harness.new_agent()+ await harness.agent.handle_message(harness.request("own change"))+ file.write_text("Someone else's revision.")+ await harness.agent.handle_message(harness.request("outside change"))+ await harness.agent.handle_message(harness.request("still pending"))+ file.write_text("Someone else's second revision.")+ harness.new_agent()+ await harness.agent.handle_message(harness.request("outside changed again"))+ global_file = paths.get_global_instructions_path()+ global_file.parent.mkdir(parents=True, exist_ok=True)+ global_file.write_text("A deliberate global rule.")+ await harness.agent.handle_message(harness.request("apply global rule"))+ await harness.agent.handle_message(harness.request("already current"))++ inputs = [row.message for row in await harness.context_rows() if row.kind == "input"]+ deltas = [parse_environment(message.content[0].text) or {} for message in inputs]+ assert deltas[0]["session"] == session and deltas[0]["instructions"] == "current"+ assert "instructions" not in deltas[1] # exact own edit is already in the conversation+ assert deltas[2]["instructions"].startswith(f"pending {file}@")+ assert "instructions" not in deltas[3]+ assert deltas[4]["instructions"] != deltas[2]["instructions"]+ assert deltas[5]["instructions"] == "current" and "instructions" not in deltas[6]+ assert all(item.system == first for item in harness.provider.requests[:6])+ assert "A deliberate global rule." in harness.provider.requests[6].system+ assert "Someone else's second revision." in harness.provider.requests[6].system+++async def test_skill_observation_describes_the_applied_catalog_not_a_deferred_candidate(+ engine, session, tmp_path, published,+) -> None:+ # The existing acceptance hook used the just-rendered candidate, which would+ # report discovery of skills the frozen prompt had not actually offered.+ def add_skill(name):+ path = tmp_path / ".agents" / "skills" / name / "SKILL.md"+ path.parent.mkdir(parents=True)+ path.write_text(f"---\nname: {name}\ndescription: {name} description\n---\nbody\n")++ add_skill("first-skill")+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))] for _ in range(2)])+ observed = []+ harness.controller.skill_observability = SimpleNamespace(enqueue=lambda event, **kwargs: observed.append(event))+ await harness.agent.handle_message(harness.request("first"))+ add_skill("deferred-skill")+ harness.new_agent()+ await harness.agent.handle_message(harness.request("second"))+ assert len(observed) == 2+ assert observed[1]["content"] == observed[0]["content"]+ assert "deferred-skill" not in harness.provider.requests[1].system+ assert any(entry["skill_name"] == "first-skill" for entry in observed[1]["content"]["entries"])+++async def test_pending_write_failure_uses_fresh_candidate_instead_of_resetting_its_deadline(+ engine, session, tmp_path, published, monkeypatch,+) -> None:+ # A read-only pending file used to reset first-seen on every Turn, keeping+ # a tier-2 change stale indefinitely. The adapter must lose only caching.+ file = tmp_path / "AGENTS.md"+ file.write_text("old")+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))] for _ in range(3)])+ await harness.agent.handle_message(harness.request("initial"))+ file.write_text("new instructions")++ def denied(*args):+ raise PermissionError("read only")++ monkeypatch.setattr(type(harness.agent.prompt_snapshots), "_write_bytes", denied)+ await harness.agent.handle_message(harness.request("changed"))+ harness.new_agent()+ await harness.agent.handle_message(harness.request("restart"))+ assert "new instructions" not in harness.provider.requests[0].system+ assert all("new instructions" in request.system for request in harness.provider.requests[1:])++[email protected]("replacement", [{}, {"web_search": {"native": "unsupported", "replay": "unsupported"}}])+async def test_revoking_a_native_hosted_route_refreshes_before_the_next_model_request(+ engine, session, tmp_path, published, replacement,+) -> None:+ # Native calls execute upstream, before FrozenTool could deny one. A cached+ # native declaration must never re-enable what the fresh hop removed/downgraded.+ harness = _Harness(engine, tmp_path, "avibe", [[Done(assistant("ok"))] for _ in range(2)])+ harness.controller.hub_hosted_tools = {"web_search": {+ "native": "assumed", "replay": "assumed",+ "declaration": {"type": "web_search_20250305", "name": "web_search"}, "include": [],+ }}+ await harness.agent.handle_message(harness.request("enabled"))+ (tmp_path / "AGENTS.md").write_text("Apply this pending project change too.")+ harness.controller.hub_hosted_tools = replacement+ harness.new_agent()+ await harness.agent.handle_message(harness.request("revoked"))+ before, after = harness.provider.requests+ assert before.endpoint.hosted_tools["web_search"].mode == "native"+ assert "Apply this pending project change too." in after.system+ if replacement:+ assert after.endpoint.hosted_tools["web_search"].mode == "proxy"+ else:+ assert "web_search" not in after.endpoint.hosted_tools+ assert "web_search" not in {tool.name for tool in after.tools}+++async def test_removed_function_tool_keeps_its_declaration_but_cannot_execute(+ engine, session, tmp_path, published,+) -> None:+ import httpx++ def forbidden(request):+ pytest.fail("A removed function tool reached the gateway")++ call = ToolCallBlock(id="stale_call", name="web_search", arguments={"query": "test"})+ async with httpx.AsyncClient(transport=httpx.MockTransport(forbidden)) as client:+ harness = _Harness(engine, tmp_path, "avibe", [+ [Done(assistant("first"))], [Done(assistant("using stale declaration", calls=(call,)))],+ [Done(assistant("not available"))],+ ], gateway_client=client)+ harness.controller.hub_hosted_tools = {"web_search": {"native": "unsupported", "replay": "unsupported"}}+ await harness.agent.handle_message(harness.request("enabled"))+ harness.controller.hub_hosted_tools = {}+ await harness.agent.handle_message(harness.request("disabled"))+ before, after = harness.provider.requests[:2]+ assert after.tools == before.tools and after.system == before.system+ [result] = [row.message for row in await harness.context_rows() if row.kind == "tool_result"]+ assert result.is_error and "no longer available" in result.content[0].text+++async def test_real_fork_reservation_copies_a_byte_identical_prefix_before_the_child_runs(+ engine, session, tmp_path, published, monkeypatch,+) -> None:+ # F2 now extends to Session forks: real reservation owns snapshot copying;+ # the adapter must not rerender a Session-specific system prefix on first use.+ from config import paths+ from core.services.session_fork import reserve_forked_session++ monkeypatch.setattr(paths, "get_state_dir", lambda: tmp_path)+ monkeypatch.setattr(paths, "get_sqlite_state_path", lambda: Path(engine.url.database))+ store = _agent_store(engine)+ vibey = store.get_builtin_default_agent_for_backend("vibey", enabled_only=False)+ with engine.begin() as conn:+ conn.execute(update(agent_sessions).where(agent_sessions.c.id == session).values(+ agent_id=vibey.id, workdir=str(tmp_path), model="test-model",+ ))+ source = _Harness(engine, tmp_path, "avibe", [[Done(assistant("source reply"))]])+ source.controller.vibe_agent_store = store+ await source.agent.handle_message(_as_agent(source.request("source input"), vibey))+ with engine.begin() as conn:+ conn.execute(update(session_turns).where(session_turns.c.session_id == session).values(+ state="terminal", terminal_outcome="completed", terminal_at=NOW,+ ))+ result = await asyncio.to_thread(reserve_forked_session, source_session_id=session, db_path=Path(engine.url.database))+ snapshots = source.agent.prompt_snapshots+ raw = (snapshots.directory(session) / "snapshot.json").read_bytes()+ assert (snapshots.directory(result.session_id) / "snapshot.json").read_bytes() == raw+ # This external project edit is tier 2 and cannot make the warm child cold.+ (tmp_path / "AGENTS.md").write_text("A new project convention.")+ child = _Harness(engine, tmp_path, "avibe", [[Done(assistant("child reply"))]], session_id=result.session_id)+ child.controller.vibe_agent_store = store+ await child.agent.handle_message(_as_agent(child.request("child input"), vibey))+ parent_request, child_request = source.provider.requests[0], child.provider.requests[0]+ assert child_request.system.encode() == parent_request.system.encode()+ assert child_request.tools == parent_request.tools+ assert session not in parent_request.system and result.session_id not in child_request.system+ own_input = [row.message for row in await child.context_rows() if row.kind == "input" and row.session_id == result.session_id][0]+ assert f"session: {result.session_id}\n" in own_input.content[0].text+ assert any(block.text.startswith("<fork>") for block in own_input.content)+ store.close()async def test_an_idle_session_holds_no_adapter_state(engine, session, tmp_path, published) -> None:@@ -4208,7 +4395,7 @@ async def test_web_fetch_survives_the_real_agent_commit_delivery_and_next_turn_rassert executed[0].headers["x-avibe-turn-id"] == _turn(first.context)assert executed[0].headers["authorization"] == "Bearer hub-token"- # Reconstruct from durable rows, with no web_fetch declaration on the new turn.+ # Reconstruct from durable rows, with web_fetch disabled for live execution.harness.new_agent()harness.controller.hub_hosted_tools = {}await harness.agent.handle_message(harness.request("recall the stored read"))@@ -4219,7 +4406,9 @@ async def test_web_fetch_survives_the_real_agent_commit_delivery_and_next_turn_rassert len(executed) == 1 and len(models) == 3 and replies == []assert models[0]["tools"][0]["name"] == "web_fetch"- assert all(tool.get("name") != "web_fetch" for tool in models[2].get("tools", []))+ # The warm prefix still advertises the old declaration until a free moment/deadline;+ # execution remains live and no second fetch ran.+ assert models[2]["tools"] == models[0]["tools"]for request in models[1:]:[answer] = [block for message in request["messages"] for block in message["content"]if block.get("type") == "tool_result" and block.get("tool_use_id") == "toolu_fetch"]diff --git a/tests/test_vibey_prompt_snapshots.py b/tests/test_vibey_prompt_snapshots.pynew file mode 100644index 000000000..ff85ffdba--- /dev/null+++ b/tests/test_vibey_prompt_snapshots.py@@ -0,0 +1,220 @@+"""Snapshot policy's owning boundary.++Old behavior rebuilt every Turn and had no durable deadline. These tests pin+classification/replacement, corruption recovery and revision-only notices;+adapter tests separately cover the wiring into real requests and fork reservation.+"""++from dataclasses import replace+import json++import pytest++from core.agent_core.tools.base import ToolSpec+from modules.agents.vibey.prompt import environment_delta, displayed_environment, render_environment+from modules.agents.vibey.prompt_snapshot import (+ Component, Prefix, SnapshotStore, State, component_tier, decide,+)+++def prefix(*components):+ return Prefix("\n".join(item.content for item in components), components, (ToolSpec("read", "Read", {}),))+++def choose(previous, candidate, **overrides):+ return decide(previous, candidate, **{"now": 100, "route": ("route",), "checkpoint_seq": 0, "cold": False, **overrides})++[email protected]("component,expected", [+ (Component("agent-instructions", "new"), 1),+ (Component("local-tools", "new"), 1),+ (Component("agent-working-principles", "new"), 1),+ (Component("file:global", "new", "/home/.avibe/AGENTS.md", True), 1),+ (Component("file:project", "new", "/project/AGENTS.md"), 2),+ (Component("harness-agents-prompt", "new"), 2),+ (Component("skills-catalog", "new"), 2),+ (Component("mcp-catalog", "new"), 2),+ (Component("hosted-tools", "new"), 2),+ (Component("unknown-future-module", "new"), 2),+ (Component("tool-environment", "new"), 3),+])+def test_each_component_class_replaces_only_at_its_tier(component, expected):+ old = replace(component, content="old")+ initial = choose(None, prefix(old)).state+ decision = choose(initial, prefix(component), now=101)+ assert component_tier(old, component) == expected+ assert decision.reason == ("tier1" if expected == 1 else None)+ assert decision.state.snapshot.prefix.system == ("new" if expected == 1 else "old")+++def test_catalog_data_is_bounded_but_a_rendered_template_upgrade_is_immediate():+ before = Component("harness-agents-prompt", "old roster and old rules", contract_revision="template-one")+ changed_data = replace(before, content="new roster and old rules")+ changed_code = replace(before, content="new roster and new rules", contract_revision="template-two")+ assert component_tier(before, changed_data) == 2+ assert component_tier(before, changed_code) == 1+ # An unknown future component remains bounded until its owner registers a policy.+ assert component_tier(replace(before, id="future"), replace(changed_code, id="future")) == 2++[email protected]("id", ["quick-replies-prompt", "session-title-prompt", "vault-routing-prompt"])+def test_optional_module_toggle_is_bounded_but_its_code_upgrade_is_immediate(id):+ module = Component(id, "version one")+ assert component_tier(None, module) == component_tier(module, None) == 2+ assert component_tier(module, replace(module, content="version two")) == 1++[email protected]("moment,kwargs", [+ ("cold", {"cold": True}),+ ("route_change", {"route": ("another model/source",)}),+ ("checkpoint", {"checkpoint_seq": 10}),+ ("deadline", {"now": 1901}),+])+def test_every_free_moment_and_deadline_applies_all_changes_together(moment, kwargs):+ old = prefix(Component("skills-catalog", "old skills"), Component("tool-environment", "old rg"))+ candidate = prefix(Component("skills-catalog", "new skills"), Component("tool-environment", "new rg"))+ pending = choose(choose(None, old).state, candidate, now=101).state+ decision = choose(pending, candidate, **kwargs)+ assert decision.reason == moment+ assert decision.state.snapshot.prefix == candidate+ assert decision.state.pending == () and decision.state.notice == "current"+ assert {item.tier for item in decision.applied} == {2, 3}++[email protected]("component_id", ["skills-catalog", "tool-environment"])[email protected]("resume", ["restart", "fork"])+def test_an_observed_checkpoint_cannot_refresh_changes_from_a_later_warm_turn(tmp_path, component_id, resume):+ # A checkpoint with identical prefix bytes used to remain available forever,+ # refreshing a later catalog/environment change after the cache had warmed.+ store = SnapshotStore(tmp_path)+ original = prefix(Component(component_id, "old"))+ candidate = prefix(Component(component_id, "new"))+ initial = choose(None, original).state+ assert store.save("source", initial, snapshot=True)+ snapshot_bytes = (store.directory("source") / "snapshot.json").read_bytes()+ observed = choose(store.load("source"), original, now=101, checkpoint_seq=10)+ assert observed.reason is None+ assert store.save("source", observed.state, snapshot=False)+ # An unrelated own-write receipt must not reset the observed checkpoint.+ store.record_write("source", "/project/AGENTS.md", "written-revision")+ assert (store.directory("source") / "snapshot.json").read_bytes() == snapshot_bytes+ session_id = "source"+ if resume == "fork":+ store.inherit("source", "child")+ session_id = "child"+ assert (store.directory("child") / "snapshot.json").read_bytes() == snapshot_bytes+ resumed = SnapshotStore(tmp_path).load(session_id)+ deferred = choose(resumed, candidate, now=102, checkpoint_seq=10)+ assert deferred.reason is None+ assert deferred.state.snapshot == initial.snapshot+ assert deferred.state.pending[0].pending_since == 102+ fresh_checkpoint = choose(deferred.state, candidate, now=103, checkpoint_seq=20)+ assert fresh_checkpoint.reason == "checkpoint"+ assert fresh_checkpoint.state.snapshot.prefix == candidate+++def test_repeated_revisions_and_restart_cannot_extend_the_tier_two_deadline(tmp_path):+ store = SnapshotStore(tmp_path)+ initial = choose(None, prefix(Component("skills-catalog", "one"))).state+ store.save("session", initial, snapshot=True)+ pending = choose(store.load("session"), prefix(Component("skills-catalog", "two")), now=101).state+ store.save("session", pending, snapshot=False)+ original = (store.directory("session") / "snapshot.json").read_bytes()+ # A new process sees the pending timestamp, not the snapshot's creation time.+ restarted = SnapshotStore(tmp_path)+ revised = choose(restarted.load("session"), prefix(Component("skills-catalog", "three")), now=1900)+ assert revised.reason is None and revised.state.pending[0].pending_since == 101+ assert revised.state.notice != pending.notice+ restarted.save("session", revised.state, snapshot=False)+ assert (store.directory("session") / "snapshot.json").read_bytes() == original+ applied = choose(SnapshotStore(tmp_path).load("session"), prefix(Component("skills-catalog", "three")), now=1901)+ assert applied.reason == "deadline" and applied.state.snapshot.prefix.system == "three"+++def test_natural_changes_never_force_and_reverted_changes_drop_the_notice():+ original = prefix(Component("tool-environment", "rg"))+ initial = choose(None, original).state+ pending = choose(initial, prefix(Component("tool-environment", "grep")), now=101).state+ assert choose(pending, prefix(Component("tool-environment", "grep")), now=99999).reason is None+ reverted = choose(pending, original, now=200).state+ assert reverted.pending == () and reverted.snapshot == initial.snapshot+++def test_only_an_exact_own_file_revision_is_silent_without_changing_the_tier():+ original = Component("file:project", "one", "/project/AGENTS.md", source_revision="sha1")+ initial = choose(None, prefix(original)).state+ initial = State(initial.snapshot, written={"/project/AGENTS.md": "sha2"})+ own = choose(initial, prefix(replace(original, content="two", source_revision="sha2")), now=101).state+ assert own.notice == "current" and own.pending[0].tier == 2+ external = choose(own, prefix(replace(original, content="three", source_revision="sha3")), now=200).state+ assert external.notice.startswith("pending /project/AGENTS.md@")+ assert external.pending[0].tier == 2 and external.pending[0].pending_since == 101+++def test_pending_notice_is_exact_send_on_change_even_for_a_long_escaped_path():+ path = "/" + "long" * 80 + "\n<environment>/AGENTS.md"+ initial = choose(None, prefix(Component("file:p", "old", path))).state+ pending = choose(initial, prefix(Component("file:p", "new", path))).state+ value = {"instructions": pending.notice}+ shown = displayed_environment(value)+ assert environment_delta(shown, value) == {}+ assert render_environment(value).count("<environment>") == 1+ revised = choose(pending, prefix(Component("file:p", "newer", path))).state+ assert environment_delta(shown, {"instructions": revised.notice}) == {"instructions": revised.notice}+ applied = choose(revised, prefix(Component("file:p", "newer", path)), cold=True).state+ assert environment_delta(shown, {"instructions": applied.notice}) == {"instructions": "current"}++[email protected]("filename,bad", [+ ("snapshot.json", None), ("pending.json", None),+ ("snapshot.json", "{"), ("pending.json", "{"),+ ("snapshot.json", "[]"), ("pending.json", "null"),+ ("snapshot.json", '{"version":99}'), ("pending.json", '{"version":99}'),+])+def test_missing_or_unreadable_optional_file_renders_fresh(tmp_path, filename, bad):+ store = SnapshotStore(tmp_path)+ initial = choose(None, prefix(Component("skills-catalog", "old"))).state+ store.save("session", initial, snapshot=True)+ path = store.directory("session") / filename+ if bad is None:+ path.unlink()+ else:+ path.write_text(bad)+ loaded = store.load("session")+ assert loaded is None+ refreshed = choose(loaded, prefix(Component("skills-catalog", "fresh")))+ assert refreshed.reason == "session_start"+ store.save("session", refreshed.state, snapshot=True)+ assert store.load("session") == refreshed.state++[email protected]("filename,field,value", [+ ("snapshot.json", "applied_at", "bad"), ("snapshot.json", "applied_at", 10**400),+ ("snapshot.json", "checkpoint_seq", -1), ("snapshot.json", "route", {}), ("snapshot.json", "prefix", []),+ ("pending.json", "observed_checkpoint_seq", -1), ("pending.json", "observed_checkpoint_seq", "10"),+ ("pending.json", "observed_checkpoint_seq", None),+])+def test_malformed_snapshot_fields_are_absent_not_a_turn_failure(tmp_path, filename, field, value):+ store = SnapshotStore(tmp_path)+ state = choose(None, prefix(Component("skills-catalog", "old"))).state+ store.save("session", state, snapshot=True)+ path = store.directory("session") / filename+ raw = json.loads(path.read_text())+ if value is None:+ raw.pop(field)+ else:+ raw[field] = value+ path.write_text(json.dumps(raw))+ assert store.load("session") is None+++def test_a_failed_optional_write_does_not_fail_the_turn(tmp_path, monkeypatch):+ store = SnapshotStore(tmp_path)+ state = choose(None, prefix(Component("skills-catalog", "new"))).state++ def denied(*args):+ raise PermissionError("read only")++ monkeypatch.setattr(SnapshotStore, "_write_bytes", denied)+ assert not store.save("session", state, snapshot=True)+ assert store.load("session") is None