PUBLIC REFERENCE · NO SIGN-IN

REFERENCE · BUILD

Technical guide

How a sample is wired, which endpoint accepts it, what each secret unlocks and the exact arithmetic behind a derived cost. Account-specific values are left as placeholders here.

01 / Wire a collector

Two environment variables in the monitored service, then the snippet below. It reads cgroup v2 directly, which is the same counter the provider bills against, so the derived cost stays comparable to the invoice.

KLSWITCH_INGEST_KEY=<your asset ingest key>
KLSWITCH_INGEST_URL=https://klswitch.app/functions/infraMeter
const fs = require('fs');

const KEY = process.env.KLSWITCH_INGEST_KEY;
const SINK = process.env.KLSWITCH_INGEST_URL;
const usageUsec = () => Number(fs.readFileSync('/sys/fs/cgroup/cpu.stat', 'utf8').match(/usage_usec (\d+)/)[1]);
const memGb = () => Number(fs.readFileSync('/sys/fs/cgroup/memory.current', 'utf8')) / 1073741824;

let lastUsec = usageUsec();
let lastAt = Date.now();

setInterval(async () => {
  const now = Date.now();
  const seconds = (now - lastAt) / 1000;
  const deltaUsec = usageUsec() - lastUsec;
  lastUsec = usageUsec(); lastAt = now;
  await fetch(SINK, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({
      key: KEY,
      vcpu: seconds > 0 ? deltaUsec / 1e6 / seconds : 0,
      ram_gb: memGb(),
      disk_gb: 0,
      egress_bytes: 0,
      seconds,
    }),
  });
}, 60000);

NO ASSET YET · CREATE ONE AND THIS BLOCK FILLS WITH ITS REAL KEY

02 / Ingest endpoints

Machine authentication · asset ingest key

EndpointAuthContract
/functions/infraMeterPOST · x-klswitch-key header onlyasset ingest key

Prices one interval against the rate card, appends a PROVISIONAL ledger entry, then tests the sample for a spike and for capping.

{ vcpu, ram_gb, disk_gb, egress_bytes, seconds }

/functions/deployIngestPOST · x-klswitch-key header onlyasset ingest key

Records the commit that went live. Without it a spike can be seen but never attributed.

{ sha, author, message, deployed_at }

/functions/settleIngestPOST · x-klswitch-key header onlyasset ingest key

Enters one provider bill for one UTC day. A second post for the same asset and day is refused, so a retry cannot double-count dollars.

{ amount, day (YYYY-MM-DD), external_ref }

03 / Enforcement endpoints

Machine authentication · valve key and fingerprint

EndpointAuthContract
/functions/sovereignGateALL · x-klswitch-key + x-activation-fingerprintvalve key + activation fingerprint

Three locks: activation (a sealed, active chain that has not drifted), compliance (critical evidence present and unexpired), budget (valve armed with headroom). Every decision is journaled as a GateEvent.

x-activation-fingerprint: <32 hex>

/functions/sentinelProxyPOST · x-klswitch-keyvalve key

The valve itself. The bare mount is the endpoint: the platform reads everything after /functions/ as the function name, so /functions/sentinelProxy/chat/completions 404s. With no sub-path the upstream route defaults to /chat/completions, which is the route the valve forwards. Meters the usage block into SpendEvent, returns 429 once the hard cap or volatility ceiling trips, and 403 when the target is disarmed.

the provider request body, unchanged (OpenAI-shaped)

Gate failure codes · SEEN means this account has produced it

