Skip to content
Merged
40 changes: 39 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
person, with what was said under that name still attached. Now, when a persist closes a naming fact (`is named`,
`is called`, any subject: the user, a person, a pet) in favour of a new name, the owner's entity with the old name is
merged into the one with the new name (created if missing): relationships move, the old name stays as an alias so it
is still recognised, and the old entity is closed. The live facts said about the old name are restated under the new
is still recognised, and the old entity is closed; when entity resolution already filed the new name under the old entity (as an alias), that entity is renamed in place. The live facts said about the old name are restated under the new
one, each superseding its original. Facts that mention the old name as their object are not rewritten.

- **The people a recalled fact names bring their relationships** (with `RecallOptions.MaxRelationships` set). Recall
Expand All @@ -23,6 +23,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`ILongTermMemoryService.GetRelationshipsAroundAsync` / `IRelationshipRepository.GetLiveAroundAsync` (defaults fall
back to the id-only reads).

- **A value said again after it was replaced starts a second period.** "Copenhagen, then Oslo, then back to
Copenhagen" used to re-open the first Copenhagen fact: live again, but still ended at the Oslo move, and its first
period lost, so "as of the Oslo months" believed both cities. Facts now carry a `period_key`: open ('') while
nothing replaced them, the fact's own id once a newer value supersedes it. The fact writes MERGE on the open period,
so the triple said again later is a new fact (its own period) and the closed one keeps its end; a restatement of a
live fact still lands on it (mention count, confidence), and a fact closed any other way (retracted, decayed,
consolidated) re-opens as before. Existing stores get their period keys at bootstrap, before any write.
`FindByTripleAsync` prefers the live period. `IFactRepository.FindSupersededCandidatesAsync` gains an overload
taking `now`, so write-time supersession judges the candidates at the same instant it judged the new value (it read
the store's wall clock before).

- **Owner-filtered vector indexes on Neo4j 2026.x** (`Neo4jOptions.FilteredVectorIndexes`, off by default). A 2026.x
vector index can carry filter properties and filter inside the index. With the option on, bootstrap creates
`fact_embedding_owner_idx` and `entity_embedding_owner_idx` (the embedding, filtered on `owner_key`; it refuses, by
name, to start on an older server), and owner-scoped fact and entity recall searches them with the Cypher 25
`SEARCH` clause: the owner's rows, then the shared rows (`owner_key = '*'`; the server takes an exact value, not a
list or an OR), merged by score. An owner is then never crowded out of a global top-K, so the widening and rescue
scans that work around that on 5.26 are not needed. Off, nothing changes. The integration suite runs against another
server with `AGENTMEMORY_TEST_NEO4J_IMAGE` (e.g. `neo4j:2026.02`).

- **Who an event was shared with is kept as its own fact** (`LlmExtractionOptions.CaptureEventCompanions`, off by
default). "Yesterday I went hiking in Sintra with my friend Pedro" was kept whole in one extraction and split without
Pedro in the next, so "who was with me?" had no answer. With the option on, every extractor (unified, multi-session,
per-type facts) also asks for, per companion, "user | went hiking with | Pedro" with the event's day; off, every
prompt is byte-for-byte what it was.

- **A plan that has begun takes over from the value it was planned to replace.** "I'm moving to Oslo next month" is
stored as a plan and replaces nothing when said; once its start has passed, recall gives Oslo, not Copenhagen as
well. Applied where a recall's facts are chosen, at the recall's instant (now, or the as-of time), per owner, subject
and single-valued relation; nothing is rewritten, so a plan cancelled later simply stops being live and the old value
is current again. Starts are compared at the precision they were said: "in August" is the whole month, so it is not
ordered before "on 20 August", and starts that overlap are ordered by when they were said.

- **`agentmemory retrim [--apply]`: repair facts stored before predicate-echo trimming.** Facts written before the
write-time trim ("Daniel | is a chef | chef", rendered "is a chef chef") are rewritten as they read once trimmed
("Daniel | is | a chef", identity keys included), or superseded by the trimmed fact when it is already stored. A dry
run unless `--apply`; on demand only, never at bootstrap (`ISchemaBootstrapper.RetrimEchoedPredicatesAsync`).

- **A held question turn says so.** `ExtractionResult.Deferred` (and the public `ExtractionResult.DeferredMetadataKey`)
tell a host that the turn was held for the next one that tells something, rather than extracted with nothing in it;
the `memory.ingestion.operations` counter tags it `status=Deferred`, apart from successes.
Expand Down
11 changes: 11 additions & 0 deletions docs/configuration/memory-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ because their effect depends on the model.
- `ContextFormatOptions`: `AgentFrameworkOptions.ContextFormat` in `AddAgentMemoryFramework`.
- `MemoryContextFormatterOptions` (Core) and `MemoryRecallSecurityOptions` (Semantic Kernel): the
renderer of each surface.
- `Neo4jOptions`: the `configureNeo4j` lambda of `AddNeo4jAgentMemory`.

