@contentrain/decide

中文文档
0.2.64发布于 2026/11/04MITTypeScriptES Module构建来源已验证近 30 天下载 4430

Small typed decisions for migration and governance pipelines — rule first, then Jev, then Claude Haiku, cached, budgeted and audited

原始使用文档
文档目录9 节
  1. Usage
  2. Jev
  3. Input shaping
  4. Kinds
  5. Cache, budget, breaker, audit
  6. The LLM link: Claude Haiku
  7. Calibration
  8. Part of the Contentrain ecosystem
  9. License

@contentrain/decide

Small typed decisions for migration and governance pipelines. A decision is a pick from a closed set (a choice) or a place on a fixed rubric (a score) — never generated text. It is asked of a chain:

rule  →  cache  →  Jev (typesafe.ai)  →  LLM (Claude Haiku, opt-in)  →  the rule's tentative answer

A deterministic rule answers first. Only what the rule leaves undecided goes to a provider, each answer is cached by its shaped input, spending is capped per tenant per day, a circuit breaker stops calling a failing provider, and every decision lands in an audit log. No provider failure ever fails a call: the decision falls back to the rule's answer, marked unreviewed.

pnpm add @contentrain/decide

Usage

import { createDecider, JsonlAuditLog, JsonlDecisionCache, MemoryDailyBudget } from '@contentrain/decide'

const decider = createDecider({
  cache: new JsonlDecisionCache('.run/decision-cache.jsonl'),
  audit: new JsonlAuditLog('.run/decisions.jsonl'),
  budget: new MemoryDailyBudget(500),
})

const decision = await decider.decide('punch_item', {
  label: '(aile: post)',
  reason: 'en kötü sayfa 43.2 < 80 (5 sayfa ölçüldü)',
})

decision.choice      // 'measurement'
decision.score       // 2.03 — severity on the kind's 0–3 rubric
decision.confidence  // 0–1
decision.source      // 'rule' | 'jev' | 'llm' | 'cache'
decision.unreviewed  // true when no provider answered

