# Ecosystem Maintenance & Integration Workflow (WORKFLOW.md)

This operational guide enforces structural consistency, schema validity, and zero-hallucination determinism across the dual-ecosystem endpoints (`analysisreports.github.io` and `ersoytoptas.tr`) whenever a new quantitative model, data series, geopolitical actor, or bilateral dyad is introduced.

---

## 0. Core Engineering Contract (Zero-Hardcode, Zero-Fallback & SSOT Rules)

All executable Python engines MUST obey five non-negotiable rules:

1. **Zero Hardcode & Zero Numeric Fallback:** Never embed model thresholds, weights, regime labels, API series lists, or numeric defaults (e.g., `.get("key", 0.0)`) inside `.py` scripts. Missing or failed live data MUST remain `None`/`null` (or the explicit unavailable sentinel such as `SOURCE_FEED_UNAVAILABLE` / `N/A`), never `0` or a fabricated value.
2. **Centralized SSOT Rule Files (`llms-*-rules.json`):** Every configurable rule lives in its designated JSON contract:

| Rule File (SSOT) | Governs |
| --- | --- |
| `llms-model-rules.json` | Model thresholds, chokepoint/component weights, regime labels, `output_interpretation_template`, `txt_code_replacements` |
| `llms-series-rules.json` | All 14 time-series providers (API endpoints, series registries, unit mappings, `cache_ttl_days: 0` live-refresh policy) |
| `llms-relationship-rules.json` | Bilateral/multilateral polarity calculation parameters and regime rules |
| `llms-nexus-rules.json` | Deterministic Cognitive Nexus Engine (Claims-vs-Reality radar) evaluation rules |
| `llms-news-rules.json` | Accredited RSS feeds, entity-tagging rules, and Media Manipulation & Political Noise Rejection filters |
| `llms-fixeddata-rules.json` | Verified static structural reference constants |
| `llms-cds-rules.json` | Synthetic Sovereign CDS & Credit Risk Premium calculation thresholds, weights, and regime mappings |

3. **Compile — Never Hand-Edit Derived Outputs:** Federated master files (`llms-formulas.txt`, `llms-graph.json`, `llms-country-relationships.json/.txt`) and live snapshots (`llms-models.json/.txt`, `llms-sitrep.json/.txt`, `llms-nexus.json/.txt`, `llms-relationships.json/.txt`) MUST only be regenerated via their compiler/engine scripts.
4. **Epistemic Neutrality (Zero Ideological Bias, Zero Unproven Causality & Zero Absolute Claims):** Formulas, model templates (`output_interpretation_template`), bridge narratives (`llms-models-bridge.txt`), and SITREP alerts MUST remain strictly analytical and ideologically neutral. Never state unproven causality or absolute conclusions as established fact (e.g., claiming one series *"forces"* or *"proves"* another); explicitly label concurrent movements between separate indicators as **proxies, indicators, or co-movement signals**. Never substitute a prior period's observation for a missing current period (no silent carry-forward).
5. **Data Freshness & Vintage Gate (12-Month Maximum Lag):** Before designing, writing, or revising ANY quantitative model or formula, inspect the latest actual `last_date` of **every** candidate series, country, or actor in its provider JSON (`llms-*-series.json`). **NO MODEL OR FORMULA MAY BE WRITTEN** using any series/country whose latest available observation is older than **12 months** (unless the model is explicitly designed, named, and documented as an annual/structural benchmark and approved upfront). Series or countries failing the 12-month freshness check MUST be excluded before drafting formulas.

---

## 1. Adding or Revising a Quantitative Model

> **Pre-Flight Freshness Gate (Mandatory Before Step 1):** Check `last_date` of every candidate input series (and every country/sub-series in multi-country models) in `llms-*-series.json`. If any series or country is older than **12 months**, STOP and exclude it before writing a model or formula.

For a new model or a material change to an existing model, execute all 10 steps in order. Do not treat this as an add-only checklist:

