diff --git a/libs/research/README.md b/libs/research/README.md index 944b6498..03973ff5 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -218,8 +218,13 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported - **Injected exchange calendars:** `resolveExchangeCalendars({ listingIds, fromDate, toDate })` supplies actual exchange session close timestamps (including half-days) for `buildEventStudyInput` so events are anchored without synthesizing calendars from bars. - **Returns, benchmark & Vault fence:** Models daily close-to-close returns with no execution or transaction costs (`adjustment` defaults to `'raw'`; `benchmark` defaults to `'equal_weight'` using available eligible listing returns, or `'none'` for unbenchmarked returns). Enforces `scope: 'vault_fenced'`, clamps `to`/`asOf` strictly below `vaultCutoffTs`, resolves named universes strictly pre-start, defensively excludes any bar or event on or after the Vault cutoff date (or with `known_at > asOf`), and writes eligible trials exclusively to the injected `trial_ledger` (`stage = 'event_study'`) under the server-injected `principalId`. +### `file_finding` Tool (Append-Only) + +- **`createFileFindingTool({ port, trialLookup, newId, now })`** — Files an append-only empirical `finding` or `dead_end` record linked to 1–32 research-visible `trial_ledger` references (`trialRefs`, capped at 256 chars each) and 0–32 optional opaque snapshot identifiers (`evidenceRefs`, never dereferenced by the tool). Trims and enforces hard limits (`title` ≤ 256, `summary` ≤ 4,096, `idempotencyKey` ≤ 128), applies array bounds before case-sensitive deduplication and sorting, and rejects unknown fields with a fixed message. +- **Review status & Vault safety:** Server-controlled metadata (`id`, UTC ISO `createdAt`, and initial `status: 'pending_review'`) cannot be supplied by callers; director approval occurs out-of-band. Every unique `trialRef` is verified via the injected read-only `trialLookup.hasResearchVisibleTrial(ref)` before generating metadata or writing (treating unknown and Vault-only refs identically). Callers must describe research-visible evidence only in `title` and `summary` and keep Vault holdout observations out of filing text. +- **Idempotency & receipts:** `FindingWritePort` exposes only `appendFinding(record, idempotencyKey?)` with atomic `created` / `replayed` / `conflict` semantics comparing normalized `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs`. Retries with the same key and normalized payload return the original `{ id, createdAt, created: false }` without appending; key reuse with a different payload returns a fixed `isError: true` conflict error with zero writes; unkeyed calls are independent. Filed records extend `FindingRecord` and can be read back by receipt ID via `read_knowledge`. + ### Remaining M2 MCP Items (Later Tasks) -- Additional research tools: `search_symbols`, `analyze_signal`, `file_finding`, and `read_knowledge`. - SSE/HTTP transport wrapper in `apps/stock/web-api`. - Runnable CLI binary wired to real DuckDB/Parquet and PostgreSQL adapters. diff --git a/libs/research/src/mcp/index.ts b/libs/research/src/mcp/index.ts index 5241cac4..f228f04a 100644 --- a/libs/research/src/mcp/index.ts +++ b/libs/research/src/mcp/index.ts @@ -3,6 +3,7 @@ export * from './server'; export * from './stdio'; export * from './tools/analyze-signal'; export * from './tools/event-study'; +export * from './tools/file-finding'; export * from './tools/query-data'; export * from './tools/read-knowledge'; export * from './tools/search-symbols'; diff --git a/libs/research/src/mcp/tools/file-finding.ts b/libs/research/src/mcp/tools/file-finding.ts new file mode 100644 index 00000000..97fb8d3f --- /dev/null +++ b/libs/research/src/mcp/tools/file-finding.ts @@ -0,0 +1,416 @@ +import { z } from 'zod'; +import type { McpToolCallResult } from '../protocol'; +import { type McpToolEntry, defineMcpTool } from '../server'; +import { type FindingRecord, READ_KNOWLEDGE_MAX_TEXT_LENGTH } from './read-knowledge'; +import { MAX_ECMASCRIPT_EPOCH_MS } from './vault-fenced-input'; + +/** Supported filing kinds for `file_finding` (per D12 in `design/PLATFORM-PLAN.md`). */ +export const FILE_FINDING_KINDS = ['finding', 'dead_end'] as const; + +export type FileFindingKind = (typeof FILE_FINDING_KINDS)[number]; + +/** Initial server-assigned review status for every newly filed finding or dead end. */ +export const FILE_FINDING_INITIAL_STATUS = 'pending_review' as const; + +export type FileFindingInitialStatus = typeof FILE_FINDING_INITIAL_STATUS; + +/** Hard maximum character length of a trimmed `file_finding` title. */ +export const FILE_FINDING_MAX_TITLE_LENGTH = 256; + +/** Hard maximum character length of a trimmed `file_finding` summary. */ +export const FILE_FINDING_MAX_SUMMARY_LENGTH = READ_KNOWLEDGE_MAX_TEXT_LENGTH; + +/** Hard maximum character length of a trimmed trial or evidence reference string. */ +export const FILE_FINDING_MAX_REF_LENGTH = 256; + +/** Hard maximum number of raw `trialRefs` accepted before deduplication. */ +export const FILE_FINDING_MAX_TRIAL_REFS = 32; + +/** Hard maximum number of raw `evidenceRefs` accepted before deduplication. */ +export const FILE_FINDING_MAX_EVIDENCE_REFS = 32; + +/** Hard maximum character length of a trimmed `idempotencyKey`. */ +export const FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH = 128; + +/** Fixed validation message used when unknown keys are supplied (never echoes caller keys). */ +export const FILE_FINDING_ERROR_UNKNOWN_KEYS = 'Unrecognized field(s) are not allowed.'; + +/** Fixed tool error message when one or more trial refs are unknown or Vault-only. */ +export const FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF = + 'One or more referenced trials are unavailable in the research-visible trial ledger.'; + +/** Fixed tool error message when an idempotency key is reused with a different payload. */ +export const FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT = + 'Idempotency key conflict: the provided idempotency key was already used with a different finding payload.'; + +/** Fixed tool error message when trial lookup, metadata generation, or append fails. */ +export const FILE_FINDING_ERROR_FILING_FAILED = + 'Failed to file finding due to a storage or lookup error.'; + +/** + * Append-only finding or dead-end record passed to {@link FindingWritePort.appendFinding}. + * + * Extends {@link FindingRecord} with `kind` and fixes `status` to `'pending_review'` + * so filed records are directly readable via `read_knowledge` while director approval + * happens out-of-band. + */ +export interface FiledFindingRecord extends FindingRecord { + readonly kind: FileFindingKind; + readonly status: FileFindingInitialStatus; +} + +/** Normalized caller-supplied fields compared for idempotency equality. */ +export type FiledFindingComparablePayload = Pick< + FiledFindingRecord, + 'kind' | 'title' | 'summary' | 'trialRefs' | 'evidenceRefs' +>; + +/** + * Discriminated outcome returned by {@link FindingWritePort.appendFinding}. + * + * - `'created'`: A new record was appended. + * - `'replayed'`: An existing record with the same `idempotencyKey` and + * identical normalized payload (`kind`, `title`, `summary`, `trialRefs`, + * `evidenceRefs`) was found; zero rows were appended and the stored `id` + * and `createdAt` are returned. + * - `'conflict'`: An existing record with the same `idempotencyKey` has a + * different normalized payload; zero rows were appended. + */ +export type AppendFindingResult = + | { + readonly status: 'created'; + readonly id: string; + readonly createdAt: string; + } + | { + readonly status: 'replayed'; + readonly id: string; + readonly createdAt: string; + } + | { + readonly status: 'conflict'; + }; + +/** + * Append-only write port injected into {@link createFileFindingTool}. + * + * Port contract: + * - Append-only by construction: exposes only {@link appendFinding} (no update + * or delete methods). + * - When `idempotencyKey` is supplied, the port must atomically compare and + * append within its configured key namespace: + * - Compare normalized `kind`, `title`, `summary`, `trialRefs`, and + * `evidenceRefs` (excluding server-generated `id`, `createdAt`, and `status`). + * - On an identical payload match, return `{ status: 'replayed', id, createdAt }` + * with the originally stored `id` and `createdAt` without appending a new row. + * - On a payload mismatch, return `{ status: 'conflict' }` and append zero rows. + * - When `idempotencyKey` is omitted (`undefined`), each call is independent and + * appends a new row, returning `{ status: 'created', id, createdAt }`. + */ +export interface FindingWritePort { + appendFinding( + record: FiledFindingRecord, + idempotencyKey?: string + ): Promise; +} + +/** + * Read-only trial visibility lookup port injected into {@link createFileFindingTool}. + * + * Bound at composition to the caller's research-visible `trial_ledger` and active + * Vault boundary. Accepts opaque string refs (for example, decimal `trialId` strings + * from `trial_ledger` receipts without numeric coercion) and returns `true` only when + * the trial exists and is research-visible. Unknown and Vault-only refs both return + * `false`. + */ +export interface TrialRefLookupPort { + hasResearchVisibleTrial(trialRef: string): Promise | boolean; +} + +/** Server-side injected configuration for {@link createFileFindingTool}. */ +export interface FileFindingToolOptions { + readonly port: FindingWritePort; + readonly trialLookup: TrialRefLookupPort; + readonly newId: () => string; + readonly now: () => Date | number; +} + +/** Structured JSON receipt serialized into the `file_finding` MCP text result. */ +export interface FileFindingResultPayload { + readonly id: string; + readonly createdAt: string; + readonly created: boolean; +} + +function compareStrings(a: string, b: string): number { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; +} + +function normalizeRefSet(refs: readonly string[]): readonly string[] { + const unique = Array.from(new Set(refs)); + unique.sort(compareStrings); + return unique; +} + +function areStringArraysEqual(a: readonly string[], b: readonly string[]): boolean { + if (a.length !== b.length) { + return false; + } + for (let i = 0; i < a.length; i += 1) { + if (a[i] !== b[i]) { + return false; + } + } + return true; +} + +/** + * Compares two normalized filing payloads for idempotency equality across + * `kind`, `title`, `summary`, `trialRefs`, and `evidenceRefs` (excluding + * server-generated `id`, `createdAt`, and `status`). + */ +export function areFiledFindingPayloadsEqual( + a: FiledFindingComparablePayload, + b: FiledFindingComparablePayload +): boolean { + return ( + a.kind === b.kind && + a.title === b.title && + a.summary === b.summary && + areStringArraysEqual(a.trialRefs, b.trialRefs) && + areStringArraysEqual(a.evidenceRefs, b.evidenceRefs) + ); +} + +const refStringSchema = z.string().trim().min(1).max(FILE_FINDING_MAX_REF_LENGTH); + +/** + * Strict Zod input schema for the `file_finding` MCP tool. + * + * Intentionally omits server-controlled fields (`id`, `status`, `createdAt`) and + * Vault/holdout fields (`scope`, `vault_evaluation_only`, `vaultCutoffTs`). + * `.strict(FILE_FINDING_ERROR_UNKNOWN_KEYS)` rejects any unknown keys with a fixed + * message so caller-supplied key names are never echoed. + * + * `title` and `summary` must describe research-visible evidence only; `evidenceRefs` + * are opaque snapshot identifiers that the tool stores without dereferencing. + */ +export const fileFindingInputSchema = z + .object({ + kind: z + .enum(FILE_FINDING_KINDS, { + errorMap: () => ({ message: "Expected 'finding' or 'dead_end'." }), + }) + .describe("Filing classification: 'finding' or 'dead_end'."), + title: z + .string() + .trim() + .min(1) + .max(FILE_FINDING_MAX_TITLE_LENGTH) + .describe( + `Short title describing research-visible evidence (trimmed, 1–${FILE_FINDING_MAX_TITLE_LENGTH} characters).` + ), + summary: z + .string() + .trim() + .min(1) + .max(FILE_FINDING_MAX_SUMMARY_LENGTH) + .describe( + `Concise summary of research-visible evidence only; never include Vault holdout observations (trimmed, 1–${FILE_FINDING_MAX_SUMMARY_LENGTH} characters).` + ), + trialRefs: z + .array(refStringSchema) + .min(1) + .max(FILE_FINDING_MAX_TRIAL_REFS) + .transform(normalizeRefSet) + .describe( + `Opaque research-visible trial_ledger references (1–${FILE_FINDING_MAX_TRIAL_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; deduplicated case-sensitively and sorted).` + ), + evidenceRefs: z + .array(refStringSchema) + .max(FILE_FINDING_MAX_EVIDENCE_REFS) + .default([]) + .transform(normalizeRefSet) + .describe( + `Optional opaque snapshot or artifact identifiers never dereferenced by the tool (0–${FILE_FINDING_MAX_EVIDENCE_REFS} raw entries, each 1–${FILE_FINDING_MAX_REF_LENGTH} characters; defaults to empty list, deduplicated case-sensitively and sorted).` + ), + idempotencyKey: z + .string() + .trim() + .min(1) + .max(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH) + .optional() + .describe( + `Optional retry idempotency key (trimmed, 1–${FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH} characters).` + ), + }) + .strict(FILE_FINDING_ERROR_UNKNOWN_KEYS); + +export type FileFindingInput = z.infer; + +function toolError(message: string): McpToolCallResult { + return { + content: [{ type: 'text', text: message }], + isError: true, + }; +} + +function validateNonEmptyString(value: unknown): string | null { + if (typeof value !== 'string' || value.trim().length === 0) { + return null; + } + return value; +} + +function formatUtcIsoTimestamp(raw: Date | number): string | null { + const epochMs = raw instanceof Date ? raw.getTime() : raw; + if ( + typeof epochMs !== 'number' || + !Number.isFinite(epochMs) || + Math.abs(epochMs) >= MAX_ECMASCRIPT_EPOCH_MS + ) { + return null; + } + return new Date(epochMs).toISOString(); +} + +function validateFactoryOptions(options: FileFindingToolOptions): FileFindingToolOptions { + if (typeof options !== 'object' || options === null) { + throw new Error('Invalid `options`: expected a FileFindingToolOptions object.'); + } + + if ( + typeof options.port !== 'object' || + options.port === null || + typeof options.port.appendFinding !== 'function' + ) { + throw new Error( + 'Invalid `port`: expected a FindingWritePort implementing `appendFinding`.' + ); + } + + if ( + typeof options.trialLookup !== 'object' || + options.trialLookup === null || + typeof options.trialLookup.hasResearchVisibleTrial !== 'function' + ) { + throw new Error( + 'Invalid `trialLookup`: expected a TrialRefLookupPort implementing `hasResearchVisibleTrial`.' + ); + } + + if (typeof options.newId !== 'function') { + throw new Error('Invalid `newId`: expected a function returning a non-empty finding ID.'); + } + + if (typeof options.now !== 'function') { + throw new Error('Invalid `now`: expected a clock function returning a Date or epoch ms.'); + } + + return options; +} + +/** + * Creates the append-only `file_finding` MCP tool backed by an injected + * {@link FindingWritePort} and read-only {@link TrialRefLookupPort}. + * + * Verifies every unique `trialRef` against the research-visible trial ledger + * before generating server-controlled metadata (`id`, `createdAt`, + * `status: 'pending_review'`) or calling `appendFinding`. Returns only the + * explicitly projected `{ id, createdAt, created }` receipt on success and fixed + * sanitized `isError` messages on failure. + */ +export function createFileFindingTool(options: FileFindingToolOptions): McpToolEntry { + const validated = validateFactoryOptions(options); + const { port, trialLookup, newId, now } = validated; + + return defineMcpTool({ + name: 'file_finding', + description: + 'File an append-only empirical finding or dead end linked to research-visible trial ledger references for director review.', + inputSchema: fileFindingInputSchema, + async handler(input: FileFindingInput): Promise { + // Verify every unique research-visible trial ref before generating metadata or writing. + for (let i = 0; i < input.trialRefs.length; i += 1) { + const trialRef = input.trialRefs[i] as string; + let visible: unknown; + try { + visible = await trialLookup.hasResearchVisibleTrial(trialRef); + } catch { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + if (typeof visible !== 'boolean') { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + if (!visible) { + return toolError(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + } + } + + let id: string | null; + let createdAt: string | null; + try { + id = validateNonEmptyString(newId()); + createdAt = formatUtcIsoTimestamp(now()); + } catch { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + if (id === null || createdAt === null) { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + const record: FiledFindingRecord = { + id, + kind: input.kind, + title: input.title, + status: FILE_FINDING_INITIAL_STATUS, + createdAt, + summary: input.summary, + trialRefs: [...input.trialRefs], + evidenceRefs: [...input.evidenceRefs], + }; + + let outcome: AppendFindingResult; + try { + outcome = await port.appendFinding(record, input.idempotencyKey); + } catch { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + if (typeof outcome !== 'object' || outcome === null) { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + if (outcome.status === 'conflict') { + return toolError(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); + } + + if (outcome.status !== 'created' && outcome.status !== 'replayed') { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + const receiptId = validateNonEmptyString(outcome.id); + const receiptCreatedAt = validateNonEmptyString(outcome.createdAt); + if (receiptId === null || receiptCreatedAt === null) { + return toolError(FILE_FINDING_ERROR_FILING_FAILED); + } + + const payload: FileFindingResultPayload = { + id: receiptId, + createdAt: receiptCreatedAt, + created: outcome.status === 'created', + }; + + return { + content: [{ type: 'text', text: JSON.stringify(payload) }], + }; + }, + }); +} diff --git a/libs/research/test/mcp-file-finding.test.ts b/libs/research/test/mcp-file-finding.test.ts new file mode 100644 index 00000000..ea47b644 --- /dev/null +++ b/libs/research/test/mcp-file-finding.test.ts @@ -0,0 +1,1100 @@ +import { describe, expect, test } from 'bun:test'; +import * as rootResearchExports from '../src/index'; +import { + type AppendFindingResult, + FILE_FINDING_ERROR_FILING_FAILED, + FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT, + FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF, + FILE_FINDING_ERROR_UNKNOWN_KEYS, + FILE_FINDING_INITIAL_STATUS, + FILE_FINDING_KINDS, + FILE_FINDING_MAX_EVIDENCE_REFS, + FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, + FILE_FINDING_MAX_REF_LENGTH, + FILE_FINDING_MAX_SUMMARY_LENGTH, + FILE_FINDING_MAX_TITLE_LENGTH, + FILE_FINDING_MAX_TRIAL_REFS, + type FileFindingResultPayload, + type FiledFindingRecord, + type FindingQuery, + type FindingRecord, + type FindingWritePort, + type KnowledgePort, + type ReadKnowledgeResultPayload, + type TrialRefLookupPort, + areFiledFindingPayloadsEqual, + createFileFindingTool, + createMcpServer, + createReadKnowledgeTool, + fileFindingInputSchema, +} from '../src/mcp/index'; + +interface SharedFindingsFakeOptions { + readonly failNextAppendError?: unknown; + readonly alwaysAppendError?: unknown; + readonly delayFirstAppendMs?: number; + readonly attachExtraReceiptField?: boolean; +} + +interface SharedFindingsFake { + readonly stored: FiledFindingRecord[]; + readonly appendCalls: { + readonly record: FiledFindingRecord; + readonly idempotencyKey?: string; + }[]; + readonly writePort: FindingWritePort; + readonly knowledgePort: KnowledgePort; + readonly invokedWriteMethods: string[]; +} + +function createSharedFindingsFake(options?: SharedFindingsFakeOptions): SharedFindingsFake { + const stored: FiledFindingRecord[] = []; + const byIdempotencyKey = new Map(); + const appendCalls: { readonly record: FiledFindingRecord; readonly idempotencyKey?: string }[] = + []; + const invokedWriteMethods: string[] = []; + + let failOnceError: unknown = options?.failNextAppendError; + let firstCallSeen = false; + + const rawWritePort: FindingWritePort = { + async appendFinding( + record: FiledFindingRecord, + idempotencyKey?: string + ): Promise { + appendCalls.push({ record, idempotencyKey }); + + if (options?.alwaysAppendError !== undefined) { + throw options.alwaysAppendError; + } + + if (failOnceError !== undefined) { + const err = failOnceError; + failOnceError = undefined; + throw err; + } + + // Atomic compare-and-append before any async yield so concurrent calls with + // the same idempotencyKey cannot both insert. + let outcome: AppendFindingResult; + if (idempotencyKey !== undefined) { + const existing = byIdempotencyKey.get(idempotencyKey); + if (existing !== undefined) { + if (areFiledFindingPayloadsEqual(existing, record)) { + outcome = { + status: 'replayed', + id: existing.id, + createdAt: existing.createdAt, + }; + } else { + outcome = { status: 'conflict' }; + } + } else { + const copy: FiledFindingRecord = { + ...record, + trialRefs: [...record.trialRefs], + evidenceRefs: [...record.evidenceRefs], + }; + stored.push(copy); + byIdempotencyKey.set(idempotencyKey, copy); + outcome = { + status: 'created', + id: copy.id, + createdAt: copy.createdAt, + }; + } + } else { + const copy: FiledFindingRecord = { + ...record, + trialRefs: [...record.trialRefs], + evidenceRefs: [...record.evidenceRefs], + }; + stored.push(copy); + outcome = { + status: 'created', + id: copy.id, + createdAt: copy.createdAt, + }; + } + + if (!firstCallSeen && options?.delayFirstAppendMs !== undefined) { + firstCallSeen = true; + await new Promise(resolve => setTimeout(resolve, options.delayFirstAppendMs)); + } + + if (options?.attachExtraReceiptField === true && outcome.status !== 'conflict') { + return { + ...outcome, + internalDsn: 'postgres://leaked:pass@127.0.0.1:5432/trading_bot', + } as unknown as AppendFindingResult; + } + + return outcome; + }, + }; + + const writePort = new Proxy(rawWritePort, { + get(target, prop, receiver) { + const value: unknown = Reflect.get(target, prop, receiver); + if (typeof value === 'function' && typeof prop === 'string') { + return (...args: unknown[]) => { + invokedWriteMethods.push(prop); + return (value as (...a: unknown[]) => unknown).apply(target, args); + }; + } + return value; + }, + }); + + const knowledgePort: KnowledgePort = { + async listLibraryCards() { + return []; + }, + async listFindings(q: FindingQuery): Promise { + return stored.filter(item => { + if (q.id !== undefined && item.id !== q.id) { + return false; + } + if (q.query !== undefined) { + const needle = q.query.toLowerCase(); + return ( + item.title.toLowerCase().includes(needle) || item.summary.toLowerCase().includes(needle) + ); + } + return true; + }); + }, + async listProviderCaveats() { + return []; + }, + }; + + return { + stored, + appendCalls, + writePort, + knowledgePort, + invokedWriteMethods, + }; +} + +interface FakeTrialLookup { + readonly queriedRefs: string[]; + readonly port: TrialRefLookupPort; +} + +function createFakeTrialLookup(options?: { + readonly researchVisibleRefs?: readonly string[]; + readonly vaultOnlyRefs?: readonly string[]; + readonly throwError?: unknown; +}): FakeTrialLookup { + const visibleSet = new Set( + options?.researchVisibleRefs ?? ['trial-101', 'trial-102', '9007199254740993123'] + ); + const vaultOnlySet = new Set(options?.vaultOnlyRefs ?? ['trial-vault-999']); + const queriedRefs: string[] = []; + + const port: TrialRefLookupPort = { + async hasResearchVisibleTrial(trialRef: string): Promise { + queriedRefs.push(trialRef); + if (options?.throwError !== undefined) { + throw options.throwError; + } + if (vaultOnlySet.has(trialRef)) { + return false; + } + return visibleSet.has(trialRef); + }, + }; + + return { queriedRefs, port }; +} + +function createFixedClock(startIso = '2025-03-01T12:00:00.000Z', stepMs = 60_000) { + let current = Date.parse(startIso); + let calls = 0; + return { + get calls() { + return calls; + }, + now: () => { + calls += 1; + const value = current; + current += stepMs; + return value; + }, + }; +} + +function createFixedIdGenerator(prefix = 'find') { + let counter = 0; + return { + get calls() { + return counter; + }, + newId: () => { + counter += 1; + return `${prefix}-${String(counter).padStart(4, '0')}`; + }, + }; +} + +async function callTool( + server: ReturnType, + toolName: string, + args: Record, + id: string | number = 'req-1' +): Promise<{ + readonly isError: boolean; + readonly text: string; + readonly payload: TPayload | null; +}> { + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id, + method: 'tools/call', + params: { + name: toolName, + arguments: args, + }, + }) + ); + + expect(raw).not.toBeNull(); + const parsed = JSON.parse(raw as string) as { + error?: unknown; + result: { + isError?: boolean; + content: { type: string; text: string }[]; + }; + }; + expect(parsed.error).toBeUndefined(); + const isError = parsed.result.isError === true; + const text = parsed.result.content[0]?.text ?? ''; + + return { + isError, + text, + payload: isError ? null : (JSON.parse(text) as TPayload), + }; +} + +describe('MCP file_finding tool', () => { + test('files both finding and dead_end with fixed server metadata, normalization, and explicit receipt projection', async () => { + const fake = createSharedFindingsFake({ attachExtraReceiptField: true }); + const trialLookup = createFakeTrialLookup(); + const clock = createFixedClock('2025-03-01T10:00:00.000Z', 60_000); + const idGen = createFixedIdGenerator('finding'); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + ], + }); + + const findingRes = await callTool(server, 'file_finding', { + kind: 'finding', + title: ' Post-earnings drift decays after day 3 ', + summary: ' Cross-sectional CAR flattens after session +3 across 2015-2024. ', + trialRefs: [' trial-102 ', '9007199254740993123', 'trial-102', 'trial-101'], + evidenceRefs: [' snap-b ', 'snap-a', 'snap-b', 'Snap-A'], + }); + + expect(findingRes.isError).toBe(false); + expect(findingRes.payload).toEqual({ + id: 'finding-0001', + createdAt: '2025-03-01T10:00:00.000Z', + created: true, + }); + expect(Object.keys(findingRes.payload as unknown as Record).sort()).toEqual([ + 'created', + 'createdAt', + 'id', + ]); + + expect(fake.stored[0]).toEqual({ + id: 'finding-0001', + kind: 'finding', + title: 'Post-earnings drift decays after day 3', + status: FILE_FINDING_INITIAL_STATUS, + createdAt: '2025-03-01T10:00:00.000Z', + summary: 'Cross-sectional CAR flattens after session +3 across 2015-2024.', + trialRefs: ['9007199254740993123', 'trial-101', 'trial-102'], + evidenceRefs: ['Snap-A', 'snap-a', 'snap-b'], + }); + + const deadEndRes = await callTool(server, 'file_finding', { + kind: 'dead_end', + title: 'Short-interest 1d reversal', + summary: 'No net edge after realistic borrow and spread costs.', + trialRefs: ['trial-101'], + }); + + expect(deadEndRes.isError).toBe(false); + expect(deadEndRes.payload).toEqual({ + id: 'finding-0002', + createdAt: '2025-03-01T10:01:00.000Z', + created: true, + }); + expect(fake.stored[1]).toEqual({ + id: 'finding-0002', + kind: 'dead_end', + title: 'Short-interest 1d reversal', + status: 'pending_review', + createdAt: '2025-03-01T10:01:00.000Z', + summary: 'No net edge after realistic borrow and spread costs.', + trialRefs: ['trial-101'], + evidenceRefs: [], + }); + expect(fake.invokedWriteMethods).toEqual(['appendFinding', 'appendFinding']); + }); + + test('rejects invalid inputs, blank or over-length fields, raw array limits, unknown fields, and metadata overrides with zero writes', async () => { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup(); + const clock = createFixedClock(); + const idGen = createFixedIdGenerator(); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + ], + }); + + const validBase = { + kind: 'finding', + title: 'Valid title', + summary: 'Valid research-visible summary', + trialRefs: ['trial-101'], + }; + + const invalidCases: readonly { + readonly label: string; + readonly args: Record; + readonly forbiddenSubstring?: string; + }[] = [ + { label: 'missing trialRefs', args: { kind: 'finding', title: 'T', summary: 'S' } }, + { label: 'empty trialRefs', args: { ...validBase, trialRefs: [] } }, + { label: 'blank trialRef', args: { ...validBase, trialRefs: [' '] } }, + { label: 'blank evidenceRef', args: { ...validBase, evidenceRefs: [' '] } }, + { label: 'blank title', args: { ...validBase, title: ' ' } }, + { label: 'blank summary', args: { ...validBase, summary: '\t\n ' } }, + { label: 'blank idempotencyKey', args: { ...validBase, idempotencyKey: ' ' } }, + { + label: 'over-length title', + args: { ...validBase, title: 'a'.repeat(FILE_FINDING_MAX_TITLE_LENGTH + 1) }, + }, + { + label: 'over-length summary', + args: { ...validBase, summary: 's'.repeat(FILE_FINDING_MAX_SUMMARY_LENGTH + 1) }, + }, + { + label: 'over-length trialRef', + args: { ...validBase, trialRefs: ['r'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, + }, + { + label: 'over-length evidenceRef', + args: { ...validBase, evidenceRefs: ['e'.repeat(FILE_FINDING_MAX_REF_LENGTH + 1)] }, + }, + { + label: 'over-length idempotencyKey', + args: { + ...validBase, + idempotencyKey: 'k'.repeat(FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH + 1), + }, + }, + { + label: 'raw trialRefs exceeds 32 even with duplicates', + args: { + ...validBase, + trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS + 1 }, () => 'trial-101'), + }, + }, + { + label: 'raw evidenceRefs exceeds 32 even with duplicates', + args: { + ...validBase, + evidenceRefs: Array.from( + { length: FILE_FINDING_MAX_EVIDENCE_REFS + 1 }, + () => 'snap-01' + ), + }, + }, + { + label: 'invalid kind does not echo caller value', + args: { ...validBase, kind: 'vault_secret_kind_sentinel' }, + forbiddenSubstring: 'vault_secret_kind_sentinel', + }, + { label: 'invalid title type', args: { ...validBase, title: 123 } }, + { label: 'invalid trialRefs type', args: { ...validBase, trialRefs: 'trial-101' } }, + { + label: 'caller-supplied id rejected', + args: { ...validBase, id: 'attacker-id' }, + forbiddenSubstring: 'attacker-id', + }, + { + label: 'caller-supplied status rejected', + args: { ...validBase, status: 'confirmed' }, + forbiddenSubstring: 'confirmed', + }, + { + label: 'caller-supplied createdAt rejected', + args: { ...validBase, createdAt: '2020-01-01T00:00:00.000Z' }, + forbiddenSubstring: '2020-01-01', + }, + { + label: 'holdout scope rejected without echoing key', + args: { ...validBase, scope: 'vault_evaluation_only' }, + forbiddenSubstring: 'scope', + }, + { + label: 'holdout vault_evaluation_only rejected without echoing key', + args: { ...validBase, vault_evaluation_only: true }, + forbiddenSubstring: 'vault_evaluation_only', + }, + { + label: 'holdout vaultCutoffTs rejected without echoing key', + args: { ...validBase, vaultCutoffTs: 1_700_000_000_000 }, + forbiddenSubstring: 'vaultCutoffTs', + }, + { + label: 'unknown-key sentinel rejected without echoing sentinel', + args: { ...validBase, vaultHoldoutKeySentinel_XYZ: 'secret-value' }, + forbiddenSubstring: 'vaultHoldoutKeySentinel_XYZ', + }, + ]; + + for (const testCase of invalidCases) { + const res = await callTool(server, 'file_finding', testCase.args); + expect(res.isError).toBe(true); + if (testCase.forbiddenSubstring !== undefined) { + expect(res.text).not.toContain(testCase.forbiddenSubstring); + } + if ( + testCase.label.includes('unknown-key') || + testCase.label.includes('holdout') || + testCase.label.includes('caller-supplied') + ) { + expect(res.text).toContain(FILE_FINDING_ERROR_UNKNOWN_KEYS); + } + } + + expect(fake.stored).toHaveLength(0); + expect(fake.appendCalls).toHaveLength(0); + expect(trialLookup.queriedRefs).toHaveLength(0); + expect(idGen.calls).toBe(0); + expect(clock.calls).toBe(0); + + // Raw 32 duplicate entries are accepted (bounds applied before dedup). + const maxRawRes = await callTool(server, 'file_finding', { + ...validBase, + trialRefs: Array.from({ length: FILE_FINDING_MAX_TRIAL_REFS }, () => 'trial-101'), + evidenceRefs: Array.from({ length: FILE_FINDING_MAX_EVIDENCE_REFS }, () => 'snap-1'), + }); + expect(maxRawRes.isError).toBe(false); + expect(fake.stored).toHaveLength(1); + expect(fake.stored[0]?.trialRefs).toEqual(['trial-101']); + expect(fake.stored[0]?.evidenceRefs).toEqual(['snap-1']); + }); + + test('rejects unknown and Vault-only trial refs identically with zero writes and zero metadata generation', async () => { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup({ + researchVisibleRefs: ['trial-101'], + vaultOnlyRefs: ['trial-vault-only-secret'], + }); + const clock = createFixedClock(); + const idGen = createFixedIdGenerator(); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + ], + }); + + const unknownRes = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Mixed valid and unknown ref', + summary: 'Should fail before writing.', + trialRefs: ['trial-101', 'trial-unknown-secret-ref'], + }); + + const vaultRes = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Mixed valid and Vault-only ref', + summary: 'Should fail identically to unknown ref.', + trialRefs: ['trial-101', 'trial-vault-only-secret'], + }); + + expect(unknownRes.isError).toBe(true); + expect(vaultRes.isError).toBe(true); + expect(unknownRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(vaultRes.text).toBe(FILE_FINDING_ERROR_UNAVAILABLE_TRIAL_REF); + expect(unknownRes.text).not.toContain('trial-unknown-secret-ref'); + expect(vaultRes.text).not.toContain('trial-vault-only-secret'); + expect(fake.stored).toHaveLength(0); + expect(fake.appendCalls).toHaveLength(0); + expect(idGen.calls).toBe(0); + expect(clock.calls).toBe(0); + }); + + test('sanitizes lookup and append exceptions so DSNs and stack markers never leak', async () => { + const fakeDsn = 'postgres://writer:supersecret@10.0.0.51:5432/trading_bot'; + const stackMarker = 'at internalPgPoolQuery (/srv/stock-bot/secret-adapter.ts:91:13)'; + + const lookupErr = new Error(`Lookup failed on ${fakeDsn}\n ${stackMarker}`); + lookupErr.name = 'PgConnectionError'; + + const lookupFake = createSharedFindingsFake(); + const failingLookup = createFakeTrialLookup({ throwError: lookupErr }); + const lookupServer = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: lookupFake.writePort, + trialLookup: failingLookup.port, + newId: createFixedIdGenerator().newId, + now: createFixedClock().now, + }), + ], + }); + + const lookupRes = await callTool(lookupServer, 'file_finding', { + kind: 'finding', + title: 'Lookup failure test', + summary: 'Summary text', + trialRefs: ['trial-101'], + }); + expect(lookupRes.isError).toBe(true); + expect(lookupRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(lookupRes.text).not.toContain(fakeDsn); + expect(lookupRes.text).not.toContain(stackMarker); + expect(lookupRes.text).not.toContain('PgConnectionError'); + expect(lookupFake.appendCalls).toHaveLength(0); + + const appendErr = new Error(`INSERT failed on ${fakeDsn}\n ${stackMarker}`); + appendErr.name = 'DatabaseWriteError'; + const appendFake = createSharedFindingsFake({ alwaysAppendError: appendErr }); + const appendServer = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: appendFake.writePort, + trialLookup: createFakeTrialLookup().port, + newId: createFixedIdGenerator().newId, + now: createFixedClock().now, + }), + ], + }); + + const appendRes = await callTool(appendServer, 'file_finding', { + kind: 'finding', + title: 'Append failure test', + summary: 'Summary text', + trialRefs: ['trial-101'], + }); + expect(appendRes.isError).toBe(true); + expect(appendRes.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(appendRes.text).not.toContain(fakeDsn); + expect(appendRes.text).not.toContain(stackMarker); + expect(appendRes.text).not.toContain('DatabaseWriteError'); + }); + + test('enforces idempotency replays, per-field conflicts, concurrent retries across instances, post-failure retry, and independent unkeyed calls', async () => { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup(); + const clock = createFixedClock('2025-03-01T14:00:00.000Z', 60_000); + const idGen = createFixedIdGenerator('idem'); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + ], + }); + + const first = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Momentum crowding signal', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-102', 'trial-101'], + idempotencyKey: ' key-001 ', + }); + expect(first.isError).toBe(false); + expect(first.payload).toEqual({ + id: 'idem-0001', + createdAt: '2025-03-01T14:00:00.000Z', + created: true, + }); + expect(fake.stored).toHaveLength(1); + + // Replay with whitespace, duplicate/reordered refs, and explicit empty evidenceRefs. + const replay = await callTool(server, 'file_finding', { + kind: 'finding', + title: ' Momentum crowding signal ', + summary: ' Observed IC decay during high volatility regimes. ', + trialRefs: ['trial-101', ' trial-102 ', 'trial-101'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }); + expect(replay.isError).toBe(false); + expect(replay.payload).toEqual({ + id: 'idem-0001', + createdAt: '2025-03-01T14:00:00.000Z', + created: false, + }); + expect(fake.stored).toHaveLength(1); + + // Changing each normalized payload field in turn causes a conflict with zero extra rows. + const conflictPayloads: readonly Record[] = [ + { + kind: 'dead_end', + title: 'Momentum crowding signal', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }, + { + kind: 'finding', + title: 'Different title', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }, + { + kind: 'finding', + title: 'Momentum crowding signal', + summary: 'Different summary', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }, + { + kind: 'finding', + title: 'Momentum crowding signal', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-101'], + evidenceRefs: [], + idempotencyKey: 'key-001', + }, + { + kind: 'finding', + title: 'Momentum crowding signal', + summary: 'Observed IC decay during high volatility regimes.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: ['snap-extra'], + idempotencyKey: 'key-001', + }, + ]; + + for (const conflictArgs of conflictPayloads) { + const res = await callTool(server, 'file_finding', conflictArgs); + expect(res.isError).toBe(true); + expect(res.text).toBe(FILE_FINDING_ERROR_IDEMPOTENCY_CONFLICT); + } + expect(fake.stored).toHaveLength(1); + + // Concurrent same-key calls across two separate tool instances sharing one port. + const concurrentFake = createSharedFindingsFake({ delayFirstAppendMs: 10 }); + const toolA = createFileFindingTool({ + port: concurrentFake.writePort, + trialLookup: trialLookup.port, + newId: createFixedIdGenerator('instA').newId, + now: createFixedClock('2025-03-02T00:00:00.000Z').now, + }); + const toolB = createFileFindingTool({ + port: concurrentFake.writePort, + trialLookup: trialLookup.port, + newId: createFixedIdGenerator('instB').newId, + now: createFixedClock('2025-03-02T05:00:00.000Z').now, + }); + const concurrentArgs = { + kind: 'finding', + title: 'Concurrent filing', + summary: 'Submitted concurrently by two retries.', + trialRefs: ['trial-101'], + idempotencyKey: 'concurrent-key', + }; + + const [resA, resB] = await Promise.all([ + toolA.execute(concurrentArgs), + toolB.execute(concurrentArgs), + ]); + expect(resA.isError).toBeUndefined(); + expect(resB.isError).toBeUndefined(); + const payloadA = JSON.parse(resA.content[0]?.text ?? '') as FileFindingResultPayload; + const payloadB = JSON.parse(resB.content[0]?.text ?? '') as FileFindingResultPayload; + expect(concurrentFake.stored).toHaveLength(1); + expect(payloadA.id).toBe(payloadB.id); + expect(payloadA.createdAt).toBe(payloadB.createdAt); + expect([payloadA.created, payloadB.created].sort()).toEqual([false, true]); + + // Retry after an injected pre-commit failure succeeds cleanly. + const retryFake = createSharedFindingsFake({ + failNextAppendError: new Error('transient pre-commit timeout'), + }); + const retryServer = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: retryFake.writePort, + trialLookup: trialLookup.port, + newId: createFixedIdGenerator('retry').newId, + now: createFixedClock('2025-03-03T08:00:00.000Z').now, + }), + ], + }); + + const failedAttempt = await callTool(retryServer, 'file_finding', { + kind: 'dead_end', + title: 'Retry after failure', + summary: 'First attempt fails before commit.', + trialRefs: ['trial-101'], + idempotencyKey: 'retry-key', + }); + expect(failedAttempt.isError).toBe(true); + expect(failedAttempt.text).toBe(FILE_FINDING_ERROR_FILING_FAILED); + expect(retryFake.stored).toHaveLength(0); + + const retryAttempt = await callTool(retryServer, 'file_finding', { + kind: 'dead_end', + title: 'Retry after failure', + summary: 'First attempt fails before commit.', + trialRefs: ['trial-101'], + idempotencyKey: 'retry-key', + }); + expect(retryAttempt.isError).toBe(false); + expect(retryAttempt.payload).toEqual({ + id: 'retry-0002', + createdAt: '2025-03-03T08:01:00.000Z', + created: true, + }); + expect(retryFake.stored).toHaveLength(1); + + // Unkeyed calls with identical payloads are independent. + const unkeyed1 = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Unkeyed entry', + summary: 'Independent unkeyed filing.', + trialRefs: ['trial-101'], + }); + const unkeyed2 = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Unkeyed entry', + summary: 'Independent unkeyed filing.', + trialRefs: ['trial-101'], + }); + expect(unkeyed1.isError).toBe(false); + expect(unkeyed2.isError).toBe(false); + expect(unkeyed1.payload?.created).toBe(true); + expect(unkeyed2.payload?.created).toBe(true); + expect(unkeyed1.payload?.id).not.toBe(unkeyed2.payload?.id); + expect(fake.stored).toHaveLength(3); + }); + + test('advertises strict schema via tools/list and round-trips filed records through read_knowledge', async () => { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup(); + const clock = createFixedClock('2025-03-04T09:30:00.000Z', 120_000); + const idGen = createFixedIdGenerator('kb'); + + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: idGen.newId, + now: clock.now, + }), + createReadKnowledgeTool({ + port: fake.knowledgePort, + }), + ], + }); + + const listRaw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'list-1', + method: 'tools/list', + }) + ); + expect(listRaw).not.toBeNull(); + const listParsed = JSON.parse(listRaw as string) as { + result: { + tools: { + name: string; + description: string; + inputSchema: { + type: string; + properties: Record>; + required?: string[]; + additionalProperties: boolean; + }; + }[]; + }; + }; + + expect(listParsed.result.tools.map(t => t.name)).toEqual(['file_finding', 'read_knowledge']); + const tool = listParsed.result.tools.find(t => t.name === 'file_finding'); + expect(tool).toBeDefined(); + expect(tool?.inputSchema.type).toBe('object'); + expect(tool?.inputSchema.additionalProperties).toBe(false); + expect(tool?.inputSchema.required).toEqual(['kind', 'title', 'summary', 'trialRefs']); + expect(tool?.inputSchema.properties.kind).toMatchObject({ + type: 'string', + enum: [...FILE_FINDING_KINDS], + }); + expect(tool?.inputSchema.properties.title).toMatchObject({ + type: 'string', + minLength: 1, + maxLength: FILE_FINDING_MAX_TITLE_LENGTH, + }); + expect(tool?.inputSchema.properties.summary).toMatchObject({ + type: 'string', + minLength: 1, + maxLength: FILE_FINDING_MAX_SUMMARY_LENGTH, + }); + expect(tool?.inputSchema.properties.trialRefs).toMatchObject({ + type: 'array', + minItems: 1, + maxItems: FILE_FINDING_MAX_TRIAL_REFS, + items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, + }); + expect(tool?.inputSchema.properties.evidenceRefs).toMatchObject({ + type: 'array', + maxItems: FILE_FINDING_MAX_EVIDENCE_REFS, + default: [], + items: { type: 'string', minLength: 1, maxLength: FILE_FINDING_MAX_REF_LENGTH }, + }); + expect(tool?.inputSchema.properties.idempotencyKey).toMatchObject({ + type: 'string', + minLength: 1, + maxLength: FILE_FINDING_MAX_IDEMPOTENCY_KEY_LENGTH, + }); + expect(tool?.inputSchema.properties.id).toBeUndefined(); + expect(tool?.inputSchema.properties.status).toBeUndefined(); + expect(tool?.inputSchema.properties.createdAt).toBeUndefined(); + expect(tool?.inputSchema.properties.scope).toBeUndefined(); + expect(tool?.inputSchema.properties.vault_evaluation_only).toBeUndefined(); + expect(tool?.inputSchema.properties.vaultCutoffTs).toBeUndefined(); + + // File both kinds via tools/call and read each back through read_knowledge. + const filedFinding = await callTool( + server, + 'file_finding', + { + kind: 'finding', + title: ' Event-study drift after SEC 8-K ', + summary: ' CAR peaks on session +2 and persists through +5. ', + trialRefs: ['trial-102', 'trial-101', 'trial-102'], + evidenceRefs: ['ev-html-2', 'ev-html-1'], + }, + 'call-f1' + ); + expect(filedFinding.isError).toBe(false); + const findingId = filedFinding.payload?.id as string; + + const filedDeadEnd = await callTool( + server, + 'file_finding', + { + kind: 'dead_end', + title: 'Intraday gap fade on microcaps', + summary: 'Edge disappears once 15 bps slippage is modeled.', + trialRefs: ['9007199254740993123'], + }, + 'call-f2' + ); + expect(filedDeadEnd.isError).toBe(false); + const deadEndId = filedDeadEnd.payload?.id as string; + + const readFinding = await callTool( + server, + 'read_knowledge', + { source: 'findings', id: findingId }, + 'call-r1' + ); + expect(readFinding.isError).toBe(false); + expect(readFinding.payload).toEqual({ + rowCount: 1, + sources: { library: 0, findings: 1, provider_caveats: 0 }, + rows: [ + { + source: 'findings', + id: findingId, + title: 'Event-study drift after SEC 8-K', + status: 'pending_review', + createdAt: '2025-03-04T09:30:00.000Z', + summary: 'CAR peaks on session +2 and persists through +5.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: ['ev-html-1', 'ev-html-2'], + truncated: false, + }, + ], + }); + expect(fake.stored.find(r => r.id === findingId)?.kind).toBe('finding'); + + const readDeadEnd = await callTool( + server, + 'read_knowledge', + { source: 'findings', id: deadEndId }, + 'call-r2' + ); + expect(readDeadEnd.isError).toBe(false); + expect(readDeadEnd.payload).toEqual({ + rowCount: 1, + sources: { library: 0, findings: 1, provider_caveats: 0 }, + rows: [ + { + source: 'findings', + id: deadEndId, + title: 'Intraday gap fade on microcaps', + status: 'pending_review', + createdAt: '2025-03-04T09:32:00.000Z', + summary: 'Edge disappears once 15 bps slippage is modeled.', + trialRefs: ['9007199254740993123'], + evidenceRefs: [], + truncated: false, + }, + ], + }); + expect(fake.stored.find(r => r.id === deadEndId)?.kind).toBe('dead_end'); + }); + + test('produces bit-identical receipts, stored records, and read-backs across deterministic replays', async () => { + async function runReplay() { + const fake = createSharedFindingsFake(); + const trialLookup = createFakeTrialLookup(); + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createFileFindingTool({ + port: fake.writePort, + trialLookup: trialLookup.port, + newId: createFixedIdGenerator('rep').newId, + now: createFixedClock('2025-03-05T00:00:00.000Z', 30_000).now, + }), + createReadKnowledgeTool({ port: fake.knowledgePort }), + ], + }); + + const r1 = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Replay finding', + summary: 'Deterministic summary.', + trialRefs: ['trial-102', 'trial-101'], + evidenceRefs: ['ev-b', 'ev-a'], + idempotencyKey: 'rep-key-1', + }); + const r2 = await callTool(server, 'file_finding', { + kind: 'finding', + title: 'Replay finding', + summary: 'Deterministic summary.', + trialRefs: ['trial-101', 'trial-102'], + evidenceRefs: ['ev-a', 'ev-b'], + idempotencyKey: 'rep-key-1', + }); + const r3 = await callTool(server, 'read_knowledge', { + source: 'findings', + }); + return { + receipts: [r1.payload, r2.payload], + stored: fake.stored, + knowledge: r3.payload, + }; + } + + const firstRun = await runReplay(); + const secondRun = await runReplay(); + expect(secondRun).toEqual(firstRun); + }); + + test('validates factory options eagerly and keeps MCP symbols out of browser-safe root export', () => { + const validPort = createSharedFindingsFake().writePort; + const validLookup = createFakeTrialLookup().port; + const validNewId = () => 'id-1'; + const validNow = () => Date.UTC(2025, 2, 1); + + expect(() => createFileFindingTool(null as never)).toThrow(/options/i); + expect(() => + createFileFindingTool({ + port: {} as never, + trialLookup: validLookup, + newId: validNewId, + now: validNow, + }) + ).toThrow(/port/i); + expect(() => + createFileFindingTool({ + port: validPort, + trialLookup: {} as never, + newId: validNewId, + now: validNow, + }) + ).toThrow(/trialLookup/i); + expect(() => + createFileFindingTool({ + port: validPort, + trialLookup: validLookup, + newId: 'not-a-fn' as never, + now: validNow, + }) + ).toThrow(/newId/i); + expect(() => + createFileFindingTool({ + port: validPort, + trialLookup: validLookup, + newId: validNewId, + now: 'not-a-fn' as never, + }) + ).toThrow(/now/i); + + expect( + fileFindingInputSchema.safeParse({ + kind: 'finding', + title: 'Schema export sanity check', + summary: 'Direct schema parse works.', + trialRefs: ['trial-101'], + }).success + ).toBe(true); + + expect(Object.keys(rootResearchExports)).not.toContain('createFileFindingTool'); + }); +});