T-131: M2.1b — MCP copilot analyze_signal tool: vault-fenced short-interest signal study (bars + shortsAsOf → forward-return panel → analyzeSignal + trial ledger) in libs/research/src/mcp/tools/

This commit is contained in:
Studio 2026-12-01 00:14:59 -05:00
parent e7bd019bb6
commit ff9a180f12
3 changed files with 434 additions and 98 deletions

View file

@ -333,6 +333,7 @@ function createFakeStore(options?: {
idSet.has(row.listingId) &&
row.ts >= fromMs &&
row.ts <= toMs &&
row.ts <= asOfMs &&
row.knownAt <= asOfMs
);
@ -697,9 +698,83 @@ describe('MCP analyze_signal tool', () => {
});
expect(runOtherField.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash);
// Different horizonSessions -> different expressionHash
const runOtherHorizon = await runWithArgs({ ...baseArgs, horizonSessions: 10 });
// Different horizonSessions -> different expressionHash (including position_10d_plus bucket for 11d)
const runOtherHorizon = await runWithArgs({
...baseArgs,
horizonSessions: 11,
horizonBucket: 'position_10d_plus',
});
expect(runOtherHorizon.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash);
expect(runOtherHorizon.ledger.rows[0]?.horizon_bucket).toBe('position_10d_plus');
// Equivalent date/timestamp/offset forms canonicalize to identical effective microsecond bounds & expressionHash
const midDate = fixture.allDates[120]!;
const runDateForm = await runWithArgs({
...baseArgs,
from,
to: midDate,
asOf: midDate,
});
const runIsoMicrosForm = await runWithArgs({
...baseArgs,
from: `${from}T00:00:00.000000Z`,
to: `${midDate}T23:59:59.999999Z`,
asOf: `${midDate}T23:59:59.999999Z`,
});
const runOffsetForm = await runWithArgs({
...baseArgs,
from: '2022-08-31T19:00:00.000000-05:00',
to: `${midDate}T18:59:59.999999-05:00`,
asOf: `${midDate}T18:59:59.999999-05:00`,
});
expect(runDateForm.payload.effectiveFrom).toBe(`${from}T00:00:00.000Z`);
expect(runDateForm.payload.effectiveTo).toBe(`${midDate}T23:59:59.999999Z`);
expect(runDateForm.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999999Z`);
expect(runIsoMicrosForm.payload.effectiveFrom).toBe(runDateForm.payload.effectiveFrom);
expect(runIsoMicrosForm.payload.effectiveTo).toBe(runDateForm.payload.effectiveTo);
expect(runIsoMicrosForm.payload.effectiveAsOf).toBe(runDateForm.payload.effectiveAsOf);
expect(runIsoMicrosForm.payload.trial.expressionHash).toBe(
runDateForm.payload.trial.expressionHash
);
expect(runOffsetForm.payload.trial.expressionHash).toBe(
runDateForm.payload.trial.expressionHash
);
// Distinct sub-millisecond effective bounds produce different expressionHash even with identical sampleStart/sampleEnd
const runAsOfZeroMicros = await runWithArgs({
...baseArgs,
from,
to: midDate,
asOf: `${midDate}T23:59:59.999000Z`,
});
expect(runAsOfZeroMicros.payload.effectiveAsOf).toBe(`${midDate}T23:59:59.999Z`);
expect(runAsOfZeroMicros.payload.trial.sampleStart).toBe(runDateForm.payload.trial.sampleStart);
expect(runAsOfZeroMicros.payload.trial.sampleEnd).toBe(runDateForm.payload.trial.sampleEnd);
expect(runAsOfZeroMicros.payload.trial.expressionHash).not.toBe(
runDateForm.payload.trial.expressionHash
);
const runToZeroMicros = await runWithArgs({
...baseArgs,
from,
to: `${midDate}T23:59:59.999000Z`,
asOf: midDate,
});
expect(runToZeroMicros.payload.effectiveTo).toBe(`${midDate}T23:59:59.999Z`);
expect(runToZeroMicros.payload.trial.expressionHash).not.toBe(
runDateForm.payload.trial.expressionHash
);
const runFromOneMicro = await runWithArgs({
...baseArgs,
from: `${from}T00:00:00.000001Z`,
to: midDate,
asOf: midDate,
});
expect(runFromOneMicro.payload.effectiveFrom).toBe(`${from}T00:00:00.000001Z`);
expect(runFromOneMicro.payload.trial.expressionHash).not.toBe(
runDateForm.payload.trial.expressionHash
);
// quantile_spread ledgerSeries works, truncates preview to 100 while preserving full count, and hashes distinctly
const runSpread = await runWithArgs({ ...baseArgs, ledgerSeries: 'quantile_spread' });
@ -713,65 +788,12 @@ describe('MCP analyze_signal tool', () => {
expect(runSpread.payload.trial.expressionHash).not.toBe(run1.payload.trial.expressionHash);
});
test('clamps to/asOf strictly below cutoff and blocks post-cutoff and post-asOf leakage from a leaky store, including intraday cutoff', async () => {
test('clamps to/asOf strictly below midnight and intraday Vault cutoffs and blocks cutoff-day leakage from a leaky store', async () => {
const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false });
const poisonedFixture = buildCeoShortsFixture({ poisonPostCutoff: true });
const from = cleanFixture.allDates[0]!;
const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!;
// Add a mid-window explicit asOf and verify rows known after asOf are excluded even from a leaky store
const explicitAsOfDate = cleanFixture.allDates[100]!;
const explicitAsOfMs = makeUtcMs(explicitAsOfDate, 23) + 59 * 60_000 + 59_999;
const cleanStore = createFakeStore({
bars: cleanFixture.bars,
shortsTable: cleanFixture.shortsTable,
leaky: false,
});
const leakyStore = createFakeStore({
bars: [
...poisonedFixture.bars,
// Extra bar on exact vaultCutoffDate before an intraday cutoff
{
listingId: poisonedFixture.listingIds[0]!,
ts: makeUtcMs(poisonedFixture.vaultCutoffDate, 10),
open: 888_888,
high: 888_888,
low: 888_888,
close: 888_888,
volume: 100,
vwap: 888_888,
knownAt: makeUtcMs(poisonedFixture.vaultCutoffDate, 10),
},
],
shortsTable: {
columns: poisonedFixture.shortsTable.columns,
rows: [
...poisonedFixture.shortsTable.rows,
// Shorts row with report_date on vaultCutoffDate and known_at before intraday cutoff
{
listing_id: poisonedFixture.listingIds[0]!,
report_date: poisonedFixture.vaultCutoffDate,
known_at: makeUtcMs(poisonedFixture.vaultCutoffDate, 9),
shares_short: 9_999_999,
net_change: 9_999_999,
pct_float: 0.99,
source: 'ceoShorts',
},
// Shorts row with known_at after explicitAsOf
{
listing_id: poisonedFixture.listingIds[1]!,
report_date: cleanFixture.allDates[50]!,
known_at: explicitAsOfMs + 60_000,
shares_short: 7_777_777,
net_change: 7_777_777,
pct_float: 0.77,
source: 'ceoShorts',
},
],
},
leaky: true,
});
const horizonSessions = 5;
// 1. Clamping test with to and asOf after Vault cutoff (midnight cutoff)
const clampLedger = createFakeTrialLedger();
@ -789,7 +811,7 @@ describe('MCP analyze_signal tool', () => {
to: postCutoffDate,
asOf: postCutoffDate,
signal: { source: 'shorts', field: 'net_change' },
horizonSessions: 5,
horizonSessions,
universeMarket: 'CA_EQ',
horizonBucket: 'swing_1_10d',
},
@ -813,48 +835,246 @@ describe('MCP analyze_signal tool', () => {
expect(Date.parse(clampStore.shortsCalls[0]?.asOf ?? '')).toBe(cleanFixture.vaultCutoffTs - 1);
if (clampPayload.status === 'ok') {
expect(clampPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true);
const endIdx = cleanFixture.allDates.indexOf(clampPayload.trial.sampleEnd);
const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!;
expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true);
}
// 2. Leaky store with intraday cutoff (12:00 UTC on vaultCutoffDate) and earlier explicit asOf matches clean store
// 2. Intraday Vault cutoff (12:00 UTC on vaultCutoffDate) with asOf beyond cutoff and leaky store
// injecting rows on vaultCutoffDate before cutoff, at exact cutoff timestamp, and after cutoff.
const intradayCutoffTs = makeUtcMs(cleanFixture.vaultCutoffDate, 12);
const cleanPreCutoffBars = cleanFixture.bars.filter(
b => new Date(b.ts).toISOString().slice(0, 10) < cleanFixture.vaultCutoffDate
);
const cleanPreCutoffShorts: Table = {
columns: cleanFixture.shortsTable.columns,
rows: cleanFixture.shortsTable.rows.filter(
r =>
(r.report_date as string) < cleanFixture.vaultCutoffDate &&
(r.known_at as number) < intradayCutoffTs
),
};
const cleanIntradayStore = createFakeStore({
bars: cleanPreCutoffBars,
shortsTable: cleanPreCutoffShorts,
leaky: false,
});
const leakyIntradayStore = createFakeStore({
bars: [
...poisonedFixture.bars,
// Cutoff-day bars BEFORE intradayCutoffTs (10:00 UTC) for every listing
...poisonedFixture.listingIds.map(listingId => ({
listingId,
ts: makeUtcMs(poisonedFixture.vaultCutoffDate, 10),
open: 888_888,
high: 888_888,
low: 888_888,
close: 888_888,
volume: 100,
vwap: 888_888,
knownAt: makeUtcMs(poisonedFixture.vaultCutoffDate, 10),
})),
// Bar at EXACT intradayCutoffTs (12:00 UTC)
{
listingId: poisonedFixture.listingIds[0]!,
ts: intradayCutoffTs,
open: 777_777,
high: 777_777,
low: 777_777,
close: 777_777,
volume: 100,
vwap: 777_777,
knownAt: intradayCutoffTs,
},
],
shortsTable: {
columns: poisonedFixture.shortsTable.columns,
rows: [
...poisonedFixture.shortsTable.rows,
// Shorts row on vaultCutoffDate with known_at before intradayCutoffTs
{
listing_id: poisonedFixture.listingIds[0]!,
report_date: poisonedFixture.vaultCutoffDate,
known_at: makeUtcMs(poisonedFixture.vaultCutoffDate, 9),
shares_short: 9_999_999,
net_change: 9_999_999,
pct_float: 0.99,
source: 'ceoShorts',
},
// Shorts row with report_date before cutoff but known_at at exact intradayCutoffTs
{
listing_id: poisonedFixture.listingIds[1]!,
report_date: cleanFixture.allDates[100]!,
known_at: intradayCutoffTs,
shares_short: 8_888_888,
net_change: 8_888_888,
pct_float: 0.88,
source: 'ceoShorts',
},
],
},
leaky: true,
});
const cleanIntradayLedger = createFakeTrialLedger();
const leakyIntradayLedger = createFakeTrialLedger();
const intradayArgs = {
listingIds: cleanFixture.listingIds,
from,
to: postCutoffDate,
asOf: postCutoffDate,
signal: { source: 'shorts', field: 'net_change' },
horizonSessions,
universeMarket: 'CA_EQ',
horizonBucket: 'swing_1_10d',
};
const cleanIntradayRes = await callAnalyzeSignal({
store: cleanIntradayStore.store,
ledger: cleanIntradayLedger.executor,
vaultCutoffTs: intradayCutoffTs,
args: intradayArgs,
});
const leakyIntradayRes = await callAnalyzeSignal({
store: leakyIntradayStore.store,
ledger: leakyIntradayLedger.executor,
vaultCutoffTs: intradayCutoffTs,
args: intradayArgs,
});
expect(cleanIntradayRes.isError).toBe(false);
expect(leakyIntradayRes.isError).toBe(false);
expect(leakyIntradayRes.text).toBe(cleanIntradayRes.text);
expect(leakyIntradayLedger.rows).toEqual(cleanIntradayLedger.rows);
const intradayPayload = JSON.parse(leakyIntradayRes.text) as AnalyzeSignalResultPayload;
expect(intradayPayload.status).toBe('ok');
expect(intradayPayload.clampedTo).toBe(true);
expect(intradayPayload.clampedAsOf).toBe(true);
expect(intradayPayload.toMs).toBe(intradayCutoffTs - 1);
expect(intradayPayload.asOfMs).toBe(intradayCutoffTs - 1);
if (intradayPayload.status === 'ok') {
expect(intradayPayload.trial.sampleEnd < cleanFixture.vaultCutoffDate).toBe(true);
const endIdx = cleanFixture.allDates.indexOf(intradayPayload.trial.sampleEnd);
const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!;
expect(lastForwardEndpoint < cleanFixture.vaultCutoffDate).toBe(true);
}
});
test('earlier explicit asOf excludes bars with ts > asOf or knownAt > asOf independently from a leaky store and matches clean replay', async () => {
const cleanFixture = buildCeoShortsFixture({ poisonPostCutoff: false });
const from = cleanFixture.allDates[0]!;
const postCutoffDate = cleanFixture.allDates[cleanFixture.allDates.length - 1]!;
const horizonSessions = 5;
// Set asOf to noon UTC on session 100 while `to` extends past cutoff
const asOfSessionIdx = 100;
const asOfDate = cleanFixture.allDates[asOfSessionIdx]!;
const asOfIso = `${asOfDate}T12:00:00.000Z`;
const asOfMs = makeUtcMs(asOfDate, 12);
// Clean replay store filters strictly by ts <= asOfMs && knownAt <= asOfMs
const cleanStore = createFakeStore({
bars: cleanFixture.bars,
shortsTable: cleanFixture.shortsTable,
leaky: false,
});
// Leaky store injects two independent bar leaks + a delayed shorts row:
// (a) Closing bars on `asOfDate` stamped at 21:00 UTC (> noon asOf) with knownAt at 00:00 UTC (<= noon asOf) and poisoned close
// (b) Delayed bars on session 95 (ts <= noon asOf) with knownAt at 15:00 UTC on `asOfDate` (> noon asOf) and poisoned close
const delayedBarDate = cleanFixture.allDates[95]!;
const leakyBars: BarRecord[] = cleanFixture.bars.map(bar => {
if (bar.ts === makeUtcMs(asOfDate, 21)) {
return {
...bar,
open: 666_666,
high: 666_666,
low: 666_666,
close: 666_666,
vwap: 666_666,
knownAt: makeUtcMs(asOfDate, 0), // earlier than noon asOf, while ts (21:00 UTC) > noon asOf
};
}
return bar;
});
// Also inject a bar with ts <= asOfMs but knownAt > asOfMs for listing 0 on session 95 (replace clean bar? No, add extra listing or poisoned bar on a date not in clean? Better: inject on a date after clean or with a listing that has a delayed knownAt!)
// Specifically: take a clean bar on session 95 for listing 0 and verify a delayed-knownAt poison bar on session 100-1 (where ts <= asOfMs and knownAt > asOfMs) is dropped.
// Even stronger: add a synthetic bar on `delayedBarDate` at 10:00 UTC (ts <= asOfMs) with knownAt = 15:00 UTC on `asOfDate` (> asOfMs) and poisoned close 555_555.
// If knownAt filter regresses, buildForwardReturnPanel will throw duplicate_bar (conflicting close on delayedBarDate)!
leakyBars.push({
listingId: cleanFixture.listingIds[0]!,
ts: makeUtcMs(delayedBarDate, 10),
open: 555_555,
high: 555_555,
low: 555_555,
close: 555_555,
volume: 100,
vwap: 555_555,
knownAt: makeUtcMs(asOfDate, 15), // > noon asOf, while ts <= noon asOf
});
const leakyStore = createFakeStore({
bars: leakyBars,
shortsTable: {
columns: cleanFixture.shortsTable.columns,
rows: [
...cleanFixture.shortsTable.rows,
{
listing_id: cleanFixture.listingIds[1]!,
report_date: cleanFixture.allDates[50]!,
known_at: makeUtcMs(asOfDate, 15), // > noon asOf
shares_short: 7_777_777,
net_change: 7_777_777,
pct_float: 0.77,
source: 'ceoShorts',
},
],
},
leaky: true,
});
const cleanLedger = createFakeTrialLedger();
const leakyLedger = createFakeTrialLedger();
const args = {
listingIds: cleanFixture.listingIds,
from,
to: postCutoffDate,
asOf: asOfIso,
signal: { source: 'shorts', field: 'net_change' },
horizonSessions,
universeMarket: 'CA_EQ',
horizonBucket: 'swing_1_10d',
};
const cleanRes = await callAnalyzeSignal({
store: cleanStore.store,
ledger: cleanLedger.executor,
vaultCutoffTs: intradayCutoffTs,
args: {
listingIds: cleanFixture.listingIds,
from,
to: postCutoffDate,
asOf: explicitAsOfDate,
signal: { source: 'shorts', field: 'net_change' },
horizonSessions: 5,
universeMarket: 'CA_EQ',
horizonBucket: 'swing_1_10d',
},
vaultCutoffTs: cleanFixture.vaultCutoffTs,
args,
});
const leakyRes = await callAnalyzeSignal({
store: leakyStore.store,
ledger: leakyLedger.executor,
vaultCutoffTs: intradayCutoffTs,
args: {
listingIds: cleanFixture.listingIds,
from,
to: postCutoffDate,
asOf: explicitAsOfDate,
signal: { source: 'shorts', field: 'net_change' },
horizonSessions: 5,
universeMarket: 'CA_EQ',
horizonBucket: 'swing_1_10d',
},
vaultCutoffTs: cleanFixture.vaultCutoffTs,
args,
});
expect(cleanRes.isError).toBe(false);
expect(leakyRes.isError).toBe(false);
expect(leakyRes.text).toBe(cleanRes.text);
expect(leakyLedger.rows).toEqual(cleanLedger.rows);
const payload = JSON.parse(leakyRes.text) as AnalyzeSignalResultPayload;
expect(payload.status).toBe('ok');
expect(payload.clampedAsOf).toBe(false);
expect(payload.asOfMs).toBe(asOfMs);
if (payload.status === 'ok') {
const endIdx = cleanFixture.allDates.indexOf(payload.trial.sampleEnd);
const lastForwardEndpoint = cleanFixture.allDates[endIdx + horizonSessions]!;
// Closing bar on asOfDate (21:00 UTC) was excluded by ts > asOfMs, so last forward endpoint must precede asOfDate
expect(lastForwardEndpoint < asOfDate).toBe(true);
}
});
test('request wholly inside Vault holdout returns fixed VaultHoldoutFenceError with zero store and ledger calls', async () => {
@ -1173,6 +1393,56 @@ describe('MCP analyze_signal tool', () => {
],
['horizonSessions float', { ...validBase, horizonSessions: 2.5 }],
['negative maxSignalAgeSessions', { ...validBase, maxSignalAgeSessions: -1 }],
['mismatched horizonBucket intraday for 5d daily horizon', { ...validBase, horizonSessions: 5, horizonBucket: 'intraday' }],
[
'mismatched horizonBucket position_10d_plus for 5d daily horizon',
{ ...validBase, horizonSessions: 5, horizonBucket: 'position_10d_plus' },
],
[
'mismatched horizonBucket swing_1_10d for 11d daily horizon',
{ ...validBase, horizonSessions: 11, horizonBucket: 'swing_1_10d' },
],
[
'mismatched horizonBucket intraday for 15d daily horizon',
{ ...validBase, horizonSessions: 15, horizonBucket: 'intraday' },
],
[
'named universe CA_EQ with mismatched universeMarket FX',
{
from: validBase.from,
to: validBase.to,
signal: validBase.signal,
horizonSessions: 5,
universe: 'CA_EQ',
universeMarket: 'FX',
horizonBucket: 'swing_1_10d',
},
],
[
'named universe CA_EQ with mismatched universeMarket US_EQ',
{
from: validBase.from,
to: validBase.to,
signal: validBase.signal,
horizonSessions: 5,
universe: 'CA_EQ',
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
},
],
[
'named universe US_CA_EQ with mismatched universeMarket US_EQ',
{
from: validBase.from,
to: validBase.to,
signal: validBase.signal,
horizonSessions: 5,
universe: 'US_CA_EQ',
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
},
],
['shorts study with FX universeMarket and listingIds', { ...validBase, universeMarket: 'FX' }],
];
for (const [_label, args] of invalidCases) {