Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/outpost/ai/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export {
supportReplyDetails,
} from './support-reply.js';
export type { SupportReply } from './support-reply.js';
export type { SearchTool } from './pathfinder.js';
export type { SearchTool, PathfinderSearchOutcome } from './pathfinder.js';
export { PathfinderClient } from './pathfinder.js';
export { ResponseGenerator, GROUNDING_RULES, SYSTEM_PROMPT_PREFIX } from './generator.js';
export { ConfidenceScorer } from './confidence.js';
Expand Down
89 changes: 89 additions & 0 deletions packages/outpost/ai/src/pathfinder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,58 @@ describe('PathfinderClient', () => {

await expect(client.searchCode({ query: 'x' })).resolves.toEqual([]);
});

it('keeps parseable code hits when a repository header is missing', async () => {
mockConnect();
mockFetch.mockResolvedValueOnce(
mkResp({
body: jsonRpc({
content: [
{
type: 'text',
text: 'SNIPPET 1\nPATH: packages/foo.ts\nCONTENT:\n1 | export const x = 1;',
},
],
}),
}),
);

await expect(client.searchCodeWithStatus({ query: 'x' })).resolves.toMatchObject({
results: [{ title: 'packages/foo.ts', sourceUrl: undefined }],
degraded: false,
});
});

it('distinguishes a failed code search from a successful empty search', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
mockConnect();
mockFetch.mockResolvedValueOnce(
mkResp({
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
error: { message: 'index unavailable' },
}),
}),
);

await expect(client.searchCodeWithStatus({ query: 'x' })).resolves.toEqual({
results: [],
degraded: true,
});

client.disconnect();
client = new PathfinderClient(BASE);
mockFetch.mockReset();
mockConnect();
mockFetch.mockResolvedValueOnce(mkResp({ body: jsonRpc({ content: [] }) }));

await expect(client.searchCodeWithStatus({ query: 'x' })).resolves.toEqual({
results: [],
degraded: false,
});
errorSpy.mockRestore();
});
});

// The mirror image of the code-block fix, and the reason headers are now read
Expand Down Expand Up @@ -446,6 +498,43 @@ describe('PathfinderClient', () => {
});

describe('searchDocs', () => {
it('reports a semantic-search failure as degraded when the fallback returns docs', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const fallbackResults = [{ title: 'Actions', content: 'Guide to actions', score: 0.7 }];
mockConnect();
mockFetch.mockResolvedValueOnce(
mkResp({
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
error: { message: 'index unavailable' },
}),
}),
);
vi.spyOn(client, 'fallbackSearch').mockResolvedValue(fallbackResults);

await expect(client.searchDocsWithStatus({ query: 'actions' })).resolves.toEqual({
results: fallbackResults,
degraded: true,
});

errorSpy.mockRestore();
});

it('reports a successful empty semantic search as healthy', async () => {
mockConnect();
mockFetch.mockResolvedValueOnce(
mkResp({ body: jsonRpc({ content: [{ type: 'text', text: '' }] }) }),
);
const fallbackSpy = vi.spyOn(client, 'fallbackSearch');

await expect(client.searchDocsWithStatus({ query: 'no matches' })).resolves.toEqual({
results: [],
degraded: false,
});
expect(fallbackSpy).not.toHaveBeenCalled();
});

