> ## Documentation Index
> Fetch the complete documentation index at: https://xerg.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Economic ledger API

> Read latest-measurement outcomes or calendar-period spend, waste, and verified savings across active sources.

The Economic Ledger has two authenticated read contracts:

* `GET /v1/economic-ledger` returns the latest eligible measurement for every active source, including outcome economics and the existing seven-day snapshot comparison.
* `GET /v1/economic-ledger/period?from=YYYY-MM-DD&to=YYYY-MM-DD` returns the outcome-free calendar-period basis used by Overview: runtime spend, identified waste, verified savings, daily series, coverage, and active-source rows.

The legacy latest-measurement route is unchanged.

Hermes accounting-method corrections may explain measurement or period deltas;
those deltas are not qualified savings. The corrected comparison policy blocks
incompatible old/new baselines without changing source identity. Latest-source/day
selection and highwater metering retain their existing behavior: a lower corrected
measurement does not add another source, reset highwater, or imply a refund.

```bash theme={null}
curl --request GET \
  --url https://api.xerg.ai/v1/economic-ledger \
  --header "Authorization: Bearer $XERG_API_KEY"
```

The route requires workspace authentication and reuses the existing `auditHistory` authorization; it adds no new or paid capability gate. Free workspaces include that capability and receive the latest active audit per source from their entitled 30-day history. Older snapshots are not considered when selecting that latest audit. Paid workspaces receive their full-history view. The same over-member-limit workspace lock that protects other audit-history reads also applies.

## Latest measurement response

Representative response shape (values are illustrative):

```json theme={null}
{
  "generatedAt": "2026-08-25T20:00:00.000Z",
  "currency": "USD",
  "totals": {
    "sourceCount": 3,
    "spendUsd": 24000,
    "identifiedWasteUsd": 4800,
    "structuralWasteRate": 0.2
  },
  "outcomes": {
    "sourceCount": 3,
    "trackedSourceCount": 3,
    "trackedSpendUsd": 24000,
    "successRuns": 200,
    "failureRuns": 40,
    "partialRuns": 0,
    "unknownRuns": 0,
    "untrackedRuns": 0,
    "trackedRuns": 240,
    "costPerSuccessfulRunUsd": 120,
    "successRate": 0.833333
  },
  "verifiedSavings": {
    "amountUsd": 1200,
    "validationWindowDays": 7,
    "comparisonCount": 2,
    "sourceCount": 2,
    "validatedOptimizationCount": 2,
    "latestValidatedAt": "2026-08-20T12:00:00.000Z",
    "unavailableReason": null
  },
  "comparison": {
    "days": 7,
    "currentCutoff": "2026-08-25T20:00:00.000Z",
    "priorCutoff": "2026-08-18T20:00:00.000Z",
    "sourceCounts": {
      "current": 3,
      "prior": 3,
      "intersection": 3,
      "changed": 0
    },
    "compositionDisclosure": null,
    "spend": {
      "current": 24000,
      "prior": 25200,
      "delta": -1200,
      "deltaRate": -0.047619
    },
    "waste": {
      "current": 4800,
      "prior": 6000,
      "delta": -1200,
      "deltaRate": -0.2
    },
    "wasteUnavailableReason": null,
    "outcomes": {
      "comparableSourceCount": 3,
      "costPerSuccessfulRun": {
        "current": 120,
        "prior": 128.57,
        "delta": -8.57,
        "deltaRate": -0.066656
      },
      "successRate": {
        "current": 0.833333,
        "prior": 0.816667,
        "delta": 0.016666,
        "deltaRate": 0.020407
      }
    }
  },
  "sources": []
}
```

Each `sources` row contains:

* hosted source ID, source key, and display name
* current department (`{ id, name }`) or `null` for Unassigned
* current `runtimePosture` as `vpc`, `on-prem`, `saas`, `local`, `hybrid`, `air-gap`, or `null` for Not set
* hosted audit ID and wire audit ID
* source host, environment, push timestamp, and data start/end dates
* spend, identified waste, structural waste rate, and run count
* detection coverage, pricing coverage, source stability, and the detector-coverage signature
* a nullable outcome rollup