CodeLockMeaningObserved
ALLOWNONEEvery lock was open and the request was forwarded.—
ACTIVATION_MISSINGACTIVATIONNo fingerprint was presented.—
ACTIVATION_MALFORMEDACTIVATIONA fingerprint is 32 hexadecimal characters; this one was not.—
ACTIVATION_UNKNOWNACTIVATIONThe fingerprint matches no sealed activation on record.—
SEAL_MISMATCHACTIVATIONThe sealed summary does not verify against that fingerprint.—
SEAL_UNCONFIGUREDACTIVATIONNo attestation key is configured, so no seal can be verified. Refused with 503 rather than passed unchecked.—
ASSET_NOT_ACTIVEACTIVATIONThe chain resolved, but its asset is not active.—
DRIFT_OPENCOMPLIANCEA verified DNS step no longer answers its recorded target.—
COMPLIANCE_FAILCOMPLIANCEA critical evidence item failed or expired.—
COMPLIANCE_NO_EVIDENCECOMPLIANCENo evidence was ever recorded for a critical control.—
COMPLIANCE_UNBOUNDCOMPLIANCEThe evidence belongs to a different asset than the one asking.—
VALVE_UNKNOWNBUDGETNo valve answers to that endpoint key.—
VALVE_UNBOUNDBUDGETNo valve is bound to this activation, so budget cannot be evaluated. Refused with 503.—
VALVE_DISARMEDBUDGETThe valve exists but is disarmed.—
BUDGET_EXHAUSTEDBUDGETSpend has reached the hard cap.—
BURN_VOLATILITYBUDGETBurn rate is over the volatility ceiling.—

04 / Console functions

Session authentication · scoped to your own records

EndpointAuthContract
/functions/reconcilePOST · session (admin)session

Closes completed UTC days that have a bill: a SETTLED entry at the provider number, plus a REVISION entry when the derivation was wrong. Idempotent by window.

{ lag_hours }

/functions/chainAnchorPOST · session or schedulesession / scheduled

Pins every chain head, chains the anchor to the one before it, and publishes the line to the external witness.

/functions/ledgerAuditPOST · sessionsession

Walks one asset journal from genesis and reports every break: an edited entry, a spliced entry or an unsealed tail.

{ asset_id }

/functions/activationChainPOST · sessionsession

Runs the next step of a validation chain and, when the last one passes, seals the activation fingerprint.

/functions/dnsProbePOST · sessionsession

One live DNS lookup compared against the required target. Reports MATCH, WRONG_TARGET or NXDOMAIN.

/functions/compliancePOST · sessionsession

Evaluates control evidence per asset and returns COMPLIANT, NON_COMPLIANT or NO_DATA.

/functions/capEnginePOST · session or schedulesession / scheduled

Opens a resource cap through the asset provider command URL, then restores it when burn falls back and you ask it to.

/functions/driftWatchPOST · scheduledscheduled

Re-probes verified steps on a schedule and opens or resolves a DriftEvent per step.

/functions/healthPackPOST · sessionsession

Builds the three-pillar pack (verification, stability, activation) with a digest over its own contents.

/functions/unitEconomicsPOST · sessionsession

Unit cost per window: spend divided by the volume you declare, with overhead shown separately.

/functions/dueDiligencePOST · sessionsession

Generates the CSV and ledger history server-side, with an integrity digest over the export.

/functions/financialControlPOST · sessionsession

Verification pass over the financial controls, recording what it could and could not observe.

/functions/attestationPOST · sessionsession

Writes and verifies HMAC attestations; the same key that seals ledger digests.

05 / Provider verification

The provider is not trusted and not disbelieved: what it says it metered is priced, sealed beside the derivation, and the difference is kept as a record. Connect once, map each asset to the service that answers it, then close days against the provider rather than the collector.

Session authentication · the connect flow, then admin only

EndpointAuthContract
/functions/railwayOAuthGET callback · POST { action: authorize }session

Starts and completes the provider consent in one function, because the registered redirect has to be a single exact string. Tokens are sealed at rest; nothing secret reaches this page.

{ action: "authorize" } → the consent URL · the callback the provider returns to

/functions/railwayMapPOST · sessionsession, scoped to your own assets

Turns the consent into asset-to-provider-service mappings by pairing each unmapped asset with the one service whose name answers it. An asset with two candidates is reported instead of guessed.

{ action: apply } · { action: map, asset_id, service_id }

/functions/providerReconcilerPOST · session (admin)admin session

The shadow accountant: prices the provider’s own metered quantities for a window and sets that figure beside the burn derived for the same span, sealing both into the chain. It compares meters, never claims to have read a bill.

{ day?, force? }

/functions/providerSettlePOST · session (admin)admin session

Closes whole UTC days against what the provider itself metered for those exact days, priced at the published rate card, with the variance against the derivation sealed beside it. A day the provider reports nothing for is left open, not closed at zero.

