engram-core 0.21.1

AI Memory Infrastructure - Persistent memory for AI agents with semantic search
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
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
# Engram — Complete AI Agent Guide

> **Version:** 0.21.1 | **Protocol:** MCP 2025-11-25 | **Tools:** [generated reference]MCP_TOOLS.md | **Schema:** v44

This guide shows agents how to turn scattered meetings, docs, transcripts, and project decisions into a shared source of truth that can be queried through MCP.

Use Engram when the problem is not model access, but organizing proprietary context so every agent can reach the same facts without reconstructing the same mental model.

The emphasis here is operational: ingest the material, structure it, search it, and expose it back to agents in a way that stays actionable.

---

## Table of Contents

1. [Connecting to Engram]#1-connecting-to-engram
2. [Core Concepts]#2-core-concepts
3. [Memory CRUD]#3-memory-crud
4. [Search]#4-search
5. [Cognitive Memory Types]#5-cognitive-memory-types
6. [Knowledge Graph]#6-knowledge-graph
7. [Identity & Cross-Reference]#7-identity--cross-reference
8. [Session Management]#8-session-management
9. [Workspace Organization]#9-workspace-organization
10. [Cloud Sync]#10-cloud-sync
11. [Multimodal Memory]#11-multimodal-memory
12. [Snapshots & Portability]#12-snapshots--portability
13. [Attestation Chain]#13-attestation-chain
14. [Retention Policies]#14-retention-policies
15. [Dream Snapshot Review Pipeline]#15-dream-snapshot-review-pipeline
16. [Project Context Scanning]#16-project-context-scanning
17. [Entity Extraction]#17-entity-extraction
18. [Semantic Deduplication]#18-semantic-deduplication
19. [Advanced Filtering]#19-advanced-filtering
20. [Multi-Agent Sync (Cloud)]#20-multi-agent-sync-cloud
21. [Transport Options]#21-transport-options
22. [Watcher Daemon]#22-watcher-daemon
23. [Recipes & Patterns]#23-recipes--patterns
24. [Tool Reference]#24-tool-reference
25. [Progressive Tool Discovery]#25-progressive-tool-discovery
26. [Session Handoff Protocol]#26-session-handoff-protocol
27. [Markdown Export]#27-markdown-export
28. [Recent Activity]#28-recent-activity

---

## 1. Connecting to Engram

### What this guide is for

Engram is a memory layer for teams that need to reduce information asymmetry. It is useful when:

- interviews, meetings, and docs accumulate faster than humans can index them manually
- not everyone on the team attends every conversation or research session
- decisions need to move quickly, but the relevant context is buried across many artifacts
- agents should be able to query the source of truth directly instead of relying on recollection

### Via MCP (stdio — default)

Add to your MCP client configuration:

```json
{
  "mcpServers": {
    "engram": {
      "command": "engram-server",
      "args": []
    }
  }
}
```

### Via HTTP Transport

```bash
engram-server --transport http --http-port 3000 --http-api-key sk_my_secret
```

Call tools via JSON-RPC 2.0 at `POST /mcp` (`POST /v1/mcp` is also accepted as
a compatibility alias). Include `Authorization: Bearer sk_my_secret` when
`--http-api-key` or `ENGRAM_HTTP_API_KEY` is configured:

```json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "memory_create",
    "arguments": {
      "content": "The user prefers dark mode",
      "type": "preference",
      "workspace": "settings"
    }
  }
}
```

### Via gRPC Transport

```bash
engram-server --transport grpc --grpc-port 50051 --grpc-api-key my-secret
```

Uses `proto/mcp.proto` — params and results are JSON strings inside protobuf messages.

### Via Engram Cloud (multi-tenant SaaS)

```bash
POST https://your-engram-api.fly.dev/v1/mcp
Authorization: Bearer eg_live_YOUR_API_KEY
X-Tenant: your-tenant-slug
Content-Type: application/json
```

Local HTTP MCP authentication is documented in [`docs/MCP_AUTH.md`](MCP_AUTH.md).

---

## 2. Core Concepts

### Memory Types

| Type | Purpose | Example |
|------|---------|---------|
| `note` | General information | "User's favorite color is blue" |
| `todo` | Action items | "Refactor the auth module" |
| `issue` | Bugs and problems | "Login fails on Safari" |
| `decision` | Architectural decisions | "We chose PostgreSQL over MySQL" |
| `preference` | User preferences | "Prefers TypeScript over JavaScript" |
| `learning` | Learned patterns | "This API requires pagination" |
| `context` | Session/project context | "Working on the payment module" |
| `credential` | Sensitive data | "API key stored in Vault" |
| `episodic` | Events with timestamps | "Deployed v2.0 at 14:30 UTC" |
| `procedural` | How-to patterns | "To deploy: run CI then approve PR" |
| `summary` | Compressed knowledge | "Summary of Q1 architecture decisions" |
| `checkpoint` | Stable reference points | "Sprint 5 state snapshot" |
| `image` | Image descriptions | "Architecture diagram of auth flow" |
| `audio` | Audio transcripts | "Meeting recording summary" |
| `video` | Video descriptions | "Demo walkthrough of onboarding" |

### Memory Tiers

| Tier | Behavior | `expires_at` |
|------|----------|-------------|
| `permanent` | Never expires, persists forever | Always `null` |
| `daily` | Auto-expires after TTL (default 24h) | Always set |

### Memory Scope

| Scope | Visibility | Use Case |
|-------|-----------|----------|
| `global` | System-wide | Shared knowledge |
| `user` | Persists across sessions for a user | User preferences |
| `session` | One conversation only | Temporary context |
| `agent` | Specific agent instance | Agent-private state |

### Lifecycle States

| State | In Search? | Meaning |
|-------|-----------|---------|
| `active` | Yes | Normal, recently accessed |
| `stale` | Yes | Not accessed recently |
| `archived` | No (unless `include_archived: true`) | Compressed or summarized |

### Memory Policy Boundary

Engram's memory policy layer ranks and manages explicit memories; it does not store canonical truth in model weights or hidden session state. SQLite rows, FTS, embeddings, graph edges, and provenance/audit records remain the inspectable source of truth.

---

## 3. Memory CRUD

### Create a Memory

