@contentrain/decide 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.
package/README.md ADDED
@@ -0,0 +1,199 @@
1
+ # @contentrain/decide
2
+
3
+ Small typed decisions for migration and governance pipelines. A decision is a
4
+ pick from a closed set (a *choice*) or a place on a fixed rubric (a *score*) —
5
+ never generated text. It is asked of a chain:
6
+
7
+ ```
8
+ rule → cache → Jev (typesafe.ai) → LLM (Claude Haiku, opt-in) → the rule's tentative answer
9
+ ```
10
+
11
+ A deterministic rule answers first. Only what the rule leaves undecided goes to
12
+ a provider, each answer is cached by its shaped input, spending is capped per
13
+ tenant per day, a circuit breaker stops calling a failing provider, and every
14
+ decision lands in an audit log. No provider failure ever fails a call: the
15
+ decision falls back to the rule's answer, marked `unreviewed`.
16
+
17
+ ```bash
18
+ pnpm add @contentrain/decide
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```ts
24
+ import { createDecider, JsonlAuditLog, JsonlDecisionCache, MemoryDailyBudget } from '@contentrain/decide'
25
+
26
+ const decider = createDecider({
27
+ cache: new JsonlDecisionCache('.run/decision-cache.jsonl'),
28
+ audit: new JsonlAuditLog('.run/decisions.jsonl'),
29
+ budget: new MemoryDailyBudget(500),
30
+ })
31
+
32
+ const decision = await decider.decide('punch_item', {
33
+ label: '(aile: post)',
34
+ reason: 'en kötü sayfa 43.2 < 80 (5 sayfa ölçüldü)',
35
+ })
36
+
37
+ decision.choice // 'measurement'
38
+ decision.score // 2.03 — severity on the kind's 0–3 rubric
39
+ decision.confidence // 0–1
40
+ decision.source // 'rule' | 'jev' | 'llm' | 'cache'
41
+ decision.unreviewed // true when no provider answered
42
+ ```
43
+
44
+ `decideMany(kind, inputs)` batches: items of one kind share a request, and a
45
+ kind may group them further (`punch_item` sends one site per request, at most
46
+ 25 items, as PoC-1 did). Otherwise a request holds at most 32 items and stays
47
+ under ~32k tokens by a conservative estimate (`batch` option; a kind's own
48
+ limits win). Repeated inputs are asked once unless `fold: false`.
49
+ `decide(kind, input)` without a decider uses a
50
+ default one: built-in kinds, Jev when the token is set, an in-memory cache.
51
+
52
+ ## Jev
53
+
54
+ Jev is asked only when `CONTENTRAIN_JEW_API_TOKEN` is set in the environment.
55
+ The token is read at the moment of each request and goes straight into the
56
+ `Authorization` header; it is never stored on an object, logged, or put in an
57
+ error message. Requests go to one fixed endpoint,
58
+ `https://api.typesafe.ai/v1/systemone` — there is no base-URL option. Without a
59
+ token the chain answers from rules, and in-band decisions come back
60
+ `unreviewed`.
61
+
62
+ ## Input shaping
63
+
64
+ Every kind has a shaper, and the shaped input is the only thing that leaves the
65
+ process or reaches the cache key. It keeps what the decision needs and drops the
66
+ rest: `punch_item` drops the page link and turns URLs, e-mail addresses and
67
+ paths in the text into placeholders; `eligibility_band` keeps discovery counts
68
+ and drops the sampled records themselves. The audit log keeps the input's hash,
69
+ never the input.
70
+
71
+ The *request shape* is a hash of everything that forms a provider request: the
72
+ model, the batch limits, the header, the line format, the questions and their
73
+ criteria (`requestShapeHash(kind)`). It is part of every cache key and every
74
+ audit record, so a changed prompt never serves an answer given to the old one.
75
+
76
+ ## Kinds
77
+
78
+ | Kind | Answer | Rule | Provider |
79
+ |---|---|---|---|
80
+ | `punch_item` | class (`product_defect` · `source_limit` · `cosmetic` · `measurement`) + severity 0–3 | tentative class for run-report phrasings it recognises; never final, because a rule cannot place severity | Jev, with PoC-1's request word for word (site placeholders aside); **advisory** |
81
+ | `eligibility_band` | `eligible` · `access_blocked` · `page_only` · `custom_type`, or `needs_human` | mirrors Migrate's `judgeEligibility`; final outside the undecided band | Jev, in the band only |
82
+
83
+ The `eligibility_band` band is two cases: posts and custom-type entries within
84
+ a factor of two of each other, and a site with exactly one sampled post. A Jev
85
+ answer under 0.5 confidence becomes `needs_human`, with Jev's pick kept as
86
+ `proposed`. `needs_human` is derived only — it is never offered to Jev.
87
+
88
+ Pass `options.rule` to use your own rule (Migrate passes its verdict function),
89
+ or `null` to skip rules.
90
+
91
+ ## Cache, budget, breaker, audit
92
+
93
+ | Piece | Built in | Bring your own |
94
+ |---|---|---|
95
+ | Cache — key `sha256(kind, schema version, request shape, canonical shaped input)` | `MemoryDecisionCache`, `JsonlDecisionCache` | implement `DecisionCache` (a database store belongs to the host) |
96
+ | Budget — provider decisions per tenant per UTC day | `MemoryDailyBudget` | implement `DecisionBudget` |
97
+ | Circuit breaker — per provider, opens after 3 failed requests for 60s | `CircuitBreaker` | pass `breakers` |
98
+ | Audit — one record per decision: input hash, answer, confidence, source, time, tokens | `JsonlAuditLog` (`decisions.jsonl`), `MemoryAuditLog` | implement `AuditSink` |
99
+
100
+ Only provider answers are cached. A rule answer costs nothing to recompute, and
101
+ a fallback is not an answer anyone reviewed. A cache hit and a final rule answer
102
+ use no budget.
103
+
104
+ The budget and the breakers cover both providers. One daily cap is shared:
105
+ every item in a request that actually goes out spends from it, so an item Jev
106
+ failed on and Haiku then answered spends twice. An item behind an open breaker
107
+ spends nothing: during a Jev outage only Haiku's requests are charged. Each provider has its own breaker, and
108
+ an item behind Jev's open breaker goes on to Haiku.
109
+
110
+ Both providers report token usage. `cost` carries each decision's share of
111
+ its batch's tokens, and `usd` only when you price that provider:
112
+ `pricing: { jev: {…}, llm: { inputPerMTok, outputPerMTok } }`. Jev's vendor
113
+ publishes no price.
114
+
115
+ ## The LLM link: Claude Haiku
116
+
117
+ Haiku answers what Jev does not: Jev off, its breaker open, a timeout, an
118
+ error. It is opt-in: no model is called unless you wire it.
119
+
120
+ ```ts
121
+ import { createAnthropicProvider, createDecider } from '@contentrain/decide'
122
+
123
+ const decider = createDecider({
124
+ llm: createAnthropicProvider(), // claude-haiku-4-5-20251001, temperature 0
125
+ pricing: { llm: { inputPerMTok: 1, outputPerMTok: 5 } },
126
+ })
127
+ ```
128
+
129
+ The key is read from `ANTHROPIC_API_KEY` at the moment of each request, on the
130
+ same terms as Jev's token: never stored, logged or put in an error message.
131
+ Requests go only to `https://api.anthropic.com/v1/messages`. Haiku gets the
132
+ same shaped state and questions as Jev, as a prompt, and answers through one
133
+ forced tool call, so the answer is a structured record, not parsed prose.
134
+ `punch_item` sends the prompt AO-9 measured, word for word; other kinds get a
135
+ generic prompt built from their questions.
136
+
137
+ Its answers are cached under the same key as Jev's: an input answered once, by
138
+ either provider, is served from the cache after that, and `model` says which
139
+ one answered. A model reports no confidence of its own, so Haiku's answers
140
+ carry `confidence: 0` ("not measured"). For `eligibility_band` that means
141
+ every Haiku pick goes to `needs_human`, with the pick kept as `proposed`.
142
+
143
+ A host can wire another model instead: implement `DecisionProvider` with
144
+ `name: 'llm'` and pass it as `llm`. The default is `noopLlmProvider`, which is
145
+ never available.
146
+
147
+ ## Calibration
148
+
149
+ **`punch_item` is advisory. Jev does not answer the same request the same way
150
+ every time, so these answers are not stable: show them beside the item for a
151
+ person to confirm, never as a gate.**
152
+
153
+ `pnpm calibration:live` sends the PoC-1 set three times to Jev, exactly as
154
+ the package sends it: 272 punch items from 22 run reports, 40 of them labelled by
155
+ hand. It writes `calibration/<date>.json` with the model Jev reported, the
156
+ request-shape hash, and counts only. The gate is set to what Jev measurably
157
+ does. The median run must reach class agreement of at least 85% and severity
158
+ within one level of at least 90%, and at least 85% of the labelled items must
159
+ keep the same class in all three runs.
160
+
161
+ The latest file, `calibration/2026-09-18.json`, was measured on jev-1.13.0
162
+ with request shape `32da2187d1dc37d5`. It passes:
163
+
164
+ - class agreement: 34 / 35 / 33 of 40 across the runs, median 85.0%. That is exactly
165
+ the threshold.
166
+ - severity within one level: 37 / 37 / 37 of 40, median 92.5%.
167
+ - stable: 36/40 labelled items and 237/272 of all items.
168
+
169
+ The request sends placeholders for the site name, its URL and item links. That
170
+ keeps site identity out of the request and costs about two to three items of
171
+ severity agreement. A test holds the shipped request shape to the file's shape
172
+ hash, and requires the file to pass.
173
+
174
+ `pnpm calibration:live --provider haiku` runs the same set against Haiku
175
+ (`--provider both` runs both). It needs `ANTHROPIC_API_KEY`, is held to the
176
+ same gate, and writes `calibration/haiku/<date>.json` with Haiku's own request
177
+ shape (`anthropicRequestShapeHash`) and its cost at list price. Haiku is the
178
+ fallback, so its gate result is recorded for information and blocks nothing.
179
+ `calibration/haiku/2026-09-19.json` (claude-haiku-4-5-20251001, LLM request
180
+ shape `96aa1feb04caef9a`, $0.33 for the three runs) **fails** the gate:
181
+
182
+ - class agreement: 37 / 36 / 37 of 40, median 92.5%.
183
+ - severity within one level: 33 / 34 / 33 of 40, median 82.5%. This is
184
+ under the 90% gate. Haiku answers severity as a whole level, while Jev
185
+ answers a score between levels.
186
+ - stable: 39/40 labelled items and 259/272 of all items.
187
+
188
+ The PoC-1 set names real sites, so it stays outside this repository.
189
+ `CONTENTRAIN_DECIDE_POC1_DIR` points the script and the tests at it.
190
+
191
+ The tests replay recorded answers through the full decider
192
+ (`createReplayFetch`). That checks the code path: shaping, grouping,
193
+ batching, reading and scoring. It does not measure the model.
194
+ `measurePunchCalibration(labels, decisions)` scores `punch_item` the way
195
+ PoC-1 did.
196
+
197
+ ## License
198
+
199
+ MIT