@theoklitosbam7/verdict-kit 0.0.0-stage → 0.1.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 (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +625 -2
  3. package/config/routing/engineering.action-risk.consensus.v1.json +16 -0
  4. package/config/routing/engineering.task-route.cascade.v1.json +21 -0
  5. package/dist/action-policy.d.ts +104 -0
  6. package/dist/action-policy.js +173 -0
  7. package/dist/cache.d.ts +17 -0
  8. package/dist/cache.js +139 -0
  9. package/dist/cli.d.ts +2 -0
  10. package/dist/cli.js +142 -0
  11. package/dist/concurrency.d.ts +12 -0
  12. package/dist/concurrency.js +110 -0
  13. package/dist/config.d.ts +61 -0
  14. package/dist/config.js +247 -0
  15. package/dist/decision.d.ts +75 -0
  16. package/dist/decision.js +278 -0
  17. package/dist/engine.d.ts +63 -0
  18. package/dist/engine.js +79 -0
  19. package/dist/errors.d.ts +6 -0
  20. package/dist/errors.js +19 -0
  21. package/dist/http.d.ts +18 -0
  22. package/dist/http.js +140 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +14 -0
  25. package/dist/package-info.d.ts +1 -0
  26. package/dist/package-info.js +5 -0
  27. package/dist/policy/evaluate.d.ts +7 -0
  28. package/dist/policy/evaluate.js +39 -0
  29. package/dist/policy/events.d.ts +32 -0
  30. package/dist/policy/events.js +31 -0
  31. package/dist/policy/payload.d.ts +6 -0
  32. package/dist/policy/payload.js +11 -0
  33. package/dist/policy/registry.d.ts +22 -0
  34. package/dist/policy/registry.js +89 -0
  35. package/dist/policy/schema.d.ts +198 -0
  36. package/dist/policy/schema.js +112 -0
  37. package/dist/policy/scope.d.ts +5 -0
  38. package/dist/policy/scope.js +120 -0
  39. package/dist/probability.d.ts +1 -0
  40. package/dist/probability.js +3 -0
  41. package/dist/providers/discovery.d.ts +10 -0
  42. package/dist/providers/discovery.js +113 -0
  43. package/dist/providers/index.d.ts +56 -0
  44. package/dist/providers/index.js +83 -0
  45. package/dist/providers/ollama.d.ts +12 -0
  46. package/dist/providers/ollama.js +93 -0
  47. package/dist/providers/opencode-go.d.ts +3 -0
  48. package/dist/providers/opencode-go.js +40 -0
  49. package/dist/providers/system-one.d.ts +21 -0
  50. package/dist/providers/system-one.js +44 -0
  51. package/dist/providers/typesafe.d.ts +3 -0
  52. package/dist/providers/typesafe.js +36 -0
  53. package/dist/public.d.ts +5 -0
  54. package/dist/public.js +5 -0
  55. package/dist/response.d.ts +6 -0
  56. package/dist/response.js +104 -0
  57. package/dist/routing/cascade.d.ts +112 -0
  58. package/dist/routing/cascade.js +220 -0
  59. package/dist/routing/consensus.d.ts +148 -0
  60. package/dist/routing/consensus.js +367 -0
  61. package/dist/routing/retry.d.ts +3 -0
  62. package/dist/routing/retry.js +47 -0
  63. package/dist/routing/router.d.ts +12 -0
  64. package/dist/routing/router.js +27 -0
  65. package/dist/schemas.d.ts +339 -0
  66. package/dist/schemas.js +283 -0
  67. package/dist/server.d.ts +42 -0
  68. package/dist/server.js +416 -0
  69. package/dist/telemetry/events.d.ts +15 -0
  70. package/dist/telemetry/events.js +87 -0
  71. package/dist/telemetry/sink.d.ts +7 -0
  72. package/dist/telemetry/sink.js +59 -0
  73. package/dist/templates/registry.d.ts +13 -0
  74. package/dist/templates/registry.js +100 -0
  75. package/dist/templates/schema.d.ts +115 -0
  76. package/dist/templates/schema.js +70 -0
  77. package/dist/types.d.ts +86 -0
  78. package/dist/types.js +2 -0
  79. package/package.json +77 -3
  80. package/policies/engineering-default.v1.json +36 -0
  81. package/policies/engineering-strict.v1.json +36 -0
  82. package/templates/engineering.action-risk.v1.json +32 -0
  83. package/templates/engineering.compatibility.v1.json +25 -0
  84. package/templates/engineering.pr-risk.v1.json +26 -0
  85. package/templates/engineering.security-sensitivity.v1.json +20 -0
  86. package/templates/engineering.task-route.v1.json +27 -0
  87. package/templates/engineering.test-depth.v1.json +26 -0
package/README.md CHANGED
@@ -1,3 +1,626 @@
1
- # Temporary Holding Version
1
+ # Verdict Kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An MCP server, SDK, and CLI for classifier and decision models. The npm package is [`@theoklitosbam7/verdict-kit`](https://www.npmjs.com/package/@theoklitosbam7/verdict-kit), and the CLI command is `verdict`. MCP hosts see the server as `decision-models`.
4
+
5
+ All three interfaces share one provider-neutral decision engine. See [Choose MCP, SDK, or CLI](#choose-mcp-sdk-or-cli).
6
+
7
+ The server exposes the same MCP tools across providers. Set a default with `DECISION_PROVIDER`. Per-call provider overrides are accepted only for providers listed in `DECISION_ALLOWED_PROVIDERS`; when that variable is omitted, only the default provider is allowed. An explicitly empty list prevents startup.
8
+
9
+ ## Built-in providers
10
+
11
+ - **Ollama** (`ollama`) uses System One decision models through `POST /v1/systemone`.
12
+ - **TypeSafe AI** (`typesafe`) uses the official hosted Jev API at `https://api.typesafe.ai/v1/systemone`.
13
+ - **OpenCode Go** (`opencode-go`) uses the hosted decision models of an OpenCode Go subscription, such as Jev, at `https://opencode.ai/inference/go/systemone/v1/systemone`. See [OpenCode Go setup](#opencode-go-setup).
14
+
15
+ To add a provider, see [Add another provider](#add-another-provider).
16
+
17
+ ## MCP tools
18
+
19
+ - `decision_decide` evaluates named choice, `noul`, or score questions in one request.
20
+ - `decision_classify` selects one label.
21
+ - `decision_boolean` makes a yes/no judgement with a `noul` question.
22
+ - `decision_score` places state on an ordered rubric.
23
+ - `decision_batch` runs the same questions across several states.
24
+ - `decision_gate` applies a local advisory `allow | review | block` policy to caller-supplied answers without another model call. Missing or invalid required answers, unknown choice labels, and policies with no effective rules require `review`. A valid `block` takes precedence. Invalid policy rules, such as reversed thresholds or overlapping choice lists, return an MCP input error. Keep native host permissions enabled.
25
+ - `decision_action_policy` evaluates a proposed engineering tool call, skips routine actions in the default `consequential` scope, and combines model answers with a versioned advisory `allow | review | block` policy. It can emit Codex or Claude Code `PreToolUse` hook output directly.
26
+ - `decision_providers` lists providers and reports whether each provider and its approved models are ready. See [Provider readiness](#provider-readiness).
27
+ - `decision_templates` lists installed template versions and their resource URIs.
28
+ - `decision_validate` checks state against a template version locally.
29
+ - `decision_run` evaluates state using the questions from a specific template version.
30
+ - `decision_cascade` runs a trusted cascade profile. A small model answers first, and an uncertain answer goes to a larger model. It returns `accepted` with a result or `abstained`. See [Confidence cascades](#confidence-cascades).
31
+ - `decision_consensus` runs a trusted consensus profile. Several approved models answer the same template, and the tool returns a result only when every answering model agrees. It returns `agreed`, `disagreed`, or `no_quorum`. See [Multi-model consensus](#multi-model-consensus).
32
+
33
+ Model-facing tools accept optional `provider` and `model` parameters. Set `DECISION_ALLOWED_PROVIDERS` to a comma-separated allowlist when per-call provider switching is required.
34
+
35
+ Successful MCP calls return `structuredContent` and the existing JSON text. For `decision_batch`, `structuredContent` is an object with a `results` array. The JSON text remains an array. The Codex hook still receives its existing JSON shape.
36
+
37
+ ## Use cases
38
+
39
+ Use this server when an MCP host or coding agent needs a structured decision rather than an open-ended text response:
40
+
41
+ - **Route incoming requests:** Use `decision_classify` to assign support tickets, tasks, or messages to one of several labels.
42
+ - **Choose a workflow:** Use `decision_decide` to evaluate named questions about a task, such as whether to handle it directly or send it for review.
43
+ - **Score options:** Use `decision_score` to rate a state against an ordered rubric, such as task complexity or urgency.
44
+ - **Evaluate items in a batch:** Use `decision_batch` to apply the same questions across multiple states.
45
+ - **Review proposed tool calls:** Use `decision_action_policy` to assess consequential coding-agent actions and return an advisory `allow`, `review`, or `block` result. The included Codex and Pi integrations show how to use it in agent workflows.
46
+ - **Apply a local decision policy:** Use `decision_gate` to combine caller-supplied answers into an advisory `allow`, `review`, or `block` result without another model call.
47
+
48
+ Policy outputs are advisory, not an authorization boundary. Keep your MCP host's native permissions, confirmation steps, and sandbox controls enabled.
49
+
50
+ ### Choose MCP, SDK, or CLI
51
+
52
+ The MCP server, the [SDK, and the CLI](#sdk-and-cli) run the same decision engine. They read the same environment variables, templates, policy profiles, and routing profiles, and they return the same decision for the same input. Choose by who starts the decision.
53
+
54
+ | Who starts the decision | Use |
55
+ | ----------------------------------------------- | ----------------------------------------------------------------- |
56
+ | An AI agent, while it works | MCP server |
57
+ | An agent host hook that checks tool calls | MCP (Codex, Claude Code) or SDK (Pi and other in-process plugins) |
58
+ | Your Node.js service or bot | SDK |
59
+ | A script, CI job, git hook, or another language | CLI |
60
+ | A person who wants to try a template or model | CLI |
61
+
62
+ - **MCP server.** An agent host such as Codex, Claude Code, or Pi lists the tools, and the model calls them when it needs a decision, for example to route a task or to check a tool call. It needs no code. The model decides when to call, so use the SDK or the CLI when your code must get a decision at a fixed point.
63
+ - **SDK.** A Node.js program imports `createDecisionEngine` and calls it directly, with no extra process. Use it in a service or bot, such as a ticket router or a PR risk bot, when you want typed results, `DecisionError` codes, cancellation with `signal`, or your own provider registry in tests. The Pi extension uses the SDK because a Pi `tool_call` handler cannot make a nested MCP call.
64
+ - **CLI.** A shell, script, or program in any language sends JSON and gets JSON and an exit code. Use it in CI and git hooks: `validate` exits 5 when the state does not match the template, so a step fails without parsing the output. Each call starts a new process and loads the settings again, so use the SDK or a running MCP server for many decisions per second.
65
+
66
+ For example, a team runs Codex with the MCP server for action-policy checks and task routing. Its GitHub bot uses the SDK to score the risk of each pull request, and CI runs the CLI `validate` command on new template states.
67
+
68
+ ## Requirements
69
+
70
+ - [Node.js](https://nodejs.org) 24 or later (`engines` in `package.json`). CI tests the package with Node.js 24 and the development version pinned in `.node-version`, on Linux.
71
+ - To build from source: [pnpm](https://pnpm.io) (pinned in `packageManager` in `package.json`)
72
+ - For Ollama: Ollama and a decision model
73
+ - For official TypeSafe AI: a `TYPESAFE_API_KEY`
74
+ - For OpenCode Go: an `OPENCODE_GO_API_KEY` from an account with a Go subscription
75
+
76
+ ## Install
77
+
78
+ ### From npm
79
+
80
+ Install the package in your project to use the SDK, or globally to get the `verdict` command:
81
+
82
+ ```bash
83
+ npm install @theoklitosbam7/verdict-kit
84
+ # or
85
+ npm install --global @theoklitosbam7/verdict-kit
86
+ ```
87
+
88
+ Versions published by the release workflow have an npm provenance statement that links them to the workflow run.
89
+
90
+ ### From a package tarball
91
+
92
+ To test unreleased changes, create a tarball in a clone of this repository. `pnpm pack` builds the package first.
93
+
94
+ ```bash
95
+ pnpm install --frozen-lockfile
96
+ pnpm pack
97
+ ```
98
+
99
+ This writes `theoklitosbam7-verdict-kit-<version>.tgz`. Install it the same way as the npm package:
100
+
101
+ ```bash
102
+ npm install /absolute/path/to/theoklitosbam7-verdict-kit-<version>.tgz
103
+ # or
104
+ npm install --global /absolute/path/to/theoklitosbam7-verdict-kit-<version>.tgz
105
+ ```
106
+
107
+ The package contains the compiled code, the type declarations, and the bundled templates, policy profiles, and routing profiles. `pnpm run package:check` packs the package, installs it in a clean temporary project, and checks the SDK, the CLI, and the MCP server.
108
+
109
+ ### From source
110
+
111
+ From the repository root, install dependencies and build the server:
112
+
113
+ ```bash
114
+ pnpm install --frozen-lockfile
115
+ pnpm run build
116
+ ```
117
+
118
+ The optional `inspect` script needs a newer Node.js release than the supported range; use the version pinned in `.node-version`.
119
+
120
+ The server reads environment variables from its process. It does not load `.env` itself. Set variables in your shell, MCP host, or process manager. In an MCP host config, you can also ask Node.js to load a local `.env` file with `--env-file`. See `.env.example` for the supported settings.
121
+
122
+ The server validates provider configuration at startup. Restart the MCP connection after changing settings. Include the default provider in `DECISION_ALLOWED_PROVIDERS` when you set that list. Set `OLLAMA_ALLOWED_MODELS`, `TYPESAFE_ALLOWED_MODELS`, or `OPENCODE_GO_ALLOWED_MODELS` to a comma-separated list of approved model names. Each list applies to both the provider's default model and per-call overrides. Model names must be nonblank, at most 256 characters, and free of surrounding whitespace and control characters. Omit the model setting to use the built-in default.
123
+
124
+ Action policy has a 25-second inference budget by default. Set `DECISION_ACTION_POLICY_TIMEOUT_MS` to adjust it. For a host hook, set this budget below the host's timeout. Set `DECISION_ACTION_POLICY_FAILURE_MODE` in the host or MCP server environment to choose `native` (the default), `review`, or `block` for failures the running integration can handle. See the [Codex guide](integrations/codex/README.md), [Claude Code guide](integrations/claude-code/README.md), [Pi guide](integrations/pi/README.md) and [compatibility matrix](docs/compatibility.md) for host behavior.
125
+
126
+ The normal `decision_action_policy` result reports `status` as `evaluated`, `skipped`, or `failed`. It includes the applied profile ID and version in `profile` and a stable `reasonCode`. Codex and Claude Code hook results carry `profile` and `reasonCode` in MCP metadata under `decision-models/policy`. In enforce mode, a hook result for invalid tool input carries no metadata. In observe mode it carries the observation event. A skipped result with `local_context_required` requires review. In `native` mode, a full-context inference failure defers to host permissions unless the provider returned an invalid response. Invalid responses and reduced-context failures require review. A stricter profile or failure setting can require a block.
127
+
128
+ Set `DECISION_ACTION_POLICY_SCOPE=strict` in the Codex MCP server or Pi process environment to evaluate unknown actions within the host integration’s coverage. Direct MCP callers can pass `scope: "strict"` or `scope: "all"`.
129
+
130
+ For action policy, full tool input requires a loopback Ollama endpoint and a model listed in `OLLAMA_ALLOWED_MODELS` as local. Non-local and unverified targets receive only fixed categories for supported sensitive edits, with an approved model name and fixed policy questions. Actions that need full context or contain recognizable secrets return review before inference when the target cannot receive raw input. The other decision tools take the state supplied by their caller.
131
+
132
+ ## Action policy profiles
133
+
134
+ Set `DECISION_POLICY_PROFILE` in the MCP server or Pi environment and restart the host connection. The value includes the exact version.
135
+
136
+ - `engineering-default@1` uses the existing engineering thresholds, consequential scope, and native failure mode. It reviews quoted SQL writes such as `UPDATE … SET` and `INSERT INTO`, and tools named for mutating operations such as `execute_query`. It allows approved local inference or reduced context for eligible non-local calls. Target resolution and configuration failures require review in native mode.
137
+ - `engineering-strict@1` uses strict scope, lower review thresholds, and approved local Ollama only. It blocks provider failures the running integration can handle.
138
+
139
+ A requested scope or the existing failure-mode setting can strengthen the selected profile. Provider selection must satisfy both the profile and the server allowlist. If an action needs an approved local model or requests a provider outside the profile, the tool returns review before inference. `decision_gate` continues to use its caller-supplied rules.
140
+
141
+ An invalid selection prevents the MCP server from starting. Pi blocks intercepted calls when it cannot apply a configured profile. Codex uses its native permissions if it cannot reach the policy server. See the [profile definitions](policies) for the exact rules.
142
+
143
+ ## Policy observation mode
144
+
145
+ Set `DECISION_ACTION_POLICY_MODE` in the Codex MCP server or Pi process environment and restart the connection. The mode controls the host integration. The policy profile and scope still determine which actions to evaluate.
146
+
147
+ - `enforce` (default) uses the existing host review and denial behavior.
148
+ - `observe` evaluates policy and leaves approval and execution to the host. It writes one JSON event to stderr for each policy check.
149
+ - `disabled` skips hook inference. Explicit MCP calls that request a normal policy result remain available.
150
+
151
+ An observation reports `would_allow`, `would_review`, or `would_block` with an `evaluated`, `skipped`, or `failed` status. It includes the profile version and approved provider or model identity when known. A consensus observation includes the consensus ID and version and the provider and model of each evaluated member, up to four. The event omits action input, answers, and free-form reasons. It describes the policy outcome before the host decides what to do. Codex MCP hook results also carry the event in `decision-models/policy` metadata.
152
+
153
+ ## Batch limits and partial results
154
+
155
+ Structured decision state and question definitions reject `__proto__` keys and allow up to 64 nested object or array levels.
156
+
157
+ `decision_batch` accepts 1–20 states and a concurrency of 1–8. The default concurrency is 4. Each server process shares eight active inference slots and 32 waiting slots per provider across decision tools. A full queue returns `overload`. Queue time counts toward the provider timeout, and all items in a batch share the same deadline.
158
+
159
+ The default `failure_mode: "fail_fast"` preserves the existing result array and returns a tool error on the first failure. Set `failure_mode: "partial"` to get one result per input in order. Each result has a zero-based `index` and either `status: "ok"` with a `result` or `status: "error"` with a stable `code`. For example, an item that could not enter a full queue returns `{"index":2,"status":"error","code":"overload"}`.
160
+
161
+ Successful result data is limited to 1 MiB per item and 4 MiB per batch, measured as compact JSON before the result envelope. In partial mode, the server applies the aggregate limit in input order and reports `output_limit` for items that exceed the available space.
162
+
163
+ ## Decision cache
164
+
165
+ Caching is off by default. Set `DECISION_CACHE_TTL_MS` to a value from 1 to 300000 and restart the MCP connection to reuse identical results from `decision_decide`, `decision_classify`, `decision_boolean`, `decision_score`, and `decision_run`. `DECISION_CACHE_MAX_ENTRIES` limits the number of entries. The default is 256, and the maximum is 10000. The server also limits cached result data to 8 MiB.
166
+
167
+ - A request matches an entry only when it has the same planned targets (including any fallback), template version, state, and questions. The order of keys in state objects does not matter. The order of questions, criteria, and arrays does.
168
+ - Concurrent identical requests share one inference. When one caller cancels, the inference continues for the others. It stops when all callers cancel.
169
+ - The cache stores only successful, validated results. Errors are not cached. The cache stores a SHA-256 key, not the raw request.
170
+ - Requests with recognizable secrets in state or questions bypass the cache. Responses with recognizable secrets are not stored. `decision_action_policy`, `decision_batch`, and evaluation runs do not use the cache.
171
+ - Each server connection has its own cache, held in memory only. Entries expire after the TTL. The server does not yet know model revisions, so the TTL is limited to five minutes. After you replace a model with the same name, restart the connection.
172
+
173
+ When caching is enabled, results include `{"status":"hit" | "miss" | "shared" | "bypass"}` in MCP metadata under `decision-models/cache`. The structured result and JSON text are unchanged.
174
+
175
+ ## Retries and fallback
176
+
177
+ Routing is fixed by default: each decision makes one attempt with the selected provider and model. Set these variables and restart the MCP connection to recover from transient failures:
178
+
179
+ - `DECISION_RETRY_ATTEMPTS` (0–3, default 0) retries transport failures, a full provider queue (`overload`), and HTTP 429, 502, 503, and 504. The delay doubles from 200 ms up to 2 seconds, with random jitter. A longer `Retry-After` from the provider sets the delay. The router does not retry when `Retry-After` exceeds 30 seconds. Other errors are never retried, including invalid requests, rejected credentials, invalid responses, cancellation, and timeouts.
180
+ - Retries to a hosted or unverified target can be billed again. They require `DECISION_RETRY_BILLED=true`. Without it, only approved local Ollama models (listed in `OLLAMA_ALLOWED_MODELS` on a loopback endpoint) are retried.
181
+ - `DECISION_FALLBACK` lists up to four `provider:model` targets, for example `ollama:strands-decider:2b`. After the primary target fails with a transient error and its retries end, the router tries each fallback in order. It skips a fallback when [provider readiness](#provider-readiness) reports the model as missing or unsupported.
182
+
183
+ At startup, each fallback target must pass `DECISION_ALLOWED_PROVIDERS` and the model allowlist. A target that is not an approved local Ollama model requires `DECISION_FALLBACK_ALLOW_REMOTE=true`, and local-only mode rejects it. An invalid setting prevents the server from starting.
184
+
185
+ All attempts, delays, and fallbacks share one deadline: the caller's deadline or the primary provider's timeout, whichever ends first. The router does not start a delay that would end after the deadline. Cancellation stops the current attempt and any later ones.
186
+
187
+ Fallback applies only when the caller names neither `provider` nor `model`. An explicit choice is retried but never replaced. `decision_action_policy` and evaluation runs always name their model, so they never fall back. `decision_batch` stays fixed. The cache does not store an answer from a fallback model under the primary model's key.
188
+
189
+ When retries or fallback are enabled, results from the cached decision tools include the attempts in MCP metadata under `decision-models/routing`. Each attempt has `provider`, `model`, and `outcome` (`ok` or an error code). The metadata contains no request data.
190
+
191
+ ## Confidence cascades
192
+
193
+ `decision_cascade` takes `{"cascade": {"id": ..., "version": ...}, "state": ...}`. Profiles are trusted files in [`config/routing`](config/routing). A caller can choose a profile but cannot change its models or thresholds. Each profile names a template, ordered stages, and a budget:
194
+
195
+ - Each stage has a provider, a model, the evaluated model revision, and a minimum margin. The margin is the gap between the two most likely answers. For a `noul` answer, it is the distance of the probability from 0.5, doubled. With several questions, the least certain answer decides.
196
+ - A stage accepts an answer only when the margin is at least its minimum. It does not accept an incomplete distribution or a choice below the top class.
197
+ - A stage runs only when discovery reports the model as `ready` at the evaluated revision. Otherwise, it reports `uncalibrated` and does not call the model. TypeSafe and OpenCode Go do not report revisions, so their stages never run.
198
+ - `max_attempts` limits stages that run. `max_non_local_attempts` limits stages that run on non-local targets. A stage and its retries use one attempt. Evaluation reports count each actual provider call, including retries, for both cascade and consensus.
199
+ - Before the first call, every stage must pass the provider allowlist, the model allowlist, and local-only mode. All stages share one deadline.
200
+
201
+ The result has `status` (`accepted` or `abstained`), `result` when accepted, and one `stages` entry per stage with `provider`, `model`, `outcome`, and `margin` when known. The outcome is `accepted`, `uncertain`, `uncalibrated`, `budget`, or an error code. Treat `abstained` as "no reliable answer", not as a decision. The cache does not apply to cascades.
202
+
203
+ `engineering.task-route.cascade@1` runs `strands-decider:2b` and then `d3:4b`, both with a minimum margin of 0.3. Add both models to `OLLAMA_ALLOWED_MODELS`. Action policy does not use cascades, because no evaluated profile meets the action-policy criteria. See [Evaluation datasets and baselines](docs/evaluation.md#confidence-cascade).
204
+
205
+ To benchmark a cascade, run `pnpm eval --dataset <jsonl> --cascade <id@version> --seed <integer> --out-dir <directory>` without `--provider` or `--model`. The report counts abstentions as abstained items and adds a `cascade` object with the number of model calls.
206
+
207
+ ## Multi-model consensus
208
+
209
+ `decision_consensus` takes `{"consensus": {"id": ..., "version": ...}, "state": ...}`. Profiles are trusted files in [`config/routing`](config/routing), and a caller cannot change their members or rules. Each profile names a template and these fields:
210
+
211
+ - `members`: two to four unique provider and model pairs. Before the first call, every member must pass the provider allowlist, the model allowlist, and local-only mode. A non-local member also needs `allow_non_local: true`.
212
+ - `quorum`: the minimum number of members that must return a valid answer.
213
+ - `max_calls`: the number of members to call. Members after this limit get the outcome `budget`.
214
+ - `agreement`: only `unanimous` is supported. Every member that answered must agree on every question.
215
+ - `noul_threshold` and `score_tolerance`: choice answers agree when the labels are equal. `noul` answers agree when all probabilities are on the same side of the threshold, and a probability equal to the threshold counts as true. Score answers agree when the highest and lowest scores differ by at most the tolerance. The server does not average probabilities, because the members' probabilities are not calibrated against each other.
216
+
217
+ Members run at the same time through the shared provider queues and share one deadline. A member that fails or times out does not stop the others, but cancellation stops all of them.
218
+
219
+ The result has `status`, `result` when the status is `agreed`, and one `members` entry per member with `provider`, `model`, `outcome` (`ok`, `budget`, or an error code), and the compact `answers` that were compared. If the members disagree, the status is `disagreed`, even when fewer than `quorum` members answered. Otherwise, fewer than `quorum` valid answers give `no_quorum`. When the members agree, `result` is the first valid member's response. Treat `disagreed` and `no_quorum` as a signal for review. The cache does not apply to consensus.
220
+
221
+ For action policy, each member's answers go through the policy profile's rules. A valid `block` from any member gives `block`, even if another member fails. An `allow` requires quorum and a valid `allow` from every attempted member. All other outcomes require review.
222
+
223
+ `engineering.action-risk.consensus@1` runs `d1-omni:600m` and `d3:4b` with a quorum of 2. Add both models to `OLLAMA_ALLOWED_MODELS`. On the action-policy held-out split, it met the action-policy acceptance criteria. See [Evaluation datasets and baselines](docs/evaluation.md#multi-model-consensus).
224
+
225
+ ### Consensus for live action policy
226
+
227
+ By default, `decision_action_policy` and the Codex hook use one model. To use a consensus profile instead, set `DECISION_ACTION_POLICY_CONSENSUS=engineering.action-risk.consensus@1` in the MCP server environment and restart the connection. The Pi integration does not read this setting.
228
+
229
+ - The server checks the profile at startup. The bundled consensus requires `engineering-default@1`, and its members must pass the provider, model, and locality rules. Before inference, discovery must confirm that each member is ready at its evaluated revision: `1ba59f63e836` for `d1-omni:600m` and `510b1771140e` for `d3:4b`. An unverified member does not run and cannot authorize the action. A verified member's block still wins.
230
+ - Consensus applies only when the caller names no `provider` and no `model`. A call that names either uses one model, as before.
231
+ - The result has `status`, `action`, `reasonCode` (such as `consensus_allow` or `consensus_disagreement`), `profile`, `consensus`, and one `members` entry per member. Codex hook results carry `profile`, `consensus`, and `reasonCode` in `decision-models/policy` metadata. Observation mode records the consensus result.
232
+ - When fewer than `quorum` members return a valid result, for example because Ollama is not running, the action is `review`. `DECISION_ACTION_POLICY_FAILURE_MODE` does not apply.
233
+ - A block from one member is a block, even when the other member asks for review. The three false blocks in the evaluation were all of this kind: `d1-omni:600m` blocked and `d3:4b` asked for review.
234
+ - The members run at the same time, so an action takes about as long as with `d3:4b` alone. That is about 2 seconds more than the `tev1:0.8b` baseline and well within the 25-second budget.
235
+
236
+ The setting is opt-in, and it is not the default, because the evidence is small. The held-out run had 1 false allow in 10 risky actions, exactly at the 0.1 limit, and one more false allow would fail. Re-run the comparison with a larger held-out split before you consider consensus as the default.
237
+
238
+ To benchmark a consensus profile, run `pnpm eval --dataset <jsonl> --consensus <id@version> --seed <integer> --out-dir <directory>` without `--provider` or `--model`. Action-policy records use conservative aggregation. Other records count `disagreed` and `no_quorum` as abstained items. The report adds a `consensus` object with the number of model calls and a count of each outcome.
239
+
240
+ Two flags exist only for evaluation. `--policy-providers <provider,...>` replaces the providers that the action-policy profile allows. `--full-policy-context` also treats the target as local, so a hosted provider gets the whole action and can allow. It needs `--policy-providers`. Use these flags only with synthetic datasets. The live server always applies the bundled profiles. The report records both settings in `policyProviders` and `fullPolicyContext`.
241
+
242
+ ## Decision telemetry
243
+
244
+ Telemetry is off by default. To turn it on, set `DECISION_TELEMETRY_FILE` to an absolute path for a regular file or a new file in the MCP server environment and restart the connection. Devices, FIFOs, and symlinks are not accepted. The server appends one JSON line to that file for each call to an inference tool: the decision tools, `decision_batch`, `decision_action_policy`, `decision_run`, `decision_cascade`, and `decision_consensus`. Local tools such as `decision_gate` and `decision_templates` record nothing.
245
+
246
+ Each event has `event`, `version`, a random `id`, `time`, `tool`, `status` (`ok` or `error`), and `latencyMs`. When they apply, it also has `errorCode`, `provider`, `model`, `template`, `profile`, `cascade`, `consensus`, `outcome`, `action`, `reasonCode`, `items` (the batch size), `cache`, and up to eight routing `attempts`. Each field must match a fixed list of values or a short identifier pattern. A value that does not match is left out.
247
+
248
+ Events never contain request state, tool input, answers, reasons, or error messages. Model names have passed the model allowlist, and the IDs of templates and profiles come from the installed registries.
249
+
250
+ The Codex hook records the policy outcome even when its response body only contains a permission decision. A handled timeout records `status: "error"` and `outcome: "failed"`. Routing attempts can appear in the event even when the tool returns an error.
251
+
252
+ - The server creates the file with owner-only permissions (`0600`). It does not change the permissions of an existing file.
253
+ - When the next line would make the file larger than `DECISION_TELEMETRY_MAX_BYTES` (default 10 MiB), the server renames it to `<file>.1` and shifts older files up. It keeps `DECISION_TELEMETRY_MAX_FILES` old files (default 3) and deletes older ones. This limits retention by size, not by age.
254
+ - Lines are written synchronously, so lines from concurrent calls do not interleave.
255
+ - If a write fails, the server writes one message to stderr and continues. Telemetry never changes a decision result.
256
+
257
+ The server has no OpenTelemetry exporter. An exporter would add dependencies that need a review first.
258
+
259
+ ## Provider readiness
260
+
261
+ `decision_providers` keeps the `id`, `description`, `ok`, and `detail` fields. `ok` is `true` when the provider endpoint answered the discovery request. Each provider also reports one `readiness` value:
262
+
263
+ | Readiness | Meaning |
264
+ | ------------------- | ------------------------------------------------------------------------------------------- |
265
+ | `ready` | The default model is available and supports decisions. |
266
+ | `not_configured` | The provider is inactive, or its settings prevent the default model from running. |
267
+ | `unreachable` | The provider did not respond within 2 seconds, or it returned a server error or rate limit. |
268
+ | `unauthenticated` | The provider rejected the credentials. |
269
+ | `model_missing` | The default model is not installed or not available to the account. |
270
+ | `model_unsupported` | Ollama lists the default model without the `decision` capability. |
271
+ | `unknown` | The checks could not prove readiness, for example when the model list has no capabilities. |
272
+
273
+ When the provider can list its models, the result includes `questionTypes` and a `models` list. The list contains only the models that the server accepts: the entries of `OLLAMA_ALLOWED_MODELS`, `TYPESAFE_ALLOWED_MODELS`, or `OPENCODE_GO_ALLOWED_MODELS`, or the default model when no allowlist is set. Each model has a `status` (`ready`, `missing`, `unsupported`, or `unknown`), a `locality` (`local`, `non-local`, or `unknown`), and a `default` flag. Ollama models also include their digest as `revision`. TypeSafe and OpenCode Go do not report revisions.
274
+
275
+ Discovery does not run inference or contact denied providers. Those providers remain in the list as inactive. In local-only mode, discovery omits non-local models. Ollama uses `GET /api/tags`. A model name without a tag matches the `latest` tag. Each server process reuses a discovery result for 10 seconds.
276
+
277
+ ## Versioned decision templates
278
+
279
+ The task-route, test-depth, compatibility, PR-risk, and security-sensitivity templates accept an optional `context` string.
280
+
281
+ | Template | Required state field | Decision |
282
+ | ------------------------------------ | -------------------- | ------------------------------------------------------------ |
283
+ | `engineering.task-route@1` | `task` | Choose the first work step for an engineering task. |
284
+ | `engineering.test-depth@1` | `change` | Choose the minimum verification depth for a proposed change. |
285
+ | `engineering.compatibility@1` | `change` | Classify the effect of a change on existing interface users. |
286
+ | `engineering.pr-risk@1` | `change` | Score the review risk of a proposed pull request. |
287
+ | `engineering.security-sensitivity@1` | `change` | Decide if a change needs security review. |
288
+ | `engineering.action-risk@1` | None | Assess the risk of a tool call for action policy. |
289
+
290
+ Call `decision_templates` to find an exact version and its URI. Use MCP `resources/read` with that URI to get the full JSON definition. To call `decision_run`, pass an explicit ID and version, plus state:
291
+
292
+ ```json
293
+ {
294
+ "template": { "id": "engineering.task-route", "version": 1 },
295
+ "state": { "task": "Explain the compiler diagnostics." }
296
+ }
297
+ ```
298
+
299
+ `decision_run` returns the template identity and a normal decision result. It accepts the same optional `provider` and `model` overrides as `decision_decide`. Pass the same `template` and `state` to `decision_validate` for a local check. A state mismatch returns `valid: false` from validation and a tool error from execution.
300
+
301
+ To add trusted definitions, set `DECISION_TEMPLATE_DIR` to a directory of JSON files and restart the server. Each definition requires `id`, a positive integer `version`, `description`, and `questions`. The optional `metadata` and `state_schema` fields are included in the resource definition. The supported state schema keywords cover primitive types, string length, nested object properties and required fields, and array items and length. Unknown keywords and duplicate ID/version pairs fail at startup. See the [bundled definitions](templates) for examples.
302
+
303
+ ## Decision evaluation
304
+
305
+ Run `pnpm eval --dataset <jsonl> --provider <provider> --model <model> --seed <integer> --out-dir <directory>` to write a new `report.json`. Add `--limit` to sample fewer rows. The seed ranks stable record IDs and gives the same sample order for the same IDs. The report includes the dataset SHA-256, runtime and counts. Supply `--revision`, `--device`, or `--warmth cold|warm` when known. Unknown revisions, devices, and provider costs appear as `null`. Unspecified warmth appears as `unknown`.
306
+
307
+ Each JSONL row has an `id`, `dataset_version`, `tags`, `state`, and `expected`. Use one dataset version per file.
308
+
309
+ - Use inline `questions` or a versioned `template` for a decision. Set `expected` to an object with `type` (`choice`, `noul`, or `score`), a named `question`, and a `value` (label, boolean, or score).
310
+ - Use a versioned `profile` for an action-policy case. Set `state` to `{"tool_name":"Bash","tool_input":{"command":"git status"}}` or the corresponding call. Set `expected` to an object with `type: "action"` and an `allow`, `review`, or `block` value. The runner uses the profile scope, provider restrictions, and data rules.
311
+
312
+ Accuracy uses evaluated rows, with exact scores and a 0.5 cutoff for `noul`. Macro F1 and the sparse confusion matrix use classification rows, with classes grouped by answer type. The report also includes effective accuracy, effective false allows, and PR-risk mean absolute error. These metrics penalize failures and abstentions. See [Evaluation datasets and baselines](docs/evaluation.md#decision-tasks) for the rules. Brier scores use returned probabilities, and top-label calibration uses ten confidence bins. Latency p50 and p95 use nearest ranks over evaluated rows. Metrics with no applicable observations are `null`. The report records predictions and error codes without saving raw state or upstream error messages.
313
+
314
+ Cascade benchmarks reject action records. Consensus action records must match the consensus template and any required policy profile. The runner checks every row before sampling.
315
+
316
+ CI runs deterministic [evaluation fixtures](eval/fixtures). Run live benchmarks separately with an installed model and approved data.
317
+
318
+ The [engineering datasets](eval/datasets) cover task routing, test depth, PR risk, security sensitivity, compatibility, and action policy. Each task has a development split and a held-out split. CI checks their integrity and split membership. See [Evaluation datasets and baselines](docs/evaluation.md) for the review rules, the acceptance criteria, and the recorded baseline results.
319
+
320
+ ## Local Ollama setup
321
+
322
+ ```bash
323
+ ollama pull d3:4b
324
+ # Also needed for the bundled cascade and consensus profiles
325
+ ollama pull strands-decider:2b
326
+ ollama pull d1-omni:600m
327
+ ```
328
+
329
+ Set:
330
+
331
+ ```bash
332
+ export DECISION_PROVIDER=ollama
333
+ export OLLAMA_BASE_URL=http://127.0.0.1:11434
334
+ export OLLAMA_DECISION_MODEL=d3:4b
335
+ pnpm run dev
336
+ ```
337
+
338
+ `decision_providers` reads the installed models from Ollama and reports whether each approved model is installed and supports decisions. See [Provider readiness](#provider-readiness).
339
+
340
+ The default model is `d3:4b`. Of the seven local models in the [evaluation](docs/evaluation.md), it had the best overall development results, and it was faster than `nimble:9b`. You can select any model that your Ollama server supports through `/v1/systemone`. When you set `OLLAMA_ALLOWED_MODELS`, add the model to that list.
341
+
342
+ An Ollama endpoint outside loopback requires HTTPS. For an existing trusted HTTP endpoint, set `OLLAMA_ALLOW_INSECURE_HTTP=true` explicitly or migrate the endpoint to HTTPS.
343
+
344
+ For local-only use, set `DECISION_LOCAL_ONLY=true`, use a loopback Ollama endpoint, and list approved local models in `OLLAMA_ALLOWED_MODELS`. The MCP server blocks TypeSafe, OpenCode Go, non-loopback Ollama endpoints and known cloud model names such as `clef:cloud`. Disable cloud features on the Ollama server itself to prevent forwarding through custom aliases. [Ollama cloud settings](https://docs.ollama.com/faq#how-do-i-disable-ollamas-cloud-features)
345
+
346
+ You can override the model in each model-facing MCP call. To allow provider overrides, list each permitted provider first, for example `export DECISION_ALLOWED_PROVIDERS=ollama,typesafe`. This `decision_classify` call selects another local model:
347
+
348
+ ```json
349
+ {
350
+ "provider": "ollama",
351
+ "model": "tev1:0.8b",
352
+ "state": "Fix the flaky unit test in auth.ts",
353
+ "labels": {
354
+ "simple": "Small local change",
355
+ "coding": "Needs repository edits or tests",
356
+ "research": "Needs external research"
357
+ },
358
+ "instructions": "Choose the best workflow."
359
+ }
360
+ ```
361
+
362
+ ## Official TypeSafe AI setup
363
+
364
+ Create an API key in the TypeSafe console and set `TYPESAFE_API_KEY` in your MCP host or local `.env`. The adapter sends the key to `https://api.typesafe.ai/v1/systemone` for inference and `https://api.typesafe.ai/v1/models` for discovery. [TypeSafe console](https://console.typesafe.ai/) · [TypeSafe API reference](https://api.typesafe.ai/redoc)
365
+
366
+ To keep Ollama as the default, set `DECISION_ALLOWED_PROVIDERS=ollama,typesafe` and pass `"provider": "typesafe"` when you want a hosted decision. A per-call `model` takes precedence over `TYPESAFE_DECISION_MODEL`, which defaults to `jev-latest`. Set `TYPESAFE_TIMEOUT_MS` to change the default 30-second timeout.
367
+
368
+ For TypeSafe, `decision_providers` calls `GET https://api.typesafe.ai/v1/models` with the same key and origin as inference. The call lists models and runs no inference. It reports a rejected key as `unauthenticated`, and `ok` is `false` when the key is rejected or the API cannot be reached.
369
+
370
+ If you used the former community provider, replace `jev` with `typesafe` in provider settings and tool calls. Remove the old `JEV_*` settings and use a key issued by TypeSafe AI.
371
+
372
+ ## OpenCode Go setup
373
+
374
+ [OpenCode Go](https://opencode.ai/docs/console/go) serves hosted decision models in the same System One format as TypeSafe. Create an API key in the [OpenCode Console](https://opencode.ai/console) with a Go subscription, and set `OPENCODE_GO_API_KEY` in the MCP server environment. To load it from a file, start the server with `node --env-file=/path/to/file dist/index.js`.
375
+
376
+ - Add `opencode-go` to `DECISION_ALLOWED_PROVIDERS`. A call then selects it with `"provider": "opencode-go"`, or you set `DECISION_PROVIDER=opencode-go`.
377
+ - `OPENCODE_GO_DECISION_MODEL` defaults to `jev-1.14`. `OPENCODE_GO_ALLOWED_MODELS` limits the models. The decision models are `jev-1.14`, `gemini-decision-1`, and `gpt-6-luna-decision`. Only `jev-1.14` has zero data retention.
378
+ - `OPENCODE_GO_TIMEOUT_MS` changes the 30-second timeout.
379
+ - The server sends the key only to the inference URL. `decision_providers` reads the public model list at `https://opencode.ai/inference/go/v1/models` without the key and reports only models of type `decision`.
380
+ - Every OpenCode Go model is non-local. Local-only mode rejects the provider. The bundled policy profiles do not list `opencode-go`, so action policy returns review before any request. For development results of `jev-1.14`, see [OpenCode Go Jev](docs/evaluation.md#opencode-go-jev).
381
+ - Decision models use the Go allowance at list price. A 401 means the key was rejected. A 403 means the key has no Go subscription.
382
+
383
+ ## Generic decision request
384
+
385
+ `decision_decide` uses the common System One-style shape:
386
+
387
+ ```json
388
+ {
389
+ "provider": "ollama",
390
+ "model": "d3:4b",
391
+ "state": {
392
+ "ticket": "I was charged twice. Refund the extra payment."
393
+ },
394
+ "questions": {
395
+ "team": {
396
+ "type": "choice",
397
+ "instructions": "Which team should handle this ticket?",
398
+ "criteria": {
399
+ "billing": "Payments and refunds",
400
+ "technical": "Bugs and integrations",
401
+ "other": "None of the above"
402
+ }
403
+ },
404
+ "refund": {
405
+ "type": "noul",
406
+ "instructions": "Does the customer explicitly ask for a refund?"
407
+ },
408
+ "urgency": {
409
+ "type": "score",
410
+ "instructions": "How urgent is this ticket?",
411
+ "criteria": ["Routine", "Soon", "Urgent"]
412
+ }
413
+ }
414
+ }
415
+ ```
416
+
417
+ Each provider answer must match the requested question type and include its decision value. A score can be fractional and ranges from zero to the number of rubric levels minus one. Confidence and probability maps are optional. When a choice or score probability map is present, it must cover all requested options or levels. The server returns an error for incomplete or invalid answers.
418
+
419
+ ## MCP host configuration
420
+
421
+ With the package installed globally, start the server with `verdict serve`:
422
+
423
+ ```json
424
+ {
425
+ "mcpServers": {
426
+ "decision-models": {
427
+ "command": "verdict",
428
+ "args": ["serve"],
429
+ "env": {
430
+ "DECISION_PROVIDER": "ollama",
431
+ "OLLAMA_DECISION_MODEL": "d3:4b"
432
+ }
433
+ }
434
+ }
435
+ }
436
+ ```
437
+
438
+ To run the server without a global install, use `npx`. The first start downloads the package:
439
+
440
+ ```json
441
+ {
442
+ "mcpServers": {
443
+ "decision-models": {
444
+ "command": "npx",
445
+ "args": ["-y", "@theoklitosbam7/verdict-kit", "serve"],
446
+ "env": {
447
+ "DECISION_PROVIDER": "ollama",
448
+ "OLLAMA_DECISION_MODEL": "d3:4b"
449
+ }
450
+ }
451
+ }
452
+ }
453
+ ```
454
+
455
+ From a source build, point your host at `dist/index.js` and provide environment variables:
456
+
457
+ ```json
458
+ {
459
+ "mcpServers": {
460
+ "decision-models": {
461
+ "command": "node",
462
+ "args": ["/absolute/path/to/tb-verdict-kit/dist/index.js"],
463
+ "env": {
464
+ "DECISION_PROVIDER": "ollama",
465
+ "OLLAMA_BASE_URL": "http://127.0.0.1:11434",
466
+ "OLLAMA_DECISION_MODEL": "d3:4b"
467
+ }
468
+ }
469
+ }
470
+ }
471
+ ```
472
+
473
+ To load a local `.env` file instead of listing settings under `env`, copy `.env.example` to `.env` and pass the file to Node.js before the script path:
474
+
475
+ ```json
476
+ {
477
+ "mcpServers": {
478
+ "decision-models": {
479
+ "command": "node",
480
+ "args": [
481
+ "--env-file=/absolute/path/to/tb-verdict-kit/.env",
482
+ "/absolute/path/to/tb-verdict-kit/dist/index.js"
483
+ ]
484
+ }
485
+ }
486
+ }
487
+ ```
488
+
489
+ Node.js supports `--env-file`. The project ignores `.env` in Git. Model request and provider response bodies are limited to 1 MiB, and provider redirects are rejected.
490
+
491
+ The bundled Codex and Claude Code hooks target the MCP registration named `decision-models`. If you register the server under a different name, update the hook's `server` field to match.
492
+
493
+ ### Move from direct `dist` paths to the package
494
+
495
+ | Before (source build) | With the installed package |
496
+ | ------------------------------------------- | ------------------------------------------------------------------------------------------- |
497
+ | `node /path/to/dist/index.js` | `verdict serve`, or `node <project>/node_modules/@theoklitosbam7/verdict-kit/dist/index.js` |
498
+ | `node /path/to/dist/cli.js <command>` | `verdict <command>` |
499
+ | `import ... from "/path/to/dist/public.js"` | `import ... from "@theoklitosbam7/verdict-kit"` |
500
+ | Pi `DECISION_ACTION_POLICY_MODULE` | `<project>/node_modules/@theoklitosbam7/verdict-kit/dist/public.js` (absolute path) |
501
+
502
+ The package exports only its root entry point, so `import "@theoklitosbam7/verdict-kit/dist/..."` fails. Import from `@theoklitosbam7/verdict-kit`.
503
+
504
+ ## SDK and CLI
505
+
506
+ The same decision engine runs without an MCP host.
507
+
508
+ ### SDK
509
+
510
+ Import `@theoklitosbam7/verdict-kit` (or `dist/public.js` from a source build). Importing it starts no server and writes nothing. The package includes type declarations.
511
+
512
+ ```ts
513
+ import { createDecisionEngine } from "@theoklitosbam7/verdict-kit";
514
+
515
+ const engine = createDecisionEngine({ env: process.env });
516
+ const { result } = await engine.run({
517
+ template: { id: "engineering.task-route", version: 1 },
518
+ state: { task: "Explain the compiler diagnostics." },
519
+ });
520
+ ```
521
+
522
+ `createDecisionEngine` reads its settings from `env` (default `process.env`) and fails with a `configuration` error when a setting is invalid. You can also pass a `registry`, `templates`, or `telemetry` sink. The engine has `decide`, `run`, `validate`, `templates`, `providers`, `actionPolicy`, and `createMcpServer`. Each method accepts the input of the matching MCP tool and returns the same object as the tool's `structuredContent`. Methods that call a model take an optional `{ signal }` for cancellation. Errors are `DecisionError` objects with a stable `code`.
523
+
524
+ ### CLI
525
+
526
+ ```bash
527
+ verdict run --input request.json
528
+ echo '{"template":{"id":"engineering.task-route","version":1},"state":{"task":"x"}}' \
529
+ | verdict validate
530
+ ```
531
+
532
+ From a source build, run `node dist/cli.js` in place of `verdict`.
533
+
534
+ The commands are `serve` (the MCP server on stdio), `decide`, `run`, `validate`, `providers`, and `templates`. `decide`, `run`, and `validate` read a JSON request from `--input <file>` or stdin, in the same shape as the MCP tool input. The CLI writes the result as JSON to stdout and diagnostics to stderr. It reads the same environment variables as the MCP server.
535
+
536
+ | Exit code | Meaning |
537
+ | --------- | ---------------------------------------------------------------------------------------------------- |
538
+ | 0 | Success. |
539
+ | 1 | Internal error. |
540
+ | 2 | Usage error, unreadable input, malformed JSON, or an invalid request. |
541
+ | 3 | Configuration error. |
542
+ | 4 | Provider or decision failure: timeout, transport, HTTP, invalid response, overload, or output limit. |
543
+ | 5 | `validate` found that the state does not match the template. The JSON reports `valid: false`. |
544
+ | 130 | Cancelled with SIGINT. |
545
+
546
+ `decide` and `run` exit 0 for every decision, including a `block` answer.
547
+
548
+ ## Coding-agent integrations
549
+
550
+ The repository includes integrations for current Codex CLI, Claude Code and Pi releases. [docs/compatibility.md](docs/compatibility.md) lists the checked versions and how each host applies a result.
551
+
552
+ - `integrations/codex/hooks.json` uses a Codex `PreToolUse` `mcp_tool` hook to send supported tool calls to `decision_action_policy`. The hook excludes the decision server itself to prevent recursion.
553
+ - `integrations/claude-code/hooks.json` uses a Claude Code `PreToolUse` `mcp_tool` hook with `output: "claude_code_pre_tool_use"`. A `review` result asks the user to confirm and a `block` result denies the call. The matcher selects only shell and file-edit tools, so the hook cannot evaluate its own call.
554
+ - `integrations/pi/decision-policy.ts` uses Pi's `tool_call` extension event. It blocks model-classified `block` actions and asks for confirmation on `review` when UI is available. `integrations/pi/decision-status.ts` loads the same extension and also shows each check in Pi's working line and footer.
555
+ - `.agents/skills/engineering-decisions/SKILL.md` is a portable Agent Skill that tells the agent when to use the decision templates. Pi and Codex discover it in `.agents/skills`, and Claude Code through the `.claude/skills` link.
556
+
557
+ See `integrations/codex/README.md`, `integrations/claude-code/README.md` and `integrations/pi/README.md` for setup.
558
+
559
+ The action policy is deliberately advisory. Keep the host's native permission and sandbox controls enabled.
560
+
561
+ ## Architecture
562
+
563
+ ```mermaid
564
+ flowchart TD
565
+ hosts["MCP hosts<br/>Codex hook, Pi extension, Claude Code, others"] -->|stdio| tools["MCP tools<br/>src/server.ts"]
566
+
567
+ tools --> localTools
568
+ tools --> modelTools
569
+
570
+ subgraph localTools["Local tools, no model call"]
571
+ gate["decision_gate<br/>allow, review, or block rules"]
572
+ tpl["decision_templates, decision_validate<br/>template registry"]
573
+ end
574
+
575
+ subgraph modelTools["Model-backed tools"]
576
+ decide["decision_decide, classify, boolean,<br/>score, batch, run"]
577
+ policy["decision_action_policy<br/>scope, profile, data rules,<br/>allow, review, or block"]
578
+ routed["decision_cascade, decision_consensus<br/>trusted routing profiles"]
579
+ end
580
+
581
+ modelTools --> core["Decision core<br/>cache, retries, fallback, provider queues"]
582
+ modelTools -.-> telemetry["Telemetry<br/>optional JSONL file"]
583
+ core --> registry["Provider registry<br/>allowlists, local-only mode, discovery"]
584
+ registry --> ollama["Ollama<br/>/v1/systemone"]
585
+ registry --> typesafe["TypeSafe<br/>api.typesafe.ai"]
586
+ registry --> go["OpenCode Go<br/>opencode.ai"]
587
+ ```
588
+
589
+ - `src/server.ts` defines the MCP tools and validates their input with the schemas in `src/schemas.ts`. `src/engine.ts` loads the startup settings once and serves the SDK, the CLI, and the MCP entry point `src/index.ts`.
590
+ - `src/decision.ts` is the decision core. It applies the optional cache, the retry and fallback plan from `src/routing/router.ts`, and the per-provider queues. The cache serves only the single-decision tools and `decision_run`.
591
+ - `src/routing/cascade.ts` and `src/routing/consensus.ts` run the trusted profiles in `config/routing`. Live action policy uses consensus only when `DECISION_ACTION_POLICY_CONSENSUS` selects a profile.
592
+ - `src/action-policy.ts` checks the scope in `src/policy/scope.ts`, applies the profile in `policies/`, and sends a hosted provider only the reduced view from `src/policy/payload.ts`. It then evaluates the answers locally.
593
+ - `src/providers/index.ts` selects the adapter and applies the provider and model allowlists. Each adapter sends requests to its own endpoint. TypeSafe and OpenCode Go share `src/providers/system-one.ts`.
594
+ - `src/telemetry/` appends one event per inference call when `DECISION_TELEMETRY_FILE` is set.
595
+
596
+ ## Add another provider
597
+
598
+ Implement `DecisionProvider` from `src/types.ts`:
599
+
600
+ ```ts
601
+ interface DecisionProvider {
602
+ readonly id: string;
603
+ readonly description: string;
604
+ readonly timeoutMs?: number;
605
+ decide(request: DecisionRequest): Promise<DecisionResponse>;
606
+ available(signal?: AbortSignal, deadlineAt?: number): Promise<ProviderStatus>;
607
+ }
608
+ ```
609
+
610
+ 1. Add the provider ID to `providerIds` in `src/config.ts`, and read its settings there. A hosted provider that uses the System One format can add an entry to `hostedSpecs` and build on the shared `SystemOneProvider` class, as `src/providers/opencode-go.ts` does.
611
+ 2. Register the provider in `src/providers/index.ts`.
612
+
613
+ `decide()` translates the common `state` and `questions` request into the provider API and normalizes the response to `DecisionResponse`. `available()` reports whether the endpoint answered. When the provider API can list models, it also returns a `readiness` value and the approved models. The server reports `unknown` readiness for a provider that omits it. Every provider other than Ollama counts as non-local, so local-only mode and action policy treat it as hosted.
614
+
615
+ ## Development
616
+
617
+ ```bash
618
+ pnpm run lint:check
619
+ pnpm run fmt:check
620
+ pnpm run typecheck
621
+ pnpm run build
622
+ pnpm test
623
+ pnpm run inspect
624
+ ```
625
+
626
+ To publish a new version, see [Releasing](docs/releasing.md).