diff --git a/packages/outpost/ai/src/index.ts b/packages/outpost/ai/src/index.ts index dc82003..e1f6d90 100644 --- a/packages/outpost/ai/src/index.ts +++ b/packages/outpost/ai/src/index.ts @@ -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'; diff --git a/packages/outpost/ai/src/pathfinder.test.ts b/packages/outpost/ai/src/pathfinder.test.ts index f2cc5e5..c3788af 100644 --- a/packages/outpost/ai/src/pathfinder.test.ts +++ b/packages/outpost/ai/src/pathfinder.test.ts @@ -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 @@ -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( diff --git a/packages/outpost/ai/src/pathfinder.ts b/packages/outpost/ai/src/pathfinder.ts index 87e8636..f8f13f8 100644 --- a/packages/outpost/ai/src/pathfinder.ts +++ b/packages/outpost/ai/src/pathfinder.ts @@ -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; @@ -516,14 +522,16 @@ 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 { + private async searchWithStatus( + tool: SearchTool, + query: PathfinderQuery, + ): Promise { try { const result = await this.callTool(tool, { query: capQuery(query.query, config.pathfinder.maxQueryChars), @@ -531,15 +539,27 @@ export class PathfinderClient { 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 { + return (await this.searchWithStatus(tool, query)).results; + } + /** * Search CopilotKit's SOURCE, not its docs. * @@ -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 { + return this.searchWithStatus('search-code', query); + } + /** Search AG-UI's source. Same reasoning as `searchCode`, other repo. */ async searchAgUiCode(query: PathfinderQuery): Promise { return this.search('search-ag-ui-code', query); @@ -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 { + 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. */ diff --git a/packages/outpost/ai/src/pipeline-groundedness.test.ts b/packages/outpost/ai/src/pipeline-groundedness.test.ts index 37c96a6..d29bd9f 100644 --- a/packages/outpost/ai/src/pipeline-groundedness.test.ts +++ b/packages/outpost/ai/src/pipeline-groundedness.test.ts @@ -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), diff --git a/packages/outpost/ai/src/pipeline.test.ts b/packages/outpost/ai/src/pipeline.test.ts index 9f628a2..8a1d773 100644 --- a/packages/outpost/ai/src/pipeline.test.ts +++ b/packages/outpost/ai/src/pipeline.test.ts @@ -56,7 +56,21 @@ function createPipeline(supportAgent?: Pick) { 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(), @@ -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 @@ -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 () => { @@ -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, diff --git a/packages/outpost/ai/src/pipeline.ts b/packages/outpost/ai/src/pipeline.ts index 129d617..3f28dfc 100644 --- a/packages/outpost/ai/src/pipeline.ts +++ b/packages/outpost/ai/src/pipeline.ts @@ -149,6 +149,7 @@ export class AIPipeline { let generatedResponse: GeneratedResponse; let mustRoute = false; let investigationFailed = false; + let retrievalDegraded = false; const pipelineContext: PipelineContext = { question, source: options.source, @@ -198,35 +199,55 @@ export class AIPipeline { } } else { const perTool = Math.ceil(config.pathfinder.defaultLimit / 2); - const [docsOutcome, codeOutcome] = await Promise.allSettled([ - this.pathfinder.searchDocs({ query: question, limit: perTool }), - this.pathfinder.searchCode({ query: question, limit: perTool }), - ]); - for (const [label, outcome] of [ - ['searchDocs', docsOutcome], - ['searchCode', codeOutcome], - ] as const) { - if (outcome.status === 'rejected') { - console.error( - `[Pipeline] ${label} failed: ${ - outcome.reason instanceof Error - ? outcome.reason.message - : String(outcome.reason) - }`, - ); - } + const docsSearch = + typeof this.pathfinder.searchDocsWithStatus === 'function' + ? this.pathfinder.searchDocsWithStatus({ query: question, limit: perTool }) + : this.pathfinder + .searchDocs({ query: question, limit: perTool }) + .then((results) => ({ results, degraded: false })); + const codeSearch = + typeof this.pathfinder.searchCodeWithStatus === 'function' + ? this.pathfinder.searchCodeWithStatus({ query: question, limit: perTool }) + : this.pathfinder + .searchCode({ query: question, limit: perTool }) + .then((results) => ({ results, degraded: false })); + const [docsOutcome, codeOutcome] = await Promise.allSettled([docsSearch, codeSearch]); + if (docsOutcome.status === 'rejected') { + console.error( + `[Pipeline] searchDocs failed: ${ + docsOutcome.reason instanceof Error + ? docsOutcome.reason.message + : String(docsOutcome.reason) + }`, + ); + } + if (codeOutcome.status === 'rejected') { + console.error( + `[Pipeline] searchCode failed: ${ + codeOutcome.reason instanceof Error + ? codeOutcome.reason.message + : String(codeOutcome.reason) + }`, + ); } - // Coerced rather than trusted. This class's contract is that it never - // crashes, and `Promise.allSettled` reports a non-promise or an - // `undefined` return as *fulfilled* — so a client that answers with - // anything other than an array would reach the merge and throw on - // `.length`, taking down the one code path that is supposed to always - // produce an answer. The old `try`/`catch` hid this; removing it made it - // reachable, which is a good reason to handle it rather than re-wrap. - const asResults = (outcome: PromiseSettledResult): SearchResult[] => - outcome.status === 'fulfilled' && Array.isArray(outcome.value) ? outcome.value : []; - const docs = asResults(docsOutcome); - const code = asResults(codeOutcome); + // `Promise.allSettled` treats an undefined return as fulfilled, so + // injected clients can still hand us malformed values. Keep the + // generator path resilient while marking a malformed source degraded. + const docsStatus = docsOutcome.status === 'fulfilled' ? docsOutcome.value : undefined; + const docs = docsStatus && Array.isArray(docsStatus.results) ? docsStatus.results : []; + const docsUnavailable = + docsOutcome.status === 'rejected' || + !docsStatus || + !Array.isArray(docsStatus.results) || + docsStatus.degraded !== false; + const codeStatus = codeOutcome.status === 'fulfilled' ? codeOutcome.value : undefined; + retrievalDegraded = + docsUnavailable || + codeOutcome.status === 'rejected' || + !codeStatus || + !Array.isArray(codeStatus.results) || + codeStatus.degraded !== false; + const code = codeStatus && Array.isArray(codeStatus.results) ? codeStatus.results : []; // Code leads, because the stated precedence is source first, docs second. // Interleaved rather than concatenated so neither source is buried: the @@ -269,6 +290,8 @@ export class AIPipeline { }; }); + const confidenceDegraded = confidenceAssessment.degraded || retrievalDegraded; + // The new provider publishes only when the independent verifier is usable. mustRoute ||= !!this.supportAgent && @@ -357,7 +380,7 @@ export class AIPipeline { // score that still classifies below HIGH so the response keeps a disclaimer. This // only ever LOWERS the score — a genuinely low degraded signal is left untouched and // still falls through to escalation. - if (confidenceAssessment.degraded && finalConfidenceScore >= AI_CONFIDENCE.HIGH_THRESHOLD) { + if (confidenceDegraded && finalConfidenceScore >= AI_CONFIDENCE.HIGH_THRESHOLD) { finalConfidenceScore = DEGRADED_CONFIDENCE_CAP; } const finalConfidence = classifyConfidence(finalConfidenceScore); @@ -442,9 +465,13 @@ export class AIPipeline { ? 'The investigator routed the question without a usable reason' : !lint.publish || groundedness.suppress || groundedness.forcesEscalation ? 'A draft check required review without a usable finding' - : confidenceAssessment.degraded - ? 'Independent verification was unavailable or malformed' - : 'Independent verification found insufficient support'; + : confidenceAssessment.degraded && retrievalDegraded + ? 'Retrieval and independent verification were unavailable' + : retrievalDegraded + ? 'Retrieval was unavailable' + : confidenceAssessment.degraded + ? 'Independent verification was unavailable or malformed' + : 'Independent verification found insufficient support'; const handoffReason = suppressed || groundedness.forcesEscalation ? storableReason([...deterministicReasons, generatedResponse.reasoning], 2000) || @@ -459,6 +486,7 @@ export class AIPipeline { confidenceLevel: finalConfidence, confidenceScore: finalConfidenceScore, searchResults, + retrievalDegraded, tokenUsage: totalTokenUsage, latencyMs, groundedness, diff --git a/packages/outpost/ai/src/types.ts b/packages/outpost/ai/src/types.ts index 995ca55..8386b9c 100644 --- a/packages/outpost/ai/src/types.ts +++ b/packages/outpost/ai/src/types.ts @@ -299,6 +299,12 @@ export interface PipelineResult { confidenceScore: number; /** Search results used as context */ searchResults: SearchResult[]; + /** + * True when the pipeline's direct docs or code retrieval failed, even if + * another source returned results. SupportAgent investigations signal their + * own failures by routing the response for human review. + */ + retrievalDegraded: boolean; /** Token usage across generation and verification calls */ tokenUsage: TokenUsage; /** End-to-end latency in milliseconds */