gasp-standard-mcp 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +24 -4
  2. package/build/cel.d.ts +84 -0
  3. package/build/cel.js +211 -0
  4. package/build/checks.d.ts +173 -0
  5. package/build/checks.js +465 -0
  6. package/build/compile.d.ts +4 -0
  7. package/build/compile.js +6 -1
  8. package/build/derive.d.ts +8 -0
  9. package/build/derive.js +11 -2
  10. package/build/dialect.d.ts +5 -2
  11. package/build/dialect.js +6 -1
  12. package/build/formula.d.ts +3 -0
  13. package/build/formula.js +3 -0
  14. package/build/index.js +113 -29
  15. package/build/loader.js +17 -1
  16. package/build/ossie/adapt.d.ts +96 -0
  17. package/build/ossie/adapt.js +363 -0
  18. package/build/ossie/check.d.ts +18 -4
  19. package/build/ossie/check.js +88 -18
  20. package/build/ossie/company.d.ts +55 -0
  21. package/build/ossie/company.js +215 -0
  22. package/build/ossie/conformance.d.ts +100 -0
  23. package/build/ossie/conformance.js +186 -0
  24. package/build/ossie/decide.d.ts +81 -0
  25. package/build/ossie/decide.js +532 -0
  26. package/build/ossie/demo.d.ts +62 -0
  27. package/build/ossie/demo.js +100 -0
  28. package/build/ossie/drift.d.ts +159 -0
  29. package/build/ossie/drift.js +650 -0
  30. package/build/ossie/example.d.ts +16 -0
  31. package/build/ossie/example.js +203 -0
  32. package/build/ossie/index.js +1 -1
  33. package/build/ossie/mapping.d.ts +26 -1
  34. package/build/ossie/mapping.js +45 -15
  35. package/build/ossie/metrics.d.ts +2 -0
  36. package/build/ossie/metrics.js +13 -10
  37. package/build/ossie/model.d.ts +39 -4
  38. package/build/ossie/model.js +56 -26
  39. package/build/ossie/names.d.ts +4 -0
  40. package/build/ossie/names.js +4 -0
  41. package/build/ossie/portability.d.ts +56 -0
  42. package/build/ossie/portability.js +109 -0
  43. package/build/ossie/profile.d.ts +157 -0
  44. package/build/ossie/profile.js +754 -0
  45. package/build/ossie/propose.d.ts +107 -0
  46. package/build/ossie/propose.js +454 -0
  47. package/build/ossie/types.d.ts +36 -7
  48. package/build/ossie/types.js +39 -1
  49. package/build/ranges.d.ts +20 -0
  50. package/build/ranges.js +51 -0
  51. package/build/readiness.d.ts +139 -0
  52. package/build/readiness.js +232 -0
  53. package/build/standard-data.json +1 -1
  54. package/build/standard-version.json +1 -1
  55. package/build/synthetic.d.ts +223 -0
  56. package/build/synthetic.js +1175 -0
  57. package/build/tools.d.ts +27 -1
  58. package/build/tools.js +10 -8
  59. package/build/types.d.ts +12 -0
  60. package/package.json +7 -3
package/README.md CHANGED
@@ -40,8 +40,17 @@ Restart your MCP client after adding the config.
40
40
  | `get_relationships` | One node of the relationship graph (metric, entity or concept) with its direct edges: upstream, measured by, downstream and measures. 21 relationship types across signal, lifecycle, ownership, interaction and financial flow categories. Metric names resolve as in `lookup_metric`, ambiguity included; a metric outside the graph says so. An entity also lists every metric whose formula reads its datasets (from `entityMappings`), with department and URL |
41
41
  | `get_data_requirements` | Data requirements for one metric, a department or every metric with a formula: per metric, each field and dataset pair with its type, the staged flag, source, grain, frequency, page URL and example SQL. The metric resolves exactly as in `lookup_metric`; `department` lists a department or picks between metrics sharing a name. Optional `breakdown` names a breakdown the metric declares (`by_plan` on MRR) and returns that breakdown's requirement: the dimension among the fields and example SQL with one row per value; an unknown name lists the declared ones. Optional `dialect` (`postgres` by default and for Redshift, `snowflake`, `bigquery`, `databricks`) writes the example SQL for that warehouse |
42
42
  | `search` | Whole-word phrase search across metrics (names, aliases, definitions, formulas, fields, categories, departments) and glossary terms (terms, definitions, sections); the last word may take a plural or verb ending. Up to 10 results, one per metric or term, ranked name, alias and term first, then words within them, then definitions, then formulas and fields, each with what matched and its gaspwiki.com URL. A query that matches nothing returns up to 6 close names as "Did you mean" |