```json
{
  "name": "memory_create",
  "arguments": {
    "content": "The client prefers communication via WhatsApp",
    "type": "preference",
    "tags": ["client", "communication"],
    "workspace": "crm",
    "importance": 0.8,
    "metadata": {
      "client_id": "12345",
      "source": "onboarding-call"
    }
  }
}
```

**Parameters:**

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `content` | string | Yes || Memory text (non-empty) |
| `type` | string | No | `note` | Memory type (see table above) |
| `tags` | string[] | No | `[]` | Searchable labels |
| `workspace` | string | No | `default` | Namespace (lowercase, `[a-z0-9_-]`, max 64 chars) |
| `importance` | float | No | `0.5` | 0.0–1.0 priority weight |
| `metadata` | object | No | `{}` | Arbitrary JSON key-value pairs |
| `scope` | string | No | `global` | Visibility scope |
| `tier` | string | No | `permanent` | `permanent` or `daily` |
| `ttl_seconds` | integer | No || Override TTL for daily tier |
| `defer_embedding` | boolean | No | `false` | Skip immediate embedding (batch later) |
| `dedup_mode` | string | No | `allow` | `allow`, `reject`, `skip`, `merge` |
| `dedup_threshold` | float | No | `0.95` | Similarity threshold for dedup |
| `media_url` | string | No || URL/path for multimodal memories |

### Create Daily (Auto-Expiring) Memory

```json
{
  "name": "memory_create_daily",
  "arguments": {
    "content": "Cached lookup: João Silva, CPF 123.456.789-00",
    "tags": ["person", "cpf:12345678900"],
    "workspace": "crm",
    "ttl_seconds": 86400
  }
}
```

Creates a `daily` tier memory that auto-expires. Perfect for caching API responses.

### Create Batch

```json
{
  "name": "memory_create_batch",
  "arguments": {
    "memories": [
      {"content": "Fact 1", "type": "note", "tags": ["import"]},
      {"content": "Fact 2", "type": "note", "tags": ["import"]},
      {"content": "Fact 3", "type": "note", "tags": ["import"]}
    ],
    "workspace": "knowledge"
  }
}
```

### Get a Memory

```json
{
  "name": "memory_get",
  "arguments": {"id": 42}
}
```

Returns the full memory including content, metadata, tags, timestamps, and importance.

### Get Public (Strips Private Sections)

```json
{
  "name": "memory_get_public",
  "arguments": {"id": 42}
}
```

Removes any `<private>...</private>` sections from content. Use when sharing memory externally.

### Update a Memory

```json
{
  "name": "memory_update",
  "arguments": {
    "id": 42,
    "content": "Updated preference: prefers Telegram over WhatsApp",
    "tags": ["client", "communication", "updated"],
    "importance": 0.9,
    "media_url": null
  }
}
```

All fields except `id` are optional. Pass `null` to clear nullable fields like `event_time`, `trigger_pattern`, or `media_url`.

### Delete a Memory

```json
{
  "name": "memory_delete",
  "arguments": {"id": 42}
}
```

### Delete Batch

```json
{
  "name": "memory_delete_batch",
  "arguments": {"ids": [42, 43, 44]}
}
```

### List Memories

```json
{
  "name": "memory_list",
  "arguments": {
    "workspace": "crm",
    "limit": 20,
    "offset": 0,
    "tags": ["client"],
    "type": "preference",
    "tier": "permanent"
  }
}
```

### List Compact (IDs + Titles Only)

```json
{
  "name": "memory_list_compact",
  "arguments": {
    "workspace": "crm",
    "limit": 50
  }
}
```

Returns lightweight entries — ideal for building UI lists or quick scans.

### Promote to Permanent

```json
{
  "name": "memory_promote_to_permanent",
  "arguments": {"id": 42}
}
```

Converts a `daily` memory to `permanent`. Clears `expires_at`.

### Boost Importance

```json
{
  "name": "memory_boost",
  "arguments": {
    "id": 42,
    "boost_amount": 0.1
  }
}
```

Increases importance score. Capped at 1.0.

---

## 4. Search

### Hybrid Search (Default)

```json
{
  "name": "memory_search",
  "arguments": {
    "query": "client communication preferences",
    "workspace": "crm",
    "limit": 10,
    "min_score": 0.3
  }
}
```

Engram combines **3 base retrieval signals**:

1. **BM25** — keyword matching via SQLite FTS5
2. **Vector similarity** — semantic embeddings (cosine similarity over BLOBs in the `embeddings` table)
3. **Fuzzy matching** — typo tolerance

Reciprocal Rank Fusion (RRF) merges those retrieval signals. The default heuristic reranker is controlled by the `rerank` parameter. Policy-based retrieval priority is separate and opt-in via `policy_rerank`.

**Search Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `query` | string || Search text |
| `limit` | integer | `10` | Max results |
| `min_score` | float | `0.0` | Minimum relevance threshold |
| `tags` | string[] || Filter by tags (AND logic) |
| `type` | string || Filter by memory type |
| `workspace` | string || Single workspace filter |
| `workspaces` | string[] || Multiple workspaces (OR) |
| `strategy` | string | `hybrid` | `hybrid`, `keyword_only`, `semantic_only` |
| `explain` | boolean | `false` | Include match explanations |
| `scope` | string || Scope filter |
| `tier` | string || Tier filter |
| `include_archived` | boolean | `false` | Include archived memories |
| `include_transcripts` | boolean | `false` | Include `transcript_chunk` type |
| `filter` | object || Advanced metadata filters |

### Search with Explanations

```json
{
  "name": "memory_search",
  "arguments": {
    "query": "authentication flow",
    "explain": true,
    "limit": 5
  }
}
```

Each result includes a breakdown of why it matched (keyword score, semantic score, recency boost, etc.).

### Search Suggestions

```json
{
  "name": "memory_search_suggest",
  "arguments": {
    "query": "authentcation"
  }
}
```

Returns spelling corrections and query suggestions.

### Cross-Workspace Search

```json
{
  "name": "memory_search",
  "arguments": {
    "query": "João Silva",
    "workspaces": ["crm", "notes", "sessions"]
  }
}
```

---

## 5. Cognitive Memory Types

### Episodic Memory (Events)

Record events with temporal context:

```json
{
  "name": "memory_create_episodic",
  "arguments": {
    "content": "Deployed v2.0 to production. Zero downtime.",
    "event_time": "2026-03-19T14:30:00Z",
    "event_duration_seconds": 300,
    "tags": ["deployment", "v2.0"],
    "workspace": "ops"
  }
}
```