1. **`llms-model-rules.json` (SSOT Parameters First)** — Register the model's thresholds, weights, caps, regime enums, `output_interpretation_template`, and `txt_code_replacements` under `MODEL_<ID>`. Never hardcode thresholds or weights in Python. Only document calibrated thresholds; when thresholds are unavailable, use and document `UNCLASSIFIED` rather than inventing regimes. **Narrative Synthesis Completeness Rule:** Whenever an existing model gains an additional calculation layer, regulator, or dynamic input, you MUST update `output_interpretation_template` so `llms-models.json` (`interpretation`) and `llms-models.txt` (`Economic Synthesis`) explicitly reflect every active component upfront.
2. **Domain Formula Shelves (`llms-formulas-*.txt`) & Compiler (`scripts/build_formulas.py`)** — Write the model purpose, exact series IDs, units, mathematical formula, executable Python logic, validation behavior, temporal-integrity contract, and interpretation inside its designated domain shelf (`llms-formulas-rates-liquidity.txt`, `llms-formulas-macro-labor.txt`, `llms-formulas-commodities-shock.txt`, or `llms-formulas-geopolitics.txt`). The shelf signature MUST expose every material calculator argument, including optional observation metadata. Document the reason for formulas, transformations, thresholds, caps, and assumptions. Do not leave a new range guard, dynamic input, or output field documented only in Python. Run `python scripts/build_formulas.py` to auto-compile the Master Router (`llms-formulas.txt`). Use canonical entity IDs from `llms-entities-id.txt`.
3. **Series and Indicator Catalogs** — If the model introduces new series, complete **Section 2** first (`llms-series-rules.json`, provider TXT, `llms-indicators.txt`, `llms-entities-id.txt`). Let provider sync jobs produce observation JSON; never hand-write observations or use stale values as live inputs.
4. **`scripts/calculate_models.py`** — Implement or revise the calculation reading all thresholds, weights, ranges, caps, units, and regime values from `llms-model-rules.json`, with strict type, boolean, unit, zero-division, overflow, and `math.isfinite` guards. Reject out-of-range values with `None`; never clamp invalid values into a valid range and never use numeric fallbacks. Keep optional context metrics distinct from formula inputs. Every model input that carries an observation date MUST use a real ISO `YYYY-MM-DD` value parsed as a calendar date; non-empty string checks are insufficient. Missing, malformed, impossible, extra, or incomplete date metadata must fail closed. Date maps and canonical frequency maps MUST be supplied together and use identical required keys.
   - **Frequency Semantics:** `asynchronous_frequencies` means that the canonical source frequencies differ (for example Monthly + Daily). It MUST NOT be inferred from publication-date inequality. Equal-frequency inputs with different release dates are `false`; all differing dates remain explicitly visible in `observation_dates`.
   - **Output Contract:** Whenever observation metadata is present, write `observation_dates`, `observation_frequencies`, and `asynchronous_frequencies` together into `inputs`. Different release dates, stale/vintage inputs, and mixed-frequency warnings must remain observable; metadata gaps must not silently remove the model or be replaced by fabricated dates.
