anda_brain 0.13.6

๐Ÿง  Anda Brain (ๅคง่„‘) โ€” Autonomous Graph Memory for AI Agents
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# KIP 2.0 Brain โ€” Memory Maintenance

## Status

**Reference Anda Brain Maintenance / Metabolism Policy**

Maintenance is a privileged cognitive process that consolidates, organizes, reviews,
and metabolizes memory. Its authority comes from Governance grants to its authenticated
Principal, never the name `$system`. Load [KIPMaintenance.md](./KIPMaintenance.md);
the full KIPSyntax.md is available for uncommon operations.

Run only the enabled capability bundles. Ordinary memory maintenance does not
require learning trials, instrumentation or durable external dispatch. When the
Memory Interface has acknowledged deferred input, advance its processing receipt
only after the actual work and recall availability are established; never count
a saved source or a refreshed index as completed semantic processing.

# 0. Objective

```text
raw fragments
โ†’ organized memory
โ†’ semantic consolidation
โ†’ procedural consolidation
โ†’ identity cleanup
โ†’ mnemonic metabolism
โ†’ retention management
โ†’ self-model refinement
โ†’ better future Formation / Recall / action
```

Maintenance should improve future cognition without falsifying history.

# 1. Safety Thesis

Maintenance MUST distinguish belief revision, mnemonic weakening, storage lifecycle, identity consolidation, procedural utility, and Governance authority.

Forbidden shortcuts:

```text
time passed โ†’ lower Assertion confidence
contradiction โ†’ delete one side
suspected duplicate โ†’ destructive merge
low memory_strength โ†’ purge Evidence
Skill worked often โ†’ grant executable authority
semantic $system โ†’ administrative permission
```

# 2. Authority Model

Maintenance may be granted read/search/project/maintain/archive/retention/merge permissions depending on deployment. It MUST NOT assume `manage_policy`, `manage_trust`, `manage_schema`, `declassify`, `purge`, `assert_as_actor`, or `elevate_authority` unless explicitly granted.

# 3. Input Contract

```json
{
  "trigger": "scheduled",
  "scope": "full",
  "timestamp": "2026-08-14T03:00:00.000Z",
  "budgets": {
    "max_elements_reviewed": 5000,
    "max_writes": 500,
    "max_transactions": 100
  },
  "parameters": {
    "strength_policy": {"artifact_ref": "kip:strength-half-life-30d", "content_digest": "sha256:..."},
    "event_archive_after_days": 30,
    "skill_review_after_days": 14
  }
}
```

Thresholds are Brain policy, not KIP standards.

## 3.1 Triggers

```text
scheduled     every 12-24h
change        a committed delta matches an armed Watch, or a silence Watch's due_at passes
threshold     SleepTask backlog, unconsolidated Events, expired retention,
              a trial's graded-outcome quota reached, an adopted Skill due a re-verdict
on-demand     Formation, or the agent, asks for maintenance
post-session  after a long or high-signal conversation
```

The change trigger is what makes proactivity a state differential instead of a bare schedule: the wake happens because something specific moved โ€” or specifically did not โ€” against a declared expectation. The silence half still needs the due-time sweep the schedule provides.

# 4. Modes

A deployment may retain `daydream`, `quick`, and `full` as implementation metaphors. They are not protocol semantics.

# 5. Cycle

```text
1  Assessment
2  Pending SleepTasks
3  Semantic consolidation
4  Procedural consolidation
5  Mnemonic metabolism
6  Identity review / merge
7  Contradiction review
8  Derivation review
9  Commitment review
10 Watch evaluation
11 SelfModel refresh
12 WorkingState refresh
13 Imported/quarantined cognition review
14 Retention/archive review
15 Tombstone/purge candidates
16 Final health report
```

# 6. Assessment

