Skip to content

solvi.solutions.knowledge

solvi.Knowledge: the knowledge store, the agenda, the action model and the failure memory behind one object that solvi.build, solvi.Guard and solvi.Agent share. See Using solvi: agents and knowledge.

Knowledge.redecide(storage, decide, affected=[...], valid_at_key="date") reconsiders decisions using current knowledge at each decision input's explicitly named world date. Tell the replacement with its validity interval and retain the earlier assertion for dates where it was valid. Global retraction removes that support and is a different operation. The method preserves snapshot query scope and prepares all selected dates/snapshots before running callbacks.

It returns answer_changes and justification_only, without saving new decisions. Each side is evaluated by the current callable or System: the old side reruns that callable on the historical snapshot, rather than loading the historical model's prediction. Callbacks retain their external effects. Dates must be canonical ISO dates or date objects; outputs must be finite JSON values. System Unknown answers carry an explicit marker plus old_unknown_paths / new_unknown_paths, distinguishing them from literal JSON with the same marker shape. Ordinary retract and the low-level historical counterfactual default remain available.

km.branch(path=None) creates an independent writable what-if at the current state. Facts, write gates, writer/reassert permissions, agenda callbacks, native action model and failure memory are copied; writes never change the parent or another branch. Custom action models are refused before destination writes. Python callbacks retain access to their external state; branching does not snapshot their closure or external services. There is no merge.

km.store.branch(storage=None, upto=None) also supports a historical journal prefix (upto is a record count). A journal note records the parent head and original selected prefix hash. The optional destination must be empty. Physical destination hashes are newly assigned; the lineage note identifies the inherited history rather than claiming it was observed again. Persistent branches containing inherited verified/of decision references are refused before creating the destination, because decision proofs are not exported. Source/write gates remain active.

Reopen a persistent branch with the normal Knowledge/KnowledgeStore constructor and the same explicit writers, gates, clock and native vocabulary configuration. Journal replay restores knowledge; Python policy, agenda callbacks and volatile failure-memory state are not serialized. The returned live branch preserves those runtime objects independently. A bare reopen is not a policy/configuration export. Use the low-level store prefix API for historical branches; the facade branches only its current runtime state.

Knowledge: what a system learned, from whom, and what rests on it — one object a decision system, a guard and an environment agent share.

import solvi

km = solvi.Knowledge("knowledge.jsonl", vocabulary={"here": lambda s, a: s["here"]})
km.tell({"s": "c17", "r": "tier", "o": "vip"}, source="person", by="crm")      # a fact, with its source
km.goal("wood", done=lambda s: s["wood"] > 0)                                 # an agenda goal: done is code
km.agenda.gate("tool_first", lambda s: s["pickaxe"], blocks=["collect_stone"])  # a gate: a hard check
km.observe(state, "collect_wood", outcome)        # an environment step: action model, map facts, agenda, skills
km.retract(item_id, why="wrong label")            # with everything derived from it
km.report()

A facade over the low level (solvi.core.knowledge): store is the KnowledgeStore (the hash-chained journal: facts, rules, skills, actions, episodes, with provenance, disputes to a person and the exact retraction cascade), agenda the Agenda (goals with done checks in code, gates, order — in the same journal), actions the action model (ConservativeActionModel over vocabulary, or one of your own with actions=, or None), failures the failure memory (FailureMemory, with failures=True or its settings as a dict; None by default).

Who reads it: solvi.build(..., knowledge=km) gives every decision km.snapshot() as the fact "knowledge" (a rule reads it with Knowledge.value(knowledge, s, r)); solvi.Guard(..., knowledge=km) turns the action model's refusals and the agenda's gates into hard checks on tool calls; solvi.Agent(env, knowledge=km) acts on it in an environment and writes what it observes back. Knowledge never comes from the system's own unverified answers: the store's source check refuses them (sources "person", "outcome", "spec", or "verified" with the stored decision it comes from).

Map facts. observe(..., at=, to=, map=) writes what an environment showed as facts scoped to one map: "leads_to " (from the key at, the action led to the key to) and "accepts " (taken or refused there). They are carried to the next episode on the same map as they are — and dropped by the first contradiction: an arrival that contradicts a fact learned in an earlier episode raises a flag on the map's scope (KnowledgeStore.flag), so every older map fact is a hint, not a fact, until an observation confirms it again. Rules (the action model, the skills) are carried across maps. A skill is a confirmed route of a goal: the action after which the goal's done check turned true, written as a "skill" item (source "outcome").

Knowledge