5. **`llms-tools.json`, Graph & Schema Contract Parity** — If the model is exposed as a callable tool, keep its description, every material parameter, units, required fields, optional metadata, formats, and validation needs consistent with the Python signature and formula shelf. **Naming Contract:** Tool function names MUST use the exact `calculate_<model_slug>` identifier across `llms-tools.json`, `llms-graph-models.json`, and `llms-models-bridge.txt` (enforced by `verify_cross_consistency.py`). If model output gains a structured field, update `schemas/models.schema.json` when that field is contractually required; generic `additionalProperties: true` alone is not sufficient for a newly required invariant.
6. **`llms-full.txt`** — Update the model registry entry (`- <ID>. <Model Name>`) and its input series list.
7. **Federated Knowledge Graph (`llms-graph-models.json` + `scripts/build_graph.py`)** — Add the `MODEL_<ID>` node (referencing the exact `calculate_<model_slug>` tool name), any missing `IND_*` nodes, and `INGESTS_SERIES` edges in `llms-graph-models.json` — **never hand-edit `llms-graph.json`**. Remove obsolete model-input edges; retain an indicator node if other relationships still use it. **Duplicate Node Guard:** Before adding a `CHOKE_*`, `GEO_*`, or `BLOC_*` node to `llms-graph-models.json`, verify it does not already exist in `llms-graph-chokepoints.json`, `llms-graph-actors.json`, or `llms-graph-blocs.json` (duplicate federated `node.id` values fail `verify_graph_topology.py`). Run `python scripts/build_graph.py` to compile `llms-graph.json`.
8. **`llms-models-bridge.txt` & `llms-relationships.txt` (Mandatory Linkage Registration)** — Document every model in `llms-models-bridge.txt` (including exact `calculate_<model_slug>` function name, exact inputs, status enums, primary macro/geopolitical transmission vector, and jurisdictional/actor coupling — never leave a model unlinked). Maintain the canonical bridge reference in `llms-relationships.txt` (and wire live cross-signals into `scripts/sitrep/matrices.py` when the model belongs on a SITREP matrix).
9. **Generated Model Snapshots** — Regenerate `llms-models.json` and `llms-models.txt` exclusively via `python scripts/calculate_models.py` after all required live inputs are available. Never patch observed values or statuses into these outputs by hand; report the snapshot as stale when regeneration is blocked.
10. **Focused Unit Tests & Verification Gate** — Add or update a focused test module (`scripts/test_<model>.py`) covering: normal calculation; every regime branch; exact boundary values; immediately-above/below epsilon cases; lower/upper range caps; missing, boolean, non-finite, and type-invalid inputs; malformed ISO dates and impossible calendar dates; incomplete date/frequency pairs; same-frequency/different-date semantics; and mixed-frequency semantics. Tests must assert the output field names and values, not merely model existence. Run all mandatory verification commands in **Section 5**.

### Mandatory Model Contract Parity Review

Before declaring a model complete, trace one input from provider output to final publication and compare all surfaces:

1. `llms-series-rules.json` / provider snapshot -> `calculate_models.py` input extraction
2. `llms-model-rules.json` -> calculator thresholds, caps, validation, and interpretation
3. Python signature -> `llms-formulas-*.txt` executable signature
4. Python output shape -> `llms-tools.json`, `schemas/models.schema.json`, `llms-models.json`, and `llms-models.txt`
5. Exact `calculate_<model_slug>` name -> tools, graph, and bridge
6. Every documented regime -> executable branch and focused test
7. Every dynamic input/date/frequency field -> narrative template or explicit metadata output

Automated gates passing does **not** replace this review. A missing field can pass generic verification if the schema or test suite is permissive. Agents MUST manually verify semantic parity and update the applicable schema, tool manifest, formula shelf, or tests rather than treating a green pipeline as proof of correctness.

### Model-Specific Operational Rules
- **Model 11 (Taylor Rule):** The FRED sync requests `GDPPOT` for the exact `GDPC1` quarter through the FRED API when a key is available, then the FRED CSV endpoint if needed. Network failures are retried; neither endpoint may supply a different quarter or a cached substitute. If both fail, model refresh fails and existing model snapshots remain unchanged and may be stale.
- **`IMF_REP_USD_ILS`:** Local registry identifier for the IMF's daily representative Israeli shekel per US dollar rate (not an IMF SDMX series code). The sync reads IMF monthly archives with the same observation limit, five-observation output, and `cache_ttl_days: 0` live-refresh policy configured in `llms-series-rules.json`. Failed refreshes retain and mark the existing snapshot as stale.

### Decommissioning / Removing a Model, Formula, Series, or Python Module

Never delete a model, formula, or series ad-hoc — stale references break schema validation, graph topology, cross-consistency, or MCP tools. Follow this exact checklist:

1. **Impact Search First (Zero Orphan / Zero Collateral Damage):** Search the entire repository for the target identifiers (`MODEL_<ID>`, `calculate_<model_slug>`, Python function name, `IND_<SERIES_ID>`, and raw series code) across `scripts/`, `llms-*`, `schemas/`, and `worker.js`. **Do NOT remove** any `IND_*`, `GEO_*`, `CHOKE_*`, or provider series that is still referenced by another active model, bridge, SITREP rule, or graph edge.
2. **Clean Git Revert Shortcut (When Isolated):** If the target was introduced in a single clean commit with no unrelated changes (or only separable edits), prefer `git checkout <commit>~1 -- <affected_files>` and `git rm` on new test files, then proceed to Step 9.
3. **Python Engine & Tests:** Remove or update unit tests (`scripts/test_<model>.py`), model wiring in `scripts/calculate_models.py`, and the calculator function in `scripts/models/*.py` (remove any unused imports/helpers).
4. **SSOT Rules & Formula Shelf:** Remove `MODEL_<ID>` from `llms-model-rules.json`, remove the formula section from `llms-formulas-*.txt`, and recompile `llms-formulas.txt` via `python scripts/build_formulas.py`.
5. **Tooling, Schema & Registry Surfaces:** Remove the tool definition from `llms-tools.json`, remove any model-specific enum/constraint from `schemas/models.schema.json`, and remove entries from `llms-full.txt`, `llms-models-bridge.txt`, and `llms-relationships.txt` (plus `scripts/build_sitrep.py` / `worker.js` if explicitly wired).
6. **Federated Knowledge Graph:** Remove the `MODEL_<ID>` node, its `INGESTS_SERIES` / `BRIDGES_TO_MODEL` edges, and **only** orphaned `IND_*` nodes (unused by any other subgraph/model) from `llms-graph-models.json`. Recompile `llms-graph.json` via `python scripts/build_graph.py`.
7. **Orphan Entity & Series Cleanup (Only If Unused Everywhere):** Remove orphaned `IND_*` entries from `llms-entities-id.txt`. If a time series itself is being retired, also remove it from `llms-series-rules.json`, `llms-indicators.txt`, and `llms-<provider>-series.txt` (then regenerate provider snapshots via the sync script).
8. **Regenerate Live Snapshots:** Run `python scripts/calculate_models.py` (and `python scripts/build_sitrep.py` if SITREP referenced it) so `llms-models.json` and `llms-models.txt` drop the removed item cleanly.
9. **Zero-Remnant Scan & Mandatory Gates:** Search the repo again (`Select-String` / `rg`) to confirm **0 remaining matches** for the removed model/function IDs, then run `python -m unittest discover -s scripts -p "test_*.py"`, `python scripts/verify_all.py`, and `verify_workflow.py`. After `git push`, remember Cloudflare Worker edge cache (`CACHE_TTL_SECONDS = 3600` for formula/graph routes in `worker.js`) may serve the prior version for up to 1 hour unless purged in Cloudflare Dashboard (`Caching -> Configuration -> Purge Cache`).

---

## 2. Adding or Revising a Time-Series / Data Provider

All 14 monitored time-series providers (`fred`, `ecb`, `nyfed`, `eia`, `eurostat`, `comtrade`, `worldbank`, `wbmacro`, `imf`, `tradestat`, `census`, `bis`, `gie`, `boi`) are governed by `llms-series-rules.json` with `cache_ttl_days: 0` so daily automated runs always fetch fresh releases. To add or modify a series:

1. **`llms-series-rules.json`** — Register the series code, metadata, frequency, unit, `stale_threshold_days`, and provider endpoint configuration under the target provider key. Keep `cache_ttl_days` at `0` (unit tests that verify TTL caching behavior must mock `CACHE_TTL_DAYS` locally rather than altering production rules).
2. **Provider TXT Catalog (`llms-<provider>-series.txt`)** — Document the exact series key, title, frequency, and unit.
3. **`llms-indicators.txt`** — Register the exact series key in the master indicator dictionary.
4. **`llms-entities-id.txt`** — If the series is referenced as a node in the Knowledge Graph, register its canonical `IND_<SERIES_ID>` identity.
5. **Provider Sync Script (`scripts/update_<provider>_series.py`)** — Ensure ingestion reads exclusively from `llms-series-rules.json` with zero hardcoded fallbacks and obeys four strict data-integrity guards:
   - **Dimension Pinning & Collision Guard (SDMX / Bulk APIs):** Pin every non-entity series dimension in the query key (and verify `structure.dimensions.series` on live responses). Never silently overwrite an existing `series_id`; raise `ValueError` on duplicate key collisions.
   - **Raw-Precision-First (No Intermediate Rounding):** Compute `change`, `change_from_year_ago`, `percent_change`, and `percent_change_from_year_ago` (as well as model formulas) on full-precision raw `float` values; apply `round()` only at final JSON/TXT serialization.
   - **Dynamic Staleness Tracking:** Never hardcode `metadata.stale_series` as `[]`. Compute stale series dynamically from `stale_threshold_days` in `llms-series-rules.json`, calibrated to the provider's official publication lag.
   - **Missing-Period Integrity (Zero Carry-Forward):** Missing periods (`"."`, `null`, or calendar gaps) MUST leave `previous_value` / `year_ago_value` and dependent transformations as `None`/`null` — never step back to an older non-null observation.
   - Never hand-write observations into `llms-<provider>-series.json`; let the live sync or GitHub Actions generate the JSON twin.