## The switches

Expand All @@ -28,6 +29,7 @@ because their effect depends on the model.
| `RecallOptions.MaxRelationships` | `0` | How many live relationships touching the recalled entities to include, rendered `Rosa — best friend → Carmen`. `0` reads none. Live recall only. |
| `LlmExtractionOptions.TemporalValidity` | `TemporalValidityMode.Ignore` | `Extract` asks the model for validity dates where the conversation states them, at the precision stated, and for the day a one-off event happened (`Fact.OccurredOn`); each turn reaches the extractor with its timestamp. |
| `ExtractionOptions.SupersedeReplacedFacts` | `false` | A new value of a single-valued relation closes the one it replaces: every present-state form ("works for" replaces "works at"), a stated age, `favourite <thing>`, an entailed state ("moved to" a place → "lives in"), relationship edges. Only values that hold now replace or are replaced. |
| `LlmExtractionOptions.CaptureEventCompanions` | `false` | Who an event was shared with is also written as its own fact ("user \| went hiking with \| Pedro", with the event's day), so "who was with me?" has an answer however the event itself is split. |
| `LlmExtractionOptions.MarkCorrections` | `false` | The extractor marks what a correction replaces ("actually Arcade Fire, not Radiohead"); with `SupersedeReplacedFacts`, the write closes the fact or preference it names. |
| `LlmExtractionOptions.OwnPreferencesOnly` | `false` | A preference is only the user's own stated taste; someone else's taste is a fact about them, and a request is not a preference. |
| `ExtractionOptions.ResolveUserToName` | `true` | Once the user's name is known, what they say about themselves is stored under that name, and no entity called "user" is created beside the person. |
Expand All @@ -45,6 +47,15 @@ Behaviour with no switch:
"is a | chef").
- Entities carry `owner_key` (`"*"` when shared), so entity resolution seeks shared candidates by
index; existing stores are backfilled at bootstrap. See [schema.md](../schema.md).
- A value said again after it was replaced starts a second period (its own fact), so the first period keeps its end
and as-of recall of the time between is right; facts carry `period_key`, backfilled at bootstrap.
- A plan that has begun takes over from the value it was planned to replace in recall, at the recall's instant.

### Newer Neo4j servers

| Option | Default | What it does |
|---|---|---|
| `Neo4jOptions.FilteredVectorIndexes` | `false` | Neo4j 2026.x and later: bootstrap creates owner-filtered vector indexes for facts and entities (the embedding, filtered on `owner_key`), and owner-scoped recall searches them, so an owner is never crowded out of a global top-K by other owners' rows. Refused at bootstrap on an older server. |

## Example

Expand Down
16 changes: 16 additions & 0 deletions src/AgentMemory.Abstractions/Repositories/IFactRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,22 @@ Task<IReadOnlyList<Fact>> FindSupersededCandidatesAsync(
CancellationToken cancellationToken = default) =>
Task.FromResult<IReadOnlyList<Fact>>([]);

/// <summary>
/// J-6. As <see cref="FindSupersededCandidatesAsync(string, string, string, string, MemoryScope?, CancellationToken)"/>,
/// judging "holds now" at <paramref name="now"/>: the caller's clock, so the write side (which decides whether the
/// winner holds) and this read (which decides whether a candidate does) agree. The default ignores
/// <paramref name="now"/> and reads with the store's own notion of now.
/// </summary>
Task<IReadOnlyList<Fact>> FindSupersededCandidatesAsync(
string winnerFactId,
string subject,
string predicate,
string @object,
DateTimeOffset now,
MemoryScope? scope = null,
CancellationToken cancellationToken = default) =>
FindSupersededCandidatesAsync(winnerFactId, subject, predicate, @object, scope, cancellationToken);

