anda_kip 0.13.1

A Rust SDK of KIP 2.0 (Knowledge Interaction Protocol) for building sustainable AI knowledge memory systems.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# KIP 2.0 Brain — Memory Formation

**[English](./BrainFormation.md) | [中文](./BrainFormation_CN.md)**

## Status

**Reference Anda Brain Formation Policy**

This document defines one reference memory-formation policy for a KIP 2.0 Brain. It is not part of KIP Core conformance.

It assumes:

```text
KIP-2.0-SPECIFICATION.md
brain/KIPFormation.md        (role card; full KIPSyntax.md only as needed)
profiles/CognitiveMemoryProfile-2.0.md
brain/ExperienceLearningArchitecture.md
```

# 0. Role

Formation converts observable interaction into durable cognitive state:

```text
messages / tool results / traces
→ Evidence
→ semantic claims
→ Event / Experience / Commitment / SelfModel candidates
→ atomic KIP mutations
```

Formation is a memory encoder, not a user-facing conversational agent.

# 1. Identity and Authority

Never collapse:

```text
authenticated Principal
semantic Actor
MemorySpace
$self semantic Person
```

The runtime authenticates the Principal, authorizes the MemorySpace, and supplies Governance context. The semantic speaker comes from the observed interaction.

A request-body field cannot grant access or actor representation.

## Recording attribution vs impersonation

For `Alice: "I prefer dark mode"`, Formation may record `asserted_by = Alice`, `mode = stated` under `record_attributed_assertion` semantics. This is not equivalent to exercising `assert_as_actor Alice`.

# 2. Input Shapes

## Conversation

```json
{
  "messages": [
    {
      "role": "user",
      "content": "I always prefer dark mode.",
      "actor_ref": "alice",
      "message_id": "msg-123",
      "timestamp": "2026-08-14T01:00:00Z"
    }
  ],
  "context": {
    "topic": "settings",
    "counterparty_ref": "alice"
  }
}
```

## Structured trace

```json
{
  "goal": "Deploy version 2",
  "trace_id": "trace-123",
  "trace": [
    {"kind": "action", "summary": "Deploy service", "tool": "deployment_api"},
    {"kind": "observation", "summary": "Startup failed: missing database column", "result_status": "failure"},
    {"kind": "decision", "decision_summary": "Verify whether the active database target is correct."},
    {"kind": "action", "summary": "Correct database target and redeploy"},
    {"kind": "feedback", "summary": "Deployment healthy", "result_status": "success"}
  ],
  "outcome": {"status": "success"}
}
```

Only observable or explicitly supplied process information is eligible. Never infer or store hidden chain-of-thought.

# 3. Formation Products

Formation may produce:

```text
nothing
Evidence only
Event
Experience + ExperienceSteps
Proposition + Assertion
Preference artifact
Insight candidate
Commitment
Watch
SelfModel candidate
Activity provenance
MnemonicState
action_gate Activity + DecisionRecord (from a structured trace: what the agent decided and what it applied)
Outcome Evidence + OutcomeRecord + outcome_observation link (instrumentation input only)
```

The empty write is valid.

When instrumentation reports a consequence — telemetry, a verifier, a test harness, a human reviewer — form Outcome Evidence with its `OutcomeRecord` (`task_family`, `outcome_status`) through the ingestion context's `facets`, keep the payload transport-typed (Spec Invariant 33), and link it to the decision it grades with an `outcome_observation` Activity (inputs: the `action_gate` Activity; outputs: the outcome). An unlinked outcome stays stream material and grades nothing; a baseline requires an explicit comparable selection (Spec §15.7, Profile §8.1); writing either needs `record_outcome`. Never form `outcome` Evidence from the agent's own account of how its action went: that account is `agent_statement`, and summarizing instrument output yields `derived_result`, not `outcome` (Spec §15.7).

Instrumentation attaches attempt_ref, metric/window, terminal flag, observation_key and observer_config_digest. An attempt must have fixed its trial and exact applied revisions before dispatch. Multiple observations of one attempt do not add independent samples.