Query events by time range:

```json
{
  "name": "memory_get_timeline",
  "arguments": {
    "start_time": "2026-03-01T00:00:00Z",
    "end_time": "2026-03-31T23:59:59Z",
    "workspace": "ops",
    "limit": 50
  }
}
```

### Procedural Memory (How-To Patterns)

Record learned procedures:

```json
{
  "name": "memory_create_procedural",
  "arguments": {
    "content": "To deploy: 1) Run CI pipeline 2) Wait for green 3) Approve PR 4) Merge to main 5) Monitor Grafana for 15 min",
    "trigger_pattern": "deploy to production",
    "tags": ["deployment", "runbook"],
    "workspace": "ops"
  }
}
```

Track outcomes to build success rates:

```json
{
  "name": "record_procedure_outcome",
  "arguments": {
    "id": 99,
    "success": true
  }
}
```

Query procedures filtered by success rate:

```json
{
  "name": "memory_get_procedures",
  "arguments": {
    "trigger_pattern": "deploy",
    "min_success_rate": 0.8,
    "workspace": "ops"
  }
}
```

### Summary Memory (Compressed Knowledge)

```json
{
  "name": "memory_create",
  "arguments": {
    "content": "Q1 2026: Shipped auth rewrite, migrated to PostgreSQL, onboarded 3 new devs. Key decision: chose gRPC over REST for internal services.",
    "type": "summary",
    "tags": ["q1-2026", "architecture"],
    "workspace": "decisions"
  }
}
```

### Checkpoint Memory (State Snapshots)

```json
{
  "name": "memory_checkpoint",
  "arguments": {
    "content": "Sprint 12 complete. Auth module stable. Payment integration 80% done. Blocking: Stripe webhook reliability.",
    "tags": ["sprint-12"],
    "workspace": "project"
  }
}
```

---

## 6. Knowledge Graph

### Link Memories

```json
{
  "name": "memory_link",
  "arguments": {
    "from_id": 10,
    "to_id": 20,
    "edge_type": "depends_on",
    "weight": 0.9
  }
}
```

**Built-in edge types:** `related_to`, `supersedes`, `contradicts`, `depends_on`, `implements`, `extends`, `references`, `derived_from`, `blocks`, `follows_up`

### Get Related Memories

```json
{
  "name": "memory_related",
  "arguments": {
    "id": 10,
    "relation": "depends_on",
    "limit": 10
  }
}
```

### Multi-Hop Graph Traversal (BFS)

```json
{
  "name": "memory_traverse",
  "arguments": {
    "start_id": 10,
    "max_depth": 3,
    "relation": "depends_on",
    "limit": 50
  }
}
```

Traverses the knowledge graph breadth-first from a starting memory.

### Find Shortest Path

```json
{
  "name": "memory_find_path",
  "arguments": {
    "source_id": 10,
    "target_id": 50,
    "max_depth": 5
  }
}
```

Returns the shortest path between two memories through the graph.

### Unlink Memories

```json
{
  "name": "memory_unlink",
  "arguments": {
    "source_id": 10,
    "target_id": 20,
    "relation": "depends_on"
  }
}
```

### Export Knowledge Graph

```json
{
  "name": "memory_export_graph",
  "arguments": {
    "workspace": "project",
    "format": "json"
  }
}
```

---

## 7. Identity & Cross-Reference

Unify multiple identifiers (CPF, phone, email) into a single identity:

### Create Identity

```json
{
  "name": "identity_create",
  "arguments": {
    "canonical_id": "person:12345678900",
    "display_name": "João Silva",
    "aliases": [
      "cpf:12345678900",
      "phone:+5511999887766",
      "email:joao@example.com"
    ]
  }
}
```

### Resolve Identity

```json
{
  "name": "identity_resolve",
  "arguments": {
    "alias": "phone:+5511999887766"
  }
}
```

Returns the canonical identity — look up any person by any known identifier.

### Add Alias

```json
{
  "name": "identity_add_alias",
  "arguments": {
    "canonical_id": "person:12345678900",
    "alias": "whatsapp:+5511999887766"
  }
}
```

---

## 8. Session Management

### Index a Conversation

```json
{
  "name": "session_index",
  "arguments": {
    "session_id": "chat-2026-03-19-001",
    "messages": [
      {"role": "user", "content": "What properties does João own?"},
      {"role": "assistant", "content": "João Silva owns 3 properties in São Paulo..."},
      {"role": "user", "content": "Show me the one in Pinheiros"},
      {"role": "assistant", "content": "The apartment at Rua dos Pinheiros..."}
    ],
    "workspace": "sessions"
  }
}
```

Creates searchable `transcript_chunk` memories from conversation turns.

### Search Past Sessions

```json
{
  "name": "memory_session_search",
  "arguments": {
    "query": "properties in Pinheiros",
    "workspace": "sessions",
    "limit": 5
  }
}
```

---

## 9. Workspace Organization

Workspaces are namespaces that isolate memories by domain.

**Rules:**
- Lowercase only: `[a-z0-9_-]`
- Max 64 characters
- Cannot start with `_` (reserved for system)
- Reserved names: `_system`, `_archive`

### Common Workspace Patterns

| Workspace | Purpose |
|-----------|---------|
| `default` | General-purpose |
| `crm` | Customer data, cached lookups |
| `notes` | User/broker notes |
| `sessions` | Conversation transcripts |
| `ops` | Operations, deployments, incidents |
| `decisions` | Architectural decisions |
| `knowledge` | Domain knowledge base |
| `agents` | Agent working state (M3) |

### Workspace Stats

```json
{
  "name": "memory_stats",
  "arguments": {
    "workspace": "crm"
  }
}
```

---

## 10. Cloud Sync

Engram can sync its SQLite database to S3-compatible cloud storage (AWS S3, Cloudflare R2, MinIO).

### Prerequisites

```bash
# Environment variables
export ENGRAM_STORAGE_URI=s3://your-bucket/memories.db
export ENGRAM_CLOUD_ENCRYPT=true  # AES-256 encryption

# For Cloudflare R2
export R2_ACCESS_KEY_ID=your-key
export R2_SECRET_ACCESS_KEY=your-secret
export AWS_ENDPOINT_URL=https://your-account.r2.cloudflarestorage.com
```

### Build with Cloud Feature

```bash
cargo build --release --features cloud
```