43
- | `generate_query` | Compile warehouse SQL from the metric's canonical formula and an adapter. One scalar subquery per aggregate, each reading the table mapped for its dataset, with `:period_start` and `:period_end` date parameters (both inclusive). Unmapped pairs stay as `{{field@dataset}}` placeholders and are listed with any dataset lacking a table and any mapping conflict. Optional `breakdown` names a breakdown the metric declares (`by_plan` on MRR) and returns one row per value; an unknown name lists the declared ones. Optional `dialect` (`postgres`, `snowflake`, `bigquery`, `databricks`; `postgres` also covers Redshift) picks the SQL syntax for date arithmetic, casts and percentiles; without it the adapter's `warehouse` decides when it names one of them, else postgres. The output says which dialect it used |
44
- | `validate_adapter` | Validate a GASP adapter. Applies the bundled adapter JSON Schema (draft 2020-12, versions 1.0 and 1.1) first and lists each violation with its JSON path, then reports unknown fields and datasets, fields mapped to a dataset that does not carry them, bare column names on fields that live on several datasets, dataset table conflicts, enum fields mapped without a transform, covered metrics without an owner and owners naming unknown metrics. Scores every metric with a formula against the exact field and dataset pairs its compiled SQL reads (full, partial with the missing pairs or none) and ranks up to 15 unmapped pairs by how many partially covered metrics need them |
43
+ | `generate_query` | Compile warehouse SQL from the metric's canonical formula and a mapping (a GASP adapter, or an Ossie mapping with its `semantic_model`). One scalar subquery per aggregate, each reading the table mapped for its dataset, with `:period_start` and `:period_end` date parameters (both inclusive). Unmapped pairs stay as `{{field@dataset}}` placeholders and are listed with any dataset lacking a table and any mapping conflict. Optional `breakdown` names a breakdown the metric declares (`by_plan` on MRR) and returns one row per value; an unknown name lists the declared ones. Optional `dialect` (`postgres`, `snowflake`, `bigquery`, `databricks`; `postgres` also covers Redshift) picks the SQL syntax for date arithmetic, casts and percentiles; without it the adapter's `warehouse` decides when it names one of them, else postgres. The output says which dialect it used |
44
+ | `validate_mapping` | Validate a warehouse mapping in either format: a GASP adapter (JSON) or an Apache Ossie mapping document (YAML or JSON) over your semantic model, passed as `semantic_model`. A GASP adapter is converted on load into an Ossie mapping over a model synthesised from its tables and columns. Reports in layers: the schema (the adapter JSON Schema, and the bundled Ossie mapping schema for the Ossie form), GASP's cross-document checks against the GASP ontology and the model, then coverage: unknown fields and datasets, fields mapped to a dataset that does not carry them, table conflicts, every metric with a formula scored against the field and dataset pairs its compiled SQL reads (full, partial with the missing pairs or none), enum fields mapped without a transform, covered metrics without an owner, owners naming unknown metrics and up to 15 unmapped pairs ranked by how many partially covered metrics need them. `validate_adapter` is the same tool under its original name |
45
+ | `score_drift` | Score how far your own metrics drift from GASP's canonical definitions, by result. Takes your mapping (either format) and your `semantic_model` holding your metrics; each is matched to a GASP metric by exact name, by the synonyms in its `ai_context` or by a pair in `matches`, a name ending in -O or -M matching that declared form, with near names listed for review and never scored on a guess. The canonical metric is compiled into your names and both run on the GASP synthetic SaaS dataset for six monthly periods in an in-process Postgres (PGlite, an optional dependency). Differences come with both values per period and the likely cause read from the canonical formula: a null on one side (a sum over no rows is NULL in your SQL and 0 in GASP's), a cohort or opening value the expression cannot state, a filter one side applies, a dataset one side reads, an aggregate with no equal on the other side. Your values are checked against the standard's range for the metric per period, and where both forms of a dual-lens metric are matched the O/M bridge (the Durability Gap for ARR, the Activation Delta for CAC and the others the Core metrics name) is scored beside the canonical gap. `output: json` returns the data |
46
+ | `profile_schema` | Profile your warehouse schema into a minimal Ossie semantic model, the first step towards a mapping. Pass the rows of `information_schema.columns` (JSON or CSV), a tables list or `CREATE TABLE` statements, read through your own warehouse MCP or from a dump, and optionally statistics per column (`output: statistics` returns the query that gathers them). Every table gets a key, a time field and a kind (snapshot, event, fact or reference) with the evidence and a confidence, plus the relationships the columns imply; what the names cannot settle is a question for you rather than a guess. The model is returned as YAML to pass on as `semantic_model` |
47
+ | `propose_mapping` | Propose a GASP mapping from the model `profile_schema` returned (or your own Ossie model, or a schema profiled on the way in). Every table is scored against the GASP datasets on its columns, its profiled kind, key and time field and its name; every column of a proposed table against the dataset's fields by name, structural role, a short synonym list, word order and near names, checked against the type and the listed values. A column in cents gets a divide-by-100 transform and enum values the standard does not use a `CASE` recode when one is known. High-confidence pairs become an Ossie mapping over the model (a transform a calculated field) for `validate_mapping`; medium ones are candidates with their evidence and what would settle them; `output: adapter` gives the pairs as a GASP adapter |
48
+ | `derive_cel` | SQL that derives CEL `Revenue_Event` rows from your subscription ledger by the rules in `cel.md`: the subscription dataset your mapping covers (snapshots at any cadence or a version history) becomes one event per movement, with the customer's `prior_mrr` and `new_mrr` chained so the row identity holds, the event type read from the customer's MRR around the step, the ATL lifecycle tag and an empty `expansion_classification` the ledger cannot fill. Same mapping input as `generate_query`, plus the ledger's currency; dialect from the request or the warehouse; unmapped fields listed |
49
+ | `generate_checks` | SQL for the readiness checks the standard states, over the datasets your mapping covers: CEL row identity, MRR continuity, unique event ids, the ATL tags (lifecycle, expansion classification, cost function), customer identity both ways, freshness per dataset and, for every fully mapped metric with a hard range rule in the ontology (NRR at least 0, GRR at most 100%), its value in every reporting period of your period spine (`period_spine`, the table `compile_model` reads), one row per check. Paste the result rows back as `results` for pass or fail per check and per metric, each check naming the metrics it protects. Same mapping input as `generate_query`; dialect from the request or the warehouse |
50
+ | `plan_fixes` | The ranked fix list: every unmapped field and every failing check, ordered by Core metrics unlocked, then all metrics unlocked, with an effort class shown and used only as a tiebreak. A fix unlocks a metric when it is the last thing between that metric and covered-and-passing. Takes the mapping and the `results` from `generate_checks` |
51
+ | `readiness_report` | Which readiness level a company has reached and what stands between it and the next, read from the documents the other tools wrote: L1 Profiled (a semantic model exists), L2 Mapped (a metric fully covered, no open question or candidate), L3 Clean core (the CEL revenue events mapped, the checks run and every covered Core metric passing every check that protects it), L4 LLM-ready (the canonical metrics compiled into the model and none of your own metrics differing from its canonical counterpart). Takes the mapping, the `semantic_model` (with an adapter, the one `compile_model` returned) and the `results` from `generate_checks`; each blocker names the tool that clears it and the Next line is the one action to take
52
+ | `record_decision` | Record the decisions people make on the proposed mapping, each named by content with its owner and date: a profiler question answered (key, time field, kind, datatype) is written into the model; a candidate accepted or rejected into the mapping (an accepted table matched column by column, an accepted column with an optional transform as a calculated field); a metric owner into `metricOwners`; a judgement call GASP cannot apply (reporting currency, churn date) recorded. All land in the mapping's GASP extension; a later decision on a subject replaces the earlier one. With no decisions it lists the open questions, candidates and unowned metrics and whether readiness level 2 is reached |
53
+ | `compile_model` | Compile the GASP metrics your mapping covers into your Apache Ossie semantic model. Same input as `validate_mapping`; returns your model with a `gasp_` metric per covered formula entry (main formula, O and M forms, variants, named breakdowns): a direct `OSSIE_SQL_2026` expression over your datasets and fields where the language can state it, else staged through a `gasp_staged_` per-period dataset whose `source` is the compiled SQL over your tables in your warehouse `dialect`, reading the `period_spine` table you name. Entries with unmapped pairs are listed with the pairs they need; recompiling replaces the `gasp_` additions and leaves the rest. Optional `metrics` and `department` compile a subset; `output: report` returns the coverage without the document |
45
54
  | `infer_drivers` | Diagnose what could explain an observed metric movement: up to 25 upstream candidates ranked by attenuation score, each with its implied direction and path. Direction flips across `reduces` edges and negative-polarity inputs; a baseline input (MRR read at period start by NRR) is listed but not walked through. Metric nodes only; `maxDepth` 1 to 8 (default 6) |