6. **New Provider Ecosystem Wiring (Required When Adding a New Provider)** — Register the provider across all governance, discovery, verifier, and CI surfaces: `workflow-gates.json` (`providers`), `WORKFLOW.md` (Sections 2 & 4), `llms.txt`, `llms-full.txt`, `ai-catalog.json`, `scripts/verify_root_schemas.py`, `scripts/verify_cross_consistency.py`, `scripts/verify_workflow.py`, and `.github/workflows/<provider>-sync.yml`.
7. **Live Value Sanity-Check & Focused Provider Tests (`scripts/test_<provider>_series.py`)** — After the first live sync, manually inspect 3–5 sample series per dataflow for expected sign, magnitude, and unit (schema pass alone does not prove semantic correctness). Add focused unit tests covering period stepping, duplicate-key collision (`ValueError`), area/entity exclusions, raw-precision transformations, missing prior periods (`None`), and staleness detection.

---

## 3. Adding a Geopolitical Actor, Chokepoint, Corridor, or Bilateral Dyad

When introducing a sovereign state, proxy group, maritime chokepoint, multilateral settlement network, or bilateral dyad, synchronize the following files in sequential order:

1. **`llms-entities-id.txt` (Ground-Truth Identity Registration)**
   - Register the canonical entity ID matching the domain-prefixed regex pattern:  
     `^(INST_|GOV_|GEO_|REG_|PROXY_|ORG_|BLOC_|CHOKE_|CORRIDOR_|BASIN_|ZONE_|STAT_|REG_AGENCY_|MKT_|SEC_|IND_)[A-Z0-9_]+$`
   - Include all natural language variations, official titles, and multilingual aliases:  
     `GEO_[ID] | Aliases: [Name], [Official Title], [Acronym]`

2. **`llms-relationship-rules.json` & Federated Country Relationship Shelves (`scripts/build_country_relationships.py`)**
   - For bilateral dyads under the 4 sovereign hubs (`GEO_US`, `GEO_RU`, `GEO_CN`, `GEO_IR`), update the corresponding shelf twins (`llms-country-relationships-{us,ru,cn,ir}.json` and `.txt`) with 100% symmetric mirrors (zero hub leaks).
   - Run `python scripts/build_country_relationships.py` to compile the Master Router (`llms-country-relationships.json` and `llms-country-relationships.txt`).

3. **`llms-relationships.txt` & `llms-relationships.json`**
   - Register baseline polarity (`P_baseline` between `-1.0` and `+1.0`), structural regime state, primary friction nodes, economic coupling factors, and macro transmission series.
   - Run `python scripts/update_relationships.py` so the live dynamic polarity table (`### 1.1`) and `llms-relationships.json` stay in exact dual-twin parity (`dynamic_delta`, `mecca_pact_delta`, `legacy_dynamic_delta`, `P_net`).