### Check Sync Status

```json
{
  "name": "memory_sync_status",
  "arguments": {}
}
```

Returns sync state: last sync time, pending changes, conflict count.

### Trigger Sync

Sync happens automatically on a debounced schedule. The sync layer:
- Detects local changes since last sync
- Uploads to S3/R2 with optional AES-256 encryption
- Handles conflict resolution (3-way merge)
- Supports bidirectional sync

### Media Asset Sync (Multimodal + Cloud)

```json
{
  "name": "memory_sync_media",
  "arguments": {
    "dry_run": true
  }
}
```

Uploads local media files (images, audio, video) from `media_assets` table to S3/R2. Set `dry_run: false` to actually upload.

**Requires:** `--features multimodal,cloud`

---

## 11. Multimodal Memory

Store and search across text, images, audio, and video.

### Create Image Memory

```json
{
  "name": "memory_create",
  "arguments": {
    "content": "Architecture diagram showing the auth flow: client -> gateway -> auth service -> database",
    "type": "image",
    "media_url": "local:///path/to/diagram.png",
    "tags": ["architecture", "auth"],
    "workspace": "docs"
  }
}
```

### Create Audio Memory

```json
{
  "name": "memory_create",
  "arguments": {
    "content": "Weekly standup recording. Key points: sprint on track, blocker on payments API",
    "type": "audio",
    "media_url": "https://storage.example.com/standup-2026-03-19.mp3",
    "tags": ["standup", "sprint-12"],
    "workspace": "meetings"
  }
}
```

### Create Video Memory

```json
{
  "name": "memory_create",
  "arguments": {
    "content": "Onboarding walkthrough demo: account creation, profile setup, first project",
    "type": "video",
    "media_url": "s3://media-bucket/onboarding-demo.mp4",
    "tags": ["onboarding", "demo"],
    "workspace": "docs"
  }
}
```

### Search by Image

```json
{
  "name": "memory_search_by_image",
  "arguments": {
    "image_url": "local:///path/to/query-image.png",
    "limit": 5,
    "workspace": "docs"
  }
}
```

Uses CLIP-style cross-modal embeddings. Falls back to vision model description + text search.

**Requires:** `--features multimodal`

---

## 12. Snapshots & Portability

Create portable `.egm` knowledge packages that can be shared between Engram instances.

### Create Snapshot

```json
{
  "name": "snapshot_create",
  "arguments": {
    "workspace": "knowledge",
    "output_path": "/tmp/broker-knowledge.egm",
    "encrypt": true,
    "passphrase": "my-secret-passphrase",
    "sign": true
  }
}
```

**Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `workspace` | string || Workspace to export |
| `output_path` | string || Where to save the `.egm` file |
| `encrypt` | boolean | `false` | AES-256-GCM encryption |
| `passphrase` | string || Required if `encrypt: true` |
| `sign` | boolean | `false` | Ed25519 digital signature |
| `tags` | string[] || Filter memories by tags |
| `include_graph` | boolean | `true` | Include knowledge graph edges |

### Load Snapshot

```json
{
  "name": "snapshot_load",
  "arguments": {
    "path": "/tmp/broker-knowledge.egm",
    "strategy": "merge",
    "passphrase": "my-secret-passphrase",
    "target_workspace": "imported-knowledge"
  }
}
```

**Load Strategies:**

| Strategy | Behavior |
|----------|----------|
| `merge` | Add new memories, skip duplicates (by content hash) |
| `replace` | Delete target workspace, then load all memories |
| `isolate` | Load into a separate workspace (no collision) |
| `dry_run` | Report what would happen without making changes |

### Inspect Snapshot

```json
{
  "name": "snapshot_inspect",
  "arguments": {
    "path": "/tmp/broker-knowledge.egm"
  }
}
```

Returns metadata: memory count, workspace, creation date, encryption status, signature status — without loading the data.

**Requires:** `--features agent-portability`

---

## 13. Attestation Chain

Track the provenance of knowledge — who ingested what, when, and with what hash.

### Log Attestation

```json
{
  "name": "attestation_log",
  "arguments": {
    "document_path": "/docs/api-spec.md",
    "content_hash": "sha256:abc123...",
    "source": "manual-import",
    "sign": true
  }
}
```

### Verify Document

```json
{
  "name": "attestation_verify",
  "arguments": {
    "content_hash": "sha256:abc123..."
  }
}
```

### Verify Chain Integrity

```json
{
  "name": "attestation_chain_verify",
  "arguments": {}
}
```

Verifies the entire attestation chain — each record links to its predecessor via SHA-256 hashes, forming a tamper-evident log.

### List Attestations

```json
{
  "name": "attestation_list",
  "arguments": {
    "format": "json",
    "limit": 20
  }
}
```

Formats: `json`, `csv`, `merkle_proof`.

**Requires:** `--features agent-portability`

---

## 14. Retention Policies

Automate memory lifecycle management — compress old memories, enforce limits, purge expired data.

### Set Retention Policy

```json
{
  "name": "memory_set_retention_policy",
  "arguments": {
    "workspace": "crm",
    "type": "note",
    "max_age_days": 90,
    "max_count": 1000,
    "compress_after_days": 30,
    "action": "archive"
  }
}
```

### Apply Retention Policies

```json
{
  "name": "memory_apply_retention_policies",
  "arguments": {}
}
```

Runs the 3-phase retention pipeline:
1. **Compress** — summarize old memories past `compress_after_days`
2. **Enforce max** — trim oldest memories when `max_count` exceeded
3. **Hard age** — delete/archive memories past `max_age_days`

### List Policies

```json
{
  "name": "memory_list_retention_policies",
  "arguments": {}
}
```

### Delete Policy

```json
{
  "name": "memory_delete_retention_policy",
  "arguments": {
    "id": 5
  }
}
```

---

## 15. Dream Snapshot Review Pipeline

Dream Snapshot Review Pipeline is planned in RFC 0007 as a reviewable memory
synthesis workflow. Dream jobs produce candidates for summaries, preferences,
constraints, stale facts, contradictions, merges, promotions, decay, and
temporal updates. Those candidates are proposals, not canonical memory.

Safety boundary:

- Candidate generation must not create, update, expire, promote, demote, or
  delete canonical memories.
- Applying a candidate requires explicit review and `confirm=true`.
- Unaccepted candidates do not appear in default memory or context search.
- Candidate provenance must point back to source memories, context events,
  artifacts, commits, issues, or harness records where available.