Knowledge(path=None, *, vocabulary=None, write_gate=None, actions=None, failures=None, severity=1.0, writers=None, reassert_writers=(), now=None, revival_window=None)

See the module docstring.

path: where the journal is kept — None (in memory), a path (.jsonl, .db, ...) or a TraceStorage (the decisions' store, so knowledge and decisions share one hash chain); an existing journal is replayed (the action model too, when it is built from a vocabulary). vocabulary: a Vocabulary or {name: predicate(state, args)} — the conditions the action model may learn from (None: no action model unless actions= gives one). write_gate: a WriteGate (or a list) run after the built-in source and consistency gates. actions: an ActionModel of your own (instead of vocabulary=). failures: True or FailureMemory settings ({"window", "unit", "max_blocked", "min_open"}) — a failure memory whose blocks are hard checks of the agent (None: off). severity: the action model's harm of a refused action (a number or {action: number}). writers: {writer: source (or sources), ...} — opt-in: a source is a rank (outcome > person > spec > verified wins a contradiction), and with a registry it is taken only from a writer (by=) registered with it; an unregistered writer, or one declaring another source, is refused with the reason in the journal (KnowledgeStore(writers=)). What observe writes comes from the writer "environment" with source "outcome": register it when an agent writes here. None (default): any writer may declare any source, as before. now: a world clock for usable with no time — a callable returning the current world time, or a fixed time (KnowledgeStore (now=)); None: usable reads status and staleness only.

branch

branch(path=None)

A writable what-if at the current state, with independent native components.

Preserves agenda callbacks, native action model and failure memory. Custom action models are refused before destination writes. Callback external state is not cloned. See KnowledgeStore.branch for persistence, policy reopening and provenance limits.

tell

tell(fact, *, source, by=None, of=None, scope=None, derived_from=(), evidence=None, valid=None, consulted=(), inferred=False, reassert=False)

Write a fact — {"s", "r", "o"} or (s, r, o) — from a person, an outcome, a written spec, or a verified System 2 answer (of= its stored decision). It goes through the source check and the write gates; a contradiction of equal rank becomes a person question (store.disputes()). → the item's id, or None when a gate refused it (the journal says why). consulted: the items looked at besides derived_from (an alternative's evidence): retracting one marks this fact for review (see KnowledgeStore.add). inferred: the fact is computed from derived_from (a rule applied to facts), not observed — it competes by rank and follows its premises (KnowledgeStore.add). A fact with derived_from and no valid holds where its premises hold together (refused when they never do).

retract

retract(item, why=None, *, by=None, storage=None, decide=None, only_from=None, assertion=None)

