Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): stop global AGENTS.md from starving project instructions

xpeng5278-web0a0cac606bc8
diff --git a/docs/adr/0037-project-instruction-chain.md b/docs/adr/0037-project-instruction-chain.md
index 4225a6986..66f8c8b2d 100644
--- a/docs/adr/0037-project-instruction-chain.md
+++ b/docs/adr/0037-project-instruction-chain.md
@@ -2,6 +2,8 @@
- Status: Accepted
- Date: 2026-07-30
+- Updated: 2026-10-08 (independent global and project budgets; visible
+ truncation notice, issue #1490)
- Related: [Agent runtime](../spec/03-runtime/02-agent-runtime.md)
## Context
@@ -25,9 +27,13 @@ workspace file access in Electron main and host-core.
3. For every project directory, the first non-empty candidate wins in this order:
`AGENTS.override.md`, `AGENTS.md`, `CLAUDE.md`,
`.claude/CLAUDE.md`.
-4. Sources are concatenated from root to target directory, capped at 32 KiB of
- UTF-8 content. Later, closer entries take precedence and each source is
- labelled in the prompt.
+4. Sources are concatenated from root to target directory. The global file and
+ the project entries have independent 32 KiB budgets of UTF-8 content, so an
+ oversized global file never removes project instructions. A file cut at its
+ budget keeps whole UTF-8 characters and is followed by a notice that names
+ the source and the loaded and total byte counts; project files after a
+ truncated one are not loaded. Later, closer entries take precedence and
+ each source is labelled in the prompt.
5. The root chain is loaded when the runtime is created. Before a file-path
tool executes, the sidecar may request a path-specific chain through the
Electron-owned `project.instructions.resolve` local proxy. The sidecar does
@@ -51,6 +57,11 @@ workspace file access in Electron main and host-core.
chain instead of waiting on the general host RPC deadline.
- Path preflight records its own duration and cache/fallback markers so
`hostRttMs` continues to describe the actual host tool call.
+- The instruction section can hold up to 64 KiB of file content: 32 KiB from
+ the global file and 32 KiB from the project chain. This mirrors Codex, where
+ `~/.codex/AGENTS.md` is loaded outside the 32 KiB `project_doc_max_bytes`
+ budget that its project files share. A truncated file is visible to the
+ model instead of ending silently.
- Root instruction changes rebuild an idle runtime on the next prompt. Nested
rules are re-resolved for future file-path tool calls.
- This private sidecar proxy remains constrained to a session id and a path
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 179204c47..0f27e8b0f 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1597,8 +1597,13 @@ All discovery stays within the session project root. A target path outside the
project root, or the root path itself, resolves to the root's own chain instead
of an empty result. File tools on attachments or other locations therefore
keep the root chain (which may itself be empty). Empty, unreadable, and
-out-of-root files are skipped. The combined UTF-8 content is capped at 32 KiB
-and source paths are labelled under `# Project instructions`.
+out-of-root files are skipped. The global file and the combined project
+entries have independent 32 KiB UTF-8 budgets, so an oversized global file
+never removes project instructions. A file that exceeds its remaining budget is
+cut on a UTF-8 character boundary and followed by a
+`[PI-Desktop truncated <source>: loaded the first <n> of <total> bytes; ...]`
+notice; project files after a truncated one are not loaded. Source paths are
+labelled under `# Project instructions`.
The sidecar never reads workspace instructions directly. A changed root chain
recreates an idle runtime on its next prompt; nested instructions are resolved
again when a relevant file tool runs. The resolver's timeout and fallback
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 41345470d..14b34168c 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -6544,7 +6544,10 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
`AGENTS.md`; `CLAUDE.md` and `.claude/CLAUDE.md` are fallback names. The idle
follow-up uses changed root content rather than reusing the prior runtime.
Empty, unreadable, oversized, and out-of-root instruction files do not block
- the turn; combined UTF-8 content is capped at 32 KiB. A file tool whose target
+ the turn; the global file and the project chain each have an independent
+ 32 KiB UTF-8 budget, an oversized global file does not remove project
+ entries, and a truncated file ends with a notice naming its source and the
+ loaded and total byte counts. A file tool whose target
is outside the project root, or targets the root itself, keeps the root chain
rather than clearing the project instructions; instruction files are still
read only from inside the root. A fixture-backed sidecar run verifies that a
diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
index d22f15b1c..d17676c83 100644
--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md
@@ -1115,8 +1115,11 @@ sidecar 无法选择不同的根。在一次提示期间,路径解析
所有发现都保留在会话项目根目录中。目标路径位于项目根之外,
或目标就是项目根本身时,解析结果回退为根目录自身的链,而不是空结果,
因此对附件或其他位置的工具调用会保留根链(根链本身也可能为空)。
-空的、不可读的以及根目录外的指令文件仍会被跳过。合并的 UTF-8 内容上限为 32 KiB
-源路径标记在 `# Project instructions` 下。
+空的、不可读的以及根目录外的指令文件仍会被跳过。全局文件与项目条目各有独立的
+32 KiB UTF-8 预算,过大的全局文件不会挤掉项目指令。超出剩余预算的文件按 UTF-8
+字符边界截断,并在末尾附加
+`[PI-Desktop truncated <source>: loaded the first <n> of <total> bytes; ...]`
+提示;被截断文件之后的项目文件不再加载。源路径标记在 `# Project instructions` 下。
sidecar 从不直接读取工作区指令。改变的根链
在下一个提示时重新创建空闲运行时;嵌套指令已解决
当相关文件工具运行时再次。解析器的超时和 fallback 是运行时保护措施;
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index 0650fd415..de3d11278 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -3761,7 +3761,8 @@ IPC 请求无法关闭。
`AGENTS.md`; `CLAUDE.md` 和 `.claude/CLAUDE.md` 是后备名称。闲着的
后续使用更改的根内容而不是重用之前的运行时。
空的、不可读的、过大的和超出根的指令文件不会阻塞
- 转牌圈;组合的 UTF-8 内容上限为 32 KiB。目标路径位于项目根之外,
+ 转牌圈;全局文件与项目链各有独立的 32 KiB UTF-8 预算,过大的全局文件不会挤掉
+ 项目条目,被截断的文件末尾带有注明来源及已加载/总字节数的提示。目标路径位于项目根之外,
或目标就是项目根本身时,文件工具会保留根链,而不是清空项目指令;
指令文件仍然只从项目根内部读取。fixture sidecar 场景验证嵌套读取应用
嵌套规则,而后续附件读取会恢复根规则且不会载入根目录外的 `AGENTS.md`。
diff --git a/packages/agent-runtime/src/project-instructions.test.ts b/packages/agent-runtime/src/project-instructions.test.ts
index 4552dc7ea..a20b64313 100644
--- a/packages/agent-runtime/src/project-instructions.test.ts
+++ b/packages/agent-runtime/src/project-instructions.test.ts
@@ -77,15 +77,30 @@ describe("loadProjectInstructions", () => {
});
});
- it("caps the complete chain at 32 KiB without splitting UTF-8 characters", async () => {
+ it("caps the project chain at 32 KiB without splitting UTF-8 characters and marks the cut", async () => {
root = await mkdtemp(join(tmpdir(), "pi-desktop-instructions-"));
await writeFile(join(root, "AGENTS.md"), "中".repeat(20_000));
const loaded = await loadProjectInstructions(root);
- expect(Buffer.byteLength(loaded!.entries[0].content, "utf8")).toBeLessThanOrEqual(
- 32 * 1024,
+ const [content, notice] = loaded!.entries[0].content.split("\n\n");
+ expect(Buffer.byteLength(content, "utf8")).toBeLessThanOrEqual(32 * 1024);
+ expect(content.endsWith("中")).toBe(true);
+ expect(notice).toBe(
+ "[PI-Desktop truncated AGENTS.md: loaded the first 32766 of 60000 bytes; the rest of this file is not in context.]",
+ );
+ });
+
+ it("does not load later project files once a truncated file exhausts the budget", async () => {
+ root = await mkdtemp(join(tmpdir(), "pi-desktop-instructions-"));
+ await mkdir(join(root, "packages"), { recursive: true });
+ await writeFile(join(root, "AGENTS.md"), "r".repeat(40 * 1024));
+ await writeFile(join(root, "packages", "AGENTS.md"), "Use package rules.");
+
+ const loaded = await loadProjectInstructions(root, "packages/index.ts");
+ expect(loaded!.entries.map((entry) => entry.source)).toEqual(["AGENTS.md"]);
+ expect(loaded!.entries[0].content).toBe(
+ `${"r".repeat(32 * 1024)}\n\n[PI-Desktop truncated AGENTS.md: loaded the first 32768 of 40960 bytes; the rest of this file is not in context.]`,
);
- expect(loaded!.entries[0].content.endsWith("中")).toBe(true);
});
it("treats missing and blank project instructions as absent", async () => {
@@ -166,14 +181,34 @@ describe("loadInstructionChain", () => {
});
});
- it("shares the 32 KiB byte budget between global and project instructions", async () => {
+ it("gives global and project instructions independent 32 KiB budgets", async () => {
root = await mkdtemp(join(tmpdir(), "pi-desktop-instructions-"));
const globalPath = join(root, "global-AGENTS.md");
await writeFile(globalPath, "a".repeat(32 * 1024));
+ await writeFile(join(root, "AGENTS.md"), "p".repeat(32 * 1024));
+
+ await expect(loadInstructionChain(root, undefined, globalPath)).resolves.toEqual({
+ entries: [
+ { source: "~/.pi/agent/AGENTS.md", content: "a".repeat(32 * 1024) },
+ { source: "AGENTS.md", content: "p".repeat(32 * 1024) },
+ ],
+ });
+ });
+
+ it("marks an oversized global file as truncated and still loads project instructions", async () => {
+ root = await mkdtemp(join(tmpdir(), "pi-desktop-instructions-"));
+ const globalPath = join(root, "global-AGENTS.md");
+ await writeFile(globalPath, "a".repeat(64 * 1024));
await writeFile(join(root, "AGENTS.md"), "Use project conventions.");
await expect(loadInstructionChain(root, undefined, globalPath)).resolves.toEqual({
- entries: [{ source: "~/.pi/agent/AGENTS.md", content: "a".repeat(32 * 1024) }],
+ entries: [
+ {
+ source: "~/.pi/agent/AGENTS.md",
+ content: `${"a".repeat(32 * 1024)}\n\n[PI-Desktop truncated ~/.pi/agent/AGENTS.md: loaded the first 32768 of 65536 bytes; the rest of this file is not in context.]`,
+ },
+ { source: "AGENTS.md", content: "Use project conventions." },
+ ],
});
});
});
diff --git a/packages/agent-runtime/src/project-instructions.ts b/packages/agent-runtime/src/project-instructions.ts
index b4ed9dd03..912151bcb 100644
--- a/packages/agent-runtime/src/project-instructions.ts
+++ b/packages/agent-runtime/src/project-instructions.ts
@@ -8,8 +8,12 @@ const INSTRUCTION_FILE_NAMES = [
"CLAUDE.md",
join(".claude", "CLAUDE.md"),
];
-const MAX_INSTRUCTION_BYTES = 32 * 1024;
+// The global file and the project chain have independent budgets so an
+// oversized global file can never starve project instructions.
+const MAX_GLOBAL_INSTRUCTION_BYTES = 32 * 1024;
+const MAX_PROJECT_INSTRUCTION_BYTES = 32 * 1024;
const GLOBAL_INSTRUCTION_PATH = join(homedir(), ".pi", "agent", "AGENTS.md");
+const GLOBAL_INSTRUCTION_SOURCE = "~/.pi/agent/AGENTS.md";
export type ProjectInstruction = {
source: string;
@@ -32,8 +36,28 @@ function normalizeStablePath(path: string): string {
return path.replace(/\\/g, "/");
}
-function limitUtf8(content: string, maxBytes: number): string {
- if (Buffer.byteLength(content, "utf8") <= maxBytes) return content;
+type LimitedInstruction = {
+ entry: ProjectInstruction;
+ /** UTF-8 bytes of file content kept, excluding any truncation notice. */
+ bytes: number;
+ truncated: boolean;
+};
+
+/**
+ * Keep at most `maxBytes` of UTF-8 content without splitting a character.
+ * A cut is never silent: the kept text is followed by a notice naming the
+ * source and the kept/total byte counts, so the model can tell the file is
+ * incomplete.
+ */
+function limitInstruction(
+ source: string,
+ content: string,
+ maxBytes: number,
+): LimitedInstruction {
+ const totalBytes = Buffer.byteLength(content, "utf8");
+ if (totalBytes <= maxBytes) {
+ return { entry: { source, content }, bytes: totalBytes, truncated: false };
+ }
let bytes = 0;
let end = 0;
for (const char of content) {
@@ -42,7 +66,13 @@ function limitUtf8(content: string, maxBytes: number): string {
bytes += charBytes;
end += char.length;
}
- return content.slice(0, end);
+ const notice = `[PI-Desktop truncated ${source}: loaded the first ${bytes} of ${totalBytes} bytes; the rest of this file is not in context.]`;
+ const kept = content.slice(0, end).trimEnd();
+ return {
+ entry: { source, content: kept ? `${kept}\n\n${notice}` : notice },
+ bytes,
+ truncated: true,
+ };
}
async function readInstruction(
@@ -50,7 +80,7 @@ async function readInstruction(
canonicalWorkspaceRoot: string,
directory: string,
remaining: number,
-): Promise<ProjectInstruction | undefined> {
+): Promise<LimitedInstruction | undefined> {
for (const name of INSTRUCTION_FILE_NAMES) {
try {
const file = join(directory, name);
@@ -58,10 +88,11 @@ async function readInstruction(
if (!isWithinRoot(canonicalWorkspaceRoot, canonicalFile)) continue;
const content = (await readFile(file, "utf8")).trim();
if (!content) continue;
- return {
- source: normalizeStablePath(relative(workspaceRoot, file) || name),
- content: limitUtf8(content, remaining),
- };
+ return limitInstruction(
+ normalizeStablePath(relative(workspaceRoot, file) || name),
+ content,
+ remaining,
+ );
} catch {
// Try the next recognized name or the next directory.
}
@@ -78,7 +109,7 @@ async function readInstruction(
export async function loadProjectInstructions(
workspaceRoot: string | null | undefined,
workspacePath?: string,
- maxBytes = MAX_INSTRUCTION_BYTES,
+ maxBytes = MAX_PROJECT_INSTRUCTION_BYTES,
): Promise<ProjectInstructions | undefined> {
if (!workspaceRoot?.trim()) return undefined;
@@ -102,37 +133,38 @@ export async function loadProjectInstructions(
let remaining = Math.max(0, maxBytes);
for (const directory of directories) {
if (remaining <= 0) break;
- const entry = await readInstruction(root, canonicalRoot, directory, remaining);
- if (!entry) continue;
- entries.push(entry);
- remaining -= Buffer.byteLength(entry.content, "utf8");
+ const loaded = await readInstruction(root, canonicalRoot, directory, remaining);
+ if (!loaded) continue;
+ entries.push(loaded.entry);
+ // A truncated file has used up the budget; closer files are not loaded.
+ if (loaded.truncated) break;
+ remaining -= loaded.bytes;
}
return entries.length > 0 ? { entries } : undefined;
}
-/** Build the complete chain: global defaults precede project instructions. */
+/**
+ * Build the complete chain: global defaults precede project instructions.
+ * The global file and the project chain are capped independently.
+ */
export async function loadInstructionChain(
workspaceRoot: string | null | undefined,
workspacePath?: string,
globalPath = GLOBAL_INSTRUCTION_PATH,
): Promise<ProjectInstructions | undefined> {
const entries: ProjectInstruction[] = [];
- let remaining = MAX_INSTRUCTION_BYTES;
try {
const content = (await readFile(globalPath, "utf8")).trim();
if (content) {
- const limited = limitUtf8(content, remaining);
- entries.push({ source: "~/.pi/agent/AGENTS.md", content: limited });
- remaining -= Buffer.byteLength(limited, "utf8");
+ entries.push(
+ limitInstruction(GLOBAL_INSTRUCTION_SOURCE, content, MAX_GLOBAL_INSTRUCTION_BYTES)
+ .entry,
+ );
}
} catch {
// A missing global file is an expected first-run state.
}
- const project = await loadProjectInstructions(
- workspaceRoot,
- workspacePath,
- remaining,
- );
+ const project = await loadProjectInstructions(workspaceRoot, workspacePath);
return entries.length || project?.entries.length
? { entries: [...entries, ...(project?.entries ?? [])] }
: undefined;