decideMany(kind, inputs) batches: items of one kind share a request, and a kind may group them further (punch_item sends one site per request, at most 25 items, as PoC-1 did). Otherwise a request holds at most 32 items and stays under ~32k tokens by a conservative estimate (batch option; a kind's own limits win). Repeated inputs are asked once unless fold: false. decide(kind, input) without a decider uses a default one: built-in kinds, Jev when the token is set, an in-memory cache.

Jev

Jev is asked only when CONTENTRAIN_JEW_API_TOKEN is set in the environment. The token is read at the moment of each request and goes straight into the Authorization header; it is never stored on an object, logged, or put in an error message. Requests go to one fixed endpoint, https://api.typesafe.ai/v1/systemone — there is no base-URL option. Without a token the chain answers from rules, and in-band decisions come back unreviewed.

Input shaping

Every kind has a shaper, and the shaped input is the only thing that leaves the process or reaches the cache key. It keeps what the decision needs and drops the rest: punch_item drops the page link and turns URLs, e-mail addresses and paths in the text into placeholders; eligibility_band keeps discovery counts and drops the sampled records themselves. The audit log keeps the input's hash, never the input.

The request shape is a hash of everything that forms a provider request: the model, the batch limits, the header, the line format, the questions and their criteria (requestShapeHash(kind)). It is part of every cache key and every audit record, so a changed prompt never serves an answer given to the old one.

Kinds

KindAnswerRuleProvider
punch_itemclass (product_defect · source_limit · cosmetic · measurement) + severity 0–3tentative class for run-report phrasings it recognises; never final, because a rule cannot place severityJev, with PoC-1's request word for word (site placeholders aside); advisory
eligibility_bandeligible · access_blocked · page_only · custom_type, or needs_humanmirrors Migrate's judgeEligibility; final outside the undecided bandJev, in the band only
field_typestring · text · markdown · richtext · relation · url · select, limited per item to the options the fact pack offersfinal for clear lengths (≤ 100 chars → string, ≥ 200 → text) and for many instances with ≤ 3 values (select); tentative otherwiseJev, one request per option set
region_namehero · card-grid · faq · cta · … (18 section roles)tentative from class, builder and child hints; content at 0.3 when nothing matchesJev
unmapped_elementan astro-kit component id, prose, or site-specificfinal (0.9) when the element name says it (*-carousel → slider, *toggle → faq, *heading → prose); tentative site-specific otherwiseJev, one request per builder; under 0.5 confidence → site-specific

The last three are Migrate v3's fact-pack leftovers: everything else about a site's structure is settled deterministically before them. Their inputs come already shaped by the fact pack, and these shapers scrub again: box sizes are rounded, text is cut and scrubbed, and element and class names are reduced to slugs.

The eligibility_band band is two cases: posts and custom-type entries within a factor of two of each other, and a site with exactly one sampled post. A Jev answer under 0.5 confidence becomes needs_human, with Jev's pick kept as proposed. needs_human is derived only — it is never offered to Jev.

Pass options.rule to use your own rule (Migrate passes its verdict function), or null to skip rules.

Cache, budget, breaker, audit

PieceBuilt inBring your own
Cache — key sha256(kind, schema version, request shape, canonical shaped input)MemoryDecisionCache, JsonlDecisionCacheimplement DecisionCache (a database store belongs to the host)
Budget — provider decisions per tenant per UTC dayMemoryDailyBudgetimplement DecisionBudget
Circuit breaker — per provider, opens after 3 failed requests for 60sCircuitBreakerpass breakers
Audit — one record per decision: input hash, answer, confidence, source, time, tokensJsonlAuditLog (decisions.jsonl), MemoryAuditLogimplement AuditSink

Only provider answers are cached. A rule answer costs nothing to recompute, and a fallback is not an answer anyone reviewed. A cache hit and a final rule answer use no budget.

The budget and the breakers cover both providers. One daily cap is shared: every item in a request that actually goes out spends from it, so an item Jev failed on and Haiku then answered spends twice. An item behind an open breaker spends nothing: during a Jev outage only Haiku's requests are charged. Each provider has its own breaker, and an item behind Jev's open breaker goes on to Haiku.

Both providers report token usage. cost carries each decision's share of its batch's tokens, and usd only when you price that provider: pricing: { jev: {…}, llm: { inputPerMTok, outputPerMTok } }. Jev's vendor publishes no price.

Haiku answers what Jev does not: Jev off, its breaker open, a timeout, an error. It is opt-in: no model is called unless you wire it.

import { createAnthropicProvider, createDecider } from '@contentrain/decide'

const decider = createDecider({
  llm: createAnthropicProvider(), // claude-haiku-4-5-20251001, temperature 0
  pricing: { llm: { inputPerMTok: 1, outputPerMTok: 5 } },
})

The key is read from ANTHROPIC_API_KEY at the moment of each request, on the same terms as Jev's token: never stored, logged or put in an error message. Requests go only to https://api.anthropic.com/v1/messages. Haiku gets the same shaped state and questions as Jev, as a prompt, and answers through one forced tool call at temperature 0, so the answer is a structured record, not parsed prose. A Claude 4.7 or later model (model option) takes neither a non-default temperature nor, on Opus and Sonnet 5.5, a forced tool call; it is asked through structured outputs, with the same prompt and an equivalent JSON schema. punch_item sends the prompt AO-9 measured, word for word; other kinds get a generic prompt built from their questions.

Its answers are cached under the same key as Jev's: an input answered once, by either provider, is served from the cache after that, and model says which one answered. A model reports no confidence of its own, so Haiku's answers carry confidence: 0 ("not measured"). For eligibility_band that means every Haiku pick goes to needs_human, with the pick kept as proposed.

A host can wire another model instead: implement DecisionProvider with name: 'llm' and pass it as llm. The default is noopLlmProvider, which is never available.

Calibration

punch_item is advisory. Jev does not answer the same request the same way every time, so these answers are not stable: show them beside the item for a person to confirm, never as a gate.

pnpm calibration:live sends the PoC-1 set three times to Jev, exactly as the package sends it: 272 punch items from 22 run reports, 40 of them labelled by hand. It writes calibration/<date>.json with the model Jev reported, the request-shape hash, and counts only. The gate is set to what Jev measurably does. The median run must reach class agreement of at least 85% and severity within one level of at least 90%, and at least 85% of the labelled items must keep the same class in all three runs.

The latest file, calibration/2026-09-18.json, was measured on jev-1.13.0 with request shape 32da2187d1dc37d5. It passes:

  • class agreement: 34 / 35 / 33 of 40 across the runs, median 85.0%. That is exactly the threshold.
  • severity within one level: 37 / 37 / 37 of 40, median 92.5%.
  • stable: 36/40 labelled items and 237/272 of all items.

The request sends placeholders for the site name, its URL and item links. That keeps site identity out of the request and costs about two to three items of severity agreement. A test holds the shipped request shape to the file's shape hash, and requires the file to pass.

pnpm calibration:live --provider haiku runs the same set against Haiku (--provider both runs both). It needs ANTHROPIC_API_KEY, is held to the same gate, and writes calibration/haiku/<date>.json with Haiku's own request shape (anthropicRequestShapeHash) and its cost at list price. Haiku is the fallback, so its gate result is recorded for information and blocks nothing. calibration/haiku/2026-09-19.json (claude-haiku-4-5-20251001, LLM request shape 96aa1feb04caef9a, $0.33 for the three runs) fails the gate:

  • class agreement: 37 / 36 / 37 of 40, median 92.5%.
  • severity within one level: 33 / 34 / 33 of 40, median 82.5%. This is under the 90% gate. Haiku answers severity as a whole level, while Jev answers a score between levels.
  • stable: 39/40 labelled items and 259/272 of all items.

The PoC-1 set names real sites, so it stays outside this repository. CONTENTRAIN_DECIDE_POC1_DIR points the script and the tests at it.

The tests replay recorded answers through the full decider (createReplayFetch). That checks the code path: shaping, grouping, batching, reading and scoring. It does not measure the model. measurePunchCalibration(labels, decisions) scores punch_item the way PoC-1 did.

Part of the Contentrain ecosystem

Contentrain is a content governance ecosystem for teams and AI agents; agents work on the content through the MCP server. This package is one of the open-source tools (docs). The other parts: Studio for team review and roles, Migrate for moving WordPress sites to Astro, and Bridge, a free WordPress plugin that exports a site as a Contentrain store.

License

MIT

版本与发布记录

@contentrain/decide 共发布 70 个版本,首次发布于 2026/09/21;过去 12 个月发布了 70 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.64latest2026/11/046 天前
0.2.632026/10/3110 天前
0.2.622026/10/3110 天前
0.2.612026/10/3011 天前
0.2.602026/10/2813 天前
0.2.592026/10/2814 天前

关于 @contentrain/decide 的常见问题

@contentrain/decide 是什么?

Small typed decisions for migration and governance pipelines — rule first, then Jev, then Claude Haiku, cached, budgeted and audited

如何安装 @contentrain/decide?

在项目目录运行 npm install @contentrain/decide,或使用 pnpm add / yarn add / bun add。

@contentrain/decide 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@contentrain/decide 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@contentrain/decide 可以商用吗?

@contentrain/decide 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@contentrain/decide 的下载量有多少?

根据 npm 官方下载统计,@contentrain/decide 在 2026/10/11 – 2026/11/09 这 30 天内被下载 4,430 次,日均约 148 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@contentrain/decide 还在维护吗?

最新版本 0.2.64 发布于 2026/11/04(6 天前);至今共发布 70 个版本,其中过去 12 个月发布了 70 个;首次发布于 2026/09/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。