@dzhechkov/keysarium-core 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -13,7 +13,7 @@ Think of it as the "operating system" for multi-agent workflows. You bring the d
13
13
  | Module | Purpose | Key Protocols |
14
14
  |--------|---------|---------------|
15
15
  | **governance/** | Structural rules and human checkpoints | Constitution, shard protocol, promise tags |
16
- | **memory/** | Persistent learning across executions | memory_query, memory_store, reward tracking, dream cycles |
16
+ | **memory/** | Persistent learning across executions | memory_query, memory_store, reward tracking, dream cycles, **2-tier index, COW branching, record lifecycle (v1.1)** |
17
17
  | **orchestration/** | Agent coordination and model routing | Queen protocol, 6 topologies, background workers, 3-tier routing |
18
18
  | **verification/** | Cryptographic integrity and isolation proofs | SHA-256 witness chain, judge attestation, audit trail |
19
19
  | **trust-tiers/** | Skill/artifact quality classification | 4-tier system (Advisory to Verified), promotion protocol |
@@ -71,9 +71,13 @@ keysarium-core has **zero dependencies** on either consumer package. Both consum
71
71
  - `shard-protocol.md` — How to create per-stage governance rules that are reloaded at each stage to prevent context drift
72
72
  - `checkpoint-protocol.md` — Human synchronization points with promise tags for machine-readable completion signals
73
73
 
74
- ### Memory
74
+ ### Memory (v1.1)
75
75
 
76
- - `memory-protocol.md` — Core `memory_query()` / `memory_store()` protocol for loading and persisting execution patterns with reward scores
76
+ - `memory-protocol.md` — Core `memory_query()` / `memory_store()` protocol with reward scores. **v1.1 enhancements:**
77
+ - **2-Tier Index** — `index.json` catalog for targeted reads instead of full directory scans
78
+ - **Brain Container Schema** — Portable brain exports with SHA-256 manifest and checksum verification
79
+ - **COW Branching** — Delta brain exports via JSON Patch (RFC 6902) for incremental knowledge transfer
80
+ - **Record Lifecycle** — HOT/WARM/COLD/PURGE tiering with automatic archive compression
77
81
  - `reward-tracker.md` — Analytics engine: per-stage averages, per-domain breakdowns, bottleneck detection, trend analysis
78
82
  - `dream-engine.md` — Background consolidation: builds concept graphs from accumulated data and generates cross-domain insights
79
83
 
@@ -120,6 +124,7 @@ keysarium-core was extracted from the [Keysarium](https://github.com/dzhechko/pr
120
124
  - **Ruflo** — 7-layer governance, 6 topologies, 3-tier model routing
121
125
  - **Agentic QE** — Trust tiers, reward-calibrated learning, dream cycles, PACT principles
122
126
  - **Quality Forge** — Portable brain containers, SHA-256 witness chains
127
+ - **RVF (RuVector Format)** — Manifest catalogs, COW branching, progressive loading, data tiering (concepts adapted to JSON-native implementation)
123
128
 
124
129
  ## License
125
130
 
package/index.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # keysarium-core Module Index
2
2
 
3
- > Manifest of all modules in @dzhechkov/keysarium-core v1.0.0
3
+ > Manifest of all modules in @dzhechkov/keysarium-core v1.1.0
4
4
 
5
5
  ## Module Registry
6
6
 
7
7
  | Module | Version | Files | Trust Tier | Description |
8
8
  |--------|---------|-------|------------|-------------|
9
9
  | governance | 1.0 | 3 | Tier 1 — Structured | Constitution, shards, checkpoints |
10
- | memory | 1.0 | 3 | Tier 1 — Structured | Reward-calibrated learning + dream cycles |
10
+ | memory | 1.1 | 3 | Tier 1 — Structured | Reward-calibrated learning + dream cycles + index + tiering + COW |
11
11
  | orchestration | 1.0 | 4 | Tier 1 — Structured | Coordinator protocol + topologies + workers |
12
12
  | verification | 1.0 | 3 | Tier 1 — Structured | Hash chains + judge attestation + audit trail |
13
13
  | trust-tiers | 1.0 | 2 | Tier 1 — Structured | 4-tier classification + promotion |
@@ -27,7 +27,7 @@
27
27
  │ └── checkpoint-protocol.md ← v1.0 — Checkpoints + promise tags
28
28
 
29
29
  ├── memory/
30
- │ ├── memory-protocol.md ← v1.0 — memory_query + memory_store
30
+ │ ├── memory-protocol.md ← v1.1 — memory_query + memory_store + index + tiering + COW
31
31
  │ ├── reward-tracker.md ← v1.0 — Analytics + pattern detection
32
32
  │ └── dream-engine.md ← v1.0 — Background insight generation
33
33
 
@@ -59,6 +59,7 @@
59
59
  | Version | Date | Changes |
60
60
  |---------|------|---------|
61
61
  | 1.0 | 2026-03-01 | Initial extraction from Keysarium v1.1.x and lib/ protocols |
62
+ | 1.1 | 2026-03-02 | Memory module v1.1: 2-tier index, record lifecycle (HOT/WARM/COLD/PURGE), brain container manifest, COW branching |
62
63
 
63
64
  ## Dependency Graph
64
65
 
@@ -75,7 +76,7 @@ All modules are independent. A consumer may use any subset of modules without im
75
76
 
76
77
  ## Schema Compatibility
77
78
 
78
- All JSON schemas defined in this package use `"version": "1.0"` as a schema version field. Consumers should check this field and warn if it does not match expected version.
79
+ JSON schemas use `"version"` as a schema version field. Memory module uses `"1.1"`, all other modules use `"1.0"`. Consumers should check this field and warn if it does not match expected version. v1.1 readers MUST accept v1.0 files for backward compatibility.
79
80
 
80
81
  ## Terminology Mapping
81
82
 
@@ -1,6 +1,8 @@
1
1
  # Memory Protocol — Reward-Calibrated Learning
2
2
 
3
3
  > Core protocol for persistent memory in multi-agent pipelines. Provides `memory_query()` before stages and `memory_store()` after stages.
4
+ >
5
+ > **Protocol version: 1.1** — adds Index, Brain Container Schema, COW Branching, and Record Lifecycle.
4
6
 
5
7
  ## Overview
6
8
 
@@ -13,13 +15,17 @@ All memory files live in a dedicated directory:
13
15
  ```
14
16
  {memory-root}/
15
17
  ├── config.json ← Global configuration
18
+ ├── index.json ← 2-tier index (v1.1)
16
19
  ├── _patterns/
17
20
  │ └── domain-patterns.json ← Detected domain patterns
18
21
  ├── _stats/
19
22
  │ └── reward-summary.json ← Aggregate statistics
20
23
  ├── {domain}/ ← Domain-specific subdirectory
21
- └── {project-slug}/
22
- └── {stage}_{timestamp}.json ← Individual reward records
24
+ ├── {project-slug}/
25
+ └── {stage}_{timestamp}.json ← HOT/WARM reward records
26
+ │ └── _archive/ ← COLD compressed records (v1.1)
27
+ │ └── {project-slug}/
28
+ │ └── {stage}_{timestamp}.json ← Archived records
23
29
  ```
24
30
 
25
31
  The `{memory-root}` defaults to `.keysarium/memory/` but can be configured.
@@ -30,7 +36,7 @@ The `{memory-root}` defaults to `.keysarium/memory/` but can be configured.
30
36
 
31
37
  ```json
32
38
  {
33
- "version": "1.0",
39
+ "version": "1.1",
34
40
  "retention_days": 90,
35
41
  "max_results_per_query": 10,
36
42
  "enabled": true,
@@ -40,10 +46,15 @@ The `{memory-root}` defaults to `.keysarium/memory/` but can be configured.
40
46
  "good": 0.7,
41
47
  "needs_work": 0.3,
42
48
  "failed": 0.0
43
- }
49
+ },
50
+ "tier_hot_days": 30,
51
+ "tier_warm_days": 90,
52
+ "tier_cold_days": 180
44
53
  }
45
54
  ```
46
55
 
56
+ **Tier fields (v1.1):** If `tier_hot_days` is absent, fall back to v1.0 behavior (flat `retention_days` with no tiering). When present, `retention_days` is ignored in favor of the tier thresholds.
57
+
47
58
  ## Protocol: memory_query(context)
48
59
 
49
60
  Call at the **start** of each pipeline stage to load relevant historical patterns.
@@ -62,12 +73,16 @@ Call at the **start** of each pipeline stage to load relevant historical pattern
62
73
  ### Algorithm
63
74
 
64
75
  1. **Check enabled:** Read `{memory-root}/config.json`. If `enabled` is false or directory does not exist, return empty result.
65
- 2. **Resolve path:** Construct `{memory-root}/{domain}/` (scan all project slugs, not just current).
66
- 3. **Scan records:** Read all `{stage}_*.json` files matching the requested stage across all slugs in the domain.
76
+ 2. **Read index (v1.1):** If `{memory-root}/index.json` exists, read it and filter `records` entries by `domain` + `stage`. Go to step 2a. If index does not exist, fall back to step 3 (v1.0 full scan).
77
+ - 2a. **Index hit:** If filtered record count ≤ `max_results_per_query`, read only those files by `file` path (Tier 2 targeted read). Go to step 4.
78
+ - 2b. **Index overflow:** If filtered count > limit, rank by `reward` from index entries, select top-N `file` paths, read those files. Go to step 4.
79
+ 3. **Full scan (fallback):** Construct `{memory-root}/{domain}/` (scan all project slugs). Read all `{stage}_*.json` files matching the requested stage.
67
80
  4. **Filter expired:** Exclude records where `expires_at < current_date`.
68
- 5. **Sort:** By `reward` DESC, then `timestamp` DESC.
69
- 6. **Limit:** Return top `max_results_per_query` records (default 10).
70
- 7. **Enrich:** Also load `{memory-root}/_patterns/domain-patterns.json` for matching domain patterns.
81
+ 5. **Archive old records (v1.1):** If tier config is present, check record ages. Move records older than `tier_cold_days` to `{memory-root}/{domain}/_archive/{slug}/` in compressed format (see Record Lifecycle). Update `index.json`.
82
+ 6. **Purge ancient records (v1.1):** Delete records from `_archive/` older than `tier_cold_days * 2` (default 360 days). Update `index.json`. In v1.0 mode, delete records where `expires_at < current_date`.
83
+ 7. **Sort:** By `reward` DESC, then `timestamp` DESC.
84
+ 8. **Limit:** Return top `max_results_per_query` records (default 10). HOT and WARM records are preferred; COLD records are included only if result count < limit.
85
+ 9. **Enrich:** Also load `{memory-root}/_patterns/domain-patterns.json` for matching domain patterns.
71
86
 
72
87
  ### Output
73
88
 
@@ -141,17 +156,23 @@ Call at each **checkpoint** after the human responds, to persist the stage outco
141
156
 
142
157
  1. **Ensure directory exists:** Create `{memory-root}/{domain}/{slug}/` if it does not exist.
143
158
  2. **Build record:** Construct full RewardRecord JSON from input.
144
- 3. **Compute expires_at:** `current_date + retention_days` (from config, default 90 days).
159
+ 3. **Compute expires_at:** `current_date + retention_days` (from config, default 90 days). If tier config is present, use `tier_cold_days * 2` instead.
145
160
  4. **Generate filename:** `{stage}_{ISO-timestamp}.json`.
146
161
  5. **Write file:** Write JSON to `{memory-root}/{domain}/{slug}/{filename}`.
147
- 6. **Log:** "Stored reward {reward} ({reward_label}) for {stage} of {slug}"
162
+ 6. **Update index (v1.1):** If `{memory-root}/index.json` exists (or tier config is present), update it:
163
+ - Add record entry to `records` map with key = record id, value = `{domain, stage, slug, reward, skill, tier: "hot", file, expires_at}`
164
+ - Increment `record_count`
165
+ - Update `by_domain`, `by_phase`, `by_skill` aggregates (count, avg_reward)
166
+ - Set `last_updated` to current timestamp
167
+ - If `index.json` does not exist, create it with this record as the first entry
168
+ 7. **Log:** "Stored reward {reward} ({reward_label}) for {stage} of {slug}"
148
169
 
149
170
  ### RewardRecord JSON Schema
150
171
 
151
172
  ```json
152
173
  {
153
174
  "id": "{slug}_{stage}_{timestamp}",
154
- "version": "1.0",
175
+ "version": "1.1",
155
176
  "timestamp": "ISO-8601",
156
177
  "project_slug": "{slug}",
157
178
  "domain": "{domain}",
@@ -195,3 +216,262 @@ To prevent unbounded growth:
195
216
  | Malformed JSON file | Skip that record, log warning, continue |
196
217
  | Write fails (permissions, disk) | Log error, continue pipeline without storing |
197
218
  | Domain not in `known_domains` | Use "unknown" as domain directory |
219
+ | `index.json` corrupted | Delete and rebuild on next `memory_store()` call |
220
+ | Archive directory write fails | Log warning, keep record in active directory |
221
+
222
+ ---
223
+
224
+ ## Index Protocol (v1.1)
225
+
226
+ The index file provides a compact catalog of all records, enabling targeted file reads instead of full directory scans.
227
+
228
+ ### index.json Schema
229
+
230
+ ```json
231
+ {
232
+ "version": "1.0",
233
+ "last_updated": "ISO-8601",
234
+ "record_count": 47,
235
+ "by_domain": {
236
+ "{domain}": {
237
+ "count": 23,
238
+ "slugs": ["{slug-1}", "{slug-2}"],
239
+ "avg_reward": 0.82
240
+ }
241
+ },
242
+ "by_stage": {
243
+ "{stage-id}": {
244
+ "count": 12,
245
+ "avg_reward": 0.65
246
+ }
247
+ },
248
+ "by_skill": {
249
+ "{skill-name}": {
250
+ "count": 10,
251
+ "avg_reward": 0.78
252
+ }
253
+ },
254
+ "records": {
255
+ "{record-id}": {
256
+ "domain": "{domain}",
257
+ "stage": "{stage-id}",
258
+ "slug": "{slug}",
259
+ "reward": 0.7,
260
+ "skill": "{skill-name}",
261
+ "tier": "hot|warm|cold",
262
+ "file": "{domain}/{slug}/{stage}_{timestamp}.json",
263
+ "expires_at": "ISO-8601"
264
+ }
265
+ }
266
+ }
267
+ ```
268
+
269
+ ### Index Update Rules
270
+
271
+ 1. **On `memory_store()`:** Add new record entry, update aggregates.
272
+ 2. **On archive (WARM→COLD):** Update `tier` to `"cold"`, change `file` path to `_archive/` location.
273
+ 3. **On purge:** Remove record entry, decrement aggregates.
274
+ 4. **Rebuild:** If `index.json` is missing or corrupted, `memory_store()` creates a fresh index with the new record. Full rebuild requires scanning all files (expensive, avoid if possible).
275
+
276
+ ### Fallback Behavior
277
+
278
+ If `index.json` does not exist, `memory_query()` falls back to the v1.0 full-scan algorithm. This ensures backward compatibility with existing memory directories that predate v1.1.
279
+
280
+ ---
281
+
282
+ ## Brain Container Schema (v1.1)
283
+
284
+ Defines the portable brain export format with an integrity manifest.
285
+
286
+ ### Container Structure
287
+
288
+ ```json
289
+ {
290
+ "version": "1.1",
291
+ "format": "keysarium-brain",
292
+ "manifest": {
293
+ "created_at": "ISO-8601",
294
+ "source_project": "{project-name}",
295
+ "source_branch": "{git-branch}",
296
+ "checksum": "sha256:{64-hex-chars}",
297
+ "record_count": 47,
298
+ "domains": ["{domain-1}", "{domain-2}"],
299
+ "skills": ["{skill-1}", "{skill-2}"],
300
+ "research_count": 5,
301
+ "harvest_pattern_count": 23,
302
+ "size_bytes": 148200,
303
+ "parent": null,
304
+ "parent_checksum": null,
305
+ "delta_type": null
306
+ },
307
+ "skills": { },
308
+ "domain_patterns": { },
309
+ "research_summaries": [ ],
310
+ "harvest_patterns": [ ],
311
+ "pipeline_metrics": { },
312
+ "reward_data": { },
313
+ "metadata": { }
314
+ }
315
+ ```
316
+
317
+ ### Manifest Fields
318
+
319
+ | Field | Type | Description |
320
+ |-------|------|-------------|
321
+ | `created_at` | string | ISO-8601 timestamp of export |
322
+ | `source_project` | string | Project name from package.json or directory name |
323
+ | `source_branch` | string | Current git branch at export time |
324
+ | `checksum` | string | SHA-256 of the JSON-serialized content (all sections except `manifest`) |
325
+ | `record_count` | integer | Total records across all sections |
326
+ | `domains` | string[] | List of domains present in export |
327
+ | `skills` | string[] | List of skill names present |
328
+ | `research_count` | integer | Number of research summaries |
329
+ | `harvest_pattern_count` | integer | Number of harvest patterns |
330
+ | `size_bytes` | integer | Approximate size of the content payload |
331
+ | `parent` | string\|null | Filename of parent brain container (COW mode) |
332
+ | `parent_checksum` | string\|null | SHA-256 of parent container (COW mode) |
333
+ | `delta_type` | string\|null | `"rfc6902"` if this is a delta container |
334
+
335
+ ### Checksum Computation
336
+
337
+ 1. Serialize all sections except `manifest` as a JSON string (sorted keys, no extra whitespace)
338
+ 2. Compute SHA-256 of the resulting string
339
+ 3. Store as `"sha256:{64-hex-chars}"`
340
+
341
+ ### Version Negotiation
342
+
343
+ | Reader Version | File Version | Behavior |
344
+ |---------------|-------------|----------|
345
+ | v1.1 | v1.0 | Accept. Manifest will be absent — proceed without integrity check |
346
+ | v1.1 | v1.1 | Accept. Read manifest, verify checksum |
347
+ | v1.0 | v1.1 | Accept. Ignore unknown `manifest` field, read sections normally |
348
+ | Any | Unknown | Warn, attempt best-effort import |
349
+
350
+ ---
351
+
352
+ ## COW Branching Protocol (v1.1)
353
+
354
+ Copy-On-Write branching for efficient delta brain exports. A child container stores only the differences from a parent container.
355
+
356
+ ### Delta Container Structure
357
+
358
+ ```json
359
+ {
360
+ "version": "1.1",
361
+ "format": "keysarium-brain",
362
+ "manifest": {
363
+ "created_at": "ISO-8601",
364
+ "source_project": "{project-name}",
365
+ "source_branch": "{git-branch}",
366
+ "checksum": "sha256:{hash-of-patch-array}",
367
+ "record_count": 3,
368
+ "domains": ["{domains-in-delta}"],
369
+ "skills": [],
370
+ "research_count": 1,
371
+ "harvest_pattern_count": 2,
372
+ "size_bytes": 4200,
373
+ "parent": "{parent-filename}",
374
+ "parent_checksum": "sha256:{parent-hash}",
375
+ "delta_type": "rfc6902"
376
+ },
377
+ "patch": [
378
+ { "op": "add", "path": "/research_summaries/-", "value": { } },
379
+ { "op": "replace", "path": "/skills/{name}/trust_tier", "value": 2 },
380
+ { "op": "add", "path": "/harvest_patterns/-", "value": { } }
381
+ ]
382
+ }
383
+ ```
384
+
385
+ ### Export Protocol (delta mode)
386
+
387
+ 1. Load parent brain container from the specified path
388
+ 2. Verify parent checksum matches `manifest.checksum` of the parent file
389
+ 3. Build current full brain container (in memory, not written to disk)
390
+ 4. Compute JSON Patch (RFC 6902) between parent and current
391
+ 5. If patch is empty → log "No changes since parent" and skip export
392
+ 6. Write delta container with `manifest.parent` set to parent filename
393
+
394
+ ### Import Protocol (delta mode)
395
+
396
+ 1. Read delta container; detect `manifest.parent != null`
397
+ 2. Resolve parent file:
398
+ - Look in the same directory as the delta file
399
+ - Look in project root
400
+ - If not found → prompt user for path
401
+ - If still not found → offer partial import (self-contained `add` operations only)
402
+ 3. If parent is also a delta → resolve recursively (chain). Warn if chain depth > 3
403
+ 4. Load parent (or resolved chain base), apply JSON Patch operations in order
404
+ 5. Verify result checksum if available
405
+ 6. Proceed with standard import (selective sections, merge strategy)
406
+
407
+ ### JSON Patch Operations (RFC 6902)
408
+
409
+ | Operation | Usage |
410
+ |-----------|-------|
411
+ | `add` | New records (research summaries, harvest patterns, skills) |
412
+ | `replace` | Updated values (trust tier upgrade, new BTO score) |
413
+ | `remove` | Deleted entries (rare, mainly cleanup) |
414
+ | `move` | Renamed entries (rare) |
415
+ | `copy` | Duplicated entries (rare) |
416
+ | `test` | Pre-condition assertions (optional, for safety) |
417
+
418
+ ### Chain Depth Limit
419
+
420
+ Delta containers may reference another delta as parent, forming a chain. Import MUST warn if chain depth exceeds 3. Recommended: periodically re-export a full container to reset the chain.
421
+
422
+ ---
423
+
424
+ ## Record Lifecycle (v1.1)
425
+
426
+ Records transition through tiers based on age, trading detail for storage efficiency.
427
+
428
+ ### Tier Definitions
429
+
430
+ | Tier | Age Range | Location | Fields | Purpose |
431
+ |------|-----------|----------|--------|---------|
432
+ | **HOT** | 0 – `tier_hot_days` (default 30) | `{domain}/{slug}/` | All fields | Active learning, full context |
433
+ | **WARM** | `tier_hot_days` – `tier_warm_days` (default 90) | `{domain}/{slug}/` | All fields | Available but deprioritized in search |
434
+ | **COLD** | `tier_warm_days` – `tier_cold_days` (default 180) | `{domain}/_archive/{slug}/` | Compressed | Long-term pattern retention |
435
+ | **PURGE** | > `tier_cold_days` | Deleted | — | Cleanup |
436
+
437
+ ### COLD Record Schema (compressed)
438
+
439
+ ```json
440
+ {
441
+ "id": "{original-id}",
442
+ "stage": "{stage-id}",
443
+ "domain": "{domain}",
444
+ "slug": "{slug}",
445
+ "reward": 0.7,
446
+ "reward_label": "good",
447
+ "skill_used": "{skill}",
448
+ "promise_tag": "{PROMISE_TAG}",
449
+ "summary": "{first 200 chars of reward_reason + checkpoint_response}",
450
+ "archived_at": "ISO-8601",
451
+ "original_timestamp": "ISO-8601"
452
+ }
453
+ ```
454
+
455
+ ### Archive Procedure
456
+
457
+ Triggered during `memory_query()` step 5:
458
+
459
+ 1. For each record in the query result set, compute age = `current_date - timestamp`
460
+ 2. If age > `tier_warm_days` and record is not already archived:
461
+ a. Read full record
462
+ b. Generate `summary` from `reward_reason` + `outcome.checkpoint_response` (truncate to 200 chars)
463
+ c. Write compressed record to `{memory-root}/{domain}/_archive/{slug}/{filename}`
464
+ d. Delete original file from active directory
465
+ e. Update `index.json`: set `tier` to `"cold"`, update `file` path
466
+
467
+ ### Purge Procedure
468
+
469
+ Triggered during `memory_query()` step 6:
470
+
471
+ 1. Scan `{domain}/_archive/` for records where age > `tier_cold_days`
472
+ 2. Delete those files
473
+ 3. Remove entries from `index.json`
474
+
475
+ ### Backward Compatibility
476
+
477
+ If `tier_hot_days` is NOT present in `config.json`, the entire lifecycle system is disabled. Records use the v1.0 flat `retention_days` for expiration. No archiving occurs. This ensures existing memory directories work without changes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dzhechkov/keysarium-core",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Core framework for multi-agent pipelines: governance, memory, orchestration, verification, trust tiers, and multi-platform support",
5
5
  "main": "index.md",
6
6
  "files": [