46
55
  | `explain_path` | Up to 5 forward edge chains from one graph node to another, shortest first, with edge type, classification (metric_signal / structural / lifecycle / behavioral / assignment / generative), attenuation and direction flips per step and the target's end direction per path. A baseline edge can only start a path |
47
56
  | `coverage_gap` | Audit a metric set: metrics with a direct edge into or out of it that it leaves out, plus graph metrics with no path to or from it. Inputs that are ambiguous, outside the graph or not metrics are listed as unresolved with the reason |
@@ -50,7 +59,7 @@ The traversal tools (`infer_drivers`, `explain_path`, `coverage_gap`) return pat
50
59
 
51
60
  ## Data
52
61
 
53
- Version 1.16.0.
62
+ Version 1.17.0.
54
63
 
55
64
  - 306 metrics across 13 departments
56
65
  - 94 glossary definitions (81 SaaS domain + 13 GASP framework)
@@ -58,7 +67,7 @@ Version 1.16.0.
58
67
  - 21 relationship types: metric signal (drives, reduces, predicts, component, measures), entity lifecycle (converts_to, parent_of, belongs_to), entity ownership (owns, grants, priced_by), entity interactions (manages, serves, engages_via, submits, represented_by, sources), entity financial flows (generates, produces, contributes_to, incurs)
59
68
  - 279 data requirements, one per metric with a formula, compiled from the formula at load time: fields with types, datasets, grain and a compiled example query
60
69
  - 279 query templates, one per metric with a formula, compiled by the same step. None of the SQL is hand-written. Every field placeholder names the dataset it is read from (`{{customer_status@customer}}`), so `generate_query` resolves per-dataset adapter mappings by tag, inside cohort subqueries too. The grammar's `window(expr, n unit)` gives Daily, Weekly and Monthly Active Users (DAU, WAU, MAU) their 1, 7 and 30 day windows. `all_time(expr)` lets retention numerators read past the period end. A multi-argument `count_distinct` counts distinct tuples (Breadth of Adoption counts account and feature pairs). A formula with a `breakdown` field compiles to one row per value of that field, with `total(expr)` reading the whole population for shares of total (Ticket Distribution by Type, CAC by Channel)
61
- - The test suite executes every compiled template against a seeded fixture in an in-process Postgres (PGlite) and checks 25 metrics against independently computed values
70
+ - The test suite executes every compiled template against a seeded fixture in an in-process Postgres (PGlite) and checks selected metrics against independently computed values
62
71
  - Apache Ossie (incubating) export, written by `npm run derive` to `standard/exports/ossie/` and served at https://gaspwiki.com/downloads/ossie/: `gasp.ontology.yaml` (every dataset and GASP concept as an entity type, every field as a value type or relationship, enum values as constraints), `gasp.semantic_model.yaml` (every dataset with `OSSIE_SQL_2026` field expressions, the foreign-key relationships between them and every canonical formula as a metric, either a direct expression or staged through a per-period dataset that carries the compiled SQL; O/M forms and variants are separate metrics with the form in `custom_extensions`), `gasp.mapping.yaml` (the ontology mapped onto the model) and `coverage.json` (how each formula was exported and why). All three documents pass the upstream validator (vendored at `ossie-validator/`) and GASP's own cross-reference checks in `src/ossie/check.ts`, which cover references the upstream validator leaves alone
63
72
  - 28 business entities (Customer, Subscription, License, Lead, Opportunity, User, Ticket, Employee, Invoice, Partner, Project, Plan, Product, Campaign, Contact, Incident, Deployment, Release, Issue, Vulnerability, Feature, Requisition, Project Milestone, Deliverable, Quote, Order, Knowledge Article and Deal Registration). Every dataset with its own identity maps to an entity; ledger and period-level facts (cost events, financials, forecasts, web traffic) stay entity-free
64
73
  - 7 business concepts (Revenue, Bookings, COGS, Cohort, Pipeline, Segment and TCV)
@@ -69,7 +78,18 @@ Version 1.16.0.
69
78
  - CEL `change_nature` field for revenue quality analysis (Adjusted NRR/GRR) and `segment` on revenue, contract and amendment events, so MRR, retention and churn metrics break down by customer segment
70
79
  - Per-department cross-references (NRR under Customer Success, CAC under Marketing) resolve to the full canonical record, with its access classification, structured formula and entity mappings
71
80
  - Every metric and definition result carries its gaspwiki.com page URL; definitions keep their full body and reference links
