Domain capability
Business-domain capabilities in the kit, grouped by domain: sales, marketing, commerce and payments, travel, voice and vision, and operations, with the shared pattern they follow.
A business capability knows the rules of one job, such as routing a lead, allocating commission, planning stock, reviewing a payment or scoring a vacancy against a profile. It is not a general agent. Each package implements a deterministic workflow with typed records and usually an append-only SQLite ledger. If a model can help, the caller injects a Scorer, Proposer or writer; the package checks what comes back before using it.
No package in this layer is core. Three are supported (fit_scoring, stage_pipeline, rendered_docs) because other projects use them; the rest are catalog. That is a statement about use, not quality: a catalog package is kept, documented and tested, and you pick it up when you have its problem.
Where the layer starts and stops
| A domain capability owns | It leaves to the application |
|---|---|
| The rules and records of one kind of work (plans, stages, quotes, ledgers) | Policy values: rates, tiers, thresholds, weights, SLAs, prices |
| State machines, idempotency keys and append-only history | Which people or roles may approve, and how they authenticate |
| A validated seam for a model or an outside processor | The model, the prompt and the live payment or booking provider |
| Recorded stand-ins so the workflow runs offline | The decision to enable a live route |
Packages in this layer compose lower layers rather than replacing them. Approvals come from the harness, durable runs from the harness RunStore, and storage from the Data platform layer. Nothing here is a model-driven agent by itself: the packages are deterministic workflows, and a model decision only enters through a seam you supply.
How a capability is shaped
Three habits repeat across the layer.
- Propose, then approve. A signal, a model answer or an inbound email produces a proposal with citations. Nothing changes until a person applies it.
- Append-only history. Ledgers refuse
UPDATEandDELETEwith triggers. The current state is computed from the events. - Idempotent, exact writes. Writes carry an idempotency key derived from the host action and are refused unless an approval binds to the exact payload.
Owners by domain
Import paths are recohut_kit.<name>. Tier is supported (S) or catalog (C).
Sales and customer relationships
| Package | Tier | What it is for |
|---|---|---|
fit_scoring | S | Score any item (vacancy, lead, vendor answer, RFP) against a profile under a weighted rubric with hard gates. Evidence must be a verbatim substring; any failed gate vetoes; scores aggregate as exact fractions. |
stage_pipeline | S | Opportunity stage machine with final and user-only stages, an append-only ledger, inbound signals turned into cited proposals, draft-only follow-ups and a funnel computed from events. |
crm_routing | C | Lead intake with duplicate detection, ordered routing rules, capacity-weighted round robin with a persisted cursor, and a first-response SLA clock. |
commissions | C | Versioned plans with effective dates, credit splits that must total 100, marginal or retroactive tiers, clawbacks into the next open period, hashed immutable statements. |
sequences | C | Durable follow-up sequences for one record: enrol once, waits as harness deadlines, a reply stops the enrolment, a ledger prevents blind resends. |
commitments | C | A client-success commitments ledger with an enforced status machine and overdue scans. |
Marketing and content
| Package | Tier | What it is for |
|---|---|---|
marketing | C | Metric definitions, a SQLite star schema with idempotent loading, anomaly detectors, scheduled reports with cited insights. |
attribution | C | Multi-touch attribution: journeys with a lookback window, six credit models in integer cents, recorded conversion payloads. |
content | C | Brand-voice and claim checks, an approval-gated content calendar, repurposing one asset into channel drafts. |
creative | C | Versioned brand kits, approved prompt templates, a recorded lane for generation tasks, and inspection receipts for generated assets. |
drafting | C | An approval-gated ledger for outgoing messages with a claim and PII guard and a send queued only after exact approval. |
reporting | C | A metric registry, report specs with schedule and audience, freshness and quality gates, row-cited values and approval-gated distribution. |
Commerce, inventory and payments
| Package | Tier | What it is for |
|---|---|---|
payments | C | A signed approval bound to one itemised payment, a single-use approval in an append-only ledger, idempotency keys and reconciliation. The bundled processor is an in-process recorded stand-in. |
shopify_admin | C | Admin GraphQL tooling: cost-aware throttling, cursor pagination, bulk operations and a webhook inbox that handles each delivery once. |
inventory_planning | C | Reorder points and safety stock from a service level, purchase suggestions that honour pack rules, and a FIFO backorder book. |
Travel and bookings
| Package | Tier | What it is for |
|---|---|---|
booking | C | Search and retrieve reads; quote, hold, book, change and cancel writes, each refused without an approval that matches the quote digest and recorded before dispatch. |
trip_plans | C | Multi-leg proposals with priced, expiring, dependency-ordered writes, a plan-level policy gate and compensation on failure. |
places | C | Travel time between places from a recorded routing transcript, with a labelled fallback estimate. |
signals | C | Signed, deduplicated change signals, a watermark poll feed and a recovery proposal that never executes. |
Voice and vision
| Package | Tier | What it is for |
|---|---|---|
voice | C | Voice-turn contracts that share the chat turn id, a push-to-talk runner (speech to text, an injected model callable, text to speech) and per-stage latency budgets. |
vision | C | Contracts and pure-Python metrics for caller-trained image classifiers and detectors, with per-class thresholds and a review queue. |
Operations, analysis and documents
| Package | Tier | What it is for |
|---|---|---|
rendered_docs | S | Checks for generated documents that must parse in downstream systems: template manifests with a compile gate, format-aware escaping, PDF text-layer and layout checks. |
automation_ops | C | An SLA-timed exception queue, KPIs from run history, and approval before a versioned workflow changes. |
process_assessment | C | Reads an event log to show variants, handoffs and bottlenecks, and writes a citation-backed automation backlog. |
org_graph | C | Expertise and co-work graphs from activity rows, with key-person risk. |
change_sentinel | C | Flags reversals and reopened decisions in decision chains and drafts per-person follow-ups. |
tool_fit | C | Evidence-backed tool selection where every statement in the decision record must cite a fact. |
Worked examples
All three run offline with the standard library plus the kit. Names and figures are synthetic.
Score an item under a rubric, with a gate
A scorer proposes dimension scores with evidence quotes. validate checks each quote is a verbatim substring of the item or a profile fact, aggregates the weights exactly, and applies the gates. A failed gate vetoes the item whatever its score.
from recohut_kit.fit_scoring import (
Band,
Dimension,
DimensionScore,
GateSpec,
GateVerdict,
Item,
Profile,
ProposalRejected,
Quote,
Rubric,
ScoreProposal,
validate,
)
RUBRIC = Rubric(
"fit",
"1",
(Dimension("technical", "0.6", ""), Dimension("career", "0.4", "")),
(Band("strong", 75), Band("weak", 0)),
(GateSpec("language", ""),),
)
ITEM = Item("item-1", "Platform role using Spark and Kubernetes. Fluent Finnish required.")
PROFILE = Profile("subject-1", {"f1": "Ran Spark pipelines for six years."})
def proposal(quote: str, language: str = "pass") -> ScoreProposal:
return ScoreProposal(
"item-1",
(
DimensionScore("technical", 90, (Quote(quote), Quote("Spark pipelines", "f1"))),
DimensionScore("career", 80, (Quote("Platform role"),)),
),
(GateVerdict("language", language, "Fluent Finnish required" if language != "pass" else None),),
("Spark experience",),
("kubernetes",),
"rule:test",
)
ok = validate(proposal("Spark and Kubernetes"), ITEM, PROFILE, RUBRIC)
print(ok.score, ok.band, ok.vetoed) # 86 strong False
vetoed = validate(proposal("Spark and Kubernetes", "fail"), ITEM, PROFILE, RUBRIC)
print(vetoed.score, vetoed.band, vetoed.vetoed_by) # 86 strong ('language',)
try:
validate(proposal("spark and kubernetes"), ITEM, PROFILE, RUBRIC) # wrong case
except ProposalRejected as rejected:
print(rejected.code) # quote_not_verbatimscore_item(scorer, item, profile, rubric) does the same with a scorer object in front: it asks the scorer, then validates. RuleScorer is a keyword-based scorer that needs no model.
Turn an inbound signal into a proposal that a person applies
The classifier reads an inbound message and proposes a stage change. The ledger holds the proposal until a person applies or rejects it. A proposal that was altered after it was issued is refused.
from pathlib import Path
from recohut_kit.stage_pipeline import (
OpportunityAlias,
PipelineLedger,
RuleClassifier,
Signal,
StageMachine,
StageRule,
propose,
)
machine = StageMachine.declare(
["draft", "applied", "interview", "rejected"],
{"draft": ["applied"], "applied": ["interview", "rejected"], "interview": ["rejected"]},
finals=["rejected"],
)
ledger = PipelineLedger(Path("pipeline.sqlite"), machine)
ledger.open("acme", actor="human:me", evidence_ref="e1", at=1.0, stage="applied")
classifier = RuleClassifier(
[StageRule("interview", ("interview invitation",))],
[OpportunityAlias("acme", ("Acme",))],
)
signal = Signal("s1", 2.0, "hr@acme.example", "Acme interview invitation", "ref1")
batch = propose([signal], ledger, classifier)
proposal = batch.proposals[0]
print(proposal.to_stage) # interview
print([p.proposal_id for p in ledger.pending_proposals()] == [proposal.proposal_id]) # True
ledger.apply_proposal(proposal, actor="human:me", at=3.0, decision_ref="d1")Nothing moved before apply_proposal. ledger.reject_proposal(...) records a rejection instead, and stage_pipeline.followups.stale_sweep(ledger, now=..., quiet_days=60) proposes a stage for records that went quiet.
Credit commissions and claw back a refund in the next period
Closed periods are sealed with a content hash. A refund after close posts a negative line to the next open period and leaves the sealed statement unchanged.
from datetime import UTC, date, datetime
from fractions import Fraction
from zoneinfo import ZoneInfo
from recohut_kit.commissions import (
CommissionLedger,
CommissionPlan,
Order,
OrderEvent,
PlanBook,
Split,
Tier,
)
plan = CommissionPlan(
"desk", 1, date(2026, 7, 1), None, "AUD", (Tier(0, Fraction(4, 100)),), mto_earning="on_deposit"
)
ledger = CommissionLedger(
PlanBook((plan,), {"rep-a": "desk", "rep-b": "desk"}),
timezone=ZoneInfo("Australia/Sydney"),
currency="AUD",
)
placed = datetime(2026, 9, 10, 1, tzinfo=UTC)
ledger.register_order(
Order("o-1", "saddle", 689000, "AUD", True, (Split("rep-a", 60), Split("rep-b", 40)), placed)
)
ledger.post(OrderEvent("e-dep", "o-1", "payment", placed, 206700, "deposit"))
september = ledger.close("2026-09", now=datetime(2026, 10, 1, 1, tzinfo=UTC))
print({s.rep_id: s.commission_total_minor for s in september})
# {'rep-a': 16536, 'rep-b': 11024}
refund_at = datetime(2026, 10, 6, 1, tzinfo=UTC)
ledger.post(OrderEvent("e-ref", "o-1", "refund", refund_at, 206700))
ledger.post(OrderEvent("e-can", "o-1", "cancel", refund_at))
october = ledger.close("2026-10", now=datetime(2026, 11, 1, 1, tzinfo=UTC))
print({s.rep_id: (s.commission_total_minor, s.payable_minor) for s in october})
# {'rep-a': (-16536, 0), 'rep-b': (-11024, 0)}Amounts are integer minor units (cents). Splits must total 100, with leftover cents assigned by largest remainder. ledger.statement(rep_id, "2026-09").verify() re-checks a sealed statement against its hash.
Choosing between owners
| You need | Use | Notes |
|---|---|---|
| Rank vacancies, leads, vendor answers or RFPs against a profile | fit_scoring | Inject a Scorer; the validator rejects any score without verbatim evidence. |
| Track an opportunity through stages from email and calendar signals | stage_pipeline | Proposals only; a person applies them. |
| Route leads and measure first response | crm_routing | A rules engine with a persisted cursor; routing rules are data. |
| Pay people from orders | commissions | Plans are versioned by effective date; periods seal. |
| Take money or book a trip | payments, booking, trip_plans | Each write needs an approval bound to the exact payload. Start on the recorded processor. |
| Plan stock | inventory_planning | Stock-out days are not zero demand. |
| Report metrics on a schedule | reporting or marketing | reporting is general; marketing ships marketing metric definitions. |
| Prove a generated document will parse downstream | rendered_docs | Compile gate, text-layer and layout checks. |
Failure behaviour, limits and gotchas
- Proposals are not actions. A proposal changes nothing until
apply_proposalor the equivalent approval call. A forged or edited proposal raisesPipelineRefusedand the real one stays pending. - Idempotency is part of the write. Booking, payment and sequence writes carry an idempotency key and refuse a second use of a single-use approval. The key exists so a retry does not repeat the effect.
- Policy lives with you. The packages do not ship rates, tiers, thresholds or SLAs as defaults for your business. Pass them in, and version them.
- Validation can reject a good model answer.
fit_scoringrefuses a quote that differs by case. That is intended: the evidence must be checkable against the item text. - Recorded lanes are not live proof. Recorded transports, stand-in processors and scripted examples show the workflow, not the behaviour of a real vendor, bank or carrier. The live route of each connector is off by default.
- Pydantic is required by some packages.
paymentsand some other packages import pydantic at load time; install thepydanticextra. - Domain names in docs are examples. Notebook sets use synthetic data. Treat the packages as generic building blocks and adapt the vocabulary to your own domain.
How is this page?
Last updated on