Metadata-Version: 2.4
Name: jevlikedecisions
Version: 0.13.0
Summary: One typed decision abstraction over jev-like decision-model providers.
License-Expression: MIT
Project-URL: Homepage, https://github.com/ashdamle/jevlikedecisions
Project-URL: Walkthrough, https://github.com/ashdamle/jevlikedecisions/blob/main/usecase.md
Project-URL: Source, https://github.com/ashdamle/jevlikedecisions
Project-URL: Issues, https://github.com/ashdamle/jevlikedecisions/issues
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: llm-spendguard<0.17,>=0.16.39
Provides-Extra: dev
Requires-Dist: mypy==1.18.2; extra == "dev"
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-timeout>=2.3; extra == "dev"
Provides-Extra: provers
Requires-Dist: packaging<27,>=24; extra == "provers"
Dynamic: license-file

# jevlikedecisions

Start with the [executed end-to-end walkthrough](https://github.com/ashdamle/jevlikedecisions/blob/main/usecase.md): one question, provider estimates, combined arms, approvals, suitability, audits, and MCP.

Already using an earlier version? Paste the [upgrade prompt](https://github.com/ashdamle/jevlikedecisions/blob/main/docs/upgrade-prompt-for-earlier-versions.md) into a coding agent working in that repository. It is pin-and-verify, not migrate: across every published version `decide()` has only gained optional keyword parameters, and the backend names, aliases, credential variables, CLI commands and MCP tool names are unchanged. The one exception in that range is the MCP reply *envelope*: 0.9.7 made `structuredContent` a JSON object, as MCP requires, so three tools now carry their value under a declared key.

Not using it yet? Paste the [adoption prompt](https://github.com/ashdamle/jevlikedecisions/blob/main/docs/adoption-prompt-for-new-repositories.md) instead. It says what a decision is and when this is the wrong tool, and it carries the full CLI / MCP / Python capability table with every reasoned absence — so it is also the document to read for the surfaces, whichever version you are on.

## Cutting a release

Before creating a `v<version>` tag, add the reviewed GitHub Release body at
`docs/release-notes/v<version>.md` and update the upgrade prompt to target that same
version. The tag-triggered publish workflow refuses missing, empty, or whitespace-only
notes before building, publishes the verified wheel and source distribution to PyPI,
then creates the GitHub Release from that file and attaches those exact artifacts.

### Re-judge changed capability documentation

Only the repository owner runs the documentation judge because it spends. From the repository root,
use the canonical invocation below; choose durable paths for the resume record and the verdict file:

```console capability-documentation-judge
python scripts/judge_capability_documentation.py --model gpt-6-luna --intent jevlikedecisions:capability-doc-substance --sample-count 3 --independent-run-count 3 --resume-path "$RESUME_PATH" --verdict-path "$VERDICT_PATH"
```

Judging is incremental: unless `--force-full-rejudge` is supplied, it selects only `(subject, hash)`
pairs absent from the existing verdict record. Changing one description therefore makes 3 samples
across 3 independent runs, or 9 calls, rather than re-judging all 71 subjects. Keep the same
`--resume-path` when retrying so completed samples are reused instead of repeated.

The judge deliberately submits with `no_metered_fallback=True`. A
`MeteredCallRefused: no_metered_fallback` result is the correct fail-closed behavior; restore
subscription-lane availability and retry with the same resume path. Never force metered spend.

## Price authority and fresh installs

<!-- documentation-fact:declared_price_authority:begin -->
Each backend's sourced, dated `price_basis` is this repository's declared price authority. Runtime resolution uses the spendguard catalogue when it carries the configured model and otherwise uses the declared input/output rates. The catalogue is a cross-check rather than the sole authority: when both prices exist they must agree within the configured tolerance, or pricing fails with both figures and sources. Missing catalogue coverage is recorded as `catalogue_cross_check: unavailable` alongside the authority row; it does not change the declared authority's status. Context pricing tiers apply to either resolved price. A backend with neither a usable catalogue price nor a usable declared basis is refused at configuration load.
<!-- documentation-fact:declared_price_authority:end -->

<!-- documentation-fact:pre_declared_price_authority:begin -->
**v0.6.0 and earlier could not price jev on any machine but the author's**, because they depended on an entry present only in the author's machine-local spendguard catalogue. Dispatch 120 removes that dependency; no local catalogue sync is required for jev estimates.
<!-- documentation-fact:pre_declared_price_authority:end -->

## One request, one or more decision backends

Python, CLI, HTTP, and MCP use the same request fields. Existing callers keep passing one configured name or alias in `backend`. A caller selects the configured pair with a configured combined-selection alias (`both` or `combined` in the packaged configuration), or passes a list of names/aliases from Python.

Every response exposes `status`, `arms`, `intent`, `via`, and `decision_invocation_id`; each arm contains either `result` or an `error` whose type and message come from that arm's actual exception. Single responses retain their existing top-level fields. Combined arms run concurrently, and any arm failure makes the combined status failed without promoting the survivor. Before any arm executes, the complete, untruncated request is built and counted for every selected wire shape. Admission-calibrated counts are checked against every declared limit of every selected backend; refusal executes zero arms. Arms keep separate audit rows and ledger IDs linked by `decision_invocation_id`. Combined execution costs the sum of its calls; its only extra product is agreement/disagreement.

`decision_invocation_id` is an opaque identity minted once per `decide()` invocation and shared by all its arm audit rows, including failures. Separate invocations receive different identities even for identical evidence, questions, backend selections, and intents. A single-backend invocation follows the same rule. `request_digest` identifies the evidence-and-question content; it cannot identify an invocation or group a combined pair. Caller-supplied `input_fingerprint` remains a separate optional signal. Historical audit rows carry a declared unknown sentinel rather than an invented invocation grouping.

`jevlikedecisions.decide(...)` is one typed decision entrypoint over a family of provider adapters. Shared evidence is sent once, in full, and responses are checked against both the provider shape and the originating questions. Backend selection is mandatory: no call silently falls back to the deterministic `mock_jevlike` backend.

## Resumable approved decision jobs

`execute_resumable_decision_job` runs an exact, fingerprinted plan item by item and durably
checkpoints each success or failure. The surrounding job-approval functions let an operator review
one aggregate zero-spend estimate and authorize that committed plan once; each item still mints and
consumes the ordinary single-use approval required by `require_matching_decision_estimate`.
Uncommitted payloads, duplicate mints, exhausted call counts, consumed jobs, and estimates beyond
the configured `maximum_committed_estimated_dollars` are refused.

That dollar ceiling bounds the sum of the committed **estimates**, not realized provider spend.
Actual cost can exceed it when an estimator is wrong; realized cost is unavailable before the paid
call at this minting seam and is not reconciled by this capability. This mechanism provides one
approval instead of N and makes an item failure cost one item of progress instead of the whole run.
It provides no provider discount, makes no fewer calls, and does not lower the price per call. See
the [executable Python step](https://github.com/ashdamle/jevlikedecisions/blob/main/usecase.md).

## Installation and spend-gate setup

Python 3.11 or newer is required.

Install the package and its sole runtime dependency, `llm-spendguard`, with pip:

```console
python -m pip install jevlikedecisions
```

> **Pending first release:** The package is not yet published on PyPI. Until the first release is published, clone this repository, change into the clone, and run `python -m pip install .`. Delete this note when publishing the first release.

Before making a model call, arm the spend gate in the virtual environment. This is required: `jevlikedecisions` deliberately refuses to call a model from an interpreter where spendguard is not enforcing. With the target virtual environment activated, run:

```console
spendguard install-hook --venv "$VIRTUAL_ENV" --no-pkg
```

> **Temporary upstream workaround:** `--no-pkg` avoids a `FileNotFoundError` for pip-installed, non-editable `llm-spendguard` environments where `install-hook` otherwise looks for a repository `pyproject.toml`. Remove this flag and note after that upstream defect is fixed.

Verify the activated interpreter:

```console
spendguard doctor
```

The successful verdict line is `ENFORCING HERE: 🟢 YES — calls from this interpreter are gated`.

> **Temporary upstream workaround:** `spendguard doctor` may currently exit non-zero after printing that successful verdict, with `ValueError: Pricing returned no token cost`. Read the verdict line rather than the exit code; remove this note after that upstream defect is fixed.

If gate setup is skipped, `decide()` refuses model calls through `require_enforcing_spendguard`.

## In-process configuration preflight

An in-process caller sets only `JEVLIKEDECISIONS_CONFIG` to one JSON file, or places that file at
`~/.config/jevlikedecisions/config.json` and sets no configuration variable:

```python
import os
import jevlikedecisions

os.environ["JEVLIKEDECISIONS_CONFIG"] = "/operator/config/jevlikedecisions.json"
readiness = jevlikedecisions.report_declared_configuration_doctor()
```

Every existing indirection key has a direct-value companion formed by removing `_env`:
`receipt_directory`, `approval_directory`, `approval_integrity_key`,
`approval_integrity_key_file`, `decision_audit_store_path`, `decision_audit_spool_path`,
`decision_audit_quarantine_path`, `mcp_http_host`, and `credential_fallback_file`.
Resolution is environment variable named by the `*_env` key, then the direct config value, then a
packaged direct default. No security-sensitive path has a packaged default. An absent or incomplete
default file therefore fails closed and names its unresolved keys. Run `jevlikedecisions doctor` or
the MCP tool `doctor_configuration` for the same zero-provider-call report, including provenance.
Model credentials remain outside this mechanism: they come only from the enforcing llm-spendguard
interpreter or its governed keys file.

## Request and question schema

Every surface accepts the same JSON object:

```json
{
  "input_parts": ["complete evidence"],
  "questions": [{"name": "safe", "type": "predicate", "description": "Is it safe?"}],
  "backend": "mock_jevlike",
  "intent": "documented-example",
  "prompt_cache_key": null
}
```

`intent` and `backend` are required. Every decision result identifies `backend`, `provider`, `model`, `route`, `via`, `ledger_id`, `usage`, `cost_complete`, and `known_input_cost_floor_usd`. Inspect `route` to distinguish in-process and metered results. `cost_complete` says whether the cost is fully settled; when a provider omits output-token usage, a metered result has `cost_complete: false`, no ledger id, and only the known input-cost floor. In-process results are settled at zero cost. Every question has `name`, `type`, and `description`. The packaged configuration is authoritative: all shipped backends support `predicate`, `choice`, and `score`. A choice also has `choices`, whose entries contain `value` and `description`. A score also has `levels`, whose entries contain `label` and `description`. TypeSafe Jev receives the canonical `predicate` type as its vendor-native `noul` type. Library validation is authoritative for every surface.

Box is `ABSENT·DELIBERATE`, with the refusal reason declared in `src/jevlikedecisions/config/unsupported_question_types.json`. TypeSafe labels Box “Dreamer-ready,” not production-ready, and warns that its request, answer, limits, and accuracy can change. It has no OpenAI Decisions counterpart, returns image coordinates plus scalar confidence rather than an answer distribution, requires image assets and image-specific transport, and has no “not found” result. Those properties violate this engine’s identical cross-backend request/response contract; Box is deliberately outside the abstraction, not awaiting implementation. A `box` request raises a typed refusal carrying that declared reason.

Free-text or open-ended answers are also `ABSENT·DELIBERATE`. This engine returns a distribution over a declared answer space: a predicate declares two outcomes, a choice declares its values, and a score declares its levels. Free text declares no answer space, distribution, or meaningful confidence, and the answer validator could check only that a string arrived. Neither the [OpenAI Decisions guide](https://developers.openai.com/api/docs/guides/decisions) nor [TypeSafe's primitive catalogue](https://docs.typesafe.ai/primitives) names a free-text or open-ended answer primitive, so the registry declares the absence against this package's typed-answer contract rather than inventing a vendor term. General text generation belongs in `llm-spendguard`, as described above; this boundary is not an implementation backlog.

### Many questions over one shared payload

One request carries one shared `input_parts` payload and between 1 and 400 questions (`limits.minimum_questions` and `limits.maximum_questions` in `src/jevlikedecisions/config/jevlikedecisions.json`). The adapter serializes the shared payload once per request, so N questions about the same evidence send that evidence once rather than N times. `validate_decision_answers` in `src/jevlikedecisions/engine/validation.py` makes this safe: it refuses a different answer count, any ordered answer whose `name` or `type` differs from its question, and any `choice` answer outside the declared values. Answers therefore cannot silently shift, arrive short, or attach to the wrong question. This is enforced correspondence, not prompt packing.

The zero-spend measurement in `scripts/measure_bulk_decision_encoding_costs.py` used the committed 12-item scenario. One question per request cost 3,026 input tokens on `openai_decisions` and 2,473 on `typesafe_jev`; moving shared criteria into state and asking all 12 questions in one request cost 1,968 and 1,489 (ratios 0.650 and 0.602). A single-item packed request was worse than unpacked (1.059 and 1.039), because it paid the shared block without amortizing it; the smallest winning chunk was 2 on both backends. There is no provider discount and neither configured endpoint is batch-submittable: the saving comes only from not resending shared input, while request cost still scales with the payload plus its questions.

The ceiling depends on what can be shared. When every question carries its choice values and descriptions, the measured ceiling is 1.54× for `openai_decisions` and 1.66× for `typesafe_jev`. Moving descriptions into the shared payload and leaving bare option values raises the measured bound to 2.04× and 2.47×. The current adapter requires a description for every choice, so bare values are a measured bound, not a supported request form.

With `q` questions per item, at most `floor(400 / q)` items fit in one request: 400 at one question each, 133 at three, and 80 at five. Use this lever when a caller already sends typed questions. Do not use it as a reason to convert a prose answer specification into typed fields: against a 30-item external workload whose answer space was already prose in shared input, typed questions added 44.3% input tokens per item when sent one request per item and still added 0.6% when all 30 were combined, relative to that workload's recorded per-item input tokens. In that workload, packing merely recovered about what the duplicated typed declarations cost.

### Decision suitability

`assess_decision_suitability` asks one configured classification question through `decide()` and returns the same contract through Python, CLI `suitability`, HTTP `/suitability`, and MCP `assess_decision_suitability`. Its bounded shapes are derived from the intersection of every configured backend's declared `question_types`, so a framing is backend-independent. In the shipped configuration these are `predicate`; `choice` with one or more caller-declared `{value, description}` entries; and `score` with caller-declared `{label, description}` levels within the configured minimum and maximum. A fourth configured outcome identifies prompts that require unbounded generation.

The result uses `decision_shape` for the selected question type, `required_declarations` for the schema the caller still owes, `decide_request` for a complete request that can be sent to `decide()`, and `question_type_disagreement` for a nullable object containing `classified_question_type` and `supplied_question_type`. On disagreement, the complete paid decision and suitability classification remain available, `decide_request` stays null, and `required_declarations` states what a conforming question for the classified shape requires. `out_of_scope_explanation` explains why an unsuitable prompt does not fit, and `general_llm_generation_pointer` remains present for work outside the bounded engine. The old `reframing` field is not part of this contract because an already-valid request is not a reframing, while an unsuitable prompt needs an explanation and declaration requirements rather than a fabricated request.

The optional `candidate_question` is the no-generation boundary. When supplied, it must already be a complete valid question of a type supported by every configured backend; malformed candidates are refused before `decide()` at zero spend. It is included whole in the same paid classification request and, when its type agrees with the selected shape, is returned unchanged inside `decide_request`. A post-call type disagreement is a reported finding, not a refusal. When the candidate is omitted, prose may still be classified as a bounded shape, but `decide_request` is null and `required_declarations` tells the caller what to supply. The capability never extracts choices or score levels from prose and never invents them. The zero-spend estimate accepts the same optional question, so it serializes and counts the same assessment request the paid path would submit.

Live suitability acceptance uses this capability directly through either Python or MCP with the same request fields. MCP tool names are resolved from the capability registry, and the measurement consumes the returned suitability contract without reconstructing or supplying any field it checks.

Backend names and aliases come from the package configuration. An alias is accepted only at selection; estimates, approvals, receipts, audit evidence, and returned provenance always use the canonical backend name. Omitting `backend` never selects a default and produces a typed `DecisionUnavailable` refusal.

| Canonical backend | Accepted aliases | Provider | Model | Usability and precondition |
|---|---|---|---|---|
| `openai_decisions` | `openai` | `openai` | `gpt-6-luna` | Usable only with `OPENAI_API_KEY`, an enforcing spendguard interpreter, and a matching estimate approval. Proven live: 53 validated attempts over 2026-11-09 to 2026-11-10 totalling 1,607,127 input tokens, every one metered, cost-complete and carrying a ledger id. The provider reports an explicit zero output tokens on every one of them, so no output-side volume has been observed and output cost cannot be reconciled from provider-supplied usage. A further 39 attempts were rejected with HTTP `400` for the same cause as the `typesafe_jev` rejections below: a `score` question carrying 11 `levels` against this provider's maximum of 10, which the packaged limit now prevents locally. |
| `typesafe_jev` | `jev` | `typesafe` | `jev-1.14.0` | Usable only with `TYPESAFE_API_KEY`, an enforcing spendguard interpreter, and a matching estimate approval. Input costs `$0.042` per 1M tokens and output is free, as documented at `docs.typesafe.ai/models`; the wire schema is documented at `docs.typesafe.ai/api/system-one`. Proven live: 33 validated attempts on 2026-11-09 totalling 1,663,893 input and 517,177 output tokens, every one metered, cost-complete and carrying a ledger id. A further 45 attempts were rejected by the real endpoint with HTTP `422`, every one for the same cause: a `score` question carrying 11 `criteria` against the provider's maximum of 10. That is a closed schema-discovery episode, not ongoing instability — the packaged `maximum_score_levels` is now `10`, and an 11-level question is refused locally by `validate_decision_questions` before any request is built or any money is spent. |
| `mock_jevlike` | none | `mock` | `deterministic` | Usable in-process and never selected implicitly. Predicate probability is exactly `0.5`; choice selects the first option with probability/confidence `1.0` and all others `0.0`; score selects the first level with score `0.0`, probability/confidence `1.0`, and all other levels `0.0`; reported input/output tokens are both `0`. |

## Estimate, approve, then spend

The shipped configuration contains exactly three backends: metered `typesafe_jev` and `openai_decisions`, plus the in-process `mock_jevlike` test double. Their only transport kinds are `http` and `in_process`. A backend that declares the removed `subscription` transport is refused when configuration loads; subscription-lane LLM access belongs in llm-spendguard.

Choice questions may declare `"calibrated_choice_distribution": "required"` or `"calibrated_choice_distribution": "omitted"`. Omitting the declaration preserves the current `required` contract: `choice`, `probabilities` for every declared choice in order, and `confidence`. Declaring `omitted` explicitly requests only `name`, `type`, and `choice`; returning either `probabilities` or `confidence` is a named nonconformance, even if null. Unknown or malformed declarations are refused with the permitted values from the packaged `choice_distribution_contract` configuration beside `limits`. Mixed declarations in one call are supported. The shared validator enforces the declared answer fields across Python, CLI, HTTP, and MCP. Score questions are unchanged.

Self-reported confidence is **not calibrated**. In the measured eight-question probe with twenty declared choices per question, gpt-6-luna returned top probability/confidence `1.0` on every item (entropy approximately zero; effective support `1.00`), while glm-5.3 returned top probability/confidence `0.99` on every item (entropy `0.0629`; effective support `1.06`). Those degenerate vectors do not establish calibrated uncertainty. At the working shape of 32 questions × 29 choices, the measured output grew from 2,149 to 23,270 tokens. The declaration allows callers to omit that unvalidated distribution rather than pay for it. The field describes the requested distribution contract; it does not certify calibration when required.

Paid decisions fail closed. First call `decide(..., estimate_only=True)`: it counts the complete provider request, prices it through the catalogue-cross-checked declared price authority, spends `$0`, and persists a matching approval. Only a later identical `decide(...)` may reach the gated metered transport. Provider usage remains authoritative for the real receipt. Configure approval storage with `JEVLIKEDECISIONS_APPROVAL_DIR`, approval signing with `JEVLIKEDECISIONS_APPROVAL_INTEGRITY_KEY_FILE`, receipt storage with `JEVLIKEDECISIONS_RECEIPT_DIR`, and an alternate package configuration with `JEVLIKEDECISIONS_CONFIG`. The legacy by-value integrity variable is retained only to produce a migration refusal. The integrity file must contain a non-whitespace UTF-8 key and permit no non-owner access.

Calibration has three declared consumers. `context_admission_input_token_calibration_factor` equals the measured minimum; `pricing_input_token_calibration_factor` follows the measured median for a one-sided undercount and the declared identity policy for a distribution spanning identity; `spend_ceiling_input_token_calibration_factor` retains the measured maximum. The repository has no active calibrated spend-ceiling check: the upper-bound declaration is reserved for that consumer, not used to refuse context. Counts round upward after multiplication. Audit rows preserve the raw count, the context-admission and pricing counts and their actual factors, and provider usage. The existing admission audit field names remain compatible, with their factor now sourced from `context_admission`. The authority gate requires the context consumer to equal the measurement minimum and the spend-ceiling consumer to equal its maximum; missing authority remains UNREVIEWED.

The direction follows the cost of the error. A request above a provider context limit is rejected without billing; a false local refusal removes the capability entirely. Context admission therefore refuses only when the measured lower bound exceeds the limit and leaves the uncertain band to the provider. The 2026-11-10 whole-store replay found that the former maximum refused 29 of 35 live-accepted TypeSafe requests. One recorded request counted 41,598 locally and 53,900 at the provider, below the documented 64,000, yet the old maximum counted 135,610. No scalar upper bound could both cover the measured ratio maximum and admit that request. A spend ceiling has the opposite error cost because an excess spend is billed, so it retains the maximum.

TypeSafe's measurement is n=35, minimum 1.2957353718928795, median 1.5357755386429415, maximum 3.26. OpenAI's n=55 measurement has minimum 0.7163480405897853, median 0.9432314410480349, maximum 1.2069486404833838; context admission uses that minimum while pricing retains its declared identity policy. These empirical bounds do not guarantee future counts. `scripts/derive_audit_input_token_calibration.py --store-path <store> --provider <provider>` derives the distribution under the enforcing interpreter.

<!-- documentation-fact:declared_input_limits:begin -->
Configuration declares `input_token_limits`, each with a name, scope, maximum, and source basis. Admission checks every limit of every selected backend before submitting any arm, without truncation. TypeSafe checks state plus all questions against 64,000 tokens and state plus each individual question against 32,000; OpenAI declares one input limit. The shared path does not assume a fixed number of limits. Explicit long-context opt-in is off by default. Set `JEVLIKEDECISIONS_TYPESAFE_LONG_CONTEXT=true` before estimating and executing (or explicitly enable the configured mode); unset it to retain the default limits. When enabled, it sends `TypeSafe-Danger-Zone-Long-Context: true` and raises both TypeSafe limits to 262,000. Admission never enables it to make a request fit. The vendor describes it as slower and less accurate at the same per-token price.
<!-- documentation-fact:declared_input_limits:end -->

<!-- documentation-fact:openai_context_and_tier:begin -->
OpenAI's [gpt-6-luna model documentation](https://developers.openai.com/api/docs/models/gpt-6-luna), retrieved 2026-11-10, documents a 1,050,000 context window. The retained 1,047,576 input ceiling is below that documented maximum. Its Standard base rates use the spendguard catalogue when available and otherwise its sourced declared price basis, with the backend price basis declaring the long-input tier: prompts above 272,000 input tokens multiply input/cache rates by 2 and output by 1.5 for the entire request. The estimate applies configured tiers structurally, including no tiers or multiple thresholds, without embedding vendor-specific thresholds in Python. TypeSafe declares no tier because its long context has the same per-token rate. Estimates currently price input with zero output tokens; the declared output multiplier remains explicit for rate calculations. Other OpenAI service modes and regional surcharges are outside the configured Standard route.
<!-- documentation-fact:openai_context_and_tier:end -->


<!-- documentation-fact:typesafe_price_authority:begin -->
[TypeSafe models documentation](https://docs.typesafe.ai/models), verified 2026-11-10, is authoritative for the configured `api.typesafe.ai/v1/systemone` endpoint: Jev 1.14 and 1.13 cost $0.042/M input, with output free. The $0.25–$0.42/M prepaid packs at [jevtypesafeai.com/pricing](https://jevtypesafeai.com/pricing) price the different `jevtypesafeai.com/api/v1/decide` product surface and do not apply here. An earlier entry applying $0.42/M here was incorrect; it was recorded in, and reverted from, a machine-local spendguard catalogue. spendguard’s shipped catalogue has never carried a jev entry at all, which is why this repository declares the price itself and treats the catalogue as a cross-check. Jev 1.14 supports Choice, Score, Noul, and Box; Jev 1.13 supports Choice, Score, and Noul.
<!-- documentation-fact:typesafe_price_authority:end -->

<!-- documentation-fact:settled_output_cost_basis:begin -->
A 2026-11-10 measurement of this machine's local audit store found 55 validated `openai_decisions` attempts and 35 validated `typesafe_jev` attempts. Every measured OpenAI attempt carried provider usage with zero output tokens and total tokens equal to input tokens, so for that observed route a decision's settled cost equalled its input cost and the default zero-output estimate agreed with settlement by construction. This is observed behaviour, not a vendor guarantee, and could change. The cost path still prices provider-reported non-zero output tokens at the declared $0.5/M output rate. TypeSafe reaches input-only cost for a different, declared reason: its configured price basis marks output free.
<!-- documentation-fact:settled_output_cost_basis:end -->

The 2026-11-10 proof exposed dispatch 116's error: an admission upper bound systematically overstated the cost prediction. At the authoritative rates (Jev $0.042/M input, output free; gpt-6-luna $0.1/M), raw counting estimated $0.00017684 (−22.9%), the shipped maximum factor estimated $0.00027730 (+20.9%), and median pricing estimates $0.00020069 (−12.5%), against $0.00022935 actual provider billing. Only the median passes the 15% reconciliation threshold. Jev input counts were 529 raw, 1,725 maximum-calibrated, 813 median-calibrated, and 828 actual.

Run callers under an enforcing llm-spendguard interpreter: the gate supplies model credentials from its governed keys file before this package starts. The packaged backend `key_env` declarations currently name `OPENAI_API_KEY` for `openai_decisions` and `TYPESAFE_API_KEY` for `typesafe_jev`; jevlikedecisions has no default-path credential loader. For a repository-specific fallback only, set the environment variable named by `credential_fallback_file_env` (`JEVLIKEDECISIONS_KEYS_FILE` in the packaged configuration). If unset, its configured default is `.jevlikedecisions/jdlkeys.env` beneath the caller's home directory. An absent fallback is normal. The file may supply only names declared by backend `key_env`, never overwrites a name already supplied by the gate or caller, must permit no non-owner access, and must not have a replaceable non-sticky ancestor.

Provider requests have a socket bound. Python, CLI, HTTP, and MCP callers may override it per call with `request_timeout_seconds`; omitting it on any surface uses the positive finite `decision_request_timeout_seconds` value from decision configuration. The packaged 300-second value is a conservative ceiling, not a measured bound: historical decide rows contain no latency distribution. It is intentionally well above a plausible healthy decision and must be re-derived after this release records request latency.

The decision audit store uses SQLite WAL journaling and the configured busy timeout on every connection opened for attempts, outcomes, queries, and wire-evidence reads. WAL permits readers to continue while a writer commits; SQLite still serializes writers. An append returns `succeeded` after a durable database write, retries busy/locked contention for the configured attempt count and backoff, then atomically spools the complete row and returns `pending`; malformed data, non-contention storage errors, or spool failure return `failed`. The first append creates the store with owner-only permissions using one atomic `O_CREAT` open; later appends do not change an existing store's mode. Opening an existing rollback-journal store switches its persistent journal setting to WAL and may create `-wal` and `-shm` sidecar files. This does not rewrite the table schema or make the database incompatible, and it is reversible by setting `PRAGMA journal_mode=DELETE` after all connections have closed and the WAL has been checkpointed.

## Python, CLI, HTTP, and MCP

Python:

```python
from jevlikedecisions import decide

estimate = decide(input_parts, questions, backend=backend, intent=intent, estimate_only=True)
result = decide(
    input_parts, questions, backend=backend, intent=intent,
    request_timeout_seconds=request_timeout_seconds,
)
```

CLI input comes from a JSON file or stdin. `estimate` prints the estimate and its `approval_path`; `decide` prints answers and receipt fields. The `backend` value accepts either a canonical name or an alias reported by `backends`.

```console
jevlikedecisions backends
jevlikedecisions estimate --backend "$JEVLIKEDECISIONS_BACKEND" request.json
jevlikedecisions decide --backend "$JEVLIKEDECISIONS_BACKEND" --request-timeout-seconds "$JEVLIKEDECISIONS_REQUEST_TIMEOUT_SECONDS" request.json
```

The CLI flag fills a missing request `backend`; if both the flag and JSON field are present they must agree or the command fails. CLI exit codes follow `sysexits`: `0` (`EX_OK`) for success, `64` (`EX_USAGE`) for malformed input, `65` (`EX_DATAERR`) for a typed decision refusal, and `70` (`EX_SOFTWARE`) for an internal fault. The CLI reports every failure as `TypeName: message` on stderr; catching internal faults gives automation a stable code without hiding the fault.

The standard-library HTTP server exposes every registry-declared HTTP capability over `POST`. Each request is a JSON object, each success is the registry-bound capability result, and every refusal is JSON with `error` and `message`.

| HTTP endpoint | Request JSON | Success JSON |
| --- | --- | --- |
| `/backends` | `{}` | configured canonical backends, aliases, provider/model, usability, and missing preconditions |
| `/estimate` | the complete decision request, including `backend`, `input_parts`, `questions`, and `intent` | the zero-provider-call estimate, token counts, digest or approval path, and estimate mode |
| `/decide` | the same complete decision request; optional `estimate_mode` and `request_timeout_seconds` | validated answer arms, invocation identity, usage, route, and receipt fields |
| `/suitability` | `prompt`, `backend`, `intent`, and optional `candidate_question` | bounded shape, required declarations, nullable `decide_request`, disagreement, and out-of-scope fields |
| `/estimate-suitability` | the same suitability request | its complete zero-provider-call estimate and approval metadata |
| `/outcomes` | `decision_audit_id`, `outcome`, and optional outcome metadata declared by the registry | the appended outcome identifier |
| `/learning` | the registry-declared learning query | aggregate decision-learning signal |

All endpoints share the same refusals: `400` for malformed shape or undeclared fields, `401` for a missing/invalid configured bearer token, `404` for an unknown path, `413` for a body over the configured whole-request ceiling, `422` for a typed decision refusal, `503` for `DecisionUnavailable`, and sanitized `500` for an internal fault. The JSON preserves the exact typed refusal name. The `backend` field accepts config-derived canonical names and aliases, and a paid caller must successfully call the matching estimate endpoint before the paid endpoint. Set `JEVLIKEDECISIONS_HTTP_PORT`; optionally set `JEVLIKEDECISIONS_HTTP_HOST`. With no `JEVLIKEDECISIONS_OPERATOR_TOKEN` it binds only to loopback. When that token is set, callers must send it as an operator bearer token.
Both HTTP listeners derive their maximum request-body size from four UTF-8 bytes for every token in the largest configured backend input context. A declared body above that ceiling is refused with HTTP `413` before the body is read; the capability listener uses its normal `error`/`message` JSON shape and the MCP listener uses JSON-RPC error JSON.

```console
jevlikedecisions-http --host "$JEVLIKEDECISIONS_HTTP_HOST" --port "$JEVLIKEDECISIONS_HTTP_PORT"
```

The package's sole runtime dependency is `llm-spendguard`; its MCP surface is a standard-library JSON-RPC stdio server. Its registry-derived tools are `doctor_configuration`, `list_decision_backends`, `estimate_decision`, `make_decision`, `assess_decision_suitability`, `estimate_decision_suitability`, `append_decision_outcome`, and `read_decision_learning_signal`. Tool input is the same JSON request described for its HTTP counterpart; configuration doctor and backend enumeration take no capability fields. Successful replies carry both text content and an object `structuredContent`: readiness, backend inventory, estimate/decision result, suitability result, outcome identifier, or learning signal respectively. Evidence is sent whole. Invalid JSON-RPC, unknown tools, missing required fields, and undeclared fields return the standard parse/request/method/params errors; typed decision refusals use the decision-error code and preserve type/message; unexpected defects use a sanitized internal-error reply. `make_decision` accepts optional `estimate_mode` and numeric `request_timeout_seconds`, and a matching estimate approval must exist before a paid call.

The CLI exposes `doctor`, `backends`, `estimate`, `decide`, `suitability`, `estimate-suitability`, `audit-drain`, `audit-read`, `outcome-append`, and `learning-read`. Request-document commands accept a JSON path or `-` for stdin; suitability commands accept their registry-derived prompt input, and `doctor`/`backends` need no request document. Each command prints the same JSON result as its bound capability: readiness, inventory, estimate/decision, suitability, audit rows, outcome identifier, or learning signal. Registry-declared flags supplement the request document and must agree with any duplicate payload value. Refusals are `EX_USAGE` for malformed arguments/input, `EX_DATAERR` for typed decision refusals, and `EX_SOFTWARE` for a sanitized internal fault, with `TypeName: message` on stderr.

```console
jevlikedecisions-mcp
```

The same registry-derived MCP tools are also available as a long-running, JSON-only MCP
Streamable HTTP service at `MCP_HTTP_ENDPOINT_PATH` in `mcp_http_transport.py`; this is a
transport for the stdio MCP surface, not a separate capability surface. Set
`JEVLIKEDECISIONS_MCP_HTTP_PORT`; optionally set `JEVLIKEDECISIONS_MCP_HTTP_HOST`. With no
`JEVLIKEDECISIONS_MCP_HTTP_OPERATOR_TOKEN` it binds only to loopback. When that token is set,
the host is required and callers must send the token as an operator bearer token.
Both MCP processes derive launch readiness from the environment-requirement reviews on every
MCP-exposed capability and refuse to serve if any review is `UNREVIEWED` or any required
configured variable is unset. Behavioral startup tests exercise that refusal independently for
the stdio and Streamable HTTP processes before either process can serve requests. With the
packaged metered backends, set the variables configured
by `approval_directory_env`, `approval_integrity_key_file_env`, `decision_audit_store_path_env`,
`decision_audit_spool_path_env`, `decision_audit_quarantine_path_env`, and
`receipt_directory_env`. Backend credential availability
remains the separate per-backend status returned by `list_decision_backends`; the optional
credential fallback file remains optional. Errors name variables only, never their values or
resolved paths.

```console
jevlikedecisions-mcp-http --host "$JEVLIKEDECISIONS_MCP_HTTP_HOST" --port "$JEVLIKEDECISIONS_MCP_HTTP_PORT"
```

On macOS, `scripts/generate_mcp_http_launchd_agent.py` generates a launchd user-agent plist
from the repository without putting a platform-specific entry point in the wheel. The port,
approval directory, audit store path, audit spool path, audit quarantine path, and receipt directory are required. A wrong record
location works silently and forks the decision history, so the generator will not guess any of
these five locations. The executable defaults to `jevlikedecisions-mcp-http` beside the Python interpreter
running the generator; the owner and home come from the current environment, and the label,
plist destination, and per-tool log paths derive from them. The generated daemon environment
uses the five operator-supplied record locations and defaults only the
`approval_integrity.key` owner-only key-file path. A wrong key-file path fails loudly and closed.
The bind host defaults through the
server's existing unauthenticated loopback resolution. Every derived value has an explicit
override flag, and the plist contains only the key file path, never the key value. Generate and
load an agent like this:

```console
python scripts/generate_mcp_http_launchd_agent.py --port "$JEVLIKEDECISIONS_MCP_HTTP_PORT" \
  --approval-directory "$JEVLIKEDECISIONS_APPROVAL_DIRECTORY" \
  --audit-store-path "$JEVLIKEDECISIONS_AUDIT_STORE_PATH" \
  --audit-spool-path "$JEVLIKEDECISIONS_AUDIT_SPOOL_PATH" \
  --audit-quarantine-path "$JEVLIKEDECISIONS_AUDIT_QUARANTINE_PATH" \
  --receipt-directory "$JEVLIKEDECISIONS_RECEIPT_DIRECTORY"
launchctl load "$HOME/Library/LaunchAgents/com.$USER.jevlikedecisions-mcp-http.plist"
launchctl kickstart -k "gui/$(id -u)/com.$USER.jevlikedecisions-mcp-http"
```

Those commands are for a first load. If regenerating the plist for a job that is already loaded,
replace them with `launchctl bootout gui/<uid>/<label>` followed by
`launchctl bootstrap gui/<uid> <plist>` so launchd re-reads the environment from disk; a
`kickstart -k` alone restarts the environment already loaded.

`scripts/deploy_mcp_http_service_release.py` installs a requested published release into a
versioned virtual environment, flips the stable service symlink, restarts the launchd job, and
rolls the link back if the MCP `serverInfo.version` does not match. The service identity and plist
location derive from the generator's shared declaration and the current host; the installed plist
then remains the authority for the executable layout, host, port, and environment. Every derived
value still has an optional command-line override. A normal release needs only the version:

```console
python scripts/deploy_mcp_http_service_release.py --release-version 0.8.0
```

`scripts/prove_service_release_mismatch_guard_fires.py` exercises that rollback using isolated
temporary state and injected service responses. It requires neither launchd nor a listening socket,
so `scripts/run_all_executable_provers.py` discovers and executes it with the other standalone
provers in CI. The runner derives standalone eligibility from each script's zero-argument execution
path; the shared document-guard framework requires target arguments and is therefore excluded.

Use `kickstart -k` only to restart an unchanged loaded label; do not load a second copy. This daemon is not a
singleton: another process on the same port fails to bind, and `KeepAlive` then retries it at
the configured `ThrottleInterval`. Without `JEVLIKEDECISIONS_MCP_HTTP_OPERATOR_TOKEN`, the
daemon binds loopback only. A coding tool's HTTP MCP server entry should point to
`http://127.0.0.1:<port>/mcp`, replacing `<port>` with the required operator-selected port.

## Release publication

The hand-out measurements include the repository's live release-tag set, so a release commit and
its tag must become visible together. Create and publish them only through
`scripts/push_release_commit_and_tag_atomically.py`; it refuses a remote that already contains the
release commit without its tag and sends the branch and tag in one atomic push. Supply every
repository-specific value explicitly:

```console
python scripts/push_release_commit_and_tag_atomically.py \
  --repository-root "$RELEASE_REPOSITORY_ROOT" \
  --remote "$RELEASE_REMOTE" \
  --branch "$RELEASE_BRANCH" \
  --tag "$RELEASE_TAG" \
  --tag-message "$RELEASE_TAG_MESSAGE"
```

## Paid live-proof utility

A combined `both` decision executed live on 2026-11-10. Its `jev` arm has ledger `8f67fbb96334498b` (828 input / 97 output tokens), and its `openai` arm has ledger `7e8fcb2707954b05` (799 input / 0 output tokens). Both rows are `validated` and `cost_complete`: the combined invocation totals 1,627 input / 97 output tokens. The matching separate single-backend calls have ledger IDs `d483415b72ad48f3` and `9bfed302d5804be9`. Across those four arm rows, the audit store and independently checked spendguard ledger agree on 3,254 input / 194 output tokens. These historical rows predate invocation identity; their grouping was established by the live-run evidence, not by their shared request digest.

`scripts/run_paid_decision_live_proof.py` preserves the reproducible paid-call proof harness in the repository. It takes a configuration path rather than embedding one; `examples/paid_decision_live_proof.example.json` shows the input shape. By default it estimates every configured backend, prints the per-backend and total token/USD estimates, and exits without making a paid call. After reviewing that complete estimate, rerun with the explicit `--authorize-paid-calls` flag to execute every configured proof. Its records include reported-output-token status, cost completeness, and the known input-cost floor alongside the ledger and receipt evidence.

```console
PYTHONPATH=src python scripts/run_paid_decision_live_proof.py examples/paid_decision_live_proof.example.json
PYTHONPATH=src python scripts/run_paid_decision_live_proof.py examples/paid_decision_live_proof.example.json --authorize-paid-calls
```

`assert_all_decisions_via_jevlikedecisions(...)` cross-checks package-owned receipts against spendguard rows by `ledger_id` and fails closed when there are no auditable receipts. Spendguard's calls table has no endpoint, route, or via columns, so this proves receipt-backed package calls; it cannot prove that no outside caller contacted a Decisions endpoint.

## Capability documentation verdict maintenance

Capability documentation verdicts accumulate by exact `(subject, sha256(documentation))` pairs.
The documentation judge normally evaluates only pairs absent from the schema-current record,
retains byte-identical entries with their original per-entry instrument provenance and timestamp,
and reports every stale pair it prunes. Use `--force-full-rejudge` when the judging instrument
changes, including its model, prompt, sample count, or independent-run count; that mode replaces
every current pair rather than retaining evidence produced by a different instrument. Older record
schemas are refused and must be migrated explicitly before judging.

## Troubleshooting

A framework Python without a usable certificate bundle may need `SSL_CERT_FILE` set to the path of an installed CA bundle, such as the one supplied by certifi, before a real HTTPS call. Never put keys or secret values in configuration or examples.

`anyjev` remains a named v1 schema gap: its authoritative independent wire contract was unavailable, so no fields were invented. It can be added as another adapter without changing `decide()`.
## General LLM generation

This package wraps the jev and OpenAI Decisions APIs only. General text generation was removed; use `llm-spendguard` for general LLM calls.