{ from, to } (YYYY-MM-DD) or { days: […] }, 1 to 14 days

06 / Anchor log API

Reading the log needs no console: send the anchor log key and the endpoint answers JSON. Pinning stays with the button on the anchor page or the hourly schedule, because a pin is an operator act, not a read.

Machine authentication · anchor log key

EndpointAuthContract
/functions/anchorApi?action=logGET or POST · x-anchor-key header onlyanchor log key, or an admin session

The anchor log as data: every pin with its root, the root it chained from, the counts it recorded and what the outside witness answered.

{ head_root, verdict, anchors[] } · ?limit= up to 200 pins

/functions/anchorApi?action=verifyGET or POST · x-anchor-key header onlyanchor log key, or an admin session

Re-walks the parent link between pins and returns the head root, so a printed anchor sheet can be checked against the log as it stands now.

{ head_root, links_intact, links_broken, breaks[] }

curl -s "https://klswitch.app/functions/anchorApi?action=verify" \
  -H "x-anchor-key: $ANCHOR_LOG_KEY"

A printed anchor sheet carries the head root and the instant it was captured. Verified against this endpoint later, a matching head means the log still says what the sheet said; a different one means it changed after the sheet was taken.

07 / Account API

A tenant issues one key on the API Access page and reads everything it owns from a single path. Writes stay on the purpose-built endpoints above: a meter tick, a bill and a gate decision are acts, and each keeps its own key.

Account authentication · issued key

EndpointAuthContract
/functions/appApi?resource=GET or POST · x-api-key headeraccount API key

One key, one base URL: every resource this console holds, scoped to the key owner. Issued on API Access, which lists all ten resources with their filters.

{ data[], count, has_more, next_cursor } · ?limit= max 200

/functions/apiKeysPOST · sessionsession

Issues and revokes account keys. The plaintext key comes back once; only its SHA-256 is stored.

{ action: list | create | revoke }

curl -s "https://klswitch.app/functions/appApi?resource=ledger&limit=20" \
  -H "x-api-key: $KLSWITCH_API_KEY"

08 / Secrets

  • ATTESTATION_SECRET

    HMAC key for every ledger digest and attestation. Rotating it invalidates every digest issued before the rotation.

    Without it: With no key, digests cannot be verified and the journal is refused as unproven rather than reported as continuous.

  • PROVIDER_CONTROL_TOKEN

    Bearer token sent to the provider control endpoint when the cap engine opens or restores a resource cap.

    Without it: Capping still decides and journals the intent, but the command cannot be delivered.

  • ANCHOR_WITNESS_URL

    External log that receives each anchor line, so continuity can be proven by a third party.

    Without it: Anchors are still captured and chained locally; the witness column reads UNSENT.

  • ANCHOR_LOG_KEY

    The key an outside reader presents to /functions/anchorApi, so a witness or auditor can pull the log without a console login.

    Without it: Only an admin session can read the anchor log; keyed calls answer 503.

  • RAILWAY_CLIENT_ID + RAILWAY_CLIENT_SECRET

    The OAuth client the provider consent runs under, so metered usage can be read back without a pasted token.

    Without it: The connect flow cannot start; a provider mapping has no credential to ask with.

  • RAILWAY_API_TOKEN

    Stand-in provider credential for reconciliation when no workspace consent has been granted.

    Without it: Each mapping reports that it has no credential instead of settling against a figure it never read.

VALUES LIVE IN SETTINGS → SECRETS AND ARE NEVER SHOWN HERE

09 / The arithmetic

  • provisional = vcpu × vcpu_min + ram_gb × ram_min + disk_gb × disk_min + egress_gb × egress_rate
  • measured(day) = Σ provisional entries sampled inside that UTC day
  • delta = billed − measured
  • ratified when |delta| ≤ max(0.005, measured × 0.005)
  • digest(n) = HMAC-SHA256(asset, seq, prev_digest, state, amount, sampled_at, metrics, window_key)

Settlement is additive, never destructive. A closing entry states the provider figure, a revision entry states the difference, and the provisional rows stay exactly as they were written.

10 / Anchor state

No anchor captured yet. The scheduled anchor runs hourly once the workflow is active.