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): load AGENTS.md and CLAUDE.md into the system prompt (C-7 section 9) (#2499)
Call Whitef2e2c1d3104d
diff --git a/README.md b/README.mdindex 0f8ba4510..96cac4b57 100644--- a/README.md+++ b/README.md@@ -273,6 +273,12 @@ Full references: [Commands](docs/COMMANDS.md) · [CLI](docs/CLI.md)## Agents+**Vibey reads your instruction files.** Like Claude Code and Codex, Vibey loads your standing instructions at the start of every Turn:+1. `~/.avibe/AGENTS.md`, for every project;+2. then, in each directory from the filesystem root down to the working directory, its `AGENTS.md` (or `CLAUDE.md`).++`AGENTS.override.md` takes the place of a directory's `AGENTS.md`. When two files conflict, the more specific one wins. An edit takes effect on the next Turn. The instructions are capped at 64 KiB in all; past that, Vibey is told which file was cut or left out.+The setup wizard detects Claude Code, Codex, and OpenCode on your machine and installs any you choose that are missing. To install one yourself:<details>diff --git a/README_ZH.md b/README_ZH.mdindex fa31dc1b3..d7ea1bab7 100644--- a/README_ZH.md+++ b/README_ZH.md@@ -273,6 +273,12 @@ vibe vault # 管理密钥、请求、认证请求与签名## Agent+**Vibey 会读你的说明文件。** 和 Claude Code、Codex 一样,Vibey 在每个 Turn 开始时加载你的常驻说明:+1. `~/.avibe/AGENTS.md`,对所有项目生效;+2. 再从文件系统根目录一路到工作目录,读每一层的 `AGENTS.md`(或 `CLAUDE.md`)。++`AGENTS.override.md` 会替代所在目录的 `AGENTS.md`。几份文件冲突时,越具体的那份为准。改了文件,下一个 Turn 就生效。这部分说明合计上限 64 KiB;超出时,Vibey 会被告知哪份被截断或没有加载。+设置向导会检测你机器上的 Claude Code、Codex 和 OpenCode,缺哪个、你选了哪个,就帮你装上。想自己装的话:<details>diff --git a/config/paths.py b/config/paths.pyindex 090c7ca26..d16b62702 100644--- a/config/paths.py+++ b/config/paths.py@@ -233,6 +233,14 @@ def get_state_backups_dir() -> Path:return get_state_dir() / "backups"+#: The user's global instruction file for Vibey, in the Avibe home (C-7 ``tools.md`` section 9; owner decision).+GLOBAL_INSTRUCTIONS_FILENAME = "AGENTS.md"+++def get_global_instructions_path() -> Path:+ return get_vibe_remote_dir() / GLOBAL_INSTRUCTIONS_FILENAME++def get_user_preferences_path() -> Path:return get_state_dir() / "user_preferences.md"diff --git a/docs/plans/agent-core-contracts/README.md b/docs/plans/agent-core-contracts/README.mdindex bb646f002..bb52e54b3 100644--- a/docs/plans/agent-core-contracts/README.md+++ b/docs/plans/agent-core-contracts/README.md@@ -12,7 +12,7 @@ on it fork; after that, a change needs orchestrator approval and lands here firs| C-4 | Agent event stream and its mapping to Avibe outputs | `agent` → adapter | [`agent-event.schema.json`](agent-event.schema.json), [`loop-control.md`](loop-control.md) §6 | P2 || C-5 | Transcript rows, `context_seq`, projection, fork | adapter ↔ `harness` | [`transcript.md`](transcript.md), [`transcript-rows.schema.json`](transcript-rows.schema.json) | P2 || C-6 | Model Hub consumer extension | Model Hub → adapter | [`model-hub-consumer.md`](model-hub-consumer.md), [`hop-resolution.schema.json`](hop-resolution.schema.json) | P1 |-| C-7 | Tools, output governance, job handle | `tools` → `agent`, adapter | [`tools.md`](tools.md), [`job.schema.json`](job.schema.json) | P1 |+| C-7 | Tools, output governance, job handle, environment block, project instructions | `tools` → `agent`, adapter | [`tools.md`](tools.md), [`job.schema.json`](job.schema.json) | P1 || C-8 | Backend registration | catalog → every backend list | [`backend-registration.md`](backend-registration.md) | P2 || C-5, C-7 | Recovery invariants for jobs, tool calls, and delivery, with owners and proofs | `tools`, `loop`, adapter | [`recovery.md`](recovery.md) | P1 || C-9 | Context management: tiers, trigger, cut, forked checkpoint, overflow ladder, guards | `harness` → `agent`, adapter | [`context.md`](context.md); rows in [`transcript-rows.schema.json`](transcript-rows.schema.json) | P3 (frozen 2026-10-04) |diff --git a/docs/plans/agent-core-contracts/tools.md b/docs/plans/agent-core-contracts/tools.mdindex 94c0bd6ac..e23f0e1f8 100644--- a/docs/plans/agent-core-contracts/tools.md+++ b/docs/plans/agent-core-contracts/tools.md@@ -354,3 +354,94 @@ stays bounded on every input whatever the script, and no value can add a line, fThe 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.++## 9. Project instructions (Avibe)++The Agent reads the user's instruction files into its system prompt, as Pi does (`core/resource-loader.ts`+`loadProjectContextFiles` and `core/system-prompt.ts` `renderProjectContext`). The native CLIs load their own, and+Avibe's shared prompt tells every agent that `AGENTS.md` is what later Agents load first.++**Which files, in order.**+1. The global file: `AGENTS.md` in the Avibe home, `~/.avibe/AGENTS.md` by default or under `AVIBE_HOME`+ (`config.paths.get_global_instructions_path`). It is one known path, so a user who keeps global principles+ elsewhere can sync them to it.+2. Each directory from the filesystem root down to the Session's cwd. Each contributes the first of these that is a+ readable file: `AGENTS.override.md`, `AGENTS.md`, `AGENTS.MD`, `CLAUDE.md`, `CLAUDE.MD`. A candidate that is not a+ file, or cannot be read, is skipped silently, and the next one is tried.++How the files are read:+- Symlinks are followed. A file reached twice (the same real path) is loaded once: as the global file if it is that+ one, else at the directory nearest the cwd. The first readable candidate is its directory's file even when blank.+- A linked git worktree nested inside its main repository has two copies of the same file: the main repository's is an+ ancestor of the cwd, and the worktree root holds its own. Loading both would apply that repository's instructions+ twice, so the main repository's file with the same name as the worktree root's is left out.+ - This is Pi's rule. Finding the main repository reads the worktree's `.git` file and the `commondir` it points to.+ - What is left out is a place: the main checkout's directory and the file's name. If both checkouts link one shared+ file, the worktree's copy still loads.+ - Instruction files themselves are read only from the ancestor chain and the global path.+- A blank file is left out.+- Each file is read as UTF-8, with a leading byte-order mark dropped and undecodable bytes replaced.+- Each file is read only as far as the limit below, plus one character's bytes. Every Turn reads the files, so a+ mistaken huge one costs no more than a full section.+- A file's size:+ - read whole, it is the size of its text as read, each undecodable byte counting as its three-byte replacement+ character;+ - otherwise, it is the size the file system reports.++ Either way, the limit holds for what the section carries.+- Of `.git` and `commondir`, only the one path line Git writes is read (8 KiB at most).++**Where they enter.** A `<project_context>` section of the system prompt. It comes after the Agent's head (preamble,+tools, guidelines) and before Avibe's injected sections:++```text+<project_context>+Project-specific instructions and guidelines:+More general files come first; where two conflict, the later, more specific one wins.++<project_instructions path="/Users/me/.avibe/AGENTS.md">+...+</project_instructions>++<project_instructions path="/Users/me/src/app/AGENTS.md">+...+</project_instructions>+</project_context>+```++- The first line is Pi's. The second is Avibe's.+- Each path is escaped (see Bound below) and never cut.+- Three reasons for the place:+ - It is Pi's order: rules, then project context, then skills.+ - The head and these files are the same for every Session in that cwd, while Avibe's sections carry the Session's+ own 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.+- With no file to load, the section is absent.++**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.++**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 the+number of files or the length of their paths. The owner's own set (a global file, a workspace file, and a repository+file) is about 31 KB, so Codex's 32 KiB default would already cut it.+- **Who gets the room.** First the global file, then the files from the cwd upward. The most specific project file is+ therefore the last to be cut. The section keeps the order above either way.+- **A file the room cuts** keeps its first bytes, on a character boundary, and ends with:+ `[Truncated: the first {shown} of {size} bytes. The instruction files share a 65,536-byte limit; read the file for the rest.]`+- **Files that get no room** are named after the last block, as many as fit 1,024 bytes kept for this notice, then how+ many more:+ `[Not loaded, over the 65,536-byte limit for instruction files: {path} ({size} bytes); ...; and {count} more. Read them if the task needs them.]`+- **Paths.** A path is escaped as the environment block's cwd is (§8). A path in the attribute also has `"` and `&` as+ `\u0022` and `\u0026`. This stays injective, because escaping doubles every backslash.++**Deviations from Pi.**+- The global file is one path, `AGENTS.md` in the Avibe home, not the candidate list in the agent's own directory.+- The total byte limit and its notices; Pi has no limit.+- A file is loaded once per real path, not once per path string.+- A blank file is left out.+- An unreadable file is skipped silently. Pi warns on stderr, which the Agent has no place to show.+- The precedence line.diff --git a/docs/plans/avibe-agent-core.md b/docs/plans/avibe-agent-core.mdindex ee9f064df..05c7bd9b3 100644--- a/docs/plans/avibe-agent-core.md+++ b/docs/plans/avibe-agent-core.md@@ -108,7 +108,7 @@ payload.| C-4 | Typed agent event stream and its mapping to existing Avibe outputs | `agent` → adapter → Workbench and IM progress | `agent-event.schema.json` || C-5 | Transcript rows: what each context entry stores, `context_seq`, projection, fork by reference (the fork point is C-10) | adapter ↔ `harness` | `transcript.md`, `transcript-rows.schema.json` || C-6 | Model Hub consumer extension: `google` protocol, hop resolution, served-hop report | Model Hub → adapter | `model-hub-consumer.md`, `hop-resolution.schema.json` |-| C-7 | Tools: Pi's surface plus the owner's additions; output governance; job handle | `tools` → `agent`, adapter | `tools.md`, `job.schema.json` |+| C-7 | Tools: Pi's surface plus the owner's additions; output governance; job handle; the environment block and project instructions | `tools` → `agent`, adapter | `tools.md`, `job.schema.json` || C-8 | Backend registration: the catalog as the one declaration, and which sets must include `vibey` | catalog → every backend list | `backend-registration.md` || C-9 | Context management: projection tiers, trigger, cut point, checkpoint, overflow ladder, guards | `harness` → `agent`, adapter | `context.md`; row shapes in `transcript-rows.schema.json` || C-10 | Fork: the fork point (a settled cut and its prefix), the side turn, the fork Session, lineage, capability, merge-back (frozen 2026-10-10) | `harness`, `agent`, storage, service → C-9, adapter | `fork.md` |@@ -243,6 +243,13 @@ for v1: stale-write guard, line numbers in `read`, a `workdir` parameter, head+tpost-edit LSP diagnostics, and dedicated `grep`/`find`/`ls`. Two places where tau falls short and Pi is the source:the normalized edit tier, and streaming, bounded output with spill.+**Project instructions.** As Pi does, the Agent loads instruction files into its system prompt:+- `~/.avibe/AGENTS.md`;+- then, from the filesystem root down to the Session's cwd, each directory's first of `AGENTS.override.md`,+ `AGENTS.md`, `AGENTS.MD`, `CLAUDE.md`, `CLAUDE.MD`.++They are re-read every Turn and bounded at 64 KiB in total (C-7 `tools.md` §9).+**Long-running commands through Watch.** Watch serves as the agent's background facility. A process cannot changeowners after it starts, so every command gets a portable handle from its first moment and never has to move.diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex 175d545e8..5b3a3a67f 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -84,6 +84,7 @@ from modules.agents.vibey.context import (mark_skill_loads,)from modules.agents.vibey.errors import error_text+from modules.agents.vibey.instructions import load_instruction_files, project_contextfrom modules.agents.vibey.media import MediaSnapshotsfrom modules.agents.vibey.models import HubModelRouter, ProviderFactory, registry_providers, selection_from_hopfrom modules.agents.vibey.prompt import EnvironmentValue, current_environment, system_prompt@@ -130,6 +131,12 @@ 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.@@ -296,7 +303,9 @@ 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)- self._start_agent(turn, cwd, sections, environment, builtin_agent=builtin_agent)+ # 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)runtime.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)@@ -550,13 +559,20 @@ class VibeyAgent(BaseAgent):return HubModelRouter(resolve, self._providers, first=await resolve())def _start_agent(- self, turn: _Run, cwd: str, sections: str, environment: Mapping[str, str], *, builtin_agent: bool+ self,+ turn: _Run,+ cwd: str,+ sections: str,+ environment: Mapping[str, str],+ *,+ builtin_agent: bool,+ instructions: str = "",) -> None:"""The Turn's loop, over its router, tools, system prompt, and the environment its commands run in.The bash rule names ``rg`` only when that environment's PATH finds it. That PATH is the service'sPATH plus the installed managed tools, which change only on an install or upgrade, so a Session's- Turns keep one system prompt, which changes only when ripgrep's availability does.+ Turns keep one system prompt, which changes only when ripgrep's availability or an instruction file does."""request, session_id = turn.request, turn.session_idsuite = self._tools()@@ -579,7 +595,11 @@ class VibeyAgent(BaseAgent):agent.set_tools(tools)finds_rg = shutil.which("rg", path=environment.get("PATH", "")) is not Noneagent.system = system_prompt(- [tool.spec.name for tool in tools], sections, builtin_agent=builtin_agent, rg=finds_rg+ [tool.spec.name for tool in tools],+ sections,+ builtin_agent=builtin_agent,+ rg=finds_rg,+ project_context=instructions,)turn.agent, turn.cwd = agent, cwddiff --git a/modules/agents/vibey/instructions.py b/modules/agents/vibey/instructions.pynew file mode 100644index 000000000..175fa5029--- /dev/null+++ b/modules/agents/vibey/instructions.py@@ -0,0 +1,227 @@+"""The user's instruction files in the Agent's system prompt (C-7 ``tools.md`` section 9).++Ported from Pi (MIT, Copyright (c) 2025 Mario Zechner) at ``7fbbd5f``:+- ``packages/coding-agent/src/core/resource-loader.ts``: ``loadProjectContextFiles`` and ``findShadowedContextFile``;+- ``core/footer-data-provider.ts``: ``findGitPaths``;+- ``core/system-prompt.ts``: ``renderProjectContext``.++Avibe's deviations (section 9): one global path, a shared byte limit with its notices, one load per real path, blank+files left out, unreadable files skipped silently, and a precedence line.+"""++from __future__ import annotations++import os+from dataclasses import dataclass+from pathlib import Path+from typing import Optional, Sequence++from core.agent_core.harness.context import escape++#: What each directory may hold, in order: the first readable one is that directory's file.+CANDIDATES = ("AGENTS.override.md", "AGENTS.md", "AGENTS.MD", "CLAUDE.md", "CLAUDE.MD")+#: The bytes the whole section may carry (64 KiB): its header, each file's path and markup, the files' text, and the+#: notices. Counting all of it bounds the section by construction, however many files or however long their paths.+LIMIT = 65_536+#: Of ``LIMIT``, the bytes kept for the notice naming the files left out.+OMITTED_ROOM = 1_024+HEADER = "Project-specific instructions and guidelines:"+PRECEDENCE = "More general files come first; where two conflict, the later, more specific one wins."+TRUNCATED = (+ "[Truncated: the first {shown} of {size} bytes. The instruction files share a 65,536-byte limit; read the file "+ "for the rest.]"+)+NOT_LOADED = "[Not loaded, over the 65,536-byte limit for instruction files: {files}. Read them if the task needs them.]"+MORE = "and {count} more"+++@dataclass(frozen=True)+class InstructionFile:+ path: str+ #: What was read: at most the limit's worth of the file, so a huge one costs no more than a full section.+ content: str+ 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++ @property+ def byte_size(self) -> int:+ return self.size if self.size is not None else len(self.content.encode("utf-8"))+++_BOM = b"\xef\xbb\xbf"+#: Git writes one path line into ``.git`` and ``commondir``: no more is read of either.+_GIT_LINE = 8192+++def _read(path: str) -> Optional[tuple[str, int]]:+ """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+ Turn reads the files, and a mistaken multi-gigabyte one must cost no more than a full section.+ """+ try:+ if not os.path.isfile(path):+ return None+ with open(path, "rb") as handle:+ size = os.fstat(handle.fileno()).st_size+ data = handle.read(len(_BOM) + LIMIT + 4)+ except OSError:+ return None+ if 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)+++def _from_dir(directory: str) -> Optional[InstructionFile]:+ for name in CANDIDATES:+ path = os.path.join(directory, name)+ read = _read(path)+ if read is not None:+ return InstructionFile(path, read[0], size=read[1])+ return None+++def _git_paths(cwd: str) -> Optional[tuple[str, str]]:+ """The checkout root holding ``cwd`` and its common git directory, found by walking up (Pi's ``findGitPaths``)."""+ directory = cwd+ while True:+ marker = os.path.join(directory, ".git")+ try:+ if os.path.isfile(marker):+ with open(marker, encoding="utf-8", errors="replace") as handle:+ content = handle.read(_GIT_LINE).strip()+ if content.startswith("gitdir: "):+ git_dir = os.path.normpath(os.path.join(directory, content[len("gitdir: ") :].strip()))+ if not os.path.exists(os.path.join(git_dir, "HEAD")):+ return None+ common = os.path.join(git_dir, "commondir")+ if os.path.exists(common):+ with open(common, encoding="utf-8", errors="replace") as handle:+ return directory, os.path.normpath(os.path.join(git_dir, handle.read(_GIT_LINE).strip()))+ return directory, git_dir+ elif os.path.isdir(marker):+ return (directory, marker) if os.path.exists(os.path.join(marker, "HEAD")) else None+ except OSError:+ return None+ parent = os.path.dirname(directory)+ if parent == directory:+ return None+ directory = parent+++def _shadowed(cwd: str) -> Optional[tuple[str, str]]:+ """Where the main repository's file sits that a nested linked worktree's own one stands in for (Pi's+ ``findShadowedContextFile``): both are that repository's, so loading both would apply it twice.++ A place (the main checkout's real directory and the file's name), not a file: the two copies may be links to the+ same file, and the worktree's must still load."""+ found = _git_paths(cwd)+ if found is None:+ return None+ worktree_root, common = os.path.realpath(found[0]), os.path.realpath(found[1])+ main_root = os.path.dirname(common)+ # An ordinary checkout (the two are the same directory) or a sibling worktree, whose main one is no ancestor.+ if not worktree_root.startswith(main_root + os.sep):+ return None+ # A bare layout or a submodule: the directory above the git directory checks nothing out.+ if os.path.realpath(os.path.join(main_root, ".git")) != common:+ return None+ own = _from_dir(worktree_root)+ 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]:+ """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.+ A blank file is left out.+ """+ files: list[InstructionFile] = []+ seen: set[str] = set()+ 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 not cwd:+ return files+ directory = os.path.abspath(cwd)+ shadowed = _shadowed(directory)+ chain: list[InstructionFile] = []+ while True:+ found = _from_dir(directory)+ real = os.path.realpath(found.path) if found is not None else None+ at_shadow = found is not None and (os.path.realpath(directory), os.path.basename(found.path)) == shadowed+ if found is not None and not at_shadow and real not in seen:+ seen.add(real)+ if found.content.strip():+ chain.insert(0, found)+ parent = os.path.dirname(directory)+ if parent == directory:+ break+ directory = parent+ return files + chain+++def _cut(text: str, size: int) -> str:+ """The first ``size`` bytes of ``text`` in UTF-8, on a character boundary."""+ return text.encode("utf-8")[:size].decode("utf-8", "ignore")+++def _bytes(text: str) -> int:+ return len(text.encode("utf-8"))+++def _attribute(path: str) -> str:+ """A path as a quoted attribute's value: ``escape``d, then its quote and ampersand as ``\\u0022`` and+ ``\\u0026``. Still injective: ``escape`` doubles every backslash, so only an escape writes ``\\u``."""+ return escape(path).replace('"', "\\u0022").replace("&", "\\u0026")+++def _not_loaded(files: Sequence[InstructionFile]) -> str:+ """The notice naming the files left out, as many as fit ``OMITTED_ROOM``, then how many more."""+ named: list[str] = []+ for file in files:+ entries = [*named, f"{escape(file.path)} ({file.byte_size} bytes)"]+ rest = len(files) - len(entries)+ listed = "; ".join([*entries, MORE.format(count=rest)] if rest else entries)+ if _bytes("\n\n" + NOT_LOADED.format(files=listed)) > OMITTED_ROOM:+ break+ named = entries+ rest = len(files) - len(named)+ return "\n\n" + NOT_LOADED.format(files="; ".join([*named, MORE.format(count=rest)] if rest else named))+++def project_context(files: Sequence[InstructionFile]) -> str:+ """The ``<project_context>`` section, or "" with no file; at most ``LIMIT`` bytes, all of it counted.++ The room goes first to the global file, then to the files from the cwd upward, so the most specific one is the last+ cut. A file that gets no room is named in the closing notice. The section keeps the files' order either way.+ """+ if not files:+ return ""+ opening, closing = f"<project_context>\n{HEADER}\n{PRECEDENCE}", "\n</project_context>"+ left = LIMIT - _bytes(opening) - _bytes(closing) - OMITTED_ROOM+ first = [index for index, file in enumerate(files) if file.is_global]+ rest = [index for index in reversed(range(len(files))) if not files[index].is_global]+ blocks: dict[int, str] = {}+ for index in first + rest:+ file = files[index]+ start, end = f'\n\n<project_instructions path="{_attribute(file.path)}">\n', "\n</project_instructions>"+ room = left - _bytes(start) - _bytes(end)+ text, size = file.content, file.byte_size+ if size > room or _bytes(text) > room:+ # The notice's own bytes come out of the room first; its count can only shrink after the cut.+ room -= _bytes("\n" + TRUNCATED.format(shown=max(room, 0), size=size))+ if room <= 0:+ continue+ shown = _cut(text, room)+ text = f"{shown}\n{TRUNCATED.format(shown=_bytes(shown), size=size)}"+ blocks[index] = start + text + end+ left -= _bytes(blocks[index])+ omitted = [file for index, file in enumerate(files) if index not in blocks]+ body = "".join(blocks[index] for index in sorted(blocks))+ return opening + body + (_not_loaded(omitted) if omitted else "") + closingdiff --git a/modules/agents/vibey/prompt.py b/modules/agents/vibey/prompt.pyindex 2adfbd4ce..d12aff199 100644--- a/modules/agents/vibey/prompt.py+++ b/modules/agents/vibey/prompt.py@@ -1,7 +1,8 @@"""Vibey's system prompt and the environment block of each consumed input.The system prompt is stable so providers can cache it: who the Agent is, Pi's-tool snippets and rules, then Avibe's injected sections. Who the Agent is comes+tool snippets and rules, the user's instruction files (``instructions``, C-7+tools.md section 9), then Avibe's injected sections. Who the Agent is comesfrom its record, so it is the same on every Turn the Session runs as that Agent.Facts that change (cwd, date, live Watches) travel in an ``<environment>`` blockrendered into each consumed input instead (C-7 tools.md section 8), so the@@ -110,9 +111,11 @@ def coding_prompt(tool_names: Iterable[str], *, builtin_agent: bool, rg: bool) -)-def system_prompt(tool_names: Iterable[str], avibe_sections: str, *, builtin_agent: bool, rg: bool) -> str:+def system_prompt(+ tool_names: Iterable[str], avibe_sections: str, *, builtin_agent: bool, rg: bool, project_context: str = ""+) -> str:head = coding_prompt(tool_names, builtin_agent=builtin_agent, rg=rg)- return "\n\n".join(part for part in (head, avibe_sections.strip()) if part)+ return "\n\n".join(part for part in (head, project_context, avibe_sections.strip()) if part)# --- environment block ---------------------------------------------------------diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex dbb9f77aa..36141c2f1 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -1749,6 +1749,46 @@ async def test_another_agent_on_the_backend_is_not_told_it_is_vibey(engine, sessassert "You are Rex, a careful code reviewer." in system and f"- {CONCURRENT_CALLS_RULE}" in system+async 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.+ from config import paths+ from modules.agents.vibey.prompt import FINAL_REPLY_RULE++ # The Avibe home holds the state database too, so only the global file's path moves.+ global_path = tmp_path / "avibe-home/AGENTS.md"+ monkeypatch.setattr(paths, "get_global_instructions_path", lambda: global_path)+ harness = _Harness(+ engine, tmp_path, "avibe", [[Done(assistant(reply))] for reply in ("one", "two", "three", "four")],+ tools=[FakeTool("read"), FakeTool("bash")],+ )++ await harness.agent.handle_message(harness.request("no files yet"))+ global_path.parent.mkdir(parents=True, exist_ok=True)+ global_path.write_text("Report in Chinese.", encoding="utf-8")+ (tmp_path / "AGENTS.md").write_text("Run tests under the sandbox.", encoding="utf-8")+ await harness.agent.handle_message(harness.request("now with files"))+ await harness.agent.handle_message(harness.request("unchanged"))+ (tmp_path / "AGENTS.md").write_text("Run tests under the sandbox. Never push to master.", encoding="utf-8")+ await harness.agent.handle_message(harness.request("edited"))++ without, first, again, edited = (request.system for request in harness.provider.requests)+ # The section's text, stated here rather than built by the code under test.+ section = (+ "<project_context>\nProject-specific instructions and guidelines:\n"+ "More general files come first; where two conflict, the later, more specific one wins.\n\n"+ f'<project_instructions path="{global_path}">\nReport in Chinese.\n</project_instructions>\n\n'+ f'<project_instructions path="{tmp_path / "AGENTS.md"}">\nRun tests under the sandbox.\n'+ "</project_instructions>\n</project_context>"+ )+ head_end = without.index(FINAL_REPLY_RULE) + len(FINAL_REPLY_RULE)+ assert first == f"{without[:head_end]}\n\n{section}{without[head_end:]}"+ assert again == first+ assert edited != first and "Never push to master." in edited++async def test_an_idle_session_holds_no_adapter_state(engine, session, tmp_path, published) -> None:harness = _Harness(engine, tmp_path, "avibe", _tool_turn() + [[Done(assistant("again"))]])diff --git a/tests/test_vibey_project_instructions.py b/tests/test_vibey_project_instructions.pynew file mode 100644index 000000000..4ef339f2c--- /dev/null+++ b/tests/test_vibey_project_instructions.py@@ -0,0 +1,245 @@+"""The user's instruction files in Vibey's system prompt (C-7 ``agent-core-contracts/tools.md`` section 9).++Discovery runs on real temporary directories. The walk reaches the filesystem root, so each test keeps only the files+under its own temporary directory.+"""++from __future__ import annotations++import os+import re+from pathlib import Path++import pytest++from modules.agents.vibey.instructions import InstructionFile, load_instruction_files, project_context++# The model-facing text, stated here rather than read from the constants it checks (C-7 tools.md section 9).+HEADER = (+ "Project-specific instructions and guidelines:\n"+ "More general files come first; where two conflict, the later, more specific one wins."+)+++def _write(path: Path, text: str) -> Path:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(text, encoding="utf-8")+ return path+++def _found(cwd: Path, global_path: Path, root: Path) -> list[tuple[str, str]]:+ """What the walk loads from ``cwd``, as paths relative to ``root`` (the global file by name), with contents."""+ loaded = []+ for file in load_instruction_files(str(cwd), global_path):+ if file.is_global:+ loaded.append(("<global>", file.content))+ elif Path(file.path).is_relative_to(root):+ loaded.append((Path(file.path).relative_to(root).as_posix(), file.content))+ return loaded+++def test_the_global_file_comes_first_then_each_directory_from_the_root_down_to_the_cwd(tmp_path) -> None:+ global_path = _write(tmp_path / "home/.avibe/AGENTS.md", "global")+ _write(tmp_path / "work/AGENTS.md", "workspace")+ _write(tmp_path / "work/app/CLAUDE.md", "app")+ cwd = tmp_path / "work/app/src"+ cwd.mkdir(parents=True)++ assert _found(cwd, global_path, tmp_path) == [+ ("<global>", "global"),+ ("work/AGENTS.md", "workspace"),+ ("work/app/CLAUDE.md", "app"),+ ]+ # No global file: the walk alone.+ assert _found(cwd, tmp_path / "missing/AGENTS.md", tmp_path) == [+ ("work/AGENTS.md", "workspace"),+ ("work/app/CLAUDE.md", "app"),+ ]+++def test_each_directory_contributes_its_first_candidate_and_the_override_wins(tmp_path) -> None:+ for name in ("AGENTS.override.md", "AGENTS.md", "CLAUDE.md"):+ _write(tmp_path / "a" / name, f"a {name}")+ for name in ("AGENTS.md", "CLAUDE.md"):+ _write(tmp_path / "a/b" / name, f"b {name}")+ _write(tmp_path / "a/b/c/CLAUDE.md", "c CLAUDE.md")++ assert _found(tmp_path / "a/b/c", tmp_path / "none", tmp_path) == [+ ("a/AGENTS.override.md", "a AGENTS.override.md"),+ ("a/b/AGENTS.md", "b AGENTS.md"),+ ("a/b/c/CLAUDE.md", "c CLAUDE.md"),+ ]++[email protected](os.name != "posix" or os.geteuid() == 0, reason="needs POSIX permissions that bind the user")+def test_an_unreadable_candidate_is_skipped_silently_and_the_next_one_read(tmp_path) -> None:+ locked = _write(tmp_path / "repo/AGENTS.md", "locked")+ _write(tmp_path / "repo/CLAUDE.md", "readable")+ (tmp_path / "other/AGENTS.md").mkdir(parents=True) # not a file+ _write(tmp_path / "other/CLAUDE.md", "after a directory")+ locked.chmod(0)+ try:+ assert _found(tmp_path / "repo", tmp_path / "none", tmp_path) == [("repo/CLAUDE.md", "readable")]+ assert _found(tmp_path / "other", tmp_path / "none", tmp_path) == [("other/CLAUDE.md", "after a directory")]+ finally:+ locked.chmod(0o644)+++def test_symlinks_are_followed_and_a_file_is_loaded_once(tmp_path) -> None:+ shared = _write(tmp_path / "elsewhere/principles.md", "principles")+ global_path = tmp_path / "home/.avibe/AGENTS.md"+ global_path.parent.mkdir(parents=True)+ global_path.symlink_to(shared)+ # The repository links its file to the same one, and keeps CLAUDE.md as a link to AGENTS.md.+ (tmp_path / "repo").mkdir()+ (tmp_path / "repo/AGENTS.md").symlink_to(shared)+ (tmp_path / "repo/CLAUDE.md").symlink_to(tmp_path / "repo/AGENTS.md")+ # A file outside the chain, reached through a link in it, is read.+ (tmp_path / "repo/app").mkdir()+ (tmp_path / "repo/app/AGENTS.md").symlink_to(_write(tmp_path / "elsewhere/app.md", "app rules"))++ assert _found(tmp_path / "repo/app", global_path, tmp_path) == [+ ("<global>", "principles"),+ ("repo/app/AGENTS.md", "app rules"),+ ]+++def test_blank_files_are_left_out(tmp_path) -> None:+ _write(tmp_path / "repo/AGENTS.md", " \n\n")+ _write(tmp_path / "repo/CLAUDE.md", "not reached: the blank AGENTS.md is this directory's file")+ _write(tmp_path / "repo/app/AGENTS.md", "\ufeffapp")++ assert _found(tmp_path / "repo/app", tmp_path / "none", tmp_path) == [("repo/app/AGENTS.md", "app")]+++def _git_repo(root: Path) -> None:+ _write(root / ".git/HEAD", "ref: refs/heads/master\n")+++def _linked_worktree(main: Path, worktree: Path, name: str) -> None:+ _write(main / ".git/worktrees" / name / "HEAD", "ref: refs/heads/feature\n")+ _write(main / ".git/worktrees" / name / "commondir", "../..\n")+ _write(worktree / ".git", f"gitdir: {main / '.git/worktrees' / name}\n")++[email protected]("links", ("none", "main", "both"), ids=("files", "main file is a link", "both link one file"))+def test_a_nested_linked_worktree_does_not_load_its_main_repository_file_twice(tmp_path, links) -> None:+ main = tmp_path / "repo"+ _git_repo(main)+ nested = main / ".worktrees/feature"+ _linked_worktree(main, nested, "feature")+ if links == "both":+ # Both checkouts link the same shared file: it is still the worktree's that loads.+ shared = _write(tmp_path / "elsewhere/rules.md", "shared rules")+ (main / "AGENTS.md").symlink_to(shared)+ (nested / "AGENTS.md").symlink_to(shared)+ assert _found(nested / "src", tmp_path / "none", tmp_path) == [+ ("repo/.worktrees/feature/AGENTS.md", "shared rules")+ ]+ return+ if links == "main":+ (main / "AGENTS.md").symlink_to(_write(tmp_path / "elsewhere/main-rules.md", "main copy"))+ else:+ _write(main / "AGENTS.md", "main copy")+ _write(nested / "AGENTS.md", "worktree copy")+ sibling = tmp_path / "feature-sibling"+ _linked_worktree(main, sibling, "sibling")+ _write(sibling / "AGENTS.md", "sibling copy")++ # Both copies are the repository's: only the worktree's own is loaded.+ assert _found(nested / "src", tmp_path / "none", tmp_path) == [("repo/.worktrees/feature/AGENTS.md", "worktree copy")]+ # A sibling worktree has no main repository above it, and an ordinary checkout is its own repository.+ assert _found(sibling, tmp_path / "none", tmp_path) == [("feature-sibling/AGENTS.md", "sibling copy")]+ assert _found(main / "src", tmp_path / "none", tmp_path) == [("repo/AGENTS.md", "main copy")]+++def test_the_section_holds_each_file_by_path_in_order() -> None:+ files = [+ InstructionFile("/home/me/.avibe/AGENTS.md", "global rules", is_global=True),+ InstructionFile('/src/<a "b" & c>/AGENTS.md', "project rules"),+ ]++ # A path is escaped for its quoted attribute: it cannot close the attribute or the tag.+ assert project_context(files) == (+ f"<project_context>\n{HEADER}\n\n"+ '<project_instructions path="/home/me/.avibe/AGENTS.md">\nglobal rules\n</project_instructions>\n\n'+ '<project_instructions path="/src/\\u003ca \\u0022b\\u0022 \\u0026 c\\u003e/AGENTS.md">\nproject rules\n'+ "</project_instructions>\n</project_context>"+ )+ assert project_context([]) == ""+++_NOTICE = re.compile(+ r"\n\[Truncated: the first (\d+) of (\d+) bytes\. The instruction files share a 65,536-byte limit; read the file "+ r"for the rest\.\]\n</project_instructions>"+)+++def _blocks(section: str) -> dict[str, str]:+ """Each file's block text by path."""+ return dict(re.findall(r'<project_instructions path="([^"]*)">\n(.*?)\n</project_instructions>', section, re.S))+++def test_the_section_carries_at_most_64_kib_given_first_to_the_global_file_then_from_the_cwd_upward() -> None:+ global_file = InstructionFile("/g/AGENTS.md", "g" * 10, is_global=True)+ root_file = InstructionFile("/AGENTS.md", "r" * 40_000)++ # The root file is cut: the global file and the cwd's come first.+ section = project_context([global_file, root_file, InstructionFile("/repo/AGENTS.md", "p" * 40_000)])+ blocks = _blocks(section)+ assert len(section.encode("utf-8")) <= 65_536+ assert blocks["/g/AGENTS.md"] == "g" * 10 and blocks["/repo/AGENTS.md"] == "p" * 40_000+ ((shown, size),) = _NOTICE.findall(section)+ assert size == "40000" and blocks["/AGENTS.md"].startswith("r" * int(shown) + "\n[Truncated")+ assert section.index("/g/AGENTS.md") < section.index('"/AGENTS.md"') < section.index("/repo/AGENTS.md")++ # Less room: the cwd's file is cut, and the root file is named as not loaded.+ section = project_context([global_file, root_file, InstructionFile("/repo/AGENTS.md", "p" * 70_000)])+ assert len(section.encode("utf-8")) <= 65_536 and '"/AGENTS.md"' not in section+ ((shown, size),) = _NOTICE.findall(section)+ assert size == "70000" and _blocks(section)["/repo/AGENTS.md"].startswith("p" * int(shown) + "\n[Truncated")+ assert section.endswith(+ "[Not loaded, over the 65,536-byte limit for instruction files: /AGENTS.md (40000 bytes). Read them if the "+ "task needs them.]\n</project_context>"+ )+++def test_paths_and_markup_count_toward_the_limit() -> None:+ # A deep tree with a file at every level: each block repeats a long path, and the notice names what it can.+ files = [InstructionFile("/" + "d/" * 100 + f"{index}/AGENTS.md", "x") for index in range(1_000)]++ section = project_context(files)+ assert len(section.encode("utf-8")) <= 65_536+ assert re.search(r"; and \d+ more\. Read them if the task needs them\.\]\n</project_context>$", section)+++def test_a_cut_falls_on_a_character_boundary() -> None:+ section = project_context([InstructionFile("/AGENTS.md", "é" * 40_000)])++ ((shown, size),) = _NOTICE.findall(section)+ assert size == "80000" and _blocks(section)["/AGENTS.md"].startswith("é" * (int(shown) // 2) + "\n[Truncated")+ assert int(shown) % 2 == 0+++def test_a_huge_file_is_read_only_as_far_as_the_section_can_hold(tmp_path) -> None:+ # Every Turn reads the files: a mistaken multi-megabyte one must cost no more than a full section.+ _write(tmp_path / "repo/AGENTS.md", "x" * (16 * 65_536))++ (file,) = [found for found in load_instruction_files(str(tmp_path / "repo"), tmp_path / "none") if+ Path(found.path).is_relative_to(tmp_path)]+ assert len(file.content.encode("utf-8")) <= 65_536 + 4+ ((_, size),) = _NOTICE.findall(project_context([file]))+ assert size == str(16 * 65_536)+++def test_undecodable_bytes_count_toward_the_limit_as_read(tmp_path) -> None:+ # Each invalid byte reads as a three-byte replacement character: the limit holds for what the prompt carries.+ (tmp_path / "repo").mkdir()+ (tmp_path / "repo/AGENTS.md").write_bytes(b"\xff" * 65_536)++ (file,) = [found for found in load_instruction_files(str(tmp_path / "repo"), tmp_path / "none") if+ Path(found.path).is_relative_to(tmp_path)]+ section = project_context([file])+ assert len(section.encode("utf-8")) <= 65_536+ ((_, size),) = _NOTICE.findall(section)+ assert size == str(3 * 65_536)