Documentation
¶
Overview ¶
Package agent holds what an agent knows and what it decided.
What it knows is a graph. Every node and edge carries the span of time it is held true, so the graph can be asked how it stood at a moment rather than only how it stands now, and a fact can stop being current without being erased. What it decided is a node in that same graph, written with the evidence the choice rested on and the rule it was taken under. Because a decision is a node, "why did the agent do this" is a walk over edges, not a stored explanation that can drift from the graph it explains.
The parts stay separable. Graph is the store, Memory the recent window, Journal the write path for decisions, Cause the read path for why, Rules the tests a choice must pass, and Ken composes the five for a caller who wants one thing instead of five. Journal, Cause and Rules satisfy decision.Recorder, decision.Cause and decision.Policy, so a caller may keep those interfaces and swap any implementation out.
A refusal is a decision. It is recorded, with the rule that refused and the reason, and never returned as an error: an agent that was stopped still made a choice, and the reason it was stopped is what somebody will want to read later.
Index ¶
- Constants
- Variables
- func Fit(score float64, sameTopic, sameChoice bool) float64
- func Strength(label string, confidence float64, hops int) float64
- type Ask
- type Away
- type Band
- type Cause
- func (c *Cause) Chain(ctx context.Context, id string) ([]decision.Record, error)
- func (c *Cause) Down(id string, depth int) []Away
- func (c *Cause) Force(id string) float64
- func (c *Cause) Loops(depth int) [][]string
- func (c *Cause) Net(ids []string) Net
- func (c *Cause) Roots(id string, depth int) []Away
- func (c *Cause) Trace(from, to string) Trace
- func (c *Cause) Up(id string, depth int) []Away
- type Change
- type Decision
- type Edge
- type Found
- type Graph
- func (g *Graph) Add(n Node) bool
- func (g *Graph) At(at time.Time) ([]Node, []Edge)
- func (g *Graph) Cross(from string, to *Graph, id string, r Reach) Route
- func (g *Graph) Cut(l Link, why string, at time.Time) bool
- func (g *Graph) Door(from string, to *Graph, id string)
- func (g *Graph) Drop(l Link, why string, at time.Time) bool
- func (g *Graph) Edge(l Link) (Edge, bool)
- func (g *Graph) Edges(label string) []Edge
- func (g *Graph) Find(q string) []Hit
- func (g *Graph) In(id string) []Edge
- func (g *Graph) Join(e Edge) bool
- func (g *Graph) Like(id string, byShape bool, n int) []Hit
- func (g *Graph) Losses() []Loss
- func (g *Graph) Lost(id string) (Loss, bool)
- func (g *Graph) Near(id string, r Reach) []Step
- func (g *Graph) Node(id string) (Node, bool)
- func (g *Graph) Nodes(kind string) []Node
- func (g *Graph) Out(id string) []Edge
- func (g *Graph) Path(from, to string, r Reach) Route
- func (g *Graph) Purge(id, why string, at time.Time) bool
- func (g *Graph) Retract(id, why string, at time.Time) bool
- func (g *Graph) Stats() Stats
- type Hit
- type Journal
- func (j *Journal) About(entity string) []Decision
- func (j *Journal) All() []Decision
- func (j *Journal) Before(id string) []Decision
- func (j *Journal) By(ctx context.Context, agent string) ([]decision.Record, error)
- func (j *Journal) Lead(from, to, how string) error
- func (j *Journal) Like(a Ask) []Match
- func (j *Journal) On(topic string) []Decision
- func (j *Journal) Read(id string) (Decision, bool)
- func (j *Journal) Record(ctx context.Context, r decision.Record) error
- func (j *Journal) Write(ctx context.Context, d Decision) (Decision, error)
- type Ken
- type Link
- type Loss
- type Match
- type Memory
- func (m *Memory) About(entity string) []Note
- func (m *Memory) Add(n Note) string
- func (m *Memory) All(s Scope) []Note
- func (m *Memory) Count() int
- func (m *Memory) Forget(id string) bool
- func (m *Memory) Get(id string) (Note, bool)
- func (m *Memory) Recall(q string, n int, s Scope) []Found
- func (m *Memory) Recent() []Note
- type Net
- type Node
- type Note
- type Op
- type Policy
- type Reach
- type Route
- type Rules
- func (r *Rules) Add(p Policy) (Policy, error)
- func (r *Rules) Allow(ctx context.Context, agent, choice string) (bool, string)
- func (r *Rules) Check(d Decision, p Policy) Verdict
- func (r *Rules) Drop(id string) bool
- func (r *Rules) For(topic string) []Policy
- func (r *Rules) Get(id, want string) (Policy, bool)
- func (r *Rules) History(id string) []Policy
- func (r *Rules) Revise(id string, rules map[string]any) (Policy, error)
- func (r *Rules) Sway(id string, proposed map[string]any, ds []Decision) (Sway, error)
- func (r *Rules) Vet(d Decision) Verdict
- func (r *Rules) Waive(w Waiver) error
- func (r *Rules) Waivers() []Waiver
- type Scope
- type Span
- type Stats
- type Step
- type Story
- type Swap
- type Sway
- type Trace
- type Verdict
- type Waiver
- type Where
Constants ¶
const ( Caused = "caused" // the earlier decision brought the later one about Influenced = "influenced" // it weighed on the later one without settling it Precedes = "precedes" // it is the precedent the later one followed )
The three ways one decision can bear on another. Nothing else is causal, so a walk over these labels is a walk over causality and over nothing else — which is what keeps "why did the agent do this" from wandering into every entity the decision merely mentioned.
const About = "about"
About is the edge from a decision to a thing the decision was about. It is how evidence is attached: the decision's Because is the ends of these edges, so the evidence is in the graph rather than in a list beside it.
Variables ¶
var ErrNoDecision = errors.New("agent: no such decision")
ErrNoDecision is returned when a decision id names nothing.
Functions ¶
func Fit ¶
Fit is how well a past decision serves as a precedent: how like the case it is, raised when it was the same kind of question and reached the same choice, lowered when it was neither.
Types ¶
type Ask ¶
type Ask struct {
Case string // the situation to match
Topic string // only this topic; empty asks every topic
Of []string // only decisions that rested on these entities
Floor float64 // ignore anything scoring under this
At time.Time // as the journal stood then; zero means now
Old bool // include decisions whose span has closed
N int // at most this many, best first
}
Ask is a search for the decisions most like the one at hand.
type Band ¶
type Band string
Band is how far apart two nodes are, said in words. Hop counts are exact but not comparable across graphs of different density; the band is what a reader should act on.
type Cause ¶
type Cause struct{ G *Graph }
Cause reads a graph as causality: what led to a decision, what it led to, how far back it reaches and how much of the claim survives the distance.
Its zero value reads an empty graph. It satisfies decision.Cause.
func (*Cause) Chain ¶
Chain is what a decision rests on, root cause first. It is decision.Cause's way in, and reads the same walk as Up.
func (*Cause) Force ¶
Force is how much a decision moved: the decisions it caused or influenced, weighed by how sure those were, plus the decisions that followed it as a precedent, weighed at half — being cited is weaker evidence of consequence than causing something outright. The result runs from 0 to 1.
A decision with no consequence scores 0 rather than dividing by nothing: the denominator counts at least one of each, so silence reads as no force rather than as an error.
func (*Cause) Loops ¶
Loops are the causal cycles in the graph: a decision that, followed forward, leads back to itself. A cycle is a modelling error more often than a fact about the world, so finding them is how a graph is checked.
Each cycle is returned once, starting and ending at the same decision. Depth bounds the search, and is worth setting low on a densely linked graph: the number of distinct paths through one grows faster than the graph does.
func (*Cause) Net ¶
Net measures the causal network over the decisions named, or over every decision when none are.
func (*Cause) Roots ¶
Roots are the decisions a chain ends at: upstream of this one, with nothing causing them in turn. They are where an explanation stops.
type Change ¶
Change is one mutation, as handed to Graph.Watch.
type Decision ¶
type Decision struct {
decision.Record
Topic string // the class of question: loan, triage, release
Case string // the situation decided
Reason string // why the agent chose as it did
Confidence float64 // how sure it was, from 0 to 1
Allowed bool // whether the rules permitted the choice
Gloss string // what the rules said, permitted or not
Props map[string]any
Span Span // when this decision is in force
}
Decision is one choice an agent made. The embedded record says who chose what, on which evidence, under which rule and when; the rest says what the choice was about, which is what makes two decisions comparable and a precedent findable.
Allowed and Gloss carry the verdict of the rules. A refused choice is still a decision and is still written down — that record is the only place the reason for a refusal survives.
type Edge ¶
type Edge struct {
Link
Weight float64 // how much confidence survives a walk across it; 1 by default
Props map[string]any
Span Span
}
Edge is one relation asserted between two nodes.
type Graph ¶
type Graph struct {
// Watch, when set, is called once per change after the graph is
// consistent and the lock is released. It is how an audit trail is kept
// outside the graph, so the graph does not have to know what an audit is.
Watch func(Change)
// contains filtered or unexported fields
}
Graph is the agent's knowledge: nodes, edges, and when each is true. Its zero value is an empty graph ready to write to, and it is safe for concurrent use.
func (*Graph) Add ¶
Add writes a node, replacing any node of the same id. It reports whether the id was new. A node with an empty id is not a node, and is refused.
func (*Graph) At ¶
At is the graph as it stood at one moment: the nodes whose span covers at, and the edges that both cover at and still have both ends. An edge to a node that was not yet true is not a relation, so it is left out.
func (*Graph) Cross ¶
Cross finds a way from a node here to a node in another graph, through however many doors it takes. Hops bounds the whole route, doors included, and defaults to ten as in Path.
func (*Graph) Door ¶
Door opens from a node here onto a node in another graph, so a walk can leave this graph and continue there without the two being merged. It is how one task's context stays its own while still being reachable from another.
func (*Graph) Edges ¶
Edges lists edges carrying one label in the order they were first written, or every edge when label is empty.
func (*Graph) Find ¶
Find scores every node against a keyword query by the share of query words its text carries, and returns those that carry at least one, best first. Ties keep the order the nodes were written in, so the answer is stable.
func (*Graph) Join ¶
Join writes an edge, creating either end that does not exist yet as a bare entity. It reports whether the edge was new; an edge asserted again keeps its place and takes the new weight, properties and span.
func (*Graph) Like ¶
Like finds the nodes most like one already in the graph, best first. Words are the measure by default; by shape when byShape is set, which asks about position in the graph instead of content.
func (*Graph) Lost ¶
Lost reports the last thing that happened to a node, if it was retracted or purged.
func (*Graph) Near ¶
Near walks out from a node and reports what it reaches. Confidence decays by the weight of each edge crossed, so a fact three weak edges away arrives marked as the weak evidence it is rather than as a neighbour.
Each node is reached once, by the first path that gets there, and the result is ordered nearest first and strongest first within a hop.
func (*Graph) Nodes ¶
Nodes lists nodes of one kind in the order they were first written, or every node when kind is empty.
func (*Graph) Path ¶
Path finds a way between two nodes of this graph. Unlike Near, which walks one hop unless told otherwise, a search with no Hops set looks up to ten edges deep: the caller is asking whether the two are connected at all.
func (*Graph) Purge ¶
Purge removes a node and every edge touching it, keeping only the note that it was removed. Use it when the data itself has to be gone; use Retract when it merely stopped being true.
func (*Graph) Retract ¶
Retract closes a node's span at at, and every edge touching it. The record stays: a question asked of an earlier moment still finds the node, and a decision that rested on it stays explainable. Edges are closed with it because a live relation around a node that is no longer true reads as current when it is not.
It reports whether the node was there and not already retracted.
type Journal ¶
type Journal struct{ G *Graph }
Journal writes decisions into a graph and reads them back. A decision is a node and its evidence is edges, so nothing is stored twice and a decision is reachable by the same walk as anything else in the graph.
Its zero value writes to a graph of its own. It satisfies decision.Recorder.
func (*Journal) About ¶
About lists the decisions that rested on one entity, in the order they were written.
func (*Journal) Before ¶
Before lists the decisions recorded as precedents for this one, in the order the links were made.
func (*Journal) Lead ¶
Lead records that one decision led to another: it caused it, influenced it, or is the precedent it followed. Both ends must be decisions — causality between a decision and a document is not causality, it is evidence, and evidence is what About is for.
func (*Journal) Like ¶
Like finds the decisions most like a case, best first. It is the search a caller makes before deciding: what did we do the last time this came up.
func (*Journal) Record ¶
Record writes the root form of a decision: everything decision.Recorder carries, and nothing this package adds. It is the interface's way in and calls Write. The root record names no class of question, so one written this way is filed under the topic "decision" and reads as allowed, since nothing was asked of the rules before it was written.
type Ken ¶
type Ken struct {
Graph *Graph
Memory *Memory
Journal *Journal
Cause *Cause
Rules *Rules
// Scope narrows what Learn writes and what Recall reads, so one agent's
// session or task does not answer another's questions.
Scope Scope
}
Ken is the range of what an agent knows: the graph of what it has been told, the memory of what was said lately, the decisions it took, why they followed from each other, and the rules it took them under.
It composes the five rather than replacing them. Every part is a field, so a caller who needs one takes that one and leaves the rest; Ken is only here to save the caller who would otherwise put the same five together the same way every time.
func (*Ken) Decide ¶
Decide puts a choice to the rules and records what happened either way. A refusal is not an error: the agent asked, the rules answered, and the answer with its reason is the record. The error return is for a decision that could not be written at all — one with no topic, case or choice, which is a mistake in the calling code rather than an answer about the world.
func (*Ken) Learn ¶
Learn keeps a note and puts what it is about into the graph: the note becomes a node, and every entity it names becomes one too, joined to it. Two entities named in the same note are then one hop apart through it, which is a claim the note actually supports — unlike an edge drawn straight between them, which asserts a relation nobody wrote down.
func (*Ken) Recall ¶
Recall finds what the agent knows about a question: the notes whose words answer it, and the notes about an entity the question names. A note found both ways ranks above one found only by its words, which is the reason for keeping a graph beside the memory rather than either alone.
type Link ¶
Link names an edge by its ends and what it asserts. Two assertions with the same ends and label are the same edge, so repeating one updates it rather than growing the graph.
type Loss ¶
type Loss struct {
Node string // set when a node was lost
Edge Link // set when an edge was lost
At time.Time
Why string
Purged bool
Via string // the node whose retraction or purge reached this edge
}
Loss is the note left when a node or edge stops being current. A retraction closes the span and keeps the record; a purge removes the record and leaves only this note, which is what erasure needs: proof that something was removed, without the thing itself.
type Match ¶
type Match struct {
Decision Decision
Score float64 // the two below, weighted
Words float64 // how much of the case it shares
Shape float64 // how alike its place in the graph is
}
Match is a past decision and how like the present one it is.
type Memory ¶
type Memory struct {
// Window is how many recent notes to hold. Zero means ten.
Window int
// Budget is roughly how many tokens the window may hold. Zero means two
// thousand. Size is counted the cheap way, four characters to a token,
// which is close enough to keep a prompt inside its limit.
Budget int
// Hold is how long a note is kept. Zero keeps everything.
Hold time.Duration
// contains filtered or unexported fields
}
Memory is what an agent has been told. Everything kept is searchable; the most recent is also held in a window, which is the part that fits in a prompt. The window is bounded twice — by count and by size — because either alone lets the other run away: ten long notes overflow a prompt, and a size budget alone can hold a hundred fragments no one wanted.
Its zero value is an empty memory with a window of ten notes and about two thousand tokens, and it is safe for concurrent use.
func (*Memory) Add ¶
Add keeps a note and puts it at the head of the window, dropping whatever no longer fits and whatever is older than Hold. It fills in an id and a time when the caller left them empty, and returns the id.
type Net ¶
type Net struct {
Decisions []string
Edges int
Density float64 // edges over every ordered pair that could have one
Path float64 // the rough mean distance, 1/density, never above the node count
Rank map[string]float64 // degree over the largest degree, from 0 to 1
Parts [][]string // the groups that reach each other and nothing else
}
Net is the shape of a causal network: how tied together it is, which decisions sit at the middle of it, and which parts of it never touch.
type Node ¶
type Node struct {
ID string
Kind string // entity, decision, policy — the caller's vocabulary
Text string // what it says, and what keyword search reads
Props map[string]any
Scope Scope
Span Span
}
Node is one thing the agent knows about.
type Note ¶
type Note struct {
ID string
Text string
At time.Time
Scope Scope
Of []string // the entities the note is about
Props map[string]any
}
Note is one thing an agent was told or observed.
type Policy ¶
type Policy struct {
ID string
Name string
Topic string // the decisions it governs; empty governs every topic
Version string // major.minor, and optionally more parts and a label
Text string // what it is for, in words
Rules map[string]any
At time.Time
}
Policy is a named, versioned set of tests a decision has to pass. Rules are data rather than code so a policy can be written, versioned and audited by people who do not write Go, which is who usually owns them.
A rule's name says what it tests and of what:
min_x the decision's x is at least the bound max_x the decision's x is at most the bound has_x x carries every value listed, or equals the bound if it is single one_x x is one of the values listed
Any other name requires only that the field be there at all, which is how a policy says "this must have been considered" without saying what the answer had to be.
x is looked for in the decision's properties first, then in a property whose name ends in x — so a rule on status finds a verification_status — and finally among the decision's own fields: topic, case, reason, choice, confidence, agent, rule.
type Reach ¶
type Reach struct {
Hops int // edges deep; zero means one
Labels []string // follow only these labels; empty follows every label
Min float64 // do not cross an edge weaker than this
Floor float64 // drop what arrives with less confidence than this
At time.Time // walk the graph as it stood then; zero ignores spans
}
Reach says how far a walk may go and what it may follow. Its zero value walks one hop over every edge, ignoring time.
type Route ¶
type Route struct {
Path []Where
Hops int
Decay float64
Doors int // boundaries between graphs the route crossed
Band Band
Found bool
}
Route is a way from one node to another: the fewest edges, not the strongest chain, so Decay describes the route found rather than the best route available.
type Rules ¶
type Rules struct {
// contains filtered or unexported fields
}
Rules holds policies and answers whether a decision passes them. Every answer comes with the reason, because a refusal without one cannot be argued with, appealed, or fixed.
Its zero value is an empty book, and it is safe for concurrent use. It satisfies decision.Policy.
func (*Rules) Add ¶
Add writes a policy. It fills in an id and a first version when the caller left them empty, and refuses a version that already exists — a rule that changed under a version anyone has already been judged by is not the same rule.
func (*Rules) Allow ¶
Allow is decision.Policy's way in: the coarse question, asked with nothing but an agent and a choice. Two things follow from how little that is. Only rules about the choice itself can be answered, so a policy testing confidence or evidence is not consulted; and with no topic to go on, only policies that govern every topic are, since applying a lending rule to a medical choice would be worse than not asking. Vet is the full question.
func (*Rules) Check ¶
Check tests one decision against one policy. A waiver passes the decision and says on whose authority.
func (*Rules) For ¶
For is the newest version of every policy that governs a topic, in the order the policies were first added.
func (*Rules) Revise ¶
Revise writes the next version of a policy: the same name and topic, new rules, the last version's number with its final part raised by one. The version it replaces stays readable, which is what makes a decision taken last year still explainable this year.
func (*Rules) Vet ¶
Vet tests a decision against every policy that governs its topic. The first refusal is the answer, since a decision that fails one rule is refused whatever the others say.
type Scope ¶
Scope is whose knowledge this is and what it was for. An empty field asks nothing, so the zero Scope, read as a filter, admits everything.
type Span ¶
Span is the stretch of time a fact is held true. A zero bound is open, so the zero Span holds always — which is what an ordinary fact wants.
type Stats ¶
type Stats struct {
Nodes int
Edges int
Kinds map[string]int
Labels map[string]int
Density float64
}
Stats counts what the graph holds.
type Step ¶
type Step struct {
Node Node
Label string // the edge followed to arrive
Weight float64 // that edge's weight
Hop int
Decay float64 // the product of every weight along the path
Path []string
Band Band
}
Step is one node a walk reached, and what the walk cost to get there.
type Story ¶
type Story struct {
Decision Decision
Because []Node // the evidence, as it stands in the graph now
Led []Away // what led to it, farthest first
Roots []Away // where the chain ends
Gloss string
}
Story is why a decision was taken: the decision itself, what it rested on, what led to it, and where the explanation stops.
type Sway ¶
type Sway struct {
Policy string
Judged int
Affected int // decisions that pass now and would not
Fall float64 // the share that would pass, less one: 0 costs nothing
Risk float64 // half the share that would fail
Changed map[string]Swap // the rules that differ
}
Sway is what changing a policy's rules would do to the decisions already taken under it. A rule change is cheap to write and expensive to mean, so the cost is worth seeing first.
type Trace ¶
type Trace struct {
From string
To string
Path []string
Hops int
Between []string // the decisions the path passed through
Decay float64 // the product of the weights along it
Weakest Link // the edge that costs the most confidence
Weight float64 // that edge's weight
Band Band
Gloss string // what the numbers amount to, in words
Found bool
}
Trace is one causal path and what survives it.
type Verdict ¶
Verdict is what the rules said: whether the choice stands, which policy settled it, and why. The reason travels with the answer because a refusal nobody can read is a refusal nobody can appeal or fix.