Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- **A corrected name renames what it named** (`ExtractionOptions.RenameOnCorrectedName`, off by default; needs
`SupersedeReplacedFacts`). "It's Priya, not Pruya" used to close the old naming fact but leave "Pruya" as a second
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
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
already added the relationships between the recalled entities; now also those of the entities the recalled facts
name, by name or alias, in the same single query. "What does my manager's husband do?" gets "Priya Nair — married
to → Daniel" beside "Daniel works as chef", even when neither person was recalled by itself.
`ILongTermMemoryService.GetRelationshipsAroundAsync` / `IRelationshipRepository.GetLiveAroundAsync` (defaults fall
back to the id-only reads).

- **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.

- **A turn in which the user only asks waits for the next turn that tells something**
(`AgentFrameworkOptions.DeferQuestionTurns`, off by default; `ExtractionRequest.DeferIfOnlyAsking` for other hosts;
`ExtractionOptions.MaxDeferredTurns` 3). In simulated conversations 43 % of extraction calls returned nothing, almost
Expand Down
1 change: 1 addition & 0 deletions docs/configuration/memory-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ because their effect depends on the model.
| `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. |
| `ExtractionOptions.RenameOnCorrectedName` | `false` | When a correction replaces a name ("it's Priya, not Pruya"; "the cat is called Miso"), the entity with the old name merges into the one with the new name (old name kept as an alias) and the facts said about the old name are restated under the new one. Needs `SupersedeReplacedFacts`. |
| `LlmExtractionOptions.CaptureUserName` | `true` | Asks the extractor for a `user \| is named \| <name>` fact when the user states their name; `ResolveUserToName` reads it. |
| `LlmExtractionOptions.IgnoreQuestions` | `true` | A question states nothing, including what it takes for granted ("When did I move to Lyon?" is not stored as a move). |
| `MemoryOptions.WorkingMemory.RecentTopicsDays` | `0` | "Lately": the profile block ends with one line naming what the person talked about most in the last this-many days (`Lately (7 days): marathon (5 mentions), Ana (2 mentions)`), counted by the facts extracted from what the person said; never the person themselves. `MaxRecentTopics` (3) and `MinRecentTopicMentions` (2) shape it. `0` leaves the block as it was. |
Expand Down
12 changes: 12 additions & 0 deletions src/AgentMemory.Abstractions/Domain/Extraction/ExtractionResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,16 @@ public sealed record ExtractionResult

/// <summary>Convenience accessor: <see langword="true"/> when <see cref="Status"/> is <see cref="IngestionStatus.PartiallySucceeded"/>.</summary>
public bool IsPartial => Status == IngestionStatus.PartiallySucceeded;

/// <summary>
/// The <see cref="Metadata"/> key set on a result whose turn only asked and was held for the next turn that tells
/// something (<c>ExtractionRequest.DeferIfOnlyAsking</c>): nothing was extracted yet, and nothing failed.
/// </summary>
public const string DeferredMetadataKey = "agentMemory.extraction.deferred";

/// <summary>
/// <see langword="true"/> when the turn was held rather than extracted (<see cref="DeferredMetadataKey"/>): an empty
/// result that is neither a success with nothing in it nor a failure. The ingestion metrics count it apart.
/// </summary>
public bool Deferred => Metadata.TryGetValue(DeferredMetadataKey, out var held) && held is true;
}
11 changes: 11 additions & 0 deletions src/AgentMemory.Abstractions/Options/ExtractionOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,17 @@ public sealed class ExtractionOptions
/// </summary>
public bool ResolveUserToName { get; set; } = true;

/// <summary>
/// A name that replaces another renames what it named, instead of leaving two of it (default false). When this
/// persist closed a naming fact ("user | is named | Pruya", "cat | is called | Missou") in favour of a new name
/// (a correction, or a real change of 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 one, each
/// superseding its original, so the history stays readable. Needs <see cref="SupersedeReplacedFacts"/> (which
/// closes the old naming fact). Owner-scoped: a shared (owner-less) write renames nothing.
/// </summary>
public bool RenameOnCorrectedName { get; set; }

/// <summary>
/// Merge near-identical facts produced by ONE extraction (dark, default false). A single message
/// produced "moved to | analytics team" and "moved to | analytics", and "requested help with" next to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,21 @@ Task<IReadOnlyList<RecalledRelationship>> GetLiveAmongAsync(
CancellationToken cancellationToken = default) =>
throw new NotSupportedException("This IRelationshipRepository implementation cannot read relationships for recall.");

/// <summary>
/// J-7. As <see cref="GetLiveAmongAsync"/>, and also the relationships of the entities called one of
/// <paramref name="names"/> (by name or alias, case-insensitive): the people and things recalled facts name, so
/// "Priya Nair is married to Daniel" reaches a question about her husband even when neither entity was recalled
/// by itself. The default ignores the names.
/// </summary>
Task<IReadOnlyList<RecalledRelationship>> GetLiveAroundAsync(
IReadOnlyList<string> entityIds,
IReadOnlyList<string> names,
int limit,
DateTimeOffset now,
MemoryScope? scope = null,
CancellationToken cancellationToken = default) =>
GetLiveAmongAsync(entityIds, limit, now, scope, cancellationToken);

/// <summary>
/// 36.4. Ends a relationship: sets its <c>valid_until</c> to <paramref name="endedAt"/> unless it already ended
/// (the first end is kept). The edge stays, with its provenance, for history. Returns true when it exists in
Expand Down
13 changes: 13 additions & 0 deletions src/AgentMemory.Abstractions/Services/ILongTermMemoryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,19 @@ Task<IReadOnlyList<RecalledRelationship>> GetRelationshipsAmongAsync(
CancellationToken cancellationToken = default) =>
throw new NotSupportedException("This ILongTermMemoryService implementation cannot read relationships for recall.");

/// <summary>
/// J-7. As <see cref="GetRelationshipsAmongAsync"/>, and also the relationships of the entities called one of
/// <paramref name="names"/> (the people and things the recalled facts name). The default ignores the names.
/// </summary>
Task<IReadOnlyList<RecalledRelationship>> GetRelationshipsAroundAsync(
IReadOnlyList<string> entityIds,
IReadOnlyList<string> names,
int limit,
DateTimeOffset now,
MemoryScope? scope = null,
CancellationToken cancellationToken = default) =>
GetRelationshipsAmongAsync(entityIds, limit, now, scope, cancellationToken);

/// <summary>
/// Deletes a preference by identifier. When <paramref name="scope"/> is supplied (R1) the delete
/// only affects the owner's own preference — never another owner's, and never shared/global ones.
Expand Down
93 changes: 93 additions & 0 deletions src/AgentMemory.Core/Extraction/PersistenceStage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,14 @@ public async Task<PersistenceResult> PersistAsync(
MemoryTrustLevel trustLevel = MemoryTrustLevel.Untrusted,
CancellationToken cancellationToken = default)
{
var started = _clock.UtcNow;
var result = await PersistCoreAsync(extraction, ownerId, trustLevel, cancellationToken)
.ConfigureAwait(false);

// J-11. After the write (whichever path produced it), outside its transaction: a name that replaced another
// renames what it named. Before the rebuild below, so the working-memory block is compiled from the result.
await RenameCorrectedNamesAsync(extraction, ownerId, started, cancellationToken).ConfigureAwait(false);

// Once per persist, and here rather than inside the core so it happens exactly once whichever
// of the three return paths (atomic / best-effort / replay) produced the result, and outside
// the storage transaction either way. A throw from the core skips it, which is right: nothing
Expand Down Expand Up @@ -217,6 +222,94 @@ private async Task<PersistenceResult> PersistCoreAsync(

private sealed class ReplayBestEffortPersistenceException : Exception;

/// <summary>
/// J-11 (<see cref="ExtractionOptions.RenameOnCorrectedName"/>). The renames this persist made: for each naming fact
/// it wrote ("user | is named | Priya"), the naming facts of the same subject it closed ("… | Pruya"), found in the
/// store rather than threaded through the write, so it holds for every write path (atomic, best-effort, replayed).
/// Best-effort, like supersession: a failed rename leaves the two names side by side, never a failed ingestion.
/// </summary>
private async Task RenameCorrectedNamesAsync(
ExtractionStageResult extraction, string? ownerId, DateTimeOffset since, CancellationToken cancellationToken)
{
if (!_options.RenameOnCorrectedName || string.IsNullOrWhiteSpace(ownerId)) return;
var naming = extraction.FilteredFacts
.Where(f => UserNames.IsNamingPredicate(f.Predicate) && !string.IsNullOrWhiteSpace(f.Object))
.ToList();
if (naming.Count == 0) return;

var scope = MemoryScope.For(ownerId, includeShared: false);
// The store's clock stamps invalidated_at; a second of slack keeps a close made by this persist inside.
var from = since - TimeSpan.FromSeconds(1);
foreach (var named in naming)
{
var name = named.Object.Trim();
try
{
var replaced = (await _factRepository.GetBySubjectAsync(named.Subject, scope, cancellationToken).ConfigureAwait(false))
.Where(f => UserNames.IsNamingPredicate(f.Predicate) && f.InvalidatedAtUtc >= from &&
!string.Equals(f.Object.Trim(), name, StringComparison.OrdinalIgnoreCase))
.Select(f => f.Object.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
foreach (var old in replaced)
await RenameAsync(old, name, scope, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception ex)
{
_logger.LogWarning(ex, "Renaming to '{Name}' failed; the old name stays beside it.", name);
}
}
}

/// <summary>J-11: the entity called <paramref name="old"/> becomes <paramref name="name"/>, and so do the facts about it.</summary>
private async Task RenameAsync(string old, string name, MemoryScope scope, CancellationToken cancellationToken)
{
// The entity: only one that bears the old name as its own (an alias match is already the renamed one).
var source = await _entityRepository.FindLiveByNameAsync(old, null, scope, cancellationToken).ConfigureAwait(false);
if (source is not null && string.Equals(source.Name, old, StringComparison.OrdinalIgnoreCase))
{
var target = await _entityRepository.FindLiveByNameAsync(name, null, scope, cancellationToken).ConfigureAwait(false)
?? await _entityRepository.UpsertAsync(new Entity
{
EntityId = _idGenerator.GenerateId(),
Comment on lines +272 to +275
Name = name,
Type = source.Type,
Subtype = source.Subtype,
Confidence = source.Confidence,
OwnerId = scope.OwnerId,
CreatedAtUtc = _clock.UtcNow,
SourceMessageIds = source.SourceMessageIds,
Embedding = await _embeddingOrchestrator.EmbedAsync(name, cancellationToken).ConfigureAwait(false),
}, cancellationToken).ConfigureAwait(false);
if (target.EntityId != source.EntityId)
{
// 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);
await _entityRepository.InvalidateAsync(source.EntityId, scope, cancellationToken).ConfigureAwait(false);
_logger.LogDebug("Renamed entity '{Old}' to '{Name}' ({Source} into {Target}).", old, name, source.EntityId, target.EntityId);
}
}

// The facts said about the old name, restated under the new one; each original is superseded by its restatement.
var facts = await _factRepository.GetBySubjectAsync(old, scope, cancellationToken).ConfigureAwait(false);
foreach (var fact in facts.Where(f => f.InvalidatedAtUtc is null))
{
var metadata = new Dictionary<string, object>(fact.Metadata) { ["renamed_from"] = old };
var restated = await _factRepository.UpsertAsync(fact with
{
FactId = _idGenerator.GenerateId(),
Subject = name,
CreatedAtUtc = _clock.UtcNow,
Metadata = metadata,
Embedding = await _embeddingOrchestrator.EmbedFactAsync(name, fact.Predicate, fact.Object, cancellationToken)
.ConfigureAwait(false),
}, cancellationToken).ConfigureAwait(false);
if (restated.FactId != fact.FactId)
await _factRepository.SupersedeAsync(fact.FactId, restated.FactId, scope, cancellationToken).ConfigureAwait(false);
}
}

private async Task<PersistenceResult> PersistPreparedAsync(
ExtractionStageResult extraction,
string? ownerId,
Expand Down
10 changes: 10 additions & 0 deletions src/AgentMemory.Core/Services/LongTermMemoryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,16 @@ public Task<IReadOnlyList<RecalledRelationship>> GetRelationshipsAmongAsync(
CancellationToken cancellationToken = default) =>
_relRepo.GetLiveAmongAsync(entityIds, limit, now, Resolve(scope, nameof(GetRelationshipsAmongAsync)), cancellationToken);

/// <inheritdoc/>
public Task<IReadOnlyList<RecalledRelationship>> GetRelationshipsAroundAsync(
IReadOnlyList<string> entityIds,
IReadOnlyList<string> names,
int limit,
DateTimeOffset now,
MemoryScope? scope = null,
CancellationToken cancellationToken = default) =>
_relRepo.GetLiveAroundAsync(entityIds, names, limit, now, Resolve(scope, nameof(GetRelationshipsAroundAsync)), cancellationToken);

/// <inheritdoc/>
public Task DeletePreferenceAsync(
string preferenceId,
Expand Down
25 changes: 19 additions & 6 deletions src/AgentMemory.Core/Services/MemoryContextAssembler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,13 +239,14 @@ private static IReadOnlyDictionary<TruncationStrategy, ITruncationStrategy> Buil
/// recall: a store that cannot read them, or a read that fails, leaves the section empty, never the recall.
/// </summary>
private async Task<IReadOnlyList<RecalledRelationship>> RelationshipsAmongAsync(
IReadOnlyList<Entity> entities, int limit, MemoryScope? scope, CancellationToken cancellationToken)
IReadOnlyList<Entity> entities, IReadOnlyList<string> factNames, int limit, MemoryScope? scope, CancellationToken cancellationToken)
{
try
{
return await TimedAsync("memory.recall.relationships", () => _longTerm.GetRelationshipsAmongAsync(
entities.Select(entity => entity.EntityId).Distinct(StringComparer.Ordinal).ToList(),
limit, _clock.UtcNow, scope, cancellationToken))
var ids = entities.Select(entity => entity.EntityId).Distinct(StringComparer.Ordinal).ToList();
return await TimedAsync("memory.recall.relationships", () => factNames.Count == 0
? _longTerm.GetRelationshipsAmongAsync(ids, limit, _clock.UtcNow, scope, cancellationToken)
: _longTerm.GetRelationshipsAroundAsync(ids, factNames, limit, _clock.UtcNow, scope, cancellationToken))
.ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
Expand All @@ -257,6 +258,15 @@ private async Task<IReadOnlyList<RecalledRelationship>> RelationshipsAmongAsync(
}
}

/// <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 })
.Where(name => !string.IsNullOrWhiteSpace(name) && name.Trim().Length > 1 &&
!Extraction.PersistenceStage.UserNames.IsSelf(name))
.Select(name => name.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.Take(40)];

private static int? SharedBudgetFor(MemoryScope? scope, int? sharedRecallBudget) =>
LongTermMemoryService.SplitsShared(sharedRecallBudget, scope) ? sharedRecallBudget : null;

Expand Down Expand Up @@ -1024,8 +1034,11 @@ public async Task<MemoryContext> AssembleContextAsync(
projection = SuppressNoDirectMatch(projection, Projection.ProjectionSectionKeys.Facts);

// 36.7. How the recalled entities relate, from the entities that reach the prompt. Off unless asked for.
var relationships = recallOpts.MaxRelationships > 0 && entities.Count > 0
? await RelationshipsAmongAsync(entities, recallOpts.MaxRelationships, scope, cancellationToken).ConfigureAwait(false)
// J-7: and the people and things the recalled facts name ("Daniel | works as | chef" brings "Priya Nair married
// to Daniel" to "what does my manager's husband do?"), even when those entities were not recalled themselves.
IReadOnlyList<string> factNames = recallOpts.MaxRelationships > 0 ? NamesIn(facts) : [];
var relationships = recallOpts.MaxRelationships > 0 && (entities.Count > 0 || factNames.Count > 0)
? await RelationshipsAmongAsync(entities, factNames, recallOpts.MaxRelationships, scope, cancellationToken).ConfigureAwait(false)
: Array.Empty<RecalledRelationship>();

var context = new MemoryContext
Expand Down
2 changes: 1 addition & 1 deletion src/AgentMemory.Core/Services/MemoryService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ public async Task<ExtractionResult> ExtractAndPersistAsync(
}

/// <summary>37.4. Result metadata key set (true) when a turn was held for later extraction.</summary>
internal const string DeferredMetadataKey = "agentMemory.extraction.deferred";
internal const string DeferredMetadataKey = ExtractionResult.DeferredMetadataKey;

/// <summary>
/// Attaches the preceding turns an extractor may read to resolve references (E2).
Expand Down
Loading
Loading