"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(sec): key reporting periods on their span, and page oversized results
Haozhe Wufde1aa58f449
diff --git a/agent/backtest/loaders/fundamentals_loader.py b/agent/backtest/loaders/fundamentals_loader.pyindex ba2318c85..d7c1a0240 100644--- a/agent/backtest/loaders/fundamentals_loader.py+++ b/agent/backtest/loaders/fundamentals_loader.py@@ -21,6 +21,7 @@ import pandas as pdfrom backtest.loaders import sec_edgar_clientfrom backtest.loaders.base import cached_loader_fetch, validate_date_range+from backtest.loaders.sec_frames import ANNUAL_SPAN_DAYS, QUARTER_SPAN_DAYSlogger = logging.getLogger(__name__)@@ -116,7 +117,7 @@ def _extract_concept_series(df = df.drop_duplicates(subset=["period_start", "period_end"], keep=keep)duration = (df["period_end"] - df["period_start"]).dt.daysif freq == "annual":- df = df[duration.between(330, 380)]+ df = df[duration.between(*ANNUAL_SPAN_DAYS)]else:df = _quarterly_flow_frames(df, duration)else:@@ -138,8 +139,8 @@ def _quarterly_flow_frames(df: pd.DataFrame, duration: pd.Series) -> pd.DataFram``FY - (Q1 + Q2 + Q3)``. The synthesized row is anchored on the 10-K``filed`` date, which keeps it PIT-safe."""- quarters = df[duration.between(60, 120)].copy()- annuals = df[duration.between(330, 380)]+ quarters = df[duration.between(*QUARTER_SPAN_DAYS)].copy()+ annuals = df[duration.between(*ANNUAL_SPAN_DAYS)]quarter_ends = set(quarters["period_end"])synthesized: list[dict[str, Any]] = []for annual in annuals.to_dict("records"):@@ -383,6 +384,20 @@ def _compute_derived(derived: Any, dependencies: dict[str, pd.DataFrame]) -> pd.def _resolve_ciks(symbols: list[str]) -> dict[str, str | None]:+ """Map each symbol to its SEC CIK.++ Args:+ symbols: Requested symbols.++ Returns:+ A symbol -> CIK mapping; the value is ``None`` for a symbol the SEC+ ticker table does not carry.++ Raises:+ ValueError: If no symbol resolves. Returning an all-null panel here+ reads as "this issuer reports nothing" rather than "this loader+ cannot serve this market", which is the more damaging of the two.+ """ciks: dict[str, str | None] = {}missing: list[str] = []for symbol in symbols:@@ -392,6 +407,12 @@ def _resolve_ciks(symbols: list[str]) -> dict[str, str | None]:missing.append(symbol)if missing:logger.warning("No SEC CIK for symbols: %s", ", ".join(missing))+ if symbols and len(missing) == len(symbols):+ raise ValueError(+ f"no SEC CIK resolved for any of: {', '.join(missing)}. The "+ "fundamentals loader is US-only (SEC XBRL); pass a US ticker with "+ "or without a .US suffix, e.g. 'AAPL' or 'AAPL.US'."+ )return ciksdiff --git a/agent/backtest/loaders/sec_edgar_client.py b/agent/backtest/loaders/sec_edgar_client.pyindex c232dafb1..1073e6eb4 100644--- a/agent/backtest/loaders/sec_edgar_client.py+++ b/agent/backtest/loaders/sec_edgar_client.py@@ -43,6 +43,10 @@ _MIN_INTERVAL_DEFAULT = 0.12_MIN_INTERVAL_ENV = "VIBE_TRADING_SEC_MIN_INTERVAL"_TICKERS_URL = "https://www.sec.gov/files/company_tickers.json"++# Symbol suffixes that denote a market rather than a share class, so they can be+# stripped before a ticker lookup.+_MARKET_SUFFIXES = frozenset({"US"})_SUBMISSIONS_URL = "https://data.sec.gov/submissions/CIK{cik}.json"_COMPANY_FACTS_URL = "https://data.sec.gov/api/xbrl/companyfacts/CIK{cik}.json"@@ -174,7 +178,21 @@ def cik_for(ticker: str) -> Optional[str]:"""if not ticker or not ticker.strip():return None- return _ticker_map().get(ticker.strip().upper())+ table = _ticker_map()+ candidate = ticker.strip().upper()+ if candidate in table:+ return table[candidate]+ # ``AAPL.US`` is this project's US symbol convention while the SEC table+ # carries the bare ticker. Only a known market suffix may be stripped — a+ # trailing ``.B`` is a share class, not a market.+ head, _, tail = candidate.rpartition(".")+ if head and tail in _MARKET_SUFFIXES:+ candidate = head+ if candidate in table:+ return table[candidate]+ # The SEC table writes share classes with a dash (``BRK-B``, ``MOG-A``) and+ # contains no dots at all; users and vendors commonly write a dot.+ return table.get(candidate.replace(".", "-"))def get_submissions(cik: str | int) -> Dict[str, Any]:diff --git a/agent/backtest/loaders/sec_frames.py b/agent/backtest/loaders/sec_frames.pynew file mode 100644index 000000000..664012f06--- /dev/null+++ b/agent/backtest/loaders/sec_frames.py@@ -0,0 +1,128 @@+"""Shared period-frame selection for SEC XBRL ``companyfacts`` rows.++``companyfacts`` interleaves several kinds of fact row that can share an ``end``+date:++* **instant** facts (balance-sheet concepts) carry no ``start`` at all;+* **true-quarter** duration frames span roughly 90 days;+* **year-to-date** duration frames span roughly 180 or 270 days;+* **full-year** duration frames span roughly 365 days.++A 10-Q reports the true quarter *and* the year-to-date frame for the same+``end``, under the same ``fy``, ``fp``, ``form`` and ``accn``. Any consumer that+identifies a period by ``end`` — with or without those four companions —+therefore silently conflates a nine-month figure with the quarter that ends on+the same day. On live AAPL revenue data 36 of 81 such keys collide.++The only field that separates them is ``start``, so the identity of a reporting+period is exactly the ``(start, end)`` span. This module is the single+implementation of that rule; ``fundamentals_loader`` and the SEC tools all route+through it rather than re-deriving the thresholds.+"""++from __future__ import annotations++from typing import Any++import pandas as pd++# Inclusive day-count windows. Quarters run 89-93 days but issuers with 4-4-5+# fiscal calendars stretch further, and 52/53-week years land either side of+# 365, so both windows are deliberately generous.+QUARTER_SPAN_DAYS = (60, 120)+ANNUAL_SPAN_DAYS = (330, 380)++#: Period-type labels emitted by :func:`classify_span`.+INSTANT = "instant"+QUARTER = "quarter"+ANNUAL = "annual"+YTD = "ytd"+++def span_days(row: dict[str, Any]) -> int | None:+ """Return the number of days a duration fact covers.++ Args:+ row: One SEC ``companyfacts`` unit row.++ Returns:+ The day count between ``start`` and ``end``, or ``None`` when the row is+ an instant fact (no ``start``) or either date fails to parse.+ """+ start, end = row.get("start"), row.get("end")+ if not start or not end:+ return None+ start_ts = pd.to_datetime(start, errors="coerce")+ end_ts = pd.to_datetime(end, errors="coerce")+ if pd.isna(start_ts) or pd.isna(end_ts):+ return None+ return int((end_ts - start_ts).days)+++def is_quarter_span(days: int | None) -> bool:+ """Return whether ``days`` falls in the true-quarter window."""+ return days is not None and QUARTER_SPAN_DAYS[0] <= days <= QUARTER_SPAN_DAYS[1]+++def is_annual_span(days: int | None) -> bool:+ """Return whether ``days`` falls in the full-year window."""+ return days is not None and ANNUAL_SPAN_DAYS[0] <= days <= ANNUAL_SPAN_DAYS[1]+++def classify_span(days: int | None) -> str:+ """Label a span as instant, quarter, annual, or year-to-date.++ Args:+ days: Output of :func:`span_days`.++ Returns:+ One of :data:`INSTANT`, :data:`QUARTER`, :data:`ANNUAL`, :data:`YTD`.+ Anything that is a duration but matches neither the quarter nor the+ annual window is year-to-date or a stub period, and is labelled+ :data:`YTD` so a caller never mistakes it for a reporting period.+ """+ if days is None:+ return INSTANT+ if is_quarter_span(days):+ return QUARTER+ if is_annual_span(days):+ return ANNUAL+ return YTD+++def frame_key(row: dict[str, Any]) -> tuple[Any, Any]:+ """Return the identity of the reporting period a fact row belongs to.++ ``(start, end)`` and nothing else. Including ``fy`` would split one period+ into a separate row per filing that reports it as a comparative, and+ including only ``end`` would collide a year-to-date frame with the true+ quarter ending the same day.++ Args:+ row: One SEC ``companyfacts`` unit row.++ Returns:+ The ``(start, end)`` pair; ``start`` is ``None`` for instant facts.+ """+ return (row.get("start"), row.get("end"))+++def matches_cadence(row: dict[str, Any], period: str) -> bool:+ """Return whether a fact row is a reporting period at the requested cadence.++ Args:+ row: One SEC ``companyfacts`` unit row.+ period: ``"annual"`` or ``"quarter"``.++ Returns:+ ``True`` for instant facts (they are valid at any cadence and are keyed+ on ``end``), for full-year frames when ``period`` is ``"annual"``, and+ for true-quarter frames when ``period`` is ``"quarter"``. Year-to-date+ frames never match.+ """+ kind = classify_span(span_days(row))+ if kind == INSTANT:+ return True+ if period == "annual":+ return kind == ANNUAL+ return kind == QUARTERdiff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 5ddabc063..1b498af93 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -47,12 +47,12 @@ from src.providers.content_filter import (from src.config.accessor import get_env_configfrom src.config.paths import get_runs_dir, get_sessions_dirfrom src.tools.background_tools import get_background_manager+from src.config.limits import TOOL_RESULT_LIMIT, truncate_tool_resultfrom src.tools.redaction import redact_payload, redact_tool_resultRUNS_DIR = get_runs_dir()SESSIONS_DIR = get_sessions_dir()KEEP_RECENT = 3-TOOL_RESULT_LIMIT = 10_000LLM_USAGE_ARTIFACT = "llm_usage.json"COLLAPSE_PRESERVE_RECENT = 6@@ -1706,7 +1706,7 @@ class AgentLoop:)status = "ok" if success else "error"- truncated = result[:TOOL_RESULT_LIMIT]+ truncated = truncate_tool_result(result)messages.append(context.format_tool_result(tc.id, tc.name, truncated))# One redaction feeds every subscriber below: the persisted tracediff --git a/agent/src/config/limits.py b/agent/src/config/limits.pynew file mode 100644index 000000000..253d37a49--- /dev/null+++ b/agent/src/config/limits.py@@ -0,0 +1,48 @@+"""Shared runtime limits for tool results.++The cap on a tool result used to live in :mod:`src.agent.loop` and was copied as+a bare literal into :mod:`src.swarm.worker`, so the two could drift. It lives+here instead: a leaf module with no imports of its own, which the agent loop,+the swarm worker and individual tools can all read without any of them taking a+dependency on the others.+"""++from __future__ import annotations++#: Maximum characters of a single tool result handed back to the model.+TOOL_RESULT_LIMIT = 10_000++_TRUNCATION_NOTICE = (+ "\n\n[TRUNCATED: {shown} of {total} characters delivered. The remainder was "+ "not sent. Do not treat this as the complete result — narrow the request, "+ "or call the tool again with its paging parameter if it has one.]"+)+++def truncate_tool_result(result: str, limit: int = TOOL_RESULT_LIMIT) -> str:+ """Cut an oversized tool result to ``limit`` characters and say so.++ A silent cut is indistinguishable from a complete answer, so the model+ reports a prefix as if it were the whole thing. Measured on live data,+ ``get_financial_statements("AAPL.US", period="quarter")`` returns 28,498+ characters for 40 periods; the silent cut delivered roughly 12 of them.++ Args:+ result: The full tool result.+ limit: Maximum characters to deliver, notice included.++ Returns:+ ``result`` unchanged when it fits, otherwise a prefix of exactly+ ``limit`` characters or fewer, ending in a notice that states how much+ was withheld.+ """+ total = len(result)+ if total <= limit:+ return result+ notice = _TRUNCATION_NOTICE.format(shown=limit, total=total)+ body = limit - len(notice)+ if body <= 0:+ # Pathologically small limit: the notice alone is more useful than a+ # fragment, so deliver it rather than silently cutting to nothing.+ return notice[:limit]+ return result[:body] + _TRUNCATION_NOTICE.format(shown=body, total=total)diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.pyindex a32abc33c..a62451448 100644--- a/agent/src/swarm/worker.py+++ b/agent/src/swarm/worker.py@@ -17,6 +17,7 @@ from src.agent.context import ContextBuilderfrom src.agent.progress import HeartbeatTimerfrom src.agent.skills import SkillsLoaderfrom src.agent.tools import ToolRegistry+from src.config.limits import TOOL_RESULT_LIMITfrom src.config.schema import AgentConfigfrom src.providers.chat import ChatLLM, LLMResponse, ProviderStreamErrorfrom src.providers.content_filter import (@@ -711,7 +712,9 @@ def run_worker(},)messages.append(- ContextBuilder.format_tool_result(tc.id, tc.name, result[:10_000])+ ContextBuilder.format_tool_result(+ tc.id, tc.name, result[:TOOL_RESULT_LIMIT]+ ))# Content filter ratio trackingdiff --git a/agent/src/tools/_result_paging.py b/agent/src/tools/_result_paging.pynew file mode 100644index 000000000..18e583415--- /dev/null+++ b/agent/src/tools/_result_paging.py@@ -0,0 +1,66 @@+"""Fit a list of records into one tool result without dropping the tail silently.++A tool result is cut at :data:`src.config.limits.TOOL_RESULT_LIMIT` characters.+For a JSON envelope that cut lands mid-structure, so the model receives a broken+fragment and — worse — reads the records that survived as if they were the whole+answer. Measured live before this existed:+``get_financial_statements("AAPL.US", statement="income", period="quarter")``+serialized to 28,498 characters for 40 quarters and delivered roughly 12.++Records are therefore paged whole. The envelope carries a ``paging`` block+stating the total, what was returned, and where to resume, so a partial answer+is self-describing rather than indistinguishable from a complete one.+"""++from __future__ import annotations++import json+from typing import Any, Callable++from src.config.limits import TOOL_RESULT_LIMIT+++def fit_records(+ records: list[Any],+ offset: int,+ build: Callable[[list[Any], dict[str, Any]], dict[str, Any]],+ *,+ limit: int = TOOL_RESULT_LIMIT,+ max_records: int | None = None,+) -> str:+ """Serialize the largest whole-record page of ``records[offset:]`` that fits.++ Args:+ records: All available records, newest first by the caller's ordering.+ offset: Index to start the page at.+ build: Callback taking ``(page, paging_meta)`` and returning the full+ envelope dict to serialize.+ limit: Character budget for the serialized envelope.+ max_records: Optional ceiling on records per page, applied before the+ character budget.++ Returns:+ The serialized envelope, at most ``limit`` characters, containing whole+ records only.+ """+ remaining = records[offset:]+ count = len(remaining)+ if max_records is not None:+ count = min(count, max_records)++ while True:+ page = remaining[:count]+ next_offset = offset + len(page)+ meta = {+ "total": len(records),+ "offset": offset,+ "returned": len(page),+ "next_offset": None if next_offset >= len(records) else next_offset,+ "complete": next_offset >= len(records),+ }+ payload = json.dumps(build(page, meta), ensure_ascii=False)+ if len(payload) <= limit or count <= 1:+ return payload+ # Shrink proportionally to the overflow, then one further so a page of+ # unusually wide records still converges in a couple of rounds.+ count = max(1, min(count - 1, int(count * limit / len(payload))))diff --git a/agent/src/tools/financial_statements_tool.py b/agent/src/tools/financial_statements_tool.pyindex 076cb5ee5..1cd42531c 100644--- a/agent/src/tools/financial_statements_tool.py+++ b/agent/src/tools/financial_statements_tool.py@@ -28,9 +28,11 @@ import jsonimport loggingfrom typing import Any+from backtest.loaders import sec_framesfrom backtest.loaders.eastmoney_client import get_json, resolve_secidfrom backtest.loaders.sec_edgar_client import cik_for, get_company_factsfrom src.agent.tools import BaseTool+from src.tools._result_paging import fit_recordslogger = logging.getLogger(__name__)@@ -138,16 +140,19 @@ def _truncate_period(record: dict[str, Any]) -> dict[str, Any]:def _cap_periods(periods: list[dict[str, Any]]) -> list[dict[str, Any]]:- """Keep the most recent periods, each truncated to a safe field count.+ """Cap each period's field count, keeping every period.++ The record count is no longer clipped here: ``execute`` pages whole periods+ against the result-size budget, so clipping at the parser would put the+ older history permanently out of reach of any ``offset``.Args:periods: Period records as returned by the provider parser.Returns:- A new list of at most :data:`_MAX_PERIODS` field-capped records.+ A new list of field-capped records, one per input period."""- capped = periods[:_MAX_PERIODS]- return [_truncate_period(record) for record in capped]+ return [_truncate_period(record) for record in periods]def _eastmoney_market_group(secid: str) -> str | None:@@ -304,8 +309,20 @@ def _pick_sec_unit(units: dict[str, Any]) -> tuple[str, list[Any]]:return best_key, best_rows-def _sec_period_matches(row: dict[str, Any], period: str) -> bool:- """Return whether a SEC fact row belongs in the requested cadence."""+def _sec_instant_matches(row: dict[str, Any], period: str) -> bool:+ """Return whether an instant (balance-sheet) fact belongs in the cadence.++ Instant facts carry no span, so their cadence can only be read off the+ filing they came from: a fiscal-year-end balance sheet is the one reported+ on a 10-K.++ Args:+ row: One SEC ``companyfacts`` unit row with no ``start``.+ period: ``"annual"`` or ``"quarter"``.++ Returns:+ ``True`` when the fact should be kept.+ """if period != "annual":return Truefp = str(row.get("fp") or "").upper()@@ -313,6 +330,165 @@ def _sec_period_matches(row: dict[str, Any], period: str) -> bool:return fp == "FY" or form == "10-K"+def _record_sec_fact(+ bucket: dict[tuple[Any, Any], dict[str, Any]],+ row: dict[str, Any],+ concept_name: str,+ value: float,+ unit_key: str,+) -> None:+ """Merge one fact into the period record identified by its ``(start, end)``.++ A period is filed once as the primary period and then repeated as a+ comparative in later filings, which may restate it. The earliest filing+ carries the correct fiscal label, the latest carries the current value, so+ both are kept and both dates are surfaced.++ Args:+ bucket: Period records keyed by :func:`sec_frames.frame_key`.+ row: One SEC ``companyfacts`` unit row.+ concept_name: The us-gaap concept this value belongs to.+ value: The parsed numeric value.+ unit_key: The unit bucket the value came from (e.g. ``"USD"``).+ """+ key = sec_frames.frame_key(row)+ filed = str(row.get("filed") or "")+ record = bucket.get(key)+ if record is None:+ days = sec_frames.span_days(row)+ record = bucket[key] = {+ "REPORT_DATE": row.get("end"),+ "PERIOD_START": row.get("start"),+ "PERIOD_DAYS": days,+ "PERIOD_TYPE": sec_frames.classify_span(days),+ "FISCAL_YEAR": row.get("fy"),+ "FISCAL_PERIOD": row.get("fp"),+ "FORM": row.get("form"),+ "ACCESSION": row.get("accn"),+ "FILED": filed or None,+ "LAST_FILED": filed or None,+ "_units": {},+ "_filed": {},+ }+ if filed and filed < (record["FILED"] or filed):+ record["FISCAL_YEAR"] = row.get("fy")+ record["FISCAL_PERIOD"] = row.get("fp")+ record["FORM"] = row.get("form")+ record["ACCESSION"] = row.get("accn")+ record["FILED"] = filed+ if filed > (record["LAST_FILED"] or ""):+ record["LAST_FILED"] = filed+ if filed >= record["_filed"].get(concept_name, ""):+ record["_filed"][concept_name] = filed+ record[concept_name] = value+ record["_units"][concept_name] = unit_key+++def _synthesize_fiscal_q4(+ frames: dict[tuple[Any, Any], dict[str, Any]],+ annual_frames: dict[tuple[Any, Any], dict[str, Any]],+) -> None:+ """Derive fiscal Q4 rows, which issuers report only inside the 10-K.++ Flow concepts are never filed as a standalone Q4 duration frame, so without+ this the fourth quarter simply vanishes from a quarterly series. It is+ derived as ``FY - (Q1 + Q2 + Q3)``, the same way+ :mod:`backtest.loaders.fundamentals_loader` derives it for the PIT panel,+ and marked ``DERIVED`` so a computed figure is never mistaken for a filed+ one.++ Args:+ frames: True-quarter period records; synthesized rows are added here.+ annual_frames: Full-year period records used as the raw material.+ """+ quarter_ends = {+ record["REPORT_DATE"]+ for record in frames.values()+ if record["PERIOD_TYPE"] == sec_frames.QUARTER+ }+ for (start, end), annual in annual_frames.items():+ if not start or end in quarter_ends:+ continue+ inside = [+ record+ for record in frames.values()+ if record["PERIOD_TYPE"] == sec_frames.QUARTER+ and record["PERIOD_START"]+ and record["PERIOD_START"] >= start+ and record["REPORT_DATE"] < end+ ]+ if len(inside) != 3:+ continue+ values = {+ concept: annual[concept] - sum(quarter[concept] for quarter in inside)+ for concept in annual["_units"]+ if all(concept in quarter for quarter in inside)+ }+ if not values:+ continue+ q4_start = max(quarter["REPORT_DATE"] for quarter in inside)+ filed = max(+ [annual["FILED"] or ""] + [quarter["FILED"] or "" for quarter in inside]+ )+ record = {+ "REPORT_DATE": end,+ "PERIOD_START": q4_start,+ "PERIOD_DAYS": sec_frames.span_days({"start": q4_start, "end": end}),+ "PERIOD_TYPE": sec_frames.QUARTER,+ "FISCAL_YEAR": annual["FISCAL_YEAR"],+ "FISCAL_PERIOD": "Q4",+ "FORM": annual["FORM"],+ "ACCESSION": annual["ACCESSION"],+ "FILED": filed or None,+ "LAST_FILED": filed or None,+ "DERIVED": "FY - (Q1 + Q2 + Q3)",+ "_units": {concept: annual["_units"][concept] for concept in values},+ "_filed": {},+ }+ record.update(values)+ frames[(q4_start, end)] = record+++def _merge_sec_instants(+ frames: dict[tuple[Any, Any], dict[str, Any]],+) -> list[dict[str, Any]]:+ """Fold instant facts into the duration period ending on the same day.++ ``indicators`` mixes balance-sheet concepts (instant) with income-statement+ concepts (duration); without merging, one reporting period would come back+ as two half-populated rows.++ Args:+ frames: All period records for the requested cadence.++ Returns:+ One record per reporting period.+ """+ durations = [+ record+ for record in frames.values()+ if record["PERIOD_TYPE"] != sec_frames.INSTANT+ ]+ instants = {+ record["REPORT_DATE"]: record+ for record in frames.values()+ if record["PERIOD_TYPE"] == sec_frames.INSTANT+ }+ if not durations:+ return list(instants.values())+ for record in durations:+ instant = instants.get(record["REPORT_DATE"])+ if instant is None:+ continue+ for concept, unit_key in instant["_units"].items():+ record.setdefault(concept, instant[concept])+ record["_units"].setdefault(concept, unit_key)+ covered = {record["REPORT_DATE"] for record in durations}+ return durations + [+ record for end, record in instants.items() if end not in covered+ ]++def _fetch_sec_statement(code: str, *, statement: str, period: str) -> dict[str, Any]:"""Fetch one US statement from SEC companyfacts, shaped as flat periods.@@ -343,7 +519,12 @@ def _fetch_sec_statement(code: str, *, statement: str, period: str) -> dict[str,if not isinstance(gaap, dict):return {"periods": []}- periods_by_key: dict[tuple[Any, ...], dict[str, Any]] = {}+ # Keyed on the ``(start, end)`` span, never on ``end`` alone: a 10-Q files+ # the true quarter and the year-to-date frame under the same end date, and+ # the same fy/fp/form/accn, so any narrower key silently lets one overwrite+ # the other.+ frames: dict[tuple[Any, Any], dict[str, Any]] = {}+ annual_frames: dict[tuple[Any, Any], dict[str, Any]] = {}for concept_name in _SEC_CONCEPTS[statement]:concept = gaap.get(concept_name)units = concept.get("units") if isinstance(concept, dict) else None@@ -351,32 +532,38 @@ def _fetch_sec_statement(code: str, *, statement: str, period: str) -> dict[str,continueunit_key, rows = _pick_sec_unit(units)for row in rows:- if not isinstance(row, dict) or not _sec_period_matches(row, period):+ if not isinstance(row, dict):continue- end = row.get("end")value = _to_number(row.get("val"))- if not end or value is None:+ if not row.get("end") or value is None:continue- key = (end, row.get("fy"), row.get("fp"), row.get("form"), row.get("accn"))- period_row = periods_by_key.setdefault(- key,- {- "REPORT_DATE": end,- "FISCAL_YEAR": row.get("fy"),- "FISCAL_PERIOD": row.get("fp"),- "FORM": row.get("form"),- "ACCESSION": row.get("accn"),- "_units": {},- },- )- period_row[concept_name] = value- period_row["_units"][concept_name] = unit_key+ kind = sec_frames.classify_span(sec_frames.span_days(row))+ if kind == sec_frames.YTD:+ continue+ if kind == sec_frames.INSTANT:+ if not _sec_instant_matches(row, period):+ continue+ bucket = frames+ elif kind == sec_frames.ANNUAL:+ # A full year is the annual cadence, and the raw material for a+ # synthesized fiscal Q4 when the cadence is quarterly.+ bucket = frames if period == "annual" else annual_frames+ else:+ if period == "annual":+ continue+ bucket = frames+ _record_sec_fact(bucket, row, concept_name, value, unit_key)++ if period == "quarter":+ _synthesize_fiscal_q4(frames, annual_frames)periods = sorted(- periods_by_key.values(),+ _merge_sec_instants(frames),key=lambda row: str(row.get("REPORT_DATE") or ""),reverse=True,)+ for record in periods:+ record.pop("_filed", None)return {"periods": _cap_periods(periods)}@@ -441,6 +628,15 @@ class FinancialStatementsTool(BaseTool):),"default": "annual",},+ "offset": {+ "type": "integer",+ "description": (+ "Index of the first period to return, newest first; "+ "defaults to 0. Periods are returned whole and only as many "+ "as fit one result — read paging.total and paging.next_offset "+ "in the response and call again to continue."+ ),+ },},"required": ["code"],}@@ -492,15 +688,38 @@ class FinancialStatementsTool(BaseTool):# The fetch failed for every requested code (here, the single ``code``)# iff its result carries an ``error``. Surface that as a top-level# ``ok: false`` so a nested failure is never masked by ``ok: true``.- all_failed = "error" in result- envelope: dict[str, Any] = {- "ok": not all_failed,- "market": market,- "source": source,- "statement": statement,- "period": period,- "data": {code: result},- }- if all_failed:- envelope["error"] = result["error"]- return json.dumps(envelope, ensure_ascii=False)+ if "error" in result:+ return json.dumps(+ {+ "ok": False,+ "market": market,+ "source": source,+ "statement": statement,+ "period": period,+ "data": {code: result},+ "error": result["error"],+ },+ ensure_ascii=False,+ )++ try:+ offset = max(int(kwargs.get("offset") or 0), 0)+ except (TypeError, ValueError):+ return _error("offset must be an integer")++ # Page whole periods. A raw character cut lands mid-record, and the+ # model reads the periods that survived as the issuer's full history.+ periods = result.get("periods") or []++ def _build(page: list[dict[str, Any]], paging: dict[str, Any]) -> dict[str, Any]:+ return {+ "ok": True,+ "market": market,+ "source": source,+ "statement": statement,+ "period": period,+ "paging": paging,+ "data": {code: dict(result, periods=page)},+ }++ return fit_records(periods, offset, _build, max_records=_MAX_PERIODS)diff --git a/agent/src/tools/get_fundamentals_tool.py b/agent/src/tools/get_fundamentals_tool.pyindex e98e54926..feebaa41b 100644--- a/agent/src/tools/get_fundamentals_tool.py+++ b/agent/src/tools/get_fundamentals_tool.py@@ -14,7 +14,10 @@ from src.agent.tools import BaseToollogger = logging.getLogger(__name__)_VALID_FREQS = ("annual", "quarterly", "ttm")-_VALID_SOURCES = ("auto", "sec", "eastmoney", "tushare")+# Mirrors what ``load_fundamental_panel`` actually accepts. Advertising+# ``eastmoney``/``tushare`` here made the agent pick a source the loader rejects+# at runtime.+_VALID_SOURCES = ("auto", "sec")def _error(message: str) -> str:@@ -74,7 +77,11 @@ class GetFundamentalsTool(BaseTool):"symbols": {"type": "array","items": {"type": "string"},- "description": 'Symbols such as ["AAPL.US", "600519.SH", "00700.HK"].',+ "description": (+ "US tickers, with or without a .US suffix, e.g. "+ '["AAPL", "MSFT.US", "BRK-B"]. This tool is US-only: it '+ "reads SEC XBRL, so A-share and HK symbols are rejected."+ ),},"fields": {"type": "array",diff --git a/agent/src/tools/load_skill_tool.py b/agent/src/tools/load_skill_tool.pyindex 7bff4b526..7a94c29f3 100644--- a/agent/src/tools/load_skill_tool.py+++ b/agent/src/tools/load_skill_tool.py@@ -1,4 +1,17 @@-"""Load skill tool: load full skill documentation by name."""+"""Load skill tool: load full skill documentation by name, in pages.++Skill documents *are* the implementation for a large part of this product — the+bond maths, the implied-vol solver, the impact models and the China market+structure all live in markdown the agent reads and executes. A tool result is+capped at :data:`src.config.limits.TOOL_RESULT_LIMIT` characters, and 31 of the 88+bundled skills exceed it: ``tushare`` delivers 9.7% of its 103,037 characters,+``options-payoff`` 33.8%, ``credit-analysis`` 43.0%. The cut used to be silent,+so the agent could not tell a complete document from an amputated one and had no+way to reach the rest.++The envelope therefore always states how much of the document was delivered and+where to resume, and ``offset`` lets the agent page through the remainder.+"""from __future__ import annotations@@ -7,17 +20,38 @@ from typing import Anyfrom src.agent.skills import SkillsLoaderfrom src.agent.tools import BaseTool+from src.config.limits import TOOL_RESULT_LIMIT++# Characters of skill body per page. The cap applies to the whole serialized+# envelope, so this leaves room for the surrounding JSON keys and counters.+_PAGE_CHARS = TOOL_RESULT_LIMIT - 600++# Floor on the shrink loop so a pathologically escape-heavy document still makes+# forward progress rather than paging one character at a time.+_MIN_PAGE_CHARS = 1_000class LoadSkillTool(BaseTool):"""Load the full documentation for a named skill."""name = "load_skill"- description = "Load full documentation for a named skill. Use this to learn about unfamiliar strategy patterns or workflows before starting."+ description = (+ "Load full documentation for a named skill. Use this to learn about "+ "unfamiliar strategy patterns or workflows before starting. Long skills "+ "are returned in pages: when the result reports next_offset, call again "+ "with that offset to read the rest."+ )parameters = {"type": "object","properties": {"name": {"type": "string", "description": "Skill name (e.g. 'strategy-generate', 'momentum')"},+ "offset": {+ "type": "integer",+ "description": (+ "Character offset to read from; defaults to 0. Pass the "+ "next_offset value from a previous call to continue."+ ),+ },},"required": ["name"],}@@ -32,17 +66,67 @@ class LoadSkillTool(BaseTool):self._loader = skills_loader or SkillsLoader()def execute(self, **kwargs: Any) -> str:- """Load skill documentation.+ """Load one page of a skill's documentation.Args:- **kwargs: Must include name.+ **kwargs: Must include ``name``; may include ``offset``.Returns:- Full skill documentation or an error message.+ A JSON envelope carrying the page plus ``total_chars``, ``offset``,+ ``next_offset`` and ``complete`` so a partial read is never mistaken+ for the whole document."""name = kwargs["name"]content = self._loader.get_content(name)- return json.dumps({- "status": "ok" if not content.startswith("Error:") else "error",- "content": content,- }, ensure_ascii=False)+ if content.startswith("Error:"):+ return json.dumps({"status": "error", "content": content}, ensure_ascii=False)++ try:+ offset = max(int(kwargs.get("offset") or 0), 0)+ except (TypeError, ValueError):+ return json.dumps(+ {"status": "error", "content": "Error: offset must be an integer"},+ ensure_ascii=False,+ )++ total = len(content)+ if offset >= total and total:+ return json.dumps(+ {+ "status": "error",+ "content": (+ f"Error: offset {offset} is past the end of skill "+ f"{name!r} ({total} characters)"+ ),+ },+ ensure_ascii=False,+ )++ # The cap applies to the serialized envelope, and JSON escaping is+ # content-dependent — a newline-dense page costs two characters per+ # line break. Size the page by what it actually serializes to, or a+ # markdown-heavy skill silently loses its tail all over again.+ size = _PAGE_CHARS+ while True:+ page = content[offset : offset + size]+ next_offset = offset + len(page)+ complete = next_offset >= total+ envelope = json.dumps(+ {+ "status": "ok",+ "content": page,+ "total_chars": total,+ "offset": offset,+ "next_offset": None if complete else next_offset,+ "complete": complete,+ },+ ensure_ascii=False,+ )+ if len(envelope) <= TOOL_RESULT_LIMIT or size <= _MIN_PAGE_CHARS:+ return envelope+ # Shrink proportionally to the overflow, then a little further so a+ # page dense in escapes still converges in a couple of rounds.+ size = max(+ _MIN_PAGE_CHARS,+ int(size * TOOL_RESULT_LIMIT / len(envelope)) - 64,+ )diff --git a/agent/src/tools/sec_filings_tool.py b/agent/src/tools/sec_filings_tool.pyindex 2782029ce..a72c0676d 100644--- a/agent/src/tools/sec_filings_tool.py+++ b/agent/src/tools/sec_filings_tool.py@@ -22,12 +22,14 @@ from __future__ import annotationsimport jsonfrom typing import Any, Dict, List, Optional+from backtest.loaders import sec_framesfrom backtest.loaders.sec_edgar_client import (cik_for,get_company_facts,get_submissions,)from src.agent.tools import BaseTool+from src.tools._result_paging import fit_records# Hard caps so a long filing history or metric series cannot bloat the payload._MAX_LIMIT = 40@@ -76,6 +78,15 @@ class SecFilingsTool(BaseTool):"carries the reported time series for that concept."),},+ "offset": {+ "type": "integer",+ "description": (+ "Index of the first filing to return, newest first; "+ "defaults to 0. Filings are returned whole and only as many "+ "as fit one result — read paging.total and paging.next_offset "+ "and call again to continue."+ ),+ },"limit": {"type": "integer","description": (@@ -98,8 +109,10 @@ class SecFilingsTool(BaseTool):Returns:A JSON string envelope. On success:``{"ok": true, "market": "US", "source": "sec_edgar",- "data": {"ticker", "cik", "filings": [...], "metric": {...}}}``- (``metric`` present only when requested). On failure:+ "paging": {...}, "data": {"ticker", "cik", "filings": [...],+ "metric": {...}}}`` (``metric`` present only when requested).+ ``filings`` is paged: read ``paging.next_offset`` to continue.+ On failure:``{"ok": false, "error": str}``."""ticker = kwargs.get("ticker")@@ -129,23 +142,35 @@ class SecFilingsTool(BaseTool):filings = _parse_filings(submissions, form_filter, cik)- data: Dict[str, Any] = {- "ticker": ticker,- "cik": cik,- "filings": filings,- }-+ metric_block: Dict[str, Any] | None = Noneif metric_name is not None:try:facts = get_company_facts(cik)except Exception as exc: # noqa: BLE001 - surface any fetch failure as envelopereturn _error(f"SEC companyfacts request failed: {exc}")- data["metric"] = _parse_metric(facts, metric_name, limit)+ metric_block = _parse_metric(facts, metric_name, limit)- return json.dumps(- {"ok": True, "market": "US", "source": "sec_edgar", "data": data},- ensure_ascii=False,- )+ try:+ offset = max(int(kwargs.get("offset") or 0), 0)+ except (TypeError, ValueError):+ return _error("offset must be an integer")++ # The filing index is the bulk of this envelope — 12,077 of 12,190+ # characters for a bare AAPL call, i.e. the default request already+ # overflowed the result budget and lost its tail without saying so.+ def _build(page: List[Any], paging: Dict[str, Any]) -> Dict[str, Any]:+ data: Dict[str, Any] = {"ticker": ticker, "cik": cik, "filings": page}+ if metric_block is not None:+ data["metric"] = metric_block+ return {+ "ok": True,+ "market": "US",+ "source": "sec_edgar",+ "paging": paging,+ "data": data,+ }++ return fit_records(filings, offset, _build)def _clamp_limit(value: Any) -> int:@@ -243,9 +268,11 @@ def _parse_metric(facts: Any, metric_name: str, limit: int) -> Dict[str, Any]:"""Extract one us-gaap concept's reported series from a companyfacts payload.XBRL companyfacts nest as ``facts.us-gaap.<Concept>.units.<Unit>`` -> a list- of points (``{end, val, fy, fp, form, accn, frame?}``). We surface the most- populated unit, newest points last in source order then truncated to the- most recent ``limit``.+ of points (``{start?, end, val, fy, fp, form, accn, filed, frame?}``). We+ surface the most populated unit, deduplicated to one point per ``(start,+ end)`` span, sorted oldest first and truncated to the most recent ``limit``.+ Each point carries its span so a year-to-date frame can never be read as a+ quarter.Args:facts: Decoded companyfacts JSON.@@ -275,6 +302,20 @@ def _parse_metric(facts: Any, metric_name: str, limit: int) -> Dict[str, Any]:base["unit"] = unit_keypoints = [p for p in (_normalize_point(r) for r in rows) if p is not None]+ # A period is filed once and then repeated as a comparative in every later+ # filing, so keeping each vintage both inflates the series and pushes real+ # history out of ``limit``. Identity is the ``(start, end)`` span; the+ # newest filing wins so a restatement is what surfaces.+ latest: Dict[tuple[Any, Any], Dict[str, Any]] = {}+ for point in points:+ key = (point["start"], point["end"])+ prior = latest.get(key)+ if prior is None or str(point["filed"] or "") >= str(prior["filed"] or ""):+ latest[key] = point+ points = sorted(+ latest.values(),+ key=lambda point: (str(point["end"] or ""), str(point["start"] or "")),+ )base["points"] = points[-limit:] if limit > 0 else pointsreturn base@@ -305,8 +346,8 @@ def _normalize_point(row: Any) -> Optional[Dict[str, Any]]:row: One element of a unit's fact list.Returns:- ``{end, val, fiscal_year, fiscal_period, form, accession, frame}`` or- ``None``.+ ``{end, val, start, period_days, period_type, filed, fiscal_year,+ fiscal_period, form, accession, frame}`` or ``None``."""if not isinstance(row, dict):return None@@ -314,9 +355,17 @@ def _normalize_point(row: Any) -> Optional[Dict[str, Any]]:val = _to_number(row.get("val"))if not end and val is None:return None+ days = sec_frames.span_days(row)return {"end": end,"val": val,+ # Without the span a nine-month year-to-date figure is indistinguishable+ # from the quarter ending the same day, and both are reported under the+ # same fiscal_period on the same 10-Q.+ "start": row.get("start"),+ "period_days": days,+ "period_type": sec_frames.classify_span(days),+ "filed": row.get("filed"),"fiscal_year": row.get("fy"),"fiscal_period": row.get("fp"),"form": row.get("form"),diff --git a/agent/tests/test_fundamentals_pit.py b/agent/tests/test_fundamentals_pit.pyindex c11f54c5f..2fcb6a21d 100644--- a/agent/tests/test_fundamentals_pit.py+++ b/agent/tests/test_fundamentals_pit.py@@ -326,3 +326,43 @@ def test_ytd_and_full_year_frames_are_excluded_and_q4_is_synthesized(# NOT values inflated by the 30.0 YTD frame or the 100.0 full-year frame.assert series.loc[pd.Timestamp("2024-02-01")] == 100.0assert series.loc[pd.Timestamp("2024-02-02")] == 100.0+++def test_unresolvable_symbols_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None:+ """A market this loader cannot serve must raise, not return an empty panel.++ ``get_fundamentals("600519.SH")`` used to answer ``ok: true`` with every+ value null, which reads as "this issuer reports nothing" rather than "this+ loader is US-only".+ """+ _install_schema_stub(monkeypatch)+ _patch_sec(monkeypatch, {})++ with pytest.raises(ValueError, match="no SEC CIK resolved"):+ fundamentals_loader.load_fundamental_panel(+ symbols=["600519.SH"],+ fields=["revenue"],+ start="2023-01-01",+ end="2023-03-01",+ )+++def test_a_partially_resolvable_batch_still_loads(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """One unresolvable symbol must not sink the symbols that do resolve."""+ _install_schema_stub(monkeypatch)+ _patch_sec(+ monkeypatch,+ {"AAPL": _facts({"Revenues": [_fact_row("2023-12-31", "2024-01-30", 100.0)]})},+ )++ panel = fundamentals_loader.load_fundamental_panel(+ ["AAPL", "600519.SH"],+ ["revenue"],+ "2024-01-01",+ "2024-02-05",+ freq="quarterly",+ )+ assert panel["revenue"]["AAPL"].notna().any()+ assert panel["revenue"]["600519.SH"].isna().all()diff --git a/agent/tests/test_load_skill_paging.py b/agent/tests/test_load_skill_paging.pynew file mode 100644index 000000000..fd7d462f7--- /dev/null+++ b/agent/tests/test_load_skill_paging.py@@ -0,0 +1,109 @@+"""Regression: an oversized skill must be reachable, and the cut must be stated.++Skill documents are the implementation for much of this product — the bond+maths, the implied-vol solver, the impact models, the China market structure.+A tool result is capped at ``TOOL_RESULT_LIMIT`` characters and 31 of the 88+bundled skills exceed it: ``tushare`` delivered 9.7% of its ~103k characters,+``options-payoff`` 33.8%, ``credit-analysis`` 43.0%. The cut was silent, so the+agent could not tell an amputated document from a complete one and had no way+to reach the remainder.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from src.agent.loop import TOOL_RESULT_LIMIT+from src.agent.skills import SkillsLoader+from src.tools.load_skill_tool import LoadSkillTool++_SKILL_ROOT = Path(__file__).resolve().parents[1] / "src" / "skills"+++def _skill_names() -> list[str]:+ return sorted(path.parent.name for path in _SKILL_ROOT.glob("*/SKILL.md"))+++def _read_all(tool: LoadSkillTool, name: str) -> tuple[str, int, int]:+ """Page a skill to completion; return (text, page_count, longest_envelope)."""+ offset, pages, chunks, longest = 0, 0, [], 0+ while True:+ raw = tool.execute(name=name, offset=offset)+ longest = max(longest, len(raw))+ payload = json.loads(raw)+ assert payload["status"] == "ok", payload+ pages += 1+ chunks.append(payload["content"])+ if payload["complete"]:+ return "".join(chunks), pages, longest+ offset = payload["next_offset"]+ assert pages < 400, f"{name} did not converge"++[email protected](scope="module")+def tool() -> LoadSkillTool:+ return LoadSkillTool()+++class TestEnvelopeStatesWhatItDelivered:+ """A partial read must never look like a whole document."""++ def test_a_long_skill_reports_that_it_is_incomplete(self, tool):+ payload = json.loads(tool.execute(name="tushare"))++ assert payload["complete"] is False+ assert payload["next_offset"] > 0+ assert payload["total_chars"] > len(payload["content"])++ def test_a_short_skill_reports_that_it_is_complete(self, tool):+ name = min(_skill_names(), key=lambda n: len(SkillsLoader().get_content(n)))+ payload = json.loads(tool.execute(name=name))++ assert payload["complete"] is True+ assert payload["next_offset"] is None++ def test_an_unknown_skill_still_errors(self, tool):+ payload = json.loads(tool.execute(name="no-such-skill-here"))++ assert payload["status"] == "error"++ def test_a_non_integer_offset_is_rejected(self, tool):+ payload = json.loads(tool.execute(name="tushare", offset="banana"))++ assert payload["status"] == "error"++ def test_an_offset_past_the_end_is_rejected(self, tool):+ payload = json.loads(tool.execute(name="tushare", offset=10_000_000))++ assert payload["status"] == "error"+++class TestEverySkillIsFullyReachable:+ """Paging must reconstruct each document exactly, without breaching the cap."""++ def test_no_single_page_exceeds_the_tool_result_limit(self, tool):+ # The cap applies to the serialized envelope, and JSON escaping is+ # content-dependent — a newline-dense page costs two characters a line.+ oversized = []+ for name in _skill_names():+ _, _, longest = _read_all(tool, name)+ if longest > TOOL_RESULT_LIMIT:+ oversized.append((name, longest))++ assert oversized == []++ def test_paging_reconstructs_every_skill_byte_for_byte(self, tool):+ loader = SkillsLoader()+ mismatched = [+ name for name in _skill_names() if _read_all(tool, name)[0] != loader.get_content(name)+ ]++ assert mismatched == []++ def test_the_largest_skill_pages_in_a_sane_number_of_calls(self, tool):+ _, pages, _ = _read_all(tool, "tushare")++ assert 1 < pages <= 20diff --git a/agent/tests/test_sec_edgar_client.py b/agent/tests/test_sec_edgar_client.pyindex aec60fb57..2eaa3adad 100644--- a/agent/tests/test_sec_edgar_client.py+++ b/agent/tests/test_sec_edgar_client.py@@ -69,6 +69,39 @@ class TestCikFor:assert sec.cik_for("NOCIK") is None+class TestSymbolSuffixes:+ """The SEC table carries bare tickers with dashes and no dots at all.++ ``get_fundamentals("AAPL.US")`` — the tool's own documented example — used to+ return ``ok: true`` with an all-null panel because the ``.US`` market suffix+ was passed through to the lookup verbatim.+ """++ _PAYLOAD = {+ "0": {"cik_str": 320193, "ticker": "AAPL", "title": "Apple Inc."},+ "1": {"cik_str": 1067983, "ticker": "BRK-B", "title": "Berkshire B"},+ }++ def test_us_market_suffix_is_stripped(self):+ with patch.object(sec, "throttled_get_json", return_value=self._PAYLOAD):+ assert sec.cik_for("AAPL.US") == "0000320193"+ assert sec.cik_for("aapl.us") == "0000320193"++ def test_share_class_written_with_a_dot_resolves(self):+ with patch.object(sec, "throttled_get_json", return_value=self._PAYLOAD):+ assert sec.cik_for("BRK.B") == "0001067983"+ assert sec.cik_for("BRK-B") == "0001067983"++ def test_share_class_and_market_suffix_together_resolve(self):+ with patch.object(sec, "throttled_get_json", return_value=self._PAYLOAD):+ assert sec.cik_for("BRK.B.US") == "0001067983"++ def test_a_non_us_market_suffix_is_not_stripped(self):+ with patch.object(sec, "throttled_get_json", return_value=self._PAYLOAD):+ assert sec.cik_for("600519.SH") is None+ assert sec.cik_for("00700.HK") is None++class TestCikPadding:"""_pad_cik normalizes ints, padded strings, and CIK-prefixed strings."""diff --git a/agent/tests/test_sec_period_frames.py b/agent/tests/test_sec_period_frames.pynew file mode 100644index 000000000..5cfced2f4--- /dev/null+++ b/agent/tests/test_sec_period_frames.py@@ -0,0 +1,251 @@+"""Regression tests for SEC XBRL period-frame selection.++SEC ``companyfacts`` files the true quarter and the year-to-date frame for the+same ``end`` date under the same ``fy``/``fp``/``form``/``accn``, so a consumer+keying on anything narrower than the ``(start, end)`` span silently lets one+overwrite the other. Reproduced live on AAPL before the fix: 36 of 81 revenue+keys collided, ``period="annual"`` returned 64,698,000,000 for FY2020 against a+filed 274,515,000,000, and ``period="quarter"`` served the full-year figure in+every fiscal-Q4 slot.++All HTTP is mocked; no test touches a live endpoint.+"""++from __future__ import annotations++import json+from unittest.mock import patch++from backtest.loaders import sec_frames+from src.tools.financial_statements_tool import FinancialStatementsTool+from src.tools.sec_filings_tool import _parse_metric+++def _row(start, end, val, *, fy, fp, form, accn, filed):+ """Build one companyfacts unit row; ``start=None`` makes it an instant fact."""+ row = {+ "end": end,+ "val": val,+ "fy": fy,+ "fp": fp,+ "form": form,+ "accn": accn,+ "filed": filed,+ }+ if start is not None:+ row["start"] = start+ return row+++def _facts(rows, concept="Revenues"):+ """Wrap unit rows in the companyfacts envelope shape."""+ return {"facts": {"us-gaap": {concept: {"label": concept, "units": {"USD": rows}}}}}+++def _fetch(facts, *, statement="income", period="annual", code="AAPL.US"):+ """Run the tool against a mocked companyfacts payload and return its periods."""+ with patch(+ "src.tools.financial_statements_tool.cik_for", return_value="0000320193"+ ), patch(+ "src.tools.financial_statements_tool.get_company_facts", return_value=facts+ ):+ text = FinancialStatementsTool().execute(+ code=code, statement=statement, period=period+ )+ payload = json.loads(text)+ assert payload["ok"] is True+ return payload["data"][code]["periods"]+++# The shape that caused the defect: one 10-Q carrying a 272-day year-to-date+# frame and the 90-day quarter it contains, identical in every other field.+_TENQ_COLLISION = [+ _row("2025-09-28", "2026-06-27", 364_357, fy=2026, fp="Q3", form="10-Q",+ accn="q3", filed="2026-07-31"),+ _row("2026-03-29", "2026-06-27", 109_417, fy=2026, fp="Q3", form="10-Q",+ accn="q3", filed="2026-07-31"),+]++# The same shape on a 10-K: the full year and a Q4 duration frame share an end.+_TENK_COLLISION = [+ _row("2019-09-29", "2020-09-26", 274_515, fy=2020, fp="FY", form="10-K",+ accn="k20", filed="2020-10-30"),+ _row("2020-06-28", "2020-09-26", 64_698, fy=2020, fp="FY", form="10-K",+ accn="k20", filed="2020-10-30"),+]+++class TestSpanPrimitives:+ """The shared span helpers are the single definition of the thresholds."""++ def test_span_days_measures_a_duration_fact(self):+ assert sec_frames.span_days({"start": "2026-03-29", "end": "2026-06-27"}) == 90++ def test_span_days_is_none_for_an_instant_fact(self):+ assert sec_frames.span_days({"end": "2026-06-27"}) is None++ def test_classify_span_separates_the_four_kinds(self):+ assert sec_frames.classify_span(None) == sec_frames.INSTANT+ assert sec_frames.classify_span(90) == sec_frames.QUARTER+ assert sec_frames.classify_span(363) == sec_frames.ANNUAL+ assert sec_frames.classify_span(272) == sec_frames.YTD+ assert sec_frames.classify_span(181) == sec_frames.YTD++ def test_frame_key_separates_a_ytd_frame_from_its_quarter(self):+ ytd, quarter = _TENQ_COLLISION+ assert sec_frames.frame_key(ytd) != sec_frames.frame_key(quarter)++ def test_matches_cadence_rejects_year_to_date_at_both_cadences(self):+ ytd, quarter = _TENQ_COLLISION+ assert sec_frames.matches_cadence(ytd, "quarter") is False+ assert sec_frames.matches_cadence(ytd, "annual") is False+ assert sec_frames.matches_cadence(quarter, "quarter") is True+ assert sec_frames.matches_cadence(quarter, "annual") is False+++class TestQuarterCadence:+ """A quarterly series carries true quarters and nothing else."""++ def test_year_to_date_frame_never_replaces_the_quarter(self):+ periods = _fetch(_facts(_TENQ_COLLISION), period="quarter")+ assert [p["Revenues"] for p in periods] == [109_417]+ assert periods[0]["PERIOD_DAYS"] == 90+ assert periods[0]["PERIOD_TYPE"] == sec_frames.QUARTER++ def test_full_year_frame_is_not_served_as_a_quarter(self):+ periods = _fetch(_facts(_TENK_COLLISION), period="quarter")+ assert 274_515 not in [p.get("Revenues") for p in periods]+ assert [p["Revenues"] for p in periods] == [64_698]+++class TestAnnualCadence:+ """An annual series carries full-year frames and nothing else."""++ def test_quarter_frame_never_overwrites_the_full_year(self):+ periods = _fetch(_facts(_TENK_COLLISION), period="annual")+ assert [p["Revenues"] for p in periods] == [274_515]+ assert periods[0]["PERIOD_DAYS"] == 363++ def test_year_to_date_frame_is_excluded(self):+ periods = _fetch(_facts(_TENQ_COLLISION), period="annual")+ assert periods == []+++class TestFiscalQ4Synthesis:+ """Q4 flows are filed only inside the 10-K, so they must be derived."""++ _NO_Q4_FILED = [+ _row("2023-10-01", "2024-09-28", 400, fy=2024, fp="FY", form="10-K",+ accn="k24", filed="2024-11-01"),+ _row("2023-10-01", "2023-12-30", 120, fy=2024, fp="Q1", form="10-Q",+ accn="q1", filed="2024-02-02"),+ _row("2023-12-31", "2024-03-30", 90, fy=2024, fp="Q2", form="10-Q",+ accn="q2", filed="2024-05-03"),+ _row("2024-03-31", "2024-06-29", 85, fy=2024, fp="Q3", form="10-Q",+ accn="q3", filed="2024-08-02"),+ ]++ def test_missing_q4_is_derived_from_the_full_year(self):+ periods = _fetch(_facts(self._NO_Q4_FILED), period="quarter")+ by_end = {p["REPORT_DATE"]: p for p in periods}+ q4 = by_end["2024-09-28"]+ assert q4["Revenues"] == 400 - (120 + 90 + 85)+ assert q4["FISCAL_PERIOD"] == "Q4"++ def test_a_derived_quarter_is_labelled_as_derived(self):+ periods = _fetch(_facts(self._NO_Q4_FILED), period="quarter")+ q4 = next(p for p in periods if p["REPORT_DATE"] == "2024-09-28")+ assert q4["DERIVED"] == "FY - (Q1 + Q2 + Q3)"++ def test_a_filed_q4_is_not_overwritten_by_a_derived_one(self):+ periods = _fetch(_facts(_TENK_COLLISION), period="quarter")+ q4 = next(p for p in periods if p["REPORT_DATE"] == "2020-09-26")+ assert q4["Revenues"] == 64_698+ assert "DERIVED" not in q4+++class TestComparativeVintages:+ """One period repeated across filings is one row, not one row per filing."""++ _RESTATED = [+ _row("2022-10-02", "2023-09-30", 383_285, fy=2023, fp="FY", form="10-K",+ accn="k23", filed="2023-11-03"),+ _row("2022-10-02", "2023-09-30", 383_290, fy=2024, fp="FY", form="10-K",+ accn="k24", filed="2024-11-01"),+ _row("2022-10-02", "2023-09-30", 383_290, fy=2025, fp="FY", form="10-K",+ accn="k25", filed="2025-10-31"),+ ]++ def test_one_period_yields_one_row(self):+ periods = _fetch(_facts(self._RESTATED), period="annual")+ assert len(periods) == 1++ def test_the_restated_value_wins_and_both_dates_are_visible(self):+ period = _fetch(_facts(self._RESTATED), period="annual")[0]+ assert period["Revenues"] == 383_290+ assert period["FILED"] == "2023-11-03"+ assert period["LAST_FILED"] == "2025-10-31"++ def test_the_originating_filing_supplies_the_fiscal_label(self):+ period = _fetch(_facts(self._RESTATED), period="annual")[0]+ assert period["FISCAL_YEAR"] == 2023+++class TestInstantAndDurationMerge:+ """``indicators`` mixes balance-sheet instants with income-statement flows."""++ def test_one_period_carries_both_kinds_of_concept(self):+ facts = {+ "facts": {+ "us-gaap": {+ "Revenues": {+ "label": "Revenues",+ "units": {+ "USD": [+ _row("2023-10-01", "2024-09-28", 400, fy=2024,+ fp="FY", form="10-K", accn="k24",+ filed="2024-11-01")+ ]+ },+ },+ "Assets": {+ "label": "Assets",+ "units": {+ "USD": [+ _row(None, "2024-09-28", 365_000, fy=2024,+ fp="FY", form="10-K", accn="k24",+ filed="2024-11-01")+ ]+ },+ },+ }+ }+ }+ periods = _fetch(facts, statement="indicators", period="annual")+ assert len(periods) == 1+ assert periods[0]["Revenues"] == 400+ assert periods[0]["Assets"] == 365_000+++class TestSecFilingsMetricPoints:+ """Raw metric points keep every frame but must never be ambiguous."""++ def test_each_point_carries_its_span_and_kind(self):+ points = _parse_metric(_facts(_TENQ_COLLISION), "Revenues", 10)["points"]+ by_val = {p["val"]: p for p in points}+ assert by_val[364_357]["period_type"] == sec_frames.YTD+ assert by_val[364_357]["period_days"] == 272+ assert by_val[109_417]["period_type"] == sec_frames.QUARTER+ assert by_val[109_417]["period_days"] == 90++ def test_repeated_vintages_of_one_period_collapse(self):+ rows = TestComparativeVintages._RESTATED+ points = _parse_metric(_facts(rows), "Revenues", 10)["points"]+ assert len(points) == 1+ assert points[0]["val"] == 383_290++ def test_points_are_ordered_oldest_first(self):+ points = _parse_metric(_facts(_TENQ_COLLISION + _TENK_COLLISION),+ "Revenues", 10)["points"]+ ends = [p["end"] for p in points]+ assert ends == sorted(ends)diff --git a/agent/tests/test_tool_result_paging.py b/agent/tests/test_tool_result_paging.pynew file mode 100644index 000000000..a501602a7--- /dev/null+++ b/agent/tests/test_tool_result_paging.py@@ -0,0 +1,197 @@+"""Regression: an oversized tool result must be paged, and any cut declared.++A tool result is capped at ``TOOL_RESULT_LIMIT`` characters and the cut used to+be silent. For a JSON envelope it also lands mid-structure, so the model got a+broken fragment and read the records that survived as the whole answer.+Measured live before this landed:++* ``get_financial_statements("AAPL.US", statement="income", period="quarter")``+ serialized to 28,498 characters for 40 periods and delivered roughly 12 — and+ a parser-level cap of 40 put the other 32 quarters out of reach of any request.+* ``get_sec_filings(ticker="AAPL")`` with no options at all serialized to 12,190+ characters, i.e. the default call already overflowed.+"""++from __future__ import annotations++import json+from unittest.mock import patch++import pytest++from src.config.limits import TOOL_RESULT_LIMIT, truncate_tool_result+from src.tools._result_paging import fit_records+from src.tools.financial_statements_tool import FinancialStatementsTool+++class TestTruncationNotice:+ """The generic backstop for tools that cannot page."""++ def test_a_short_result_is_untouched(self):+ assert truncate_tool_result("short") == "short"++ def test_a_result_at_the_limit_is_untouched(self):+ exact = "x" * TOOL_RESULT_LIMIT+ assert truncate_tool_result(exact) == exact++ def test_an_oversized_result_still_fits_the_budget(self):+ assert len(truncate_tool_result("x" * 50_000)) <= TOOL_RESULT_LIMIT++ def test_an_oversized_result_says_it_was_cut(self):+ out = truncate_tool_result("x" * 50_000)++ assert "TRUNCATED" in out+ assert "50000" in out++ def test_the_notice_survives_an_absurdly_small_budget(self):+ out = truncate_tool_result("x" * 500, limit=40)++ assert len(out) <= 40+ assert "TRUNCATED" in out+++class TestFitRecords:+ """Records are paged whole; a page is never a partial record."""++ def _build(self, page, paging):+ return {"paging": paging, "rows": page}++ def test_everything_fits_in_one_page_when_small(self):+ payload = json.loads(fit_records([{"a": 1}, {"a": 2}], 0, self._build))++ assert payload["paging"]["complete"] is True+ assert payload["paging"]["next_offset"] is None+ assert len(payload["rows"]) == 2++ def test_a_large_set_pages_and_reports_the_total(self):+ records = [{"i": i, "pad": "y" * 400} for i in range(100)]++ payload = json.loads(fit_records(records, 0, self._build))++ assert payload["paging"]["total"] == 100+ assert payload["paging"]["complete"] is False+ assert 0 < payload["paging"]["returned"] < 100++ def test_every_page_stays_within_the_budget(self):+ records = [{"i": i, "pad": "y" * 400} for i in range(100)]+ offset, seen, guard = 0, 0, 0+ while True:+ raw = fit_records(records, offset, self._build)+ assert len(raw) <= TOOL_RESULT_LIMIT+ paging = json.loads(raw)["paging"]+ seen += paging["returned"]+ guard += 1+ assert guard < 200+ if paging["complete"]:+ break+ offset = paging["next_offset"]++ assert seen == 100++ def test_records_are_never_split(self):+ records = [{"i": i, "pad": "y" * 400} for i in range(100)]++ rows = json.loads(fit_records(records, 0, self._build))["rows"]++ assert all(set(row) == {"i", "pad"} for row in rows)++ def test_a_single_oversized_record_is_still_emitted(self):+ # One page must always carry at least one record, or paging deadlocks.+ payload = json.loads(fit_records([{"pad": "y" * 50_000}], 0, self._build))++ assert payload["paging"]["returned"] == 1++ def test_max_records_caps_a_page_below_the_budget(self):+ records = [{"i": i} for i in range(100)]++ payload = json.loads(fit_records(records, 0, self._build, max_records=7))++ assert payload["paging"]["returned"] == 7+++def _sec_facts(period_count: int) -> dict:+ rows = []+ for i in range(period_count):+ year = 2000 + i // 4+ month = 3 * (i % 4) + 3+ end = f"{year}-{month:02d}-28"+ start = f"{year}-{month - 2:02d}-01"+ rows.append(+ {+ "start": start,+ "end": end,+ "val": 1_000_000 + i,+ "fy": year,+ "fp": f"Q{i % 4 + 1}",+ "form": "10-Q",+ "accn": f"a{i}",+ "filed": f"{year}-{month:02d}-30",+ }+ )+ return {"facts": {"us-gaap": {"Revenues": {"label": "Revenues", "units": {"USD": rows}}}}}+++class TestFinancialStatementsPaging:+ """The analyst-facing statement tool must expose its whole history."""++ def _run(self, offset: int, period_count: int = 120):+ with patch(+ "src.tools.financial_statements_tool.cik_for", return_value="0000320193"+ ), patch(+ "src.tools.financial_statements_tool.get_company_facts",+ return_value=_sec_facts(period_count),+ ):+ raw = FinancialStatementsTool().execute(+ code="AAPL.US", statement="income", period="quarter", offset=offset+ )+ return raw, json.loads(raw)++ def test_the_first_page_reports_the_full_period_count(self):+ _, payload = self._run(0)++ assert payload["paging"]["total"] == 120+ assert payload["paging"]["returned"] < 120++ def test_every_page_stays_within_the_budget(self):+ offset, guard = 0, 0+ while True:+ raw, payload = self._run(offset)+ assert len(raw) <= TOOL_RESULT_LIMIT+ guard += 1+ assert guard < 100+ if payload["paging"]["complete"]:+ break+ offset = payload["paging"]["next_offset"]++ def test_paging_reaches_every_period_exactly_once(self):+ offset, ends = 0, []+ while True:+ _, payload = self._run(offset)+ ends.extend(+ row["REPORT_DATE"] for row in payload["data"]["AAPL.US"]["periods"]+ )+ if payload["paging"]["complete"]:+ break+ offset = payload["paging"]["next_offset"]++ assert len(ends) == 120+ assert len(set(ends)) == 120++ def test_a_non_integer_offset_is_rejected(self):+ with patch(+ "src.tools.financial_statements_tool.cik_for", return_value="0000320193"+ ), patch(+ "src.tools.financial_statements_tool.get_company_facts",+ return_value=_sec_facts(8),+ ):+ payload = json.loads(+ FinancialStatementsTool().execute(code="AAPL.US", offset="banana")+ )++ assert payload["ok"] is False++ def test_a_short_history_is_complete_in_one_call(self):+ _, payload = self._run(0, period_count=4)++ assert payload["paging"]["complete"] is True+ assert payload["paging"]["next_offset"] is None