Outcome coverage is explicit. A source without outcome data stays in the ledger and contributes to total spend and waste, but it is excluded from outcome-tracked spend, successful-run cost, and success-rate denominators. It is never treated as zero outcomes.

The aggregate known cost per successful run is `outcome-tracked source spend / successful runs`. The aggregate success rate is `successful runs / tracked runs`, where tracked runs include success, failure, partial, and unknown outcomes.

## Seven-day comparison

The API selects the deterministic latest eligible snapshot per source at `generatedAt` and exactly seven days earlier. It reconstructs active eligibility from source and audit archive timestamps, then computes deltas only over the intersection of source IDs present at both cutoffs.

`sourceCounts.changed` and `compositionDisclosure` identify sources added or removed during the period. Spend deltas remain neutral. Identified-waste deltas are omitted when either side has partial or unavailable assessment, incomplete pricing, unstable source evidence, or incompatible detector coverage; `wasteUnavailableReason` gives the bounded reason. This prevents lower bounds from being differenced as exact values.

Outcome comparisons include only sources with tracked outcomes at both cutoffs. Cost per successful run additionally requires at least one successful run in both periods. With no prior snapshot for any current source, all deltas are unavailable.

## Verified savings

`verifiedSavings` is separate from the ordinary seven-day KPI comparison. It includes only modeled Optimizations whose status is Validated, whose selected same-source before and after audits each cover exactly seven days, and whose stored evidence supports a causal realized-savings claim. Both periods must be inside the workspace's entitled audit-history window and have complete pricing, full monetary-detector coverage, stable source reads, tracked outcomes, and non-declining successful runs. The current comparison must resolve the Optimization's same detector-versioned high-confidence finding and total runtime spend must decrease.

Validated Optimizations are grouped by source and comparison pair. Finding identities are deduplicated, and each pair contributes at most the smaller of matched resolved-waste reduction and `baseline runtime spend - after runtime spend`. Regressed, archived, partial, unpriced, unstable, outcome-degraded, incompatible, or non-seven-day comparisons contribute nothing.

When no modeled Optimization is Validated, `amountUsd` is `null` with `unavailableReason: "no_validated_optimizations"`. When validations exist but none has an eligible exact comparison, the reason is `"no_exact_comparison"`. Consumers must not render either state as `$0 saved`.

Verified-savings calculations continue to use existing stored audit summaries and Optimization lifecycle records. Runtime posture is separate current source metadata backed by forward-only migration `0034`; the migration adds a nullable constrained column to the workspace source registry and does not backfill existing sources. Current Push v7 can add optional workflow waste and finding-change detail without changing the wire version; earlier Push v7, v6, and stored history remain readable, and pushes never assign or overwrite posture.

The posture on each Economic Ledger source row is the workspace's current admin-assigned value, not a historical measurement fact. Xerg never infers it from framework, brand, host, collection environment, or audit evidence. The authenticated `GET /v1/sources/runtime-postures` route returns zero-filled active and all-source counts for the six fixed values plus Not set directly from the workspace source registry, independently of audit-history eligibility.

## Calendar-period ledger

Use the additive period route when the question is about a calendar range rather than each source's latest measurement:

```bash theme={null}
curl --request GET \
  --url 'https://api.xerg.ai/v1/economic-ledger/period?from=2026-08-01&to=2026-08-07' \
  --header "Authorization: Bearer $XERG_API_KEY"
```

`from` and `to` are required, inclusive UTC dates. The immediately preceding range with the same number of dates is the comparison period. A range that includes the current UTC date is marked in progress and its deltas are suppressed, because a partial day is not comparable with completed days. The maximum is 30 days for a workspace with the ordinary Free history limit and 90 days for a full-history workspace. Invalid, reversed, future, over-limit, or history-ineligible ranges are rejected rather than silently narrowed.

The route starts with every current active runtime source. For each source and activity date, it selects the latest eligible `audit_daily_coverage` row by measurement push time and stored row ID. This coverage-window basis prevents overlapping rolling audits from being added together. It also means a source can remain in `sources` with `periodMeasurement: null` and **No data in period** instead of disappearing or contributing a fabricated zero.

The period contract contains only these metrics:

