160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.
Python ai-toolsai-watchanthropicclaudecybersecuritydashboardgeofencinggeopoliticalgeospatialintelligencemarketsmcpmigrationmilitarymodel-context-protocolnuclearosintreal-timespace-weatherthreat-intelligence
Decide lagged-connection significance on the AR(1)-adjusted q
Phoenix Agent (mac-studio)44f044fcad88
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 76b3fe5..7f5c4b5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -241,10 +241,14 @@ source here, and no proxy is substituted for any of these measures.default (levels of trending series correlate spuriously).- Per pair: the lag with the smallest p, with r, n (overlapping periodsafter the transform and shift), a two-sided p from Student's t (computed- from the regularized incomplete beta function, standard library only) and- the Benjamini-Hochberg q across every test in the call, with the- Benjamini-Yekutieli `q_by` alongside. Significant at q <= 0.05 by default- (allowed 0.001 to 0.25); the other significant lags are listed too.+ from the regularized incomplete beta function, standard library only)+ that treats periods as independent, `p_ar1` (p recomputed with an AR(1)+ effective sample size, below), and the Benjamini-Hochberg `q` and `q_ar1`+ across every test in the call, with the Benjamini-Yekutieli `q_by` (of+ `q_ar1`) alongside. `significant` means `q_ar1` <= 0.05 by default+ (allowed 0.001 to 0.25), and `significant_if_independent` applies the+ threshold to `q`; the other significant lags are listed too. The summary+ gives both counts.- A pair and lag with fewer than 30 overlapping periods (callers may go downto 20), or a constant side, is listed as not tested with its n, neverdropped. 30 points give about 80% power for a true |r| of 0.5 at alpha@@ -253,26 +257,47 @@ source here, and no proxy is substituted for any of these measures.without `observed_at` (Yahoo quotes) are not used, with the reason: rowsare stored only on change, so a missing day cannot be told from anunchanged one. A period takes its last observation; nothing is averaged.-- Serial correlation: each series' lag-1 autocorrelation after the- transform, and per strongest result an AR(1) effective sample size and- the p recomputed with it, as a diagnostic outside q. Nothing is- prewhitened.+ On the week and month grids each series reports the shortest and longest+ interval its changes span (`change_interval_days`), and `data_gaps` names+ unequal intervals.+- Serial correlation: each series' lag-1 autocorrelation (phi) after the+ transform, and on every test an AR(1) effective sample size n (1 - phi_a+ phi_b) / (1 + phi_a phi_b), capped at n, with `p_ar1` recomputed from it;+ significance follows `q_ar1`. Below an effective size of 3, or without a+ measurable phi, `p_ar1` is 1 and the entry says "no evidence" or "not+ assessed". `serial_correlation_dominates` marks an effective size under a+ fifth of n, and `data_gaps` names those pairs and every series with+ |phi| above 0.3. The strongest lag's p and `p_ar1` are post-selection;+ `q` and `q_ar1` adjust for every test. Nothing is prewhitened. Measured in+ a scratch simulation through the store: two independent random walks of+ 300 daily points in levels (seeds 0-99, defaults) have a lag with q <=+ 0.05 in 91 seeds and with `q_ar1` <= 0.05 in none; two independent series+ of 200 AR(1) changes (4,000 runs, lag 0) reject at p <= 0.05 in 12.2%+ (phi 0.5) and 35.3% (phi 0.8) of runs, and at `q_ar1` <= 0.05 in 4.5% and+ 5.1%.- `cannot_prove` in every response: correlation is not causation, a lead isnot a causal direction, serial correlation inflates significance, ashared driver produces correlation, the store holds only what thecollector recorded, BH under dependence is approximate and covers onecall, and a small q is not a large effect.- An unknown grid or transform is an error naming the allowed values;- numeric inputs are clamped and each clamp is reported.+ numeric inputs are clamped and each clamp is reported, in the MCP+ response (`inputs_clamped`) and as a `Clamped:` line in the CLI. A given+ `start` moved later by the 3,000-period window cut is reported the same+ way.- Measured 2026-10-17 over a live MCP stdio session and the CLI, on fourreal FRED series (WALCL, WDTGAL, WTREGEN, RRPONTSYD) loaded into an- isolated store as one capture; illustrative, not findings. Week grid,- changes: 26 of 66 tests significant; the Wednesday TGA level against its- week average gives r 0.61 at lag 0 and 0.59 at lag +1, the averaging- window rather than a cause. Levels: Fed total assets against either TGA- series gives r 0.74 at lag 0 (n 1,244) with an AR(1) effective sample- size of 5.3 and 3.4. Day grid: the weekly series have no adjacent-day- changes, so nothing is tested and the response says why.+ isolated store as one capture; illustrative, not findings. The figures+ below were recomputed offline on that stored capture (direct, CLI and MCP+ stdio) after `q_ar1` became the significance rule. Week grid, changes: 24+ of 66 tests significant (26 if periods were independent); the Wednesday+ TGA level against its week average gives r 0.61 at lag 0 and 0.59 at lag+ +1, the averaging window rather than a cause. Levels: Fed total assets+ against either TGA series gives r 0.74 at lag 0 (n 1,244) and p near+ 1e-214 if the weeks were independent, but AR(1) effective sample sizes of+ 5.2 and 3.3 leave `p_ar1` 0.13 and 0.37: not significant, and `data_gaps`+ says serial correlation dominates. Day grid: the weekly series have no+ adjacent-day changes, so nothing is tested and the response says why.- With the default 365-day observation retention(`WORLD_INTEL_HISTORY_DAYS`), a store filled only by the collector spansabout a year, so the month grid cannot reach the 20-point floor without adiff --git a/README.md b/README.mdindex 1b291d5..cb3a2d6 100644--- a/README.md+++ b/README.md@@ -614,7 +614,7 @@ Reads the history store only, so the sample is what the collector saved, not eac| Tool | Description ||------|-------------|-| `intel_lagged_connections` | Correlation between 2 to 8 stored series (keys as `intel_series_history` lists them) on a UTC day, week or month grid, tested at every lag from `-max_lag` to `+max_lag` (default 5, at most 30, at most 1,000 tests a call). Default transform is period-over-period changes, because levels of trending series correlate spuriously; `levels` on request. Per pair: the lag with the smallest p, with Pearson r, overlap n, two-sided p from Student's t and the Benjamini-Hochberg q across every test in the call (significant at q <= 0.05 by default). Lag +k compares A at period t with B at t+k, so A leads B by k. Pair/lag overlaps under 30 points are listed as not tested with their n; revised points use the latest vintage; rows without `observed_at` (Yahoo quotes) are not used. Each strongest result also carries an AR(1) effective sample size as a serial-correlation diagnostic |+| `intel_lagged_connections` | Correlation between 2 to 8 stored series (keys as `intel_series_history` lists them) on a UTC day, week or month grid, tested at every lag from `-max_lag` to `+max_lag` (default 5, at most 30, at most 1,000 tests a call). Default transform is period-over-period changes, because levels of trending series correlate spuriously; `levels` on request. Per pair: the lag with the smallest p, with Pearson r, overlap n, two-sided p from Student's t (periods treated as independent), `p_ar1` recomputed with an AR(1) effective sample size from both series' lag-1 autocorrelations, and the Benjamini-Hochberg `q` and `q_ar1` across every test in the call. `significant` means `q_ar1` <= 0.05 by default (`significant_if_independent` applies the threshold to `q`); an effective sample under 3 is reported as no evidence, and `data_gaps` names autocorrelated series and pairs where serial correlation dominates. Lag +k compares A at period t with B at t+k, so A leads B by k. Pair/lag overlaps under 30 points are listed as not tested with their n; revised points use the latest vintage; rows without `observed_at` (Yahoo quotes) are not used; every clamped input is reported, in the CLI too |---diff --git a/ROADMAP.md b/ROADMAP.mdindex 29f1c5b..8448706 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -580,7 +580,7 @@ dashboard.| 1 | Liquidity and flows | Fed balance sheet, Treasury General Account, reverse repo and net liquidity (FRED keyless CSV), money supply (US M2, euro area M1/M2/M3, never summed), ECB, ICI fund flows and ETF net issuance, FINRA margin statistics, BLS series; amounts kept separate from flows | :yellow_circle: Built, unreleased: 5 tools (`intel_liquidity_board`, `intel_net_liquidity`, `intel_money_supply`, `intel_fed_liquidity_series`, `intel_ecb_series`), 5 CLI commands, 2 collector sources. FRED graph CSV and ECB Data Portal live-verified 2026-10-17. The TGA term is WDTGAL (Wednesday level, USD millions): WTREGEN is a week average; the net liquidity `method` block states each term's units, conversion and how RRPONTSYD (daily, USD billions) is aligned to the Wednesday. Blocked, measured 2026-10-17, and listed in the board's `blocked` field; no proxy is substituted, so fund flows and ETF net issuance have no source: ICI (money market fund assets at /research/stats/mmf, ETF net issuance at /research/stats/etf) answers 403 Akamai "Access Denied" on every path, robots.txt included; FINRA margin statistics XLSX answers 200, but the finra.org Terms of Use (Restrictions d and e) forbid building a database from the site and data mining, scraping or harvesting tools, robots included, and the page says data feeds are not available; BLS public API v1 answers 200 without a key (CPI-U, payrolls), but api.bls.gov robots.txt is `Disallow: /` and the terms page on www.bls.gov answers 403 to this server's User-Agent, so it is not used || 1 | Kalshi + cross-venue markets | Kalshi public market data next to Polymarket; same-event comparison with an explicit match confidence; settled markets scored against pre-settlement prices (Brier) | :red_circle: || 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :white_check_mark: Built 2026-10-17, unreleased: `intel_news_market_reaction` and `intel news-reaction`. Company rows: stock, benchmark (SPY, or the exchange country's index) and excess return on the story's session; country rows: index return with a trailing z-score. Session rule in the exchange's timezone (after close = next session; weekends and holidays read from the listing's own bars). Open: `^TASI` and `^TA125` (Saudi and Israel in the country-index table) return 404 on Yahoo, so those benchmarks are data gaps; story times inherit `sources/news.py`'s RSS timestamp offset until that is fixed |-| 2 | Connections with timing offsets | Correlation between retained series over a shared sample, tested at leads and lags, with minimum sample size and false-discovery control; states that it does not prove causation | :white_check_mark: Built 2026-10-17, unreleased: `intel_lagged_connections` and `intel history connections`. Pearson r on a UTC day, week or month grid at every lag from -max_lag to +max_lag (default 5, cap 30, at most 1,000 tests a call), period-over-period changes by default, p from Student's t (regularized incomplete beta, standard library), Benjamini-Hochberg q across the call (default 0.05), a 30-point minimum with every untested pair and lag listed with its n, latest vintage, rows without `observed_at` refused with the reason, an AR(1) effective sample size as a diagnostic, and a `cannot_prove` list. p-values match scipy to 3.3e-13 relative error. Verified 2026-10-17 over a live MCP stdio session and the CLI on four real FRED series loaded into an isolated store. Not done: rank correlation, prewhitening |+| 2 | Connections with timing offsets | Correlation between retained series over a shared sample, tested at leads and lags, with minimum sample size and false-discovery control; states that it does not prove causation | :white_check_mark: Built 2026-10-17, unreleased: `intel_lagged_connections` and `intel history connections`. Pearson r on a UTC day, week or month grid at every lag from -max_lag to +max_lag (default 5, cap 30, at most 1,000 tests a call), period-over-period changes by default, p from Student's t (regularized incomplete beta, standard library), Benjamini-Hochberg adjustment across the call (default 0.05) with significance decided on the AR(1)-adjusted `q_ar1` (independent random walks in levels: 91 of 100 seeds flagged by the unadjusted q, none by `q_ar1`), "no evidence" below an effective sample of 3, a 30-point minimum with every untested pair and lag listed with its n, latest vintage, rows without `observed_at` refused with the reason, every clamp reported in the MCP response and the CLI, and a `cannot_prove` list. p-values match scipy to 3.3e-13 relative error. Verified 2026-10-17 over a live MCP stdio session and the CLI on four real FRED series loaded into an isolated store. Not done: rank correlation, prewhitening || 2 | Day timeline | What every retained source recorded for a given day, by observation date or collection date | :red_circle: || 3 | Dashboard views | Liquidity board, situations, top stories, collection health panels | :red_circle: |diff --git a/src/world_intel_mcp/analysis/lagged_connections.py b/src/world_intel_mcp/analysis/lagged_connections.pyindex 94c2a35..9dba077 100644--- a/src/world_intel_mcp/analysis/lagged_connections.py+++ b/src/world_intel_mcp/analysis/lagged_connections.py@@ -21,7 +21,11 @@ Alignment:- Sampling: a period takes the value of its last observation by``observed_at``, so a daily series on the week grid is its last day of theweek. Values inside a period are not averaged: averaging a random walk- makes its period-to-period changes serially correlated.+ makes its period-to-period changes serially correlated. On the week and+ month grids a change therefore runs from one period's last observation to+ the next period's, and those intervals need not be equal (a Monday close+ then the next week's Friday close is 11 days); each series reports the+ shortest and longest interval in days (dated observations only).- Rows without ``observed_at`` (Yahoo quotes) are not used. Their only dateis ``collected_at``, when this server saw a changed value, and rows arestored only when the value changes, so a day with no row cannot be told@@ -29,7 +33,9 @@ Alignment:excluded with that reason.- ``start`` / ``end`` select whole grid periods (the ones containing them andevery period between). Without them the window is the series' combined- span, cut to the most recent ``MAX_PERIODS`` periods.+ span. Either way it is cut to the most recent ``MAX_PERIODS`` periods; when+ the cut moves a given ``start``, the start actually used is reported in+ ``inputs_clamped``.Transform:- ``changes`` (default): a period's value minus the immediately preceding@@ -50,10 +56,12 @@ Tests:P(|T| >= |t|) = I_{1 - r^2}((n - 2) / 2, 1 / 2), the regularized incompletebeta function, evaluated by its continued fraction (DLMF 8.17.22) with themodified Lentz method. No permutation test is run.-- q is the Benjamini-Hochberg adjusted p over every test run in the call;- ``q_by`` is the Benjamini-Yekutieli version, valid under any dependence- between tests. A test is significant when q <= the threshold (default- ``DEFAULT_Q`` = 0.05).+- q is the Benjamini-Hochberg adjusted p over every test run in the call,+ and q_ar1 the same adjustment of ``p_ar1`` (below); ``q_by`` is the+ Benjamini-Yekutieli version of q_ar1, valid under any dependence between+ tests. A test is significant when q_ar1 <= the threshold (default+ ``DEFAULT_Q`` = 0.05); ``significant_if_independent`` applies the+ threshold to q.Minimum sample, ``DEFAULT_MIN_OVERLAP`` = 30 overlapping points (callers mayraise it, or lower it to ``MIN_OVERLAP_FLOOR`` = 20): at n = 30 a two-sided@@ -65,20 +73,38 @@ more often missed than found, and one that passes rests on few points. Thefloor is 20 because below it a single outlying pair can dominate r and the treference distribution leans on near-normal values.-Serial correlation: p and q treat periods as independent. Each series'-lag-1 autocorrelation after the transform is reported, and each strongest-result carries ``n_effective_ar1`` and ``p_ar1``: n scaled by-(1 - phi_a phi_b) / (1 + phi_a phi_b), the large-sample variance inflation-of r for two AR(1) series (Bartlett), capped at n. That is a diagnostic only:-q uses p, and nothing is prewhitened.+Serial correlation: p and q treat periods as independent, which overstates+the evidence when a series is autocorrelated after the transform. Each+series' lag-1 autocorrelation (phi) is measured, and every test carries+``n_effective_ar1``, n scaled by (1 - phi_a phi_b) / (1 + phi_a phi_b) (the+large-sample variance inflation of r for two AR(1) series, Bartlett) and+capped at n, and ``p_ar1``, p recomputed with that sample size. Significance+uses q_ar1. Below an effective size of 3 the sample carries no evidence+either way, and without a measurable phi (fewer than ``_AUTOCORR_MIN_PAIRS``+adjacent periods) the adjustment cannot be made; both set p_ar1 to 1 and the+entry says why. ``serial_correlation_dominates`` marks n_effective_ar1 below+``DOMINATES_BELOW`` x n (variance of r inflated more than fivefold), and+data_gaps names those pairs and every series with |phi| above+``AUTOCORR_NOTE_ABOVE``. The strongest lag is chosen by p among a pair's+lags, so its p and p_ar1 are post-selection values; q and q_ar1 carry the+adjustment for every test in the call. Measured 2026-10-17 in a scratch+simulation through the store (not part of the test suite): for two+independent Gaussian random walks of 300 daily points, levels, defaults,+seeds 0-99, 91 of 100 seeds have a lag with q <= 0.05 and none with q_ar1 <=+0.05 (conservative there: their phi is near 1). For two independent series+of 200 AR(1) changes, 4,000 runs, at lag 0 p <= 0.05 in 12.2% (phi 0.5) and+35.3% (phi 0.8) of runs and q_ar1 <= 0.05 in 4.5% and 5.1%; with the default+11 lags a call has any significant lag in 4.3% and 2.9% of runs.Gaps / not covered:- Pearson only: no rank correlation, so a few extreme changes can drive r.- No prewhitening and no correction for autocorrelation beyond lag 1 or for- volatility clustering; ``p_ar1`` is an AR(1) approximation outside q.+ volatility clustering: ``p_ar1`` is an AR(1) approximation, so series+ with longer memory (seasonal patterns, long swings) can still have their+ evidence overstated.- Benjamini-Hochberg assumes independent or positively dependent tests;- neighbouring lags of one pair share most of their data, so q is- approximate (``q_by`` is the any-dependence bound).+ neighbouring lags of one pair share most of their data, so q and q_ar1 are+ approximate (``q_by`` is the any-dependence bound for q_ar1).- The adjustment covers one call. Other calls with other series, grids orwindows are further tests it cannot see.- Business-day series lose their Monday changes on the day grid (Friday to@@ -115,6 +141,11 @@ MAX_TESTS = 1000MAX_PERIODS = 3000# Fewer adjacent pairs than this and a lag-1 autocorrelation is not reported._AUTOCORR_MIN_PAIRS = 10+# n_effective_ar1 below this share of n: the variance of r is inflated more+# than fivefold, so serial correlation, not the sample size, sets the evidence.+DOMINATES_BELOW = 0.2+# A series whose |lag-1 autocorrelation| exceeds this gets a data_gaps line.+AUTOCORR_NOTE_ABOVE = 0.3_UNIT = {"day": "day", "week": "week", "month": "month"}@@ -126,7 +157,9 @@ GRID_RULES = {SAMPLING_RULE = ("Each period takes the value of its last observation by observed_at (a daily ""series on the week grid is its last day of the week). Values inside a period "- "are not averaged."+ "are not averaged. On the week and month grids a change runs from one period's "+ "last observation to the next period's, so changes can span unequal intervals; "+ "each series reports change_interval_days (shortest and longest).")VINTAGE_RULE = ("Latest vintage: where later captures revised the value for an observed_at, the "@@ -168,10 +201,35 @@ MIN_OVERLAP_REASON = ()AR1_RULE = ("p and q treat periods as independent. Done: each series' lag-1 "- "autocorrelation after the transform is reported, and each strongest result "- "carries n_effective_ar1 (n scaled by (1 - phi_a phi_b) / (1 + phi_a phi_b), "- "capped at n) and p_ar1 (p recomputed with it). Not done: prewhitening, "- "autocorrelation beyond lag 1, volatility clustering; p_ar1 does not enter q."+ "autocorrelation (phi) after the transform is measured, and every test carries "+ "n_effective_ar1 (n scaled by (1 - phi_a phi_b) / (1 + phi_a phi_b), capped at "+ "n) and p_ar1 (p recomputed with it). q_ar1 is the Benjamini-Hochberg "+ "adjustment of p_ar1 across the call, and significant uses q_ar1; p_ar1 does "+ "not enter q. Below an effective sample size of 3 the sample carries no "+ "evidence either way, and without a measurable phi (fewer than "+ f"{_AUTOCORR_MIN_PAIRS} adjacent periods) no adjustment can be made; both set "+ "p_ar1 to 1 and say why in the entry's note. n_effective_ar1 is shown rounded "+ "down to one decimal. serial_correlation_dominates "+ f"marks n_effective_ar1 below {DOMINATES_BELOW:g} n. The strongest lag is the "+ "smallest p among the pair's lags, so its p and p_ar1 are post-selection "+ "values; q and q_ar1 carry the adjustment for every test in the call. Not "+ "done: prewhitening, autocorrelation beyond lag 1, volatility clustering."+)+SIGNIFICANCE_RULE = (+ "A test is significant when q_ar1 <= the threshold. significant_if_independent "+ "applies the same threshold to q, which treats periods as independent and "+ "overstates the evidence for autocorrelated series."+)+NO_EVIDENCE_NOTE = (+ "no evidence: the AR(1) effective sample size is below 3, so with this much "+ "serial correlation the sample cannot tell a real correlation from chance; "+ "p_ar1 is set to 1"+)+NO_PHI_NOTE = (+ "not assessed: a series has fewer than "+ f"{_AUTOCORR_MIN_PAIRS} adjacent periods after the transform, so its lag-1 "+ "autocorrelation cannot be measured and p cannot be adjusted for it; p_ar1 is "+ "set to 1, so the test cannot be significant")NOT_TESTED_REASONS = {"below_min_overlap": "fewer overlapping periods than min_overlap",@@ -185,9 +243,11 @@ CANNOT_PROVE = ["a third factor can reach A first.","Serial correlation inflates significance even after differencing: p and q ""treat periods as independent. What was done: lag-1 autocorrelations are "- "reported and p_ar1 recomputes the strongest results with an AR(1) effective "- "sample size. What was not: prewhitening, autocorrelation beyond lag 1, "- "volatility clustering. p_ar1 does not enter q.",+ "measured, every test carries p_ar1 with an AR(1) effective sample size, and "+ "significant uses q_ar1, the false-discovery adjustment of p_ar1. What was "+ "not: prewhitening, autocorrelation beyond lag 1, volatility clustering, so "+ "series with longer memory than AR(1) can still have their evidence "+ "overstated.","A shared common driver produces correlation: two series that both respond to ""a third (the business cycle, a policy date, a holiday calendar) correlate ""with no link between them.",@@ -196,9 +256,9 @@ CANNOT_PROVE = ["periods the collector missed are absent, not zero.","Benjamini-Hochberg controls the false discovery rate for independent or ""positively dependent tests; neighbouring lags of one pair share most of "- "their data, so q is approximate (q_by holds under any dependence). The "- "adjustment covers this call only, not other calls with other series, grids "- "or windows.",+ "their data, so q and q_ar1 are approximate (q_by, the Benjamini-Yekutieli "+ "version of q_ar1, holds under any dependence). The adjustment covers this "+ "call only, not other calls with other series, grids or windows.",]@@ -276,6 +336,27 @@ def correlation_p_value(r: float, n: float) -> float:return min(1.0, _ibeta(df / 2.0, 0.5, (1.0 - r) * (1.0 + r), r * r))+def ar1_adjusted(+ r: float, n: int, phi_a: float | None, phi_b: float | None+) -> tuple[float | None, float, str | None]:+ """(n_effective_ar1, p_ar1, note) for one test: n scaled by+ (1 - phi_a phi_b) / (1 + phi_a phi_b) and capped at n, and p recomputed+ with it. p_ar1 is 1, with a note, when either phi is unknown or the+ effective size is below 3."""+ if phi_a is None or phi_b is None:+ return None, 1.0, NO_PHI_NOTE+ prod = phi_a * phi_b+ if prod >= 1.0:+ n_eff = 0.0+ elif prod <= -1.0:+ n_eff = float(n)+ else:+ n_eff = min(float(n), n * (1.0 - prod) / (1.0 + prod))+ if n_eff < 3:+ return n_eff, 1.0, NO_EVIDENCE_NOTE+ return n_eff, correlation_p_value(r, n_eff), None++# Quotes a p from correlation_p_value, so it joins the list once that exists.CANNOT_PROVE.append("A small q is not a large effect: q says r is unlikely to be zero in this "@@ -490,6 +571,7 @@ def _sample_on_grid(key: str, rows: list[tuple], grid: str) -> dict[str, Any]:coarser = unreadable = 0coarser_kinds: set[str] = set()levels: dict[int, float] = {}+ days: dict[int, int | None] = {}for observed_at in sorted(latest):period, why = period_of(observed_at, grid)if period is None:@@ -500,6 +582,9 @@ def _sample_on_grid(key: str, rows: list[tuple], grid: str) -> dict[str, Any]:unreadable += 1continuelevels[period] = latest[observed_at] # sorted, so the last one wins+ # The sampled observation's day; a YYYY-MM row on the month grid has none.+ day = _DAY.fullmatch(str(observed_at))+ days[period] = date(int(day[1]), int(day[2]), int(day[3])).toordinal() if day else Nonelast_row = rows[-1] if rows else (None, None, None, None, None)return {"series_key": key,@@ -513,10 +598,21 @@ def _sample_on_grid(key: str, rows: list[tuple], grid: str) -> dict[str, Any]:"revised_observed_at": sum(1 for values in distinct.values() if len(values) > 1),"dated_observations": len(latest),"_levels": levels,+ "_days": days,"_coarser_kinds": coarser_kinds,}+def change_interval_days(levels: dict[int, float], days: dict[int, int | None]) -> list[int]:+ """Days spanned by each period-over-period change, from the earlier+ period's sampled observation to the later one's (both ends dated)."""+ out = []+ for p in sorted(levels):+ if p - 1 in levels and days.get(p) is not None and days.get(p - 1) is not None:+ out.append(days[p] - days[p - 1])+ return out++def _exclusion_reason(info: dict, grid: str) -> str | None:if info["dated_observations"] == 0:return (@@ -548,6 +644,11 @@ def _sig(value: float) -> float:return float(f"{value:.3g}")+def _floor1(value: float) -> float:+ # Rounded down, so an effective size just under 3 never reads as 3.0.+ return math.floor(value * 10 + 1e-9) / 10++# ---------------------------------------------------------------------------# The analysis# ---------------------------------------------------------------------------@@ -615,6 +716,7 @@ def lagged_connections(else:usable.append(info)+ unit = _UNIT[grid]# One shared window of whole grid periods.window: dict[str, Any] = {"start": None, "end": None, "limited_to_recent": False}lo = period_of(start_d.isoformat(), grid)[0] if start_d else None@@ -627,6 +729,12 @@ def lagged_connections(if hi - lo + 1 > MAX_PERIODS:lo = hi - MAX_PERIODS + 1window["limited_to_recent"] = True+ if start_d:+ clamps.append({+ "input": "start", "requested": start_d.isoformat(),+ "used": period_label(lo, grid),+ "reason": f"the window is limited to the most recent {MAX_PERIODS} {unit}s",+ })window.update(start=period_label(lo, grid), end=period_label(hi, grid),periods=max(0, hi - lo + 1))@@ -640,6 +748,10 @@ def lagged_connections("reason": "no observation inside the window"})continueinfo["_values"] = apply_transform(inside, transform)+ info["_intervals"] = (+ change_interval_days(inside, info["_days"]) if transform == "changes" else []+ )+ info["_phi"], info["_phi_pairs"] = lag1_autocorrelation(info["_values"])still_usable.append(info)usable = still_usable@@ -669,23 +781,26 @@ def lagged_connections(pair["not_tested"].append({"lag": k, "n": n, "reason": "no_variation"})continuet_abs = math.inf if abs(r) >= 1.0 else abs(r) * math.sqrt((n - 2) / (1 - r * r))- test = {"lag": k, "r": r, "n": n, "p": correlation_p_value(r, n), "_t": t_abs}+ n_eff, p_ar1, note = ar1_adjusted(r, n, a["_phi"], b["_phi"])+ test = {"lag": k, "r": r, "n": n, "p": correlation_p_value(r, n), "_t": t_abs,+ "n_eff": n_eff, "p_ar1": p_ar1, "note": note}tests.append(test)pair["_tests"].append(test)pairs.append(pair)pvalues = [t["p"] for t in tests]- for test, q_bh, q_by in zip(tests, benjamini_hochberg(pvalues), benjamini_yekutieli(pvalues)):- test["q"], test["q_by"] = q_bh, q_by- test["significant"] = q_bh <= q_threshold+ p_ar1_values = [t["p_ar1"] for t in tests]+ for test, q_bh, q_ar1, q_by in zip(+ tests, benjamini_hochberg(pvalues), benjamini_hochberg(p_ar1_values),+ benjamini_yekutieli(p_ar1_values),+ ):+ test["q"], test["q_ar1"], test["q_by"] = q_bh, q_ar1, q_by+ test["significant"] = q_ar1 <= q_threshold+ test["significant_if_independent"] = q_bh <= q_threshold- for info in usable:- info["_phi"], info["_phi_pairs"] = lag1_autocorrelation(info["_values"])-- unit = _UNIT[grid]gaps: list[str] = []- def _entry(test: dict, a: dict, b: dict, full: bool) -> dict:+ def _entry(test: dict) -> dict:k = test["lag"]plural = "" if abs(k) == 1 else "s"timing = (@@ -693,6 +808,7 @@ def lagged_connections(else f"B leads A by {-k} {unit}{plural}" if k < 0else f"same {unit}")+ n_eff = test["n_eff"]out = {"lag": k,"timing": timing,@@ -701,23 +817,18 @@ def lagged_connections("n": test["n"],"p": _sig(test["p"]),"q": _sig(test["q"]),+ "n_effective_ar1": None if n_eff is None else _floor1(n_eff),+ "p_ar1": _sig(test["p_ar1"]),+ "q_ar1": _sig(test["q_ar1"]),"q_by": _sig(test["q_by"]),"significant": test["significant"],+ "significant_if_independent": test["significant_if_independent"],+ "serial_correlation_dominates": (+ None if n_eff is None else n_eff < DOMINATES_BELOW * test["n"]+ ),}- if full:- phi_a, phi_b = a["_phi"], b["_phi"]- if phi_a is None or phi_b is None:- out["n_effective_ar1"] = out["p_ar1"] = None- else:- prod = phi_a * phi_b- if prod >= 1.0:- n_eff = 0.0- elif prod <= -1.0:- n_eff = float(test["n"])- else:- n_eff = min(float(test["n"]), test["n"] * (1.0 - prod) / (1.0 + prod))- out["n_effective_ar1"] = round(n_eff, 1)- out["p_ar1"] = _sig(correlation_p_value(test["r"], n_eff)) if n_eff >= 3 else None+ if test["note"]:+ out["note"] = test["note"]return outpair_out = []@@ -731,8 +842,8 @@ def lagged_connections("b": pair["b"],"lags_tested": len(pair["_tests"]),"lags_not_tested": len(pair["not_tested"]),- "strongest": [_entry(t, a, b, full=True) for t in strongest],- "significant": [_entry(t, a, b, full=False) for t in ranked if t["significant"]],+ "strongest": [_entry(t) for t in strongest],+ "significant": [_entry(t) for t in ranked if t["significant"]],"not_tested": pair["not_tested"],})if not ranked:@@ -741,10 +852,25 @@ def lagged_connections(f"{pair['a']} / {pair['b']}: no lag could be tested (largest overlap "f"{biggest} periods; minimum {min_n})")+ elif strongest[0]["n_eff"] is not None and (+ strongest[0]["n_eff"] < DOMINATES_BELOW * strongest[0]["n"]+ ):+ best = strongest[0]+ gap = (+ f"{pair['a']} / {pair['b']}: serial correlation dominates: lag-1 "+ f"autocorrelations {a['_phi']:+.2f} and {b['_phi']:+.2f} leave an AR(1) "+ f"effective sample size of {_floor1(best['n_eff']):g} of {best['n']} periods "+ "at the strongest lag, so p and q overstate the evidence; significance uses q_ar1"+ )+ if best["n_eff"] < 3:+ gap += ". Below 3 the sample carries no evidence either way (p_ar1 set to 1)"+ gaps.append(gap)+ tested_keys = {key for p in pairs if p["_tests"] for key in (p["a"], p["b"])}series_out = []for info in usable:values = info["_values"]+ intervals = info["_intervals"]series_out.append({"series_key": info["series_key"],"source": info["source"],@@ -764,8 +890,40 @@ def lagged_connections("points_after_transform": len(values),"lag1_autocorrelation": None if info["_phi"] is None else round(info["_phi"], 4),"lag1_pairs": info["_phi_pairs"],+ "change_interval_days": (+ {"min": min(intervals), "max": max(intervals)} if intervals else None+ ),})key = info["series_key"]+ phi = info["_phi"]+ tested = key in tested_keys+ if tested and phi is not None and abs(phi) > AUTOCORR_NOTE_ABOVE:+ gaps.append(+ f"{key}: lag-1 autocorrelation {phi:+.2f} after the transform; p and q "+ "assume independent periods, so significance uses the AR(1)-adjusted "+ "p_ar1 and q_ar1"+ )+ elif tested and phi is None:+ gap = (+ f"{key}: lag-1 autocorrelation not measurable ({info['_phi_pairs']} adjacent "+ f"periods after the transform, at least {_AUTOCORR_MIN_PAIRS} needed), so its "+ "tests cannot be adjusted for serial correlation and are not counted as "+ "significant (p_ar1 set to 1)"+ )+ spacing = _median_gap(info["_levels"])+ if spacing is not None and spacing > 1:+ gap += (f"; its observations are a median {spacing:g} {unit}s apart, so a "+ "coarser grid may fit")+ gaps.append(gap)+ # A week is 7 days; calendar months alone vary from 28 to 31.+ if grid != "day" and intervals and max(intervals) - min(intervals) > (+ 0 if grid == "week" else 3+ ):+ gaps.append(+ f"{key}: on the {grid} grid its changes span {min(intervals)} to "+ f"{max(intervals)} days (each period takes its last observation), so "+ "changes cover unequal intervals"+ )if info["rows_without_observed_at"]:gaps.append(f"{key}: {info['rows_without_observed_at']} rows without observed_at not used")if info["rows_coarser_than_grid"]:@@ -792,12 +950,18 @@ def lagged_connections(gaps.append("fewer than two series could be used, so nothing was tested")significant = sum(1 for t in tests if t["significant"])+ significant_independent = sum(1 for t in tests if t["significant_if_independent"])with_signal = sum(1 for p in pair_out if p["significant"])+ with_signal_independent = sum(+ 1 for p in pairs if any(t["significant_if_independent"] for t in p["_tests"])+ )not_run = sum(p["lags_not_tested"] for p in pair_out)return {"summary": (- f"{with_signal} of {len(pair_out)} pairs have a lag with q <= {q_threshold:g} "- f"({significant} of {len(tests)} tests; {not_run} pair/lag combinations not tested)"+ f"{with_signal} of {len(pair_out)} pairs have a lag with q_ar1 <= {q_threshold:g} "+ f"({significant} of {len(tests)} tests; {not_run} pair/lag combinations not "+ f"tested). Assuming independent periods instead, {with_signal_independent} of "+ f"{len(pair_out)} pairs have a lag with q <= {q_threshold:g}."),"series": series_out,"excluded_series": excluded,@@ -805,6 +969,7 @@ def lagged_connections("tests_run": len(tests),"tests_not_run": not_run,"significant_tests": significant,+ "significant_tests_if_independent": significant_independent,"method": {"grid": grid,"grid_rule": GRID_RULES[grid],@@ -821,8 +986,11 @@ def lagged_connections("transformed values exist; n is reported per test.","correlation": "Pearson r","p_value": P_RULE,- "multiple_testing": f"Benjamini-Hochberg q across all {len(tests)} tests run in "- "this call; q_by is the Benjamini-Yekutieli version, valid under any dependence.",+ "multiple_testing": f"Benjamini-Hochberg across all {len(tests)} tests run in "+ "this call: q over p (periods treated as independent) and q_ar1 over p_ar1; "+ "q_by is the Benjamini-Yekutieli version of q_ar1, valid under any dependence "+ "between tests.",+ "significance": SIGNIFICANCE_RULE,"q_threshold": q_threshold,"q_threshold_default": DEFAULT_Q,"strongest": "Per pair, the tested lag(s) with the smallest p (ties broken by "diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.pyindex 6af7f9b..4e78708 100644--- a/src/world_intel_mcp/cli.py+++ b/src/world_intel_mcp/cli.py@@ -3337,7 +3337,7 @@ def _p_text(value: float) -> str:@click.option("--min-overlap", type=int, default=_lagged.DEFAULT_MIN_OVERLAP, show_default=True,help=f"Fewest overlapping periods a test needs (at least {_lagged.MIN_OVERLAP_FLOOR})")@click.option("--q", "q", type=float, default=_lagged.DEFAULT_Q, show_default=True,- help="False discovery rate threshold (Benjamini-Hochberg)")+ help="False discovery rate threshold (Benjamini-Hochberg, applied to q_ar1)")@click.option("--start", default=None, help="First date YYYY-MM-DD")@click.option("--end", default=None, help="Last date YYYY-MM-DD")@click.pass_context@@ -3363,30 +3363,46 @@ def history_connections(lo, hi = method["lags"]table = Table(title=f"Connections ({method['grid']} grid, {method['transform']}, lags {lo:+d} to "- f"{hi:+d}, {data['tests_run']} tests, BH q <= {method['q_threshold']:g})",+ f"{hi:+d}, {data['tests_run']} tests, BH q_ar1 <= {method['q_threshold']:g})",box=box.SIMPLE_HEAVY,)- for name in ("A", "B", "Lag", "Timing", "r", "n", "n_eff", "p", "q", "Significant"):- justify = "right" if name in ("Lag", "r", "n", "n_eff", "p", "q") else "left"- table.add_column(name, justify=justify)+ numeric = ("Lag", "r", "n", "n_eff", "p", "q", "p_ar1", "q_ar1")+ for name in ("A", "B", "Lag", "Timing", "r", "n", "n_eff", "p", "q", "p_ar1", "q_ar1",+ "Significant"):+ table.add_column(name, justify="right" if name in numeric else "left")for pair in data["pairs"]:if not pair["strongest"]:table.add_row(_cell(pair["a"]), _cell(pair["b"]), "-",- Text("not tested", style="dim"), "-", "-", "-", "-", "-", "-")+ Text("not tested", style="dim"), *["-"] * 8)for entry in pair["strongest"]:- n_eff = entry.get("n_effective_ar1")+ n_eff = entry["n_effective_ar1"]table.add_row(_cell(pair["a"]), _cell(pair["b"]), f"{entry['lag']:+d}", entry["timing"],f"{entry['r']:+.3f}", str(entry["n"]), "-" if n_eff is None else f"{n_eff:g}",- _p_text(entry["p"]), _p_text(entry["q"]),+ _p_text(entry["p"]), _p_text(entry["q"]), _p_text(entry["p_ar1"]),+ _p_text(entry["q_ar1"]),Text("yes", style="green") if entry["significant"] else Text("no"),)console.print(table)console.print(escape(data["summary"]))console.print(- "n_eff: AR(1) effective sample size from the two series' lag-1 autocorrelations, "- "a diagnostic only: p and q use n."+ "n_eff: AR(1) effective sample size from the two series' lag-1 autocorrelations. "+ "p and q use n (periods treated as independent); p_ar1 and q_ar1 use n_eff, and "+ f"Significant means q_ar1 <= {method['q_threshold']:g}.")+ for pair in data["pairs"]:+ for entry in pair["strongest"]:+ if entry.get("note"):+ console.print(+ f"[yellow]Note:[/yellow] {escape(pair['a'])} / {escape(pair['b'])} lag "+ f"{entry['lag']:+d}: {escape(entry['note'])}"+ )+ for clamp in data["inputs_clamped"]:+ why = clamp.get("reason") or "allowed {} to {}".format(*clamp["allowed"])+ console.print(+ f"[yellow]Clamped:[/yellow] {clamp['input']} {escape(str(clamp['requested']))} -> "+ f"{escape(str(clamp['used']))} ({escape(why)})"+ )console.print(f"Lag convention: {escape(method['lag_convention'])}")console.print(f"Transform: {escape(method['transform_rule'])} {escape(method['why_changes_default'])}"@@ -3396,7 +3412,7 @@ def history_connections(others = [e for e in pair["significant"] if e["lag"] not in best]if others:listed = ", ".join(- f"lag {e['lag']:+d} (r {e['r']:+.3f}, q {_p_text(e['q'])})" for e in others+ f"lag {e['lag']:+d} (r {e['r']:+.3f}, q_ar1 {_p_text(e['q_ar1'])})" for e in others)console.print(f"Also significant: {escape(pair['a'])} / {escape(pair['b'])}: {listed}")if pair["not_tested"]:diff --git a/src/world_intel_mcp/tests/test_lagged_connections.py b/src/world_intel_mcp/tests/test_lagged_connections.pyindex e203f41..256d83c 100644--- a/src/world_intel_mcp/tests/test_lagged_connections.py+++ b/src/world_intel_mcp/tests/test_lagged_connections.py@@ -133,6 +133,24 @@ def _planted(store, at: float = T0) -> None:_write(store, {"x": _days(x), "y": _days(y, offset=3)}, at)+def _ar1(seed: int, n: int, phi: float) -> list[float]:+ """n unit-variance AR(1) values: e_t = phi e_(t-1) + sqrt(1 - phi^2) z_t."""+ z = _normals(seed, n)+ out = [z[0]]+ for t in range(1, n):+ out.append(phi * out[-1] + math.sqrt(1.0 - phi * phi) * z[t])+ return out+++def _levels(changes: list[float]) -> list[float]:+ """Levels starting at 0 whose day-to-day changes are ``changes``."""+ level, out = 0.0, [0.0]+ for step in changes:+ level += step+ out.append(level)+ return out++# ---------------------------------------------------------------------------# Statistics against independent reference values# ---------------------------------------------------------------------------@@ -500,6 +518,204 @@ def test_cannot_prove_says_a_small_q_is_not_a_large_effect(store) -> None:assert set(lc.NOT_TESTED_REASONS) == {"below_min_overlap", "no_variation"}+# ---------------------------------------------------------------------------+# Serial correlation decides significance (q_ar1)+# ---------------------------------------------------------------------------+++def test_independent_random_walks_in_levels_are_not_flagged(store) -> None:+ """Two independent Gaussian random walks of 300 daily points per seed,+ levels, defaults. q treats the periods as independent and flags almost+ every seed; significant follows q_ar1 and flags about none. Measured+ through the store in a scratch run over seeds 0-99: 91 by q, 0 by q_ar1.+ Seeds 0-19 here: 19 by q, 0 by q_ar1."""+ series = {}+ for s in range(20):+ steps = _normals(s, 600)+ series[f"w{s}a"] = _days(_levels(steps[:300])[1:])+ series[f"w{s}b"] = _days(_levels(steps[300:])[1:])+ _write(store, series)+ flagged = flagged_if_independent = 0+ for s in range(20):+ result = _run(store, [f"w{s}a", f"w{s}b"], transform="levels")+ flagged += result["significant_tests"] > 0+ flagged_if_independent += result["significant_tests_if_independent"] > 0+ assert flagged_if_independent >= 15+ assert flagged <= 1+++def test_autocorrelated_changes_keep_significance_near_the_nominal_rate(store) -> None:+ """Independent pairs whose daily changes are AR(1) with phi 0.8, 200+ changes each, one test per call (max_lag 0), so q_ar1 is p_ar1 and q is+ p. A scratch run of 4,000 pairs gave p <= 0.05 in 35.3% and p_ar1 <= 0.05+ in 5.1%; these 120 pairs give 44 by q and 4 by q_ar1."""+ series = {}+ for run in range(120):+ series[f"ar{run}a"] = _days(_levels(_ar1(2000 + 2 * run, 200, 0.8)))+ series[f"ar{run}b"] = _days(_levels(_ar1(2001 + 2 * run, 200, 0.8)))+ _write(store, series)+ significant = if_independent = 0+ for run in range(120):+ result = _run(store, [f"ar{run}a", f"ar{run}b"], max_lag=0)+ significant += result["significant_tests"]+ if_independent += result["significant_tests_if_independent"]+ assert if_independent >= 30+ assert significant <= 12+ gaps = _run(store, ["ar0a", "ar0b"], max_lag=0)["data_gaps"]+ assert any(g.startswith("lagtest:ar0a: lag-1 autocorrelation +0.8") for g in gaps)+ assert any("significance uses the AR(1)-adjusted p_ar1 and q_ar1" in g for g in gaps)+++def test_below_an_effective_size_of_three_is_no_evidence(store) -> None:+ """Seeds 1000/1001 in levels: |r| 0.87 and q ~ 1e-59 if periods were+ independent, but both lag-1 autocorrelations are above 0.99, leaving an+ effective sample under 1. That is reported as no evidence, not as null."""+ _write(store, {"rwa": _days(_walk(1000, 200)), "rwb": _days(_walk(1001, 200))})+ result = _run(store, ["rwa", "rwb"], transform="levels")+ best = result["pairs"][0]["strongest"][0]+ assert abs(best["r"]) > 0.8 and best["q"] < 1e-50+ assert best["n_effective_ar1"] < 3 and best["p_ar1"] == 1.0 and best["q_ar1"] == 1.0+ assert best["note"].startswith("no evidence:")+ assert best["significant"] is False and best["significant_if_independent"] is True+ assert best["serial_correlation_dominates"] is True+ assert result["significant_tests"] == 0 and result["significant_tests_if_independent"] > 0+ assert result["summary"].startswith("0 of 1 pairs have a lag with q_ar1 <= 0.05")+ assert "Assuming independent periods instead, 1 of 1 pairs have a lag with q <= 0.05." in result["summary"]+ (dominates,) = [g for g in result["data_gaps"] if "serial correlation dominates" in g]+ assert dominates.startswith("lagtest:rwa / lagtest:rwb: serial correlation dominates")+ assert "no evidence either way" in dominates+ assert "significant uses q_ar1" in result["method"]["serial_correlation"]+ assert "post-selection" in result["method"]["serial_correlation"]+++def test_unmeasurable_autocorrelation_is_not_counted_as_significant(store) -> None:+ """Weekly observations on the day grid, in levels: no two observations+ sit on adjacent days, so neither lag-1 autocorrelation can be measured and+ p cannot be adjusted. The near-exact lag-0 match keeps its p but is not+ counted as significant, and the response says why."""+ x = _walk(501, 40)+ noise = _normals(502, 40)+ weeks = [(D0 + timedelta(days=7 * i)).isoformat() for i in range(40)]+ _write(store, {"wx": list(zip(weeks, x)),+ "wy": list(zip(weeks, [v + 0.1 * e for v, e in zip(x, noise)]))})+ result = _run(store, ["wx", "wy"], transform="levels")+ best = result["pairs"][0]["strongest"][0]+ assert (best["lag"], best["n"]) == (0, 40) and best["r"] > 0.99+ assert best["significant_if_independent"] is True and best["significant"] is False+ assert best["n_effective_ar1"] is None and best["p_ar1"] == 1.0+ assert best["serial_correlation_dominates"] is None+ assert best["note"].startswith("not assessed:")+ unmeasurable = [g for g in result["data_gaps"]+ if "lag-1 autocorrelation not measurable (0 adjacent periods" in g]+ assert len(unmeasurable) == 2+ assert all(g.endswith("a median 7 days apart, so a coarser grid may fit") for g in unmeasurable)+++def test_q_and_q_ar1_adjust_across_every_test_in_the_call(store) -> None:+ """Three series, 3 pairs x 11 lags = 33 tests. The planted lag's p (and+ p_ar1) is the smallest in the call by far, so Benjamini-Hochberg gives it+ m p with m = 33, every test in the call; per pair it would be 11 p.+ Measured: q / p = 33.08 and q_ar1 / p_ar1 = 32.98 after rounding to three+ significant digits."""+ _planted(store)+ _write(store, {"z": _days(_walk(13, 200))}, at=T0 + 1)+ result = _run(store, ["x", "y", "z"])+ assert result["tests_run"] == 33+ (xy,) = [p for p in result["pairs"] if (p["a"], p["b"]) == ("lagtest:x", "lagtest:y")]+ best = xy["strongest"][0]+ assert best["lag"] == 3 and 0 < best["p"] <= best["p_ar1"] < 1e-50+ # Ratios: pytest.approx's default absolute tolerance (1e-12) would call+ # any two values this small equal.+ assert best["q"] / best["p"] == pytest.approx(33, rel=0.02)+ assert best["q_ar1"] / best["p_ar1"] == pytest.approx(33, rel=0.02)+ harmonic = sum(1 / i for i in range(1, 34))+ assert best["q_by"] / best["q_ar1"] == pytest.approx(harmonic, rel=0.02)+++def test_strongest_breaks_ties_on_p_by_the_larger_t(store) -> None:+ """b_t = a_(t-2) + 0.9 a_(t-3) + small noise over 3,000 days: in changes,+ r is 0.748 at +2 and 0.675 at +3 on 2,996 points, and both p underflow to+ exactly 0.0. Equal p, so the larger |t| (lag +2) is the strongest."""+ a = _walk(301, 3000)+ noise = _normals(302, 3000)+ b = [a[t - 2] + 0.9 * a[t - 3] + 0.05 * noise[t] for t in range(3, 3000)]+ _write(store, {"ta": _days(a), "tb": _days(b, offset=3)})+ pair = _run(store, ["ta", "tb"])["pairs"][0]+ assert [(e["lag"], e["p"]) for e in pair["significant"]] == [(2, 0.0), (3, 0.0)]+ (best,) = pair["strongest"]+ assert (best["lag"], best["n"]) == (2, 2996)+ assert best["r"] == pytest.approx(0.748, abs=0.005)+++def test_a_q_exactly_at_the_threshold_is_significant(store, monkeypatch) -> None:+ """The rule is q_ar1 <= threshold (q <= threshold for+ significant_if_independent). With every adjusted value forced to the+ threshold itself, every test counts."""+ _planted(store)+ monkeypatch.setattr(lc, "benjamini_hochberg", lambda pvalues: [0.05] * len(pvalues))+ result = _run(store, ["x", "y"])+ assert result["tests_run"] == 11+ assert result["significant_tests"] == 11+ assert result["significant_tests_if_independent"] == 11+ entries = result["pairs"][0]["significant"]+ assert len(entries) == 11 and all(e["q_ar1"] == e["q"] == 0.05 for e in entries)+++def test_effective_sample_size_is_capped_at_n(store) -> None:+ """Changes autocorrelated with opposite signs (measured phi +0.53 and+ -0.42) make (1 - phi_a phi_b) / (1 + phi_a phi_b) about 1.57; the+ effective size is capped at n, so p_ar1 equals p instead of undercutting+ it."""+ pos = _ar1(401, 300, 0.5)+ neg = [c + 0.25 * v for v, c in zip(pos, _ar1(402, 300, -0.5))]+ _write(store, {"pos": _days(_levels(pos)), "neg": _days(_levels(neg))})+ result = _run(store, ["pos", "neg"])+ phi_a, phi_b = (s["lag1_autocorrelation"] for s in result["series"])+ assert phi_a > 0.3 and phi_b < -0.3+ best = result["pairs"][0]["strongest"][0]+ assert best["lag"] == 0 and best["p"] < 1e-4+ assert best["n_effective_ar1"] == best["n"] == 300+ assert best["p_ar1"] == best["p"]+ assert best["serial_correlation_dominates"] is False+++def test_week_grid_reports_unequal_change_intervals(store) -> None:+ """Each week takes its last observation. A series seen on Fridays except+ every third week (Monday only) has changes spanning 3 to 11 days; a daily+ series has 7-day changes throughout."""+ rows = [((D0 + timedelta(days=7 * w + (0 if w % 3 == 0 else 4))).isoformat(), v)+ for w, v in enumerate(_walk(601, 40))]+ _write(store, {"irregular": rows, "daily": _days(_walk(602, 280))})+ result = _run(store, ["irregular", "daily"], grid="week", min_overlap=20, max_lag=1)+ by_key = {s["series_key"]: s for s in result["series"]}+ assert by_key["lagtest:irregular"]["change_interval_days"] == {"min": 3, "max": 11}+ assert by_key["lagtest:daily"]["change_interval_days"] == {"min": 7, "max": 7}+ gaps = result["data_gaps"]+ assert any(g.startswith("lagtest:irregular: on the week grid its changes span 3 to 11 days")+ for g in gaps)+ assert not any(g.startswith("lagtest:daily: on the week grid") for g in gaps)+ assert "unequal intervals" in result["method"]["sampling"]+ levels = _run(store, ["irregular", "daily"], grid="week", transform="levels", max_lag=1)+ assert all(s["change_interval_days"] is None for s in levels["series"])+++def test_window_cut_reports_a_given_start_as_clamped(store, monkeypatch) -> None:+ """The most-recent cut also applies when start is given; the start+ actually used is then reported (200 days, cut to the last 120: day 80)."""+ monkeypatch.setattr(lc, "MAX_PERIODS", 120)+ _planted(store)+ result = _run(store, ["x", "y"], start=D0.isoformat())+ (clamp,) = [c for c in result["inputs_clamped"] if c["input"] == "start"]+ assert clamp == {+ "input": "start", "requested": D0.isoformat(),+ "used": (D0 + timedelta(days=80)).isoformat(),+ "reason": "the window is limited to the most recent 120 days",+ }+ assert result["method"]["window"]["start"] == clamp["used"]+ inside = _run(store, ["x", "y"], start=(D0 + timedelta(days=100)).isoformat())+ assert not [c for c in inside["inputs_clamped"] if c["input"] == "start"]++# ---------------------------------------------------------------------------# Inputs: clamps and errors# ---------------------------------------------------------------------------@@ -712,3 +928,29 @@ def test_cli_connections_json_and_errors(cli_db) -> None:assert out.startswith("Error:") and "lagtest:nope" in outbad = CliRunner().invoke(cli.main, ["history", "connections", "a", "b", "--grid", "hour"])assert bad.exit_code == 2 and "day" in bad.output and "month" in bad.output+++def test_cli_connections_reports_each_clamp(cli_db, monkeypatch) -> None:+ out = _invoke("history", "connections", "lagtest:x", "lagtest:y",+ "--min-overlap", "5", "--max-lag", "40", "--q", "0.5").output+ assert "Clamped: min_overlap 5 -> 20 (allowed 20 to 3000)" in out+ assert "Clamped: max_lag 40 -> 30 (allowed 0 to 30)" in out+ assert "Clamped: q 0.5 -> 0.25 (allowed 0.001 to 0.25)" in out+ monkeypatch.setattr(lc, "MAX_PERIODS", 120)+ cut = _invoke("history", "connections", "lagtest:x", "lagtest:y", "--start", D0.isoformat()).output+ used = (D0 + timedelta(days=80)).isoformat()+ assert (f"Clamped: start {D0.isoformat()} -> {used} (the window is limited to the most "+ "recent 120 days)") in cut+ assert "Clamped:" not in _invoke("history", "connections", "lagtest:x", "lagtest:y").output+++def test_cli_connections_table_shows_p_ar1_and_q_ar1(cli_db) -> None:+ args = ("history", "connections", "lagtest:x", "lagtest:y", "--transform", "levels")+ best = json.loads(_invoke("--json-output", *args).output)["pairs"][0]["strongest"][0]+ out = _invoke(*args).output+ (header,) = [line for line in out.splitlines() if "n_eff" in line and "Timing" in line]+ assert header.split()[-5:] == ["p", "q", "p_ar1", "q_ar1", "Significant"]+ (row,) = [line for line in out.splitlines() if "A leads B by 3 days" in line]+ assert row.split()[-3:] == [cli._p_text(best["p_ar1"]), cli._p_text(best["q_ar1"]),+ "yes" if best["significant"] else "no"]+ assert "p_ar1 and q_ar1 use n_eff, and Significant means q_ar1 <= 0.05" in outdiff --git a/src/world_intel_mcp/tools/lagged_connections.py b/src/world_intel_mcp/tools/lagged_connections.pyindex 44c5298..77c5352 100644--- a/src/world_intel_mcp/tools/lagged_connections.py+++ b/src/world_intel_mcp/tools/lagged_connections.py@@ -24,8 +24,13 @@ TOOLS: list[Tool] = ["tested at every lag from -max_lag to +max_lag. Default transform is period-over-""period changes, because levels of trending series correlate spuriously; 'levels' ""on request. Per pair: the lag with the strongest evidence (smallest p) with "- "Pearson r, overlap n, two-sided p from Student's t, and the Benjamini-Hochberg q "- f"across every test in the call (significant at q <= {lc.DEFAULT_Q:g} by default). "+ "Pearson r, overlap n, two-sided p from Student's t treating periods as "+ "independent, p_ar1 recomputed with an AR(1) effective sample size from both "+ "series' lag-1 autocorrelations, and the Benjamini-Hochberg q and q_ar1 across "+ f"every test in the call. Significant means q_ar1 <= {lc.DEFAULT_Q:g} by default "+ "(significant_if_independent applies it to q); serial_correlation_dominates and "+ "data_gaps name autocorrelated series, and an effective sample below 3 is "+ "reported as no evidence. ""Lag +k compares A at period t with B at t+k, so A leads B by k. Pair/lag "f"overlaps under {lc.DEFAULT_MIN_OVERLAP} points are listed as not tested. Revised ""points use the latest vintage; rows without observed_at (Yahoo quotes) are not "@@ -77,14 +82,18 @@ TOOLS: list[Tool] = ["q": {"type": "number","description": (- f"False discovery rate threshold (default {lc.DEFAULT_Q:g}, clamped to "- f"{lc.Q_FLOOR:g}..{lc.Q_CAP:g})"+ f"False discovery rate threshold applied to q_ar1 (default "+ f"{lc.DEFAULT_Q:g}, clamped to {lc.Q_FLOOR:g}..{lc.Q_CAP:g})"),"default": lc.DEFAULT_Q,},"start": {"type": "string",- "description": "First date YYYY-MM-DD; its grid period and later are used",+ "description": (+ "First date YYYY-MM-DD; its grid period and later are used (moved "+ f"later, and reported, when the window would exceed {lc.MAX_PERIODS:,} "+ "periods)"+ ),},"end": {"type": "string",