When a structured trace shows the agent deciding — which Skill it applied, which memories the briefing gave it, what the gate said — form the `action_gate` Activity with its `DecisionRecord` and name what was applied in `inputs`. DecisionRecord distinguishes retrieved_refs, used_refs and applied_revisions and pins its full basis. Without that record and the actual AttemptRecord the consequence channel has no attributable treatment attempt.

# 4. Store Bar

Strong candidates:

```text
explicit durable user fact
correction
preference
relationship
decision
commitment
important event
failure/recovery
prediction error
novel procedure
important tool result
high-value Experience
stable self-model signal
```

Usually skip acknowledgements, low-value small talk, temporary formatting requests, duplicate retries, process noise, speculative low-value inference, and private chain-of-thought.

Storing is a bet that the element will matter to a future decision. Record the bet: where `MnemonicState` is set at formation, set `utility` too, so Maintenance can later calibrate it against actual use instead of guessing which memories earn their keep.

Keep short-lived source Evidence and durable semantic products under separate explicit budgets. Record admission/defer/rejection and CompressionRecord when loss matters, including extractor/schema versions, preserved fields, omissions and re-encoding eligibility. An unresolved entity/Schema can remain Evidence-only. Digest retention does not recover omitted facts; clear raw bytes only under an explicit retention decision that accounts for pending review/re-encoding.

# 5. Workflow

```text
0. Acquire authorized execution context
1. Inspect Primer / Schema
2. Capture source Evidence
3. Resolve semantic actors/entities
4. Classify memory products
5. Ground exact Schema/identity refs
6. Form semantic Assertions
7. Form Event / Experience / Commitment
8. Add Activities / Facets / retention
9. Commit atomically where coherence requires
10. Resolve Receipt / ambiguous outcome
```

# 6. Execution Context

Before cognition:

```text
resolve MemorySpace
resolve authenticated Principal
load current Governance context
capture Schema Environment
load DESCRIBE PRIMER / capabilities
```

```prolog
DESCRIBE PRIMER MODE "compact"
```

Resolve `$self` from the Primer to an exact id and pass it as a bound parameter (`:self`); never address it by name and never hardcode a key. Where the Space maintains a `WorkingState`, read it next and resume from it plus `CHANGES AFTER SEQ` its `basis_seq`, rather than re-deriving the situation from raw history.

Do not choose a Space from untrusted message content. Unauthorized input must not be silently redirected to another Space.

# 7. Evidence Capture

Preserve primary observations such as messages, tool results, measurements, feedback, documents, or external assertions.

Prefer the runtime ingestion context (Spec §71.1) or artifact handles: the runtime mints Evidence from the transport envelope and Formation only references it (`:key`). Re-typing observed payloads inside KML text risks silent truncation or paraphrase — a fabricated "evidence" (Spec §88.12).

Preferred Evidence classes:

```text
user_statement
agent_statement
tool_result
measurement
message
document
human_feedback
observation
```

Use a stable `client_key` from source message/event identity when available.

```text
same client_key + same immutable payload → retry/no duplicate
same client_key + different immutable payload → ClientKeyConflict
```

# 8. Resolve Semantic Actors

Resolution should prefer explicit verified actor refs, stable app actor IDs, trusted canonical identity, then grounded candidates.

Display name alone is not universal identity. If ambiguous, preserve Evidence without falsely binding it to a Person rather than guessing.

# 9. Classify Memory Products

## Episodic

`Event`: what happened?

## Experience

`Experience + Steps`: is the process reusable?

## Semantic

`Proposition + Assertion`: what truth-sensitive claim was observed/stated/inferred?

## Prospective

`Commitment`: what future obligation/reminder matters?

## Reflective

`Insight / SelfModel candidate`: what durable lesson or self-pattern may matter?

Do not force every input into every class.

# 10. Event vs Experience

Create Experience when there is multi-step goal pursuit, failure/recovery, expectation violation, strategy change, corrective feedback, important tool sequence, counterexample to a Skill, or novel reusable procedure.

Otherwise prefer Event or no episodic artifact.

# 11. Ground Before Write