- Raw logs, raw transcripts, terminal dumps, secrets, and environment dumps are
  excluded by default.

Implementation and eval details:

- Contract: [`docs/rfcs/0007-dream-snapshot-review-pipeline.md`]rfcs/0007-dream-snapshot-review-pipeline.md
- Eval scaffold: [`docs/DREAM_SNAPSHOT_EVALS.md`]DREAM_SNAPSHOT_EVALS.md

The generated MCP tool reference remains the source of truth for live tools.
Do not call planned `dream_*` tools until they appear in
[`MCP_TOOLS.md`](MCP_TOOLS.md).

---

## 16. Project Context Scanning

Automatically discover and ingest AI instruction files from project directories.

### Scan Project

```json
{
  "name": "memory_scan_project",
  "arguments": {
    "path": "/Users/dev/my-project",
    "scan_parents": true,
    "extract_sections": true
  }
}
```

**Detected files:** `CLAUDE.md`, `AGENTS.md`, `.cursorrules`, `.github/copilot-instructions.md`, `GEMINI.md`, `.aider.conf.yml`, `.windsurfrules`, `CONVENTIONS.md`, `CODING_GUIDELINES.md`

Content is hashed for idempotency — rescanning the same file with unchanged content is a no-op.

### Get Project Context

```json
{
  "name": "memory_get_project_context",
  "arguments": {
    "path": "/Users/dev/my-project",
    "include_sections": true
  }
}
```

### List Instruction Files

```json
{
  "name": "list_instruction_files",
  "arguments": {
    "path": "/Users/dev/my-project",
    "scan_parents": true
  }
}
```

Lists detected files without ingesting them.

---

## 17. Entity Extraction

Extract named entities (people, organizations, technologies, locations) from memory content.

### Extract Entities

```json
{
  "name": "memory_extract_entities",
  "arguments": {
    "id": 42
  }
}
```

Idempotent — re-extracting from the same memory is safe.

### Search by Entity

```json
{
  "name": "memory_search_entities",
  "arguments": {
    "entity": "PostgreSQL",
    "limit": 10
  }
}
```

---

## 18. Semantic Deduplication

Prevent duplicate memories using embedding-based similarity detection.

### Find Duplicates

```json
{
  "name": "memory_find_semantic_duplicates",
  "arguments": {
    "workspace": "crm",
    "threshold": 0.9,
    "limit": 20
  }
}
```

Returns pairs of memories with cosine similarity above the threshold.

### Merge Duplicates

```json
{
  "name": "memory_merge",
  "arguments": {
    "source_id": 42,
    "target_id": 43
  }
}
```

Merges `source` into `target` — combines tags and metadata, deletes source.

### Create with Dedup

```json
{
  "name": "memory_create",
  "arguments": {
    "content": "User prefers dark mode",
    "dedup_mode": "skip",
    "dedup_threshold": 0.95,
    "workspace": "settings"
  }
}
```

| Mode | Behavior on Duplicate |
|------|-----------------------|
| `allow` | Create anyway (default) |
| `reject` | Return error |
| `skip` | Return existing memory |
| `merge` | Update existing with new tags/metadata |

---

## 19. Advanced Filtering

Use structured filters for complex queries beyond text search.

### Metadata Filters

```json
{
  "name": "memory_list",
  "arguments": {
    "workspace": "crm",
    "filter": {
      "AND": [
        {"metadata.client_id": {"eq": "12345"}},
        {"metadata.source": {"eq": "api"}}
      ]
    }
  }
}
```

### Filter Operators

| Operator | Example | Description |
|----------|---------|-------------|
| `eq` | `{"field": {"eq": "value"}}` | Exact match |
| `ne` | `{"field": {"ne": "value"}}` | Not equal |
| `gt` / `gte` | `{"field": {"gt": 5}}` | Greater than |
| `lt` / `lte` | `{"field": {"lt": 10}}` | Less than |
| `contains` | `{"field": {"contains": "sub"}}` | String contains |
| `in` | `{"field": {"in": ["a", "b"]}}` | Value in list |

### Combining Filters

```json
{
  "filter": {
    "OR": [
      {"metadata.priority": {"eq": "high"}},
      {"AND": [
        {"metadata.priority": {"eq": "medium"}},
        {"importance": {"gte": 0.8}}
      ]}
    ]
  }
}
```

---

## 20. Multi-Agent Sync (Cloud)

When using Engram Cloud, multiple AI agents can coordinate through shared memory.

### List Sessions by Agent

```json
{
  "name": "session_list_by_agent",
  "arguments": {
    "agent_id": "sales-agent-001"
  }
}
```

### Global Session Search (All Agents)

```json
{
  "name": "session_search_global",
  "arguments": {
    "query": "pricing discussion",
    "limit": 10
  }
}
```

Searches across all agents' session transcripts.

### Set Agent Context

```json
{
  "name": "agent_set_context",
  "arguments": {
    "agent_id": "sales-agent-001",
    "context": {
      "current_task": "follow-up-call",
      "client_cpf": "12345678900",
      "notes": "Client interested in 3BR apartment in Pinheiros"
    }
  }
}
```

Persists agent working state. Upsert semantics (creates or updates).

### Get Agent Context

```json
{
  "name": "agent_get_context",
  "arguments": {
    "agent_id": "sales-agent-001"
  }
}
```

Returns the agent's saved context + last 5 session summaries.

---

## 21. Transport Options

Engram server supports multiple transport protocols simultaneously.

### stdio (Default — MCP Standard)

```bash
engram-server
```

Used by Claude Desktop, Cursor, and other MCP clients.

### HTTP

```bash
engram-server --transport http --http-port 3000 --http-api-key sk_my_secret
```

- Endpoint: `POST /mcp` (`POST /v1/mcp` compatibility alias)
- Auth: `Authorization: Bearer sk_my_secret`
- Protocol: JSON-RPC 2.0

### gRPC

```bash
engram-server --transport grpc --grpc-port 50051 --grpc-api-key my-secret
```

- Proto: `proto/mcp.proto`
- Auth: Bearer token in gRPC metadata
- Streaming: `Subscribe` RPC for real-time events

### Both (stdio + HTTP)

```bash
engram-server --transport both --http-port 3000 --http-api-key sk_my_secret
```