/// <summary>
/// Finds an existing fact matching the subject-predicate-object triple. When <paramref name="scope"/>
/// is supplied (R1) the lookup is confined to the owner's own and (optionally) shared facts. Null
Expand Down
21 changes: 18 additions & 3 deletions src/AgentMemory.Core/Extraction/PersistenceStage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,21 @@ private async Task RenameAsync(string old, string name, MemoryScope scope, Cance
SourceMessageIds = source.SourceMessageIds,
Embedding = await _embeddingOrchestrator.EmbedAsync(name, cancellationToken).ConfigureAwait(false),
}, cancellationToken).ConfigureAwait(false);
if (target.EntityId != source.EntityId)
if (target.EntityId == source.EntityId)
{
// Entity resolution already filed the new name under the old entity (as an alias): it is the same one,
// so it is renamed in place, the new name its own and the old one kept as an alias.
await _entityRepository.UpsertAsync(source with
{
Name = name,
CanonicalName = name,
Aliases = [.. source.Aliases.Where(a => !string.Equals(a, name, StringComparison.OrdinalIgnoreCase))
.Append(old).Distinct(StringComparer.OrdinalIgnoreCase)],
Embedding = await _embeddingOrchestrator.EmbedAsync(name, cancellationToken).ConfigureAwait(false),
}, cancellationToken).ConfigureAwait(false);
_logger.LogDebug("Renamed entity '{Old}' to '{Name}' in place ({Id}).", old, name, source.EntityId);
}
else
{
// Relationships and mentions move, the old name becomes an alias; then the old entity is closed.
await _entityRepository.MergeEntitiesAsync(source.EntityId, target.EntityId, scope, cancellationToken).ConfigureAwait(false);
Expand Down Expand Up @@ -835,16 +849,17 @@ async Task SupersedeReplacedFactsAsync(Fact winner, Fact? under = null)
var candidates = SharedScopes.OwnedOrShared(ownerId);
try
{
// J-6: one clock. The winner was judged to hold at `now`; the candidates are judged at the same instant.
var losers = await _factRepository.FindSupersededCandidatesAsync(
winner.FactId, said.Subject, said.Predicate, winner.Object, candidates,
winner.FactId, said.Subject, said.Predicate, winner.Object, now, candidates,
cancellationToken).ConfigureAwait(false);
// I-5. A fact now stored under the user's name also replaces what was stored before the
// name was known, under the words used then ("user | lives in | Lisbon").
if (said.Metadata.TryGetValue("subject_surface", out var surface) && surface is string surfaceSubject &&
UserNames.IsSelf(surfaceSubject))
{
losers = [.. losers, .. await _factRepository.FindSupersededCandidatesAsync(
winner.FactId, surfaceSubject, said.Predicate, winner.Object, candidates,
winner.FactId, surfaceSubject, said.Predicate, winner.Object, now, candidates,
cancellationToken).ConfigureAwait(false)];
}

Expand Down
77 changes: 77 additions & 0 deletions src/AgentMemory.Core/Memory/ValueHandOver.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
using AgentMemory.Abstractions.Domain;

namespace AgentMemory.Core.Memory;

/// <summary>
/// J-6 (b, c). A plan that has begun takes over from the value it was planned to replace. "I'm moving to Oslo next
/// month" is stored as a plan (its start is ahead), so it replaces nothing when said; once that start has passed, the
/// value it was planned to replace is no longer the current one. Applied where a recall's facts are chosen, at the
/// recall's instant (now, or the as-of time), so nothing is rewritten: a plan that is later cancelled simply stops being
/// a live fact, and the old value is current again.
/// </summary>
/// <remarks>
/// Only single-valued relations (the ones supersession acts on: where someone lives, works, their age), per owner and
/// subject. Among a group's values that have begun, the one that began last is current, and the others that began
/// before it are dropped; values still ahead (plans) stay, shown with their start. Starts are compared at the precision
/// they were said (J-6 c): "in August" is the whole of August, so it is not before "on 20 August"; two starts that
/// overlap are ordered by when they were said.
/// </remarks>
internal static class ValueHandOver
{
internal static IReadOnlyList<Fact> Current(IReadOnlyList<Fact> facts, DateTimeOffset at)
{
if (facts.Count < 2) return facts;
HashSet<string>? dropped = null;
foreach (var group in facts
.Where(f => MemoryRelationCardinality.IsSingleValued(f.Predicate))
.GroupBy(f => (f.OwnerId, Subject: MemoryTripleCanonicalizer.CanonicalValue(f.Subject),
Relation: MemoryRelationCardinality.Relation(f.Predicate))))
{
var begun = group.Where(f => Start(f).From <= at).ToList();
if (begun.Count < 2) continue;
var current = begun.Aggregate((latest, next) => Before(latest, next) ? next : latest);
foreach (var earlier in begun.Where(f => f.FactId != current.FactId && Before(f, current)))
(dropped ??= new HashSet<string>(StringComparer.Ordinal)).Add(earlier.FactId);
}
return dropped is null ? facts : [.. facts.Where(f => !dropped.Contains(f.FactId))];
}

/// <summary>Whether <paramref name="a"/> began before <paramref name="b"/>: at their precision, else in the order said.</summary>
internal static bool Before(Fact a, Fact b)
{
var (aFrom, aTo) = Start(a);
var (bFrom, bTo) = Start(b);
if (aTo < bFrom) return true;
if (bTo < aFrom) return false;
return a.CreatedAtUtc < b.CreatedAtUtc; // the spans overlap: what was said later is the newer value
}

/// <summary>
/// When a value began, as the span its precision allows: a day, a month, a year. No start: the moment it was said.
/// </summary>
internal static (DateTimeOffset From, DateTimeOffset To) Start(Fact fact)
{
if (fact.ValidFrom is { } from) return Span(from, fact.ValidFromPrecision);
if (fact.OccurredOn is { } on) return Span(on, fact.OccurredOnPrecision);
return (fact.CreatedAtUtc, fact.CreatedAtUtc);
}

internal static (DateTimeOffset From, DateTimeOffset To) Span(DateTimeOffset at, DatePrecision precision)
{
var utc = at.ToUniversalTime();
if (precision == DatePrecision.Instant) return (utc, utc);
var start = precision switch
{
DatePrecision.Year => new DateTimeOffset(utc.Year, 1, 1, 0, 0, 0, TimeSpan.Zero),
DatePrecision.Month => new DateTimeOffset(utc.Year, utc.Month, 1, 0, 0, 0, TimeSpan.Zero),
_ => new DateTimeOffset(utc.Year, utc.Month, utc.Day, 0, 0, 0, TimeSpan.Zero),
};
var end = precision switch
{
DatePrecision.Year => start.AddYears(1),
DatePrecision.Month => start.AddMonths(1),
_ => start.AddDays(1),
};
return (start, end.AddTicks(-1));
}
}
16 changes: 16 additions & 0 deletions src/AgentMemory.Core/Services/MemoryContextAssembler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,16 @@ private async Task<IReadOnlyList<RecalledRelationship>> RelationshipsAmongAsync(
}
}

/// <summary>J-6 (b): <see cref="ValueHandOver"/>, with the scores filtered in lockstep (a score for a dropped fact would point at nothing).</summary>
private static (IReadOnlyList<Fact> Facts, IReadOnlyList<(Fact Fact, double Score)> Scores) HandOver(
IReadOnlyList<Fact> facts, IReadOnlyList<(Fact Fact, double Score)> scores, DateTimeOffset at)
{
var current = ValueHandOver.Current(facts, at);
if (current.Count == facts.Count) return (facts, scores);
var kept = current.Select(f => f.FactId).ToHashSet(StringComparer.Ordinal);
return (current, scores.Where(s => kept.Contains(s.Fact.FactId)).ToArray());
}

/// <summary>J-7: the names the recalled facts are about (subjects and objects), not "user", at most 40.</summary>
internal static IReadOnlyList<string> NamesIn(IReadOnlyList<Fact> facts) =>
[.. facts.SelectMany(fact => new[] { fact.Subject, fact.Object })
Expand Down Expand Up @@ -877,6 +887,9 @@ public async Task<MemoryContext> AssembleContextAsync(
}
}

// J-6 (b). A plan that has begun takes over from the value it was planned to replace (now).
(facts, factScores) = HandOver(facts, factScores, _clock.UtcNow);

// 30.8. Runs AFTER the fact section resolves, because its trigger is what that section came
// back with. One extra query, only on a thin recall, only with the flag on -- a well-answered
// turn pays nothing at all.
Expand Down Expand Up @@ -1440,6 +1453,9 @@ await Task.WhenAll(
}
}