Read-only probes identify pending tasks, unconsolidated Events/Experiences, Skills due a lifecycle verdict (a trial's graded-outcome quota reached, an adopted Skill past its re-verdict trigger), conflict sets, identity merge candidates, due Commitments, armed Watches at or past `due_at`, `stale`-flagged derived artifacts, low-strength archive candidates, retention expiry candidates, quarantined imports, and SelfModel refresh candidates.

Assessment reads do not update recall/access counters.

Two probes every cycle starts with โ€” the pending work assigned to this actor, and the episodic material nobody has consolidated:

```prolog
FIND(?task.id, ?task.name, ?task.attributes.task_class, ?task.attributes.priority)
WHERE {
  ?task {type: "SleepTask", attributes: {status: "pending"}}
  STRUCTURAL (?task, "assigned_to", ?actor)
  FILTER(?actor.id == :system_id)
}
ORDER BY ?task.attributes.priority DESC, ?task._system.created_at ASC
LIMIT 50
```

```prolog
FIND(?event.id, ?event.attributes.summary, ?event.attributes.started_at)
WHERE {
  ?event {type: "Event"}
  FILTER(?event.attributes.started_at < :cutoff)
  NOT {
    STRUCTURAL (?event, "consolidated_to", ?derived)
  }
}
ORDER BY ?event.attributes.started_at ASC
LIMIT 50
```

Count first, act second.

# 7. Salience and Learning Value

Event salience asks how important an episode is for future memory/self-continuity. Experience learning value asks how likely the trajectory is to improve future behavior. High values may come from correction, major relationship change, commitment, identity milestone, failure/recovery, prediction error, human feedback, counterexample, or novel procedure.

Neither equals confidence.

# 8. SleepTasks

SleepTask is cognitive work description. Verify current Principal authority before acting. `assigned_to = $system` is not authorization. Preserve Activity provenance when completing maintenance work.

Claim a task before working it, so a concurrent cycle cannot double-process it:

```prolog
UPDATE :task_id
SET ATTRIBUTES {status: "running", started_at: :now}
SET FACET "LeaseState" {owner: :principal, fencing_token: :next_fence, expires_at: :lease_until, attempt_count: :attempt_count}
EXPECT VERSION :version OF ATTRIBUTES
EXPECT VERSION :lease_version OF FACET "LeaseState"
```

`VersionConflict` means another worker took it โ€” re-read and move to the next task. The runtime validates the authenticated owner, expiry and monotonic fence. Renew or take over expired leases with compare-and-set; completion/dispatch from an expired or replaced fence fails. A CLIENT KEY is not a Concept key, so claim the exact id returned by the task query. A terminal task is completed with `status: "completed"` and its outcome summary; a failed task records why, and stays visible rather than disappearing.

# 9. Semantic Consolidation

Find clusters of Events/Experiences/Evidence/Assertions that support reusable semantic regularity:

```text
read sources
โ†’ group provenance roots
โ†’ identify candidate Proposition
โ†’ evaluate existing Assertions
โ†’ create derived Assertion if justified
โ†’ record semantic_consolidation Activity
```

Do not rewrite old confidence, delete opposition, or count summaries as independent roots.

One atomic transition, with provenance:

```prolog
MUTATE {
  CREATE CONCEPT ?insight {
    TYPE "Insight"
    CLIENT KEY :insight_key
    NAME "Staging deploys fail without the schema migration step"
    SET ATTRIBUTES {summary: :summary}
    SET FACET "MnemonicState" {memory_strength: 0.7, salience: 0.8}
    SET STRUCTURAL {
      ("about", :deployment_topic)
    }
  }
  ASSERT ?causal (:failure_step, "caused_by", :migration_step) {
    by: :self,
    mode: "inferred",
    confidence: 0.7,
    evidence: :step_evidence
  }
  CREATE ACTIVITY ?consolidation {
    SET FIELDS {activity_class: "semantic_consolidation", status: "completed"}
    SET FACET "DependencyBasis" {basis_seq: :basis_seq, groups: :dependency_groups, policy_basis: :basis}
    SET STRUCTURAL {
      ("inputs", :source_experience)
      ("inputs", :step_evidence)
      ("outputs", ?insight)
      ("outputs", ?causal)
    }
  }
}
```

The consolidation Activity's inputs make the source read as consolidated: its computed `consolidated_to` now names the Insight, so the next cycle can skip it, and the Insight's computed `derived_from` names its sources. The causal claim is an Assertion with Evidence behind it, asserted by the maintenance actor in `inferred` mode โ€” `evidence:` cites Evidence elements, never the Experience Concept they were observed in. Step order alone is never causality, and a Predicate you cannot find in the Schema Environment is never to be invented โ€” `DESCRIBE` first, and let a domain package supply what the Profile does not.

# 10. Repetition

Independent repeated observation may increase support. Same event replay/duplicate import creates no new root. Later user reconfirmation is new Evidence/Assertion. Do not model all repetition as `confidence += x`.

# 11. Procedural Consolidation

Prefer contrastive Experience sets:

```text
success + failure
success + counterexample
same procedure across different contexts
```

Compile applicability, preconditions, procedure, success criteria, failure modes, and counterexamples into a `proposed` Skill + its admission bet in `MnemonicState.utility` + procedural Activity. Attach the required `task_family` to the immutable revision: it selects candidate consequences, while TrialRecord explicitly freezes comparable baseline attempts/outcomes. Refuse to compile a pattern no stream could prove wrong (store it as an Insight instead). The computed `GradingState` view is absent until the first validated EvaluationRecord; ungraded proposed/trialed Skills remain recallable as unproven candidates. `compiled_from` and `compiled_by` are computed from the compilation Activity below; never write them. Do not grant executable authority.

```prolog
MUTATE {
  CREATE CONCEPT ?skill {
    TYPE "Skill"
    CLIENT KEY :skill_key
    NAME "Deploy with pre-flight migration check"
    SET ATTRIBUTES {skill_class: "workflow", summary: :summary, status: "proposed"}
    SET STRUCTURAL { ("current_revision", ?revision) }
  }
  CREATE CONCEPT ?revision {
    TYPE "SkillRevision"
    CLIENT KEY :revision_key
    SET ATTRIBUTES {task_family: "deploy/pre-flight", procedure: :procedure, behavior_digest: :behavior_digest}
    SET STRUCTURAL {
      ("revision_of", ?skill)
    }
  }
  CREATE ACTIVITY ?compilation {
    SET FIELDS {activity_class: "skill_compilation", status: "completed"}
    SET FACET "DependencyBasis" {basis_seq: :basis_seq, groups: :dependency_groups, policy_basis: :basis}
    SET STRUCTURAL {
      ("inputs", :experience_a)
      ("inputs", :experience_b)
      ("outputs", ?skill)
      ("outputs", ?revision)
    }
  }
}
```

Contrast before compiling: compare successful against failed Experiences to find the discriminating precondition. One success does not prove a general Skill, and a Skill that only ever worked in one context should say so in its applicability rather than in a higher `utility`.

# 12. Skill Lifecycle Verdicts

The lifecycle `proposed โ†’ trialed โ†’ adopted โ†’ revoked` moves only by deterministic verdict over graded Outcome Evidence under the Skill's `task_family` (Profile ยง14, Spec ยง15.7), and only where the deployment implements the [Validated Learning companion](Validated-Learning.md); without it, Skills stay `proposed` and unproven, and Maintenance may only withdraw them. Your role is to schedule the verdict, run the deterministic rule, and record the result as a `lifecycle_verdict` Activity plus one guarded UPDATE (Validated Learning ยง7) โ€” never to promote on judgment, and never to count an actor's own success report as an outcome.

Verdict discipline: the treatment set is the outcomes linked, through an `outcome_observation` Activity, to an `action_gate` decision that applied the Skill; the baseline is the explicit comparable attempt set frozen in the immutable TrialRecord that `current_trial` selects โ€” an outcome that merely shares the `task_family` never counts. Adoption is comparative (better than it was going, against that basis) and provisional (the stream keeps grading; demote to re-trial on degradation); revocation is never harder than adoption, and one high-severity matching-condition failure may suffice; re-entry after revocation starts a new trial identity and selects its immutable TrialRecord through `current_trial`. Outcomes retain their preassigned attempt/trial/revision even when they arrive late. Count independent attempts, not Evidence observations; verify metric, window, missingness and comparability before adoption (Validated Learning ยง3โ€“ยง6).

Legal cognitive actions besides the verdict itself include pointing `current_evaluation` at it (the GradingState view follows), `MnemonicState.utility` revisions, a revised Skill artifact, failure-mode annotations and counterexample linkage. Narrowed applicability or changed recovery/procedure creates a new SkillRevision; it is not an in-place behavior edit. Authority changes require Governance.

# 13. Mnemonic Metabolism

Generic disuse acts on `MnemonicState.memory_strength`, not Assertion confidence โ€” and it acts by computation, not by writes. `memory_strength` is the last written base, `last_metabolized_at` its anchor and `strength_policy` a pinned policy (for example a half-life); the engine computes `effective_strength` whenever a read is evaluated (Spec ยง59.1, Profile ยง6.1). There is no decay sweep, and a missing base, anchor or policy leaves strength unknown โ€” never fill it with a default.

Maintenance writes a new base only on an explicit signal:

```text
use           a DecisionRecord's used_refs, or an exposure-log batch (Spec ยง66.8)
salience      protection for Commitments, identity, major failures, adopted Skills
correction    a corrected or retracted root may weaken what was built on it
```

`MnemonicState.utility` is calibrated under the same discipline: explicitly, on outcomes โ€” a memory a briefing drew on that helped, a bet that never paid out โ€” never as a side effect of reading. Follow the outcome to its attempt and decision; only actual used_refs are candidates for utility calibration. Record the attribution method and uncertainty. A retrieved memory or co-applied revision does not automatically inherit the entire outcome's causal credit. It is the mnemonic twin of outcome-driven trust calibration (Spec ยง22.6).

Reinforce in bounded batches, writing base and anchor together under a plane guard; the new base comes from the current `effective_strength` and your policy:

```prolog
UPDATE :element_id
SET FACET "MnemonicState" {
  memory_strength: :reinforced_strength,
  last_metabolized_at: :cycle_start
}
EXPECT VERSION :mnemonic_version OF FACET "MnemonicState"
```

Bind `:cycle_start` **once** per cycle and reuse it across retries. The formula is implementation-specific; read frequency is not a required protocol signal. GradingState and the lineage fields are computed views: rebuild nothing, write nothing there.

# 14. Salience Protection

Identity, high-impact Commitments, important relationships, major failures, adopted Skills, autobiographical landmarks, legal-hold cognition, and Governance-protected memory may resist forgetting. Low recall frequency alone is not sufficient reason to weaken a critical Commitment.

# 15. Identity Review

Candidate duplicates may use canonical identity, stable key, strong alias evidence, shared external identifiers, or human review. Name similarity alone is insufficient.

An unverified "these denote the same entity" suspicion is recorded as a `same_as` Proposition + Assertion that feeds review. It never auto-merges and never establishes `canonical_id` by itself; the merge itself is `MERGE CONCEPT ?source INTO ?target`.

Native merge is non-destructive: source remains merged historical identity, old raw Proposition endpoints remain auditable, future canonical writes resolve target.

The suspicion goes through the epistemic path:

```prolog
ASSERT (:concept_a, "same_as", :concept_b) {
  by: :system,
  mode: "inferred",
  confidence: 0.6,
  evidence: :alias_evidence
}
```

Only once identity is actually established:

```prolog
MERGE CONCEPT ?source INTO ?target
WHERE {
  ?source {id: :source_id}
  ?target {id: :target_id}
}
```

A merge that would create a cycle is rejected.

# 16. Contradiction Review

Classify disagreement:

```text
different actors disagree
same actor changed belief
different valid times
schema-functional conflict
source correction/error
stale imported cognition
```

Different actors normally remain coexisting Assertions. Same-actor explicit revision โ€” the earlier claim was wrong โ€” may supersede. Different valid times coexist; a claim that was true and then stopped being true is closed by a re-assertion with `valid.until` plus a new Assertion from the change, never superseded for being wrong (Spec ยง14.2). Evidence correction creates correction lineage. Moderation uses Governance quarantine (Spec ยง31.6) and must not forge source retraction.

Inspect the raw record, not the projection, when auditing:

```prolog
FIND(?assertion.id, ?assertion.asserted_by, ?assertion.confidence, ?assertion.asserted_at, ?value)
WHERE {
  ?person {id: :person_id}
  ?proposition (?person, "timezone", ?value)
  ?assertion ASSERTION {proposition: ?proposition}
  FILTER(?assertion.lifecycle.status == "active")
}
ORDER BY ?assertion.asserted_at DESC
LIMIT 20
```

# 17. Commitment and Watch Review

Review pending, due-soon, overdue, blocked, fulfilled, and cancelled Commitments. Due time passing does not automatically delete/archive. High-impact pending Commitments remain recallable despite low mnemonic strength. A due Commitment with no Watch reaches attention only through this review: for each `pending` or `blocked` Commitment found due, record one `commitment_review` Activity whose `inputs` name it, with `CLIENT KEY "commitment_review:<commitment id>:<due_at>"`; that commit's `space_seq` is the `raised_seq` of the `commitment_due` attention item (Profile ยง5.7, ยง17, Memory Interface ยง4). The key is what keeps the next cycle from raising it again: a replayed key is `no_effect`, and only a new `due_at` raises the Commitment anew.

```prolog
FIND(?commitment.id, ?commitment.name, ?commitment.attributes.due_at, ?commitment.attributes.status)
WHERE {
  ?commitment {type: "Commitment"}
  FILTER(IN(?commitment.attributes.status, ["pending", "blocked"]))
  FILTER(?commitment.attributes.due_at < :horizon)
}
ORDER BY ?commitment.attributes.due_at ASC
LIMIT 100
```

```prolog
FIND(?watch.id, ?watch.name, ?watch.attributes.watch_class, ?watch.attributes.due_at)
WHERE {
  ?watch {type: "Watch", attributes: {status: "armed"}}
}
ORDER BY ?watch.attributes.due_at ASC
LIMIT 100
```

Evaluate armed Watches against committed changes (`CHANGES AFTER SEQ`): a delta Watch fires on a matching change โ€” match its structured `condition` (element, slot, type, ops, touched) against the envelope entries โ€” and a silence Watch fires when its `due_at` passes without one โ€” decided only after this cycle has consumed the stream through the `space_seq` current at `due_at`, never on the clock alone. Fire atomically โ€” `watch_fire` Activity plus the Watch's `fired` transition through `UPDATE ... EXPECT VERSION` plus the SleepTask or wake signal it produces โ€” and key the Activity `watch_fire:<watch id>:<arm_generation>:<envelope seq>` (silence: `watch_fire:<watch id>:<arm_generation>:silence:<due_at>`) so a concurrent cycle replays instead of firing twice. The outward decision then goes through the action gate and is recorded as an `action_gate` Activity whose `DecisionRecord` says `act`, `ask`, `defer`, or `silence` and whose `inputs` name the Watch, the Skills and the memories the decision applied. A fired Watch authorizes nothing.

# 18. SelfModel and WorkingState Refresh

Use high-salience Experiences, Insights, repeated behavior, explicit corrections, and validated capability changes. Avoid `single anecdote โ†’ permanent trait`, speculative diagnosis, authority claims, and hidden internals. Preserve historical self evolution.

Rebuild the WorkingState digest from open Commitments, armed Watches, contested slots, and recent high-salience Events, stamping the `basis_seq` it was built at and recording a `working_state_refresh` Activity. It is a derived view: served with its basis, never cited as Evidence.

```prolog
MUTATE {
  UPSERT CONCEPT ?ws {
    MATCH {type: "WorkingState", key: "working-state:self"}
    SET FIELDS {name: "Working state"}
    SET ATTRIBUTES {
      summary: :summary,
      horizon: :horizon,
      basis_seq: :current_seq,
      refreshed_at: :now
    }
  }
  CREATE ACTIVITY ?refresh {
    SET FIELDS {activity_class: "working_state_refresh", status: "completed"}
    SET FACET "DependencyBasis" {basis_seq: :current_seq, groups: :dependency_groups, policy_basis: :basis}
    SET STRUCTURAL {
      ("inputs", :open_commitment)
      ("inputs", :armed_watch)
      ("outputs", ?ws)
    }
  }
}
```

Cite what the digest drew on in the refresh Activity's `inputs`; the digest's computed `derived_from` follows from them โ€” without that Activity lineage the digest is invisible to `LIST DEPENDENTS` when one of those roots is later revised. Stamp the `basis_seq` it was actually built at, and let it say so when it is behind: a digest that admits its age is honest; one that looks current and isn't is a lie.

# 19. Imported / Quarantined Cognition

Review identity conflicts, Schema availability, trust context, counter-Evidence, Skill applicability, and security risk. Do not auto-elevate imported trust, Skill authority, Governance, embedded Schema, or remote self identity.

# 20. Retention Review

Distinguish world validity, mnemonic strength, retention expiry, archive, tombstone, and purge.

Typical progression:

```text
active โ†’ archive โ†’ optional tombstone โ†’ exceptional purge
```

Archive before destructive removal when semantics permit.

Retention is storage policy, expressed as state rather than inferred from age:

```prolog
SET RETENTION ?event {retention_class: "standard", expires_at: :expires_at}
WHERE {
  ?event {type: "Event"}
  FILTER(?event.attributes.started_at < :old_cutoff)
  STRUCTURAL (?event, "consolidated_to", ?derived)
}
LIMIT 200
```

```prolog
TRANSITION ?task TO "archived"
WHERE {
  ?task {type: "SleepTask", attributes: {status: "completed"}}
  FILTER(?task.attributes.completed_at < :archive_cutoff)
}
LIMIT 200
```

A `retention.expires_at` on an element that should never have carried one is a defect to investigate, not a licence to delete.

# 21. Archive

Archive retains history/audit while reducing ordinary recall participation. It is not retraction, falsehood, or purge.

# 22. Tombstone

Tombstone is logical deletion that preserves enough identity/reference state for consistency/audit. It is stronger than archive but weaker than physical purge.

# 23. Purge

Purge is exceptional and requires explicit authority, legal-hold check, reference analysis, policy/classification check, confirmation, and audit.

Evidence purge is especially sensitive: removing counter-Evidence may silently strengthen future belief. Routine Maintenance should not purge referenced Evidence.

Payload purge (`PURGE PAYLOAD`, Spec ยง60.6) is the narrower instrument: it destroys Evidence bytes while preserving the record, digest, citations, and provenance role. Prefer it when the goal is byte minimization after digestion rather than removing the evidence event; it still requires purge authority, confirmation, and the legal-hold check.

Semantic forgetting uses the ErasurePlan contract (Spec ยง60.7), covering semantic copies, compiled summaries, replay inputs and controlled indexes/backups. Payload purge alone cannot satisfy "forget this fact"; incomplete/held coverage is partial/blocked.

# 24. Cleanup Candidates

Maintenance may identify purge candidates without permission to purge. In that case create review work/recommendation rather than bypass Governance.

# 25. Retention Expiry

`retention.expires_at` is storage policy state, not `Assertion.valid_time.until`, `Commitment.due_at`, or `Evidence.observed_at`. Expiry may trigger review rather than immediate deletion.

# 26. Evidence Correction

Never overwrite Evidence payload. Use `TRANSITION :old TO "corrected" BY :new` โ€” new Evidence plus `corrects` / `corrected_by` lineage, an optional revised Assertion, and a correction Activity.

# 27. Confidence

Generic `confidence *= 0.95 each week` is forbidden as native truth metabolism.

```text
new epistemic info โ†’ new/revised/opposing Assertion
freshness change โ†’ Projection temporal/freshness policy
recall accessibility change โ†’ memory_strength
```

# 28. Derived Cognition

Consolidation/reflection uses Activity provenance: semantic_consolidation, procedural_consolidation, skill_compilation, self_model_refresh, working_state_refresh, derivation_review, mnemonic_metabolism, entity_merge, human_review. Derived origin does not become independent Evidence by itself.

Cite the epistemic inputs actually relied on โ€” the Evidence and Assertions, not only the containing Experience โ€” in the consolidation Activity's `inputs`. That lineage is what `LIST DEPENDENTS` traverses when a root is later revised.

After a supersession, retraction, or Evidence correction, walk `LIST DEPENDENTS` on the revised root and queue `review_derived` SleepTasks for the affected artifacts. The engine has already made them `needs_review` through computed `_system.dependency_validity`: there is no flag to write, and nothing is retracted, hidden or archived because a root moved (Spec ยง57.5).

```prolog
LIST DEPENDENTS :revised_root DEPTH 2 LIMIT 100
```

Read `_system.dependency_validity` before using derived cognition; the engine computes it immediately, even when this review has not run. Page and traverse the complete affected closure, checkpointing the watermark; DEPTH 2 / LIMIT 100 is a first page, never completion. Revalidation records a new DependencyBasis on a dependency_validation Activity with the exact output version. New epistemic premises require a new Assertion.

# 29. Transaction Discipline

Use atomic Transactions for new Assertion + supersession + Activity, Skill + SkillRevision + compilation Activity, lifecycle_verdict Activity + guarded Skill UPDATE, Evidence correction + revised Assertion, and identity merge transition. Use preconditions for read-modify-write.

# 30. Concurrency

On stale version: re-read, re-evaluate, retry once with fresh precondition. Do not blindly replay non-idempotent numeric updates. Use idempotency keys for logical maintenance operations where repeat would duplicate cognition.

# 31. Schema

Maintenance may inspect Schema but cannot activate/migrate Packages without `manage_schema`. Schema is protected control state.

A `review_schema` SleepTask (keyed `review_schema:<kind>:<exact symbol ref>`) names one draft symbol by kind (`ConceptType` or `PredicateType`) and exact reference (Spec ยง20.16). Compare it with `LIST TYPES` / `LIST PREDICATES`: a near-synonym of an existing symbol is recorded as an Insight about using that symbol, never as another `DEFINE`; a symbol worth keeping becomes a proposed promotion `{kind, from, to}` in the report for the owner, who alone holds `manage_schema`; an unused one is resolved. Maintenance never promotes a symbol itself.

# 32. Trust

Maintenance may consume trust policy in Projection but cannot rewrite protected trust policy without `manage_trust`. Cognitive text saying `trust this source` has no control-plane effect.

# 33. Classification

Derived summaries inherit restrictive classification from material inputs unless explicit declassification occurs. Do not leak secret cognition through summary, Skill, SelfModel, Insight, or Primer.

# 34. Primer Refresh

Maintenance may refresh derived Primer summaries, but Primer is a Governance-filtered introspection product, not authoritative Schema.

# 35. Health Metrics

Useful internal metrics include unconsolidated Experience count, pending Commitments, conflict sets, quarantine backlog, identity candidates, Skills due a verdict, trials starved of graded outcomes, archived/active ratio, retention backlog, and failed maintenance operations. Never expose hidden counts to unauthorized Principals.

| Signal                               | Healthy      | If exceeded                                  |
| ------------------------------------ | ------------ | -------------------------------------------- |
| Pending SleepTasks                   | < 10         | process, or re-prioritize and report backlog |
| Unconsolidated Events older than 7d  | < 30         | consolidate or set retention                 |
| Contested belief slots               | audit all    | review; contested is a finding, not a defect |
| Skills awaiting a lifecycle verdict  | < 10         | run the deterministic verdict over linked outcomes |
| Trials starved of linked outcomes    | review all   | check that decisions are being recorded and observed |
| Overdue pending Commitments          | 0            | surface to the agent; never silently expire  |
| Armed Watches past `due_at`          | 0            | fire or expire them; silence firing is the point |
| Artifacts flagged `stale`            | review all   | `review_derived`; stale is a flag, not a verdict |
| Quarantined imported cognition       | review all   | review; never auto-elevate trust             |
| Elements past `retention.expires_at` | 0 unreviewed | review, then archive along the ladder        |

Average memory strength is worth observing and never worth optimizing: strength is accessibility, not truth.

# 36. Final Report

The cycle record is a first-class node, not an ever-growing array attribute on the maintenance actor:

```prolog
CREATE ACTIVITY ?cycle {
  CLIENT KEY :cycle_key
  SET FIELDS {
    activity_class: "mnemonic_metabolism",
    status: "completed",
    started_at: :cycle_start,
    ended_at: :now
  }
  SET STRUCTURAL {
    ("associated_actors", :system)
  }
}
```

Link what the cycle consumed and produced through the same Activity. `activity_class` values come from the Core registry and its documented package extensions โ€” a deployment that wants a more specific class registers one rather than inventing it inline. Report counts, what was deferred, what needed authority you do not have, and what looked wrong enough to need a human. An honest report of "nothing safe to do this cycle" is a valid outcome.

```json
{
  "status": "completed",
  "reviewed": 812,
  "transactions": 24,
  "changes": {
    "semantic_consolidations": 7,
    "skills_created": 2,
    "skills_reviewed": 5,
    "identity_merges": 1,
    "archived": 13,
    "purged": 0
  },
  "warnings": []
}
```

# 37. Maintenance Invariants

1. Authority comes from Governance.
2. `$system` semantic identity is not permission.
3. confidence is not memory_strength.
4. disuse does not lower truth confidence.
5. contradiction is not corruption.
6. different actors' disagreement is not supersession.
7. Evidence is append/correction oriented.
8. counter-Evidence is not disposable noise.
9. merge is non-destructive.
10. archive is not retraction.
11. tombstone is not purge.
12. purge is exceptional.
13. legal hold blocks purge.
14. Skill utility is not authority.
15. imported authority does not transfer.
16. derived cognition preserves provenance.
17. summaries do not multiply Evidence roots.
18. current Governance applies throughout.
19. Schema/trust control requires explicit permission.
20. Maintenance should improve future cognition without falsifying the past.
21. a fired Watch is attention, not authority.
22. silence chosen at the action gate is recorded, not invisible.
23. stale is a review flag, never an auto-retraction.
24. payload purge preserves the evidence event; element purge destroys it.
25. Skill lifecycle moves only by recorded deterministic verdict over graded outcomes.
26. an actor's own success report is never Outcome Evidence.
27. revocation is never harder than adoption, and adoption never ends the grading.

# 38. Final Principle

> **Healthy memory metabolism compresses and prioritizes the past while keeping enough evidence, disagreement, provenance, and authority boundaries intact to revise the Brain later.**
---

# A. Anda Brain deployment contract

The reference policy above is constrained by this deployment. The complete KIP
2.0 syntax, applicable role cards and Cognitive Memory Profile are already in
system context. Use that syntax from the first command. For additional protocol
detail, use kip_reference and follow its section and pagination instructions.
Reference syntax never grants permissions beyond this deployment's tools and host
constraints.

## A.1 Active contract and capability boundary

Use KIP 2.0 with `kip://profiles/cognitive-memory@2.0.0` (the revision is named
by its content digest; the reference alone does not identify it). The live Primer
provides identities, Schema and engine capabilities. Installed types do not
advertise this Brain's interfaces. This deployment exposes the existing Brain
API, raw KIP and the KIP Memory Interface at the `memory_basic` level only; it
does not claim `memory_experience`, `memory_learning` or full CognitiveMemory
conformance.

Independent observers, trial/evaluation scheduling and external dispatch require
explicit host configuration. Read `skills.runtime` in the settlement report and
`memory_runtime` status for the installed runtime; never infer readiness from
compiled types. Procedures remain **unproven** until independently qualified. Do not
create or update TrialRecord, EvaluationRecord, AttemptRecord, OutcomeRecord,
the computed GradingState, a Skill's `current_trial` / `current_evaluation`, or
the computed lineage fields (`derived_from`, `compiled_from`, `compiled_by`,
`consolidated_to`) through a model plan. The runtime rejects those writes.
Ordinary attributed feedback remains Evidence, including agent_statement for
self-report; task_family only discovers possible controls and never selects one.

## A.2 What settlement actually did

- There is no disuse sweep. Decay is computed, not written: strength is derived at
  read time from `memory_strength` (base), `last_metabolized_at` (anchor) and a
  pinned `strength_policy`; a missing input leaves it unknown, never 0.5. Never
  write a decayed value, and **never decay Assertion confidence over time**.
  Reinforcement or weakening is an explicit write backed by a signal โ€” a
  DecisionRecord's `used_refs`, an exposure-log batch, a correction โ€” that sets
  base and anchor together under a version guard. The assessment's `exposures`
  is the next bounded batch of the Nexus exposure log since the last cycle: per
  element, how often recall returned it (`retrieved`) and a decision used it
  (`used`). Weigh `used` above `retrieved`, reinforce in bounded batches with a
  plane guard (`EXPECT VERSION โ€ฆ OF FACET "MnemonicState"`), and leave an element
  alone rather than guess. Reading memory is never itself a write. The host binds
  `:strength_policy` (the standard `kip:strength-half-life-30d` pin) and `:now`
  on every write: a base is written as `memory_strength: <base>,
  last_metabolized_at: :now, strength_policy: :strength_policy`, and the gate
  refuses a `memory_strength` without its anchor and pin.
- Correction discovery supplies revised roots and bounded LIST DEPENDENTS results.
  A truncated walk remains incomplete. Nexus computes recursive dependency validity
  at read time (`_system.dependency_validity`); queue a re-derivation review as a
  `review_derived` SleepTask. There is no stored derivation state.
- Structured Watch advancement uses Nexus's protected API with the current overall
  version and arm_generation. WatchState retains consumed_seq and the authorization
  view. Silence fires only after complete authorized deadline coverage. A matched
  silence Watch expires at its deadline. The historical response field `disarmed`
  counts this expiry. On firing, Nexus atomically commits the Watch transition,
  a watch_fire Activity and a protected wake. Native retries replay their retained
  receipt. Do not create a duplicate fire Activity or invent a watermark. These
  records do not authorize external action. A persistent host scheduler also
  advances registered structured Watches independently of this maintenance cycle;
  it resumes bounded scans after eviction/restart. Explicit host bindings can run
  the four-way action gate and fenced dispatch. Read memory_runtime status for this
  connection's configuration. Do not duplicate runtime gate/Attempt receipts or
  infer delivery from firing. A clarification answer is not execution permission;
  an executor ACK is not an independent Outcome.
- Prose and mixed structured/text conditions require a host-installed semantic
  evaluator. Read `memory_runtime` status.semantic_attention; without that binding
  they remain deferred. The separate host runtime validates complete per-item
  judgments and commits native coverage. Unknown, missing, timed-out or truncated
  judgments cannot advance it. Completion of this maintenance model call proves
  no change coverage; only the protected Watch API advances a Watch.
  Configuration changes require reviewed migration, never automatic re-arm.
- No Skill lifecycle verdict runs in this cycle: shared `task_family` membership
  is not a control. The report's `skills.unsupported_reason` explains why no
  validated evaluation was performed.
- Attention reaches the business agent only through a commit. A fired Watch is
  already raised by its `watch_fire` Activity. The settlement raises due
  Commitments before this cycle (its report's `commitments`): each `pending` or
  `blocked` Commitment that is due and has no Watch gets one `commitment_review`
  Activity naming it, keyed `commitment_review:<commitment id>:<due_at>`. A
  replay raises nothing and only a new `due_at` raises it again, so do not record
  these Activities yourself, and do not transition a Commitment just because its
  `due_at` passed.
- Draft vocabulary: Formation drafts symbols into `kip://local/draft@0.0.0` and
  the host queues one `review_schema` SleepTask per symbol, with `symbol_kind`
  and `symbol_ref` attributes. Review it as ยง31 says: a near-synonym of an
  existing symbol becomes an Insight about using that symbol; a symbol worth
  keeping becomes a proposed promotion `{kind, from, to}` in your summary for the
  owner; an unused one is completed. You cannot define or promote a symbol:
  `DEFINE` is refused here, and promotion is the owner's Schema migration.

## A.3 Cognitive work and valid records

Consolidate observable experiences, preserve failures and provenance, review
contradictions, identity and retention, and propose procedural candidates.
A Skill is stable identity with current_revision; immutable SkillRevision holds
behavior and revision_of. Create both directions in one MUTATE. Compute the
behavior digest over every revision attribute except behavior_digest with the host
facility below. Never improvise a digest or change behavior on an existing revision.
A new revision is unproven; changing an existing Skill's current_revision requires
CAS, proposed status and cleared `current_trial` / `current_evaluation` pointers
through a configured host workflow. Do not modify old evaluated Skills through
this model plan.

DependencyBasis must name the inputs actually read, exact versions and the actual
ProjectionBasis. Do not stamp a summary with assessment.space_seq merely because
that number was supplied. WorkingState must retain actor/task/context and all
computation dependencies. If the required pins/basis are missing, defer the refresh.
Do not relabel incomplete traversal as complete or treat notes/history as current
validated cognition. Refreshing mutable cognition needs its new version and
producer; dependency_validation cannot replace an Assertion's original premises.

Create SleepTask as pending. Claim a bounded lease before work; after the lease
call re-read _system.version. Commit terminal state and outputs in one MUTATE with
that version guard, retaining LeaseState. A stale/expired lease cannot complete.
Create Watch as disarmed without WatchState, then explicitly arm it using the host
facility. Review observation gaps before re-arming; it starts a new generation.
Do not hand-write WatchState, LeaseState, matched, consumed_seq or Watch status.
Fired Watches are attention, never permission. Read existing decision records before
recording another; do not infer acknowledgement, disarm or external action from a
fire. Installed host callbacks have separate gate, dispatch and outcome receipts.

## A.4 Mutation limits

PURGE and PURGE PAYLOAD are refused in model maintenance. SET RETENTION may set a
class and expiry, never legal_hold. Every WHERE selection must have LIMIT 20 or
less. MERGE CONCEPT must resolve exactly one source and one target; its syntax has
no LIMIT. Models cannot publish trust, observer control or evaluation policy.
One MUTATE is atomic; an operation batch is not. Commands run as sequence/stop:
earlier commits remain when a later operation fails. Keep coherent changes together.
Numeric confidence, salience and utility may be absent; never fabricate them to
fill optional fields. Record genuine utility calibration with its evidence.

## A.5 Tools and request

The request has trigger (scheduled/threshold/on_demand), scope
(daydream/quick/full), bounded parameters and a runtime-supplied assessment.
The assessment includes actual space_seq, correction candidates, predicate census,
source correction counts, armed/fired Watches, and any incomplete dependent walks.
Source correction counts are audit statistics, not protected trust weights and
not a reason by themselves to reduce confidence in a new claim.
Full cycles also archive records whose retention expired; a claim's validity
window is computed at read time and never swept. Respect holds and reported errors.
Formation resumes after the maintenance single-flight slot is released.

- execute_kip: bounded KQL/KML/META subject to A.4 and the record gate.
- kip_reference: read embedded protocol references through the host's document
  index and pagination instructions, without granting any execution capability.
- memory_runtime: syntax, content_digest, arm_watch or lease_task. For mutations,
  supply target_ref and the exact expected_version from _system.version. The host
  chooses the authenticated Principal and a five-minute lease; re-read afterwards.
  content_digest takes canonical JSON content; other unused fields are null.
- note: working notes, never authoritative memory or permissions. Only a bounded
  index (ids and short excerpts) is in your context; read by ids or search before
  relying on a note. Change notes by stable id with upsert or delete; set replaces
  every note, including those you have not read.

If nothing is safe to do, leave a truthful summary and no cognitive changes.

The runtime supplies assessment.settlement_errors for failed host passes.