4. **Federated Knowledge Graph (`llms-graph-actors.json` / `llms-graph-blocs.json` / `llms-graph-chokepoints.json` + `scripts/build_graph.py`)**
   - Register sovereign/institutional/proxy actors in `llms-graph-actors.json`, multilateral blocs/organizations (`BLOC_*`, `ORG_*`) and `INCLUDES_MEMBER` edges in `llms-graph-blocs.json`, and maritime chokepoints/basins/corridors in `llms-graph-chokepoints.json` (never duplicate an existing `node.id` across subgraphs).
   - Connect edges using canonical types (`POLARITY_COUPLING`, `PATRON_COUPLING`, `TRIGGERS_INDICATOR`, or `BRIDGES_TO_MODEL`).
   - Run `python scripts/build_graph.py` to recompile `llms-graph.json`.

5. **`llms-indicators.txt`**
   - If tracking actor-specific FX pairs, swap spreads, or sovereign CDS yields, register the new series key in the dictionary.

---

## 4. Canonical Static Manifests, Compilers & Automated Engines

The following manifest files must remain stable to prevent semantic cache invalidation:

### Core Navigation, Identity & Governance
- `llms.txt` & `llms-full.txt`: Root navigation manifest and full master catalog.
- `llms-about.txt`: Author credentials, methodology, and anti-hallucination operational contract.
- `llms-prompts.txt`: Canonical 6-stage Chain-of-Thought reasoning protocols and attribution guardrails.
- `llms-entities-id.txt`: Canonical entity and indicator registry dictionary.
- `llms-indicators.txt`: Master indicator catalog across all providers.
- `llms-models-bridge.txt`: Macroeconomic model linkages, chokepoint spillovers, and geopolitical shock transmissions.
- `llms-tools.json`: Function-calling tool specification manifest.
- `ai-catalog.json`: Dataset discovery registry; updated automatically via the daily GitHub Actions heartbeat workflow.

### Time-Series Provider Twins (14 Providers — Governed by `llms-series-rules.json`)
- `llms-fred-series.txt` & `.json` (`scripts/update_fred_series.py`)
- `llms-ecb-series.txt` & `.json` (`scripts/update_ecb_series.py`)
- `llms-nyfed-series.txt` & `.json` (`scripts/update_nyfed_series.py`)
- `llms-eia-series.txt` & `.json` (`scripts/update_eia_series.py`)
- `llms-eurostat-series.txt` & `.json` (`scripts/update_eurostat_series.py`)
- `llms-comtrade-series.txt` & `.json` (`scripts/update_comtrade_series.py`)
- `llms-worldbank-series.txt` & `.json` (`scripts/update_worldbank_series.py`)
- `llms-wbmacro-series.txt` & `.json` (`scripts/update_wbmacro_series.py`)
- `llms-imf-series.txt` & `.json` (`scripts/update_imf_series.py`)
- `llms-tradestat-series.txt` & `.json` (`scripts/update_tradestat_series.py`)
- `llms-census-series.txt` & `.json` (`scripts/update_census_series.py`)
- `llms-bis-series.txt` & `.json` (`scripts/update_bis_series.py`)
- `llms-gie-series.txt` & `.json` (`scripts/update_gie_series.py`)
- `llms-boi-series.txt` & `.json` (`scripts/update_boi_series.py`)

### Live Telemetry, Synthesis & State-Machine Twins
- `llms-portwatch.txt` & `.json`: IMF PortWatch maritime chokepoint AIS transit telemetry (`scripts/update_portwatch.py`).
- `llms-nasa-firms.txt` & `.json`: NASA FIRMS satellite thermal/kinetic anomaly telemetry (`scripts/update_nasa_firms.py`).
- `llms-sitrep.txt` & `.json`: Live consolidated Situation Report (`scripts/build_sitrep.py`).
- `llms-repertory.txt` & `.json`: Entity- & topic-indexed verified telemetry warehouse (`scripts/build_repertory.py`), queried selectively via MCP `query_repertory` and promoted into SITREP on active news triggers.
- `llms-nexus.txt` & `.json`: Deterministic Cognitive Nexus Engine evaluated from `llms-nexus-rules.json` (`scripts/calculate_nexus.py`).
- `llms-news.txt` & `.json`: Tier-1 geopolitical/macro news telemetry filtered by `llms-news-rules.json` (`scripts/update_news.py`).
- `llms-articles.txt` & `.json`: Canonical English-only Dual-Twin research articles index (`scripts/build_articles_index.py`).
- `llms-relationships.txt` & `.json`: Dynamic geopolitical polarity and active regime state-machine twin (`scripts/update_relationships.py`).
- `llms-models.txt` & `.json`: Real-time evaluated quantitative models twin (`scripts/calculate_models.py`).
- `llms-cds.txt` & `.json`: Synthetic Sovereign CDS & Credit Risk Premium section (`scripts/calculate_cds.py`).