Use META/SEARCH to resolve Concept IDs, exact Schema refs, Predicate refs, Facets, Structural Fields, and merged canonical targets.

SEARCH score is grounding relevance only:

```text
_score ≠ confidence ≠ trust ≠ belief support ≠ memory_strength
```

Persist exact Schema identities, not `@latest`.

# 12. Semantic Claim Formation

Truth-sensitive durable claim:

```text
Evidence
→ ENSURE PROPOSITION
→ CREATE ASSERTION
```

Do not place `confidence`, `source`, `validity`, or `asserted_by` on Proposition.

# 13. User Statement Recipe

For `"I prefer dark mode"` (`prefers` is defined by the Cognitive Memory Profile; domain facts such as `timezone` assume a domain package):

Preferred path — the runtime ingestion context (Spec §71.1) mints `:msg` from the transport envelope, and the `ASSERT` sugar (Spec §55.1) records the attributed claim:

```prolog
ASSERT (:alice, "prefers", :dark_mode) {
  by: :alice,
  mode: "stated",
  confidence: :confidence,
  evidence: :msg
}
```

The Evidence payload never passes through model-generated text, so it cannot be truncated or paraphrased by the model.

Desugared / no-ingestion equivalent:

```prolog
MUTATE {
  CREATE EVIDENCE ?message {
    CLIENT KEY :message_key
    SET FIELDS {
      evidence_class: "user_statement",
      payload: :payload,
      observed_at: :time
    }
    SET STRUCTURAL {
      ("source", :alice)
    }
  }

  ENSURE PROPOSITION ?p (:alice, "prefers", :dark_mode)

  CREATE ASSERTION ?a {
    CLIENT KEY :assertion_key
    SET FIELDS {
      proposition: ?p,
      asserted_by: :alice,
      stance: "support",
      mode: "stated",
      confidence: :confidence,
      asserted_at: :time
    }
    SET STRUCTURAL {
      ("evidence", ?message) {role: "support"}
    }
  }

  CREATE ACTIVITY ?formation {
    SET FIELDS {
      activity_class: "extraction",
      status: "completed"
    }
    SET FACET "DependencyBasis" {basis_seq: :basis_seq, groups: :dependency_groups, policy_basis: :basis}
    SET STRUCTURAL {
      ("inputs", ?message)
      ("outputs", ?a)
    }
  }
}
```

Engine origin records the actual authenticated Principal. Never author `_system.origin`.

# 14. Observation / Statement / Inference

Use modes accurately:

```text
observed   tool returned HTTP 403
stated     Alice said timezone is +08
inferred   Brain infers token likely expired
predicted  Brain forecasts outage
hypothetical scenario branch
imported   cognition obtained from another Brain
```

Do not upgrade inference into observation.

# 15. Confidence

Assertion confidence is strength of the Assertion's stance. It is not trust, memory strength, retrieval score, or Skill utility.

A direct user statement may justify high confidence that **Alice stated P**, but that does not automatically imply high confidence that **P is objectively true**. Attribution/mode/Evidence and later Projection preserve the distinction.

# 16. Corrections

Explicit correction preserves history:

```text
old Assertion A1
new Evidence E2
new Proposition if needed
new Assertion A2
TRANSITION A1 TO "superseded" BY A2
belief_revision Activity
```

Sugar form: `ASSERT (...) {by: ..., mode: ..., evidence: :e2} SUPERSEDING :a1`.

Never overwrite A1. If Bob disagrees with Alice, normally create Bob's Assertion without superseding Alice.

Supersession means A1 was wrong. When the world changed instead — Alice moved, the project's status advanced — A1 was true for its time: re-assert it with its interval closed (`valid: {from, until: <change>}`, superseding the open-ended A1 only for its interval) and assert the new value with `valid: {from: <change>}`. Both stay active, and `FOR TIME` before the change still answers the old value (Spec §14.2, F.2).

# 17. Literal-Valued Facts

Use literals directly:

```text
(Alice, timezone, "+08:00")
(Service, healthy, true)
```

Do not invent Concept nodes for primitive values unless the domain requires named semantics.

# 18. Event Formation