---

## 22. Watcher Daemon

The Engram Watcher is a separate binary that proactively captures context from your environment.

### Three Capture Sources

| Source | What it Captures |
|--------|-----------------|
| **File System** | File changes in watched directories (debounced) |
| **Browser History** | URLs visited in Chrome/Firefox/Safari (polling) |
| **App Focus** | Which app has focus and for how long (platform-specific) |

### Running the Watcher

```bash
# Dry-run mode (log events, don't send)
engram-watcher --dry-run --verbose

# Normal mode (sends to engram-server via HTTP)
engram-watcher

# Custom config
engram-watcher --config /path/to/watcher.toml
```

### Configuration (`watcher.toml`)

```toml
engram_url = "http://localhost:3000"
workspace = "watcher"

[file_watcher]
enabled = true
paths = ["/home/user/projects", "/home/user/notes"]
extensions = ["rs", "md", "txt", "py", "ts"]
debounce_ms = 500
ignore_patterns = [".git", "node_modules", "target"]

[browser]
enabled = true
browsers = ["chrome", "firefox"]
poll_interval_secs = 60
exclude_patterns = ["localhost", "127.0.0.1", "about:"]

[app_focus]
enabled = false
poll_interval_secs = 5
min_focus_secs = 1
exclude_apps = ["Finder", "Dock"]
```

**Config location:**
- macOS: `~/Library/Application Support/engram/watcher.toml`
- Linux: `~/.config/engram/watcher.toml`

**Requires:** `--features watcher`

---

## 23. Recipes & Patterns

### Pattern 1: Cold Start — Seed a Knowledge Base

```json
{
  "name": "context_seed",
  "arguments": {
    "facts": [
      {"content": "Our API uses REST with JSON responses", "type": "context", "confidence": 0.95},
      {"content": "PostgreSQL 15 is the primary database", "type": "context", "confidence": 0.9},
      {"content": "All endpoints require Bearer token auth", "type": "context", "confidence": 1.0}
    ],
    "workspace": "project"
  }
}
```

Higher confidence → longer TTL. Confidence 1.0 creates permanent memories.

### Pattern 2: CRM Lookup Caching

```
1. Search Engram for cached data:
   memory_search("CPF 12345678900", workspace: "crm")

2. If no results, fetch from API and cache:
   memory_create_daily(content: "Person summary...", tags: ["person", "cpf:12345678900"], workspace: "crm", ttl_seconds: 86400)

3. Create identity for cross-reference:
   identity_create(canonical_id: "person:12345678900", display_name: "João", aliases: ["cpf:12345678900", "phone:+55..."])
```

### Pattern 3: Conversation Memory

```
1. During chat, save important insights:
   memory_create(content: "User wants 3BR in Pinheiros under R$2M", type: "preference", workspace: "notes")

2. After 4+ messages, index the conversation:
   session_index(session_id: "chat-001", messages: [...], workspace: "sessions")

3. In future chats, recall context:
   memory_search("apartment Pinheiros", workspaces: ["notes", "sessions", "crm"])
```

### Pattern 4: Decision Log

```
1. Record decisions as they happen:
   memory_create(content: "Chose gRPC for internal services — 3x faster than REST for our payload sizes", type: "decision", tags: ["architecture", "grpc"])

2. Link related decisions:
   memory_link(source_id: 10, target_id: 20, relation: "supports")

3. Later, review decision chain:
   memory_traverse(start_id: 10, max_depth: 3, relation: "supports")
```

### Pattern 5: Runbook with Tracking

```
1. Record the procedure:
   memory_create_procedural(content: "Deployment steps: ...", trigger_pattern: "deploy to prod")

2. After each deployment, record outcome:
   record_procedure_outcome(id: 99, success: true)
   record_procedure_outcome(id: 99, success: false)

3. Query reliable procedures:
   memory_get_procedures(trigger: "deploy", min_success_rate: 0.9)
```

### Pattern 6: Knowledge Package Distribution

```
1. Build knowledge base in workspace:
   memory_create(..., workspace: "broker-onboarding")

2. Package for distribution:
   snapshot_create(workspace: "broker-onboarding", output_path: "broker-kit.egm", encrypt: true, passphrase: "secret")

3. New broker loads the package:
   snapshot_load(path: "broker-kit.egm", strategy: "merge", passphrase: "secret", target_workspace: "my-knowledge")
```

### Pattern 7: Council Skill for Multi-Model Consensus

Use `memory_council` when you need a structured consensus step with optional checkpoint persistence:

Python (SDK helper):

```python
from engram_client import EngramClient
from engram_client.integrations import CouncilSkill

async def run_arch_review() -> None:
    async with EngramClient(
        base_url="https://your-engram-api.fly.dev",
        api_key="ek_...",
        tenant="my-tenant",
    ) as client:
        council = CouncilSkill(
            client,
            default_workspace="architecture",
            default_timeout_seconds=120,
            default_include_raw_stages=False,
        )
        decision = await council.ask_with_persistence(
            "Should we use UUIDv7 or ULID?"
        )
        print(decision)
```

TypeScript (SDK helper):

```typescript
import { CouncilSkill, EngramClient } from "engram-client";

const client = new EngramClient({
  baseUrl: "https://your-engram-api.fly.dev",
  apiKey: "ek_...",
  tenant: "my-tenant",
});

const council = new CouncilSkill(client, {
  defaultWorkspace: "architecture",
  defaultTimeoutSeconds: 120,
  defaultIncludeRawStages: false,
});

const decision = await council.askWithPersistence("Should we use UUIDv7 or ULID?");
```

If this repository is used in Claude/agent workflows, also use the reusable skill
at `skills/engram-council/SKILL.md` to standardize the same consensus routine
across projects.

### Pattern 8: Graceful Degradation

Always handle Engram being unavailable:

```python
try:
    result = engram.search("query", workspace="crm")
except Exception:
    result = None  # Engram is optional — continue without cached data

# The app works with or without memory
if result:
    use_cached_data(result)
else:
    fetch_from_primary_api()
```

---

## 24. Tool Reference

### Quick Reference Table

