T-149: M2.1h — MCP copilot analyze_signal: add a Vault-fenced fundamentals signal source (point-in-time fundamentalsAsOf month-end snapshots → SignalObservations) + extend the headless stdio end-to-end test to run a fundamental AND a shorts study (pure, injected ports, no new deps)

This commit is contained in:
Studio 2026-12-01 23:48:26 -05:00
parent ee826bdef4
commit 5de54be1e3
2 changed files with 121 additions and 18 deletions

View file

@ -705,8 +705,7 @@ function appendEligibleFundamentalsObservations(params: {
}
const rawValue = row[field];
const isFiniteValue = typeof rawValue === 'number' && Number.isFinite(rawValue);
if (!isFiniteValue && rawValue !== null) {
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
continue;
}
@ -717,10 +716,6 @@ function appendEligibleFundamentalsObservations(params: {
latestKnownAtByListing.set(normalizedListingId, normalizedKnownAt);
}
if (!isFiniteValue) {
continue;
}
const normalizedValue = rawValue === 0 ? 0 : rawValue;
const dedupeKey = `${normalizedListingId}:${normalizedKnownAt}`;
if (seenKeys.has(dedupeKey)) {
@ -1047,10 +1042,10 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
// Backfill vintages superseded earlier within this month (or prior
// to the first eligible bar for the initial month) by stepping to
// the latest uncovered eligible bar strictly before each returned
// vintage. When `allowEstimatedLag` is false, DuckDB omits listings
// whose latest vintage uses estimated publication lag, so treat
// omitted listings as unresolved intervals and probe earlier
// eligible closes in the month. Listings sharing a target bar
// vintage. Under either lag setting, a requested listing with no
// valid observation (omitted by DuckDB or carrying a null/non-finite
// field) is treated as an unresolved interval so earlier eligible
// closes within the month are probed. Listings sharing a target bar
// timestamp are batched.
const pendingByBarTs = new Map<number, number[]>();
const enqueueBackfill = (
@ -1060,14 +1055,10 @@ export function createAnalyzeSignalTool(options: AnalyzeSignalToolOptions): McpT
): void => {
for (const lid of queriedListingIds) {
const knownAt = knownByListing.get(lid);
let upperExclusive: number;
if (knownAt !== undefined) {
upperExclusive = Math.min(knownAt, upperBoundExclusiveMs);
} else if (!allowEstimatedLag) {
upperExclusive = upperBoundExclusiveMs;
} else {
continue;
}
const upperExclusive =
knownAt !== undefined
? Math.min(knownAt, upperBoundExclusiveMs)
: upperBoundExclusiveMs;
const prevBarTs = findLatestBarBefore(
barTimestampsByListing.get(lid),
upperExclusive,

View file

@ -3158,6 +3158,118 @@ describe('MCP analyze_signal tool — fundamentals source', () => {
expect(allowLagLedger.rows[0]?.daily_series).not.toEqual(mcpLedger.rows[0]?.daily_series);
}
expect(allowLagStore.fundamentalsCalls.every(c => c.allowEstimatedLag === true)).toBe(true);
// 6. Stale March null row for an omitted listing must not suppress April omission backfill;
// exact payload and ledger rows must match the clean run.
const staleNullKnownAt = makeUtcMs('2023-03-20', 13);
const staleNullStore = createFakeStore({
bars,
fundamentalsResolver: q => {
const cleanTable = queryFundamentalsFixtureRows(pitRows, q);
const returnedIds = new Set(cleanTable.rows.map(r => r.listing_id));
const injected: TableRow[] = [];
for (const omittedTarget of [listingIds[1]!, listingIds[5]!]) {
if (q.listingIds.includes(omittedTarget) && !returnedIds.has(omittedTarget)) {
injected.push({
listing_id: omittedTarget,
effective_known_at: staleNullKnownAt,
known_at_source: 'sec_edgar_filing',
has_estimated_lag: false,
period_end: '2022-12-31',
fiscal_period: 'Q1',
currency: 'USD',
period_known_at: staleNullKnownAt,
ttm_revenue: null,
ttm_period_end: null,
ttm_currency: null,
ttm_has_estimated_lag: false,
});
}
}
return {
columns: cleanTable.columns,
rows: [...cleanTable.rows, ...injected],
};
},
});
const staleNullLedger = createFakeTrialLedger();
const staleNullRes = await callAnalyzeSignal({
store: staleNullStore.store,
ledger: staleNullLedger.executor,
vaultCutoffTs,
args: {
listingIds,
from: allDates[0]!,
to: allDates[allDates.length - 1]!,
signal: { source: 'fundamentals', field: 'ttm_revenue' },
horizonSessions: 3,
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
},
});
expect(staleNullRes.isError).toBe(false);
expect(staleNullRes.text).toBe(mcpRes.text);
expect(staleNullLedger.rows).toEqual(mcpLedger.rows);
for (const call of staleNullStore.fundamentalsCalls) {
expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs);
expect(call.allowEstimatedLag).toBe(false);
}
// 7. Genuinely null latest field with allowEstimatedLag: true must still probe earlier
// eligible closes and recover the valid April 5 release.
const nullLatestPitRows: FundamentalsPitFixtureRow[] = pitRows.map(row =>
row.effective_known_at === aprEstimatedLagKnownAt ? { ...row, ttm_revenue: null } : row
);
const nullLatestAllowLagStore = createFakeStore({
bars,
fundamentalsResolver: q => queryFundamentalsFixtureRows(nullLatestPitRows, q),
});
const nullLatestAllowLagLedger = createFakeTrialLedger();
const nullLatestAllowLagRes = await callAnalyzeSignal({
store: nullLatestAllowLagStore.store,
ledger: nullLatestAllowLagLedger.executor,
vaultCutoffTs,
args: {
listingIds,
from: allDates[0]!,
to: allDates[allDates.length - 1]!,
signal: { source: 'fundamentals', field: 'ttm_revenue', allowEstimatedLag: true },
horizonSessions: 3,
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
},
});
expect(nullLatestAllowLagRes.isError).toBe(false);
const nullLatestAllowLagPayload = JSON.parse(
nullLatestAllowLagRes.text
) as AnalyzeSignalResultPayload;
expect(nullLatestAllowLagPayload.status).toBe('ok');
if (nullLatestAllowLagPayload.status === 'ok') {
expect(nullLatestAllowLagPayload.analysis.rankIc).toEqual(
directVerifiedStudy.analysis.rankIc
);
expect(nullLatestAllowLagPayload.analysis.pearsonIc).toEqual(
directVerifiedStudy.analysis.pearsonIc
);
expect(nullLatestAllowLagLedger.rows[0]?.daily_series).toEqual(
directVerifiedLedger.rows[0]?.daily_series
);
const recoveredByDate = new Map(
nullLatestAllowLagPayload.analysis.ledgerSeries.points.map(p => [p.date, p.value])
);
let recoveredAprilDiffCount = 0;
for (const d of aprilPreEstimatedDates) {
if (recoveredByDate.get(d) !== brokenByDate.get(d)) {
recoveredAprilDiffCount += 1;
}
}
expect(recoveredAprilDiffCount).toBeGreaterThan(0);
}
expect(nullLatestAllowLagStore.fundamentalsCalls.length).toBeGreaterThan(0);
for (const call of nullLatestAllowLagStore.fundamentalsCalls) {
expect(Date.parse(call.asOf)).toBeLessThan(vaultCutoffTs);
expect(call.allowEstimatedLag).toBe(true);
}
});
test('Vault fence and defensive filtering: clean vs deliberately leaky fundamentals store produce identical payloads and ledger rows', async () => {