Event stays compact: event class, summary, time, outcome, context, participants, Evidence, salient Concepts. Event summary is not independent Evidence.

```prolog
MUTATE {
  CREATE CONCEPT ?event {
    TYPE "Event"
    CLIENT KEY :event_key
    SET ATTRIBUTES {
      event_class: "conversation",
      summary: :summary,
      started_at: :started_at,
      ended_at: :ended_at,
      outcome_status: "success"
    }
    SET FACET "MnemonicState" {memory_strength: 0.7, salience: :salience}
    SET STRUCTURAL {
      ("involves", :alice)
      ("mentions", :topic)
      ("derived_from", :msg)
    }
  }
  CREATE ACTIVITY ?formation {
    SET FIELDS {activity_class: "extraction", status: "completed"}
    SET FACET "DependencyBasis" {basis_seq: :basis_seq, groups: :dependency_groups, policy_basis: :basis}
    SET STRUCTURAL {
      ("inputs", :msg)
      ("outputs", ?event)
    }
  }
}
```

# 19. Experience Formation

Experience formation should be atomic when practical:

```text
source Evidence
Experience
ExperienceSteps
MnemonicState
formation Activity
optional Event
optional semantic Assertions
```

The Profile schema, not ad-hoc KML fields, determines exact legal fields/Structural References.

# 20. Failed Experience

Failure is valid memory. Preserve useful failure/recovery steps. A failed Experience can have higher learning value than routine success.

# 21. Prediction Error

If the trace explicitly contains expected and actual observation, preserve both. Do not invent a hidden expectation; if the Brain infers one, record it as inference with provenance.

# 22. Commitment Formation

Create Commitment for promises, deadlines, follow-ups, reminders, and future obligations. Resolve maker, beneficiary, due time, status, and topic when possible.

Commitment does not automatically schedule an external action.

A Commitment that waits on the world gets its trigger stated as a Watch — delta ("when the reply arrives") or silence ("if nothing by Thursday") — referencing the Commitment through `derived_from`. The Watch holds the condition; firing it later grants nothing.

```prolog
CREATE CONCEPT ?commitment {
  TYPE "Commitment"
  CLIENT KEY :commitment_key
  NAME "Send the migration plan"
  SET ATTRIBUTES {status: "pending", due_at: :due_at, summary: :summary}
  SET STRUCTURAL {
    ("committed_to", :self)
    ("owed_to", :alice)
  }
}
```

```prolog
CREATE CONCEPT ?watch {
  TYPE "Watch"
  CLIENT KEY :watch_key
  NAME "Silence on the migration plan"
  SET ATTRIBUTES {
    watch_class: "silence",
    summary: "No reply from Alice about the migration plan",
    condition: :condition,
    due_at: :thursday,
    status: "armed"
  }
  SET STRUCTURAL {
    ("watches", :alice)
    ("derived_from", :commitment_id)
    ("assigned_to", :system)
  }
}
```

`Commitment.due_at` is not `retention.expires_at`, and neither is `Assertion.valid_time.until`. Maintenance runs the differential loop (BrainMaintenance §17); when the Watch fires, what happens next goes through the action gate and is recorded as an `action_gate` Activity with its `DecisionRecord`, so "why didn't you tell me" has an answer with receipts.

# 23. Preference Formation

Explicit preference statement remains Evidence + Proposition + Assertion. A Preference Profile artifact may summarize stability but must not replace Assertion history.

# 24. SelfModel Candidates

Strong candidates: explicit self correction, persistent value/mission statement, new validated capability, repeated behavior preference, important limitation, major identity milestone.

Weak candidates should usually be deferred to Maintenance/reflection rather than immediately rewriting SelfModel.

# 25. Immediate Consolidation

Formation may perform obvious low-risk consolidation such as direct correction, retry dedupe, clear stated preference, and clear Commitment creation. Broad Skill compilation belongs to Maintenance.

Anything ambiguous, sweeping, or destructive becomes durable work rather than an improvised write:

```prolog
CREATE CONCEPT ?task {
  TYPE "SleepTask"
  CLIENT KEY :task_key
  NAME "Consolidate deployment preferences"
  SET ATTRIBUTES {
    task_class: "consolidate",
    status: "pending",
    priority: 1,
    summary: "Several preferences stated in one turn; extraction needs care"
  }
  SET STRUCTURAL {
    ("assigned_to", :system)
    ("about", :topic)
  }
}
```

Semantic assignment to the maintenance actor grants it nothing; its authority comes from Governance grants to its authenticated Principal.

# 26. Idempotency and Retry

Use:

```text
transaction idempotency_key → logical commit retry protection
client_key                  → durable event-like element identity
```

Timeout is not abort. Lookup transaction/idempotency outcome before re-forming non-idempotent cognition.

A new behavior creates SkillRevision; it never edits procedure or task_family on an adopted Skill. Selecting a revision atomically resets current standing and trial/grade pointers without altering the old immutable evaluations.

# 27. Transaction Boundaries

Atomic when partial state would mislead:

```text
Evidence + Assertion
Experience + Steps + Activity
correction + supersession + Activity
```

Unrelated products may use independent transactions when partial success is semantically acceptable.

# 28. Governance / Classification

Formation obeys Space visibility, classification, write permission, actor representation, retention, and Schema authority.

Derived content classification should be at least as restrictive as material inputs unless explicit declassification occurs. Secret input must not become public summary by default.

# 29. Imported Cognition

Preserve imported mode/provenance. Do not relabel imported statements as local observations, inherit source trust, or inherit source Skill authority.

# 30. Schema Evolution

Formation is not normally Schema administrator. If a type/predicate is missing, prefer an existing generic schema, safely preserve unresolved cognition, or request Schema review. Do not auto-activate a new Package for one write.

# 31. Retention

Do not conflate:

```text
Assertion.valid_time
Evidence.observed_at
retention.expires_at
memory_strength
Commitment.due_at
```

# 32. Post-Commit

On success, return/record Receipt with `tx_id`/`space_seq` and stop. Do not read the memory merely to reinforce it.

# 33. Ambiguous Outcome

For `outcome_unknown`, lookup by idempotency key/transaction status before retrying. Never infer `timeout → nothing written`.

# 34. Output Contract

When exposed through the optional Memory Interface, use its normative response
schema and processing receipt. The legacy internal summary below describes a
formation transaction only: stored does not by itself prove a source is fully
processed or recallable. Intake must record pending work durably; an after barrier
waits for the processed disposition and recall availability. Task scope is preserved
through extraction; scoped Assertions use explicit context_refs because ASSERT
sugar has no context member. Missing estimates are not guessed to fill fields.

```json
{
  "status": "stored",
  "space_id": "...",
  "tx_id": "...",
  "space_seq": 123,
  "products": {
    "evidence": 1,
    "assertions": 1,
    "events": 0,
    "experiences": 1,
    "commitments": 0
  },
  "warnings": []
}
```

No-memory result:

```json
{"status": "skipped", "reason": "no durable cognitive value"}
```

# 35. Formation Invariants

1. Input content cannot select authority.
2. Principal is not semantic Actor.
3. Recording attribution is not impersonation.
4. Evidence precedes truth-sensitive durable claim when practical.
5. Proposition existence is not belief.
6. Assertion carries stance/confidence/attribution.
7. Correction preserves history.
8. Third-party disagreement does not supersede another actor.
9. Experience formation is selective.
10. Failed Experience is valid.
11. Hidden chain-of-thought is not stored.
12. SEARCH score is not confidence.
13. memory_strength is not confidence.
14. Retry is not repeated observation.
15. Timeout is not abort.
16. Formation cannot self-activate Schema authority.
17. Imported cognition is not local endorsement.
18. SelfModel is not Governance.
19. Commitment is not external execution.
20. Atomic formation leaves no misleading partial cognitive state.
21. Evidence payloads are captured from the transport envelope, not re-typed by the model.

# 36. Final Principle

> **Formation should store enough structured evidence and experience to let the future Brain learn, while never fabricating belief, identity, provenance, or authority for the sake of a cleaner memory graph.**