| Category | Tools |
|----------|-------|
| **CRUD** | `memory_create`, `memory_get`, `memory_get_public`, `memory_update`, `memory_delete`, `memory_create_batch`, `memory_delete_batch` |
| **List** | `memory_list`, `memory_list_compact` |
| **Search** | `memory_search`, `memory_search_suggest`, `memory_search_by_image` |
| **Lifecycle** | `memory_create_daily`, `memory_promote_to_permanent`, `memory_boost`, `memory_checkpoint` |
| **Cognitive** | `memory_create_episodic`, `memory_create_procedural`, `memory_get_timeline`, `memory_get_procedures`, `record_procedure_outcome` |
| **Graph** | `memory_link`, `memory_unlink`, `memory_related`, `memory_traverse`, `memory_find_path`, `memory_export_graph` |
| **Identity** | `identity_create`, `identity_resolve`, `identity_add_alias` |
| **Session** | `session_index`, `memory_session_search` |
| **Dedup** | `memory_find_semantic_duplicates`, `memory_merge` |
| **Retention** | `memory_set_retention_policy`, `memory_get_retention_policy`, `memory_list_retention_policies`, `memory_delete_retention_policy`, `memory_apply_retention_policies` |
| **Entities** | `memory_extract_entities`, `memory_search_entities` |
| **Context** | `context_seed`, `memory_scan_project`, `memory_get_project_context`, `list_instruction_files` |
| **Snapshot** | `snapshot_create`, `snapshot_load`, `snapshot_inspect` |
| **Attestation** | `attestation_log`, `attestation_verify`, `attestation_chain_verify`, `attestation_list` |
| **Cloud** | `memory_sync_status`, `memory_sync_media` |
| **Admin** | `memory_stats` |
| **Multi-Agent** | `memory_council`, `session_list_by_agent`, `session_search_global`, `agent_set_context`, `agent_get_context` |

### Tool Annotations

Every tool includes MCP 2025-11-25 annotations:

| Annotation | Meaning |
|------------|---------|
| `readOnlyHint: true` | Safe to call — no data changes |
| `destructiveHint: true` | Modifies or deletes data |
| `idempotentHint: true` | Safe to retry — same result on repeated calls |

### Feature Gates

| Feature Flag | Required For |
|-------------|-------------|
| `cloud` | `memory_sync_status`, `memory_sync_media` (with multimodal) |
| `multimodal` | `memory_search_by_image`, Image/Audio/Video types |
| `agent-portability` | `snapshot_*`, `attestation_*` |
| `watcher` | `engram-watcher` binary |
| `grpc` | gRPC transport |
| `openai` | OpenAI embeddings (vs default TF-IDF) |

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `ENGRAM_DB_PATH` | SQLite database path | `~/.local/share/engram/memories.db` |
| `ENGRAM_STORAGE_URI` | S3 URI for cloud sync ||
| `ENGRAM_CLOUD_ENCRYPT` | AES-256 encryption for cloud | `false` |
| `ENGRAM_EMBEDDING_MODEL` | `tfidf` or `openai` | `tfidf` |
| `OPENAI_API_KEY` | Required for OpenAI embeddings ||
| `R2_ACCESS_KEY_ID` | Cloudflare R2 access key ||
| `R2_SECRET_ACCESS_KEY` | Cloudflare R2 secret ||
| `AWS_ENDPOINT_URL` | Custom S3 endpoint ||
| `ENGRAM_S3_BUCKET` | S3 bucket for media sync ||
| `ENGRAM_MEDIA_PUBLIC_DOMAIN` | CDN domain for media URLs ||

---

## Performance Targets

| Operation | Target |
|-----------|--------|
| Create memory (no embedding) | < 200 µs |
| Get by ID | < 100 µs |
| Hybrid search (100K+ memories) | < 10 ms |
| Entity extraction | < 50 ms |
| Snapshot create (1K memories) | < 1 s |
| Snapshot load (1K memories) | < 2 s |

---

## 25. Progressive Tool Discovery

Engram exposes the generated tool set shown in the MCP reference. To avoid overwhelming agents, tools are organized into three tiers:

| Tier | Description |
|------|-------------|
| **Essential** | Core tools every agent needs: CRUD, search, stats, sessions |
| **Standard** | Common operations: lifecycle, quality, identity, context engineering |
| **Advanced** | Specialized: compression, evolution, attestation, multimodal |

### Controlling Exposure

Set `ENGRAM_TOOL_TIER` to control which tools are listed:

```bash
# Only essential tools — great for simple agents
ENGRAM_TOOL_TIER=essential cargo run --bin engram-server

# Essential + standard — recommended for most agents
ENGRAM_TOOL_TIER=standard cargo run --bin engram-server

# All tools (default, backward compatible)
ENGRAM_TOOL_TIER=all cargo run --bin engram-server
```

### Discovering Tools

The `discover_tools` tool is always available regardless of tier setting:

```json
{"tool": "discover_tools", "params": {"tier": "standard"}}
{"tool": "discover_tools", "params": {"category": "search"}}
{"tool": "discover_tools", "params": {"search": "graph"}}
```

Response includes tool names, descriptions, tiers, and summary counts. Agents can progressively discover capabilities as needed.

---

## 26. Session Handoff Protocol

Inspired by Beads' "land the plane" pattern, Engram provides a structured end-of-session handoff:

### session_land Tool

```json
{
  "tool": "session_land",
  "params": {
    "session_id": "coding-session-42",
    "workspace": "default",
    "summary": "Implemented auth middleware and wrote unit tests",
    "next_session_hints": [
      "Integration tests still needed",
      "Review rate limiting config"
    ]
  }
}
```

Returns a structured handoff with:
- **summary** — what was accomplished
- **open_items** — unfinished todos and issues
- **recent_decisions** — decisions made in the last 24h
- **bootstrap_prompt** — ready-to-use prompt to start the next session

A checkpoint memory is automatically created with the handoff data.

### session-handoff Prompt

Use the MCP prompt for a guided workflow:

```json
{"method": "prompts/get", "params": {"name": "session-handoff", "arguments": {"session_id": "my-session"}}}
```

This guides you through: summarize progress → capture open items → call session_land → report bootstrap prompt.

---

## 27. Markdown Export

Export memories as human-readable Markdown files, inspired by Basic Memory:

```json
{
  "tool": "memory_export_markdown",
  "params": {
    "workspace": "default",
    "output_dir": "./my-knowledge-base/",
    "include_links": true
  }
}
```

### Output Structure

