test(guidance): consolidate search and locator contracts (#13312)

This commit is contained in:
morluto authored and GitHub committed 2026-11-22 04:08:28 +00:00
1 parent 664c0c5267
commit ae4e0c83dd
4 files changed
+238 -407

No files matched your search

@@ -1,6 +1,5 @@
import { expect, it } from "vitest";
import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js";
import { readGuidanceSectionInputSchema } from "../contracts/guidanceContracts.js";
import { MANAGED_SKILL_FILES } from "./SetupSkill.js";
import {
readGuidanceSectionWithReader,
@@ -22,16 +21,22 @@ it("does not substitute a common domain word for an unknown query subject", asyn
await resources.close();
});
it.each([
["## C#", "C#"],
["## C# ###", "C#"],
["## C\\#", "C\\#"],
[" ## C#", "C#"],
["## C# \t ### \t", "C#"],
["## ###", ""],
])("preserves the source title in %s", async (line, heading) => {
it("preserves ATX titles and retrieves colliding and long headings by locator", async () => {
const resources = new ArtifactResourceScope();
const source = reader(`${line}\nneedle instructions\n`);
const long = `needle ${"x".repeat(3000)}`;
const titles = [
["## C#", "C#"],
["## C# ###", "C#"],
["## C\\#", "C\\#"],
[" ## C#", "C#"],
["## C# \t ### \t", "C#"],
["## ###", ""],
[`## ${long}`, long],
] as const;
const sections = titles.map(
([line], index) => `${line}\nneedle recipe ${index}\n`,
);
const source = reader(sections.join("\n"));
const result = await searchGuidanceWithReader(
{ query: "needle" },
source,
@@ -39,40 +44,36 @@ it.each([
);
if (!result.ok || result.value.status !== "matches")
throw new Error("Expected matching documentation");
expect(result.value.matches[0]?.heading).toBe(heading);
const value = await readGuidanceSectionWithReader(
{ locator: result.value.matches[0]?.locator },
source,
resources,
const matches = result.value.matches;
expect(matches.map(({ heading }) => heading).sort()).toEqual(
titles.map(([, heading]) => heading).sort(),
);
expect(new Set(matches.map(({ locator }) => locator)).size).toBe(
titles.length,
);
expect(value).toMatchObject({
ok: true,
value: { status: "section", heading },
});
await resources.close();
});
it("issues readable locators independently of heading length", async () => {
const resources = new ArtifactResourceScope();
const heading = `needle ${"x".repeat(3000)}`;
const source = reader(`## ${heading}\nInstructions\n`);
const result = await searchGuidanceWithReader(
{ query: "needle" },
source,
resources,
);
if (!result.ok || result.value.status !== "matches")
throw new Error("Expected match");
const locator = result.value.matches[0]?.locator;
expect(readGuidanceSectionInputSchema.safeParse({ locator }).success).toBe(
true,
);
expect(
await readGuidanceSectionWithReader({ locator }, source, resources),
).toMatchObject({
ok: true,
value: { status: "section", heading },
});
for (const index of [0, 1, titles.length - 1]) {
const match = matches.find(({ context, heading }) =>
index === titles.length - 1
? heading === long
: context.includes(`needle recipe ${index}`),
);
if (match === undefined) throw new Error("Expected the selected section");
expect(
await readGuidanceSectionWithReader(
{ locator: match.locator },
source,
resources,
),
).toMatchObject({
ok: true,
value: {
status: "section",
heading: titles[index]?.[1],
content: sections[index]?.trim(),
},
});
}
await resources.close();
});
+71 -194
View File
@@ -1,9 +1,5 @@
import { expect, it } from "vitest";
import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js";
import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import { MANAGED_SKILL_FILES } from "./SetupSkill.js";
import { searchGuidanceOutputSchema } from "../contracts/guidanceContracts.js";
import { RetainedRegularFileCleanupFailure } from "../process/RegularFileRead.js";
import {
readGuidanceSectionWithReader,
searchGuidanceWithReader,
@@ -20,44 +16,9 @@ const valueOf = async (
) => {
const result = await request;
if (!result.ok) throw result.error;
return searchGuidanceOutputSchema.parse(result.value);
return result.value;
};
it("ranks a focused JavaScript module section and retrieves it with its locator", async () => {
const resources = new ArtifactResourceScope();
const result = await valueOf(
searchGuidanceWithReader(
{ query: "exact JavaScript module" },
guideFixture,
resources,
),
);
expect(result.status).toBe("matches");
if (result.status !== "matches") throw new Error("Expected guide matches");
expect(result.matches[0]).toMatchObject({
guide: "references/javascript-applications.md",
heading: "Read a module without repeating analysis",
matched_terms: ["exact", "javascript", "module"],
context: expect.stringContaining("javascript-module"),
});
const selected = result.matches[0];
if (selected === undefined) throw new Error("Expected selected guidance");
const retrieved = await readGuidanceSectionWithReader(
{ locator: selected.locator },
guideFixture,
resources,
);
if (!retrieved.ok) throw retrieved.error;
expect(retrieved.value).toMatchObject({
status: "section",
source: "installed_rea_guidance",
guide: selected.guide,
heading: selected.heading,
locator: selected.locator,
content: expect.stringContaining('"node_id":"module:main.js"'),
});
});
it("returns an honest no-match result and rejects empty queries and invalid bounds", async () => {
const resources = new ArtifactResourceScope();
expect(
@@ -73,18 +34,6 @@ it("returns an honest no-match result and rejects empty queries and invalid boun
total_matches: 0,
message: expect.stringContaining("does not indicate"),
});
expect(
await valueOf(
searchGuidanceWithReader(
{ query: "how do I frobnicate qzxv" },
guideFixture,
resources,
),
),
).toMatchObject({
status: "no_matches",
total_matches: 0,
});
expect(
await searchGuidanceWithReader({ query: " " }, guideFixture, resources),
).toMatchObject({ ok: false });
@@ -120,74 +69,77 @@ it("does not treat Markdown headings inside fenced code as section boundaries",
);
});
it("refuses an oversized guide bundle instead of indexing partial content", async () => {
it("refuses a combined guide bundle that exceeds the byte allowance", async () => {
const perFile = "x".repeat(1_048_576);
const result = await searchGuidanceWithReader(
{ query: "module" },
async (path) =>
path === "SKILL.md" ? "x".repeat(4_194_305) : guideFixture(path),
async (path) => (path === "SKILL.md" ? "# Module guidance" : perFile),
new ArtifactResourceScope(),
);
expect(result).toMatchObject({
ok: true,
value: { status: "bundle_unavailable" },
value: {
status: "bundle_unavailable",
message: expect.stringContaining("4 MiB"),
},
});
});
it("paginates deterministically without losing, duplicating, or reordering matches", async () => {
const readGuide = guideFixture;
const first = await valueOf(
searchGuidanceWithReader(
{ query: "module", limit: 2 },
readGuide,
new ArtifactResourceScope(),
),
);
const repeat = await valueOf(
searchGuidanceWithReader(
{ query: "module", limit: 2 },
readGuide,
new ArtifactResourceScope(),
),
);
expect(first).toEqual(repeat);
if (first.status !== "matches") throw new Error("Expected guide matches");
expect(first.has_more).toBe(true);
const all = first.matches.map(({ locator }) => locator);
let cursor = first.next_cursor;
while (cursor !== undefined) {
const page = await valueOf(
searchGuidanceWithReader(
{ query: "module", limit: 2, cursor },
readGuide,
new ArtifactResourceScope(),
),
);
if (page.status !== "matches") throw new Error("Expected guide matches");
all.push(...page.matches.map(({ locator }) => locator));
cursor = page.next_cursor;
}
it("walks the exact ordered guidance results with finite continuation", async () => {
const resources = new ArtifactResourceScope();
const complete = await valueOf(
searchGuidanceWithReader(
{ query: "module", limit: 20 },
readGuide,
new ArtifactResourceScope(),
),
);
if (complete.status !== "matches") throw new Error("Expected guide matches");
expect(new Set(all).size).toBe(all.length);
expect(all).toEqual(complete.matches.map(({ locator }) => locator));
});
it("rejects malformed locators and reports changed or missing installed guides", async () => {
const resources = new ArtifactResourceScope();
const search = await valueOf(
searchGuidanceWithReader(
{ query: "exact JavaScript module" },
guideFixture,
resources,
),
);
if (search.status !== "matches") throw new Error("Expected guide matches");
if (complete.status !== "matches") throw new Error("Expected guide matches");
expect(complete.has_more).toBe(false);
expect(complete.matches.length).toBeGreaterThan(2);
const limit = 2;
let cursor: string | undefined;
for (let offset = 0; offset < complete.matches.length; offset += limit) {
if (offset > 0 && cursor === undefined)
throw new Error("Expected the next guidance page");
const page = await valueOf(
searchGuidanceWithReader(
{ query: "module", limit, cursor },
guideFixture,
resources,
),
);
if (page.status !== "matches") throw new Error("Expected guide matches");
const hasMore = offset + limit < complete.matches.length;
expect(page).toMatchObject({
matches: complete.matches.slice(offset, offset + limit),
total_matches: complete.matches.length,
offset,
has_more: hasMore,
});
if (hasMore) expect(page.next_cursor).toEqual(expect.any(String));
else expect(page).not.toHaveProperty("next_cursor");
cursor = page.next_cursor;
}
});
it("rejects malformed locators and reports changed or missing installed guides", async () => {
const resources = new ArtifactResourceScope();
const first = await valueOf(
searchGuidanceWithReader(
{ query: "module", limit: 1 },
guideFixture,
resources,
),
);
if (
first.status !== "matches" ||
first.next_cursor === undefined ||
first.matches[0] === undefined
)
throw new Error("Expected a section and continuation token");
const { locator, guide } = first.matches[0];
const cursor = first.next_cursor;
expect(
await readGuidanceSectionWithReader(
{ locator: "../../outside.md" },
@@ -195,33 +147,23 @@ it("rejects malformed locators and reports changed or missing installed guides",
resources,
),
).toMatchObject({ ok: false });
const changedReader = async (path: string) =>
`${await guideFixture(path)}\nChanged after search.\n`;
const stale = await readGuidanceSectionWithReader(
{ locator: search.matches[0]?.locator },
changedReader,
resources,
);
expect(stale).toMatchObject({ ok: true, value: { status: "stale_locator" } });
const firstPage = await valueOf(
searchGuidanceWithReader(
{ query: "module", limit: 1 },
guideFixture,
resources,
),
);
if (firstPage.status !== "matches" || firstPage.next_cursor === undefined)
throw new Error("Expected a continuation token");
const changedReader = async (path: string) => {
const text = await guideFixture(path);
return path === guide ? text : `${text}\nChanged after search.\n`;
};
expect(
await readGuidanceSectionWithReader({ locator }, changedReader, resources),
).toMatchObject({ ok: true, value: { status: "stale_locator" } });
expect(
await searchGuidanceWithReader(
{ query: "module", limit: 1, cursor: firstPage.next_cursor },
{ query: "module", limit: 1, cursor },
changedReader,
resources,
),
).toMatchObject({ ok: true, value: { status: "stale_continuation" } });
expect(
await searchGuidanceWithReader(
{ query: "different query", cursor: firstPage.next_cursor },
{ query: "different query", cursor },
guideFixture,
resources,
),
@@ -233,6 +175,11 @@ it("rejects malformed locators and reports changed or missing installed guides",
resources,
),
).toMatchObject({ ok: false });
resources.retain({
kind: "lease",
resource: "unrelated completed cleanup",
lease: { release: async () => undefined },
});
const missingReader = async (): Promise<string> => {
throw Object.assign(new Error("missing"), { code: "ENOENT" });
};
@@ -244,80 +191,10 @@ it("rejects malformed locators and reports changed or missing installed guides",
),
).toMatchObject({ ok: true, value: { status: "bundle_unavailable" } });
expect(
await readGuidanceSectionWithReader(
{ locator: search.matches[0]?.locator },
missingReader,
resources,
),
await readGuidanceSectionWithReader({ locator }, missingReader, resources),
).toMatchObject({ ok: true, value: { status: "bundle_unavailable" } });
});
it("returns cleanup failures separately and retains their owner until retry succeeds", async () => {
const resources = new ArtifactResourceScope();
let failRelease = true;
const failure = new RegularFileCleanupFailure({
path: "guidance file handle",
owner: {
close: async () => {
if (failRelease) throw new Error("descriptor close failed");
},
} as never,
outcome: { kind: "failed", cause: new Error("guide read failed") },
cleanupCause: new Error("descriptor close failed"),
});
const retainedFailure = new RetainedRegularFileCleanupFailure(failure);
resources.retain(retainedFailure.cleanupOwner);
const result = await searchGuidanceWithReader(
{ query: "module" },
async () => {
throw retainedFailure;
},
resources,
);
if (result.ok) throw new Error("Expected a retained cleanup failure");
expect(result.error).toMatchObject({ cleanupIncomplete: true });
expect(result.error.cleanupResources).toEqual(["guidance file handle"]);
expect(resources.hasPending).toBe(true);
failRelease = false;
await resources.close();
expect(resources.hasPending).toBe(false);
expect(result.error.cleanupIncomplete).toBe(false);
expect(result.error.cleanupResources).toEqual([]);
const freshResources = new ArtifactResourceScope();
freshResources.retain({
kind: "lease",
resource: "unrelated pending resource",
lease: { release: async () => undefined },
});
expect(
await searchGuidanceWithReader(
{ query: "module" },
async () => {
throw new Error("guide is unreadable");
},
freshResources,
),
).toMatchObject({
ok: true,
value: { status: "bundle_unavailable" },
});
await freshResources.close();
});
it("uses only the fixed managed guide inventory for injected reads", async () => {
const requested: string[] = [];
await searchGuidanceWithReader(
{ query: "module" },
async (path) => {
requested.push(path);
return guideFixture(path);
},
new ArtifactResourceScope(),
);
expect(requested).toEqual([...MANAGED_SKILL_FILES]);
});
const nestedGuide = [
"# Native guide",
"",
-47
View File
@@ -5,53 +5,6 @@ import {
searchGuidance,
} from "../../src/application/GuidanceAccess.js";
it("finds and retrieves the selected section from the generated package bundle", async () => {
const resources = new ArtifactResourceScope();
try {
const result = await searchGuidance(
{ query: "exact JavaScript module" },
resources,
);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
status: "matches",
source: "installed_rea_guidance",
package: expect.stringMatching(/^rea-agents@/u),
});
if (result.value.status !== "matches")
throw new Error("Expected guidance matches");
const match = result.value.matches.find(
({ heading }) => heading === "Read a module without repeating analysis",
);
expect(match).toBeDefined();
expect(result.value.matches[0]?.heading).toBe(
"Read a module without repeating analysis",
);
expect(match).toMatchObject({
guide: "references/javascript-applications.md",
matched_terms: expect.arrayContaining(["exact", "javascript", "module"]),
context: expect.stringContaining("javascript-module"),
});
if (match === undefined) throw new Error("Expected selected guidance");
const retrieved = await readGuidanceSection(
{ locator: match.locator },
resources,
);
if (!retrieved.ok) throw retrieved.error;
expect(retrieved.value).toMatchObject({
status: "section",
source: "installed_rea_guidance",
guide: match.guide,
heading: match.heading,
locator: match.locator,
content: expect.stringContaining("node_id"),
});
} finally {
await resources.close();
}
});
it("finds focused installed guidance for switching providers with annotations", async () => {
const resources = new ArtifactResourceScope();
try {
+124 -124
View File
@@ -1,22 +1,16 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { afterEach, expect, it } from "vitest";
import { expect, onTestFinished } from "vitest";
import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js";
import {
readGuidanceSectionOutputSchema,
searchGuidanceInputSchema,
searchGuidanceOutputSchema,
} from "../../../src/contracts/guidanceContracts.js";
import { EvidenceMcpServer } from "../../../src/server/EvidenceMcpServer.js";
import { registerServiceTools } from "../../../src/server/serviceToolBindings.js";
import { silentLogger } from "../../../src/logger.js";
import { ToolResultDelivery } from "../../../src/server/ToolResultDelivery.js";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
const open: {
client: Client;
server: EvidenceMcpServer;
resources: ArtifactResourceScope;
}[] = [];
const guidanceOutput = <T>(
schema: { parse(value: unknown): T },
value: unknown,
@@ -27,120 +21,126 @@ const guidanceOutput = <T>(
return schema.parse(value.result);
return schema.parse(value);
};
afterEach(async () => {
await Promise.all(
open
.splice(0)
.flatMap(({ client, server, resources }) => [
client.close(),
server.close(),
resources.close(),
]),
);
});
it("advertises strict provider-free contracts and returns packaged guide results over MCP", async () => {
const server = new EvidenceMcpServer(
{ name: "guidance-test", version: "1" },
{ capabilities: { tools: { listChanged: true } } },
undefined,
new ToolResultDelivery(1024 * 1024),
);
const resources = new ArtifactResourceScope();
const admitted: string[] = [];
// Guidance is provider-free: it answers without entering analysis
// admission, even when the server supplies one.
registerServiceTools(
server,
{ guidance: resources },
{
logger: silentLogger,
withAdmittedAnalysis: (operationName) => {
admitted.push(operationName);
return Promise.reject(new Error("guidance entered analysis admission"));
mcpTest(
"advertises provider-free tools and retrieves the best packaged match",
async ({ mcp }) => {
const server = new EvidenceMcpServer(
{ name: "guidance-test", version: "1" },
{ capabilities: { tools: { listChanged: true } } },
undefined,
new ToolResultDelivery(1024 * 1024),
);
const resources = new ArtifactResourceScope();
onTestFinished(() => resources.close());
const admitted: string[] = [];
// Guidance is provider-free: it answers without entering analysis
// admission, even when the server supplies one.
registerServiceTools(
server,
{ guidance: resources },
{
logger: silentLogger,
withAdmittedAnalysis: (operationName) => {
admitted.push(operationName);
return Promise.reject(
new Error("guidance entered analysis admission"),
);
},
},
},
);
const client = new Client(
{ name: "guidance-client", version: "1" },
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
open.push({ client, server, resources });
);
const client = await mcp.connect(server);
const listed = await client.listTools();
expect(listed.tools.map(({ name }) => name)).toEqual(
expect.arrayContaining(["search_guidance", "read_guidance_section"]),
);
expect(
searchGuidanceInputSchema.safeParse({
query: "module",
unexpected: true,
}).success,
).toBe(false);
const invalidLocator = await client.callTool({
name: "read_guidance_section",
arguments: { locator: "../../outside.md" },
});
expect(invalidLocator.isError).toBe(true);
const invalidLimit = await client.callTool({
name: "search_guidance",
arguments: { query: "module", limit: 21 },
});
expect(invalidLimit.isError).toBe(true);
const response = await client.callTool({
name: "search_guidance",
arguments: { query: "exact JavaScript module" },
});
expect(response.isError).not.toBe(true);
const parsed = guidanceOutput(
searchGuidanceOutputSchema,
response.structuredContent,
);
expect(parsed).toMatchObject({
status: "matches",
source: "installed_rea_guidance",
});
if (parsed.status !== "matches") throw new Error("Expected guidance matches");
const selected = parsed.matches.find(
({ heading }) => heading === "Read a module without repeating analysis",
);
expect(selected).toBeDefined();
const section = await client.callTool({
name: "read_guidance_section",
arguments: { locator: selected?.locator },
});
expect(section.isError).not.toBe(true);
expect(
guidanceOutput(readGuidanceSectionOutputSchema, section.structuredContent),
).toMatchObject({
status: "section",
heading: selected?.heading,
source: "installed_rea_guidance",
});
const firstPage = await client.callTool({
name: "search_guidance",
arguments: { query: "module", limit: 1 },
});
const firstResult = guidanceOutput(
searchGuidanceOutputSchema,
firstPage.structuredContent,
);
if (firstResult.status !== "matches" || firstResult.next_cursor === undefined)
throw new Error("Expected a guidance continuation token");
const nextPage = await client.callTool({
name: "search_guidance",
arguments: {
query: "module",
limit: 1,
cursor: firstResult.next_cursor,
},
});
expect(
guidanceOutput(searchGuidanceOutputSchema, nextPage.structuredContent),
).toMatchObject({ status: "matches", offset: 1 });
expect(admitted).toEqual([]);
});
const listed = await client.listTools();
expect(listed.tools.map(({ name }) => name)).toEqual(
expect.arrayContaining(["search_guidance", "read_guidance_section"]),
);
const invalidLocator = await client.callTool({
name: "read_guidance_section",
arguments: { locator: "../../outside.md" },
});
expect(parseMcpToolError(invalidLocator).error).toMatchObject({
code: "invalid_request",
details: { issues: [{ path: ["locator"], reason: "invalid_value" }] },
});
const invalidSearch = await client.callTool({
name: "search_guidance",
arguments: { query: "module", limit: 21, unexpected: true },
});
expect(parseMcpToolError(invalidSearch).error).toMatchObject({
code: "invalid_request",
details: {
issues: [
{ path: ["limit"], reason: "out_of_range", maximum: 20 },
{ path: ["unexpected"], reason: "unknown_argument" },
],
},
});
const response = await client.callTool({
name: "search_guidance",
arguments: { query: "exact JavaScript module" },
});
expect(response.isError).not.toBe(true);
const parsed = guidanceOutput(
searchGuidanceOutputSchema,
response.structuredContent,
);
if (parsed.status !== "matches")
throw new Error("Expected guidance matches");
expect(parsed).toMatchObject({
source: "installed_rea_guidance",
package: expect.stringMatching(/^rea-agents@/u),
});
const [selected] = parsed.matches;
expect(selected).toMatchObject({
guide: "references/javascript-applications.md",
heading: "Read a module without repeating analysis",
matched_terms: ["exact", "javascript", "module"],
context: expect.stringContaining("javascript-module"),
});
if (selected === undefined)
throw new Error("Expected the selected section");
const section = await client.callTool({
name: "read_guidance_section",
arguments: { locator: selected.locator },
});
expect(section.isError).not.toBe(true);
expect(
guidanceOutput(
readGuidanceSectionOutputSchema,
section.structuredContent,
),
).toMatchObject({
status: "section",
guide: selected.guide,
heading: selected.heading,
locator: selected.locator,
source: "installed_rea_guidance",
content: expect.stringContaining("node_id"),
});
const firstPage = await client.callTool({
name: "search_guidance",
arguments: { query: "module", limit: 1 },
});
const firstResult = guidanceOutput(
searchGuidanceOutputSchema,
firstPage.structuredContent,
);
if (
firstResult.status !== "matches" ||
firstResult.next_cursor === undefined
)
throw new Error("Expected a guidance continuation token");
const nextPage = await client.callTool({
name: "search_guidance",
arguments: {
query: "module",
limit: 1,
cursor: firstResult.next_cursor,
},
});
expect(
guidanceOutput(searchGuidanceOutputSchema, nextPage.structuredContent),
).toMatchObject({ status: "matches", offset: 1 });
expect(admitted).toEqual([]);
},
);