Take an item back with everything derived from it (nothing is deleted: the journal keeps it). → {"status": {id: (before, after)}, "answer_changes", "justification_only"} — the last two (with storage=, the decisions' TraceStorage, and decide=, a System or a function init → answers) list the stored decisions that rested on it, re-run on the snapshot rebuilt without it: the answer changes (for a reviewer) or only the justification. only_from (a writer, or (writer, evidence)) and assertion (a journal position): take back only those assertions of the item (KnowledgeStore.retract).

redecide

redecide(storage, decide, *, affected, valid_at_key, fact='knowledge')

Reconsider stored answers on current knowledge at each explicit input date.

Does not retract affected items or save decisions. All candidate dates and snapshots are validated before callbacks; callbacks retain their own effects. valid_at_key names a top-level ISO YYYY-MM-DD/date input field. Baseline is the current callback rerun on the historical snapshot, not a saved historical prediction. Callback outputs must be finite JSON; System Unknown answers render as {"$solvi": "unknown"}; when present, result entries include old_unknown_paths/new_unknown_paths JSON Pointer sidecars to distinguish them from identical literal JSON objects. Comparison also distinguishes Unknown from literal JSON. Sidecars are relative to old/new.

forget

forget(writer, *, by=None, why=None, storage=None, decide=None)

Forget a source in one call: what writer told is taken back, and with storage= (the decisions' TraceStorage or its path) and decide= (a System or a function init → answers) the stored decisions that rested on it are re-decided (KnowledgeStore.forget). → {"source", "retracted", "decisions", "changed", "same", "entry"}.

goal

goal(name, done, requires=(), gates=())

An agenda goal: done(state) → bool is its check in code (never a model's claim); requires: goals done first; gates: gates (declared with km.agenda.gate(name, check, blocks=)) that must pass for it to be open. → self.

observe

observe(state, action, outcome, *, args=None, at=None, to=None, map=None)

One environment step: action taken in state gave outcome (an Outcome, or True / False: accepted or refused). Updates the action model (and journals its prediction against what happened), the failure memory, the agenda (done checks on the new state) and the skills (a goal done right after this action); with at (the key of state), to (the key reached) and map (the map's name), the map facts — the first contradiction of a fact carried from an earlier episode flags the map (see the module docstring). → {"prediction": the action model's prediction before the step (dict) or None, "surprise", "drift": the flag's id or None, "goals_done": goals whose done check turned true, "skills": skill item ids written}.

usable

usable(iid, *, valid_at=None)

Whether this item may be used, optionally at an explicit world time.

valid_at follows KnowledgeStore.usable: use the same units as valid=. None preserves the configured now clock, or status-only reads without one.

edges

edges(map_id, at, *, valid_at=None)

The usable map facts from key at: {action key: key reached}.

valid_at is the explicit world time, as in usable; at remains a map key.

accepted_at

accepted_at(map_id, at, akey, *, valid_at=None)

What the map says about taking akey at at: True / False (a usable fact), or None.

skills

skills(goal, *, valid_at=None)

The actions after which goal's done check turned true (usable skill items).

where

where(map_id, akey, *, valid_at=None)

The keys on a map where akey was accepted (usable facts).

snapshot

snapshot(**query)

What a decision is given: KnowledgeStore.snapshot(**query) (default: the facts and rules) — the active items as facts, the hints with why, the ids they rest on, the store's fingerprint and journal position.

values staticmethod

values(snapshot, s, r, *, valid_at=None, scope=None)

Distinct matching fact values, in snapshot order (not a precedence order).

scope is a partial scope filter, as in KnowledgeStore.snapshot. valid_at selects effective periods when present, otherwise valid; an undated fact holds at any time. Without a time, all matching intervals are read. Equal values are returned once, including unhashable JSON values.

value staticmethod

value(snapshot, s, r, default=None, *, valid_at=None, scope=None)

The unique matching fact value, or default when no fact matches.

Raise ValueError for distinct matching values: narrow the read with world time valid_at and/or partial scope, or use values for a plural relation. Repeated equal values are unambiguous. See values for time filtering; without a time all matching intervals participate.

report

report()

What was learned and from whom (the store's report), the agenda (done, open, blocked), the action model (per action: allowed values, refusal signatures, transitions — for the built-in model), the skills, the failure memory's blocks, and the map facts per map.

action_key

action_key(action)

An environment's action as the knowledge names it: a string as it is, anything else as its JSON form.

split_action

split_action(action, args=None)

An action → (name, args) for an action model and the agenda's gates: "name" → (name, {}); ("name", x, ...) → (name, {"args": [x, ...]}); {"name": n, ...} → (n, the other keys); anything else → (its JSON form, {}).

Reading an item at an explicit time

Knowledge.usable accepts the same explicit valid_at keyword as its store and as Knowledge.snapshot. Use a time expressed in the same units as valid=:

from solvi import Knowledge

knowledge = Knowledge()
old = knowledge.tell(("pump", "rate", 1), source="outcome", by="meter", valid=(0, None))
new = knowledge.tell(("pump", "rate", 2), source="outcome", by="meter", valid=(10, None))
assert knowledge.usable(old, valid_at=5)
assert not knowledge.usable(old, valid_at=15)
assert knowledge.usable(new, valid_at=15)

Numeric times above are owner-defined world-time units. They are independent of store.tick, the logical clock used for expiry and withdrawal windows. For dates, use consistent ISO date strings or datetime.date values; incompatible numeric/date comparisons raise the store's explicit ValueError, rather than guessing a unit or converting to today's date.

Omitting valid_at (or passing None) keeps existing behavior: the explicit Knowledge(now=...) world clock applies if configured, otherwise usable reads status and staleness without choosing a date. An omitted assertion validity retains its existing meaning; this facade keyword does not turn omission into a timeless assertion. Corrections of recorded decisions still use the separately declared redecide(..., valid_at_key=...) input field.

The indexed map/skill helpers accept the same keyword:

edges = knowledge.edges("level-1", "room-0", valid_at=5)
accepted = knowledge.accepted_at("level-1", "room-0", "go-east", valid_at=5)
skills = knowledge.skills("reach-exit", valid_at=5)
locations = knowledge.where("level-1", "go-east", valid_at=5)

Here room-0 is the map key (at), while valid_at=5 is the world time. The helpers filter their existing indexed facts/skills using the store's effective periods, including derived support. They keep existing sorting, map filtering and missing-value behavior. This filters the current index; it does not rebuild historical indexes or search older map entries. Use a time-specific snapshot when inspecting the full version history. Omitting valid_at or passing None keeps the configured now clock, or the existing status-only behavior without one.