```
my-knowledge-base/
├── index.md                    # Workspace overview + table of contents
├── notes/
│   ├── 42-project-architecture.md
│   └── 57-api-design-notes.md
├── decisions/
│   └── 63-chose-postgresql.md
└── todos/
    └── 71-add-rate-limiting.md
```

### File Format

Each file includes YAML frontmatter and optional wiki-style `[[links]]`:

```markdown
---
id: 42
type: note
tags: ["architecture", "backend"]
importance: 0.80
tier: permanent
created_at: "2026-03-20T10:30:00Z"
---

Project architecture uses a layered approach with...

## Related

- relates_to [[63-chose-postgresql]]
- supports [[57-api-design-notes]]
```

---

## 28. Recent Activity

Discover what changed recently with the `recent_activity` tool:

```json
{
  "tool": "recent_activity",
  "params": {
    "workspace": "default",
    "timeframe": "24h",
    "limit": 10
  }
}
```

Returns compact previews sorted by most recent activity:

```json
{
  "activities": [
    {
      "id": 42,
      "preview": "Project architecture uses a layered approach with...",
      "memory_type": "note",
      "tags": "architecture,backend",
      "created_at": "2026-03-20T10:30:00Z",
      "updated_at": "2026-03-20T14:15:00Z"
    }
  ],
  "count": 1,
  "timeframe": "24h"
}
```

Timeframe options: `"1h"`, `"24h"`, `"7d"`, `"30d"`.

### Enhanced Context Building

`memory_build_context` now supports depth traversal and timeframe filtering:

```json
{
  "tool": "memory_build_context",
  "params": {
    "query": "authentication",
    "depth": 2,
    "timeframe": "7d",
    "include_types": ["note", "decision"],
    "include_graph": true,
    "total_budget": 4096
  }
}
```

- **depth** (1-3): Follow related memory links for richer context
- **timeframe**: Filter to recent memories only
- **include_types**: Restrict to specific memory types
- **include_graph**: Include entity relationship edges in response

---

## Salience

Controls how memories surface in retrieval based on computed importance and recency signals.

| Tool | Description | Key Parameters |
|------|-------------|----------------|
| `salience_get` | Get salience score for a memory | `id` |
| `salience_set_importance` | Override base importance score | `id`, `importance` (0.0–1.0) |
| `salience_boost` | Temporarily boost salience | `id`, `boost_amount`, `duration_hours` |
| `salience_demote` | Temporarily reduce salience | `id`, `demote_amount` |
| `salience_decay_run` | Trigger a decay pass for a workspace | `workspace` |
| `salience_stats` | Salience distribution stats for a workspace | `workspace` |
| `salience_history` | Salience score history over time | `id`, `limit` |
| `salience_top` | Top-N memories by current salience | `workspace`, `limit`, `memory_type` |

---

## Quality

Quality scoring, duplicate detection, conflict resolution, and source trust management.

| Tool | Description | Key Parameters |
|------|-------------|----------------|
| `quality_score` | Compute quality score for a memory | `id` |
| `quality_report` | Quality summary for a workspace | `workspace` |
| `quality_find_duplicates` | Scan for near-duplicate memories | `workspace`, `threshold` |
| `quality_get_duplicates` | Retrieve previously found duplicate sets | `workspace` |
| `quality_find_conflicts` | Detect contradicting memories | `workspace` |
| `quality_get_conflicts` | Retrieve previously found conflicts | `workspace` |
| `quality_resolve_conflict` | Mark a conflict as resolved with a strategy | `conflict_id`, `resolution_strategy`, `winning_id` |
| `quality_improve` | Apply automated quality improvements to a memory | `id` |

---

## Session Context

Manage per-session memory windows for context-aware retrieval and export.

| Tool | Description | Key Parameters |
|------|-------------|----------------|
| `session_context_create` | Create a new session context | `session_id`, `workspace`, `description` |
| `session_context_add_memory` | Add a memory to the session window | `session_id`, `memory_id` |
| `session_context_remove_memory` | Remove a memory from the session window | `session_id`, `memory_id` |
| `session_context_get` | Get session context and its memories | `session_id` |
| `session_context_list` | List all active session contexts | `workspace` |
| `session_context_search` | Search within a session's memory window | `session_id`, `query` |
| `session_context_update_summary` | Update the session's running summary | `session_id`, `summary` |
| `session_context_end` | Close a session and optionally export | `session_id` |
| `session_context_export` | Export session context as structured data | `session_id`, `format` |

---

## Scope & Access Control

Hierarchical memory scoping with `global/org/project/agent` path structure and per-agent access grants.

| Tool | Description | Key Parameters |
|------|-------------|----------------|
| `memory_scope_set` | Set scope path on a memory | `id`, `scope_path` |
| `memory_scope_get` | Get the scope path of a memory | `id` |
| `memory_scope_list` | List memories under a scope path | `scope_path`, `recursive` |
| `memory_grant_access` | Grant read/write access to an agent | `scope_path`, `agent_id`, `permission` |
| `memory_revoke_access` | Revoke an agent's access grant | `scope_path`, `agent_id` |
| `memory_list_grants` | List all grants for a scope path | `scope_path` |
| `memory_check_access` | Check if an agent can access a scope | `scope_path`, `agent_id`, `permissions` |

---

## Workspaces

Manage isolated memory namespaces.

| Tool | Description | Key Parameters |
|------|-------------|----------------|
| `workspace_list` | List all workspaces ||
| `workspace_stats` | Memory counts and stats for a workspace | `workspace` |
| `workspace_move` | Move memories from one workspace to another | `from_workspace`, `to_workspace`, `filter` |
| `workspace_delete` | Delete a workspace and all its memories | `workspace`, `confirm` |

---

## Smart Retrieve

Intent-aware unified retrieval — combines semantic search, graph traversal, and temporal context in a single call.

| Tool | Description | Key Parameters |
|------|-------------|----------------|
| `memory_smart_retrieve` | Retrieve memories matching an intent-aware query | `query`, `intent` (`explore`/`focus`/`recent`), `workspace`, `limit` |

**Intent values:**
- `explore` — broad semantic search, favours diversity
- `focus` — precision retrieval, top matches only
- `recent` — recency-weighted, useful for "what was I just working on?"

---

*Engram v0.21.1 - AI Memory Engine*
*MCP tool reference: [MCP_TOOLS.md](MCP_TOOLS.md) (generated) | Hybrid search | Knowledge graphs | Cloud sync | Multimodal | Agent portability | Progressive discovery*