it('parses the SNIPPET/TITLE/SOURCE/CONTENT text format', async () => {
mockConnect();
mockFetch.mockResolvedValueOnce(
Expand Down
50 changes: 41 additions & 9 deletions packages/outpost/ai/src/pathfinder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,12 @@ function isCodeSearchTool(tool: SearchTool): boolean {
*
* Falls back to a plain-text docs search when MCP is unavailable.
*/
export interface PathfinderSearchOutcome {
results: SearchResult[];
/** True when the tool call failed, distinct from a successful search with no hits. */
degraded: boolean;
}

export class PathfinderClient {
private readonly endpoint: string;
private sessionId: string | null = null;
Expand Down Expand Up @@ -516,30 +522,44 @@ export class PathfinderClient {
* Kept private with named wrappers rather than exposed as a tool-name
* parameter, so a caller cannot invent a name that fails at the wire.
*
* That is a narrow guarantee, and worth not overstating: `SearchTool` is a
* compile-time union and cannot know what the server actually exposes. A
* server-side rename of `search-code` still produces a JSON-RPC error, one
* `console.error`, and `[]` — indistinguishable from "no code matched" for as
* long as nobody reads the logs. Making that checkable needs a `tools/list`
* probe at startup; tracked in #244.
* `SearchTool` is a compile-time union and cannot know what the server
* actually exposes. A server-side rename of `search-code` still produces a
* JSON-RPC error. The status-bearing result preserves that failure separately
* from a successful search with no matches; the array-only wrappers retain
* their historical empty-array fallback for existing callers.
*/
private async search(tool: SearchTool, query: PathfinderQuery): Promise<SearchResult[]> {
private async searchWithStatus(
tool: SearchTool,
query: PathfinderQuery,
): Promise<PathfinderSearchOutcome> {
try {
const result = await this.callTool(tool, {
query: capQuery(query.query, config.pathfinder.maxQueryChars),
limit: query.limit ?? config.pathfinder.defaultLimit,
min_score: query.minScore ?? config.pathfinder.defaultMinScore,
...(query.version ? { version: query.version } : {}),
});
return this.parseSearchResults(result);
if (
!result ||
typeof result !== 'object' ||
!Array.isArray((result as { content?: unknown }).content) ||
('isError' in result && result.isError)
) {
throw new Error(`Pathfinder ${tool} returned an invalid tool result`);
}
return { results: this.parseSearchResults(result), degraded: false };
} catch (error) {
console.error(
`[Pathfinder] ${tool} failed: ${error instanceof Error ? error.message : String(error)}`,
);
return [];
return { results: [], degraded: true };
}
}

private async search(tool: SearchTool, query: PathfinderQuery): Promise<SearchResult[]> {
return (await this.searchWithStatus(tool, query)).results;
}

/**
* Search CopilotKit's SOURCE, not its docs.
*
Expand All @@ -554,6 +574,11 @@ export class PathfinderClient {
return this.search('search-code', query);
}

/** Search code and preserve whether an empty result came from a tool failure. */
async searchCodeWithStatus(query: PathfinderQuery): Promise<PathfinderSearchOutcome> {
return this.searchWithStatus('search-code', query);
}

/** Search AG-UI's source. Same reasoning as `searchCode`, other repo. */
async searchAgUiCode(query: PathfinderQuery): Promise<SearchResult[]> {
return this.search('search-ag-ui-code', query);
Expand All @@ -564,6 +589,13 @@ export class PathfinderClient {
return this.search('search-ag-ui-docs', query);
}

/** Search documentation while preserving whether MCP had to fall back. */
async searchDocsWithStatus(query: PathfinderQuery): Promise<PathfinderSearchOutcome> {
const outcome = await this.searchWithStatus('search-docs', query);
if (!outcome.degraded) return outcome;
return { results: await this.fallbackSearch(query.query), degraded: true };
}

/**
* Search documentation using Pathfinder's semantic search.
*/
Expand Down
2 changes: 2 additions & 0 deletions packages/outpost/ai/src/pipeline-groundedness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,11 +98,13 @@ function createPipeline() {
return new AIPipeline({
pathfinder: {
searchDocs: vi.fn().mockResolvedValue(SOURCES),
searchDocsWithStatus: vi.fn().mockResolvedValue({ results: SOURCES, degraded: false }),
// Retrieval now queries code alongside docs, so this stub has to
// answer both. Returning [] rather than SOURCES keeps this file's
// subject — that the groundedness penalty is deducted exactly once —
// measured against the same source set it was written for.
searchCode: vi.fn().mockResolvedValue([]),
searchCodeWithStatus: vi.fn().mockResolvedValue({ results: [], degraded: false }),
searchAgUiDocs: vi.fn().mockResolvedValue([]),
searchAgUiCode: vi.fn().mockResolvedValue([]),
searchAll: vi.fn().mockResolvedValue(SOURCES),
Expand Down
31 changes: 28 additions & 3 deletions packages/outpost/ai/src/pipeline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,21 @@ function createPipeline(supportAgent?: Pick<SupportAgent, 'investigate'>) {
supportAgent,
pathfinder: {
searchDocs: mockSearchDocs,
searchDocsWithStatus: async (...args: unknown[]) => {
try {
return { results: await mockSearchDocs(...args), degraded: false };
} catch {
return { results: [], degraded: true };
}
},
searchCode: mockSearchCode,
searchCodeWithStatus: async (...args: unknown[]) => {
try {
return { results: await mockSearchCode(...args), degraded: false };
} catch {
return { results: [], degraded: true };
}
},
searchAgUiDocs: vi.fn(),
searchAgUiCode: vi.fn(),
exploreDocs: vi.fn(),
Expand Down Expand Up @@ -196,10 +210,13 @@ describe('AIPipeline', () => {
mockSearchDocs.mockResolvedValue([docHit('a')]);
mockSearchCode.mockResolvedValue([]);

await createPipeline().generateSupportResponse('q', { source: undefined } as never);
const result = await createPipeline().generateSupportResponse('q', {
source: undefined,
} as never);

const sources = mockGenerate.mock.calls[0][1] as SearchResult[];
expect(sources.map((s) => s.title)).toEqual(['a']);
expect(result.retrievalDegraded).toBe(false);
});

// The first version of this used Promise.all, which rejects on the first
Expand All @@ -210,20 +227,27 @@ describe('AIPipeline', () => {
mockSearchDocs.mockResolvedValue([docHit('a')]);
mockSearchCode.mockRejectedValue(new Error('code index unavailable'));

await createPipeline().generateSupportResponse('q', { source: undefined } as never);
const result = await createPipeline().generateSupportResponse('q', {
source: undefined,
} as never);

const sources = mockGenerate.mock.calls[0][1] as SearchResult[];
expect(sources.map((s) => s.title)).toEqual(['a']);
expect(result.retrievalDegraded).toBe(true);
expect(result.confidenceLevel).not.toBe(ConfidenceLevel.HIGH);
});

it('keeps the code results when the docs search rejects', async () => {
mockSearchDocs.mockRejectedValue(new Error('docs index unavailable'));
mockSearchCode.mockResolvedValue([codeHit('p/a.ts')]);

await createPipeline().generateSupportResponse('q', { source: undefined } as never);
const result = await createPipeline().generateSupportResponse('q', {
source: undefined,
} as never);

const sources = mockGenerate.mock.calls[0][1] as SearchResult[];
expect(sources.map((s) => s.title)).toEqual(['p/a.ts']);
expect(result.retrievalDegraded).toBe(true);
});

it('answers with no sources only when both reject', async () => {
Expand Down Expand Up @@ -1490,6 +1514,7 @@ describe('AIPipeline confidence calibration', () => {
vi.resetAllMocks();
pipeline = createPipeline();
mockSearchDocs.mockResolvedValue(sampleSearchResults);
mockSearchCode.mockResolvedValue([]);
mockGenerate.mockResolvedValue(sampleGeneratedResponse); // generator score 0.85
mockScore.mockResolvedValue({
...sampleConfidence,
Expand Down
Loading