Skip to content

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

test(agent-runtime): cover out-of-root instruction fallback

vastsa6ab074e9a702
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7498a29cc..a8508fce2 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -6502,9 +6502,10 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
1. Start an Agent-mode conversation and submit a task covered by the root
instruction.
2. Let the agent read or edit `packages/api/handler.ts`.
- 3. Add `packages/api/AGENTS.override.md`, then have the agent access another
+ 3. Have the agent read an attachment outside the project root.
+ 4. Add `packages/api/AGENTS.override.md`, then have the agent access another
file in that directory.
- 4. Edit the root instruction while the session is idle, then submit a
+ 5. Edit the root instruction while the session is idle, then submit a
follow-up task.
- **Expected**: The initial runtime receives the root chain. Before the file
tool executes, the nested instruction is appended after its root source and
@@ -6515,7 +6516,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
the turn; combined UTF-8 content is capped at 32 KiB. 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. If path-specific resolution exceeds its
+ read only from inside the root. A fixture-backed sidecar run verifies that a
+ nested read applies nested rules and a following attachment read restores the
+ root rules without loading an outside `AGENTS.md`. If path-specific resolution exceeds its
two-second deadline or the host is unavailable, the
file tool continues with the base chain and does not retain a sibling
directory's rules. Repeated file tools in the same directory during one
@@ -6526,9 +6529,10 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
- **Specs linked**: `03-runtime/02-agent-runtime.md`
- **Acceptance**: C (chat/stream), F (persistence)
- **Milestone**: M5
-- **Status**: Partially automated (`project-instructions.test.ts`,
- `runtime.test.ts`); full
- provider/UI journey Draft
+- **Status**: Resolver and runtime behavior are automated in
+ `project-instructions.test.ts` and `runtime.test.ts`; the fixture-backed
+ sidecar scenario runs through `pnpm test:e2e:hosted-search`. The broader full
+ provider/UI journey remains Draft.
#### E2E-AGENTS-002: Global settings and project menus manage instruction files
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 b0e0086e7..ba38e8c94 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
@@ -3749,9 +3749,10 @@ IPC 请求无法关闭。
1. 启动Agent模式对话并提交root覆盖的任务
指示。
2. 让代理读取或编辑 `packages/api/handler.ts`。
- 3. 添加 `packages/api/AGENTS.override.md`,然后让代理访问另一个
+ 3. 让代理读取项目根目录之外的附件。
+ 4. 添加 `packages/api/AGENTS.override.md`,然后让代理访问另一个
该目录中的文件。
- 4. 在会话空闲时编辑 root 指令,然后提交
+ 5. 在会话空闲时编辑 root 指令,然后提交
后续任务。
- **预期**:初始运行时接收根链。文件之前
工具执行时,嵌套指令将附加在其根源之后,并且
@@ -3761,7 +3762,9 @@ IPC 请求无法关闭。
空的、不可读的、过大的和超出根的指令文件不会阻塞
转牌圈;组合的 UTF-8 内容上限为 32 KiB。目标路径位于项目根之外,
或目标就是项目根本身时,文件工具会保留根链,而不是清空项目指令;
- 指令文件仍然只从项目根内部读取。如果路径特定
+ 指令文件仍然只从项目根内部读取。fixture sidecar 场景验证嵌套读取应用
+ 嵌套规则,而后续附件读取会恢复根规则且不会载入根目录外的 `AGENTS.md`。
+ 如果路径特定
分辨率超过其两秒期限或主机不可用,则
文件工具继续使用基础链并且不保留同级链
目录的规则。同一目录中的重复文件工具一次
@@ -3772,9 +3775,9 @@ IPC 请求无法关闭。
- **链接规格**:`03-runtime/02-agent-runtime.md`
- **接受**:C (chat/stream),F(持久)
- **里程碑**:M5
-- **状态**:部分自动化(`project-instructions.test.ts`,
- `runtime.test.ts`);满
- provider/UI 旅程草案
+- **状态**:解析器与运行时由 `project-instructions.test.ts` 和
+ `runtime.test.ts` 自动化;fixture sidecar 场景通过
+ `pnpm test:e2e:hosted-search` 运行。完整 provider/UI 旅程仍为草案。
#### E2E-AGENTS-002:全局设置和项目菜单管理指令文件
diff --git a/scripts/e2e-hosted-search.mjs b/scripts/e2e-hosted-search.mjs
index 78178e29d..d2fc25539 100644
--- a/scripts/e2e-hosted-search.mjs
+++ b/scripts/e2e-hosted-search.mjs
@@ -9,6 +9,7 @@ import { copyFile, cp, mkdir, mkdtemp, readFile, readdir, stat, writeFile } from
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { parseArgs } from "node:util";
+import { pathToFileURL } from "node:url";
import { isolatedEnv } from "./e2e/hosted-search-sidecar.mjs";
import { runScenarios } from "./e2e/hosted-search-scenarios.mjs";
@@ -89,10 +90,10 @@ const { values } = parseArgs({ options: {
} });
if (values.help) {
console.log(`Usage: node scripts/e2e-hosted-search.mjs [--bundle PATH] [--timeout-ms 15000]
-Default: pnpm --filter @pi-desktop/shared build, then @pi-desktop/agent-runtime bundle.
---bundle: skip rebuilding and run that explicit artifact, retaining its SHA-256.
+Default: build shared, agent-runtime, and the production sidecar bundle.
+--bundle: build the resolver module and run that explicit sidecar artifact.
Evidence and isolated homes stay under PI_SCRATCH_DIR or mkdtemp(os.tmpdir()).
-Seven cases: next prompt, Read, instruction change, real Task/TaskWait, persisted restore, two invalid-history cases.
+Eight cases: next prompt, Read, instruction change, out-of-project instruction fallback, real Task/TaskWait, persisted restore, two invalid-history cases.
Files are retained for inspection; no automatic deletion and no dependency installation.
Reviewed source, patches, and lock metadata are fingerprinted before the build and again
when the run ends; any change between the two fails the run.`);
@@ -173,17 +174,29 @@ when the run ends; any change between the two fails the run.`);
evidence.lockfileSha256 = await hash(join(root, "pnpm-lock.yaml"));
evidence.head = git("rev-parse", "HEAD");
evidence.statusBefore = git("status", "--short");
- evidence.build = values.bundle ? "explicit supplied artifact; not rebuilt by this invocation" : "production package build + bundle";
+ evidence.build = values.bundle ? "agent-runtime resolver build + explicit supplied artifact" : "shared + agent-runtime builds and production bundle";
evidence.sourceFingerprintBefore = await fingerprint();
assert.ok(evidence.head !== "unavailable" && evidence.sourceFingerprintBefore, "build source identity is unavailable");
if (!values.bundle) {
- for (const [pkg, script] of [["@pi-desktop/shared", "build"], ["@pi-desktop/agent-runtime", "bundle"]]) {
+ for (const [pkg, script, label] of [
+ ["@pi-desktop/shared", "build", "shared-build"],
+ ["@pi-desktop/agent-runtime", "build", "agent-runtime-build"],
+ ["@pi-desktop/agent-runtime", "bundle", "sidecar-bundle"],
+ ]) {
const args = ["--filter", pkg, script];
console.log(`Build: pnpm ${args.join(" ")}`);
const output = runPnpm(args);
- await writeFile(join(dir, `${script}.log`), output);
+ await writeFile(join(dir, `${label}.log`), output);
}
+ } else {
+ const args = ["--filter", "@pi-desktop/agent-runtime", "build"];
+ console.log(`Build: pnpm ${args.join(" ")}`);
+ const output = runPnpm(args);
+ await writeFile(join(dir, "agent-runtime-build.log"), output);
}
+ const instructionModule = await import(pathToFileURL(
+ join(root, "packages/agent-runtime/dist/project-instructions.js"),
+ ).href);
const source = resolve(root, values.bundle ?? "packages/agent-runtime/dist-bundle/sidecar.js");
const bundleDirectory = join(dir, "artifact");
evidence.bundleSource = source;
@@ -197,7 +210,7 @@ when the run ends; any change between the two fails the run.`);
evidence.results = await runScenarios(bundle, dir, timeoutMs, (result) => {
console.log(`${result.passed ? "PASS" : "FAIL"} ${result.name} (${result.requests} provider requests)`);
if (!result.passed) console.error(result.error);
- });
+ }, instructionModule.loadInstructionChain);
assert.equal(await bundleArtifactHash(bundle), evidence.sha256, "executed snapshot was modified");
// The snapshot protects execution; qualification also requires the source
// artifact and every relative chunk to remain stable during the run.
diff --git a/scripts/e2e/hosted-search-scenarios.mjs b/scripts/e2e/hosted-search-scenarios.mjs
index 4d827fea6..5c79ea1a9 100644
--- a/scripts/e2e/hosted-search-scenarios.mjs
+++ b/scripts/e2e/hosted-search-scenarios.mjs
@@ -1,14 +1,14 @@
import assert from "node:assert/strict";
import { mkdir, readFile, writeFile } from "node:fs/promises";
-import { join } from "node:path";
+import { join, resolve } from "node:path";
import { OfflineSidecar, fixtureHost } from "./hosted-search-sidecar.mjs";
import { assertReplay, functionResult, providerConfig, SEARCH_ITEM, startProvider } from "./hosted-search-provider.mjs";
-function parameters(baseUrl, dir, sessionId) {
+function parameters(baseUrl, dir, sessionId, projectPath = dir) {
return {
sessionId, mode: "agent", thinkingLevel: "off", infiniteProviderRetry: false,
commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
- provider: providerConfig(baseUrl), scratchDir: dir, projectPath: dir,
+ provider: providerConfig(baseUrl), scratchDir: dir, projectPath,
pluginTools: [], pluginSkills: [], trustedExtensions: [],
};
}
@@ -62,7 +62,7 @@ async function scenario(bundle, root, name, timeoutMs, handler, run) {
}
}
-export async function runScenarios(bundle, root, timeoutMs, report) {
+export async function runScenarios(bundle, root, timeoutMs, report, loadInstructionChain) {
const results = [];
const run = async (...args) => {
const result = await scenario(bundle, root, args[0], timeoutMs, ...args.slice(1));
@@ -113,6 +113,65 @@ export async function runScenarios(bundle, root, timeoutMs, report) {
});
}
+ const attachmentPath = join(root, "project-instructions-outside-target", "outside", "attachment.txt");
+ await run("project-instructions-outside-target", (body, requests) => {
+ const input = JSON.stringify(body.input);
+ if (requests.length === 1) {
+ assertTool(body, "Read");
+ return { tool: { name: "Read", args: { path: "nested/fixture.txt" } } };
+ }
+ if (requests.length === 2) {
+ assert.match(input, /OFFLINE_PROJECT_ROOT_RULE/);
+ assert.match(input, /OFFLINE_NESTED_RULE/);
+ assert.doesNotMatch(input, /OFFLINE_OUTSIDE_RULE/);
+ assert.match(functionResult(body, "Read"), /OFFLINE_NESTED_CONTENT/);
+ return { tool: { name: "Read", args: { path: attachmentPath } } };
+ }
+ assert.equal(requests.length, 3, "outside-target Read must continue without retry");
+ assert.match(input, /OFFLINE_PROJECT_ROOT_RULE/);
+ assert.doesNotMatch(input, /OFFLINE_NESTED_RULE|OFFLINE_OUTSIDE_RULE/);
+ assert.match(input, /OFFLINE_ATTACHMENT_CONTENT/);
+ return { text: "PROJECT_ROOT_INSTRUCTIONS_RETAINED" };
+ }, async ({ provider, start, dir }) => {
+ assert.equal(typeof loadInstructionChain, "function", "the production instruction resolver must be built");
+ const projectRoot = join(dir, "project");
+ const outside = join(dir, "outside");
+ const nestedFile = join(projectRoot, "nested", "fixture.txt");
+ const attachmentFile = join(outside, "attachment.txt");
+ const globalPath = join(dir, "global-AGENTS.md");
+ await mkdir(join(projectRoot, "nested"), { recursive: true });
+ await mkdir(outside, { recursive: true });
+ await writeFile(join(projectRoot, "AGENTS.md"), "OFFLINE_PROJECT_ROOT_RULE: keep project constraints.");
+ await writeFile(join(projectRoot, "nested", "AGENTS.md"), "OFFLINE_NESTED_RULE: follow nested constraints.");
+ await writeFile(join(outside, "AGENTS.md"), "OFFLINE_OUTSIDE_RULE: never load this file.");
+ await writeFile(nestedFile, "OFFLINE_NESTED_CONTENT");
+ await writeFile(attachmentFile, "OFFLINE_ATTACHMENT_CONTENT");
+
+ const baseHost = fixtureHost();
+ const host = async (method, params) => {
+ if (method === "project.instructions.resolve") {
+ return loadInstructionChain(projectRoot, params.path, globalPath);
+ }
+ if (method === "tools.execute") {
+ assert.equal(params.toolName, "Read");
+ return { ok: true, content: await readFile(resolve(projectRoot, params.args.path), "utf8") };
+ }
+ return baseHost(method, params);
+ };
+ const sidecar = await start("runtime", host);
+ await sidecar.prompt(
+ parameters(provider.baseUrl, dir, "outside-target", projectRoot),
+ "Read a nested source file, then inspect an attachment outside the project.",
+ );
+ assertText(sidecar, "PROJECT_ROOT_INSTRUCTIONS_RETAINED");
+ const instructionCalls = sidecar.hostCalls.filter((call) => call.method === "project.instructions.resolve");
+ assert.equal(instructionCalls.length, 2);
+ assert.equal(instructionCalls[0]?.params.path, "nested/fixture.txt");
+ assert.equal(instructionCalls[1]?.params.path, attachmentPath);
+ assert.equal(sidecar.hostCalls.filter((call) => call.method === "tools.execute").length, 2);
+ assert.equal(provider.requests.length, 3);
+ });
+
let parentRequests = 0;
let delegateRequests = 0;
await run("search-task-delegation", (body) => {