@danielsimonjr/memoryjs 1.9.1 → 1.15.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 +513 -148
- package/dist/cli/index.js +3242 -155
- package/dist/cli/index.js.map +1 -1
- package/dist/index.cjs +12223 -2479
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2594 -186
- package/dist/index.d.ts +2594 -186
- package/dist/index.js +26900 -17163
- package/dist/index.js.map +1 -1
- package/package.json +6 -3
package/dist/index.d.cts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z, ZodError, ZodSchema } from 'zod';
|
|
2
|
-
import workerpool, {
|
|
2
|
+
import workerpool, { PoolStats, Pool } from '@danielsimonjr/workerpool';
|
|
3
3
|
import { EventEmitter } from 'events';
|
|
4
|
+
import { EventEmitter as EventEmitter$1 } from 'node:events';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* Search Types
|
|
@@ -362,6 +363,8 @@ declare class TaskQueue {
|
|
|
362
363
|
private totalExecutionTime;
|
|
363
364
|
private totalProcessed;
|
|
364
365
|
private useWorkerPool;
|
|
366
|
+
private static readonly MAX_COMPLETED;
|
|
367
|
+
private static readonly MAX_QUEUE;
|
|
365
368
|
constructor(options?: {
|
|
366
369
|
concurrency?: number;
|
|
367
370
|
timeout?: number;
|
|
@@ -595,6 +598,40 @@ interface Entity {
|
|
|
595
598
|
isLatest?: boolean;
|
|
596
599
|
/** Name of the entity that superseded this one. */
|
|
597
600
|
supersededBy?: string;
|
|
601
|
+
/**
|
|
602
|
+
* SHA-256 of raw content (pre-role-prefix). Populated by MemoryEngine for
|
|
603
|
+
* conversation turns to enable O(1) Tier 1 exact-equality dedup. Other
|
|
604
|
+
* entity types leave this undefined.
|
|
605
|
+
*/
|
|
606
|
+
contentHash?: string;
|
|
607
|
+
/**
|
|
608
|
+
* ISO 8601 — entity is valid from this instant. Absent ⇒ always-valid since
|
|
609
|
+
* creation. Orthogonal to `version`/`supersededBy` (those answer "which
|
|
610
|
+
* version is current?"; this answers "was the entity true at time T?").
|
|
611
|
+
*/
|
|
612
|
+
validFrom?: string;
|
|
613
|
+
/**
|
|
614
|
+
* ISO 8601 — entity is valid until this instant. Absent ⇒ still valid. Set
|
|
615
|
+
* by `EntityManager.invalidateEntity` to mark an entity as no longer valid
|
|
616
|
+
* without deleting it.
|
|
617
|
+
*/
|
|
618
|
+
validUntil?: string;
|
|
619
|
+
/**
|
|
620
|
+
* Per-observation temporal validity, indexed parallel to `observations[]`
|
|
621
|
+
* by content match. Absent or partial ⇒ those observations are unbounded
|
|
622
|
+
* (always-valid) — preserves backwards-compat with entities that don't use
|
|
623
|
+
* the bitemporal axis.
|
|
624
|
+
*/
|
|
625
|
+
observationMeta?: Array<{
|
|
626
|
+
/** Matches an entry in `observations[]` by exact content. */
|
|
627
|
+
content: string;
|
|
628
|
+
/** ISO 8601 — observation valid from. Absent ⇒ valid since recorded. */
|
|
629
|
+
validFrom?: string;
|
|
630
|
+
/** ISO 8601 — observation valid until. Absent ⇒ still valid. */
|
|
631
|
+
validUntil?: string;
|
|
632
|
+
/** ISO 8601 — when this fact was recorded (bitemporal axis). */
|
|
633
|
+
recordedAt?: string;
|
|
634
|
+
}>;
|
|
598
635
|
}
|
|
599
636
|
/**
|
|
600
637
|
* Options for observation deduplication at write time.
|
|
@@ -2802,6 +2839,32 @@ interface DecayEngineConfig {
|
|
|
2802
2839
|
* Enable to make low-confidence memories decay faster in importance.
|
|
2803
2840
|
*/
|
|
2804
2841
|
applyConfidenceToImportance?: boolean;
|
|
2842
|
+
/**
|
|
2843
|
+
* PRD `decay_rate`: exponential decay rate per second for the recency
|
|
2844
|
+
* term in `calculatePrdEffectiveImportance`. When absent, derived from
|
|
2845
|
+
* `halfLifeHours` via `ln(2) / (halfLifeHours * 3600)`.
|
|
2846
|
+
* Distinct from the legacy half-life formula used by
|
|
2847
|
+
* `calculateEffectiveImportance`.
|
|
2848
|
+
*/
|
|
2849
|
+
decayRate?: number;
|
|
2850
|
+
/**
|
|
2851
|
+
* PRD `freshness_coefficient`: exponential coefficient for the
|
|
2852
|
+
* freshness term (per second since last access). Default 0.01.
|
|
2853
|
+
*/
|
|
2854
|
+
freshnessCoefficient?: number;
|
|
2855
|
+
/**
|
|
2856
|
+
* PRD `relevance_weight`: scaling factor for the relevance-boost term.
|
|
2857
|
+
* Default 0.35.
|
|
2858
|
+
*/
|
|
2859
|
+
relevanceWeight?: number;
|
|
2860
|
+
/**
|
|
2861
|
+
* PRD `min_importance_threshold`: retrieval-time filter for
|
|
2862
|
+
* `IMemoryBackend.get_weighted` and similar callers. Distinct from
|
|
2863
|
+
* `minImportance` (which is a clamp applied during scoring) — this is
|
|
2864
|
+
* a *filter* applied to the final score. Entities scoring below it
|
|
2865
|
+
* are pruned. Default 0.1.
|
|
2866
|
+
*/
|
|
2867
|
+
minImportanceThreshold?: number;
|
|
2805
2868
|
}
|
|
2806
2869
|
/**
|
|
2807
2870
|
* Options for batch decay operations.
|
|
@@ -2921,6 +2984,32 @@ declare class DecayEngine {
|
|
|
2921
2984
|
* Exposed for callers that need freshness calculations alongside decay.
|
|
2922
2985
|
*/
|
|
2923
2986
|
getFreshnessManager(): FreshnessManager;
|
|
2987
|
+
/**
|
|
2988
|
+
* Calculate effective importance using the Context Engine PRD formula.
|
|
2989
|
+
*
|
|
2990
|
+
* Distinct from `calculateEffectiveImportance` (legacy formula preserved
|
|
2991
|
+
* for `DecayScheduler`, `SearchManager`, `SemanticForget`, etc.).
|
|
2992
|
+
*
|
|
2993
|
+
* Formula:
|
|
2994
|
+
* ```
|
|
2995
|
+
* effective = importance × recency × freshness + relevance_boost
|
|
2996
|
+
* recency = e^(−decayRate × age_seconds)
|
|
2997
|
+
* freshness = e^(−freshnessCoefficient × seconds_since_last_access)
|
|
2998
|
+
* relevance_boost = (|query_tokens ∩ turn_tokens| / |query_tokens|) × relevanceWeight
|
|
2999
|
+
* ```
|
|
3000
|
+
*
|
|
3001
|
+
* `importance` is auto-scaled from memoryjs's `[0, 10]` range to PRD's
|
|
3002
|
+
* `[1.0, 3.0]` range via `prd_importance = 1.0 + (memoryjs_importance / 10.0) * 2.0`.
|
|
3003
|
+
*
|
|
3004
|
+
* @param entity AgentEntity to score.
|
|
3005
|
+
* @param queryContext Optional query string. When provided, enables the
|
|
3006
|
+
* relevance-boost term via token overlap.
|
|
3007
|
+
* @param now Optional clock override (test injection). Defaults to `Date.now()`.
|
|
3008
|
+
* @returns Float in `[0, ∞)`. Callers filter via `minImportanceThreshold`.
|
|
3009
|
+
*/
|
|
3010
|
+
calculatePrdEffectiveImportance(entity: AgentEntity, queryContext?: string, now?: number): number;
|
|
3011
|
+
/** Read-only accessor for the configured PRD `min_importance_threshold`. */
|
|
3012
|
+
get prdMinImportanceThreshold(): number;
|
|
2924
3013
|
/**
|
|
2925
3014
|
* Get memories that have decayed below threshold.
|
|
2926
3015
|
*
|
|
@@ -4193,6 +4282,30 @@ interface AgentEntity extends Entity {
|
|
|
4193
4282
|
visibility: MemoryVisibility;
|
|
4194
4283
|
/** Provenance tracking for memory origin */
|
|
4195
4284
|
source?: MemorySource;
|
|
4285
|
+
/**
|
|
4286
|
+
* Optional role gate. When set, requesting agents whose
|
|
4287
|
+
* `AgentMetadata.role` is NOT in this list are denied access — even
|
|
4288
|
+
* if the visibility level would otherwise grant it. AND-combined with
|
|
4289
|
+
* the level check; this tightens, never widens.
|
|
4290
|
+
*
|
|
4291
|
+
* Free-form strings; aligns with the five built-in `RoleProfiles`
|
|
4292
|
+
* (`researcher`/`planner`/`executor`/`reviewer`/`coordinator`) but
|
|
4293
|
+
* accepts any caller-defined role.
|
|
4294
|
+
*/
|
|
4295
|
+
allowedRoles?: string[];
|
|
4296
|
+
/**
|
|
4297
|
+
* ISO 8601 — memory becomes visible at this instant. Absent ⇒ visible
|
|
4298
|
+
* since creation. Evaluated FIRST in the resolver, before owner/level
|
|
4299
|
+
* rules: a memory whose `visibleFrom` is in the future is unreachable
|
|
4300
|
+
* even by its owner until then.
|
|
4301
|
+
*/
|
|
4302
|
+
visibleFrom?: string;
|
|
4303
|
+
/**
|
|
4304
|
+
* ISO 8601 — memory stops being visible at this instant. Absent ⇒
|
|
4305
|
+
* visible indefinitely. Useful for shared drafts that should expire on
|
|
4306
|
+
* a known handoff date — the entity is still stored, just hidden after.
|
|
4307
|
+
*/
|
|
4308
|
+
visibleUntil?: string;
|
|
4196
4309
|
}
|
|
4197
4310
|
/**
|
|
4198
4311
|
* Extended observation with confidence, temporal validity, and provenance.
|
|
@@ -5035,6 +5148,14 @@ interface AgentMetadata {
|
|
|
5035
5148
|
* percentages tuned for the agent's functional role.
|
|
5036
5149
|
*/
|
|
5037
5150
|
roleProfile?: RoleProfile;
|
|
5151
|
+
/**
|
|
5152
|
+
* Free-form role string used by `VisibilityResolver` for `allowedRoles`
|
|
5153
|
+
* predicate checks (η.5.5.b). Distinct from `roleProfile` (which is the
|
|
5154
|
+
* built-in salience-tuning profile); a single agent can have a
|
|
5155
|
+
* `roleProfile: 'researcher'` while bearing `role: 'admin'` for
|
|
5156
|
+
* visibility purposes.
|
|
5157
|
+
*/
|
|
5158
|
+
role?: string;
|
|
5038
5159
|
}
|
|
5039
5160
|
|
|
5040
5161
|
/**
|
|
@@ -6321,6 +6442,7 @@ declare const EntitySchema: z.ZodObject<{
|
|
|
6321
6442
|
tags: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
6322
6443
|
importance: z.ZodOptional<z.ZodNumber>;
|
|
6323
6444
|
parentId: z.ZodOptional<z.ZodString>;
|
|
6445
|
+
contentHash: z.ZodOptional<z.ZodString>;
|
|
6324
6446
|
}, "strict", z.ZodTypeAny, {
|
|
6325
6447
|
name: string;
|
|
6326
6448
|
entityType: string;
|
|
@@ -6330,6 +6452,7 @@ declare const EntitySchema: z.ZodObject<{
|
|
|
6330
6452
|
tags?: string[] | undefined;
|
|
6331
6453
|
importance?: number | undefined;
|
|
6332
6454
|
parentId?: string | undefined;
|
|
6455
|
+
contentHash?: string | undefined;
|
|
6333
6456
|
}, {
|
|
6334
6457
|
name: string;
|
|
6335
6458
|
entityType: string;
|
|
@@ -6339,6 +6462,7 @@ declare const EntitySchema: z.ZodObject<{
|
|
|
6339
6462
|
tags?: string[] | undefined;
|
|
6340
6463
|
importance?: number | undefined;
|
|
6341
6464
|
parentId?: string | undefined;
|
|
6465
|
+
contentHash?: string | undefined;
|
|
6342
6466
|
}>;
|
|
6343
6467
|
/**
|
|
6344
6468
|
* Entity creation input schema.
|
|
@@ -6355,11 +6479,32 @@ declare const CreateEntitySchema: z.ZodObject<{
|
|
|
6355
6479
|
projectId: z.ZodOptional<z.ZodString>;
|
|
6356
6480
|
createdAt: z.ZodOptional<z.ZodString>;
|
|
6357
6481
|
lastModified: z.ZodOptional<z.ZodString>;
|
|
6482
|
+
ttl: z.ZodOptional<z.ZodNumber>;
|
|
6483
|
+
confidence: z.ZodOptional<z.ZodNumber>;
|
|
6358
6484
|
version: z.ZodOptional<z.ZodNumber>;
|
|
6359
6485
|
parentEntityName: z.ZodOptional<z.ZodString>;
|
|
6360
6486
|
rootEntityName: z.ZodOptional<z.ZodString>;
|
|
6361
6487
|
isLatest: z.ZodOptional<z.ZodBoolean>;
|
|
6362
6488
|
supersededBy: z.ZodOptional<z.ZodString>;
|
|
6489
|
+
contentHash: z.ZodOptional<z.ZodString>;
|
|
6490
|
+
validFrom: z.ZodOptional<z.ZodString>;
|
|
6491
|
+
validUntil: z.ZodOptional<z.ZodString>;
|
|
6492
|
+
observationMeta: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
6493
|
+
content: z.ZodString;
|
|
6494
|
+
validFrom: z.ZodOptional<z.ZodString>;
|
|
6495
|
+
validUntil: z.ZodOptional<z.ZodString>;
|
|
6496
|
+
recordedAt: z.ZodOptional<z.ZodString>;
|
|
6497
|
+
}, "strip", z.ZodTypeAny, {
|
|
6498
|
+
content: string;
|
|
6499
|
+
validFrom?: string | undefined;
|
|
6500
|
+
validUntil?: string | undefined;
|
|
6501
|
+
recordedAt?: string | undefined;
|
|
6502
|
+
}, {
|
|
6503
|
+
content: string;
|
|
6504
|
+
validFrom?: string | undefined;
|
|
6505
|
+
validUntil?: string | undefined;
|
|
6506
|
+
recordedAt?: string | undefined;
|
|
6507
|
+
}>, "many">>;
|
|
6363
6508
|
}, "strict", z.ZodTypeAny, {
|
|
6364
6509
|
name: string;
|
|
6365
6510
|
entityType: string;
|
|
@@ -6369,12 +6514,23 @@ declare const CreateEntitySchema: z.ZodObject<{
|
|
|
6369
6514
|
tags?: string[] | undefined;
|
|
6370
6515
|
importance?: number | undefined;
|
|
6371
6516
|
parentId?: string | undefined;
|
|
6517
|
+
ttl?: number | undefined;
|
|
6518
|
+
confidence?: number | undefined;
|
|
6372
6519
|
projectId?: string | undefined;
|
|
6373
6520
|
version?: number | undefined;
|
|
6374
6521
|
parentEntityName?: string | undefined;
|
|
6375
6522
|
rootEntityName?: string | undefined;
|
|
6376
6523
|
isLatest?: boolean | undefined;
|
|
6377
6524
|
supersededBy?: string | undefined;
|
|
6525
|
+
contentHash?: string | undefined;
|
|
6526
|
+
validFrom?: string | undefined;
|
|
6527
|
+
validUntil?: string | undefined;
|
|
6528
|
+
observationMeta?: {
|
|
6529
|
+
content: string;
|
|
6530
|
+
validFrom?: string | undefined;
|
|
6531
|
+
validUntil?: string | undefined;
|
|
6532
|
+
recordedAt?: string | undefined;
|
|
6533
|
+
}[] | undefined;
|
|
6378
6534
|
}, {
|
|
6379
6535
|
name: string;
|
|
6380
6536
|
entityType: string;
|
|
@@ -6384,12 +6540,23 @@ declare const CreateEntitySchema: z.ZodObject<{
|
|
|
6384
6540
|
tags?: string[] | undefined;
|
|
6385
6541
|
importance?: number | undefined;
|
|
6386
6542
|
parentId?: string | undefined;
|
|
6543
|
+
ttl?: number | undefined;
|
|
6544
|
+
confidence?: number | undefined;
|
|
6387
6545
|
projectId?: string | undefined;
|
|
6388
6546
|
version?: number | undefined;
|
|
6389
6547
|
parentEntityName?: string | undefined;
|
|
6390
6548
|
rootEntityName?: string | undefined;
|
|
6391
6549
|
isLatest?: boolean | undefined;
|
|
6392
6550
|
supersededBy?: string | undefined;
|
|
6551
|
+
contentHash?: string | undefined;
|
|
6552
|
+
validFrom?: string | undefined;
|
|
6553
|
+
validUntil?: string | undefined;
|
|
6554
|
+
observationMeta?: {
|
|
6555
|
+
content: string;
|
|
6556
|
+
validFrom?: string | undefined;
|
|
6557
|
+
validUntil?: string | undefined;
|
|
6558
|
+
recordedAt?: string | undefined;
|
|
6559
|
+
}[] | undefined;
|
|
6393
6560
|
}>;
|
|
6394
6561
|
/**
|
|
6395
6562
|
* Entity update input schema.
|
|
@@ -6404,22 +6571,68 @@ declare const UpdateEntitySchema: z.ZodObject<{
|
|
|
6404
6571
|
parentId: z.ZodOptional<z.ZodString>;
|
|
6405
6572
|
isLatest: z.ZodOptional<z.ZodBoolean>;
|
|
6406
6573
|
supersededBy: z.ZodOptional<z.ZodString>;
|
|
6574
|
+
rootEntityName: z.ZodOptional<z.ZodString>;
|
|
6575
|
+
parentEntityName: z.ZodOptional<z.ZodString>;
|
|
6576
|
+
version: z.ZodOptional<z.ZodNumber>;
|
|
6577
|
+
contentHash: z.ZodOptional<z.ZodString>;
|
|
6578
|
+
validFrom: z.ZodOptional<z.ZodString>;
|
|
6579
|
+
validUntil: z.ZodOptional<z.ZodString>;
|
|
6580
|
+
observationMeta: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
6581
|
+
content: z.ZodString;
|
|
6582
|
+
validFrom: z.ZodOptional<z.ZodString>;
|
|
6583
|
+
validUntil: z.ZodOptional<z.ZodString>;
|
|
6584
|
+
recordedAt: z.ZodOptional<z.ZodString>;
|
|
6585
|
+
}, "strip", z.ZodTypeAny, {
|
|
6586
|
+
content: string;
|
|
6587
|
+
validFrom?: string | undefined;
|
|
6588
|
+
validUntil?: string | undefined;
|
|
6589
|
+
recordedAt?: string | undefined;
|
|
6590
|
+
}, {
|
|
6591
|
+
content: string;
|
|
6592
|
+
validFrom?: string | undefined;
|
|
6593
|
+
validUntil?: string | undefined;
|
|
6594
|
+
recordedAt?: string | undefined;
|
|
6595
|
+
}>, "many">>;
|
|
6407
6596
|
}, "strict", z.ZodTypeAny, {
|
|
6408
6597
|
entityType?: string | undefined;
|
|
6409
6598
|
observations?: string[] | undefined;
|
|
6410
6599
|
tags?: string[] | undefined;
|
|
6411
6600
|
importance?: number | undefined;
|
|
6412
6601
|
parentId?: string | undefined;
|
|
6602
|
+
version?: number | undefined;
|
|
6603
|
+
parentEntityName?: string | undefined;
|
|
6604
|
+
rootEntityName?: string | undefined;
|
|
6413
6605
|
isLatest?: boolean | undefined;
|
|
6414
6606
|
supersededBy?: string | undefined;
|
|
6607
|
+
contentHash?: string | undefined;
|
|
6608
|
+
validFrom?: string | undefined;
|
|
6609
|
+
validUntil?: string | undefined;
|
|
6610
|
+
observationMeta?: {
|
|
6611
|
+
content: string;
|
|
6612
|
+
validFrom?: string | undefined;
|
|
6613
|
+
validUntil?: string | undefined;
|
|
6614
|
+
recordedAt?: string | undefined;
|
|
6615
|
+
}[] | undefined;
|
|
6415
6616
|
}, {
|
|
6416
6617
|
entityType?: string | undefined;
|
|
6417
6618
|
observations?: string[] | undefined;
|
|
6418
6619
|
tags?: string[] | undefined;
|
|
6419
6620
|
importance?: number | undefined;
|
|
6420
6621
|
parentId?: string | undefined;
|
|
6622
|
+
version?: number | undefined;
|
|
6623
|
+
parentEntityName?: string | undefined;
|
|
6624
|
+
rootEntityName?: string | undefined;
|
|
6421
6625
|
isLatest?: boolean | undefined;
|
|
6422
6626
|
supersededBy?: string | undefined;
|
|
6627
|
+
contentHash?: string | undefined;
|
|
6628
|
+
validFrom?: string | undefined;
|
|
6629
|
+
validUntil?: string | undefined;
|
|
6630
|
+
observationMeta?: {
|
|
6631
|
+
content: string;
|
|
6632
|
+
validFrom?: string | undefined;
|
|
6633
|
+
validUntil?: string | undefined;
|
|
6634
|
+
recordedAt?: string | undefined;
|
|
6635
|
+
}[] | undefined;
|
|
6423
6636
|
}>;
|
|
6424
6637
|
/**
|
|
6425
6638
|
* Complete Relation schema with all fields.
|
|
@@ -6463,14 +6676,14 @@ declare const CreateRelationSchema: z.ZodObject<{
|
|
|
6463
6676
|
validUntil: z.ZodOptional<z.ZodString>;
|
|
6464
6677
|
provenance: z.ZodOptional<z.ZodString>;
|
|
6465
6678
|
}, "strip", z.ZodTypeAny, {
|
|
6466
|
-
bidirectional?: boolean | undefined;
|
|
6467
6679
|
validFrom?: string | undefined;
|
|
6468
6680
|
validUntil?: string | undefined;
|
|
6681
|
+
bidirectional?: boolean | undefined;
|
|
6469
6682
|
provenance?: string | undefined;
|
|
6470
6683
|
}, {
|
|
6471
|
-
bidirectional?: boolean | undefined;
|
|
6472
6684
|
validFrom?: string | undefined;
|
|
6473
6685
|
validUntil?: string | undefined;
|
|
6686
|
+
bidirectional?: boolean | undefined;
|
|
6474
6687
|
provenance?: string | undefined;
|
|
6475
6688
|
}>>;
|
|
6476
6689
|
}, "strict", z.ZodTypeAny, {
|
|
@@ -6482,9 +6695,9 @@ declare const CreateRelationSchema: z.ZodObject<{
|
|
|
6482
6695
|
confidence?: number | undefined;
|
|
6483
6696
|
weight?: number | undefined;
|
|
6484
6697
|
properties?: {
|
|
6485
|
-
bidirectional?: boolean | undefined;
|
|
6486
6698
|
validFrom?: string | undefined;
|
|
6487
6699
|
validUntil?: string | undefined;
|
|
6700
|
+
bidirectional?: boolean | undefined;
|
|
6488
6701
|
provenance?: string | undefined;
|
|
6489
6702
|
} | undefined;
|
|
6490
6703
|
}, {
|
|
@@ -6496,9 +6709,9 @@ declare const CreateRelationSchema: z.ZodObject<{
|
|
|
6496
6709
|
confidence?: number | undefined;
|
|
6497
6710
|
weight?: number | undefined;
|
|
6498
6711
|
properties?: {
|
|
6499
|
-
bidirectional?: boolean | undefined;
|
|
6500
6712
|
validFrom?: string | undefined;
|
|
6501
6713
|
validUntil?: string | undefined;
|
|
6714
|
+
bidirectional?: boolean | undefined;
|
|
6502
6715
|
provenance?: string | undefined;
|
|
6503
6716
|
} | undefined;
|
|
6504
6717
|
}>;
|
|
@@ -6558,11 +6771,32 @@ declare const BatchCreateEntitiesSchema: z.ZodArray<z.ZodObject<{
|
|
|
6558
6771
|
projectId: z.ZodOptional<z.ZodString>;
|
|
6559
6772
|
createdAt: z.ZodOptional<z.ZodString>;
|
|
6560
6773
|
lastModified: z.ZodOptional<z.ZodString>;
|
|
6774
|
+
ttl: z.ZodOptional<z.ZodNumber>;
|
|
6775
|
+
confidence: z.ZodOptional<z.ZodNumber>;
|
|
6561
6776
|
version: z.ZodOptional<z.ZodNumber>;
|
|
6562
6777
|
parentEntityName: z.ZodOptional<z.ZodString>;
|
|
6563
6778
|
rootEntityName: z.ZodOptional<z.ZodString>;
|
|
6564
6779
|
isLatest: z.ZodOptional<z.ZodBoolean>;
|
|
6565
6780
|
supersededBy: z.ZodOptional<z.ZodString>;
|
|
6781
|
+
contentHash: z.ZodOptional<z.ZodString>;
|
|
6782
|
+
validFrom: z.ZodOptional<z.ZodString>;
|
|
6783
|
+
validUntil: z.ZodOptional<z.ZodString>;
|
|
6784
|
+
observationMeta: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
6785
|
+
content: z.ZodString;
|
|
6786
|
+
validFrom: z.ZodOptional<z.ZodString>;
|
|
6787
|
+
validUntil: z.ZodOptional<z.ZodString>;
|
|
6788
|
+
recordedAt: z.ZodOptional<z.ZodString>;
|
|
6789
|
+
}, "strip", z.ZodTypeAny, {
|
|
6790
|
+
content: string;
|
|
6791
|
+
validFrom?: string | undefined;
|
|
6792
|
+
validUntil?: string | undefined;
|
|
6793
|
+
recordedAt?: string | undefined;
|
|
6794
|
+
}, {
|
|
6795
|
+
content: string;
|
|
6796
|
+
validFrom?: string | undefined;
|
|
6797
|
+
validUntil?: string | undefined;
|
|
6798
|
+
recordedAt?: string | undefined;
|
|
6799
|
+
}>, "many">>;
|
|
6566
6800
|
}, "strict", z.ZodTypeAny, {
|
|
6567
6801
|
name: string;
|
|
6568
6802
|
entityType: string;
|
|
@@ -6572,12 +6806,23 @@ declare const BatchCreateEntitiesSchema: z.ZodArray<z.ZodObject<{
|
|
|
6572
6806
|
tags?: string[] | undefined;
|
|
6573
6807
|
importance?: number | undefined;
|
|
6574
6808
|
parentId?: string | undefined;
|
|
6809
|
+
ttl?: number | undefined;
|
|
6810
|
+
confidence?: number | undefined;
|
|
6575
6811
|
projectId?: string | undefined;
|
|
6576
6812
|
version?: number | undefined;
|
|
6577
6813
|
parentEntityName?: string | undefined;
|
|
6578
6814
|
rootEntityName?: string | undefined;
|
|
6579
6815
|
isLatest?: boolean | undefined;
|
|
6580
6816
|
supersededBy?: string | undefined;
|
|
6817
|
+
contentHash?: string | undefined;
|
|
6818
|
+
validFrom?: string | undefined;
|
|
6819
|
+
validUntil?: string | undefined;
|
|
6820
|
+
observationMeta?: {
|
|
6821
|
+
content: string;
|
|
6822
|
+
validFrom?: string | undefined;
|
|
6823
|
+
validUntil?: string | undefined;
|
|
6824
|
+
recordedAt?: string | undefined;
|
|
6825
|
+
}[] | undefined;
|
|
6581
6826
|
}, {
|
|
6582
6827
|
name: string;
|
|
6583
6828
|
entityType: string;
|
|
@@ -6587,12 +6832,23 @@ declare const BatchCreateEntitiesSchema: z.ZodArray<z.ZodObject<{
|
|
|
6587
6832
|
tags?: string[] | undefined;
|
|
6588
6833
|
importance?: number | undefined;
|
|
6589
6834
|
parentId?: string | undefined;
|
|
6835
|
+
ttl?: number | undefined;
|
|
6836
|
+
confidence?: number | undefined;
|
|
6590
6837
|
projectId?: string | undefined;
|
|
6591
6838
|
version?: number | undefined;
|
|
6592
6839
|
parentEntityName?: string | undefined;
|
|
6593
6840
|
rootEntityName?: string | undefined;
|
|
6594
6841
|
isLatest?: boolean | undefined;
|
|
6595
6842
|
supersededBy?: string | undefined;
|
|
6843
|
+
contentHash?: string | undefined;
|
|
6844
|
+
validFrom?: string | undefined;
|
|
6845
|
+
validUntil?: string | undefined;
|
|
6846
|
+
observationMeta?: {
|
|
6847
|
+
content: string;
|
|
6848
|
+
validFrom?: string | undefined;
|
|
6849
|
+
validUntil?: string | undefined;
|
|
6850
|
+
recordedAt?: string | undefined;
|
|
6851
|
+
}[] | undefined;
|
|
6596
6852
|
}>, "many">;
|
|
6597
6853
|
/**
|
|
6598
6854
|
* Batch relation creation validation.
|
|
@@ -6613,14 +6869,14 @@ declare const BatchCreateRelationsSchema: z.ZodArray<z.ZodObject<{
|
|
|
6613
6869
|
validUntil: z.ZodOptional<z.ZodString>;
|
|
6614
6870
|
provenance: z.ZodOptional<z.ZodString>;
|
|
6615
6871
|
}, "strip", z.ZodTypeAny, {
|
|
6616
|
-
bidirectional?: boolean | undefined;
|
|
6617
6872
|
validFrom?: string | undefined;
|
|
6618
6873
|
validUntil?: string | undefined;
|
|
6874
|
+
bidirectional?: boolean | undefined;
|
|
6619
6875
|
provenance?: string | undefined;
|
|
6620
6876
|
}, {
|
|
6621
|
-
bidirectional?: boolean | undefined;
|
|
6622
6877
|
validFrom?: string | undefined;
|
|
6623
6878
|
validUntil?: string | undefined;
|
|
6879
|
+
bidirectional?: boolean | undefined;
|
|
6624
6880
|
provenance?: string | undefined;
|
|
6625
6881
|
}>>;
|
|
6626
6882
|
}, "strict", z.ZodTypeAny, {
|
|
@@ -6632,9 +6888,9 @@ declare const BatchCreateRelationsSchema: z.ZodArray<z.ZodObject<{
|
|
|
6632
6888
|
confidence?: number | undefined;
|
|
6633
6889
|
weight?: number | undefined;
|
|
6634
6890
|
properties?: {
|
|
6635
|
-
bidirectional?: boolean | undefined;
|
|
6636
6891
|
validFrom?: string | undefined;
|
|
6637
6892
|
validUntil?: string | undefined;
|
|
6893
|
+
bidirectional?: boolean | undefined;
|
|
6638
6894
|
provenance?: string | undefined;
|
|
6639
6895
|
} | undefined;
|
|
6640
6896
|
}, {
|
|
@@ -6646,9 +6902,9 @@ declare const BatchCreateRelationsSchema: z.ZodArray<z.ZodObject<{
|
|
|
6646
6902
|
confidence?: number | undefined;
|
|
6647
6903
|
weight?: number | undefined;
|
|
6648
6904
|
properties?: {
|
|
6649
|
-
bidirectional?: boolean | undefined;
|
|
6650
6905
|
validFrom?: string | undefined;
|
|
6651
6906
|
validUntil?: string | undefined;
|
|
6907
|
+
bidirectional?: boolean | undefined;
|
|
6652
6908
|
provenance?: string | undefined;
|
|
6653
6909
|
} | undefined;
|
|
6654
6910
|
}>, "many">;
|
|
@@ -6673,14 +6929,14 @@ declare const DeleteRelationsSchema: z.ZodArray<z.ZodObject<{
|
|
|
6673
6929
|
validUntil: z.ZodOptional<z.ZodString>;
|
|
6674
6930
|
provenance: z.ZodOptional<z.ZodString>;
|
|
6675
6931
|
}, "strip", z.ZodTypeAny, {
|
|
6676
|
-
bidirectional?: boolean | undefined;
|
|
6677
6932
|
validFrom?: string | undefined;
|
|
6678
6933
|
validUntil?: string | undefined;
|
|
6934
|
+
bidirectional?: boolean | undefined;
|
|
6679
6935
|
provenance?: string | undefined;
|
|
6680
6936
|
}, {
|
|
6681
|
-
bidirectional?: boolean | undefined;
|
|
6682
6937
|
validFrom?: string | undefined;
|
|
6683
6938
|
validUntil?: string | undefined;
|
|
6939
|
+
bidirectional?: boolean | undefined;
|
|
6684
6940
|
provenance?: string | undefined;
|
|
6685
6941
|
}>>;
|
|
6686
6942
|
}, "strict", z.ZodTypeAny, {
|
|
@@ -6692,9 +6948,9 @@ declare const DeleteRelationsSchema: z.ZodArray<z.ZodObject<{
|
|
|
6692
6948
|
confidence?: number | undefined;
|
|
6693
6949
|
weight?: number | undefined;
|
|
6694
6950
|
properties?: {
|
|
6695
|
-
bidirectional?: boolean | undefined;
|
|
6696
6951
|
validFrom?: string | undefined;
|
|
6697
6952
|
validUntil?: string | undefined;
|
|
6953
|
+
bidirectional?: boolean | undefined;
|
|
6698
6954
|
provenance?: string | undefined;
|
|
6699
6955
|
} | undefined;
|
|
6700
6956
|
}, {
|
|
@@ -6706,9 +6962,9 @@ declare const DeleteRelationsSchema: z.ZodArray<z.ZodObject<{
|
|
|
6706
6962
|
confidence?: number | undefined;
|
|
6707
6963
|
weight?: number | undefined;
|
|
6708
6964
|
properties?: {
|
|
6709
|
-
bidirectional?: boolean | undefined;
|
|
6710
6965
|
validFrom?: string | undefined;
|
|
6711
6966
|
validUntil?: string | undefined;
|
|
6967
|
+
bidirectional?: boolean | undefined;
|
|
6712
6968
|
provenance?: string | undefined;
|
|
6713
6969
|
} | undefined;
|
|
6714
6970
|
}>, "many">;
|
|
@@ -6846,8 +7102,13 @@ declare const SavedSearchUpdateSchema: z.ZodObject<{
|
|
|
6846
7102
|
declare const ImportFormatSchema: z.ZodEnum<["json", "csv", "graphml"]>;
|
|
6847
7103
|
/**
|
|
6848
7104
|
* Export format validation (includes all output formats).
|
|
7105
|
+
*
|
|
7106
|
+
* Includes the η.5.4 W3C Linked Data formats:
|
|
7107
|
+
* - `turtle`: RDF 1.1 Turtle
|
|
7108
|
+
* - `rdf-xml`: RDF 1.1 XML serialization (uses Statement reification for non-NCName predicates)
|
|
7109
|
+
* - `json-ld`: JSON-LD 1.1 with @context mapping to RDFS + DCTerms
|
|
6849
7110
|
*/
|
|
6850
|
-
declare const ExtendedExportFormatSchema: z.ZodEnum<["json", "csv", "graphml", "gexf", "dot", "markdown", "mermaid"]>;
|
|
7111
|
+
declare const ExtendedExportFormatSchema: z.ZodEnum<["json", "csv", "graphml", "gexf", "dot", "markdown", "mermaid", "turtle", "rdf-xml", "json-ld"]>;
|
|
6851
7112
|
/**
|
|
6852
7113
|
* Merge strategy validation for imports.
|
|
6853
7114
|
*/
|
|
@@ -7452,18 +7713,19 @@ declare function escapeCsvFormula(field: string | undefined | null): string;
|
|
|
7452
7713
|
*
|
|
7453
7714
|
* @param filePath - The file path to validate
|
|
7454
7715
|
* @param baseDir - Optional base directory for relative paths (defaults to process.cwd())
|
|
7716
|
+
* @param confineToBase - Whether to confine the resolved path to the base directory (defaults to true)
|
|
7455
7717
|
* @returns Validated absolute file path
|
|
7456
7718
|
* @throws {FileOperationError} If path traversal is detected or path is invalid
|
|
7457
7719
|
*
|
|
7458
7720
|
* @example
|
|
7459
7721
|
* ```typescript
|
|
7460
7722
|
* // Valid paths
|
|
7461
|
-
* validateFilePath('/var/data/memory.jsonl'); // Returns absolute path
|
|
7723
|
+
* validateFilePath('/var/data/memory.jsonl', '/var/data', true); // Returns absolute path
|
|
7462
7724
|
* validateFilePath('data/memory.jsonl'); // Returns absolute path from cwd
|
|
7463
7725
|
*
|
|
7464
7726
|
* // Invalid paths (throws FileOperationError)
|
|
7465
7727
|
* validateFilePath('../../../etc/passwd'); // Path traversal detected
|
|
7466
|
-
* validateFilePath('/var/data/../../../etc/passwd'); // Path
|
|
7728
|
+
* validateFilePath('/var/data/../../../etc/passwd', '/var/data', true); // Path is outside the allowed directory
|
|
7467
7729
|
* ```
|
|
7468
7730
|
*/
|
|
7469
7731
|
declare function validateFilePath(filePath: string, baseDir?: string, confineToBase?: boolean): string;
|
|
@@ -7725,6 +7987,10 @@ declare class WorkerPoolManager {
|
|
|
7725
7987
|
private eventCallbacks;
|
|
7726
7988
|
private isShuttingDown;
|
|
7727
7989
|
private shutdownRegistered;
|
|
7990
|
+
private exitHandler;
|
|
7991
|
+
private sigintHandler;
|
|
7992
|
+
private sigtermHandler;
|
|
7993
|
+
private uncaughtExceptionHandler;
|
|
7728
7994
|
private constructor();
|
|
7729
7995
|
/** Get the singleton instance. */
|
|
7730
7996
|
static getInstance(): WorkerPoolManager;
|
|
@@ -7732,6 +7998,8 @@ declare class WorkerPoolManager {
|
|
|
7732
7998
|
static resetInstance(): void;
|
|
7733
7999
|
/** Register process exit handlers for cleanup. */
|
|
7734
8000
|
private registerShutdownHandlers;
|
|
8001
|
+
/** Unregister process exit handlers to prevent memory leaks during tests. */
|
|
8002
|
+
private unregisterShutdownHandlers;
|
|
7735
8003
|
/** Get or create a named worker pool. */
|
|
7736
8004
|
getPool(poolId: string, config?: WorkerPoolConfig): Pool;
|
|
7737
8005
|
/** Create a new worker pool. Throws if poolId already exists. */
|
|
@@ -9301,6 +9569,23 @@ declare class GraphStorage implements IGraphStorage {
|
|
|
9301
9569
|
* ```
|
|
9302
9570
|
*/
|
|
9303
9571
|
get events(): GraphEventEmitter;
|
|
9572
|
+
/**
|
|
9573
|
+
* Synchronous access to the in-memory cached graph. Returns `null` if the
|
|
9574
|
+
* cache is not yet warm — in which case consumers should call
|
|
9575
|
+
* `loadGraph()` once to populate it and then use this accessor on
|
|
9576
|
+
* subsequent reads.
|
|
9577
|
+
*
|
|
9578
|
+
* Intended for integrations that need a synchronous read path backed by
|
|
9579
|
+
* `GraphStorage`'s already-materialized cache (e.g., the `ObservableDataModel`
|
|
9580
|
+
* adapter consumed by JSON-UI's `DataProvider`, which must supply a
|
|
9581
|
+
* synchronous `snapshot()` to React's `useSyncExternalStore`). Most
|
|
9582
|
+
* callers should prefer `loadGraph()`, which lazy-loads on first call.
|
|
9583
|
+
*
|
|
9584
|
+
* The returned reference is the live cache object — do NOT mutate it.
|
|
9585
|
+
* Use `loadGraph()` for a defensive read or `getGraphForMutation()` for
|
|
9586
|
+
* a mutable copy.
|
|
9587
|
+
*/
|
|
9588
|
+
get cachedGraph(): ReadonlyKnowledgeGraph | null;
|
|
9304
9589
|
/**
|
|
9305
9590
|
* Write content to file with fsync for durability.
|
|
9306
9591
|
*
|
|
@@ -9695,6 +9980,19 @@ declare class SQLiteStorage implements IGraphStorage {
|
|
|
9695
9980
|
* Checks if columns exist and adds them if not for backward compatibility.
|
|
9696
9981
|
*/
|
|
9697
9982
|
private migrateEntitiesTable;
|
|
9983
|
+
/**
|
|
9984
|
+
* Fields that round-trip through the `agentMetadata` JSON blob column.
|
|
9985
|
+
* Native columns (importance, projectId, version, contentHash, etc.) are
|
|
9986
|
+
* stored separately for SQL-side queryability. Everything else lives in
|
|
9987
|
+
* the blob to avoid schema-migration drift as the type system evolves.
|
|
9988
|
+
* Mirrors `OPTIONAL_PERSISTED_ENTITY_FIELDS` in GraphStorage.ts minus
|
|
9989
|
+
* the fields that already have native columns.
|
|
9990
|
+
*/
|
|
9991
|
+
private static readonly EXTENSION_FIELDS;
|
|
9992
|
+
/** Build the JSON blob payload for the `agentMetadata` column. */
|
|
9993
|
+
private serializeExtensionFields;
|
|
9994
|
+
/** Inverse of `serializeExtensionFields`. Tolerant of malformed JSON. */
|
|
9995
|
+
private parseExtensionFields;
|
|
9698
9996
|
/**
|
|
9699
9997
|
* Load all data from SQLite into memory cache.
|
|
9700
9998
|
*/
|
|
@@ -10369,7 +10667,28 @@ declare class EntityManager {
|
|
|
10369
10667
|
* }
|
|
10370
10668
|
* ```
|
|
10371
10669
|
*/
|
|
10372
|
-
|
|
10670
|
+
/**
|
|
10671
|
+
* Update an entity with optional optimistic-concurrency-control (η.5.5.c).
|
|
10672
|
+
*
|
|
10673
|
+
* Pass `options.expectedVersion` to enforce OCC: the caller asserts the
|
|
10674
|
+
* live entity has a specific `version`. If it differs (because another
|
|
10675
|
+
* agent / consolidation pass / contradiction-resolution incremented it
|
|
10676
|
+
* since the caller fetched), `VersionConflictError` is thrown with the
|
|
10677
|
+
* expected and actual versions. Omit `expectedVersion` for legacy
|
|
10678
|
+
* last-write-wins semantics (the default — backwards-compat).
|
|
10679
|
+
*
|
|
10680
|
+
* On a successful OCC-guarded write, `version` is auto-incremented:
|
|
10681
|
+
* `(entity.version ?? 1) + 1`. This makes OCC composable with the
|
|
10682
|
+
* existing v1.8.0 supersession-driven version increments.
|
|
10683
|
+
*
|
|
10684
|
+
* **Caveat**: a `ConsolidationScheduler` running in the background can
|
|
10685
|
+
* increment `version` between caller fetch and update, producing
|
|
10686
|
+
* spurious conflicts. Don't cache `expectedVersion` across scheduler
|
|
10687
|
+
* cycles — fetch immediately before writing.
|
|
10688
|
+
*/
|
|
10689
|
+
updateEntity(name: string, updates: Partial<Entity>, options?: {
|
|
10690
|
+
expectedVersion?: number;
|
|
10691
|
+
}): Promise<Entity>;
|
|
10373
10692
|
/**
|
|
10374
10693
|
* Update multiple entities in a single batch operation.
|
|
10375
10694
|
*
|
|
@@ -10485,6 +10804,36 @@ declare class EntityManager {
|
|
|
10485
10804
|
affectedEntities: string[];
|
|
10486
10805
|
count: number;
|
|
10487
10806
|
}>;
|
|
10807
|
+
/**
|
|
10808
|
+
* Mark an entity as no longer valid by setting `validUntil`. Idempotent:
|
|
10809
|
+
* a second call updates the existing `validUntil`. Does not delete the
|
|
10810
|
+
* entity — `entityAsOf` still returns it for past asOf timestamps.
|
|
10811
|
+
*
|
|
10812
|
+
* @param name - The entity to invalidate
|
|
10813
|
+
* @param ended - ISO 8601 timestamp; defaults to current time
|
|
10814
|
+
* @throws {EntityNotFoundError} If no entity exists with the given name
|
|
10815
|
+
*/
|
|
10816
|
+
invalidateEntity(name: string, ended?: string): Promise<void>;
|
|
10817
|
+
/**
|
|
10818
|
+
* Return the entity at a given point in time, or null if it didn't exist
|
|
10819
|
+
* (or was already invalidated) then. An entity is valid at `asOf` when:
|
|
10820
|
+
* - `validFrom` is undefined OR `validFrom` <= asOf
|
|
10821
|
+
* - `validUntil` is undefined OR `validUntil` >= asOf
|
|
10822
|
+
*
|
|
10823
|
+
* @param name - The entity name
|
|
10824
|
+
* @param asOf - ISO 8601 date string
|
|
10825
|
+
* @throws {ValidationError} If `asOf` is not an ISO 8601 date string
|
|
10826
|
+
*/
|
|
10827
|
+
entityAsOf(name: string, asOf: string): Promise<Entity | null>;
|
|
10828
|
+
/**
|
|
10829
|
+
* Return all temporal versions of an entity in chronological order
|
|
10830
|
+
* (by `validFrom`, with unbounded entities last). When `name` matches
|
|
10831
|
+
* a member of a v1.8.0 supersession chain, returns the full chain
|
|
10832
|
+
* sorted by `validFrom`. Otherwise returns just the named entity (or []).
|
|
10833
|
+
*
|
|
10834
|
+
* @param name - Any entity name in the chain
|
|
10835
|
+
*/
|
|
10836
|
+
entityTimeline(name: string): Promise<Entity[]>;
|
|
10488
10837
|
}
|
|
10489
10838
|
|
|
10490
10839
|
/**
|
|
@@ -10963,7 +11312,7 @@ declare class SemanticSearch {
|
|
|
10963
11312
|
* @module features/ContradictionDetector
|
|
10964
11313
|
*/
|
|
10965
11314
|
|
|
10966
|
-
interface Contradiction {
|
|
11315
|
+
interface Contradiction$1 {
|
|
10967
11316
|
/** Existing observation on the entity */
|
|
10968
11317
|
existingObservation: string;
|
|
10969
11318
|
/** New observation attempting to be added */
|
|
@@ -10982,7 +11331,7 @@ declare class ContradictionDetector {
|
|
|
10982
11331
|
* about the same subject with different values (e.g. "Lives in NYC" vs
|
|
10983
11332
|
* "Lives in SF") will be semantically close but textually different.
|
|
10984
11333
|
*/
|
|
10985
|
-
detect(entity: Entity, newObservations: string[]): Promise<Contradiction[]>;
|
|
11334
|
+
detect(entity: Entity, newObservations: string[]): Promise<Contradiction$1[]>;
|
|
10986
11335
|
/**
|
|
10987
11336
|
* Create a new version of an entity that supersedes the old one.
|
|
10988
11337
|
* The old entity gets isLatest=false and supersededBy=newName.
|
|
@@ -10998,50 +11347,356 @@ declare class ContradictionDetector {
|
|
|
10998
11347
|
}
|
|
10999
11348
|
|
|
11000
11349
|
/**
|
|
11001
|
-
*
|
|
11350
|
+
* Conflict Resolver
|
|
11002
11351
|
*
|
|
11003
|
-
*
|
|
11004
|
-
* Extracted from EntityManager (Phase 4: Consolidate God Objects).
|
|
11352
|
+
* Detects and resolves conflicting memories from different agents.
|
|
11005
11353
|
*
|
|
11006
|
-
* @module
|
|
11354
|
+
* @module agent/ConflictResolver
|
|
11007
11355
|
*/
|
|
11008
11356
|
|
|
11009
11357
|
/**
|
|
11010
|
-
*
|
|
11358
|
+
* Configuration for ConflictResolver.
|
|
11011
11359
|
*/
|
|
11012
|
-
|
|
11013
|
-
|
|
11014
|
-
|
|
11015
|
-
|
|
11016
|
-
|
|
11017
|
-
|
|
11360
|
+
interface ConflictResolverConfig {
|
|
11361
|
+
/** Similarity threshold for conflict detection (0-1, default: 0.7) */
|
|
11362
|
+
similarityThreshold?: number;
|
|
11363
|
+
/** Default resolution strategy */
|
|
11364
|
+
defaultStrategy?: ConflictStrategy;
|
|
11365
|
+
/** Enable negation detection */
|
|
11366
|
+
detectNegations?: boolean;
|
|
11367
|
+
}
|
|
11368
|
+
/**
|
|
11369
|
+
* Result of conflict resolution.
|
|
11370
|
+
*/
|
|
11371
|
+
interface ResolutionResult {
|
|
11372
|
+
/** Resolved memory */
|
|
11373
|
+
resolvedMemory: AgentEntity;
|
|
11374
|
+
/** Strategy used */
|
|
11375
|
+
strategy: ConflictStrategy;
|
|
11376
|
+
/** Memories that were merged/resolved */
|
|
11377
|
+
sourceMemories: string[];
|
|
11378
|
+
/** Audit trail entry */
|
|
11379
|
+
auditEntry: string;
|
|
11380
|
+
}
|
|
11381
|
+
/**
|
|
11382
|
+
* Resolves conflicts between memories from different agents.
|
|
11383
|
+
*
|
|
11384
|
+
* @example
|
|
11385
|
+
* ```typescript
|
|
11386
|
+
* const resolver = new ConflictResolver();
|
|
11387
|
+
* const conflicts = resolver.detectConflicts(memories);
|
|
11388
|
+
* const resolved = resolver.resolveConflict(conflictInfo, memories, agentMetadata, 'trusted_agent');
|
|
11389
|
+
* ```
|
|
11390
|
+
*/
|
|
11391
|
+
declare class ConflictResolver extends EventEmitter {
|
|
11392
|
+
private readonly config;
|
|
11393
|
+
constructor(config?: ConflictResolverConfig);
|
|
11018
11394
|
/**
|
|
11019
|
-
*
|
|
11020
|
-
*
|
|
11021
|
-
*
|
|
11395
|
+
* Detect conflicts between memories.
|
|
11396
|
+
*
|
|
11397
|
+
* Compares memories from different agents and identifies contradictions
|
|
11398
|
+
* based on observation similarity and negation patterns.
|
|
11399
|
+
*
|
|
11400
|
+
* @param memories - Memories to check for conflicts
|
|
11401
|
+
* @returns Array of detected conflicts
|
|
11022
11402
|
*/
|
|
11023
|
-
|
|
11403
|
+
detectConflicts(memories: AgentEntity[]): ConflictInfo[];
|
|
11024
11404
|
/**
|
|
11025
|
-
*
|
|
11405
|
+
* Check if two memories conflict.
|
|
11406
|
+
* @internal
|
|
11026
11407
|
*/
|
|
11027
|
-
|
|
11408
|
+
private checkConflict;
|
|
11028
11409
|
/**
|
|
11029
|
-
*
|
|
11030
|
-
*
|
|
11031
|
-
* Priority: explicit parameter > env var > disabled (default).
|
|
11032
|
-
* If the env var `MEMORY_OBSERVATION_DEDUP` is set to `'true'` and no explicit
|
|
11033
|
-
* options are provided, dedup is enabled with default settings.
|
|
11034
|
-
*
|
|
11035
|
-
* @param dedup - Explicit deduplication options (if any)
|
|
11036
|
-
* @returns Resolved options, or undefined if dedup is disabled
|
|
11410
|
+
* Calculate similarity between two memories using TF-style scoring.
|
|
11037
11411
|
* @internal
|
|
11038
11412
|
*/
|
|
11039
|
-
private
|
|
11413
|
+
private calculateSimilarity;
|
|
11040
11414
|
/**
|
|
11041
|
-
*
|
|
11415
|
+
* Convert memory to text for comparison.
|
|
11416
|
+
* @internal
|
|
11417
|
+
*/
|
|
11418
|
+
private memoryToText;
|
|
11419
|
+
/**
|
|
11420
|
+
* Detect negation patterns in observations.
|
|
11421
|
+
* @internal
|
|
11422
|
+
*/
|
|
11423
|
+
private detectNegation;
|
|
11424
|
+
/**
|
|
11425
|
+
* Simple text similarity.
|
|
11426
|
+
* @internal
|
|
11427
|
+
*/
|
|
11428
|
+
private textSimilarity;
|
|
11429
|
+
/**
|
|
11430
|
+
* Check if two memories have equal observations.
|
|
11431
|
+
* @internal
|
|
11432
|
+
*/
|
|
11433
|
+
private observationsEqual;
|
|
11434
|
+
/**
|
|
11435
|
+
* Suggest the best resolution strategy based on memory properties.
|
|
11436
|
+
* @internal
|
|
11437
|
+
*/
|
|
11438
|
+
private suggestStrategy;
|
|
11439
|
+
/**
|
|
11440
|
+
* Resolve a conflict using the specified strategy.
|
|
11042
11441
|
*
|
|
11043
|
-
*
|
|
11044
|
-
*
|
|
11442
|
+
* @param conflict - Conflict information
|
|
11443
|
+
* @param memories - All memories involved
|
|
11444
|
+
* @param agents - Agent metadata for trust-based resolution
|
|
11445
|
+
* @param strategy - Resolution strategy (uses suggested if not specified)
|
|
11446
|
+
* @returns Resolution result
|
|
11447
|
+
*/
|
|
11448
|
+
resolveConflict(conflict: ConflictInfo, memories: AgentEntity[], agents: Map<string, AgentMetadata>, strategy?: ConflictStrategy): ResolutionResult;
|
|
11449
|
+
/**
|
|
11450
|
+
* Resolve by selecting most recently modified memory.
|
|
11451
|
+
* @internal
|
|
11452
|
+
*/
|
|
11453
|
+
private resolveMostRecent;
|
|
11454
|
+
/**
|
|
11455
|
+
* Resolve by selecting highest confidence memory.
|
|
11456
|
+
* @internal
|
|
11457
|
+
*/
|
|
11458
|
+
private resolveHighestConfidence;
|
|
11459
|
+
/**
|
|
11460
|
+
* Resolve by selecting most confirmed memory.
|
|
11461
|
+
* @internal
|
|
11462
|
+
*/
|
|
11463
|
+
private resolveMostConfirmations;
|
|
11464
|
+
/**
|
|
11465
|
+
* Resolve by selecting memory from most trusted agent.
|
|
11466
|
+
* @internal
|
|
11467
|
+
*/
|
|
11468
|
+
private resolveTrustedAgent;
|
|
11469
|
+
/**
|
|
11470
|
+
* Resolve by merging all observations into one memory.
|
|
11471
|
+
* @internal
|
|
11472
|
+
*/
|
|
11473
|
+
private resolveMergeAll;
|
|
11474
|
+
/**
|
|
11475
|
+
* Get current configuration.
|
|
11476
|
+
*/
|
|
11477
|
+
getConfig(): Readonly<Required<ConflictResolverConfig>>;
|
|
11478
|
+
}
|
|
11479
|
+
|
|
11480
|
+
/**
|
|
11481
|
+
* MemoryValidator — Phase δ.1 (ROADMAP §3B.1).
|
|
11482
|
+
*
|
|
11483
|
+
* Reflection-stage service that prevents hallucinations and logical errors
|
|
11484
|
+
* from contaminating memory through self-critique before storage. Wraps
|
|
11485
|
+
* the existing `ContradictionDetector` for the detection method (per
|
|
11486
|
+
* ADR-011 wrap-and-extend), and adds four new methods natively:
|
|
11487
|
+
*
|
|
11488
|
+
* - `validateConsistency(newObs, existing)` — semantic + temporal +
|
|
11489
|
+
* structural check of one new observation against an entity's body.
|
|
11490
|
+
* - `detectContradictions(entity)` — delegates to `ContradictionDetector.detect`.
|
|
11491
|
+
* - `repairMemory(entity, feedback)` — applies feedback as a corrective
|
|
11492
|
+
* observation; integrates with `ConflictResolver` when configured.
|
|
11493
|
+
* - `validateTemporalOrder(observations)` — synchronous chronological
|
|
11494
|
+
* sanity check on observations carrying ISO-8601 timestamps.
|
|
11495
|
+
* - `calculateReliability(entity)` — composite score from confidence,
|
|
11496
|
+
* confirmation count, and access pattern (read-only).
|
|
11497
|
+
*
|
|
11498
|
+
* @module agent/MemoryValidator
|
|
11499
|
+
*/
|
|
11500
|
+
|
|
11501
|
+
/** Per-issue annotation produced by `validateConsistency` /
|
|
11502
|
+
* `validateTemporalOrder`. Named `MemoryValidationIssue` to avoid
|
|
11503
|
+
* collision with the existing `ValidationIssue` re-exported under
|
|
11504
|
+
* `src/types/`. */
|
|
11505
|
+
interface MemoryValidationIssue {
|
|
11506
|
+
/** Stable kind identifier — useful for filtering in higher layers. */
|
|
11507
|
+
kind: 'semantic-contradiction' | 'temporal-disorder' | 'duplicate-observation' | 'low-confidence';
|
|
11508
|
+
/** Human-readable description (no localization yet). */
|
|
11509
|
+
message: string;
|
|
11510
|
+
/** Optional pointer to the offending observation (when applicable). */
|
|
11511
|
+
observation?: string;
|
|
11512
|
+
}
|
|
11513
|
+
/** Composite result returned by the `validate*` methods. Distinct from
|
|
11514
|
+
* the existing `ContradictionDetector.Contradiction` shape because it
|
|
11515
|
+
* spans multiple issue kinds, not just semantic similarity hits. Named
|
|
11516
|
+
* `MemoryValidationResult` to avoid collision with the existing
|
|
11517
|
+
* `MemoryValidationResult` re-exported under `src/utils/`. */
|
|
11518
|
+
interface MemoryValidationResult {
|
|
11519
|
+
isValid: boolean;
|
|
11520
|
+
/** Confidence in the validation itself (0-1). Reflects how certain we
|
|
11521
|
+
* are about the verdict, separate from the entity's own confidence. */
|
|
11522
|
+
confidence: number;
|
|
11523
|
+
issues: MemoryValidationIssue[];
|
|
11524
|
+
/** Plain-text follow-up actions a higher-level orchestrator might apply
|
|
11525
|
+
* (e.g., "drop observation X", "re-confirm with user"). */
|
|
11526
|
+
suggestions: string[];
|
|
11527
|
+
}
|
|
11528
|
+
/** Per-spec extended Contradiction shape with a conflict type and
|
|
11529
|
+
* severity tag. The lighter `ContradictionDetector.Contradiction` shape
|
|
11530
|
+
* (similarity-only) is converted up at the boundary. */
|
|
11531
|
+
interface Contradiction {
|
|
11532
|
+
observation1: string;
|
|
11533
|
+
observation2: string;
|
|
11534
|
+
conflictType: 'factual' | 'temporal' | 'logical';
|
|
11535
|
+
severity: 'low' | 'medium' | 'high';
|
|
11536
|
+
/** Optional resolved/repaired observation that supersedes both inputs. */
|
|
11537
|
+
resolution?: string;
|
|
11538
|
+
}
|
|
11539
|
+
interface MemoryValidatorConfig {
|
|
11540
|
+
/** Confidence floor below which `calculateReliability` flags
|
|
11541
|
+
* `low-confidence`. Default 0.4. */
|
|
11542
|
+
lowConfidenceThreshold?: number;
|
|
11543
|
+
}
|
|
11544
|
+
declare class MemoryValidator {
|
|
11545
|
+
private readonly contradictionDetector;
|
|
11546
|
+
private readonly lowConfidenceThreshold;
|
|
11547
|
+
constructor(contradictionDetector: ContradictionDetector, config?: MemoryValidatorConfig);
|
|
11548
|
+
/**
|
|
11549
|
+
* Check a new observation against an entity's existing knowledge.
|
|
11550
|
+
* Composite: runs the contradiction detector, plus duplicate detection,
|
|
11551
|
+
* plus low-confidence flag if the entity itself looks unreliable.
|
|
11552
|
+
*/
|
|
11553
|
+
validateConsistency(newObservation: string, existing: Entity): Promise<MemoryValidationResult>;
|
|
11554
|
+
/**
|
|
11555
|
+
* Detect contradictions within an entity's own observation set.
|
|
11556
|
+
* Delegates to `ContradictionDetector.detect` against a synthetic
|
|
11557
|
+
* "new observations" set (every observation paired against the rest).
|
|
11558
|
+
*
|
|
11559
|
+
* Per ROADMAP §3B.1 spec, returns the extended Contradiction shape
|
|
11560
|
+
* (with `conflictType` + `severity`) — these are derived heuristically
|
|
11561
|
+
* from similarity score because the underlying detector is similarity-
|
|
11562
|
+
* only.
|
|
11563
|
+
*/
|
|
11564
|
+
detectContradictions(entity: Entity): Promise<Contradiction[]>;
|
|
11565
|
+
/**
|
|
11566
|
+
* Apply feedback to repair an entity by appending a corrective
|
|
11567
|
+
* observation prefixed with `[repair]`. Returns the repaired entity
|
|
11568
|
+
* — does NOT persist. Caller decides via
|
|
11569
|
+
* `EntityManager.updateEntity` or supersede semantics.
|
|
11570
|
+
*
|
|
11571
|
+
* For full `ConflictResolver`-driven repair against a competing
|
|
11572
|
+
* memory, see `repairWithResolver`.
|
|
11573
|
+
*/
|
|
11574
|
+
repairMemory(entity: Entity, feedback: string): Promise<Entity>;
|
|
11575
|
+
/**
|
|
11576
|
+
* Repair an entity by delegating to a `ConflictResolver`. Constructs
|
|
11577
|
+
* the minimal `ConflictInfo` from a `Contradiction` finding so callers
|
|
11578
|
+
* don't have to hand-build it. Closes the loop spec'd in ROADMAP §3B.1
|
|
11579
|
+
* for `repairMemory` integration.
|
|
11580
|
+
*
|
|
11581
|
+
* @param entity Primary memory being repaired (must be `AgentEntity`).
|
|
11582
|
+
* @param competing Competing memory to resolve against.
|
|
11583
|
+
* @param contradiction Optional similarity score / context. Severity
|
|
11584
|
+
* is mapped onto `detectionMethod = 'similarity'`.
|
|
11585
|
+
* @param resolver The `ConflictResolver` instance.
|
|
11586
|
+
* @param agents Optional agent-metadata registry (used by the
|
|
11587
|
+
* `trusted_agent` strategy). Empty Map is fine
|
|
11588
|
+
* for the strategies that don't need it.
|
|
11589
|
+
* @returns The resolved memory per the resolver's verdict.
|
|
11590
|
+
*
|
|
11591
|
+
* Throws when neither input is an `AgentEntity` (resolver requires the
|
|
11592
|
+
* extension fields), or when the resolver itself throws (e.g., no
|
|
11593
|
+
* conflicting memories found — should not happen given we provide both).
|
|
11594
|
+
*/
|
|
11595
|
+
repairWithResolver(entity: AgentEntity, competing: AgentEntity, resolver: ConflictResolver, options?: {
|
|
11596
|
+
contradiction?: {
|
|
11597
|
+
similarity?: number;
|
|
11598
|
+
};
|
|
11599
|
+
detectionMethod?: 'similarity' | 'negation' | 'manual';
|
|
11600
|
+
strategy?: ConflictStrategy;
|
|
11601
|
+
agents?: Map<string, AgentMetadata>;
|
|
11602
|
+
}): Promise<AgentEntity>;
|
|
11603
|
+
/**
|
|
11604
|
+
* Validate temporal consistency of observations carrying ISO-8601
|
|
11605
|
+
* timestamps. Looks for either explicit `[T=ISO]` prefixes or
|
|
11606
|
+
* `createdAt`-style metadata. Returns `isValid: false` when any
|
|
11607
|
+
* adjacent pair is out of order.
|
|
11608
|
+
*
|
|
11609
|
+
* Synchronous (no I/O); the spec method is sync.
|
|
11610
|
+
*/
|
|
11611
|
+
validateTemporalOrder(observations: string[]): MemoryValidationResult;
|
|
11612
|
+
/**
|
|
11613
|
+
* Reliability score in `[0, 1]`. Composite of:
|
|
11614
|
+
* - the entity's own `confidence` field (default 0.5 when absent),
|
|
11615
|
+
* - confirmation count (asymptotic — diminishing returns past 5),
|
|
11616
|
+
* - inverse decay from creation time (older = slightly less reliable
|
|
11617
|
+
* absent reinforcement; very gentle, doesn't dominate).
|
|
11618
|
+
*
|
|
11619
|
+
* Read-only; does not persist anything to the entity.
|
|
11620
|
+
*/
|
|
11621
|
+
calculateReliability(entity: Entity): number;
|
|
11622
|
+
}
|
|
11623
|
+
|
|
11624
|
+
/**
|
|
11625
|
+
* Observation Manager
|
|
11626
|
+
*
|
|
11627
|
+
* Handles observation CRUD operations for entities.
|
|
11628
|
+
* Extracted from EntityManager (Phase 4: Consolidate God Objects).
|
|
11629
|
+
*
|
|
11630
|
+
* @module core/ObservationManager
|
|
11631
|
+
*/
|
|
11632
|
+
|
|
11633
|
+
/**
|
|
11634
|
+
* Manages observation operations for entities in the knowledge graph.
|
|
11635
|
+
*/
|
|
11636
|
+
declare class ObservationManager {
|
|
11637
|
+
private storage;
|
|
11638
|
+
private contradictionDetector?;
|
|
11639
|
+
private linkedEntityManager?;
|
|
11640
|
+
private _autoLinker?;
|
|
11641
|
+
/** Lazy provider for the validator — invoking it constructs / fetches
|
|
11642
|
+
* the MemoryValidator. Stored as a thunk so unconditional wiring at
|
|
11643
|
+
* `ManagerContext` construction time costs nothing until the validator
|
|
11644
|
+
* is actually needed (i.e., MEMORY_VALIDATE_ON_STORE flips on AND an
|
|
11645
|
+
* observation gets added). */
|
|
11646
|
+
private memoryValidatorProvider?;
|
|
11647
|
+
constructor(storage: GraphStorage);
|
|
11648
|
+
/**
|
|
11649
|
+
* Enable contradiction detection on addObservations.
|
|
11650
|
+
* When a new observation is detected as contradicting an existing one,
|
|
11651
|
+
* a new entity version is created instead of appending.
|
|
11652
|
+
*/
|
|
11653
|
+
setContradictionDetector(detector: ContradictionDetector, entityManager: EntityManager): void;
|
|
11654
|
+
/**
|
|
11655
|
+
* Set the AutoLinker for optional automatic mention detection.
|
|
11656
|
+
*/
|
|
11657
|
+
setAutoLinker(autoLinker: AutoLinker): void;
|
|
11658
|
+
/**
|
|
11659
|
+
* Wire a `MemoryValidator` provider for the optional pre-storage
|
|
11660
|
+
* validation hook (Phase δ.1, T31). The argument is a thunk so the
|
|
11661
|
+
* validator can be lazy-constructed only when actually needed —
|
|
11662
|
+
* `ManagerContext` wires this unconditionally at construction time so
|
|
11663
|
+
* runtime toggling of `MEMORY_VALIDATE_ON_STORE` works in both
|
|
11664
|
+
* directions, but the validator object itself isn't built until the
|
|
11665
|
+
* first observation is added with the flag on.
|
|
11666
|
+
*
|
|
11667
|
+
* Behaviour when flag is on:
|
|
11668
|
+
* - `duplicate-observation` → blocking; observation skipped with a
|
|
11669
|
+
* `console.warn`.
|
|
11670
|
+
* - `semantic-contradiction` → ADVISORY; if a `ContradictionDetector`
|
|
11671
|
+
* is also wired (the v1.8.0 supersede branch), that branch handles
|
|
11672
|
+
* the case downstream and creates a proper version chain. Filtering
|
|
11673
|
+
* it here would silently disable supersede semantics.
|
|
11674
|
+
* - `low-confidence` → ADVISORY only.
|
|
11675
|
+
*
|
|
11676
|
+
* Default off — preserves backwards-compat for existing callers.
|
|
11677
|
+
*
|
|
11678
|
+
* Overload: accepts either a validator instance (eager) or a thunk
|
|
11679
|
+
* (lazy). Pass the instance for tests where a stub is convenient;
|
|
11680
|
+
* pass the thunk for production wiring through `ManagerContext`.
|
|
11681
|
+
*/
|
|
11682
|
+
setMemoryValidator(validatorOrProvider: MemoryValidator | (() => MemoryValidator)): void;
|
|
11683
|
+
/**
|
|
11684
|
+
* Resolve deduplication options from explicit parameter and environment variable.
|
|
11685
|
+
*
|
|
11686
|
+
* Priority: explicit parameter > env var > disabled (default).
|
|
11687
|
+
* If the env var `MEMORY_OBSERVATION_DEDUP` is set to `'true'` and no explicit
|
|
11688
|
+
* options are provided, dedup is enabled with default settings.
|
|
11689
|
+
*
|
|
11690
|
+
* @param dedup - Explicit deduplication options (if any)
|
|
11691
|
+
* @returns Resolved options, or undefined if dedup is disabled
|
|
11692
|
+
* @internal
|
|
11693
|
+
*/
|
|
11694
|
+
private resolveDedup;
|
|
11695
|
+
/**
|
|
11696
|
+
* Add observations to multiple entities in a single batch operation.
|
|
11697
|
+
*
|
|
11698
|
+
* This method performs the following operations:
|
|
11699
|
+
* - Adds new observations to specified entities
|
|
11045
11700
|
* - Filters out exact duplicate observations (already present)
|
|
11046
11701
|
* - Optionally performs fuzzy deduplication against existing observations
|
|
11047
11702
|
* - Updates lastModified timestamp only if new observations were added
|
|
@@ -11133,6 +11788,26 @@ declare class ObservationManager {
|
|
|
11133
11788
|
entityName: string;
|
|
11134
11789
|
observations: string[];
|
|
11135
11790
|
}[]): Promise<void>;
|
|
11791
|
+
/**
|
|
11792
|
+
* Mark a specific observation as no longer valid by setting its
|
|
11793
|
+
* `validUntil`. Creates the parallel `observationMeta[]` entry if absent
|
|
11794
|
+
* (preserves backwards-compat for entities that don't use the bitemporal
|
|
11795
|
+
* axis). Idempotent: a second call updates the existing `validUntil`.
|
|
11796
|
+
*
|
|
11797
|
+
* @throws {EntityNotFoundError} If no entity exists with the given name
|
|
11798
|
+
* @throws {ValidationError} If the observation isn't found on the entity
|
|
11799
|
+
*/
|
|
11800
|
+
invalidateObservation(entityName: string, content: string, ended?: string): Promise<void>;
|
|
11801
|
+
/**
|
|
11802
|
+
* Return observations valid at a given point in time. An observation
|
|
11803
|
+
* with no meta entry is treated as unbounded (always valid). With a meta
|
|
11804
|
+
* entry, validity rules mirror `EntityManager.entityAsOf`:
|
|
11805
|
+
* - `validFrom` undefined OR `validFrom` <= asOf
|
|
11806
|
+
* - `validUntil` undefined OR `validUntil` >= asOf
|
|
11807
|
+
*
|
|
11808
|
+
* @throws {ValidationError} If `asOf` is not an ISO 8601 date string
|
|
11809
|
+
*/
|
|
11810
|
+
observationsAsOf(entityName: string, asOf: string): Promise<string[]>;
|
|
11136
11811
|
}
|
|
11137
11812
|
|
|
11138
11813
|
/**
|
|
@@ -15456,7 +16131,7 @@ declare class LLMSearchExecutor {
|
|
|
15456
16131
|
|
|
15457
16132
|
/** Unified manager for import, export, and backup operations. */
|
|
15458
16133
|
|
|
15459
|
-
type ExportFormat = 'json' | 'csv' | 'graphml' | 'gexf' | 'dot' | 'markdown' | 'mermaid';
|
|
16134
|
+
type ExportFormat = 'json' | 'csv' | 'graphml' | 'gexf' | 'dot' | 'markdown' | 'mermaid' | 'turtle' | 'rdf-xml' | 'json-ld';
|
|
15460
16135
|
type ImportFormat = 'json' | 'csv' | 'graphml';
|
|
15461
16136
|
type MergeStrategy = 'replace' | 'skip' | 'merge' | 'fail';
|
|
15462
16137
|
interface IngestInput {
|
|
@@ -15545,6 +16220,46 @@ declare class IOManager {
|
|
|
15545
16220
|
constructor(storage: GraphStorage);
|
|
15546
16221
|
/** Export graph to specified format. */
|
|
15547
16222
|
exportGraph(graph: ReadonlyKnowledgeGraph, format: ExportFormat): string;
|
|
16223
|
+
/** IRI for an entity resource. Format: `urn:memoryjs:entity:<percent-encoded-name>`. */
|
|
16224
|
+
private entityIri;
|
|
16225
|
+
/** IRI for a relation predicate. Format: `urn:memoryjs:rel:<percent-encoded-type>`. */
|
|
16226
|
+
private relationIri;
|
|
16227
|
+
/**
|
|
16228
|
+
* Escape a string for a Turtle `STRING_LITERAL_QUOTE` per W3C Turtle 1.1.
|
|
16229
|
+
* - Named ECHAR escapes for `\\ " \n \r \t \b \f`
|
|
16230
|
+
* - Other C0 control chars (forbidden unescaped in `"..."`) as `\uXXXX`
|
|
16231
|
+
*/
|
|
16232
|
+
private turtleEscape;
|
|
16233
|
+
/**
|
|
16234
|
+
* Test whether a string is a valid XML 1.0 NCName — ASCII subset,
|
|
16235
|
+
* sufficient because `relationIri()` percent-encodes everything else.
|
|
16236
|
+
* RDF/XML requires this for property-element predicate names.
|
|
16237
|
+
*/
|
|
16238
|
+
private isValidNCName;
|
|
16239
|
+
/**
|
|
16240
|
+
* Export as Turtle (W3C RDF 1.1).
|
|
16241
|
+
* - entity → `urn:memoryjs:entity:<name>` resource
|
|
16242
|
+
* - entityType → `rdf:type` with `urn:memoryjs:type:<type>` IRI
|
|
16243
|
+
* - observations → `rdfs:comment` literals
|
|
16244
|
+
* - tags → `dcterms:subject` literals
|
|
16245
|
+
* - createdAt → `dcterms:created` literal
|
|
16246
|
+
* - relation → `<from> <urn:memoryjs:rel:<type>> <to>` triple
|
|
16247
|
+
*/
|
|
16248
|
+
private exportAsTurtle;
|
|
16249
|
+
/**
|
|
16250
|
+
* Export as RDF/XML (W3C RDF 1.1 XML serialization).
|
|
16251
|
+
* - Same triple set as Turtle, in XML form
|
|
16252
|
+
* - NCName-valid relation types → property-element under `mjsRel:`
|
|
16253
|
+
* - Otherwise → asserted `mjsRel:link` triple plus `rdf:Statement` reification preserving the original predicate IRI
|
|
16254
|
+
*/
|
|
16255
|
+
private exportAsRdfXml;
|
|
16256
|
+
/**
|
|
16257
|
+
* Export as JSON-LD (JSON for Linking Data).
|
|
16258
|
+
* - `@context` maps memoryjs schema to RDFS + DCTerms vocabularies
|
|
16259
|
+
* - observations/tags use `@container: @set` so each value becomes its own triple (matches Turtle/RDF-XML), not an `rdf:List`
|
|
16260
|
+
* - any JSON-LD parser yields the same RDF graph as the Turtle export
|
|
16261
|
+
*/
|
|
16262
|
+
private exportAsJsonLd;
|
|
15548
16263
|
/** Export graph with optional brotli compression. */
|
|
15549
16264
|
exportGraphWithCompression(graph: ReadonlyKnowledgeGraph, format: ExportFormat, options?: ExportOptions): Promise<ExportResult>;
|
|
15550
16265
|
/** Stream export to a file for large graphs. */
|
|
@@ -16330,6 +17045,11 @@ declare class TransitionLedger {
|
|
|
16330
17045
|
* @returns Unsubscribe function to detach all listeners
|
|
16331
17046
|
*/
|
|
16332
17047
|
attachToEmitter(emitter: GraphEventEmitter, onError?: (error: unknown) => void): () => void;
|
|
17048
|
+
/**
|
|
17049
|
+
* Map entity state to a consistent audit format.
|
|
17050
|
+
* Extracts only the core data fields to avoid metadata noise.
|
|
17051
|
+
*/
|
|
17052
|
+
private mapEntityState;
|
|
16333
17053
|
/**
|
|
16334
17054
|
* Deep equality check for transition values.
|
|
16335
17055
|
* Handles primitives, arrays, and plain objects.
|
|
@@ -18442,137 +19162,6 @@ declare class SessionManager {
|
|
|
18442
19162
|
getActiveSessionCount(): number;
|
|
18443
19163
|
}
|
|
18444
19164
|
|
|
18445
|
-
/**
|
|
18446
|
-
* Conflict Resolver
|
|
18447
|
-
*
|
|
18448
|
-
* Detects and resolves conflicting memories from different agents.
|
|
18449
|
-
*
|
|
18450
|
-
* @module agent/ConflictResolver
|
|
18451
|
-
*/
|
|
18452
|
-
|
|
18453
|
-
/**
|
|
18454
|
-
* Configuration for ConflictResolver.
|
|
18455
|
-
*/
|
|
18456
|
-
interface ConflictResolverConfig {
|
|
18457
|
-
/** Similarity threshold for conflict detection (0-1, default: 0.7) */
|
|
18458
|
-
similarityThreshold?: number;
|
|
18459
|
-
/** Default resolution strategy */
|
|
18460
|
-
defaultStrategy?: ConflictStrategy;
|
|
18461
|
-
/** Enable negation detection */
|
|
18462
|
-
detectNegations?: boolean;
|
|
18463
|
-
}
|
|
18464
|
-
/**
|
|
18465
|
-
* Result of conflict resolution.
|
|
18466
|
-
*/
|
|
18467
|
-
interface ResolutionResult {
|
|
18468
|
-
/** Resolved memory */
|
|
18469
|
-
resolvedMemory: AgentEntity;
|
|
18470
|
-
/** Strategy used */
|
|
18471
|
-
strategy: ConflictStrategy;
|
|
18472
|
-
/** Memories that were merged/resolved */
|
|
18473
|
-
sourceMemories: string[];
|
|
18474
|
-
/** Audit trail entry */
|
|
18475
|
-
auditEntry: string;
|
|
18476
|
-
}
|
|
18477
|
-
/**
|
|
18478
|
-
* Resolves conflicts between memories from different agents.
|
|
18479
|
-
*
|
|
18480
|
-
* @example
|
|
18481
|
-
* ```typescript
|
|
18482
|
-
* const resolver = new ConflictResolver();
|
|
18483
|
-
* const conflicts = resolver.detectConflicts(memories);
|
|
18484
|
-
* const resolved = resolver.resolveConflict(conflictInfo, memories, agentMetadata, 'trusted_agent');
|
|
18485
|
-
* ```
|
|
18486
|
-
*/
|
|
18487
|
-
declare class ConflictResolver extends EventEmitter {
|
|
18488
|
-
private readonly config;
|
|
18489
|
-
constructor(config?: ConflictResolverConfig);
|
|
18490
|
-
/**
|
|
18491
|
-
* Detect conflicts between memories.
|
|
18492
|
-
*
|
|
18493
|
-
* Compares memories from different agents and identifies contradictions
|
|
18494
|
-
* based on observation similarity and negation patterns.
|
|
18495
|
-
*
|
|
18496
|
-
* @param memories - Memories to check for conflicts
|
|
18497
|
-
* @returns Array of detected conflicts
|
|
18498
|
-
*/
|
|
18499
|
-
detectConflicts(memories: AgentEntity[]): ConflictInfo[];
|
|
18500
|
-
/**
|
|
18501
|
-
* Check if two memories conflict.
|
|
18502
|
-
* @internal
|
|
18503
|
-
*/
|
|
18504
|
-
private checkConflict;
|
|
18505
|
-
/**
|
|
18506
|
-
* Calculate similarity between two memories using TF-style scoring.
|
|
18507
|
-
* @internal
|
|
18508
|
-
*/
|
|
18509
|
-
private calculateSimilarity;
|
|
18510
|
-
/**
|
|
18511
|
-
* Convert memory to text for comparison.
|
|
18512
|
-
* @internal
|
|
18513
|
-
*/
|
|
18514
|
-
private memoryToText;
|
|
18515
|
-
/**
|
|
18516
|
-
* Detect negation patterns in observations.
|
|
18517
|
-
* @internal
|
|
18518
|
-
*/
|
|
18519
|
-
private detectNegation;
|
|
18520
|
-
/**
|
|
18521
|
-
* Simple text similarity.
|
|
18522
|
-
* @internal
|
|
18523
|
-
*/
|
|
18524
|
-
private textSimilarity;
|
|
18525
|
-
/**
|
|
18526
|
-
* Check if two memories have equal observations.
|
|
18527
|
-
* @internal
|
|
18528
|
-
*/
|
|
18529
|
-
private observationsEqual;
|
|
18530
|
-
/**
|
|
18531
|
-
* Suggest the best resolution strategy based on memory properties.
|
|
18532
|
-
* @internal
|
|
18533
|
-
*/
|
|
18534
|
-
private suggestStrategy;
|
|
18535
|
-
/**
|
|
18536
|
-
* Resolve a conflict using the specified strategy.
|
|
18537
|
-
*
|
|
18538
|
-
* @param conflict - Conflict information
|
|
18539
|
-
* @param memories - All memories involved
|
|
18540
|
-
* @param agents - Agent metadata for trust-based resolution
|
|
18541
|
-
* @param strategy - Resolution strategy (uses suggested if not specified)
|
|
18542
|
-
* @returns Resolution result
|
|
18543
|
-
*/
|
|
18544
|
-
resolveConflict(conflict: ConflictInfo, memories: AgentEntity[], agents: Map<string, AgentMetadata>, strategy?: ConflictStrategy): ResolutionResult;
|
|
18545
|
-
/**
|
|
18546
|
-
* Resolve by selecting most recently modified memory.
|
|
18547
|
-
* @internal
|
|
18548
|
-
*/
|
|
18549
|
-
private resolveMostRecent;
|
|
18550
|
-
/**
|
|
18551
|
-
* Resolve by selecting highest confidence memory.
|
|
18552
|
-
* @internal
|
|
18553
|
-
*/
|
|
18554
|
-
private resolveHighestConfidence;
|
|
18555
|
-
/**
|
|
18556
|
-
* Resolve by selecting most confirmed memory.
|
|
18557
|
-
* @internal
|
|
18558
|
-
*/
|
|
18559
|
-
private resolveMostConfirmations;
|
|
18560
|
-
/**
|
|
18561
|
-
* Resolve by selecting memory from most trusted agent.
|
|
18562
|
-
* @internal
|
|
18563
|
-
*/
|
|
18564
|
-
private resolveTrustedAgent;
|
|
18565
|
-
/**
|
|
18566
|
-
* Resolve by merging all observations into one memory.
|
|
18567
|
-
* @internal
|
|
18568
|
-
*/
|
|
18569
|
-
private resolveMergeAll;
|
|
18570
|
-
/**
|
|
18571
|
-
* Get current configuration.
|
|
18572
|
-
*/
|
|
18573
|
-
getConfig(): Readonly<Required<ConflictResolverConfig>>;
|
|
18574
|
-
}
|
|
18575
|
-
|
|
18576
19165
|
/**
|
|
18577
19166
|
* Multi-Agent Memory Manager
|
|
18578
19167
|
*
|
|
@@ -19280,10 +19869,55 @@ interface CollaborativeSynthesisConfig {
|
|
|
19280
19869
|
relationTypes?: string[];
|
|
19281
19870
|
}
|
|
19282
19871
|
/**
|
|
19283
|
-
*
|
|
19872
|
+
* A single multi-agent conflict surfaced during synthesis (η.5.5.a).
|
|
19873
|
+
*
|
|
19874
|
+
* Each ConflictView represents a group of entities that share the same
|
|
19875
|
+
* `rootEntityName` (or `name` when there is no v1.8.0 supersession chain)
|
|
19876
|
+
* but were authored by *different* `agentId`s — i.e. multiple agents have
|
|
19877
|
+
* written competing versions of the same logical entity.
|
|
19878
|
+
*
|
|
19879
|
+
* The `recommendedWinner` is the agentId of the candidate with the highest
|
|
19880
|
+
* `score = (confidence ?? 0.5) × salienceScore`. Callers pick a final
|
|
19881
|
+
* winner by calling `resolveConflicts(result, policy)` on the synthesis
|
|
19882
|
+
* instance — the recommendation is advisory.
|
|
19284
19883
|
*/
|
|
19285
|
-
interface
|
|
19286
|
-
/**
|
|
19884
|
+
interface ConflictView {
|
|
19885
|
+
/** Logical entity identity — `rootEntityName` if set, else `name`. */
|
|
19886
|
+
entityName: string;
|
|
19887
|
+
/** Competing versions, sorted by score descending. */
|
|
19888
|
+
candidates: Array<{
|
|
19889
|
+
agentId: string;
|
|
19890
|
+
entity: AgentEntity;
|
|
19891
|
+
/** confidence × salienceScore, normalized to [0, 1]. */
|
|
19892
|
+
score: number;
|
|
19893
|
+
}>;
|
|
19894
|
+
/** agentId of the highest-scored candidate (advisory). */
|
|
19895
|
+
recommendedWinner: string;
|
|
19896
|
+
}
|
|
19897
|
+
/**
|
|
19898
|
+
* Strategy for resolving a `ConflictView` programmatically.
|
|
19899
|
+
*
|
|
19900
|
+
* - `most_recent` — pick the candidate with the latest `lastModified`.
|
|
19901
|
+
* - `highest_confidence` — pick the candidate with the highest `confidence`.
|
|
19902
|
+
* - `highest_score` — pick `recommendedWinner` (default).
|
|
19903
|
+
* - `trusted_agent` — caller supplies a `trustedAgentId`; that agent wins
|
|
19904
|
+
* if present in the candidates, else falls back to `highest_score`.
|
|
19905
|
+
*/
|
|
19906
|
+
type ConflictResolutionPolicy = {
|
|
19907
|
+
strategy: 'most_recent';
|
|
19908
|
+
} | {
|
|
19909
|
+
strategy: 'highest_confidence';
|
|
19910
|
+
} | {
|
|
19911
|
+
strategy: 'highest_score';
|
|
19912
|
+
} | {
|
|
19913
|
+
strategy: 'trusted_agent';
|
|
19914
|
+
trustedAgentId: string;
|
|
19915
|
+
};
|
|
19916
|
+
/**
|
|
19917
|
+
* Result of a collaborative synthesis operation.
|
|
19918
|
+
*/
|
|
19919
|
+
interface SynthesisResult {
|
|
19920
|
+
/** Name of the seed entity used as the traversal start point */
|
|
19287
19921
|
seedEntity: string;
|
|
19288
19922
|
/** Neighbor entities that passed the salience filter, sorted by score descending */
|
|
19289
19923
|
neighbors: ScoredEntity[];
|
|
@@ -19293,6 +19927,12 @@ interface SynthesisResult {
|
|
|
19293
19927
|
traversedCount: number;
|
|
19294
19928
|
/** Number of entities filtered out due to low salience */
|
|
19295
19929
|
filteredCount: number;
|
|
19930
|
+
/**
|
|
19931
|
+
* Multi-agent conflicts detected among the neighbors (η.5.5.a). Each
|
|
19932
|
+
* entry describes a logical entity with competing versions from different
|
|
19933
|
+
* agents. Empty array when no conflicts exist (single-agent case).
|
|
19934
|
+
*/
|
|
19935
|
+
conflicts: ConflictView[];
|
|
19296
19936
|
}
|
|
19297
19937
|
/**
|
|
19298
19938
|
* Collaboratively synthesises context from a seed entity's graph neighbourhood.
|
|
@@ -19326,6 +19966,39 @@ declare class CollaborativeSynthesis {
|
|
|
19326
19966
|
* @returns SynthesisResult with scored neighbors and synthesized observations
|
|
19327
19967
|
*/
|
|
19328
19968
|
synthesize(seedEntityName: string, context?: SalienceContext): Promise<SynthesisResult>;
|
|
19969
|
+
/**
|
|
19970
|
+
* Detect multi-agent conflicts among the synthesized neighbors (η.5.5.a).
|
|
19971
|
+
*
|
|
19972
|
+
* Two entities are *competing* when they share a logical identity
|
|
19973
|
+
* (same `rootEntityName`, falling back to `name` when no chain) but
|
|
19974
|
+
* carry distinct `agentId` values. A single-agent group of versions is
|
|
19975
|
+
* NOT a conflict — only divergence between agents counts.
|
|
19976
|
+
*
|
|
19977
|
+
* Candidates within a conflict are ranked by `score = (confidence ?? 0.5)
|
|
19978
|
+
* × salienceScore`, so a high-confidence finding from a noisy region of
|
|
19979
|
+
* the graph can still rank below a moderate-confidence finding in a
|
|
19980
|
+
* salient region.
|
|
19981
|
+
*
|
|
19982
|
+
* @internal
|
|
19983
|
+
*/
|
|
19984
|
+
private detectConflicts;
|
|
19985
|
+
/**
|
|
19986
|
+
* Pick a winner per `ConflictView` according to the supplied policy.
|
|
19987
|
+
* Returns a map keyed by `entityName` whose values are the winning
|
|
19988
|
+
* `AgentEntity`. Pure function — does not mutate the synthesis result
|
|
19989
|
+
* or persist anything to storage. Callers feed the winners back through
|
|
19990
|
+
* their write path of choice (e.g. `EntityManager.updateEntity`).
|
|
19991
|
+
*
|
|
19992
|
+
* @example
|
|
19993
|
+
* ```typescript
|
|
19994
|
+
* const result = await synth.synthesize('Alice');
|
|
19995
|
+
* const winners = synth.resolveConflicts(result, { strategy: 'most_recent' });
|
|
19996
|
+
* for (const [name, winner] of winners) {
|
|
19997
|
+
* await entityManager.updateEntity(name, { ...winner });
|
|
19998
|
+
* }
|
|
19999
|
+
* ```
|
|
20000
|
+
*/
|
|
20001
|
+
resolveConflicts(result: SynthesisResult, policy: ConflictResolutionPolicy): Map<string, AgentEntity>;
|
|
19329
20002
|
/**
|
|
19330
20003
|
* Group neighbors by entityType and produce summary observation lines.
|
|
19331
20004
|
*
|
|
@@ -20255,6 +20928,1192 @@ declare class SemanticForget {
|
|
|
20255
20928
|
private semanticFallback;
|
|
20256
20929
|
}
|
|
20257
20930
|
|
|
20931
|
+
interface ImportanceScorerConfig {
|
|
20932
|
+
domainKeywords?: Set<string>;
|
|
20933
|
+
lengthWeight?: number;
|
|
20934
|
+
keywordWeight?: number;
|
|
20935
|
+
overlapWeight?: number;
|
|
20936
|
+
}
|
|
20937
|
+
interface ScoreOptions {
|
|
20938
|
+
queryContext?: string;
|
|
20939
|
+
recentTurns?: string[];
|
|
20940
|
+
}
|
|
20941
|
+
declare class ImportanceScorer {
|
|
20942
|
+
private readonly domainKeywords;
|
|
20943
|
+
private readonly lengthWeight;
|
|
20944
|
+
private readonly keywordWeight;
|
|
20945
|
+
private readonly overlapWeight;
|
|
20946
|
+
constructor(config?: ImportanceScorerConfig);
|
|
20947
|
+
/**
|
|
20948
|
+
* Score new content at creation time.
|
|
20949
|
+
*
|
|
20950
|
+
* PRD MEM-02: "Auto-importance scoring evaluates: content length
|
|
20951
|
+
* (log-scaled), domain keyword presence, query token overlap with
|
|
20952
|
+
* recent turns" (PRD §8 line 409).
|
|
20953
|
+
*
|
|
20954
|
+
* Returns integer in [0, 10] (memoryjs scale). PRD's narrower [1.0, 3.0]
|
|
20955
|
+
* range is out of scope here; the Decay Extensions spec owns the mapping.
|
|
20956
|
+
*/
|
|
20957
|
+
score(content: string, options?: ScoreOptions): number;
|
|
20958
|
+
}
|
|
20959
|
+
|
|
20960
|
+
interface MemoryEngineConfig {
|
|
20961
|
+
jaccardThreshold?: number;
|
|
20962
|
+
prefixOverlapThreshold?: number;
|
|
20963
|
+
dedupScanWindow?: number;
|
|
20964
|
+
maxTurnsPerSession?: number;
|
|
20965
|
+
semanticDedupEnabled?: boolean;
|
|
20966
|
+
semanticThreshold?: number;
|
|
20967
|
+
recentTurnsForImportance?: number;
|
|
20968
|
+
}
|
|
20969
|
+
interface AddTurnOptions {
|
|
20970
|
+
sessionId: string;
|
|
20971
|
+
role: 'user' | 'assistant' | 'system';
|
|
20972
|
+
agentId?: string;
|
|
20973
|
+
projectId?: string;
|
|
20974
|
+
importance?: number;
|
|
20975
|
+
metadata?: Record<string, unknown>;
|
|
20976
|
+
queryContext?: string;
|
|
20977
|
+
recentTurns?: string[];
|
|
20978
|
+
}
|
|
20979
|
+
type DedupTier = 'exact' | 'prefix' | 'jaccard' | 'semantic';
|
|
20980
|
+
interface AddTurnResult {
|
|
20981
|
+
entity: AgentEntity;
|
|
20982
|
+
duplicateDetected: boolean;
|
|
20983
|
+
duplicateOf?: string;
|
|
20984
|
+
duplicateTier?: DedupTier;
|
|
20985
|
+
importanceScore: number;
|
|
20986
|
+
}
|
|
20987
|
+
interface DuplicateCheckResult {
|
|
20988
|
+
isDuplicate: boolean;
|
|
20989
|
+
match?: AgentEntity;
|
|
20990
|
+
tier?: DedupTier;
|
|
20991
|
+
}
|
|
20992
|
+
type MemoryEngineEventName = 'memoryEngine:turnAdded' | 'memoryEngine:duplicateDetected' | 'memoryEngine:sessionDeleted';
|
|
20993
|
+
/** Resolved configuration with all defaults applied. Used in T5–T10. */
|
|
20994
|
+
interface ResolvedConfig$1 {
|
|
20995
|
+
jaccardThreshold: number;
|
|
20996
|
+
prefixOverlapThreshold: number;
|
|
20997
|
+
dedupScanWindow: number;
|
|
20998
|
+
maxTurnsPerSession: number;
|
|
20999
|
+
semanticDedupEnabled: boolean;
|
|
21000
|
+
semanticThreshold: number;
|
|
21001
|
+
recentTurnsForImportance: number;
|
|
21002
|
+
}
|
|
21003
|
+
/** Injected dependencies bundle. Used in T5–T10. */
|
|
21004
|
+
interface Deps {
|
|
21005
|
+
storage: IGraphStorage;
|
|
21006
|
+
entityManager: EntityManager;
|
|
21007
|
+
episodicMemory: EpisodicMemoryManager;
|
|
21008
|
+
workingMemory: WorkingMemoryManager;
|
|
21009
|
+
importanceScorer: ImportanceScorer;
|
|
21010
|
+
semanticSearch: SemanticSearch | null | undefined;
|
|
21011
|
+
embeddingService: EmbeddingService | null | undefined;
|
|
21012
|
+
}
|
|
21013
|
+
declare class MemoryEngine {
|
|
21014
|
+
readonly events: EventEmitter$1<[never]>;
|
|
21015
|
+
/** Dependencies bundle — populated in constructor, consumed in T5–T10. */
|
|
21016
|
+
protected readonly deps: Deps;
|
|
21017
|
+
/** Resolved config — populated in constructor, consumed in T5–T10. */
|
|
21018
|
+
protected readonly cfg: ResolvedConfig$1;
|
|
21019
|
+
constructor(storage: IGraphStorage, entityManager: EntityManager, episodicMemory: EpisodicMemoryManager, workingMemory: WorkingMemoryManager, importanceScorer: ImportanceScorer, semanticSearch?: SemanticSearch | null, embeddingService?: EmbeddingService | null, config?: MemoryEngineConfig);
|
|
21020
|
+
addTurn(content: string, options: AddTurnOptions): Promise<AddTurnResult>;
|
|
21021
|
+
private loadRecentTurnsForImportance;
|
|
21022
|
+
getSessionTurns(sessionId: string, options?: {
|
|
21023
|
+
limit?: number;
|
|
21024
|
+
role?: 'user' | 'assistant' | 'system';
|
|
21025
|
+
}): Promise<AgentEntity[]>;
|
|
21026
|
+
checkDuplicate(content: string, sessionId: string): Promise<DuplicateCheckResult>;
|
|
21027
|
+
private checkTierSemantic;
|
|
21028
|
+
private computeContentHash;
|
|
21029
|
+
private checkTierExact;
|
|
21030
|
+
private getRecentSessionEntities;
|
|
21031
|
+
private checkTierPrefix;
|
|
21032
|
+
private checkTierJaccard;
|
|
21033
|
+
deleteSession(sessionId: string): Promise<{
|
|
21034
|
+
deleted: number;
|
|
21035
|
+
}>;
|
|
21036
|
+
listSessions(): Promise<string[]>;
|
|
21037
|
+
}
|
|
21038
|
+
|
|
21039
|
+
/**
|
|
21040
|
+
* Memory Backend Interface (`IMemoryBackend`)
|
|
21041
|
+
*
|
|
21042
|
+
* Phase β.1 of the v1.12.0 Memory Engine Decay Extensions plan
|
|
21043
|
+
* (`docs/superpowers/specs/2026-04-16-memory-engine-decay-extensions-design.md`).
|
|
21044
|
+
*
|
|
21045
|
+
* This is the interface only — adapters (`InMemoryBackend`, `SQLiteBackend`)
|
|
21046
|
+
* land in T12 / T13 and `DecayEngine.calculatePrdEffectiveImportance` in T15.
|
|
21047
|
+
*
|
|
21048
|
+
* Why a new interface vs. `IGraphStorage`:
|
|
21049
|
+
* - `IGraphStorage` is the durable graph-store contract (entities + relations
|
|
21050
|
+
* + indexes + transactions).
|
|
21051
|
+
* - `IMemoryBackend` is the agent-memory-flavored contract — turn-level
|
|
21052
|
+
* ingest, weighted retrieval (PRD `get_weighted`), session lifecycle.
|
|
21053
|
+
* Both can coexist; this is purely additive.
|
|
21054
|
+
*
|
|
21055
|
+
* Naming convention: `get_weighted` and `delete_session` use snake_case
|
|
21056
|
+
* deliberately to match the Context Engine PRD spec verbatim (PRD MEM-04).
|
|
21057
|
+
* This is the only place in the codebase that does so. The rest of the
|
|
21058
|
+
* codebase keeps camelCase.
|
|
21059
|
+
*
|
|
21060
|
+
* @module agent/MemoryBackend
|
|
21061
|
+
*/
|
|
21062
|
+
/**
|
|
21063
|
+
* The unit of conversation memory the backend round-trips. Distinct from
|
|
21064
|
+
* `AgentEntity`: this is a thinner shape designed to map cleanly to PRD
|
|
21065
|
+
* MEM-04 `add()` / `get_weighted()`. Adapters translate to/from
|
|
21066
|
+
* `AgentEntity` at the storage boundary.
|
|
21067
|
+
*/
|
|
21068
|
+
interface MemoryTurn {
|
|
21069
|
+
/**
|
|
21070
|
+
* Stable turn identifier.
|
|
21071
|
+
*
|
|
21072
|
+
* **Per-backend honoring:**
|
|
21073
|
+
* - `InMemoryBackend` — caller-supplied `id` is honored verbatim.
|
|
21074
|
+
* - `SQLiteBackend` — caller-supplied `id` is **silently overridden**
|
|
21075
|
+
* by an engine-generated entity name unless `preserveCallerIds: true`
|
|
21076
|
+
* is set on the backend (which currently throws, pending a future
|
|
21077
|
+
* `storage.renameEntity` primitive).
|
|
21078
|
+
*
|
|
21079
|
+
* Callers that need stable cross-backend IDs should not rely on this
|
|
21080
|
+
* field round-tripping unchanged today.
|
|
21081
|
+
*/
|
|
21082
|
+
id: string;
|
|
21083
|
+
/** Session this turn belongs to. Authoritative for routing + filtering. */
|
|
21084
|
+
sessionId: string;
|
|
21085
|
+
/** Raw turn content (no role prefix — adapters add `[role=...]` on write). */
|
|
21086
|
+
content: string;
|
|
21087
|
+
/** Speaker role. Determines role-prefix on storage. */
|
|
21088
|
+
role: 'user' | 'assistant' | 'system';
|
|
21089
|
+
/**
|
|
21090
|
+
* Importance score in PRD range [1.0, 3.0]. Adapters using the legacy
|
|
21091
|
+
* memoryjs scale [0, 10] convert at the boundary via
|
|
21092
|
+
* `DecayEngine.calculatePrdEffectiveImportance`.
|
|
21093
|
+
*/
|
|
21094
|
+
importance: number;
|
|
21095
|
+
/**
|
|
21096
|
+
* ISO-8601 creation timestamp.
|
|
21097
|
+
*
|
|
21098
|
+
* **Per-backend honoring:**
|
|
21099
|
+
* - `InMemoryBackend` — caller-supplied `createdAt` is honored verbatim.
|
|
21100
|
+
* - `SQLiteBackend` — caller-supplied `createdAt` is **silently
|
|
21101
|
+
* overridden** by `EpisodicMemoryManager.createEpisode`'s
|
|
21102
|
+
* `new Date().toISOString()`.
|
|
21103
|
+
*
|
|
21104
|
+
* Set by the engine on read.
|
|
21105
|
+
*/
|
|
21106
|
+
createdAt: string;
|
|
21107
|
+
/** ISO-8601 most-recent-access timestamp. Updated by `get_weighted`. */
|
|
21108
|
+
lastAccessedAt?: string;
|
|
21109
|
+
/** Total reads of this turn through `get_weighted`. */
|
|
21110
|
+
accessCount?: number;
|
|
21111
|
+
/** Optional dense embedding vector (semantic recall). */
|
|
21112
|
+
embedding?: number[];
|
|
21113
|
+
/**
|
|
21114
|
+
* Caller metadata round-tripped opaquely.
|
|
21115
|
+
*
|
|
21116
|
+
* **Per-backend honoring:**
|
|
21117
|
+
* - `InMemoryBackend` — full round-trip via the in-memory `MemoryTurn` map.
|
|
21118
|
+
* - `SQLiteBackend` — currently dropped on write; round-trip returns
|
|
21119
|
+
* `undefined`. Future enhancement could thread metadata through the
|
|
21120
|
+
* `agentMetadata` JSON-blob column shipped in T06b.
|
|
21121
|
+
*/
|
|
21122
|
+
metadata?: Record<string, unknown>;
|
|
21123
|
+
}
|
|
21124
|
+
/** Result row returned by `get_weighted`: a turn plus its decay-weighted score. */
|
|
21125
|
+
interface WeightedTurn {
|
|
21126
|
+
turn: MemoryTurn;
|
|
21127
|
+
/** PRD effective importance × recency × overlap. Higher = more relevant. */
|
|
21128
|
+
score: number;
|
|
21129
|
+
}
|
|
21130
|
+
/** Options for `get_weighted` retrieval. */
|
|
21131
|
+
interface GetWeightedOptions {
|
|
21132
|
+
/** Maximum rows to return. Default backend-defined (typically 10). */
|
|
21133
|
+
limit?: number;
|
|
21134
|
+
/**
|
|
21135
|
+
* Score floor — turns scoring below this are pruned from the result set.
|
|
21136
|
+
* Distinct from the legacy `MEMORY_DECAY_MIN_IMPORTANCE` (storage clamp);
|
|
21137
|
+
* this is a retrieval filter. Defaults to backend's
|
|
21138
|
+
* `min_importance_threshold` config.
|
|
21139
|
+
*/
|
|
21140
|
+
threshold?: number;
|
|
21141
|
+
}
|
|
21142
|
+
/**
|
|
21143
|
+
* The agent-memory-flavored backend contract. Adapters:
|
|
21144
|
+
* - `InMemoryBackend` — ephemeral `Map<sessionId, MemoryTurn[]>`, default.
|
|
21145
|
+
* - `SQLiteBackend` — wraps `SQLiteStorage` + `MemoryEngine` for persistence.
|
|
21146
|
+
* - (Phase γ) `PostgreSQLBackend`, `VectorMemoryBackend`.
|
|
21147
|
+
*
|
|
21148
|
+
* All methods are async to allow remote/streaming backends in the future.
|
|
21149
|
+
*/
|
|
21150
|
+
interface IMemoryBackend {
|
|
21151
|
+
/**
|
|
21152
|
+
* PRD MEM-04: persist a turn. `turn.sessionId` is authoritative — there
|
|
21153
|
+
* is no separate `sessionId` parameter. Idempotency is backend-defined:
|
|
21154
|
+
* `SQLiteBackend` runs the four-tier dedup chain by default; on a
|
|
21155
|
+
* duplicate hit, the call is a silent no-op (no event fires through
|
|
21156
|
+
* this interface — events live on `MemoryEngine.events`).
|
|
21157
|
+
*/
|
|
21158
|
+
add(turn: MemoryTurn): Promise<void>;
|
|
21159
|
+
/**
|
|
21160
|
+
* PRD MEM-04: return turns in weighted-by-decay order, scoped to the
|
|
21161
|
+
* given session. The score is `DecayEngine.calculatePrdEffectiveImportance`
|
|
21162
|
+
* combined with optional query-relevance signal (semantic backends use
|
|
21163
|
+
* embedding similarity; lexical backends use BM25 or token overlap).
|
|
21164
|
+
*
|
|
21165
|
+
* Note the snake_case method name preserved from the PRD.
|
|
21166
|
+
*/
|
|
21167
|
+
get_weighted(query: string, sessionId: string, options?: GetWeightedOptions): Promise<WeightedTurn[]>;
|
|
21168
|
+
/** Delete every turn in the session. Idempotent: missing session → no-op. */
|
|
21169
|
+
delete_session(sessionId: string): Promise<void>;
|
|
21170
|
+
/** Enumerate every distinct sessionId currently held by this backend. */
|
|
21171
|
+
list_sessions(): Promise<string[]>;
|
|
21172
|
+
}
|
|
21173
|
+
|
|
21174
|
+
/**
|
|
21175
|
+
* TrajectoryCompressor — Phase δ.2 (ROADMAP §3B.2).
|
|
21176
|
+
*
|
|
21177
|
+
* Reflection-stage service that distills verbose interaction histories
|
|
21178
|
+
* into compact, reusable representations. Wraps `ContextWindowManager.compressForContext`
|
|
21179
|
+
* for the `foldContext` method (per ADR-011 wrap-and-extend), and adds
|
|
21180
|
+
* four new methods natively:
|
|
21181
|
+
*
|
|
21182
|
+
* - `distill(observations, options)` — compress an observation sequence
|
|
21183
|
+
* into a `CompressedMemory` summary with key facts.
|
|
21184
|
+
* - `abstractAtLevel(memories, granularity)` — produce three coarseness
|
|
21185
|
+
* levels (`fine` / `medium` / `coarse`) from a set of entities.
|
|
21186
|
+
* - `foldContext(workingMemory, maxTokens)` — delegates to
|
|
21187
|
+
* `ContextWindowManager.compressForContext`.
|
|
21188
|
+
* - `findRedundancies(entities)` — identify groups of entities whose
|
|
21189
|
+
* observations are largely duplicates of each other.
|
|
21190
|
+
* - `mergeRedundant(group, strategy)` — collapse a redundancy group
|
|
21191
|
+
* into a single canonical entity per the chosen merge strategy.
|
|
21192
|
+
*
|
|
21193
|
+
* @module agent/TrajectoryCompressor
|
|
21194
|
+
*/
|
|
21195
|
+
|
|
21196
|
+
interface DistillOptions {
|
|
21197
|
+
/** Keep events in the order they arrived. Default true. */
|
|
21198
|
+
preserveTemporalOrder?: boolean;
|
|
21199
|
+
/** Hard cap on the produced summary length (chars). Default 2000. */
|
|
21200
|
+
maxLength?: number;
|
|
21201
|
+
/** Drop observations whose embedded importance signal is below this.
|
|
21202
|
+
* Currently uses a simple length-based heuristic (PatternDetector
|
|
21203
|
+
* doesn't expose a per-observation score). Default 0. */
|
|
21204
|
+
importanceThreshold?: number;
|
|
21205
|
+
/** Entity names whose observations should be preserved verbatim. */
|
|
21206
|
+
preserveEntities?: string[];
|
|
21207
|
+
}
|
|
21208
|
+
interface CompressedMemory {
|
|
21209
|
+
/** Plain-text rollup spanning the compressed observations. */
|
|
21210
|
+
summary: string;
|
|
21211
|
+
/** Bullet-style key facts extracted from the input. */
|
|
21212
|
+
keyFacts: string[];
|
|
21213
|
+
/** Number of input observations. */
|
|
21214
|
+
originalCount: number;
|
|
21215
|
+
/** Output-length / input-length ratio (0..1; lower = more compression). */
|
|
21216
|
+
compressionRatio: number;
|
|
21217
|
+
/** Observations explicitly retained (e.g., from `preserveEntities`). */
|
|
21218
|
+
preservedDetails: string[];
|
|
21219
|
+
/** Observations that were dropped from the summary. */
|
|
21220
|
+
discardedDetails: string[];
|
|
21221
|
+
}
|
|
21222
|
+
type Granularity = 'fine' | 'medium' | 'coarse';
|
|
21223
|
+
interface RedundancyGroup {
|
|
21224
|
+
/** All entities considered duplicates of each other. */
|
|
21225
|
+
entities: Entity[];
|
|
21226
|
+
/** Suggested canonical name for the merged result. */
|
|
21227
|
+
canonicalName: string;
|
|
21228
|
+
/** Average pairwise similarity within the group, 0..1. */
|
|
21229
|
+
avgSimilarity: number;
|
|
21230
|
+
}
|
|
21231
|
+
/** Named `TrajectoryMergeStrategy` to avoid collision with the existing
|
|
21232
|
+
* `MergeStrategy` re-exported under `src/features/`. */
|
|
21233
|
+
type TrajectoryMergeStrategy = 'keep-newest' | 'keep-most-confident' | 'union-observations';
|
|
21234
|
+
interface TrajectoryCompressorConfig {
|
|
21235
|
+
/** Min token-overlap ratio to call two entities redundant. Default 0.7. */
|
|
21236
|
+
redundancyThreshold?: number;
|
|
21237
|
+
}
|
|
21238
|
+
declare class TrajectoryCompressor {
|
|
21239
|
+
private readonly contextWindow;
|
|
21240
|
+
private readonly redundancyThreshold;
|
|
21241
|
+
constructor(contextWindow: ContextWindowManager, config?: TrajectoryCompressorConfig);
|
|
21242
|
+
/**
|
|
21243
|
+
* Compress an observation sequence into a CompressedMemory.
|
|
21244
|
+
* Strategy: keep observations whose tokens overlap heavily with the
|
|
21245
|
+
* majority (these are the "core" facts), drop low-overlap outliers.
|
|
21246
|
+
* Length-truncate the summary at `maxLength`. No LLM dependency yet —
|
|
21247
|
+
* pluggable later via a summarizer config option.
|
|
21248
|
+
*/
|
|
21249
|
+
distill(observations: string[], options?: DistillOptions): Promise<CompressedMemory>;
|
|
21250
|
+
/**
|
|
21251
|
+
* Produce a coarsened view of a set of entities at one of three
|
|
21252
|
+
* granularities. `fine` returns the entities unchanged; `medium`
|
|
21253
|
+
* trims observations to the top-3 most overlap-y per entity;
|
|
21254
|
+
* `coarse` distills each entity's observations into a single summary.
|
|
21255
|
+
*/
|
|
21256
|
+
abstractAtLevel(memories: Entity[], granularity: Granularity): Promise<Entity[]>;
|
|
21257
|
+
/**
|
|
21258
|
+
* Compress a working-memory text blob to fit within `maxTokens`.
|
|
21259
|
+
* Delegates to `ContextWindowManager.compressForContext` and chooses
|
|
21260
|
+
* the compression level based on how aggressively we need to shrink.
|
|
21261
|
+
* The `working` parameter is intentionally typed `string` here — the
|
|
21262
|
+
* spec talks about `WorkingMemory` but in practice the compressor
|
|
21263
|
+
* operates on serialized text.
|
|
21264
|
+
*/
|
|
21265
|
+
foldContext(working: string, maxTokens: number): Promise<string>;
|
|
21266
|
+
/**
|
|
21267
|
+
* Identify groups of entities whose observation sets are largely
|
|
21268
|
+
* duplicates. Pairs entities whose union-of-observations Jaccard
|
|
21269
|
+
* exceeds the configured threshold. O(n²) pairwise; suitable for
|
|
21270
|
+
* graphs up to ~1k entities — beyond that, a candidate-blocking
|
|
21271
|
+
* pass on tags/projectId would be the natural extension.
|
|
21272
|
+
*
|
|
21273
|
+
* Algorithmic caveat (greedy single-link): an entity is absorbed
|
|
21274
|
+
* into the FIRST seed it overlaps with above threshold; results
|
|
21275
|
+
* therefore depend on input ordering when an entity would qualify
|
|
21276
|
+
* for multiple seeds. For correctness-critical clustering, use
|
|
21277
|
+
* union-find or complete-link clustering instead.
|
|
21278
|
+
*/
|
|
21279
|
+
findRedundancies(entities: Entity[]): Promise<RedundancyGroup[]>;
|
|
21280
|
+
/**
|
|
21281
|
+
* Collapse a redundancy group into a single canonical entity per
|
|
21282
|
+
* strategy. Doesn't persist — caller is responsible for the actual
|
|
21283
|
+
* `EntityManager.deleteEntities(...)` + `createEntity(merged)` dance
|
|
21284
|
+
* if they want the change durable.
|
|
21285
|
+
*/
|
|
21286
|
+
mergeRedundant(group: RedundancyGroup, strategy: TrajectoryMergeStrategy): Promise<Entity>;
|
|
21287
|
+
}
|
|
21288
|
+
|
|
21289
|
+
/**
|
|
21290
|
+
* ExperienceExtractor — Phase δ.3 (ROADMAP §3B.3).
|
|
21291
|
+
*
|
|
21292
|
+
* Experience-stage service that abstracts universal patterns from
|
|
21293
|
+
* trajectory clusters, enabling zero-shot transfer to new scenarios.
|
|
21294
|
+
* Wraps `PatternDetector.detectPatterns` for the pattern-abstraction
|
|
21295
|
+
* method (per ADR-011 wrap-and-extend), and adds four new methods
|
|
21296
|
+
* natively:
|
|
21297
|
+
*
|
|
21298
|
+
* - `extractFromContrastivePairs(success, failure)` — derive `Rule`s
|
|
21299
|
+
* from differences between successful and failed trajectories.
|
|
21300
|
+
* - `abstractPattern(trajectories, similarityThreshold)` — delegates
|
|
21301
|
+
* to `PatternDetector.detectPatterns` over flattened observations.
|
|
21302
|
+
* - `learnDecisionBoundary(trajectories, outcomeField)` — separate
|
|
21303
|
+
* trajectories by outcome and surface the most distinguishing tokens.
|
|
21304
|
+
* - `clusterTrajectories(trajectories, method)` — group by structural,
|
|
21305
|
+
* semantic, or outcome similarity.
|
|
21306
|
+
* - `synthesizeExperience(cluster)` — produce a single transferable
|
|
21307
|
+
* `Experience` artifact from a cluster.
|
|
21308
|
+
*
|
|
21309
|
+
* @module agent/ExperienceExtractor
|
|
21310
|
+
*/
|
|
21311
|
+
|
|
21312
|
+
type Outcome = 'success' | 'failure' | 'partial' | 'unknown';
|
|
21313
|
+
interface Action {
|
|
21314
|
+
name: string;
|
|
21315
|
+
parameters?: Record<string, unknown>;
|
|
21316
|
+
result?: 'ok' | 'error';
|
|
21317
|
+
}
|
|
21318
|
+
interface Trajectory {
|
|
21319
|
+
id: string;
|
|
21320
|
+
sessionId: string;
|
|
21321
|
+
observations: string[];
|
|
21322
|
+
actions: Action[];
|
|
21323
|
+
outcome: Outcome;
|
|
21324
|
+
context: Record<string, unknown>;
|
|
21325
|
+
timestamp: string;
|
|
21326
|
+
}
|
|
21327
|
+
interface Rule {
|
|
21328
|
+
/** When this rule applies (textual condition). */
|
|
21329
|
+
condition: string;
|
|
21330
|
+
/** What to do when the condition holds. */
|
|
21331
|
+
action: string;
|
|
21332
|
+
confidence: number;
|
|
21333
|
+
/** Trajectories that support this rule. */
|
|
21334
|
+
supportCount: number;
|
|
21335
|
+
/** Trajectories that contradict this rule. */
|
|
21336
|
+
contraCount: number;
|
|
21337
|
+
}
|
|
21338
|
+
interface HeuristicGuideline {
|
|
21339
|
+
pattern: string;
|
|
21340
|
+
variables: string[];
|
|
21341
|
+
occurrences: number;
|
|
21342
|
+
/** Trajectory IDs that exhibited this pattern. */
|
|
21343
|
+
sourceTrajectoryIds: string[];
|
|
21344
|
+
}
|
|
21345
|
+
interface DecisionRule {
|
|
21346
|
+
/** Tokens whose presence indicates `outcomeIfPresent` outcome. */
|
|
21347
|
+
presenceTokens: string[];
|
|
21348
|
+
/** Tokens whose absence indicates `outcomeIfAbsent` outcome. */
|
|
21349
|
+
absenceTokens: string[];
|
|
21350
|
+
outcomeIfPresent: Outcome;
|
|
21351
|
+
outcomeIfAbsent: Outcome;
|
|
21352
|
+
confidence: number;
|
|
21353
|
+
}
|
|
21354
|
+
type ClusterMethod = 'semantic' | 'structural' | 'outcome';
|
|
21355
|
+
interface TrajectoryCluster {
|
|
21356
|
+
id: string;
|
|
21357
|
+
method: ClusterMethod;
|
|
21358
|
+
trajectories: Trajectory[];
|
|
21359
|
+
/** Average pairwise similarity within the cluster, 0..1. */
|
|
21360
|
+
cohesion: number;
|
|
21361
|
+
}
|
|
21362
|
+
type ExperienceType = 'heuristic' | 'procedure' | 'constraint' | 'preference';
|
|
21363
|
+
interface Experience {
|
|
21364
|
+
id: string;
|
|
21365
|
+
type: ExperienceType;
|
|
21366
|
+
content: string;
|
|
21367
|
+
/** Task types this applies to. */
|
|
21368
|
+
applicability: string[];
|
|
21369
|
+
confidence: number;
|
|
21370
|
+
/** Trajectory IDs that produced this experience. */
|
|
21371
|
+
sourceTrajectories: string[];
|
|
21372
|
+
createdAt: string;
|
|
21373
|
+
}
|
|
21374
|
+
interface ExperienceExtractorConfig {
|
|
21375
|
+
/** Default min-occurrence count for `abstractPattern`. Default 2. */
|
|
21376
|
+
minPatternOccurrences?: number;
|
|
21377
|
+
/** Default similarity threshold for clustering. Default 0.6. */
|
|
21378
|
+
similarityThreshold?: number;
|
|
21379
|
+
}
|
|
21380
|
+
declare class ExperienceExtractor {
|
|
21381
|
+
private readonly patternDetector;
|
|
21382
|
+
private readonly minPatternOccurrences;
|
|
21383
|
+
private readonly similarityThreshold;
|
|
21384
|
+
constructor(patternDetector: PatternDetector, config?: ExperienceExtractorConfig);
|
|
21385
|
+
/**
|
|
21386
|
+
* Derive rules from contrastive pairs. Strategy: tokens appearing
|
|
21387
|
+
* disproportionately in successes (vs. failures) become condition
|
|
21388
|
+
* antecedents; the next action after the distinguishing token
|
|
21389
|
+
* becomes the rule's recommended action.
|
|
21390
|
+
*
|
|
21391
|
+
* Lightweight — no embeddings or LLMs. Suitable for the "what does
|
|
21392
|
+
* the agent do differently when it succeeds" question at scale.
|
|
21393
|
+
*/
|
|
21394
|
+
extractFromContrastivePairs(success: Trajectory[], failure: Trajectory[]): Promise<Rule[]>;
|
|
21395
|
+
/**
|
|
21396
|
+
* Abstract a pattern across trajectories' observations. Delegates
|
|
21397
|
+
* to `PatternDetector.detectPatterns` and lifts the result onto
|
|
21398
|
+
* the spec's `HeuristicGuideline` shape with trajectory provenance.
|
|
21399
|
+
*
|
|
21400
|
+
* `similarityThreshold` is currently unused by the underlying
|
|
21401
|
+
* `detectPatterns` (it operates on token-template equality, not
|
|
21402
|
+
* similarity); kept in the signature for spec compliance and future
|
|
21403
|
+
* use when an embedding-based variant lands.
|
|
21404
|
+
*/
|
|
21405
|
+
abstractPattern(trajectories: Trajectory[], similarityThreshold: number): Promise<HeuristicGuideline>;
|
|
21406
|
+
/**
|
|
21407
|
+
* Learn the decision boundary for a binary outcome split. Currently
|
|
21408
|
+
* supports `outcome` field (success vs. failure); other field names
|
|
21409
|
+
* fall back to the `Outcome` lookup. Returns the most-distinguishing
|
|
21410
|
+
* tokens per side.
|
|
21411
|
+
*/
|
|
21412
|
+
learnDecisionBoundary(trajectories: Trajectory[], outcomeField: string): Promise<DecisionRule>;
|
|
21413
|
+
/**
|
|
21414
|
+
* Cluster trajectories by the chosen method. Lightweight: no
|
|
21415
|
+
* embeddings — `semantic` and `structural` both use token-Jaccard
|
|
21416
|
+
* with different normalization; `outcome` simply groups by the
|
|
21417
|
+
* `Outcome` value.
|
|
21418
|
+
*
|
|
21419
|
+
* Algorithmic caveat (greedy single-link for semantic/structural):
|
|
21420
|
+
* a trajectory is absorbed into the FIRST seed it overlaps with
|
|
21421
|
+
* above the configured similarity threshold, regardless of whether
|
|
21422
|
+
* a later seed would match more strongly. Results therefore depend
|
|
21423
|
+
* on input ordering, and "chain" clusters (A↔B, B↔C, but A↔C far
|
|
21424
|
+
* apart) can form under low thresholds. The `cohesion` field on
|
|
21425
|
+
* each `TrajectoryCluster` surfaces this — downstream
|
|
21426
|
+
* `synthesizeExperience` already passes cohesion through to
|
|
21427
|
+
* `Experience.confidence`. For higher-quality clustering, a
|
|
21428
|
+
* complete-link or union-find variant would be the natural
|
|
21429
|
+
* extension.
|
|
21430
|
+
*/
|
|
21431
|
+
clusterTrajectories(trajectories: Trajectory[], method: ClusterMethod): Promise<TrajectoryCluster[]>;
|
|
21432
|
+
/**
|
|
21433
|
+
* Synthesize a transferable `Experience` from a cluster. Picks the
|
|
21434
|
+
* `type` heuristically (procedure if cluster is action-heavy;
|
|
21435
|
+
* heuristic otherwise) and uses the most-common-pattern across the
|
|
21436
|
+
* cluster as the experience content.
|
|
21437
|
+
*/
|
|
21438
|
+
synthesizeExperience(cluster: TrajectoryCluster): Promise<Experience>;
|
|
21439
|
+
}
|
|
21440
|
+
|
|
21441
|
+
/**
|
|
21442
|
+
* Procedural Memory Types (3B.4)
|
|
21443
|
+
*
|
|
21444
|
+
* First-class type definitions for stored, executable procedures —
|
|
21445
|
+
* skills / how-to sequences distinct from semantic facts and episodic
|
|
21446
|
+
* events. Procedures are persisted as `entityType: 'procedure'` entities
|
|
21447
|
+
* with the step list encoded in `observations` as JSON.
|
|
21448
|
+
*
|
|
21449
|
+
* @module types/procedure
|
|
21450
|
+
*/
|
|
21451
|
+
/**
|
|
21452
|
+
* Atomic step in a procedure. Steps are ordered by `order` (1-indexed)
|
|
21453
|
+
* and may carry parameters consumed by the executor.
|
|
21454
|
+
*/
|
|
21455
|
+
interface ProcedureStep {
|
|
21456
|
+
/** 1-indexed step order. */
|
|
21457
|
+
order: number;
|
|
21458
|
+
/** Caller-meaningful action identifier (e.g. `"http.get"`, `"db.commit"`). */
|
|
21459
|
+
action: string;
|
|
21460
|
+
/** Parameter map; values are caller-defined strings. */
|
|
21461
|
+
parameters: Record<string, string>;
|
|
21462
|
+
/** Optional fallback step to run if `action` fails (recursive). */
|
|
21463
|
+
fallback?: ProcedureStep;
|
|
21464
|
+
/** Maximum step duration in ms. Caller-enforced. */
|
|
21465
|
+
timeout?: number;
|
|
21466
|
+
}
|
|
21467
|
+
/**
|
|
21468
|
+
* Full procedure record. Identified by `id` (caller-supplied or
|
|
21469
|
+
* auto-generated by `ProcedureManager.addProcedure`).
|
|
21470
|
+
*/
|
|
21471
|
+
interface Procedure {
|
|
21472
|
+
/** Stable identifier — used as the underlying entity name. */
|
|
21473
|
+
id: string;
|
|
21474
|
+
/** Human-readable name. */
|
|
21475
|
+
name: string;
|
|
21476
|
+
/** What the procedure accomplishes. */
|
|
21477
|
+
description: string;
|
|
21478
|
+
/** Ordered step list. */
|
|
21479
|
+
steps: ProcedureStep[];
|
|
21480
|
+
/** Free-form trigger conditions (matched by `matchProcedure`). */
|
|
21481
|
+
triggers?: string[];
|
|
21482
|
+
/** Aggregate success rate in [0, 1], updated by `refineProcedure`. */
|
|
21483
|
+
successRate?: number;
|
|
21484
|
+
/** Number of executions recorded. */
|
|
21485
|
+
executionCount?: number;
|
|
21486
|
+
/** ISO 8601 timestamps. */
|
|
21487
|
+
createdAt?: string;
|
|
21488
|
+
lastModified?: string;
|
|
21489
|
+
}
|
|
21490
|
+
/** Result of a `matchProcedure` call. */
|
|
21491
|
+
interface ProcedureMatch {
|
|
21492
|
+
procedure: Procedure;
|
|
21493
|
+
/** Match quality in [0, 1] — overlap between context tokens and triggers. */
|
|
21494
|
+
score: number;
|
|
21495
|
+
}
|
|
21496
|
+
/** Caller feedback from a single execution, used by `refineProcedure`. */
|
|
21497
|
+
interface ProcedureFeedback {
|
|
21498
|
+
/** Whether the run succeeded. */
|
|
21499
|
+
succeeded: boolean;
|
|
21500
|
+
/** Optional notes / lesson appended to the procedure observations. */
|
|
21501
|
+
notes?: string;
|
|
21502
|
+
/** ISO 8601; defaults to current time. */
|
|
21503
|
+
recordedAt?: string;
|
|
21504
|
+
}
|
|
21505
|
+
|
|
21506
|
+
/**
|
|
21507
|
+
* Step Sequencer (3B.4)
|
|
21508
|
+
*
|
|
21509
|
+
* Stateful cursor for in-progress procedure execution. Tracks current
|
|
21510
|
+
* step, advances forward, and can branch into a step's `fallback` when
|
|
21511
|
+
* the executor signals failure. Pure value object — no IO, no side
|
|
21512
|
+
* effects.
|
|
21513
|
+
*
|
|
21514
|
+
* @module agent/procedural/StepSequencer
|
|
21515
|
+
*/
|
|
21516
|
+
|
|
21517
|
+
declare class StepSequencer {
|
|
21518
|
+
private readonly procedure;
|
|
21519
|
+
private cursor;
|
|
21520
|
+
/** When set, all `current()` / `next()` calls return this fallback chain
|
|
21521
|
+
* instead of the main steps until cleared. */
|
|
21522
|
+
private activeFallback;
|
|
21523
|
+
constructor(procedure: Procedure);
|
|
21524
|
+
/** Steps in 1-indexed order. Read-only. */
|
|
21525
|
+
get steps(): readonly ProcedureStep[];
|
|
21526
|
+
/** Index of the next step to execute (0-based). Public for tests. */
|
|
21527
|
+
get cursorIndex(): number;
|
|
21528
|
+
/** Whether all main-track steps have been consumed. Fallbacks may still run. */
|
|
21529
|
+
isComplete(): boolean;
|
|
21530
|
+
/** Return the step about to execute, or null if exhausted. */
|
|
21531
|
+
current(): ProcedureStep | null;
|
|
21532
|
+
/**
|
|
21533
|
+
* Advance the cursor and return the new current step (or null when
|
|
21534
|
+
* complete). Clears any active fallback — fallbacks are single-step
|
|
21535
|
+
* by design; deeper branching needs a nested fallback in the step's
|
|
21536
|
+
* `fallback.fallback`.
|
|
21537
|
+
*/
|
|
21538
|
+
next(): ProcedureStep | null;
|
|
21539
|
+
/**
|
|
21540
|
+
* Switch to the current step's `fallback` chain. The next `current()`
|
|
21541
|
+
* call will return the fallback's first step. Throws if the current
|
|
21542
|
+
* step has no fallback (caller should test before invoking).
|
|
21543
|
+
*/
|
|
21544
|
+
branchToFallback(): void;
|
|
21545
|
+
/** Reset the cursor and clear any fallback — start over. */
|
|
21546
|
+
reset(): void;
|
|
21547
|
+
}
|
|
21548
|
+
|
|
21549
|
+
/**
|
|
21550
|
+
* Procedure Manager (3B.4)
|
|
21551
|
+
*
|
|
21552
|
+
* Primary API for procedural memory. Composes `ProcedureStore` (persist /
|
|
21553
|
+
* load) and `StepSequencer` (in-memory execution cursor). Provides:
|
|
21554
|
+
*
|
|
21555
|
+
* - `addProcedure` — auto-generates an id when missing, persists.
|
|
21556
|
+
* - `getProcedure` — load by id.
|
|
21557
|
+
* - `executeStep` / `getNextStep` — stateless step access by order.
|
|
21558
|
+
* - `matchProcedure` — token-overlap match against `triggers` + name.
|
|
21559
|
+
* - `refineProcedure` — increment execution count + EWMA-update success rate.
|
|
21560
|
+
*
|
|
21561
|
+
* Stateful execution lives in `StepSequencer`; callers construct one via
|
|
21562
|
+
* `manager.openSequencer(procedureId)` for the duration of a run.
|
|
21563
|
+
*
|
|
21564
|
+
* @module agent/procedural/ProcedureManager
|
|
21565
|
+
*/
|
|
21566
|
+
|
|
21567
|
+
interface ProcedureManagerConfig {
|
|
21568
|
+
/** EWMA weight for new feedback in `refineProcedure` (default 0.2). */
|
|
21569
|
+
successRateAlpha?: number;
|
|
21570
|
+
}
|
|
21571
|
+
declare class ProcedureManager {
|
|
21572
|
+
private readonly store;
|
|
21573
|
+
private readonly successRateAlpha;
|
|
21574
|
+
constructor(entityManager: EntityManager, config?: ProcedureManagerConfig);
|
|
21575
|
+
/**
|
|
21576
|
+
* Persist a new procedure. Auto-generates `id` (and falls back to it
|
|
21577
|
+
* for `name`) when caller omits them. Throws if the id collides — the
|
|
21578
|
+
* caller should `getProcedure` first if upsert semantics are needed.
|
|
21579
|
+
*/
|
|
21580
|
+
addProcedure(input: Partial<Procedure>): Promise<Procedure>;
|
|
21581
|
+
/** Load by id, or null. */
|
|
21582
|
+
getProcedure(id: string): Promise<Procedure | null>;
|
|
21583
|
+
/**
|
|
21584
|
+
* Stateless lookup of a specific step by 1-indexed `stepOrder`. Returns
|
|
21585
|
+
* null when the procedure has no such step.
|
|
21586
|
+
*/
|
|
21587
|
+
getStep(procedureId: string, stepOrder: number): Promise<ProcedureStep | null>;
|
|
21588
|
+
/**
|
|
21589
|
+
* Look up the step that follows `currentOrder`. Returns null when at
|
|
21590
|
+
* the end of the procedure or the procedure does not exist.
|
|
21591
|
+
*/
|
|
21592
|
+
getNextStep(procedureId: string, currentOrder: number): Promise<ProcedureStep | null>;
|
|
21593
|
+
/**
|
|
21594
|
+
* Open a fresh `StepSequencer` for the named procedure. Returns null
|
|
21595
|
+
* when the procedure doesn't exist. Multiple sequencers per procedure
|
|
21596
|
+
* are independent — no shared cursor state.
|
|
21597
|
+
*/
|
|
21598
|
+
openSequencer(procedureId: string): Promise<StepSequencer | null>;
|
|
21599
|
+
/**
|
|
21600
|
+
* Token-overlap match: scores each procedure by Jaccard-like overlap
|
|
21601
|
+
* between the lowercased context tokens and the union of (`name`,
|
|
21602
|
+
* `triggers`). Returns matches in score order, descending. `threshold`
|
|
21603
|
+
* filters out matches below the cutoff (default 0.0 — return all).
|
|
21604
|
+
*/
|
|
21605
|
+
matchProcedure(contextDescription: string, candidates: Procedure[], threshold?: number): Promise<ProcedureMatch[]>;
|
|
21606
|
+
/**
|
|
21607
|
+
* Apply caller feedback: increment `executionCount` and update
|
|
21608
|
+
* `successRate` via EWMA. Persists the updated procedure. Returns
|
|
21609
|
+
* the updated record. Throws if procedure does not exist.
|
|
21610
|
+
*/
|
|
21611
|
+
refineProcedure(procedureId: string, feedback: ProcedureFeedback): Promise<Procedure>;
|
|
21612
|
+
}
|
|
21613
|
+
|
|
21614
|
+
/**
|
|
21615
|
+
* Causal Reasoner (3B.6)
|
|
21616
|
+
*
|
|
21617
|
+
* Symbolic forward / backward / counterfactual inference over causal
|
|
21618
|
+
* relations. Wraps `GraphTraversal.findAllPaths` filtered to causal
|
|
21619
|
+
* relation types and scores each path by the product of per-edge
|
|
21620
|
+
* `causalStrength` values.
|
|
21621
|
+
*
|
|
21622
|
+
* Out of scope (this module): probabilistic Bayes-net inference. That
|
|
21623
|
+
* would require a dedicated lib (e.g. jsbayes); deferred per the plan.
|
|
21624
|
+
*
|
|
21625
|
+
* @module agent/causal/CausalReasoner
|
|
21626
|
+
*/
|
|
21627
|
+
|
|
21628
|
+
/** Recognized causal relation types. Free-form `string` also accepted. */
|
|
21629
|
+
type CausalRelationType = 'causes' | 'enables' | 'prevents' | 'precedes' | 'correlates' | (string & {});
|
|
21630
|
+
/** Default set of relation types treated as causal. */
|
|
21631
|
+
declare const DEFAULT_CAUSAL_RELATION_TYPES: ReadonlyArray<CausalRelationType>;
|
|
21632
|
+
/** A single causal chain — sequence of entities + edges + composite score. */
|
|
21633
|
+
interface CausalChain {
|
|
21634
|
+
/** Ordered entity names from cause to effect. */
|
|
21635
|
+
path: string[];
|
|
21636
|
+
/** Edges traversed (parallel to `path` minus one). */
|
|
21637
|
+
relations: Relation[];
|
|
21638
|
+
/**
|
|
21639
|
+
* Composite score = product of per-edge `causalStrength` (defaults to 1
|
|
21640
|
+
* when an edge has no strength annotation). Range [0, 1] for normal
|
|
21641
|
+
* inputs; longer chains attenuate.
|
|
21642
|
+
*/
|
|
21643
|
+
score: number;
|
|
21644
|
+
/** Number of hops (= relations.length). */
|
|
21645
|
+
length: number;
|
|
21646
|
+
}
|
|
21647
|
+
/** A detected causal cycle (entity name appears more than once). */
|
|
21648
|
+
interface CausalCycle {
|
|
21649
|
+
/** Entity names making up the cycle, with the repeated entity at both ends. */
|
|
21650
|
+
cycle: string[];
|
|
21651
|
+
/** Edges in the cycle. */
|
|
21652
|
+
relations: Relation[];
|
|
21653
|
+
}
|
|
21654
|
+
interface CausalReasonerConfig {
|
|
21655
|
+
/** Relation types to treat as causal (default: DEFAULT_CAUSAL_RELATION_TYPES). */
|
|
21656
|
+
causalTypes?: ReadonlyArray<CausalRelationType>;
|
|
21657
|
+
/** Maximum path length for chain searches (default: 6). */
|
|
21658
|
+
maxDepth?: number;
|
|
21659
|
+
}
|
|
21660
|
+
declare class CausalReasoner {
|
|
21661
|
+
private readonly traversal;
|
|
21662
|
+
private readonly causalTypes;
|
|
21663
|
+
private readonly maxDepth;
|
|
21664
|
+
constructor(traversal: GraphTraversal, config?: CausalReasonerConfig);
|
|
21665
|
+
/**
|
|
21666
|
+
* Find all causal chains ending at `effectEntityName`. Searches for
|
|
21667
|
+
* paths from any node to `effectEntityName` along causal edges. In
|
|
21668
|
+
* practice we delegate to `findAllPaths` per candidate cause; for
|
|
21669
|
+
* unbounded discovery the caller should layer their own seed selection.
|
|
21670
|
+
*
|
|
21671
|
+
* Returns an empty array when no causal chain reaches the target. Each
|
|
21672
|
+
* chain's `score` is the product of `causalStrength` annotations on
|
|
21673
|
+
* its relations (defaults to 1 per edge when missing).
|
|
21674
|
+
*/
|
|
21675
|
+
findCauses(effectEntityName: string, candidateCauses: string[], maxDepth?: number): Promise<CausalChain[]>;
|
|
21676
|
+
/**
|
|
21677
|
+
* Find all causal chains starting at `causeEntityName` and reaching
|
|
21678
|
+
* any of `candidateEffects`. Symmetric counterpart to `findCauses`.
|
|
21679
|
+
*/
|
|
21680
|
+
findEffects(causeEntityName: string, candidateEffects: string[], maxDepth?: number): Promise<CausalChain[]>;
|
|
21681
|
+
/**
|
|
21682
|
+
* Counterfactual: "what changes if we remove edge `(removeFrom →
|
|
21683
|
+
* removeTo)` and ask whether `predict` is still reachable from
|
|
21684
|
+
* `seed`?" Returns chains from `seed` to `predict` that DO NOT use
|
|
21685
|
+
* the removed edge. Compare against the unfiltered `findEffects`
|
|
21686
|
+
* result to see which chains the removal kills.
|
|
21687
|
+
*
|
|
21688
|
+
* Pure: does not mutate the underlying graph or storage.
|
|
21689
|
+
*/
|
|
21690
|
+
counterfactual(scenario: {
|
|
21691
|
+
seed: string;
|
|
21692
|
+
removeFrom: string;
|
|
21693
|
+
removeTo: string;
|
|
21694
|
+
predict: string;
|
|
21695
|
+
maxDepth?: number;
|
|
21696
|
+
}): Promise<CausalChain[]>;
|
|
21697
|
+
/**
|
|
21698
|
+
* Detect cycles in the causal subgraph rooted at `seed`. Returns each
|
|
21699
|
+
* cycle as a list of entity names (with the repeating node at both
|
|
21700
|
+
* ends) plus the edges that close the loop.
|
|
21701
|
+
*
|
|
21702
|
+
* **Caveat**: treats `prevents` as a directed causal edge, NOT as a
|
|
21703
|
+
* negation. A `prevents`→`enables`→`prevents` triangle WILL show up
|
|
21704
|
+
* as a cycle. Document explicitly so callers don't misinterpret.
|
|
21705
|
+
*
|
|
21706
|
+
* Cycle detection here is a depth-bounded DFS rather than full Tarjan
|
|
21707
|
+
* SCC — sufficient for sparse causal graphs at hop counts ≤ 6, but
|
|
21708
|
+
* may double-report cycles that share edges. Filter by `cycle[0]`
|
|
21709
|
+
* sort-then-stringify if exact dedup is needed.
|
|
21710
|
+
*/
|
|
21711
|
+
detectCycles(seed: string, maxDepth?: number): CausalCycle[];
|
|
21712
|
+
}
|
|
21713
|
+
|
|
21714
|
+
/**
|
|
21715
|
+
* RBAC Types (η.6.1)
|
|
21716
|
+
*
|
|
21717
|
+
* Named roles with a reusable permission matrix, layered above the
|
|
21718
|
+
* five-tier visibility model (`VisibilityResolver`) and the policy hooks
|
|
21719
|
+
* on `GovernanceManager`. Role assignments are agent-scoped and optional
|
|
21720
|
+
* per resource type; the default matrix can be overridden per-grant.
|
|
21721
|
+
*
|
|
21722
|
+
* @module agent/rbac/RbacTypes
|
|
21723
|
+
*/
|
|
21724
|
+
/**
|
|
21725
|
+
* Built-in roles. Free-form strings are also accepted by
|
|
21726
|
+
* `RoleAssignmentStore` so callers can define domain-specific roles.
|
|
21727
|
+
*/
|
|
21728
|
+
type Role = 'reader' | 'writer' | 'admin' | 'owner' | (string & {});
|
|
21729
|
+
/** Operations that can be permission-checked. */
|
|
21730
|
+
type Permission = 'read' | 'write' | 'delete' | 'manage';
|
|
21731
|
+
/** Resource types that can be permission-checked. */
|
|
21732
|
+
type ResourceType = 'entity' | 'relation' | 'observation' | 'session' | 'artifact';
|
|
21733
|
+
/**
|
|
21734
|
+
* Single role grant for one agent. Optional `resourceType` narrows the
|
|
21735
|
+
* grant to only that type (omit to apply to all resource types).
|
|
21736
|
+
* Optional `scope` narrows by entity name or namespace prefix.
|
|
21737
|
+
*/
|
|
21738
|
+
interface RoleAssignment {
|
|
21739
|
+
/** ID of the agent this assignment applies to. */
|
|
21740
|
+
agentId: string;
|
|
21741
|
+
/** Granted role. */
|
|
21742
|
+
role: Role;
|
|
21743
|
+
/**
|
|
21744
|
+
* Resource type the role grants access to. When omitted, grant
|
|
21745
|
+
* applies across all resource types.
|
|
21746
|
+
*/
|
|
21747
|
+
resourceType?: ResourceType;
|
|
21748
|
+
/**
|
|
21749
|
+
* Optional scope. When set, the grant only applies if the resource's
|
|
21750
|
+
* name starts with this prefix (e.g. `'project-x:'` or just an exact
|
|
21751
|
+
* entity name). Empty / omitted ⇒ no scope restriction.
|
|
21752
|
+
*/
|
|
21753
|
+
scope?: string;
|
|
21754
|
+
/** ISO 8601 — when the assignment becomes active. Absent ⇒ active now. */
|
|
21755
|
+
validFrom?: string;
|
|
21756
|
+
/** ISO 8601 — when the assignment expires. Absent ⇒ no expiry. */
|
|
21757
|
+
validUntil?: string;
|
|
21758
|
+
/** Free-form notes (e.g. "granted by ticket #12345"). */
|
|
21759
|
+
notes?: string;
|
|
21760
|
+
}
|
|
21761
|
+
/**
|
|
21762
|
+
* RBAC policy contract. `RbacMiddleware` implements this; consumers can
|
|
21763
|
+
* also drop in their own policy if the default matrix is insufficient.
|
|
21764
|
+
*/
|
|
21765
|
+
interface RbacPolicy {
|
|
21766
|
+
/**
|
|
21767
|
+
* Decide whether `agentId` can perform `action` against `resourceType`
|
|
21768
|
+
* for the named resource. Returns `true` to grant access.
|
|
21769
|
+
*
|
|
21770
|
+
* Implementations should fail-safe: when a question can't be answered
|
|
21771
|
+
* (no assignment, missing config), return `false`.
|
|
21772
|
+
*/
|
|
21773
|
+
checkPermission(agentId: string, action: Permission, resourceType: ResourceType, resourceName?: string, now?: string): boolean;
|
|
21774
|
+
}
|
|
21775
|
+
|
|
21776
|
+
/**
|
|
21777
|
+
* Permission Matrix (η.6.1)
|
|
21778
|
+
*
|
|
21779
|
+
* Default permission grants per role. Tightens monotonically with the
|
|
21780
|
+
* role hierarchy: `reader` < `writer` < `admin` < `owner`. Consumers
|
|
21781
|
+
* can supply a fully-overridden matrix for domain-specific role models;
|
|
21782
|
+
* the defaults are designed to be safe out of the box.
|
|
21783
|
+
*
|
|
21784
|
+
* @module agent/rbac/PermissionMatrix
|
|
21785
|
+
*/
|
|
21786
|
+
|
|
21787
|
+
/** Permission set granted to a role per resource type. */
|
|
21788
|
+
type PermissionMatrixRow = ReadonlyArray<Permission>;
|
|
21789
|
+
/** Mapping from role to permissions. Keys are roles; values are sets. */
|
|
21790
|
+
type PermissionMatrix = ReadonlyMap<Role, PermissionMatrixRow>;
|
|
21791
|
+
/** Per-resource-type override layered on top of the base matrix. */
|
|
21792
|
+
type ResourcePermissionOverrides = ReadonlyMap<ResourceType, PermissionMatrix>;
|
|
21793
|
+
/**
|
|
21794
|
+
* Default permission grants. Owner has every permission; admin can
|
|
21795
|
+
* read/write/delete but not manage (manage = grant other agents the
|
|
21796
|
+
* same role); writer can read+write; reader is read-only.
|
|
21797
|
+
*/
|
|
21798
|
+
declare const DEFAULT_PERMISSION_MATRIX: PermissionMatrix;
|
|
21799
|
+
/**
|
|
21800
|
+
* Look up granted permissions for a role, applying any per-resource
|
|
21801
|
+
* overrides. Returns the empty set when the role is unknown — fail-safe
|
|
21802
|
+
* default for free-form caller-defined roles that have no matrix entry.
|
|
21803
|
+
*/
|
|
21804
|
+
declare function permissionsForRole(role: Role, resourceType: ResourceType, matrix?: PermissionMatrix, overrides?: ResourcePermissionOverrides): PermissionMatrixRow;
|
|
21805
|
+
|
|
21806
|
+
/**
|
|
21807
|
+
* Role Assignment Store (η.6.1)
|
|
21808
|
+
*
|
|
21809
|
+
* In-process registry of `RoleAssignment` records. Optional JSONL sidecar
|
|
21810
|
+
* persistence — when configured, every `assign`/`revoke` writes a single
|
|
21811
|
+
* line; on construction, replays the file to rebuild the in-memory state.
|
|
21812
|
+
*
|
|
21813
|
+
* @module agent/rbac/RoleAssignmentStore
|
|
21814
|
+
*/
|
|
21815
|
+
|
|
21816
|
+
interface RoleAssignmentStoreOptions {
|
|
21817
|
+
/** Path to a JSONL sidecar; absent ⇒ in-memory only. */
|
|
21818
|
+
persistencePath?: string;
|
|
21819
|
+
}
|
|
21820
|
+
declare class RoleAssignmentStore {
|
|
21821
|
+
private readonly assignments;
|
|
21822
|
+
private readonly persistencePath?;
|
|
21823
|
+
constructor(options?: RoleAssignmentStoreOptions);
|
|
21824
|
+
/**
|
|
21825
|
+
* Replay the JSONL persistence file (if configured) into the in-memory
|
|
21826
|
+
* map. Idempotent — safe to call multiple times. No-op when no path
|
|
21827
|
+
* is set or the file does not exist.
|
|
21828
|
+
*/
|
|
21829
|
+
hydrate(): Promise<void>;
|
|
21830
|
+
/**
|
|
21831
|
+
* Add an assignment. Multiple grants per agent are allowed (e.g. one
|
|
21832
|
+
* agent may be a `reader` for entities and a `writer` for relations).
|
|
21833
|
+
* Persists if configured.
|
|
21834
|
+
*/
|
|
21835
|
+
assign(assignment: RoleAssignment): Promise<void>;
|
|
21836
|
+
/**
|
|
21837
|
+
* Remove a specific assignment. Matching is by `agentId + role +
|
|
21838
|
+
* resourceType` (the resourceType match is exact, including undefined).
|
|
21839
|
+
*/
|
|
21840
|
+
revoke(agentId: string, role: Role, resourceType?: ResourceType): Promise<void>;
|
|
21841
|
+
/** All assignments for the given agent (active and inactive). */
|
|
21842
|
+
list(agentId: string): RoleAssignment[];
|
|
21843
|
+
/**
|
|
21844
|
+
* Active assignments for the given agent at the supplied time. Default
|
|
21845
|
+
* is current time. An assignment is active when `validFrom <= now <=
|
|
21846
|
+
* validUntil` (with absent bounds treated as unbounded).
|
|
21847
|
+
*/
|
|
21848
|
+
listActive(agentId: string, now?: string): RoleAssignment[];
|
|
21849
|
+
private applyAssign;
|
|
21850
|
+
private applyRevoke;
|
|
21851
|
+
private persist;
|
|
21852
|
+
}
|
|
21853
|
+
|
|
21854
|
+
/**
|
|
21855
|
+
* RBAC Middleware (η.6.1)
|
|
21856
|
+
*
|
|
21857
|
+
* `RbacPolicy` implementation that consults `RoleAssignmentStore` for the
|
|
21858
|
+
* requesting agent's active assignments, then applies `PermissionMatrix`
|
|
21859
|
+
* to decide grant/deny. Falls back to deny when no assignment matches.
|
|
21860
|
+
*
|
|
21861
|
+
* Designed to plug into `GovernanceManager.GovernancePolicy` so that
|
|
21862
|
+
* `canCreate`/`canUpdate`/`canDelete` are populated from RBAC by default.
|
|
21863
|
+
*
|
|
21864
|
+
* @module agent/rbac/RbacMiddleware
|
|
21865
|
+
*/
|
|
21866
|
+
|
|
21867
|
+
interface RbacMiddlewareOptions {
|
|
21868
|
+
/** Custom matrix; defaults to `DEFAULT_PERMISSION_MATRIX`. */
|
|
21869
|
+
matrix?: PermissionMatrix;
|
|
21870
|
+
/** Per-resource-type overrides layered on top of `matrix`. */
|
|
21871
|
+
overrides?: ResourcePermissionOverrides;
|
|
21872
|
+
/**
|
|
21873
|
+
* Default role granted to agents with NO assignments. Defaults to
|
|
21874
|
+
* `'reader'` (read-only) — matches the
|
|
21875
|
+
* `MEMORY_RBAC_DEFAULT_ROLE` env var convention from CLAUDE.md.
|
|
21876
|
+
* Pass `undefined` to deny unregistered agents entirely.
|
|
21877
|
+
*/
|
|
21878
|
+
defaultRole?: string;
|
|
21879
|
+
}
|
|
21880
|
+
declare class RbacMiddleware implements RbacPolicy {
|
|
21881
|
+
private readonly store;
|
|
21882
|
+
private readonly matrix;
|
|
21883
|
+
private readonly overrides?;
|
|
21884
|
+
private readonly defaultRole;
|
|
21885
|
+
constructor(store: RoleAssignmentStore, options?: RbacMiddlewareOptions);
|
|
21886
|
+
checkPermission(agentId: string, action: Permission, resourceType: ResourceType, resourceName?: string, now?: string): boolean;
|
|
21887
|
+
private matchesResource;
|
|
21888
|
+
}
|
|
21889
|
+
|
|
21890
|
+
/**
|
|
21891
|
+
* World State Snapshot (3B.7)
|
|
21892
|
+
*
|
|
21893
|
+
* Lightweight, immutable value object representing the agent's view of
|
|
21894
|
+
* its world at a single instant. Stored as a JSON-friendly shape so it
|
|
21895
|
+
* can roundtrip through any of the memoryjs storage backends.
|
|
21896
|
+
*
|
|
21897
|
+
* @module agent/world/WorldStateSnapshot
|
|
21898
|
+
*/
|
|
21899
|
+
/** Snapshot of one entity's state — only the fields that drive change detection. */
|
|
21900
|
+
interface WorldStateEntity {
|
|
21901
|
+
name: string;
|
|
21902
|
+
entityType: string;
|
|
21903
|
+
/** Importance score [0, 10]. */
|
|
21904
|
+
importance?: number;
|
|
21905
|
+
/** Confidence [0, 1]. */
|
|
21906
|
+
confidence?: number;
|
|
21907
|
+
/** Number of observations attached to this entity at snapshot time. */
|
|
21908
|
+
observationCount: number;
|
|
21909
|
+
/** Tags at snapshot time. */
|
|
21910
|
+
tags: string[];
|
|
21911
|
+
/** Last-modified timestamp. */
|
|
21912
|
+
lastModified?: string;
|
|
21913
|
+
}
|
|
21914
|
+
/** Diff between two snapshots. */
|
|
21915
|
+
interface WorldStateChange {
|
|
21916
|
+
/** Entities present only in the *before* snapshot. */
|
|
21917
|
+
removed: WorldStateEntity[];
|
|
21918
|
+
/** Entities present only in the *after* snapshot. */
|
|
21919
|
+
added: WorldStateEntity[];
|
|
21920
|
+
/** Entities present in both with at least one differing field. */
|
|
21921
|
+
modified: Array<{
|
|
21922
|
+
name: string;
|
|
21923
|
+
before: WorldStateEntity;
|
|
21924
|
+
after: WorldStateEntity;
|
|
21925
|
+
fields: ReadonlyArray<keyof WorldStateEntity>;
|
|
21926
|
+
}>;
|
|
21927
|
+
}
|
|
21928
|
+
declare class WorldStateSnapshot {
|
|
21929
|
+
/** ISO 8601 timestamp this snapshot was taken. */
|
|
21930
|
+
readonly takenAt: string;
|
|
21931
|
+
/** Map keyed by entity name. */
|
|
21932
|
+
readonly entitiesByName: ReadonlyMap<string, WorldStateEntity>;
|
|
21933
|
+
constructor(entities: ReadonlyArray<WorldStateEntity>, takenAt?: string);
|
|
21934
|
+
/** Number of entities in the snapshot. */
|
|
21935
|
+
get size(): number;
|
|
21936
|
+
/** All entities, in insertion order. */
|
|
21937
|
+
entities(): ReadonlyArray<WorldStateEntity>;
|
|
21938
|
+
/**
|
|
21939
|
+
* Pure: compute the diff to a `next` snapshot. Returns added /
|
|
21940
|
+
* removed / modified breakdown. An entity counts as "modified" when
|
|
21941
|
+
* any of `importance`, `confidence`, `observationCount`, `tags`, or
|
|
21942
|
+
* `lastModified` differs.
|
|
21943
|
+
*/
|
|
21944
|
+
diffTo(next: WorldStateSnapshot): WorldStateChange;
|
|
21945
|
+
/** JSON-serializable form. */
|
|
21946
|
+
toJSON(): {
|
|
21947
|
+
takenAt: string;
|
|
21948
|
+
entities: WorldStateEntity[];
|
|
21949
|
+
};
|
|
21950
|
+
/** Reconstruct from `toJSON()` output. */
|
|
21951
|
+
static fromJSON(json: {
|
|
21952
|
+
takenAt: string;
|
|
21953
|
+
entities: WorldStateEntity[];
|
|
21954
|
+
}): WorldStateSnapshot;
|
|
21955
|
+
}
|
|
21956
|
+
|
|
21957
|
+
/**
|
|
21958
|
+
* World Model Manager (3B.7)
|
|
21959
|
+
*
|
|
21960
|
+
* Orchestrator that composes existing services rather than implementing
|
|
21961
|
+
* new reasoning. Provides:
|
|
21962
|
+
*
|
|
21963
|
+
* - `getCurrentState()` — fresh `WorldStateSnapshot` from the live graph.
|
|
21964
|
+
* - `validateFact(observation, entityName)` — delegates to
|
|
21965
|
+
* `MemoryValidator.validateConsistency` when wired; deferred when not.
|
|
21966
|
+
* - `predictOutcome(action, candidates)` — delegates to
|
|
21967
|
+
* `CausalReasoner.findEffects` (needs `action` to be an entity name).
|
|
21968
|
+
* - `detectStateChange(before, after)` — pure snapshot diff.
|
|
21969
|
+
*
|
|
21970
|
+
* Designed to be wired through `ManagerContext` lazily; minimal
|
|
21971
|
+
* dependencies so it costs nothing when unused.
|
|
21972
|
+
*
|
|
21973
|
+
* @module agent/world/WorldModelManager
|
|
21974
|
+
*/
|
|
21975
|
+
|
|
21976
|
+
interface WorldModelManagerOptions {
|
|
21977
|
+
/**
|
|
21978
|
+
* Cap on snapshot size — keeps the snapshot small enough to roundtrip
|
|
21979
|
+
* through `worker_threads` or to persist as a single observation.
|
|
21980
|
+
* Default: 1000 entities.
|
|
21981
|
+
*/
|
|
21982
|
+
maxSnapshotSize?: number;
|
|
21983
|
+
}
|
|
21984
|
+
declare class WorldModelManager {
|
|
21985
|
+
private readonly entityManager;
|
|
21986
|
+
private readonly causalReasoner;
|
|
21987
|
+
private readonly memoryValidator;
|
|
21988
|
+
private readonly maxSnapshotSize;
|
|
21989
|
+
constructor(entityManager: EntityManager, causalReasoner: CausalReasoner | undefined, memoryValidator: MemoryValidator | undefined, options?: WorldModelManagerOptions);
|
|
21990
|
+
/**
|
|
21991
|
+
* Build a fresh snapshot from the live graph. Loads ALL entities (capped
|
|
21992
|
+
* at `maxSnapshotSize`) and reduces each to a `WorldStateEntity`. Pure
|
|
21993
|
+
* reads; safe to call concurrently.
|
|
21994
|
+
*
|
|
21995
|
+
* For graphs larger than the cap, entities are sorted by `importance`
|
|
21996
|
+
* descending and truncated — high-importance entities preferred.
|
|
21997
|
+
*/
|
|
21998
|
+
getCurrentState(): Promise<WorldStateSnapshot>;
|
|
21999
|
+
/**
|
|
22000
|
+
* Validate a candidate observation against the named entity's current
|
|
22001
|
+
* state. Delegates to `MemoryValidator.validateConsistency` when one
|
|
22002
|
+
* was wired at construction; returns a deferred result with a `null`
|
|
22003
|
+
* `issues` array when no validator is available — callers should treat
|
|
22004
|
+
* `valid: undefined` as "not checked" rather than "passed".
|
|
22005
|
+
*/
|
|
22006
|
+
validateFact(observation: string, entityName: string): Promise<MemoryValidationResult | null>;
|
|
22007
|
+
/**
|
|
22008
|
+
* Predict downstream effects of an action by walking the causal
|
|
22009
|
+
* subgraph from `actionEntity` to each candidate effect. Returns
|
|
22010
|
+
* empty when no causal reasoner was wired or no chain reaches any
|
|
22011
|
+
* candidate.
|
|
22012
|
+
*/
|
|
22013
|
+
predictOutcome(actionEntity: string, candidateEffects: string[]): Promise<CausalChain[]>;
|
|
22014
|
+
/**
|
|
22015
|
+
* Pure: diff two snapshots. Direct passthrough to
|
|
22016
|
+
* `WorldStateSnapshot.diffTo` — exposed here so callers can use the
|
|
22017
|
+
* world-model facade for both snapshotting and change detection.
|
|
22018
|
+
*/
|
|
22019
|
+
detectStateChange(before: WorldStateSnapshot, after: WorldStateSnapshot): WorldStateChange;
|
|
22020
|
+
}
|
|
22021
|
+
|
|
22022
|
+
/**
|
|
22023
|
+
* Active Retrieval Controller (3B.5)
|
|
22024
|
+
*
|
|
22025
|
+
* Decides *when* to retrieve, *what* to retrieve, and runs an iterative
|
|
22026
|
+
* query-rewriting loop that refines the query each round based on the
|
|
22027
|
+
* previous round's results. Wraps `RankedSearch` for the actual search
|
|
22028
|
+
* step and `QueryRewriter` for the expansion step.
|
|
22029
|
+
*
|
|
22030
|
+
* Out of scope (this module): LLM-driven query planning. The
|
|
22031
|
+
* `LLMQueryPlanner` already covers that path; `ActiveRetrievalController`
|
|
22032
|
+
* uses purely symbolic token-overlap expansion so it works without any
|
|
22033
|
+
* LLM provider.
|
|
22034
|
+
*
|
|
22035
|
+
* @module agent/retrieval/ActiveRetrievalController
|
|
22036
|
+
*/
|
|
22037
|
+
|
|
22038
|
+
/** Caller-supplied context for a retrieval decision. */
|
|
22039
|
+
interface RetrievalContext {
|
|
22040
|
+
/** Free-text query. */
|
|
22041
|
+
query: string;
|
|
22042
|
+
/** Optional task hint for `selectMemoryTypes`. */
|
|
22043
|
+
task?: string;
|
|
22044
|
+
/** Optional token budget cap. */
|
|
22045
|
+
budgetTokens?: number;
|
|
22046
|
+
}
|
|
22047
|
+
/** Output of `shouldRetrieve`. */
|
|
22048
|
+
interface RetrievalDecision {
|
|
22049
|
+
retrieve: boolean;
|
|
22050
|
+
/** Estimated cost in tokens (rough — proportional to query length). */
|
|
22051
|
+
estimatedCost: number;
|
|
22052
|
+
/** Free-text rationale. */
|
|
22053
|
+
reason: string;
|
|
22054
|
+
}
|
|
22055
|
+
/** Per-round trace for debugging / introspection. */
|
|
22056
|
+
interface RetrievalRound {
|
|
22057
|
+
query: string;
|
|
22058
|
+
results: SearchResult[];
|
|
22059
|
+
/** Coverage score in [0, 1] — average top-result score, capped. */
|
|
22060
|
+
coverage: number;
|
|
22061
|
+
/** Tokens added by `QueryRewriter`. Empty on the first round. */
|
|
22062
|
+
expansionTokens: string[];
|
|
22063
|
+
}
|
|
22064
|
+
/** Final result of `adaptiveRetrieve`. */
|
|
22065
|
+
interface AdaptiveResult {
|
|
22066
|
+
/** Highest-coverage round's results. */
|
|
22067
|
+
bestResults: SearchResult[];
|
|
22068
|
+
/** Coverage of `bestResults`. */
|
|
22069
|
+
bestCoverage: number;
|
|
22070
|
+
/** All rounds executed (for trace). */
|
|
22071
|
+
rounds: RetrievalRound[];
|
|
22072
|
+
}
|
|
22073
|
+
interface ActiveRetrievalConfig {
|
|
22074
|
+
/** Max retrieval rounds. Default 3. */
|
|
22075
|
+
maxRounds?: number;
|
|
22076
|
+
/** Coverage threshold; rounds stop early when reached. Default 0.6. */
|
|
22077
|
+
minCoverage?: number;
|
|
22078
|
+
/** Per-round result limit. Default 10. */
|
|
22079
|
+
resultsPerRound?: number;
|
|
22080
|
+
/** Cost-budget cutoff for `shouldRetrieve`. Default 1000 tokens. */
|
|
22081
|
+
costThreshold?: number;
|
|
22082
|
+
/** How many tokens to add per round via `QueryRewriter`. Default 3. */
|
|
22083
|
+
expansionLimit?: number;
|
|
22084
|
+
}
|
|
22085
|
+
declare class ActiveRetrievalController {
|
|
22086
|
+
private readonly rankedSearch;
|
|
22087
|
+
private readonly rewriter;
|
|
22088
|
+
private readonly maxRounds;
|
|
22089
|
+
private readonly minCoverage;
|
|
22090
|
+
private readonly resultsPerRound;
|
|
22091
|
+
private readonly costThreshold;
|
|
22092
|
+
private readonly expansionLimit;
|
|
22093
|
+
constructor(rankedSearch: RankedSearch, config?: ActiveRetrievalConfig);
|
|
22094
|
+
/**
|
|
22095
|
+
* Decide whether retrieval is worth the cost. Currently a simple
|
|
22096
|
+
* heuristic: tokens(query) × resultsPerRound × maxRounds × constant.
|
|
22097
|
+
* Returns `retrieve: false` when estimated cost > budget OR query is
|
|
22098
|
+
* empty.
|
|
22099
|
+
*/
|
|
22100
|
+
shouldRetrieve(context: RetrievalContext): RetrievalDecision;
|
|
22101
|
+
/**
|
|
22102
|
+
* Run up to `maxRounds` of (search → score coverage → rewrite). Stops
|
|
22103
|
+
* early when coverage hits `minCoverage` or no expansion tokens are
|
|
22104
|
+
* available. Returns the highest-coverage round's results plus the
|
|
22105
|
+
* full per-round trace.
|
|
22106
|
+
*/
|
|
22107
|
+
adaptiveRetrieve(context: RetrievalContext): Promise<AdaptiveResult>;
|
|
22108
|
+
/**
|
|
22109
|
+
* Quick coverage estimate: average of the top-3 results' scores,
|
|
22110
|
+
* clamped to [0, 1]. Empty results → 0. Score normalization assumes
|
|
22111
|
+
* `RankedSearch` returns BM25-ish positive numbers; we cap at 1.0 to
|
|
22112
|
+
* keep the threshold comparison meaningful.
|
|
22113
|
+
*/
|
|
22114
|
+
private estimateCoverage;
|
|
22115
|
+
}
|
|
22116
|
+
|
|
20258
22117
|
/**
|
|
20259
22118
|
* Options for constructing a ManagerContext.
|
|
20260
22119
|
*/
|
|
@@ -20296,6 +22155,18 @@ declare class ManagerContext {
|
|
|
20296
22155
|
private _factExtractor?;
|
|
20297
22156
|
private _transitionLedger?;
|
|
20298
22157
|
private _semanticSearch?;
|
|
22158
|
+
private _memoryEngine?;
|
|
22159
|
+
private _memoryBackend?;
|
|
22160
|
+
private _memoryValidator?;
|
|
22161
|
+
private _trajectoryCompressor?;
|
|
22162
|
+
private _experienceExtractor?;
|
|
22163
|
+
private _patternDetector?;
|
|
22164
|
+
private _procedureManager?;
|
|
22165
|
+
private _causalReasoner?;
|
|
22166
|
+
private _rbacMiddleware?;
|
|
22167
|
+
private _roleAssignmentStore?;
|
|
22168
|
+
private _worldModelManager?;
|
|
22169
|
+
private _activeRetrieval?;
|
|
20299
22170
|
private _accessTracker?;
|
|
20300
22171
|
private _decayEngine?;
|
|
20301
22172
|
private _decayScheduler?;
|
|
@@ -20355,6 +22226,92 @@ declare class ManagerContext {
|
|
|
20355
22226
|
* Returns null if no embedding provider is configured.
|
|
20356
22227
|
*/
|
|
20357
22228
|
get semanticSearch(): SemanticSearch | null;
|
|
22229
|
+
/**
|
|
22230
|
+
* MemoryEngine — turn-aware conversation memory facade composing over
|
|
22231
|
+
* EpisodicMemoryManager + WorkingMemoryManager + ImportanceScorer.
|
|
22232
|
+
* Lazy: instantiated on first access. Reads MEMORY_ENGINE_* env vars
|
|
22233
|
+
* for dedup thresholds, scan window, and scorer weights.
|
|
22234
|
+
*/
|
|
22235
|
+
get memoryEngine(): MemoryEngine;
|
|
22236
|
+
/**
|
|
22237
|
+
* IMemoryBackend (PRD MEM-04) — agent-memory-flavored backend.
|
|
22238
|
+
*
|
|
22239
|
+
* Selection by `MEMORY_BACKEND` env var:
|
|
22240
|
+
* - `sqlite` (default when storage is SQLite OR var unset on JSONL)
|
|
22241
|
+
* - `in-memory` (ephemeral; no persistence)
|
|
22242
|
+
* - future: `postgres`, `vector` (Phase γ)
|
|
22243
|
+
*
|
|
22244
|
+
* Both adapters wrap `ctx.memoryEngine` + `ctx.decayEngine` so they
|
|
22245
|
+
* inherit the four-tier dedup chain and PRD effective-importance
|
|
22246
|
+
* scoring respectively. Lazy-initialized; cached.
|
|
22247
|
+
*/
|
|
22248
|
+
get memoryBackend(): IMemoryBackend;
|
|
22249
|
+
/**
|
|
22250
|
+
* MemoryValidator (ROADMAP §3B.1, Phase δ.1) — reflection-stage
|
|
22251
|
+
* service that prevents hallucinations and logical errors from
|
|
22252
|
+
* contaminating memory through self-critique before storage.
|
|
22253
|
+
* Wraps `ContradictionDetector`. Lazy-initialized.
|
|
22254
|
+
*
|
|
22255
|
+
* Construction needs `ContradictionDetector(SemanticSearch, threshold)`.
|
|
22256
|
+
* If no semantic-search backend is configured, a no-op detector is
|
|
22257
|
+
* synthesized so MemoryValidator's other methods still work — the
|
|
22258
|
+
* detection method just returns no contradictions.
|
|
22259
|
+
*/
|
|
22260
|
+
get memoryValidator(): MemoryValidator;
|
|
22261
|
+
/**
|
|
22262
|
+
* TrajectoryCompressor (ROADMAP §3B.2, Phase δ.2) — reflection-stage
|
|
22263
|
+
* service that distills verbose interaction histories into compact,
|
|
22264
|
+
* reusable representations. Wraps `compressForContext`. Lazy.
|
|
22265
|
+
*/
|
|
22266
|
+
get trajectoryCompressor(): TrajectoryCompressor;
|
|
22267
|
+
/**
|
|
22268
|
+
* ExperienceExtractor (ROADMAP §3B.3, Phase δ.3) — experience-stage
|
|
22269
|
+
* service that abstracts universal patterns from trajectory clusters
|
|
22270
|
+
* for zero-shot transfer. Wraps `PatternDetector`. Lazy.
|
|
22271
|
+
*/
|
|
22272
|
+
get experienceExtractor(): ExperienceExtractor;
|
|
22273
|
+
/** Lazy `PatternDetector` instance — backs `experienceExtractor`
|
|
22274
|
+
* but also exposed directly for callers that want pattern detection
|
|
22275
|
+
* without the full Experience-stage wrapper. */
|
|
22276
|
+
get patternDetector(): PatternDetector;
|
|
22277
|
+
/**
|
|
22278
|
+
* `ProcedureManager` (3B.4) — first-class executable procedures.
|
|
22279
|
+
* Lazy. Composes `EntityManager` (persists procedures as
|
|
22280
|
+
* `entityType: 'procedure'`).
|
|
22281
|
+
*/
|
|
22282
|
+
get procedureManager(): ProcedureManager;
|
|
22283
|
+
/**
|
|
22284
|
+
* `CausalReasoner` (3B.6) — symbolic forward / backward / counter-
|
|
22285
|
+
* factual inference over the causal subgraph. Wraps `GraphTraversal`.
|
|
22286
|
+
* Lazy.
|
|
22287
|
+
*/
|
|
22288
|
+
get causalReasoner(): CausalReasoner;
|
|
22289
|
+
/**
|
|
22290
|
+
* `RoleAssignmentStore` (η.6.1) — registry of role grants per agent.
|
|
22291
|
+
* Lazy. In-memory only by default; configure persistence via the
|
|
22292
|
+
* direct constructor if a JSONL sidecar is wanted.
|
|
22293
|
+
*/
|
|
22294
|
+
get roleAssignmentStore(): RoleAssignmentStore;
|
|
22295
|
+
/**
|
|
22296
|
+
* `RbacMiddleware` (η.6.1) — `RbacPolicy` impl. Backed by the lazy
|
|
22297
|
+
* `roleAssignmentStore`. Lazy.
|
|
22298
|
+
*/
|
|
22299
|
+
get rbacMiddleware(): RbacMiddleware;
|
|
22300
|
+
/**
|
|
22301
|
+
* `WorldModelManager` (3B.7) — orchestrator that composes
|
|
22302
|
+
* `causalReasoner`, `memoryValidator`, and `entityManager` into a
|
|
22303
|
+
* single facade for `getCurrentState` / `validateFact` /
|
|
22304
|
+
* `predictOutcome` / `detectStateChange`. Lazy. Causal and validator
|
|
22305
|
+
* dependencies are passed through; methods that need them gracefully
|
|
22306
|
+
* return null/empty when they're not configured.
|
|
22307
|
+
*/
|
|
22308
|
+
get worldModelManager(): WorldModelManager;
|
|
22309
|
+
/**
|
|
22310
|
+
* `ActiveRetrievalController` (3B.5) — adaptive query-rewriting loop
|
|
22311
|
+
* over `RankedSearch`. Lazy. Pure symbolic expansion (no LLM); for
|
|
22312
|
+
* LLM-driven decomposition use `ctx.llmQueryPlanner`.
|
|
22313
|
+
*/
|
|
22314
|
+
get activeRetrieval(): ActiveRetrievalController;
|
|
20358
22315
|
/**
|
|
20359
22316
|
* TransitionLedger - Append-only audit trail for state changes.
|
|
20360
22317
|
* Returns null if not enabled via MEMORY_TRANSITION_LEDGER env var.
|
|
@@ -20378,6 +22335,9 @@ declare class ManagerContext {
|
|
|
20378
22335
|
* DecayEngine - Memory importance decay calculations.
|
|
20379
22336
|
*/
|
|
20380
22337
|
get decayEngine(): DecayEngine;
|
|
22338
|
+
/** Returns env-var as number, or undefined when unset (lets the
|
|
22339
|
+
* default-derive logic in DecayEngine kick in for `decayRate`). */
|
|
22340
|
+
private envNumberOrUndefined;
|
|
20381
22341
|
/**
|
|
20382
22342
|
* DecayScheduler - Scheduled decay and forget operations.
|
|
20383
22343
|
* Returns undefined if auto-decay is not enabled (MEMORY_AUTO_DECAY).
|
|
@@ -20983,6 +22943,161 @@ declare class GovernanceManager {
|
|
|
20983
22943
|
rollback(auditEntryId: string): Promise<void>;
|
|
20984
22944
|
}
|
|
20985
22945
|
|
|
22946
|
+
/**
|
|
22947
|
+
* ObservableDataModel Adapter
|
|
22948
|
+
*
|
|
22949
|
+
* Projects a memoryjs knowledge graph into a `Record<string, JSONValue>`
|
|
22950
|
+
* shape that satisfies JSON-UI's `ObservableDataModel` interface contract,
|
|
22951
|
+
* for use as the external store backing a `DataProvider` in the Neural
|
|
22952
|
+
* Computer runtime's Path C integration.
|
|
22953
|
+
*
|
|
22954
|
+
* NC reads durable state from memoryjs through this adapter and renders
|
|
22955
|
+
* that state in JSON-UI's non-input components. The user never writes
|
|
22956
|
+
* durable state through `DataProvider.set` — writes flow through the NC
|
|
22957
|
+
* orchestrator as LLM-dispatched memoryjs transactions (see NC spec
|
|
22958
|
+
* "Ephemeral UI State"). The adapter is therefore **read-only** at the
|
|
22959
|
+
* JSON-UI interface boundary: `set()` and `delete()` throw
|
|
22960
|
+
* `ReadOnlyMemoryGraphDataError`.
|
|
22961
|
+
*
|
|
22962
|
+
* @module features/ObservableDataModelAdapter
|
|
22963
|
+
*/
|
|
22964
|
+
|
|
22965
|
+
/**
|
|
22966
|
+
* A JSON round-trippable value. Matches `@json-ui/core`'s `JSONValue` shape
|
|
22967
|
+
* exactly; declared inline here to avoid a hard dependency on JSON-UI.
|
|
22968
|
+
*/
|
|
22969
|
+
type JSONValue = string | number | boolean | null | JSONValue[] | {
|
|
22970
|
+
[key: string]: JSONValue;
|
|
22971
|
+
};
|
|
22972
|
+
/**
|
|
22973
|
+
* Structural match for JSON-UI's `ObservableDataModel` interface from
|
|
22974
|
+
* `@json-ui/core`'s `runtime.ts`. Declared locally so the adapter does not
|
|
22975
|
+
* import `@json-ui/core` at runtime. Any consumer passing the adapter into
|
|
22976
|
+
* `<DataProvider store={adapter} />` gets structural type-compatibility
|
|
22977
|
+
* automatically — TypeScript's structural typing matches on method shapes.
|
|
22978
|
+
*/
|
|
22979
|
+
interface ObservableDataModelShape {
|
|
22980
|
+
get(path: string): JSONValue | undefined;
|
|
22981
|
+
set(path: string, value: JSONValue): void;
|
|
22982
|
+
delete(path: string): void;
|
|
22983
|
+
snapshot(): Readonly<Record<string, JSONValue>>;
|
|
22984
|
+
subscribe(callback: () => void): () => void;
|
|
22985
|
+
}
|
|
22986
|
+
/**
|
|
22987
|
+
* Thrown by the adapter's `set()` and `delete()` methods. Durable state
|
|
22988
|
+
* writes go through memoryjs's own transaction API (`ctx.governanceManager.
|
|
22989
|
+
* withTransaction`), not through `DataProvider`. The error message names the
|
|
22990
|
+
* alternative so callers know where to route the write.
|
|
22991
|
+
*/
|
|
22992
|
+
declare class ReadOnlyMemoryGraphDataError extends Error {
|
|
22993
|
+
readonly name = "ReadOnlyMemoryGraphDataError";
|
|
22994
|
+
constructor(operation: 'set' | 'delete', path: string);
|
|
22995
|
+
}
|
|
22996
|
+
/**
|
|
22997
|
+
* A projection function that maps a memoryjs graph state (entities +
|
|
22998
|
+
* relations) into a flat `Record<string, JSONValue>` view consumable by
|
|
22999
|
+
* JSON-UI's `DataProvider`.
|
|
23000
|
+
*
|
|
23001
|
+
* The projection is application-specific — memoryjs stores entities and
|
|
23002
|
+
* relations; what paths the UI needs are decided by the consumer. For
|
|
23003
|
+
* example, NC's simplest projection might be
|
|
23004
|
+
*
|
|
23005
|
+
* ```typescript
|
|
23006
|
+
* (entities) => ({
|
|
23007
|
+
* user: entities.find(e => e.entityType === "user") ?? null,
|
|
23008
|
+
* messageCount: entities.filter(e => e.entityType === "message").length,
|
|
23009
|
+
* })
|
|
23010
|
+
* ```
|
|
23011
|
+
*
|
|
23012
|
+
* Projections MUST return only `JSONValue`-compatible values — `Date`,
|
|
23013
|
+
* `Map`, class instances, functions, etc. will break `DataProvider`'s
|
|
23014
|
+
* `useSyncExternalStore` binding because React uses `Object.is` tearing
|
|
23015
|
+
* protection and any accidental non-plain-object inside the snapshot
|
|
23016
|
+
* will produce spurious re-renders or silent corruption.
|
|
23017
|
+
*
|
|
23018
|
+
* The projection is called at most once per mutation event — the adapter
|
|
23019
|
+
* caches the result and invalidates only when the graph changes. It is
|
|
23020
|
+
* NOT called on every `get()` or `snapshot()` call.
|
|
23021
|
+
*/
|
|
23022
|
+
type GraphProjection = (entities: ReadonlyArray<Entity>, relations: ReadonlyArray<Relation>) => Record<string, JSONValue>;
|
|
23023
|
+
/**
|
|
23024
|
+
* Options for `createObservableDataModelFromGraph`.
|
|
23025
|
+
*/
|
|
23026
|
+
interface ObservableDataModelAdapterOptions {
|
|
23027
|
+
/** Graph projection function. See `GraphProjection`. */
|
|
23028
|
+
projection: GraphProjection;
|
|
23029
|
+
/**
|
|
23030
|
+
* Logger for adapter-level errors (e.g., projection threw, listener
|
|
23031
|
+
* threw). Defaults to `console.error`. Pass a custom logger to route
|
|
23032
|
+
* errors into the host runtime's observability pipeline.
|
|
23033
|
+
*/
|
|
23034
|
+
onError?: (err: Error) => void;
|
|
23035
|
+
}
|
|
23036
|
+
/**
|
|
23037
|
+
* Create an `ObservableDataModel`-compatible adapter that reads its state
|
|
23038
|
+
* from a memoryjs `GraphStorage` via a caller-provided `GraphProjection`.
|
|
23039
|
+
*
|
|
23040
|
+
* The returned object satisfies the structural shape that JSON-UI's
|
|
23041
|
+
* `<DataProvider store={...} />` expects in external-store mode.
|
|
23042
|
+
*
|
|
23043
|
+
* **Async factory.** The factory awaits `storage.loadGraph()` once to warm
|
|
23044
|
+
* the storage cache, then returns a synchronous adapter. All subsequent
|
|
23045
|
+
* reads come from `storage.cachedGraph` (a sync accessor) — the adapter
|
|
23046
|
+
* does not block on I/O after construction.
|
|
23047
|
+
*
|
|
23048
|
+
* **Read-only.** `set()` and `delete()` throw `ReadOnlyMemoryGraphDataError`
|
|
23049
|
+
* because durable state in the Neural Computer architecture is owned by
|
|
23050
|
+
* memoryjs transactions, not by the React layer. Route writes through
|
|
23051
|
+
* `ctx.governanceManager.withTransaction` or the managers directly.
|
|
23052
|
+
*
|
|
23053
|
+
* **Event-driven invalidation.** The adapter subscribes to the storage's
|
|
23054
|
+
* `GraphEventEmitter` via `onAny` and invalidates its cached snapshot on
|
|
23055
|
+
* every mutation event. Because `GraphEventEmitter.emit` is synchronous
|
|
23056
|
+
* (a plain `for` loop over listeners), the adapter's subscribers fire
|
|
23057
|
+
* synchronously with the mutating call, matching JSON-UI's external-store
|
|
23058
|
+
* contract.
|
|
23059
|
+
*
|
|
23060
|
+
* **Transaction semantics.** `GovernanceManager.withTransaction` is NOT
|
|
23061
|
+
* atomic at the storage level — each `tx.createEntity` / `tx.updateEntity`
|
|
23062
|
+
* / `tx.deleteEntity` call inside the callback calls `storage.saveGraph`
|
|
23063
|
+
* directly, updates the cache synchronously, and emits a `graph:saved`
|
|
23064
|
+
* event. The adapter fires its React subscribers once per op, so a
|
|
23065
|
+
* 5-op transaction causes 5 invalidations + 5 re-renders. React's own
|
|
23066
|
+
* state batching collapses multiple synchronous setState calls in the
|
|
23067
|
+
* same tick, so the actual render count is usually lower. If a transaction
|
|
23068
|
+
* fails partway through, storage keeps the partial mutations (audit
|
|
23069
|
+
* entries are marked `rolled_back` but storage is untouched); the adapter
|
|
23070
|
+
* reflects the current storage state in either case. NC consumers that
|
|
23071
|
+
* need atomic-at-storage-level rollback should explicitly call
|
|
23072
|
+
* `governance.rollback(auditEntryId)` for each committed entry on error,
|
|
23073
|
+
* which also routes through `saveGraph` and fires another adapter
|
|
23074
|
+
* notification with the restored state.
|
|
23075
|
+
*
|
|
23076
|
+
* **Cleanup.** The adapter holds one event-emitter subscription for its
|
|
23077
|
+
* lifetime. Call `dispose()` on the returned object to release it when the
|
|
23078
|
+
* adapter is no longer needed (e.g., on app teardown).
|
|
23079
|
+
*
|
|
23080
|
+
* @example
|
|
23081
|
+
* ```typescript
|
|
23082
|
+
* import { ManagerContext, createObservableDataModelFromGraph } from '@danielsimonjr/memoryjs';
|
|
23083
|
+
*
|
|
23084
|
+
* const ctx = new ManagerContext('./memory.jsonl');
|
|
23085
|
+
*
|
|
23086
|
+
* const adapter = await createObservableDataModelFromGraph(ctx.storage, {
|
|
23087
|
+
* projection: (entities) => ({
|
|
23088
|
+
* user: entities.find((e) => e.entityType === 'user') ?? null,
|
|
23089
|
+
* messageCount: entities.filter((e) => e.entityType === 'message').length,
|
|
23090
|
+
* }),
|
|
23091
|
+
* });
|
|
23092
|
+
*
|
|
23093
|
+
* // In the React tree:
|
|
23094
|
+
* <DataProvider store={adapter}>{children}</DataProvider>
|
|
23095
|
+
* ```
|
|
23096
|
+
*/
|
|
23097
|
+
declare function createObservableDataModelFromGraph(storage: GraphStorage, options: ObservableDataModelAdapterOptions): Promise<ObservableDataModelShape & {
|
|
23098
|
+
dispose(): void;
|
|
23099
|
+
}>;
|
|
23100
|
+
|
|
20986
23101
|
/**
|
|
20987
23102
|
* Session Query Builder
|
|
20988
23103
|
*
|
|
@@ -21530,13 +23645,21 @@ declare class CognitiveLoadAnalyzer {
|
|
|
21530
23645
|
* private | team | org | shared | public
|
|
21531
23646
|
*
|
|
21532
23647
|
* Rules (evaluated in order; first match wins):
|
|
21533
|
-
*
|
|
23648
|
+
* 0. **Time-window gate (η.5.5.b)** — if `visibleFrom` is in the future
|
|
23649
|
+
* or `visibleUntil` is in the past, deny everyone (including owner).
|
|
23650
|
+
* 1. Owner always has access (subject to gate 0).
|
|
21534
23651
|
* 2. public → any agent (including unregistered / no metadata) has access.
|
|
21535
23652
|
* 3. shared → any registered agent has access.
|
|
21536
23653
|
* 4. org → agents that share the same org have access.
|
|
21537
23654
|
* 5. team → agents that share at least one team have access.
|
|
21538
23655
|
* 6. private → no other agent has access.
|
|
21539
23656
|
*
|
|
23657
|
+
* **Role gate (η.5.5.b)** — when `allowedRoles` is set on the memory, an
|
|
23658
|
+
* additional AND check applies AFTER any `true` result from rules 1-5
|
|
23659
|
+
* (except gate 0): the requesting agent's `role` must appear in the list.
|
|
23660
|
+
* Tightens, never widens. The owner is exempt (an agent should never lock
|
|
23661
|
+
* itself out of its own data).
|
|
23662
|
+
*
|
|
21540
23663
|
* @module agent/VisibilityResolver
|
|
21541
23664
|
*/
|
|
21542
23665
|
|
|
@@ -21557,9 +23680,294 @@ declare class VisibilityResolver {
|
|
|
21557
23680
|
* @param requestingAgentId - ID of the agent requesting access
|
|
21558
23681
|
* @param requestingMeta - Metadata for the requesting agent (undefined = unregistered)
|
|
21559
23682
|
* @param ownerMeta - Metadata for the owning agent (undefined = unknown owner)
|
|
23683
|
+
* @param now - Override for the current time (ISO 8601). Defaults
|
|
23684
|
+
* to `new Date().toISOString()`. Useful for tests
|
|
23685
|
+
* and for evaluating access at a hypothetical time.
|
|
21560
23686
|
* @returns True if access is permitted
|
|
21561
23687
|
*/
|
|
21562
|
-
canAccess(memory: AgentEntity, requestingAgentId: string, requestingMeta: AgentMetadata | undefined, ownerMeta: AgentMetadata | undefined): boolean;
|
|
23688
|
+
canAccess(memory: AgentEntity, requestingAgentId: string, requestingMeta: AgentMetadata | undefined, ownerMeta: AgentMetadata | undefined, now?: string): boolean;
|
|
23689
|
+
}
|
|
23690
|
+
|
|
23691
|
+
/**
|
|
23692
|
+
* `InMemoryBackend` — ephemeral, process-lifetime `IMemoryBackend` adapter.
|
|
23693
|
+
*
|
|
23694
|
+
* Phase β.2 of v1.12.0 Memory Engine Decay Extensions
|
|
23695
|
+
* (`docs/superpowers/specs/2026-04-16-memory-engine-decay-extensions-design.md`).
|
|
23696
|
+
*
|
|
23697
|
+
* Stores turns in an in-process `Map<sessionId, MemoryTurn[]>`. No
|
|
23698
|
+
* persistence. Suitable as the default backend when no SQLite/Postgres
|
|
23699
|
+
* configuration exists, and as the fast/clean fixture in unit tests.
|
|
23700
|
+
*
|
|
23701
|
+
* Scoring delegates to `DecayEngine.calculatePrdEffectiveImportance` so
|
|
23702
|
+
* `get_weighted` returns the same PRD-formula scores that
|
|
23703
|
+
* `SQLiteBackend` (T13) will produce.
|
|
23704
|
+
*
|
|
23705
|
+
* @module agent/InMemoryBackend
|
|
23706
|
+
*/
|
|
23707
|
+
|
|
23708
|
+
declare class InMemoryBackend implements IMemoryBackend {
|
|
23709
|
+
private readonly decayEngine;
|
|
23710
|
+
/** Per-session FIFO ordered list of turns. */
|
|
23711
|
+
private readonly turns;
|
|
23712
|
+
constructor(decayEngine: DecayEngine);
|
|
23713
|
+
add(turn: MemoryTurn): Promise<void>;
|
|
23714
|
+
get_weighted(query: string, sessionId: string, options?: GetWeightedOptions): Promise<WeightedTurn[]>;
|
|
23715
|
+
delete_session(sessionId: string): Promise<void>;
|
|
23716
|
+
list_sessions(): Promise<string[]>;
|
|
23717
|
+
}
|
|
23718
|
+
|
|
23719
|
+
/**
|
|
23720
|
+
* `SQLiteBackend` — durable `IMemoryBackend` adapter wrapping the
|
|
23721
|
+
* existing memoryjs `MemoryEngine` + `SQLiteStorage` + `DecayEngine`.
|
|
23722
|
+
*
|
|
23723
|
+
* Phase β.3 of v1.12.0 Memory Engine Decay Extensions
|
|
23724
|
+
* (`docs/superpowers/specs/2026-04-16-memory-engine-decay-extensions-design.md`).
|
|
23725
|
+
*
|
|
23726
|
+
* Design choices:
|
|
23727
|
+
* - **`dedupOnAdd=true` (default)** — `add()` delegates to
|
|
23728
|
+
* `MemoryEngine.addTurn`, inheriting the four-tier dedup chain
|
|
23729
|
+
* (exact / prefix / Jaccard / optional semantic) and event emission.
|
|
23730
|
+
* Idempotent on duplicate — silent no-op.
|
|
23731
|
+
* - **`dedupOnAdd=false`** — bypass dedup. `add()` writes directly via
|
|
23732
|
+
* `EntityManager.createEntities`. Intended for bulk import scenarios
|
|
23733
|
+
* where the caller has already de-duplicated upstream.
|
|
23734
|
+
* - **`preserveCallerIds=true`** — when set together with
|
|
23735
|
+
* `dedupOnAdd=true`, the engine-generated entity name is renamed to
|
|
23736
|
+
* the caller's `turn.id` after creation. Lossy translation
|
|
23737
|
+
* documented in the spec; default is `false` (engine-generated names
|
|
23738
|
+
* win, caller's IDs are silently overridden).
|
|
23739
|
+
* - **`get_weighted` reuses the v1.11.0 `MemoryEngine.getSessionTurns`**
|
|
23740
|
+
* for session-scoped retrieval, then scores via
|
|
23741
|
+
* `DecayEngine.calculatePrdEffectiveImportance` and applies the
|
|
23742
|
+
* threshold/limit filter. The four-tier-dedup-aware `addTurn` and
|
|
23743
|
+
* the sessionId-indexed retrieval together give us identical
|
|
23744
|
+
* observable behavior to `InMemoryBackend` for the contract suite.
|
|
23745
|
+
*
|
|
23746
|
+
* @module agent/SQLiteBackend
|
|
23747
|
+
*/
|
|
23748
|
+
|
|
23749
|
+
interface SQLiteBackendOptions {
|
|
23750
|
+
/** When true (default), `add()` runs the dedup chain via
|
|
23751
|
+
* `MemoryEngine.addTurn`. When false, writes bypass dedup. */
|
|
23752
|
+
dedupOnAdd?: boolean;
|
|
23753
|
+
/** When true, preserve caller's `turn.id` by renaming the
|
|
23754
|
+
* engine-generated entity name post-creation. Default false (lossy
|
|
23755
|
+
* translation: caller IDs are silently overridden). */
|
|
23756
|
+
preserveCallerIds?: boolean;
|
|
23757
|
+
}
|
|
23758
|
+
declare class SQLiteBackend implements IMemoryBackend {
|
|
23759
|
+
private readonly memoryEngine;
|
|
23760
|
+
private readonly decayEngine;
|
|
23761
|
+
private readonly options;
|
|
23762
|
+
constructor(memoryEngine: MemoryEngine, decayEngine: DecayEngine, options?: SQLiteBackendOptions);
|
|
23763
|
+
add(turn: MemoryTurn): Promise<void>;
|
|
23764
|
+
get_weighted(query: string, sessionId: string, options?: GetWeightedOptions): Promise<WeightedTurn[]>;
|
|
23765
|
+
delete_session(sessionId: string): Promise<void>;
|
|
23766
|
+
list_sessions(): Promise<string[]>;
|
|
23767
|
+
}
|
|
23768
|
+
|
|
23769
|
+
/**
|
|
23770
|
+
* Collaboration Audit Enforcer (η.5.5.d)
|
|
23771
|
+
*
|
|
23772
|
+
* Thin proxy over `EntityManager` that forces every mutation to carry an
|
|
23773
|
+
* `agentId` and appends an `AuditLog` entry on success. Distinct from
|
|
23774
|
+
* `GovernanceManager`: this enforces *attribution only* — never blocks
|
|
23775
|
+
* writes on policy grounds.
|
|
23776
|
+
*
|
|
23777
|
+
* Use when you want a guarantee that the audit trail is never anonymous,
|
|
23778
|
+
* e.g. multi-agent / multi-user setups where "who did this?" must always
|
|
23779
|
+
* be answerable.
|
|
23780
|
+
*
|
|
23781
|
+
* @module agent/collaboration/CollaborationAuditEnforcer
|
|
23782
|
+
*/
|
|
23783
|
+
|
|
23784
|
+
/**
|
|
23785
|
+
* Mode controls whether missing agentId is rejected or auto-substituted.
|
|
23786
|
+
*
|
|
23787
|
+
* - `strict` — throw `AttributionRequiredError` on any mutation without `agentId`.
|
|
23788
|
+
* - `lenient` — accept calls without agentId (audit entries omit the field).
|
|
23789
|
+
* Useful for back-compat wrapping around legacy callers.
|
|
23790
|
+
*/
|
|
23791
|
+
type AttributionMode = 'strict' | 'lenient';
|
|
23792
|
+
/** Constructor options. */
|
|
23793
|
+
interface CollaborationAuditEnforcerOptions {
|
|
23794
|
+
/**
|
|
23795
|
+
* `strict` (default) throws on missing agentId. Drive from
|
|
23796
|
+
* `MEMORY_AUDIT_ATTRIBUTION_REQUIRED` to flip behavior at construction
|
|
23797
|
+
* time.
|
|
23798
|
+
*/
|
|
23799
|
+
mode?: AttributionMode;
|
|
23800
|
+
}
|
|
23801
|
+
declare class CollaborationAuditEnforcer {
|
|
23802
|
+
private readonly entityManager;
|
|
23803
|
+
private readonly auditLog;
|
|
23804
|
+
private readonly mode;
|
|
23805
|
+
constructor(entityManager: EntityManager, auditLog: AuditLog, options?: CollaborationAuditEnforcerOptions);
|
|
23806
|
+
/**
|
|
23807
|
+
* Create entities and append a `create` audit entry per entity.
|
|
23808
|
+
* In strict mode, an empty/undefined `agentId` throws.
|
|
23809
|
+
*/
|
|
23810
|
+
createEntities(entities: Array<Omit<Entity, 'createdAt' | 'lastModified'>>, agentId: string | undefined): Promise<Entity[]>;
|
|
23811
|
+
/**
|
|
23812
|
+
* Update one entity and append an `update` audit entry capturing
|
|
23813
|
+
* before/after state. Forwards optional `expectedVersion` (η.5.5.c) to
|
|
23814
|
+
* the underlying `updateEntity` for OCC composition.
|
|
23815
|
+
*/
|
|
23816
|
+
updateEntity(name: string, updates: Partial<Entity>, agentId: string | undefined, options?: {
|
|
23817
|
+
expectedVersion?: number;
|
|
23818
|
+
}): Promise<Entity>;
|
|
23819
|
+
/**
|
|
23820
|
+
* Delete entities and append a `delete` audit entry per entity. Reads
|
|
23821
|
+
* the pre-delete snapshot for each to populate `before`.
|
|
23822
|
+
*/
|
|
23823
|
+
deleteEntities(names: string[], agentId: string | undefined): Promise<void>;
|
|
23824
|
+
private requireAttribution;
|
|
23825
|
+
}
|
|
23826
|
+
|
|
23827
|
+
/**
|
|
23828
|
+
* Query Rewriter (3B.5)
|
|
23829
|
+
*
|
|
23830
|
+
* Token-overlap query expansion. Given a base query and a set of result
|
|
23831
|
+
* snippets, extracts the highest-co-occurrence tokens from the snippets
|
|
23832
|
+
* (excluding the query's own tokens and a small stopword set) and emits
|
|
23833
|
+
* an expanded query that combines the original with the top expansion
|
|
23834
|
+
* candidates.
|
|
23835
|
+
*
|
|
23836
|
+
* Pure function — no LLM, no IO. Sufficient for retrieval refinement
|
|
23837
|
+
* loops where each round uses the previous round's results to seed the
|
|
23838
|
+
* next query.
|
|
23839
|
+
*
|
|
23840
|
+
* @module agent/retrieval/QueryRewriter
|
|
23841
|
+
*/
|
|
23842
|
+
interface RewriteResult {
|
|
23843
|
+
/** The expanded query string. */
|
|
23844
|
+
query: string;
|
|
23845
|
+
/** Tokens added to the original query. */
|
|
23846
|
+
expansionTokens: string[];
|
|
23847
|
+
}
|
|
23848
|
+
declare class QueryRewriter {
|
|
23849
|
+
/**
|
|
23850
|
+
* Expand `query` with the top-`expansionLimit` co-occurring tokens
|
|
23851
|
+
* from `snippets`. Tokens already present in the query (case-
|
|
23852
|
+
* insensitive) and stopwords are excluded.
|
|
23853
|
+
*/
|
|
23854
|
+
rewrite(query: string, snippets: ReadonlyArray<string>, expansionLimit?: number): RewriteResult;
|
|
23855
|
+
}
|
|
23856
|
+
|
|
23857
|
+
/**
|
|
23858
|
+
* Procedure Store (3B.4)
|
|
23859
|
+
*
|
|
23860
|
+
* Persists `Procedure` records as memoryjs entities (`entityType:
|
|
23861
|
+
* 'procedure'`). Steps + metadata live in `observations` as a single
|
|
23862
|
+
* JSON-encoded line; the rest of the entity carries triggers/successRate
|
|
23863
|
+
* via observations and tags. This shape lets procedures roundtrip
|
|
23864
|
+
* through both the JSONL and SQLite backends without schema changes.
|
|
23865
|
+
*
|
|
23866
|
+
* @module agent/procedural/ProcedureStore
|
|
23867
|
+
*/
|
|
23868
|
+
|
|
23869
|
+
declare const PROCEDURE_ENTITY_TYPE = "procedure";
|
|
23870
|
+
declare class ProcedureStore {
|
|
23871
|
+
private readonly entityManager;
|
|
23872
|
+
constructor(entityManager: EntityManager);
|
|
23873
|
+
/**
|
|
23874
|
+
* Persist a new procedure. The entity name = `procedure.id`. Steps and
|
|
23875
|
+
* metadata are encoded as JSON observations alongside any caller-supplied
|
|
23876
|
+
* description observation. Idempotent on duplicate id (relies on
|
|
23877
|
+
* `EntityManager.createEntities` semantics).
|
|
23878
|
+
*/
|
|
23879
|
+
save(procedure: Procedure): Promise<void>;
|
|
23880
|
+
/**
|
|
23881
|
+
* Load a procedure by id, or null if not found. Tolerant of partial
|
|
23882
|
+
* encodings — steps default to `[]`, meta to zeroed fields.
|
|
23883
|
+
*/
|
|
23884
|
+
load(id: string): Promise<Procedure | null>;
|
|
23885
|
+
/**
|
|
23886
|
+
* Replace an existing procedure's steps + metadata. Throws if the
|
|
23887
|
+
* entity doesn't exist or isn't a procedure.
|
|
23888
|
+
*/
|
|
23889
|
+
update(procedure: Procedure): Promise<void>;
|
|
23890
|
+
}
|
|
23891
|
+
/**
|
|
23892
|
+
* Pure decoder: extracts `Procedure` shape from the observation list.
|
|
23893
|
+
* Exported for tests and for callers wanting to introspect raw entities.
|
|
23894
|
+
*/
|
|
23895
|
+
declare function decodeProcedure(id: string, observations: string[]): Procedure;
|
|
23896
|
+
|
|
23897
|
+
/**
|
|
23898
|
+
* PII Redactor (η.6.3)
|
|
23899
|
+
*
|
|
23900
|
+
* Pluggable regex-based redactor for personally identifiable
|
|
23901
|
+
* information. Applied on export only — no storage mutation. Default
|
|
23902
|
+
* pattern bank covers the common five (email, phone, SSN, credit card,
|
|
23903
|
+
* IP address); callers can replace or extend the pattern list via
|
|
23904
|
+
* constructor options.
|
|
23905
|
+
*
|
|
23906
|
+
* Design rule: redactors REPLACE, never delete. Replacement preserves
|
|
23907
|
+
* length-class so downstream tooling (length checks, char counts) still
|
|
23908
|
+
* sees roughly the same shape — `<EMAIL>` for emails, `<SSN>` for SSNs,
|
|
23909
|
+
* etc. Caller can override per-pattern.
|
|
23910
|
+
*
|
|
23911
|
+
* @module security/PiiRedactor
|
|
23912
|
+
*/
|
|
23913
|
+
/** Single redaction rule. */
|
|
23914
|
+
interface PiiPattern {
|
|
23915
|
+
/** Stable name for diagnostics / metrics. */
|
|
23916
|
+
name: string;
|
|
23917
|
+
/** Regex matched against text. Use `/.../g` for multiple matches. */
|
|
23918
|
+
regex: RegExp;
|
|
23919
|
+
/** Replacement string. May reference capture groups via `$1` etc. */
|
|
23920
|
+
replacement: string;
|
|
23921
|
+
}
|
|
23922
|
+
/**
|
|
23923
|
+
* Default pattern bank. ASCII-only, conservative — false positives are
|
|
23924
|
+
* preferred over false negatives for PII. Callers exporting to a
|
|
23925
|
+
* regulated environment should layer additional patterns.
|
|
23926
|
+
*/
|
|
23927
|
+
declare const DEFAULT_PII_PATTERNS: ReadonlyArray<PiiPattern>;
|
|
23928
|
+
interface PiiRedactorOptions {
|
|
23929
|
+
/** Replace the default pattern bank entirely. */
|
|
23930
|
+
patterns?: ReadonlyArray<PiiPattern>;
|
|
23931
|
+
/** Append additional patterns to the default (or to `patterns` when set). */
|
|
23932
|
+
additionalPatterns?: ReadonlyArray<PiiPattern>;
|
|
23933
|
+
}
|
|
23934
|
+
/** Per-call redaction stats. */
|
|
23935
|
+
interface RedactionStats {
|
|
23936
|
+
/** Total bytes redacted across all patterns. */
|
|
23937
|
+
totalRedactedBytes: number;
|
|
23938
|
+
/** Per-pattern counts. */
|
|
23939
|
+
countsByPattern: Map<string, number>;
|
|
23940
|
+
}
|
|
23941
|
+
/** Result returned by `redactWithStats`. */
|
|
23942
|
+
interface RedactionResult {
|
|
23943
|
+
text: string;
|
|
23944
|
+
stats: RedactionStats;
|
|
23945
|
+
}
|
|
23946
|
+
declare class PiiRedactor {
|
|
23947
|
+
private readonly patterns;
|
|
23948
|
+
constructor(options?: PiiRedactorOptions);
|
|
23949
|
+
/**
|
|
23950
|
+
* Redact PII in `text`. Returns the cleaned string.
|
|
23951
|
+
* Patterns are applied in declaration order.
|
|
23952
|
+
*/
|
|
23953
|
+
redact(text: string): string;
|
|
23954
|
+
/**
|
|
23955
|
+
* Redact PII and return per-pattern statistics. Useful for compliance
|
|
23956
|
+
* audit trails — proves how many SSNs / emails / etc. were stripped
|
|
23957
|
+
* from an export without surfacing the actual values.
|
|
23958
|
+
*/
|
|
23959
|
+
redactWithStats(text: string): RedactionResult;
|
|
23960
|
+
/**
|
|
23961
|
+
* Redact every observation on every entity in a graph-shaped object.
|
|
23962
|
+
* Returns a shallow clone with redacted observations — does NOT touch
|
|
23963
|
+
* the input. Accepts both mutable `Entity[]` and `ReadonlyArray<Entity>`
|
|
23964
|
+
* shapes (e.g. `ReadonlyKnowledgeGraph` from `storage.loadGraph()`).
|
|
23965
|
+
*/
|
|
23966
|
+
redactGraph<T extends {
|
|
23967
|
+
entities: ReadonlyArray<{
|
|
23968
|
+
observations: ReadonlyArray<string>;
|
|
23969
|
+
}>;
|
|
23970
|
+
}>(graph: T): T;
|
|
21563
23971
|
}
|
|
21564
23972
|
|
|
21565
|
-
export { type AccessContext, AccessContextBuilder, type AccessPattern, type AccessStats, AccessTracker, type AccessTrackerConfig, type AdaptiveDepthConfig, type AdaptiveReductionResult, type AddObservationInput, AddObservationInputSchema, AddObservationsInputSchema, type AdequacyCheck, type AgentEntity, type AgentMemoryConfig, AgentMemoryManager, type AgentObservation, type AgentRole, AnalyticsManager, type ArchiveCriteria, type ArchiveCriteriaInput, ArchiveCriteriaSchema, ArchiveManager, type ArchiveOptions, type ArchiveResult, type ArchiveResultExtended, type ArtifactEntity, type ArtifactFilter, ArtifactManager, type ArtifactType, AsyncMutex, type AsyncMutexOptions, type AuditEntry, type AuditFilter, AuditLog, type AuditOperation, type AuditStats, type AutoLinkOptions, type AutoLinkResult, AutoLinker, type AutoSearchResult, type BM25Config, type BM25DocumentEntry, type BM25Index, BM25Search, type BackupInfo, type BackupInfoExtended, type BackupMetadata, type BackupMetadataExtended, type BackupOptions, type BackupResult, BasicSearch, BatchCreateEntitiesSchema, BatchCreateRelationsSchema, type BatchItemResult, type BatchOperation, type BatchOperationType, type BatchOptions, type BatchProcessResult, BatchProcessor, type BatchProcessorOptions, type BatchProgress, type BatchProgressCallback, type BatchResult, BatchTransaction, type BidirectionalRelation, type BooleanCacheEntry, type BooleanOpNode, type BooleanQueryNode, BooleanSearch, COMPRESSION_CONFIG, type CacheCompressionStats, type CacheStats, type CachedQueryEntry, type CentralityResult, CognitiveLoadAnalyzer, type CognitiveLoadConfig, type CognitiveLoadMetrics, CollaborativeSynthesis, type CollaborativeSynthesisConfig, type CommonSearchFilters, type ComponentMemoryUsage, CompositeDistillationPolicy, CompressedCache, type CompressedCacheOptions, type CompressedCacheStats, CompressionManager, type CompressionMetadata, type CompressionOptions, type CompressionQuality, type CompressionResult, type ConfirmationResult, type ConflictInfo, ConflictResolver, type ConflictResolverConfig, type ConflictStrategy, type ConnectedComponentsResult, type ConsolidateOptions, type ConsolidationAction, type ConsolidationCycleResult, ConsolidationPipeline, type ConsolidationPipelineConfig, type ConsolidationResult, type ConsolidationRule, ConsolidationScheduler, type ConsolidationSchedulerConfig, type ConsolidationTrigger, type ContextPackage, type ContextProfile, ContextProfileManager, type ContextRetrievalOptions, ContextWindowManager, type ContextWindowManagerConfig, type Contradiction, ContradictionDetector, type CreateArtifactOptions, type CreateEntityInput, CreateEntitySchema, type CreateEpisodeOptions, type CreateMemoryOptions, type CreateRelationInput, CreateRelationSchema, type CreateWorkThreadOptions, CycleDetectedError, DEFAULT_BASE_DIR, DEFAULT_BM25_CONFIG, DEFAULT_DUPLICATE_THRESHOLD, DEFAULT_EMBEDDING_CACHE_OPTIONS, DEFAULT_FILE_NAMES, DEFAULT_HYBRID_WEIGHTS, DEFAULT_INDEXER_OPTIONS, DEFAULT_SCORER_WEIGHTS, DOCUMENT_PREFIX, type DateRange, DateRangeSchema, type DecayCycleResult, DecayEngine, type DecayEngineConfig, type DecayOperationOptions, type DecayOptions, type DecayResult, DecayScheduler, type DecaySchedulerConfig, type DeduplicationOptions, DefaultDistillationPolicy, type DeleteObservationInput, DeleteObservationInputSchema, DeleteObservationsInputSchema, DeleteRelationsSchema, type DistillationConfig, DistillationPipeline, type DistillationResult, type DistillationStats, type DistilledLesson, type DistilledMemory, type DocumentVector, type DreamCycleResult, DreamEngine, type DreamEngineCallbacks, type DreamEngineConfig, type DreamPhaseConfig, type DreamPhaseResult, DuplicateEntityError, type DuplicatePair, ENV_VARS, EarlyTerminationManager, type EarlyTerminationOptions, type EarlyTerminationResult, EmbeddingCache, type EmbeddingCacheOptions, type EmbeddingCacheStats, type EmbeddingConfig, type EmbeddingMode, type EmbeddingProgressCallback, type EmbeddingService, type EndSessionResult, type Entity, type EntityCreatedEvent, type EntityDeletedEvent, type EntityInput, EntityManager, type EntityManagerOptions, EntityNamesSchema, EntityNotFoundError, type EntityRuleResult, EntitySchema, type EntityUpdatedEvent, type EntityValidationIssue, type EntityValidationResult, type EntityValidationRule, EntityValidator, type EntityValidatorConfig, type EntityWithContext, type EntropyFilterConfig, EntropyFilterStage, type EpisodicMemoryConfig, type EpisodicMemoryEntity, EpisodicMemoryManager, EpisodicRelations, ErrorCode, type ErrorOptions, type ExcludedEntity, type ExplainedSearchResult, ExportError, type ExportFilter, type ExportFilterInput, ExportFilterSchema, type ExportFormat, ExportFormatSchema, type ExportOptions, type ExportResult, type ExtendedExportFormatInput, ExtendedExportFormatSchema, type ExtendedPoolStats, type ExtendedQueryCostEstimate, type ExtractedEntity, type ExtractedFact, FILE_EXTENSIONS, FILE_SUFFIXES, type FactExtractionOptions, type FactExtractionResult, FactExtractor, FailureDistillation, type FailureDistillationConfig, type FailureDistillationResult, type FieldNode, FileOperationError, type FlushResult, type ForgetOptions, type ForgetResult, FreshnessManager, type FreshnessManagerConfig, type FreshnessReport, type FuzzyCacheKey, FuzzySearch, type FuzzySearchOptions, GRAPH_LIMITS, GovernanceManager, type GovernanceOperationOptions, type GovernancePolicy, GovernanceTransaction, type GraphCompressionResult, type GraphEvent, type GraphEventBase, GraphEventEmitter, type GraphEventListener, type GraphEventMap, type GraphEventType, type GraphLoadedEvent, type GraphSavedEvent, type GraphStats, GraphStorage, GraphTraversal, type GroupMembership, type GroupingResult, HierarchyManager, HybridScorer, type HybridScorerOptions, HybridSearchManager, type HybridSearchOptions, type HybridSearchResult, type HybridWeights, type IDistillationPolicy, type IGraphStorage, IMPORTANCE_RANGE, IOManager, type ISummarizationProvider, type IVectorStore, ImportError, type ImportFormat, type ImportFormatInput, ImportFormatSchema, type ImportResult, InMemoryVectorStore, IncrementalIndexer, type IncrementalIndexerOptions, type IndexMemoryUsage, type IndexOperation, type IndexOperationType, type IngestInput, type IngestOptions, type IngestResult, InsufficientEntitiesError, InvalidImportanceError, type JsonSchema, KeywordExtractor, type KnowledgeGraph, KnowledgeGraphError, ManagerContext as KnowledgeGraphManager, type LLMProvider, LLMQueryPlanner, type LLMQueryPlannerConfig, LLMSearchExecutor, type LLMSearchExecutorOptions, LOG_PREFIXES, type LayerRecommendationOptions, type LayerTiming, type LexicalSearchResult, LocalEmbeddingService, type LogLevel, type LongRunningOperationOptions, LowEntropyContentError, LowercaseCache, type LowercaseData, ManagerContext, type ManagerContextOptions, type MatchedTerm, type MemoryAcquisitionMethod, type MemoryAlert, type MemoryChangeCallback, MemoryFormatter, type MemoryFormatterConfig, type MemoryMergeStrategy, MemoryMonitor, type MemorySource, type MemoryThresholds, type MemoryType, type MemoryUsageStats, type MemoryVisibility, type MergeResult, type MergeStrategy, type MergeStrategyInput, MergeStrategySchema, MockEmbeddingService, type MultiAgentConfig, MultiAgentMemoryManager, NGramIndex, type NGramIndexStats, NameIndex, NoOpDistillationPolicy, type NormalizationOptions, type NormalizationResult, type ObservationAddedEvent, type ObservationDeletedEvent, ObservationManager, ObservationNormalizer, type ObservationScore, type ObservationSource, ObserverPipeline, type ObserverPipelineOptions, type ObserverPipelineStats, OpenAIEmbeddingService, OperationCancelledError, type OperationResult, OperationType, OptimizedInvertedIndex, OptionalEntityNamesSchema, OptionalTagsSchema, type PaginatedCacheEntry, ParallelSearchExecutor, type ParallelSearchOptions, type ParallelSearchResult, type ParsedTemporalRange, type PathResult, PatternDetector, type PatternResult, type PhaseDefinition, type PhraseNode, type PipelineStage, type PoolEventCallback, type PostingListResult, type PreparedEntity, type ProceduralMemoryEntity, type ProfileConfig, type ProfileEntity, ProfileManager, type ProfileManagerConfig, type ProfileOptions, type ProfileResponse, type ProgressCallback, type ProgressInfo, type ProgressInfoCallback, type ProgressOptions, type PromotionCriteria, type PromotionMarkOptions, type PromotionResult, type ProximityMatch, type ProximityMatchLocation, type ProximityNode, ProximitySearch, QUERY_LIMITS, QUERY_PREFIX, type QuantizationParams, type QuantizedSearchResult, QuantizedVectorStore, type QuantizedVectorStoreOptions, type QuantizedVectorStoreStats, type QueryAnalysis, QueryAnalyzer, type QueryCostEstimate, QueryCostEstimator, type QueryCostEstimatorOptions, type QueryLogEntry, QueryLogger, type QueryLoggerConfig, type QueryNode, QueryParser, type QueryPlan, QueryPlanCache, type QueryPlanCacheOptions, type QueryPlanCacheStats, QueryPlanner, type QueryStage, type QueryTrace, QueryTraceBuilder, type QueueStats, RankedSearch, type ReadonlyKnowledgeGraph, RefConflictError, type RefEntry, RefIndex, type RefIndexStats, RefNotFoundError, type RefinementHistoryEntry, ReflectionManager, type ReflectionOptions, type ReflectionResult, type ReinforcementOptions, type Relation, RelationBuilder, type RelationCreatedEvent, type RelationDeletedEvent, RelationIndex, type RelationInput, RelationManager, RelationNotFoundError, type RelationProperties, RelationSchema, type RelationValidationError, type RelationValidationResult, type RelationValidationWarning, type ResolutionResult, type RestoreResult, type RetrieveContextOptions, type RoleProfile, type RuleConditions, type RuleEvaluationResult, RuleEvaluator, SEARCH_LIMITS, SIMILARITY_WEIGHTS, SQLiteStorage, type SQLiteStorageWithEmbeddings, SQLiteVectorStore, STOPWORDS, STREAMING_CONFIG, type SalienceComponents, type SalienceContext, SalienceEngine, type SalienceEngineConfig, type SalienceWeights, type SavedSearch, type SavedSearchInput, SavedSearchInputSchema, SavedSearchManager, type SavedSearchUpdateInput, SavedSearchUpdateSchema, SchemaValidator, type ScoreBoost, type ScoredEntity, type ScoredKeyword, type ScoredResult, type ScoringSignal, SearchCache, type SearchExplanation, SearchFilterChain, type SearchFilters, type SearchFunction, type SearchLayer, SearchManager, type SearchMethod, type SearchQuery, SearchQuerySchema, type SearchResult, SearchSuggestions, SemanticForget, type SemanticForgetOptions, type SemanticForgetResult, type SemanticIndexOptions, type SemanticLayerResult, type SemanticMemoryEntity, SemanticSearch, type SemanticSearchResult, type SessionCheckpointData, SessionCheckpointManager, type SessionConfig, type SessionEntity, type SessionHistoryOptions, SessionManager, type SessionMemoryFilter, type SessionOutcome, SessionQueryBuilder, type SessionSearchOptions, type SessionStatus, type SpilloverResult, type SplitOptions, type SplitResult, type StageResult, type StartSessionOptions, type StorageConfig, type StreamResult, StreamingExporter, type StructuredQuery, type SubQuery, type SummarizationConfig, type SummarizationResult, SummarizationService, type SymbolicFilters, type SymbolicResult, SymbolicSearch, type SymbolicSearchResult, type SynthesisResult, TFIDFEventSync, type TFIDFIndex, TFIDFIndexManager, type TagAlias, type TagAliasInput, TagAliasSchema, TagManager, type Task, type TaskBatchOptions, TaskPriority, TaskQueue, type TaskResult, TaskStatus, type TemporalFilterField, type TemporalFocus, TemporalQueryParser, type TemporalRange, type TemporalRelation, TemporalSearch, type TemporalSearchOptions, type TermNode, type TimelineOptions, type TokenBreakdown, type TokenEstimationOptions, type TokenizedEntity, type ToolResponse, TransactionManager, type TransactionOperation, type TransactionResult, type TransitionEvent, type TransitionFilter, TransitionLedger, type TraversalOptions, type TraversalResult, TypeIndex, type UpdateEntityInput, UpdateEntitySchema, type ValidatedPagination, ValidationError, type ValidationIssue, type ValidationReport, type ValidationResult, type ValidationWarning, type VectorSearchResult, VisibilityResolver, type VisualizeOptions, type WakeUpOptions, type WakeUpResult, type WeightedRelation, type WildcardNode, type WorkThread, type WorkThreadFilter, WorkThreadManager, type WorkThreadStatus, type WorkerPoolConfig, WorkerPoolManager, type WorkingMemoryConfig, type WorkingMemoryEntity, WorkingMemoryManager, type WorkingMemoryOptions, addUniqueTags, all, allRelationsValidMetadata, applyPagination, asWarning, batchProcess, buildTFVector, calculateIDF, calculateIDFFromTokenSets, calculateTF, calculateTFIDF, calculateTextSimilarity, checkCancellation, chunkArray, cleanupAllCaches, clearAllSearchCaches, compress, compressFile, compressToBase64, computeEntropy, cosineSimilarity, createCustomProfile, createDetailedProgressReporter, createEmbeddingService, createMetadata, createProgress, createProgressInfo, createProgressReporter, createStorage, createStorageFromPath, createThrottledProgress, createUncompressedMetadata, createVectorStore, custom, customSync, debounce, decompress, decompressFile, decompressFromBase64, defaultMemoryPath, email, ensureMemoryFilePath, entityExists, entityPassesFilters, entityToText, escapeCsvFormula, executeWithPhases, filterByCreatedDate, filterByEntityType, filterByImportance, filterByModifiedDate, filterByTags, filterParallel, findEntitiesByNames, findEntityByName, fnv1aHash, formatErrorResponse, formatRawResponse, formatTextResponse, formatToolResponse, formatZodErrors, generateSuggestions, getAllCacheStats, getCompressionRatio, getCurrentTimestamp, getEntityIndex, getEntityNameSet, getPaginationMeta, getPoolStats, getQuickHint, getRoleProfile, getWorkerPoolManager, globalMemoryMonitor, groupEntitiesByType, hasAllTags, hasBrotliExtension, hasConfidence, hasMatchingTag, isAgentEntity, isArtifactEntity, isBidirectionalRelation, isCurrentlyValid, isEpisodicMemory, isPrefixPattern, isProceduralMemory, isProfileEntity, isSemanticMemory, isSessionEntity, isTemporalRelation, isValidISODate, isWeightedRelation, isWithinDateRange, isWithinImportanceRange, isWorkingMemory, isoDate, l2Normalize, levenshteinDistance, listRoleProfiles, loadConfigFromEnv, logger, mapParallel, matchesPhrase, matchesPrefix, max, maxItems, maxLength, mergeConfig, min, minItems, minLength, normalizeTag, normalizeTags, oneOf, paginateArray, parallelFilter, parallelLimit, parallelMap, parseDateRange, passesEntropyFilter, pattern, processBatch, processBatchesWithProgress, processWithRetry, range, rateLimitedProcess, removeEntityByName, removeTags, required, resolveRoleProfile, sanitizeObject, searchCaches, shutdownParallelUtils, cosineSimilarity$1 as textCosineSimilarity, tokenize as textTokenize, throttle, tokenize$1 as tokenize, touchEntity, typeOf, url, validateArrayWithSchema, validateConfig, validateEntity, validateFilePath, validateImportance, validatePagination, validateRelation, validateRelationMetadata, validateRelationsMetadata, validateSafe, validateTags, validateWithSchema, when, withRetry };
|
|
23973
|
+
export { type AccessContext, AccessContextBuilder, type AccessPattern, type AccessStats, AccessTracker, type AccessTrackerConfig, type Action, type ActiveRetrievalConfig, ActiveRetrievalController, type AdaptiveDepthConfig, type AdaptiveReductionResult, type AdaptiveResult, type AddObservationInput, AddObservationInputSchema, AddObservationsInputSchema, type AddTurnOptions, type AddTurnResult, type AdequacyCheck, type AgentEntity, type AgentMemoryConfig, AgentMemoryManager, type AgentObservation, type AgentRole, AnalyticsManager, type ArchiveCriteria, type ArchiveCriteriaInput, ArchiveCriteriaSchema, ArchiveManager, type ArchiveOptions, type ArchiveResult, type ArchiveResultExtended, type ArtifactEntity, type ArtifactFilter, ArtifactManager, type ArtifactType, AsyncMutex, type AsyncMutexOptions, type AttributionMode, type AuditEntry, type AuditFilter, AuditLog, type AuditOperation, type AuditStats, type AutoLinkOptions, type AutoLinkResult, AutoLinker, type AutoSearchResult, type BM25Config, type BM25DocumentEntry, type BM25Index, BM25Search, type BackupInfo, type BackupInfoExtended, type BackupMetadata, type BackupMetadataExtended, type BackupOptions, type BackupResult, BasicSearch, BatchCreateEntitiesSchema, BatchCreateRelationsSchema, type BatchItemResult, type BatchOperation, type BatchOperationType, type BatchOptions, type BatchProcessResult, BatchProcessor, type BatchProcessorOptions, type BatchProgress, type BatchProgressCallback, type BatchResult, BatchTransaction, type BidirectionalRelation, type BooleanCacheEntry, type BooleanOpNode, type BooleanQueryNode, BooleanSearch, COMPRESSION_CONFIG, type CacheCompressionStats, type CacheStats, type CachedQueryEntry, type CausalChain, type CausalCycle, CausalReasoner, type CausalReasonerConfig, type CausalRelationType, type CentralityResult, type ClusterMethod, CognitiveLoadAnalyzer, type CognitiveLoadConfig, type CognitiveLoadMetrics, CollaborationAuditEnforcer, type CollaborationAuditEnforcerOptions, CollaborativeSynthesis, type CollaborativeSynthesisConfig, type CommonSearchFilters, type ComponentMemoryUsage, CompositeDistillationPolicy, CompressedCache, type CompressedCacheOptions, type CompressedCacheStats, type CompressedMemory, CompressionManager, type CompressionMetadata, type CompressionOptions, type CompressionQuality, type CompressionResult, type ConfirmationResult, type ConflictInfo, ConflictResolver, type ConflictResolverConfig, type ConflictStrategy, type ConnectedComponentsResult, type ConsolidateOptions, type ConsolidationAction, type ConsolidationCycleResult, ConsolidationPipeline, type ConsolidationPipelineConfig, type ConsolidationResult, type ConsolidationRule, ConsolidationScheduler, type ConsolidationSchedulerConfig, type ConsolidationTrigger, type ContextPackage, type ContextProfile, ContextProfileManager, type ContextRetrievalOptions, ContextWindowManager, type ContextWindowManagerConfig, type Contradiction$1 as Contradiction, ContradictionDetector, type CreateArtifactOptions, type CreateEntityInput, CreateEntitySchema, type CreateEpisodeOptions, type CreateMemoryOptions, type CreateRelationInput, CreateRelationSchema, type CreateWorkThreadOptions, CycleDetectedError, DEFAULT_BASE_DIR, DEFAULT_BM25_CONFIG, DEFAULT_CAUSAL_RELATION_TYPES, DEFAULT_DUPLICATE_THRESHOLD, DEFAULT_EMBEDDING_CACHE_OPTIONS, DEFAULT_FILE_NAMES, DEFAULT_HYBRID_WEIGHTS, DEFAULT_INDEXER_OPTIONS, DEFAULT_PERMISSION_MATRIX, DEFAULT_PII_PATTERNS, DEFAULT_SCORER_WEIGHTS, DOCUMENT_PREFIX, type DateRange, DateRangeSchema, type DecayCycleResult, DecayEngine, type DecayEngineConfig, type DecayOperationOptions, type DecayOptions, type DecayResult, DecayScheduler, type DecaySchedulerConfig, type DecisionRule, type DedupTier, type DeduplicationOptions, DefaultDistillationPolicy, type DeleteObservationInput, DeleteObservationInputSchema, DeleteObservationsInputSchema, DeleteRelationsSchema, type DistillOptions, type DistillationConfig, DistillationPipeline, type DistillationResult, type DistillationStats, type DistilledLesson, type DistilledMemory, type DocumentVector, type DreamCycleResult, DreamEngine, type DreamEngineCallbacks, type DreamEngineConfig, type DreamPhaseConfig, type DreamPhaseResult, type DuplicateCheckResult, DuplicateEntityError, type DuplicatePair, ENV_VARS, EarlyTerminationManager, type EarlyTerminationOptions, type EarlyTerminationResult, EmbeddingCache, type EmbeddingCacheOptions, type EmbeddingCacheStats, type EmbeddingConfig, type EmbeddingMode, type EmbeddingProgressCallback, type EmbeddingService, type EndSessionResult, type Entity, type EntityCreatedEvent, type EntityDeletedEvent, type EntityInput, EntityManager, type EntityManagerOptions, EntityNamesSchema, EntityNotFoundError, type EntityRuleResult, EntitySchema, type EntityUpdatedEvent, type EntityValidationIssue, type EntityValidationResult, type EntityValidationRule, EntityValidator, type EntityValidatorConfig, type EntityWithContext, type EntropyFilterConfig, EntropyFilterStage, type EpisodicMemoryConfig, type EpisodicMemoryEntity, EpisodicMemoryManager, EpisodicRelations, ErrorCode, type ErrorOptions, type ExcludedEntity, type Experience, ExperienceExtractor, type ExperienceExtractorConfig, type ExperienceType, type ExplainedSearchResult, ExportError, type ExportFilter, type ExportFilterInput, ExportFilterSchema, type ExportFormat, ExportFormatSchema, type ExportOptions, type ExportResult, type ExtendedExportFormatInput, ExtendedExportFormatSchema, type ExtendedPoolStats, type ExtendedQueryCostEstimate, type ExtractedEntity, type ExtractedFact, FILE_EXTENSIONS, FILE_SUFFIXES, type FactExtractionOptions, type FactExtractionResult, FactExtractor, FailureDistillation, type FailureDistillationConfig, type FailureDistillationResult, type FieldNode, FileOperationError, type FlushResult, type ForgetOptions, type ForgetResult, FreshnessManager, type FreshnessManagerConfig, type FreshnessReport, type FuzzyCacheKey, FuzzySearch, type FuzzySearchOptions, GRAPH_LIMITS, type GetWeightedOptions, GovernanceManager, type GovernanceOperationOptions, type GovernancePolicy, GovernanceTransaction, type Granularity, type GraphCompressionResult, type GraphEvent, type GraphEventBase, GraphEventEmitter, type GraphEventListener, type GraphEventMap, type GraphEventType, type GraphLoadedEvent, type GraphProjection, type GraphSavedEvent, type GraphStats, GraphStorage, GraphTraversal, type GroupMembership, type GroupingResult, type HeuristicGuideline, HierarchyManager, HybridScorer, type HybridScorerOptions, HybridSearchManager, type HybridSearchOptions, type HybridSearchResult, type HybridWeights, type IDistillationPolicy, type IGraphStorage, IMPORTANCE_RANGE, type IMemoryBackend, IOManager, type ISummarizationProvider, type IVectorStore, ImportError, type ImportFormat, type ImportFormatInput, ImportFormatSchema, type ImportResult, ImportanceScorer, type ImportanceScorerConfig, InMemoryBackend, InMemoryVectorStore, IncrementalIndexer, type IncrementalIndexerOptions, type IndexMemoryUsage, type IndexOperation, type IndexOperationType, type IngestInput, type IngestOptions, type IngestResult, InsufficientEntitiesError, InvalidImportanceError, type JSONValue, type JsonSchema, KeywordExtractor, type KnowledgeGraph, KnowledgeGraphError, ManagerContext as KnowledgeGraphManager, type LLMProvider, LLMQueryPlanner, type LLMQueryPlannerConfig, LLMSearchExecutor, type LLMSearchExecutorOptions, LOG_PREFIXES, type LayerRecommendationOptions, type LayerTiming, type LexicalSearchResult, LocalEmbeddingService, type LogLevel, type LongRunningOperationOptions, LowEntropyContentError, LowercaseCache, type LowercaseData, ManagerContext, type ManagerContextOptions, type MatchedTerm, type MemoryAcquisitionMethod, type MemoryAlert, type MemoryChangeCallback, MemoryEngine, type MemoryEngineConfig, type MemoryEngineEventName, MemoryFormatter, type MemoryFormatterConfig, type MemoryMergeStrategy, MemoryMonitor, type MemorySource, type MemoryThresholds, type MemoryTurn, type MemoryType, type MemoryUsageStats, type MemoryValidationIssue, type MemoryValidationResult, MemoryValidator, type MemoryValidatorConfig, type Contradiction as MemoryValidatorContradiction, type MemoryVisibility, type MergeResult, type MergeStrategy, type MergeStrategyInput, MergeStrategySchema, MockEmbeddingService, type MultiAgentConfig, MultiAgentMemoryManager, NGramIndex, type NGramIndexStats, NameIndex, NoOpDistillationPolicy, type NormalizationOptions, type NormalizationResult, type ObservableDataModelAdapterOptions, type ObservableDataModelShape, type ObservationAddedEvent, type ObservationDeletedEvent, ObservationManager, ObservationNormalizer, type ObservationScore, type ObservationSource, ObserverPipeline, type ObserverPipelineOptions, type ObserverPipelineStats, OpenAIEmbeddingService, OperationCancelledError, type OperationResult, OperationType, OptimizedInvertedIndex, OptionalEntityNamesSchema, OptionalTagsSchema, type Outcome, PROCEDURE_ENTITY_TYPE, type PaginatedCacheEntry, ParallelSearchExecutor, type ParallelSearchOptions, type ParallelSearchResult, type ParsedTemporalRange, type PathResult, PatternDetector, type PatternResult, type Permission, type PermissionMatrix, type PermissionMatrixRow, type PhaseDefinition, type PhraseNode, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PipelineStage, type PoolEventCallback, type PostingListResult, type PreparedEntity, type ProceduralMemoryEntity, ProcedureManager, type ProcedureManagerConfig, ProcedureStore, type ProfileConfig, type ProfileEntity, ProfileManager, type ProfileManagerConfig, type ProfileOptions, type ProfileResponse, type ProgressCallback, type ProgressInfo, type ProgressInfoCallback, type ProgressOptions, type PromotionCriteria, type PromotionMarkOptions, type PromotionResult, type ProximityMatch, type ProximityMatchLocation, type ProximityNode, ProximitySearch, QUERY_LIMITS, QUERY_PREFIX, type QuantizationParams, type QuantizedSearchResult, QuantizedVectorStore, type QuantizedVectorStoreOptions, type QuantizedVectorStoreStats, type QueryAnalysis, QueryAnalyzer, type QueryCostEstimate, QueryCostEstimator, type QueryCostEstimatorOptions, type QueryLogEntry, QueryLogger, type QueryLoggerConfig, type QueryNode, QueryParser, type QueryPlan, QueryPlanCache, type QueryPlanCacheOptions, type QueryPlanCacheStats, QueryPlanner, QueryRewriter, type QueryStage, type QueryTrace, QueryTraceBuilder, type QueueStats, RankedSearch, RbacMiddleware, type RbacMiddlewareOptions, type RbacPolicy, ReadOnlyMemoryGraphDataError, type ReadonlyKnowledgeGraph, type RedactionResult, type RedactionStats, type RedundancyGroup, RefConflictError, type RefEntry, RefIndex, type RefIndexStats, RefNotFoundError, type RefinementHistoryEntry, ReflectionManager, type ReflectionOptions, type ReflectionResult, type ReinforcementOptions, type Relation, RelationBuilder, type RelationCreatedEvent, type RelationDeletedEvent, RelationIndex, type RelationInput, RelationManager, RelationNotFoundError, type RelationProperties, RelationSchema, type RelationValidationError, type RelationValidationResult, type RelationValidationWarning, type ResolutionResult, type ResourcePermissionOverrides, type ResourceType, type RestoreResult, type RetrievalContext, type RetrievalDecision, type RetrievalRound, type RetrieveContextOptions, type RewriteResult, type Role, type RoleAssignment, RoleAssignmentStore, type RoleAssignmentStoreOptions, type RoleProfile, type Rule, type RuleConditions, type RuleEvaluationResult, RuleEvaluator, SEARCH_LIMITS, SIMILARITY_WEIGHTS, SQLiteBackend, type SQLiteBackendOptions, SQLiteStorage, type SQLiteStorageWithEmbeddings, SQLiteVectorStore, STOPWORDS, STREAMING_CONFIG, type SalienceComponents, type SalienceContext, SalienceEngine, type SalienceEngineConfig, type SalienceWeights, type SavedSearch, type SavedSearchInput, SavedSearchInputSchema, SavedSearchManager, type SavedSearchUpdateInput, SavedSearchUpdateSchema, SchemaValidator, type ScoreBoost, type ScoreOptions, type ScoredEntity, type ScoredKeyword, type ScoredResult, type ScoringSignal, SearchCache, type SearchExplanation, SearchFilterChain, type SearchFilters, type SearchFunction, type SearchLayer, SearchManager, type SearchMethod, type SearchQuery, SearchQuerySchema, type SearchResult, SearchSuggestions, SemanticForget, type SemanticForgetOptions, type SemanticForgetResult, type SemanticIndexOptions, type SemanticLayerResult, type SemanticMemoryEntity, SemanticSearch, type SemanticSearchResult, type SessionCheckpointData, SessionCheckpointManager, type SessionConfig, type SessionEntity, type SessionHistoryOptions, SessionManager, type SessionMemoryFilter, type SessionOutcome, SessionQueryBuilder, type SessionSearchOptions, type SessionStatus, type SpilloverResult, type SplitOptions, type SplitResult, type StageResult, type StartSessionOptions, StepSequencer, type StorageConfig, type StreamResult, StreamingExporter, type StructuredQuery, type SubQuery, type SummarizationConfig, type SummarizationResult, SummarizationService, type SymbolicFilters, type SymbolicResult, SymbolicSearch, type SymbolicSearchResult, type SynthesisResult, TFIDFEventSync, type TFIDFIndex, TFIDFIndexManager, type TagAlias, type TagAliasInput, TagAliasSchema, TagManager, type Task, type TaskBatchOptions, TaskPriority, TaskQueue, type TaskResult, TaskStatus, type TemporalFilterField, type TemporalFocus, TemporalQueryParser, type TemporalRange, type TemporalRelation, TemporalSearch, type TemporalSearchOptions, type TermNode, type TimelineOptions, type TokenBreakdown, type TokenEstimationOptions, type TokenizedEntity, type ToolResponse, type Trajectory, type TrajectoryCluster, TrajectoryCompressor, type TrajectoryCompressorConfig, type TrajectoryMergeStrategy, TransactionManager, type TransactionOperation, type TransactionResult, type TransitionEvent, type TransitionFilter, TransitionLedger, type TraversalOptions, type TraversalResult, TypeIndex, type UpdateEntityInput, UpdateEntitySchema, type ValidatedPagination, ValidationError, type ValidationIssue, type ValidationReport, type ValidationResult, type ValidationWarning, type VectorSearchResult, VisibilityResolver, type VisualizeOptions, type WakeUpOptions, type WakeUpResult, type WeightedRelation, type WeightedTurn, type WildcardNode, type WorkThread, type WorkThreadFilter, WorkThreadManager, type WorkThreadStatus, type WorkerPoolConfig, WorkerPoolManager, type WorkingMemoryConfig, type WorkingMemoryEntity, WorkingMemoryManager, type WorkingMemoryOptions, WorldModelManager, type WorldModelManagerOptions, type WorldStateChange, type WorldStateEntity, WorldStateSnapshot, addUniqueTags, all, allRelationsValidMetadata, applyPagination, asWarning, batchProcess, buildTFVector, calculateIDF, calculateIDFFromTokenSets, calculateTF, calculateTFIDF, calculateTextSimilarity, checkCancellation, chunkArray, cleanupAllCaches, clearAllSearchCaches, compress, compressFile, compressToBase64, computeEntropy, cosineSimilarity, createCustomProfile, createDetailedProgressReporter, createEmbeddingService, createMetadata, createObservableDataModelFromGraph, createProgress, createProgressInfo, createProgressReporter, createStorage, createStorageFromPath, createThrottledProgress, createUncompressedMetadata, createVectorStore, custom, customSync, debounce, decodeProcedure, decompress, decompressFile, decompressFromBase64, defaultMemoryPath, email, ensureMemoryFilePath, entityExists, entityPassesFilters, entityToText, escapeCsvFormula, executeWithPhases, filterByCreatedDate, filterByEntityType, filterByImportance, filterByModifiedDate, filterByTags, filterParallel, findEntitiesByNames, findEntityByName, fnv1aHash, formatErrorResponse, formatRawResponse, formatTextResponse, formatToolResponse, formatZodErrors, generateSuggestions, getAllCacheStats, getCompressionRatio, getCurrentTimestamp, getEntityIndex, getEntityNameSet, getPaginationMeta, getPoolStats, getQuickHint, getRoleProfile, getWorkerPoolManager, globalMemoryMonitor, groupEntitiesByType, hasAllTags, hasBrotliExtension, hasConfidence, hasMatchingTag, isAgentEntity, isArtifactEntity, isBidirectionalRelation, isCurrentlyValid, isEpisodicMemory, isPrefixPattern, isProceduralMemory, isProfileEntity, isSemanticMemory, isSessionEntity, isTemporalRelation, isValidISODate, isWeightedRelation, isWithinDateRange, isWithinImportanceRange, isWorkingMemory, isoDate, l2Normalize, levenshteinDistance, listRoleProfiles, loadConfigFromEnv, logger, mapParallel, matchesPhrase, matchesPrefix, max, maxItems, maxLength, mergeConfig, min, minItems, minLength, normalizeTag, normalizeTags, oneOf, paginateArray, parallelFilter, parallelLimit, parallelMap, parseDateRange, passesEntropyFilter, pattern, permissionsForRole, processBatch, processBatchesWithProgress, processWithRetry, range, rateLimitedProcess, removeEntityByName, removeTags, required, resolveRoleProfile, sanitizeObject, searchCaches, shutdownParallelUtils, cosineSimilarity$1 as textCosineSimilarity, tokenize as textTokenize, throttle, tokenize$1 as tokenize, touchEntity, typeOf, url, validateArrayWithSchema, validateConfig, validateEntity, validateFilePath, validateImportance, validatePagination, validateRelation, validateRelationMetadata, validateRelationsMetadata, validateSafe, validateTags, validateWithSchema, when, withRetry };
|