// J-6 (b). As in live recall, at the valid-time instant asked about: which plans had begun by then.
(facts, factScores) = HandOver(facts, factScores, validAsOf);

// Built after budgeting for the same reason as the live path: ContextRank is the post-budget
// position. Off by default — every section then keeps its Array.Empty default.
IReadOnlyList<MemoryContextRankedItem> entityRanked = Array.Empty<MemoryContextRankedItem>();
Expand Down
8 changes: 8 additions & 0 deletions src/AgentMemory.Extraction.Llm/ExtractionPromptSemantics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,14 @@ internal static string CorrectionsInstruction(bool mark) => mark
+ "value exactly as it was said. Omit \"replaces\" everywhere else."
: string.Empty;

/// <summary>J-14. The people an event was shared with, each as a fact of their own. Empty when off.</summary>
internal static string EventCompanionsInstruction(bool capture) => capture
? "\nWhen the user did something WITH other people (\"hiked in Sintra with Pedro\", \"had dinner with Ana and "
+ "Luis\"), also add, for EACH of them, a fact whose subject is \"user\", whose predicate is the activity followed "
+ "by \"with\" (\"went hiking with\", \"had dinner with\") and whose object is that person's name, with the same "
+ "day as the event if it has one. Keep the facts about the event itself exactly as you would without this."
: string.Empty;

internal static string UserNameInstruction(bool capture) => capture
? "\nIf the user STATES their own name (\"I'm Dana\", \"call me Dee\"), also add a fact whose "
+ "subject is \"user\", whose predicate is \"is named\" and whose object is the name as they "
Expand Down
Loading
Loading