81
+ - One mapping format: a company's warehouse mapping is an Apache Ossie mapping document over its semantic model, and the v1 adapter is accepted everywhere and converted on load (`src/ossie/adapt.ts`). The upstream Ossie schemas travel in the bundled data as `ossieSchemas`, so `validate_mapping` checks an Ossie mapping offline
82
+ - The schema profiler (`src/ossie/profile.ts`, behind `profile_schema`) turns a schema dump into a minimal Ossie semantic model with its evidence; the Acme DDL in `test/fixture/acme-schema.sql` is its fixture.
83
+ - The mapping proposer (`src/ossie/propose.ts`, behind `propose_mapping`) turns that model into a draft GASP mapping with the evidence per pair, transforms where the name or the values call for one and candidates for the pairs the evidence does not settle; on the Acme DDL it reproduces the Acme adapter.
84
+ - The CEL derivation (`src/cel.ts`, behind `derive_cel`) is the standard's rule for turning a subscription ledger into `Revenue_Event` rows, compiled over a company's mapping in its dialect. The test suite runs it over the synthetic dataset and gets every generated movement back, with monthly sums equal to the compiled MRR movement metrics.
85
+ - Two vendor worked examples beside Acme in `test/fixture/` (`stripe/`, Redshift; `salesforce/`, BigQuery): a DDL, a GASP mapping and a README stating the source documentation and every choice, written from public API documentation and never standard content. The Stripe example is taken from a validated mapping to readiness level 4 in the test suite and its drift report names a planted difference; the Salesforce example compiles in BigQuery and stops at level 2 because a CRM maps no revenue event
86
+ - The readiness checks and the fix plan (`src/checks.ts`, behind `generate_checks` and `plan_fixes`) compile the rules in `cel.md` and `atl.md`, and the ontology's value ranges per reporting period (`src/ranges.ts`), into SQL over a mapping and rank what to fix by the metrics it unlocks; the synthetic dataset passes every check and a table of planted violations fails the right ones.
87
+ - The readiness report (`src/readiness.ts`, behind `readiness_report`) reads the level a company has reached (L1 to L4 of the interop plan) from the mapping, the model and the pasted check rows, and names what blocks the next level; the test suite takes the synthetic dataset to L4.
88
+ - The Decide step (`src/ossie/decide.ts`, behind `record_decision`) applies the answers people give to the model and the mapping and keeps every decision, with its owner, in the mapping's GASP extension; it closes readiness level 2 when no question and no candidate is open.
89
+ - The drift scorer (`src/ossie/drift.ts`, behind `score_drift`) runs a company's metrics and the canonical ones side by side on the synthetic SaaS dataset (`src/synthetic.ts`, also the test fixture) in PGlite, loaded on first use from the optional dependency `@electric-sql/pglite`; without it the tool says so and runs nothing
90
+ - The metric compiler (`src/ossie/company.ts`, behind `compile_model`) writes every covered GASP metric into a company's own Ossie model, direct or staged, over their datasets, sources and field expressions. The test suite compiles the fixture adapter and checks every direct and staged value against the reference export on the fixture rows
72
91
  - Adapter schema 1.1 (`standard/gasp-adapter-schema.json`, JSON Schema draft 2020-12, served at https://gaspwiki.com/schemas/gasp-adapter-v1.json): a `datasets` map, per-dataset mappings (a mapping names its `dataset`), informational fields and `$schema`. The schema travels in the bundled data as `adapterSchema` and `validate_adapter` applies it with Ajv, so validation works offline. `npm run derive` writes a ready template to `standard/exports/gasp-adapter-template.json` (served at https://gaspwiki.com/downloads/gasp-adapter-template.json) and the tests validate it against the schema
92
+ - GASP Ossie extension schema 1 (`standard/gasp-ossie-extension-v1.json`, JSON Schema draft 2020-12, served at https://gaspwiki.com/schemas/gasp-ossie-extension-v1.json): the parsed `data` of every `custom_extensions` entry GASP writes under `vendor_name: GASP`, one definition per placement (model, dataset, metric, mapping), strict so each key GASP adds outside Ossie is listed. It travels in the bundled data as `extensionSchema` and the cross-document checks (`checkExport` in `src/ossie/check.ts`) validate every GASP payload against it in the export, `validate_mapping`, `compile_model`, `propose_mapping` and `record_decision`
73
93
  - Sources: the canonical [GASP Standard](https://gaspwiki.com) files
74
94
 
75
95
  ## Examples
package/build/cel.d.ts ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Deriving CEL Revenue_Events from a subscription ledger (standard/cel.md,
3
+ * "Deriving Revenue Events from a Subscription Ledger").
4
+ *
5
+ * Most billing systems hold subscriptions, not events: a row per subscription
6
+ * whose MRR and status change over time, kept as snapshots or as a version
7
+ * history. The CEL needs the movements between those states. The rules here
8
+ * turn the GASP `subscription` dataset into `revenue_event` rows and are the
9
+ * same for every source system; a vendor appears only in a mapping.
10
+ *
11
+ * 1. A subscription's MRR on a snapshot is its `mrr` when `subscription_status`
12
+ * is active, else 0. A customer's MRR is the sum over its subscriptions.
13
+ * 2. A step is a snapshot whose MRR differs from the subscription's previous
14
+ * snapshot (by snapshot_date). A subscription's first snapshot steps from 0.
15
+ * 3. Rows on the ledger's first snapshot date are opening balances: they seed
16
+ * the customer's MRR and produce no event (`firstSnapshot: "steps"` turns
17
+ * that off for a ledger that starts with the business). The ledger holds
18
+ * one row per subscription per snapshot date and keeps a cancelled
19
+ * subscription's row, since a subscription that stops appearing has no step.
20
+ * 4. One Revenue_Event per step, dated the snapshot that first shows the change.
21
+ * mrr_change is the subscription's change; prior_mrr and new_mrr are the
22
+ * customer's MRR before and after it, chained through the customer's steps
23
+ * in (snapshot_date, increases before decreases, subscription_id) order, so
24
+ * prior_mrr + mrr_change = new_mrr holds on every row and the rows of one
25
+ * date add up.
26
+ * 5. event_type from the customer's MRR at the start and end of the date: an
27
+ * increase from 0 is `new`, or `reactivation` when the customer was active
28
+ * on an earlier date; a decrease to 0 is `churn`; any other increase is
29
+ * `expansion` and any other decrease `contraction`. So a plan swap onto a
30
+ * new subscription id is an expansion and a contraction, two subscriptions
31
+ * cancelled on one date are two churns. `renewal` is not a movement and
32
+ * comes from Contract_Event or the renewal fields.
33
+ * 6. lifecycle_attribution follows the ATL rules for each type; change_nature
34
+ * is `permanent`; segment is the snapshot's; expansion_classification is
35
+ * NULL, because the ledger does not say what kind of expansion it was (the
36
+ * amendment does), and the readiness check for the ATL tag names the gap.
37
+ * 7. event_id is the subscription id and the snapshot date.
38
+ *
39
+ * The cadence of the ledger is the grain of the events: with daily snapshots
40
+ * every movement is seen on its day; with month-end snapshots the movements
41
+ * inside a month net to one event dated the month end, and a churn followed by
42
+ * a reactivation inside one interval leaves no event. Where amendment events
43
+ * exist they are the better source and the pairing rule in cel.md applies.
44
+ *
45
+ * The template uses the compiler's placeholders ({{field@dataset}},
46
+ * {{_table:dataset}}), so `fillTemplate` compiles it over any adapter or Ossie
47
+ * mapping that covers the six subscription fields it reads.
48
+ */
49
+ import { type DialectName } from "./dialect.js";
50
+ import type { QueryTemplate, StandardData } from "./types.js";
51
+ export declare const DERIVATION_DATASET = "subscription";
52
+ /** The subscription fields the derivation reads, in the order the ledger CTE selects them. */
53
+ export declare const DERIVATION_FIELDS: readonly ["subscription_id", "customer_id", "snapshot_date", "mrr", "subscription_status", "segment"];
54
+ /** The revenue_event fields the derivation writes, in column order. */
55
+ export declare const DERIVED_FIELDS: readonly ["event_id", "event_date", "customer_id", "subscription_id", "event_type", "mrr_change", "currency", "prior_mrr", "new_mrr", "expansion_classification", "change_nature", "lifecycle_attribution", "segment"];
56
+ export interface DerivationOptions {
57
+ dialect?: DialectName;
58
+ /** ISO 4217 code written on every event: the ledger's currency (the subscription dataset carries none). */
59
+ currency: string;
60
+ /**
61
+ * What the rows on the ledger's first snapshot date are: `opening` (the default) seeds each customer's
62
+ * MRR and produces no event, for a ledger that starts after the oldest subscription; `steps` treats them
63
+ * as steps from 0, for a ledger that starts with the business.
64
+ */
65
+ firstSnapshot?: "opening" | "steps";
66
+ }
67
+ /** The SQL that derives revenue events from the subscription ledger, with compiler placeholders. */
68
+ export declare function revenueEventDerivationSql(opts: DerivationOptions): string;
69
+ /** The derivation as a query template, so `fillTemplate` resolves it over an adapter or Ossie mapping like a metric's. */
70
+ export declare function revenueEventDerivation(opts: DerivationOptions): QueryTemplate;
71
+ /** The reference SQL over the GASP field names, as cel.md prints it. */
72
+ export declare function referenceDerivationSql(currency?: string): string;
73
+ export interface DeriveCelOptions {
74
+ dialect?: string;
75
+ currency?: string;
76
+ firstSnapshot?: "opening" | "steps";
77
+ output?: "report" | "sql";
78
+ }
79
+ /**
80
+ * The derive_cel tool: the derivation compiled over a company's mapping (a GASP
81
+ * adapter or an Ossie mapping with its model), in the dialect asked for or the
82
+ * one the adapter's warehouse names, as a report or the SQL alone.
83
+ */
84
+ export declare function deriveCelFromText(documentText: string | undefined, modelText: string | undefined, data: StandardData, opts?: DeriveCelOptions): string;
package/build/cel.js ADDED
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Deriving CEL Revenue_Events from a subscription ledger (standard/cel.md,
3
+ * "Deriving Revenue Events from a Subscription Ledger").
4
+ *
5
+ * Most billing systems hold subscriptions, not events: a row per subscription
6
+ * whose MRR and status change over time, kept as snapshots or as a version
7
+ * history. The CEL needs the movements between those states. The rules here
8
+ * turn the GASP `subscription` dataset into `revenue_event` rows and are the
9
+ * same for every source system; a vendor appears only in a mapping.
10
+ *
11
+ * 1. A subscription's MRR on a snapshot is its `mrr` when `subscription_status`
12
+ * is active, else 0. A customer's MRR is the sum over its subscriptions.
13
+ * 2. A step is a snapshot whose MRR differs from the subscription's previous
14
+ * snapshot (by snapshot_date). A subscription's first snapshot steps from 0.
15
+ * 3. Rows on the ledger's first snapshot date are opening balances: they seed
16
+ * the customer's MRR and produce no event (`firstSnapshot: "steps"` turns
17
+ * that off for a ledger that starts with the business). The ledger holds
18
+ * one row per subscription per snapshot date and keeps a cancelled
19
+ * subscription's row, since a subscription that stops appearing has no step.
20
+ * 4. One Revenue_Event per step, dated the snapshot that first shows the change.
21
+ * mrr_change is the subscription's change; prior_mrr and new_mrr are the
22
+ * customer's MRR before and after it, chained through the customer's steps
23
+ * in (snapshot_date, increases before decreases, subscription_id) order, so
24
+ * prior_mrr + mrr_change = new_mrr holds on every row and the rows of one
25
+ * date add up.
26
+ * 5. event_type from the customer's MRR at the start and end of the date: an
27
+ * increase from 0 is `new`, or `reactivation` when the customer was active
28
+ * on an earlier date; a decrease to 0 is `churn`; any other increase is
29
+ * `expansion` and any other decrease `contraction`. So a plan swap onto a
30
+ * new subscription id is an expansion and a contraction, two subscriptions
31
+ * cancelled on one date are two churns. `renewal` is not a movement and
32
+ * comes from Contract_Event or the renewal fields.
33
+ * 6. lifecycle_attribution follows the ATL rules for each type; change_nature
34
+ * is `permanent`; segment is the snapshot's; expansion_classification is
35
+ * NULL, because the ledger does not say what kind of expansion it was (the
36
+ * amendment does), and the readiness check for the ATL tag names the gap.
37
+ * 7. event_id is the subscription id and the snapshot date.
38
+ *
39
+ * The cadence of the ledger is the grain of the events: with daily snapshots
40
+ * every movement is seen on its day; with month-end snapshots the movements
41
+ * inside a month net to one event dated the month end, and a churn followed by
42
+ * a reactivation inside one interval leaves no event. Where amendment events
43
+ * exist they are the better source and the pairing rule in cel.md applies.
44
+ *
45
+ * The template uses the compiler's placeholders ({{field@dataset}},
46
+ * {{_table:dataset}}), so `fillTemplate` compiles it over any adapter or Ossie
47
+ * mapping that covers the six subscription fields it reads.
48
+ */
49
+ import { DIALECT } from "./dialect.js";
50
+ import { exampleSql } from "./compile.js";
51
+ import { chooseDialect, fillTemplate } from "./tools.js";
52
+ import { loadAdapter } from "./ossie/adapt.js";
53
+ import { resolveDocLink } from "./urls.js";
54
+ export const DERIVATION_DATASET = "subscription";
55
+ /** The subscription fields the derivation reads, in the order the ledger CTE selects them. */
56
+ export const DERIVATION_FIELDS = ["subscription_id", "customer_id", "snapshot_date", "mrr", "subscription_status", "segment"];
57
+ /** The revenue_event fields the derivation writes, in column order. */
58
+ export const DERIVED_FIELDS = ["event_id", "event_date", "customer_id", "subscription_id", "event_type", "mrr_change", "currency", "prior_mrr", "new_mrr", "expansion_classification", "change_nature", "lifecycle_attribution", "segment"];
59
+ const ph = (field) => `{{${field}@${DERIVATION_DATASET}}}`;
60
+ /** MRR is kept to the cent, so a chained total within half a cent of zero is zero (the sums are floats on some warehouses). */
61
+ const ZERO = "0.005";
62
+ /** The SQL that derives revenue events from the subscription ledger, with compiler placeholders. */
63
+ export function revenueEventDerivationSql(opts) {
64
+ const d = DIALECT[opts.dialect ?? "postgres"];
65
+ if (!/^[A-Z]{3}$/.test(opts.currency))
66
+ throw new Error(`currency must be an ISO 4217 code, got ${JSON.stringify(opts.currency)}`);
67
+ const opening = opts.firstSnapshot === "steps" ? "0" : "CASE WHEN snapshot_date = MIN(snapshot_date) OVER () THEN 1 ELSE 0 END";
68
+ // Within a date a customer's increases come before its decreases, then subscription id, so the chained MRR is deterministic.
69
+ const chain = "PARTITION BY c.customer_id ORDER BY c.snapshot_date, CASE WHEN c.mrr_change > 0 THEN 0 ELSE 1 END, c.subscription_id";
70
+ return `WITH ledger AS (
71
+ SELECT ${ph("subscription_id")} AS subscription_id,
72
+ ${ph("customer_id")} AS customer_id,
73
+ ${ph("snapshot_date")} AS snapshot_date,
74
+ ${ph("segment")} AS segment,
75
+ CASE WHEN ${ph("subscription_status")} = 'active' THEN ROUND(COALESCE(${ph("mrr")}, 0), 2) ELSE 0 END AS mrr
76
+ FROM {{_table:${DERIVATION_DATASET}}}
77
+ WHERE ${ph("snapshot_date")} IS NOT NULL
78
+ ),
79
+ steps AS (
80
+ SELECT subscription_id, customer_id, snapshot_date, segment, mrr,
81
+ COALESCE(LAG(mrr) OVER (PARTITION BY subscription_id ORDER BY snapshot_date), 0) AS prior_sub_mrr,
82
+ ${opening} AS opening
83
+ FROM ledger
84
+ ),
85
+ changes AS (
86
+ SELECT subscription_id, customer_id, snapshot_date, segment, opening,
87
+ mrr - prior_sub_mrr AS mrr_change
88
+ FROM steps
89
+ WHERE mrr <> prior_sub_mrr
90
+ ),
91
+ day_changes AS (
92
+ SELECT customer_id, snapshot_date, SUM(mrr_change) AS day_change
93
+ FROM changes
94
+ GROUP BY customer_id, snapshot_date
95
+ ),
96
+ days AS (
97
+ SELECT customer_id, snapshot_date, day_change,
98
+ SUM(day_change) OVER (PARTITION BY customer_id ORDER BY snapshot_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS day_end
99
+ FROM day_changes
100
+ ),
101
+ day_state AS (
102
+ SELECT customer_id, snapshot_date, day_end - day_change AS day_start, day_end,
103
+ COALESCE(MAX(CASE WHEN day_end > ${ZERO} THEN 1 ELSE 0 END) OVER (PARTITION BY customer_id ORDER BY snapshot_date ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS active_before
104
+ FROM days
105
+ ),
106
+ chained AS (
107
+ SELECT c.subscription_id, c.customer_id, c.snapshot_date, c.segment, c.opening, c.mrr_change,
108
+ COALESCE(SUM(c.mrr_change) OVER (${chain} ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS prior_mrr,
109
+ SUM(c.mrr_change) OVER (${chain} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS new_mrr,
110
+ s.day_start, s.day_end, s.active_before
111
+ FROM changes c
112
+ JOIN day_state s ON s.customer_id = c.customer_id AND s.snapshot_date = c.snapshot_date
113
+ ),
114
+ typed AS (
115
+ SELECT subscription_id, customer_id, snapshot_date, segment, opening, mrr_change, prior_mrr, new_mrr,
116
+ CASE
117
+ WHEN mrr_change > 0 AND ABS(day_start) < ${ZERO} AND active_before = 1 THEN 'reactivation'
118
+ WHEN mrr_change > 0 AND ABS(day_start) < ${ZERO} THEN 'new'
119
+ WHEN mrr_change < 0 AND ABS(day_end) < ${ZERO} THEN 'churn'
120
+ WHEN mrr_change > 0 THEN 'expansion'
121
+ ELSE 'contraction'
122
+ END AS event_type
123
+ FROM chained
124
+ )
125
+ SELECT ${d.toText("subscription_id")} || ':' || ${d.toText("snapshot_date")} AS event_id,
126
+ snapshot_date AS event_date,
127
+ customer_id,
128
+ subscription_id,
129
+ event_type,
130
+ mrr_change,
131
+ '${opts.currency}' AS currency,
132
+ prior_mrr,
133
+ new_mrr,
134
+ ${d.toText("NULL")} AS expansion_classification,
135
+ 'permanent' AS change_nature,
136
+ CASE event_type
137
+ WHEN 'new' THEN 'acquisition'
138
+ WHEN 'expansion' THEN 'expansion'
139
+ WHEN 'reactivation' THEN 'reactivation'
140
+ ELSE 'retention'
141
+ END AS lifecycle_attribution,
142
+ segment
143
+ FROM typed
144
+ WHERE opening = 0
145
+ ORDER BY snapshot_date, customer_id, CASE WHEN mrr_change > 0 THEN 0 ELSE 1 END, subscription_id`;
146
+ }
147
+ /** The derivation as a query template, so `fillTemplate` resolves it over an adapter or Ossie mapping like a metric's. */
148
+ export function revenueEventDerivation(opts) {
149
+ return {
150
+ metric: "cel_revenue_events",
151
+ fields: [...DERIVATION_FIELDS],
152
+ datasets: [DERIVATION_DATASET],
153
+ sourceTable: DERIVATION_DATASET,
154
+ grain: "event",
155
+ frequency: "as the ledger is snapshotted",
156
+ source: "subscription ledger",
157
+ parameterizedQuery: revenueEventDerivationSql(opts),
158
+ staged: false,
159
+ placeholders: DERIVATION_FIELDS.map((f) => `${f}@${DERIVATION_DATASET}`),
160
+ };
161
+ }
162
+ /** The reference SQL over the GASP field names, as cel.md prints it. */
163
+ export function referenceDerivationSql(currency = "USD") {
164
+ return exampleSql(revenueEventDerivationSql({ dialect: "postgres", currency }));
165
+ }
166
+ /**
167
+ * The derive_cel tool: the derivation compiled over a company's mapping (a GASP
168
+ * adapter or an Ossie mapping with its model), in the dialect asked for or the
169
+ * one the adapter's warehouse names, as a report or the SQL alone.
170
+ */
171
+ export function deriveCelFromText(documentText, modelText, data, opts = {}) {
172
+ if (!documentText?.trim())
173
+ return "Pass adapter: your mapping as text, a GASP adapter (JSON) or an Ossie mapping document (YAML or JSON) with its semantic_model. Check it with validate_mapping first.";
174
+ const currency = opts.currency?.trim().toUpperCase();
175
+ if (!currency)
176
+ return "Pass currency: the ISO 4217 code of the ledger's currency (USD, EUR, GBP ...). Every derived event carries it; the subscription dataset has no currency field to read it from.";
177
+ if (!/^[A-Z]{3}$/.test(currency))
178
+ return `currency must be a three-letter ISO 4217 code, got ${JSON.stringify(opts.currency)}.`;
179
+ const loaded = loadAdapter(documentText, modelText, data);
180
+ if (!loaded.adapter)
181
+ return loaded.error;
182
+ const chosen = chooseDialect(opts.dialect, loaded.adapter.warehouse);
183
+ if ("error" in chosen)
184
+ return chosen.error;
185
+ const template = revenueEventDerivation({ dialect: chosen.dialect, currency, firstSnapshot: opts.firstSnapshot });
186
+ const r = fillTemplate(template, loaded.adapter, data);
187
+ if (opts.output === "sql")
188
+ return r.sql;
189
+ const p = [
190
+ "# CEL Revenue_Events derived from your subscription ledger",
191
+ `**Rules:** ${resolveDocLink("cel.md#deriving-revenue-events-from-a-subscription-ledger")}`,
192
+ `**Mapping:** ${loaded.format === "v1" ? "GASP adapter" : "Ossie mapping"}${loaded.adapter.organization ? ` (${loaded.adapter.organization})` : ""}`,
193
+ `**Warehouse:** ${loaded.adapter.warehouse || "not specified"}`,
194
+ `**Dialect:** ${chosen.note}`,
195
+ `**Reads:** the \`${DERIVATION_DATASET}\` dataset, ${r.mapped.length} / ${template.placeholders.length} fields mapped`,
196
+ `**Writes:** one \`revenue_event\` row per movement (${DERIVED_FIELDS.join(", ")}), currency \`${currency}\``,
197
+ ];
198
+ if (r.missingFields.length)
199
+ p.push(`**Unmapped fields (left as placeholders):** \`${r.missingFields.join("\`, \`")}\`. Map each on the \`${DERIVATION_DATASET}\` dataset and run again.`);
200
+ if (r.missingTables.length)
201
+ p.push(`**Dataset with no table:** ${r.missingTables.join(", ")}. Name its table under "datasets" in the adapter, or map one of its fields with a schema.table column reference.`);
202
+ for (const c of r.conflicts)
203
+ p.push(`**Conflict:** ${c}`);
204
+ p.push("", `**What the ledger can and cannot say.** Each movement is dated the snapshot that first shows it, so the ledger's cadence is the grain of the events: daily snapshots show every movement on its day, month-end snapshots net a month's movements into one event dated the month end. ${opts.firstSnapshot === "steps" ? "Every first row is a step from 0 (first_snapshot: steps), so the ledger must start with the business." : "Rows on the ledger's first snapshot date are opening balances and produce no event; a customer that churned before the ledger starts comes back as new, not reactivation. Pass first_snapshot: steps if the ledger starts with the business."} The ledger needs one row per subscription per snapshot date and must keep a cancelled subscription's row; a subscription that stops appearing produces no churn. A null MRR on an active row counts as 0. \`expansion_classification\` is empty: the ledger shows that MRR rose, not what was bought, and the Operating forms of ARR and NRR read that tag; fill it from your amendment records or record the classification as a decision. Renewals change no MRR and are not derived here.`, "", `Run the query to build (or rebuild) the \`revenue_event\` table; it reads the whole ledger and carries no period parameters. Map the result as the \`revenue_event\` dataset and the MRR movement metrics, NRR and GRR compile over it with generate_query or compile_model.`, "", "```sql\n" + r.sql + "\n```");
205
+ if (r.mapped.length) {
206
+ p.push("", "**Field mapping used:**");
207
+ for (const m of r.mapped)
208
+ p.push(`- \`${m.field}\` (${m.dataset}) → \`${m.ref}\`${m.transform ? ` (transform: ${m.transform})` : ""}`);
209
+ }
210
+ return p.join("\n");
211
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Readiness checks and the fix plan (docs/ossie-interop-spec.md, readiness
3
+ * level 3: Check and Plan), behind the generate_checks and plan_fixes tools.
4
+ *
5
+ * A check is a rule the standard already states (cel.md, atl.md), written as
6
+ * SQL that counts the rows breaking it over the GASP datasets a mapping covers.
7
+ * GASP has no warehouse access: generate_checks writes the SQL in the
8
+ * warehouse's dialect with the compiler's placeholders, the company runs it and
9
+ * pastes the result rows (check_id, violations) back, and the tool reports pass
10
+ * or fail per check and per metric. A check protects the metrics whose compiled
11
+ * formulas read the field or dataset it covers, so a failing check names the
12
+ * numbers it puts in doubt.
13
+ *
14
+ * The checks (decided 2026-11-03, DECISIONS.md):
15
+ * revenue_event_identity prior_mrr + mrr_change = new_mrr on every revenue event (cel.md)
16
+ * mrr_continuity a subscription's mrr_start equals its mrr on the previous snapshot
17
+ * unique_event_id:<dataset> event_id unique within each event dataset that carries one
18
+ * lifecycle_tag:<dataset> one lifecycle_attribution, from the ATL enum, on every event (ATL rule 1)
19
+ * expansion_tag:<dataset> expansion_classification on expansion, contraction and reactivation
20
+ * revenue events and on every amendment (ATL rule 2)
21
+ * cost_function_tag cost_function, from the enum, on every cost event (ATL rule 3)
22
+ * customer_identity:events every revenue event's customer_id is a known customer
23
+ * customer_identity:customers every customer active on the latest snapshot has a revenue event
24
+ * freshness:<dataset> the latest date in each mapped dataset is within the sync window
25
+ * range:<formulaId> the metric's value stays inside the ontology's hard min and max
26
+ * (validationRules) in every reporting period of the period spine
27
+ *
28
+ * A range check evaluates the metric's compiled template once per row of the
29
+ * company's period spine (the table compile_model reads, gasp.period_spine by
30
+ * default) and counts the periods outside the bounds; a NULL value is not a
31
+ * violation. The bounds come from src/ranges.ts, which scales a percent rule on
32
+ * a percent formula by 100 (GRR at most 1) and takes any other rule as given;
33
+ * the drift scorer reads the same bounds. A range check is kept only when the
34
+ * mapping covers its metric fully.
35
+ *
36
+ * Left out on purpose: the O/M bridges. They reconcile by construction when
37
+ * both forms come from the GASP formulas, so they live in the drift scorer,
38
+ * where a company's own O and M numbers arrive.
39
+ *
40
+ * plan_fixes ranks every fix a mapping and a set of results call for: map an
41
+ * unmapped field, or clear a failing check. Core metrics unlocked first, then
42
+ * all metrics unlocked; the effort class is shown and breaks ties, never
43
+ * multiplied into the order.
44
+ */
45
+ import { type DialectName } from "./dialect.js";
46
+ import { type Adapter } from "./tools.js";
47
+ import type { DataRequirement, QueryTemplate, StandardData } from "./types.js";
48
+ export type Effort = "small" | "medium" | "large";
49
+ export interface ReadinessCheck {
50
+ id: string;
51
+ name: string;
52
+ /** The rule, in one sentence. */
53
+ rule: string;
54
+ /** Where the standard states it: a doc link resolveDocLink accepts. */
55
+ source: string;
56
+ /** The datasets the check reads. */
57
+ datasets: string[];
58
+ /** The field@dataset pairs the SQL reads; the mapping must cover them all. */
59
+ placeholders: string[];
60
+ /** What the check protects: the metrics reading this field, or any field of this dataset, or one metric (a range check). */
61
+ protects: {
62
+ dataset: string;
63
+ field?: string;
64
+ } | {
65
+ metric: string;
66
+ };
67
+ effort: Effort;
68
+ /** The SQL, with placeholders, returning one row: violations. */
69
+ sql: (d: DialectName) => string;
70
+ }
71
+ /** Options every check function takes: the freshness window and date, and the company's period spine for the range checks. */
72
+ export interface CheckOptions {
73
+ window?: number;
74
+ asOf?: string;
75
+ /** The period table (period_start, period_end) the range checks read; compile_model reads the same one. Default gasp.period_spine. */
76
+ spine?: string;
77
+ }
78
+ /** The checks the standard's data admits, from the ontology: event datasets carrying event_id, the tag fields, every dated dataset for freshness and the hard value ranges. */
79
+ export declare function readinessChecks(data: StandardData, opts?: CheckOptions): ReadinessCheck[];
80
+ /** The metrics (data requirements) a check protects: those whose compiled formula, or one of its O and M forms, reads the field, or any field of the dataset; a range check protects its own metric (its O and M forms are the same requirement). */
81
+ export declare function protectedBy(check: ReadinessCheck, data: StandardData): DataRequirement[];
82
+ /** A check as a query template, so fillTemplate compiles it over a mapping like a metric. */
83
+ export declare function checkTemplate(check: ReadinessCheck, dialect: DialectName): QueryTemplate;
84
+ export interface CompiledCheck {
85
+ check: ReadinessCheck;
86
+ /** The SQL over the mapping; undefined when the mapping lacks a field or table it needs. */
87
+ sql?: string;
88
+ missing: string[];
89
+ protects: DataRequirement[];
90
+ }
91
+ /** Every check compiled over a mapping: the runnable ones with their SQL, the rest with what they lack. */
92
+ export declare function compileChecks(adapter: Adapter, data: StandardData, dialect: DialectName, opts?: CheckOptions): CompiledCheck[];
93
+ /** The runnable checks as one statement: one row per check (check_id, violations). */
94
+ export declare function checksAsOneQuery(compiled: CompiledCheck[]): string;
95
+ export type CheckResult = {
96
+ check_id: string;
97
+ violations: number;
98
+ };
99
+ /** Result rows pasted back: JSON (an array of objects or of [id, n] pairs, or an object keyed by check id) or CSV with a header or two columns. */
100
+ export declare function parseResults(text: string): {
101
+ results?: CheckResult[];
102
+ error?: string;
103
+ };
104
+ export type CheckStatus = "pass" | "fail" | "not run" | "cannot run";
105
+ export interface CheckReport {
106
+ dialect: string;
107
+ checks: Array<{
108
+ id: string;
109
+ name: string;
110
+ rule: string;
111
+ status: CheckStatus;
112
+ violations?: number;
113
+ missing: string[];
114
+ protects: string[];
115
+ effort: Effort;
116
+ }>;
117
+ /** Per metric that at least one runnable check protects: pass when every check protecting it passed. */
118
+ metrics: Array<{
119
+ metric: string;
120
+ department: string;
121
+ status: "pass" | "fail" | "not run";
122
+ failing: string[];
123
+ }>;
124
+ sql: string;
125
+ unknownResults: string[];
126
+ /** The period spine the range checks read, when any range check is in the report. */
127
+ spine?: string;
128
+ }
129
+ /** The checks compiled, with results applied when given. */
130
+ export declare function checkReport(compiled: CompiledCheck[], dialect: string, results?: CheckResult[], spine?: string): CheckReport;
131
+ export declare function formatCheckReport(r: CheckReport, opts: {
132
+ withSql: boolean;
133
+ }): string;
134
+ export interface GenerateChecksOptions {
135
+ dialect?: string;
136
+ window?: number;
137
+ asOf?: string;
138
+ /** The period table the range checks read (default gasp.period_spine). */
139
+ spine?: string;
140
+ results?: string;
141
+ output?: "report" | "sql" | "json";
142
+ }
143
+ /** The generate_checks tool. */
144
+ export declare function generateChecksFromText(documentText: string | undefined, modelText: string | undefined, data: StandardData, opts?: GenerateChecksOptions): string;
145
+ export interface Fix {
146
+ kind: "map" | "check";
147
+ /** The field@dataset pair to map, or the check id to clear. */
148
+ what: string;
149
+ effort: Effort;
150
+ /** Metrics this fix brings to covered and passing, Core first. */
151
+ unlocks: Array<{
152
+ metric: string;
153
+ department: string;
154
+ }>;
155
+ core: number;
156
+ /** Metrics the fix helps but which still wait on something else. */
157
+ alsoHelps: number;
158
+ why: string;
159
+ }
160
+ /**
161
+ * Every fix the mapping and the results call for, ranked: Core metrics unlocked, then all metrics
162
+ * unlocked, then metrics helped, then effort (smaller first), then name. A fix unlocks a metric
163
+ * when it is the only thing between that metric and covered-and-passing.
164
+ */
165
+ export declare function planFixes(adapter: Adapter, data: StandardData, dialect: DialectName, results: CheckResult[] | undefined, opts?: CheckOptions): Fix[];
166
+ export declare function formatFixPlan(fixes: Fix[], haveResults: boolean, limit: number): string;
167
+ export interface PlanFixesOptions extends GenerateChecksOptions {
168
+ limit?: number;
169
+ }
170
+ /** The plan_fixes tool. */
171
+ export declare function planFixesFromText(documentText: string | undefined, modelText: string | undefined, data: StandardData, opts?: PlanFixesOptions): string;
172
+ /** A check's SQL over the GASP field names, for documentation. */
173
+ export declare const referenceCheckSql: (check: ReadinessCheck, dialect?: DialectName) => string;