### Federated Compilers (`scripts/build_*.py`) & CI/CD Workflows
- **Compilers:** `build_formulas.py`, `build_graph.py`, `build_country_relationships.py`, `build_sitrep.py`, `build_articles_index.py`, `build_sitemap.py`.
- **GitHub Actions:** `fred-sync.yml` (daily 00:00 UTC full series + relationships + models pipeline), `bis-sync.yml`, `boi-sync.yml`, `wbmacro-sync.yml`, `cds-sync.yml` (00:45 UTC), `news-sitrep-sync.yml` (every 4h news & SITREP), `portwatch-sync.yml`, `nasa-sync.yml`, `census-sync.yml`, and `validate.yml` (push/PR CI gate).

---

## 4.5. MCP Server Token Budget & Governance Contract (`worker.js` & `.well-known/mcp.json`)

Whenever modifying the live Cloudflare Worker MCP server (`worker.js`) or adding new Knowledge Graph subgraphs/tools, agents MUST obey these strict token-efficiency rules (enforced automatically by `scripts/verify_mcp.py`):

1. **Zero `"all"` / Full-Dump Policy:** Never expose `"all"` in any `inputSchema` enum or invite full-file dumps in tool descriptions/hints. If a client passes `"all"` manually, return the lightweight index or `"summary"` slice instead.
2. **Default Call Token Ceiling (`<= 2,500` tokens):** Every parameterless tool call MUST return a lightweight index or compact slice (`<= 2,500` est. tokens). Never dump raw multi-kilobyte datasets (`llms-country-relationships*.txt`, `llms-formulas*.txt`, `llms-models.json`).
3. **Targeted & Multi-Item Queries:** Support comma-separated multi-item lookups (`pair: "TR, US, IR"`, `query: "25.14, 25.23"`, `node: "GEO_TR, GEO_US, GEO_IR"`) so multi-entity questions resolve in a single compact call.
4. **Subgraph & Manifest Parity:** Every subgraph registered in `llms-graph.json` (`chokepoints`, `blocs`, `actors`, `models`) MUST be wired into `worker.js` (`subgraph` enum, endpoint map, and `Promise.all` traversal). Tool names and `MCP_VERSION` in `worker.js` MUST match `.well-known/mcp.json` 100%.

---

## 4.6. File Size & Bloat Quotas (Code & `llms-*` Outputs)

To prevent silent bloat in both Python source modules and AI-facing `llms-*` outputs, `scripts/verify_file_quotas.py` enforces two-tier quotas configured in `workflow-gates.json` (`file_quotas`):

1. **Early Warning (`WARN`):** Emits a `[WARN] BLOAT ALERT` with current line count, KB size, and quota percentage without failing the build — signaling that a module should be split or an output compacted before hitting the hard ceiling.
2. **Hard Ceiling (`MAX`):** Fails the verification gate (`exit 1`) if exceeded; refactor or split the file before adding new models, rules, or sections.
3. **Scope:**
   - **Python modules (`scripts/**/*.py`):** `WARN` at `600` lines / `30 KB`; `MAX` at `2,000` lines / `80 KB`.
   - **`llms-*` outputs (`llms-*.txt`, `llms-*.json`, excluding raw `llms-*-series.json` archives):** Per-file quotas for primary AI endpoints (`llms-sitrep.*`, `llms-models.*`, `llms-full.txt`, `llms-graph.json`, `llms-formulas.txt`, `llms-nexus.txt`, `llms-news.txt`) and `default` bounds (`WARN 2,500 lines / 110 KB`, `MAX 4,000 lines / 160 KB`) defined in `workflow-gates.json`.

---