* `knownSpend`: the sum of priced daily evidence
* `identifiedWaste`: the sum of supported daily waste evidence, with `wasteRate` recomputed from aggregate waste and runtime spend
* `verifiedSavings`: qualified immutable validation facts whose `validationDate` falls inside the selected range

It contains no run-outcome fields, success rate, or cost per successful run. Those remain available from the legacy latest-measurement route and the existing Measurement and Compare views.

Every metric and series point has a `status` of `exact`, `lower_bound`, or `unavailable`. Coverage separately reports active and measured sources, measured and missing source-days, partial source-days, and priced versus unpriced calls. Positive identified waste can be a proven lower bound; a partial or unavailable zero is never presented as a conclusive finding. Missing dates have a `null` value so charts render a gap rather than zero.

Each eligible delta contains the current and prior amounts, the absolute change, and a nullable relative rate. Relative change is `null` when the prior amount is zero. Runtime-spend deltas (the `knownSpend` response field) use only aligned source-days from both periods, expose the excluded source-day count, and are suppressed if pricing is incomplete on either side. Identified-waste deltas additionally require complete period coverage, full detector assessment, stable sources, and compatible detector evidence on both sides; a lower bound is never differenced as though it were exact. No prior measurements or an in-progress current day produces a bounded `deltaUnavailableReason` instead of an invalid difference.

### Immutable validation facts

Verified savings in a period is prospective. Migration 0035 establishes a workspace-independent availability timestamp and does not backfill mutable historical Optimization state. Each action that validates or revalidates an Optimization atomically records the evidence as either qualified or unqualified. The fact freezes the validation date, source, before/after measurement identities, finding identity, bounded evidence result, and any qualified amount.

Submitting the same evidence again is idempotent. Revalidating with changed evidence creates a new fact. Regressing or archiving the Optimization later does not rewrite the fact that was observed at validation time. Soft-archiving a retained before or after measurement also does not erase its stored evidence: an accepted validation can still freeze it when the measurement remains inside the workspace's history entitlement and satisfies the same tenant, source, runtime-kind, and comparison checks.

Only positive qualified facts recorded at or after the advertised availability timestamp contribute to `verifiedSavings.valueUsd`; unqualified facts remain evidence for why no exact amount was claimed. When a selected period or UTC day crosses that exact timestamp, post-epoch qualified savings remain visible as `lower_bound`, the KPI shows `≥`, earlier dates remain unavailable, and the period delta is suppressed. Fully post-epoch dates retain exact, no-validation, and no-exact-evidence states. A savings delta compares only sources with reportable qualified facts in both periods and reports current, prior, intersection, and excluded source counts plus a disclosure when the cohorts differ. `factHistoryAvailableFrom`, validation counts, qualification counts, and bounded unavailable reasons let clients distinguish partial or unavailable pre-ledger history from a fully covered period with no validations or no exact evidence.

Qualification retains the existing strict standard: same-source before/after measurements with declared exact seven-day windows, complete pricing and monetary-detector coverage, stable evidence, a matching detector-versioned high-confidence finding resolved in the current measurement, no same-family high-confidence regression, tracked outcomes with non-declining successful runs, and lower runtime spend. Duplicate findings are deduplicated and the total for one comparison pair cannot exceed the observed spend reduction.

## Dashboard presentation

Overview uses the period route. Its three keyboard-operable KPI tabs—runtime spend, identified waste, and verified savings—select one daily chart series without another request. A compact current action follows. Department or runtime-posture waste rates use one shared neutral scale with a fleet marker; warning color is reserved for exact rows that are above an exact fleet rate. Exact dollars remain visible, lower bounds retain `≥`, and no unfilled track is described as efficient spend. The outcome-free Source Performance table retains every active source and labels missing evidence **No data in period**.

The default is the last seven completed UTC dates ending yesterday. If that implicit first load has no measured source-days but the current UTC date has data, Overview extends the range through today once, discloses the in-progress day, records the state in the URL, and suppresses deltas. An explicit date selection never auto-extends. Audit Detail continues to present outcomes, daily Performance, and workflow economics. Compare keeps Measurement A as baseline and Measurement B as current and continues to include cost-per-successful-run and success-rate rows.