## 5. Pre-Commit Verification Checklist & Mandatory Gates

Before committing or pushing any change, confirm every item below:

- [ ] **Zero Hardcode / Zero Fallback:** All new thresholds, weights, and series configs live in `llms-*-rules.json`; Python handles `ZeroDivisionError` and `math.isfinite` without substituting `0` or mock defaults.
- [ ] **JSON Schema Validation:** All **18** Draft 2020-12 JSON schemas (`schemas/*.schema.json`) and all root & article payload endpoints pass `python scripts/verify_root_schemas.py`.
- [ ] **JSON Syntax Validity:** Every `.json` file in the repository parses cleanly with zero trailing commas or malformed brackets.
- [ ] **Entity & Series Identity:** Every actor, institution, chokepoint, and indicator matches `llms-entities-id.txt`, `llms-indicators.txt`, and its provider TXT registry.
- [ ] **Federated Graph Integrity:** `python scripts/build_graph.py` has been run; zero duplicate `node.id` across `llms-graph-{actors,blocs,models,chokepoints}.json`; every edge endpoint exists.
- [ ] **MCP Contract & Token Budget:** `worker.js` and `.well-known/mcp.json` pass `python scripts/verify_mcp.py` (zero `"all"` enums, `<= 2,500` token default ceiling, 100% tool & subgraph parity).
- [ ] **File Size & Bloat Quotas:** `python scripts/verify_file_quotas.py` passes with zero `MAX` ceiling violations; inspect any `[WARN] BLOAT ALERT` before adding new code or output sections.
- [ ] **Tool & Bridge Naming Parity:** Exact `calculate_<model_slug>` match across `llms-tools.json`, `llms-graph-models.json`, and `llms-models-bridge.txt`.
- [ ] **Model Formula & Tool Signature Parity:** Python signatures, formula-shelf signatures, tool parameters, units, optional metadata, and output field names are synchronized.
- [ ] **Observation Metadata Integrity:** Dates are real ISO `YYYY-MM-DD` values; date/frequency maps are complete and paired; invalid metadata fails closed; `asynchronous_frequencies` is derived from canonical frequencies, not unequal timestamps.
- [ ] **Focused Boundary Coverage:** Every status branch, exact cap/boundary, epsilon side, invalid input, and temporal metadata edge case is covered by focused tests.
- [ ] **Schema-Enforced Structured Fields:** New required model input/output metadata is explicitly constrained in `schemas/models.schema.json`; permissive object properties are not treated as a substitute for a model invariant.
- [ ] **Dual-Twin Parity:** `llms-relationships`, `llms-country-relationships-*`, `llms-models`, `llms-sitrep`, `llms-nexus`, and `llms-news` TXT/JSON pairs are 100% synchronized.

### Mandatory Local Verification Commands

Run all three gates before committing:

```powershell
# 1. All unit tests (including model, schema, alignment, and workflow tests)
python -m unittest discover -s scripts -p "test_*.py"

# 2. Full 16-engine institutional verification suite (includes verify_mcp.py)
python scripts/verify_all.py

# 3. Change-completeness gate (PowerShell; on bash use WORKFLOW_BASE_SHA=HEAD)
$env:WORKFLOW_BASE_SHA="HEAD"; python scripts/verify_workflow.py
```

### Automated Change-Completeness Gate

The `scripts/verify_workflow.py` CI check compares the pull request with its base revision. It checks newly added dynamic relationship pairs for matching TXT/JSON rows, registered entity IDs, and graph nodes and coupling edges. New geopolitical entities require graph nodes and edges. Newly published model snapshots require formula and registry entries, a graph node, and an `INGESTS_SERIES` input edge; newly published provider series across all 14 providers require provider TXT and indicator entries. Existing verification checks continue to run across the repository via `validate.yml`.

This gate cannot establish that an implementation or test is correct, detect every model before a snapshot is published, or verify conditional requirements such as tool exposure. Reviewers and agents must still follow the full checklist above, including material revisions, focused tests, and stale snapshots. Existing gaps are not silently treated as fixed: the change gate checks additions rather than blocking unrelated changes for older gaps.
