#include "HyperTwistMemory/HyperTwistMemoryCoreLibrary.h"

#include "HyperTwistTraining/HyperTwistTrainingKnowledgeLibrary.h"
#include "HyperTwistTraining/HyperTwistTrainingRepositoryLibrary.h"

namespace HyperTwistMemoryCoreLibraryInternal
{
	FString ResolveReferenceUtc(const FString& ReferenceUtc)
	{
		return ReferenceUtc.IsEmpty() ? FDateTime::UtcNow().ToIso8601() : ReferenceUtc;
	}

	FString MakeDeckCaseKey(const FString& DeckId, const FString& CaseId)
	{
		return DeckId + TEXT("|") + CaseId;
	}

	FHyperTwistMemoryProvenanceLink MakeProvenanceLink(
		const FHyperTwistMemoryEntityDescriptor& ParentEntity,
		const FString& SourceLabel
	)
	{
		FHyperTwistMemoryProvenanceLink ProvenanceLink;
		ProvenanceLink.ParentEntityId = ParentEntity.EntityId;
		ProvenanceLink.ParentLane = ParentEntity.Lane;
		ProvenanceLink.ParentRecordKind = ParentEntity.RecordKind;
		ProvenanceLink.ParentReferenceUtc = ParentEntity.ReferenceUtc;
		ProvenanceLink.ParentSourceLabel =
			SourceLabel.IsEmpty() ? ParentEntity.RecordKind : SourceLabel;
		ProvenanceLink.bParentAuthoritative =
			ParentEntity.AuthorityKind == EHyperTwistMemoryAuthorityKind::Authoritative;
		return ProvenanceLink;
	}

	void TryAppendEntityProvenance(
		const TMap<FString, FHyperTwistMemoryEntityDescriptor>& EntitiesById,
		const FString& EntityId,
		const FString& SourceLabel,
		TArray<FHyperTwistMemoryProvenanceLink>& OutProvenanceLinks
	)
	{
		const FHyperTwistMemoryEntityDescriptor* ParentEntity = EntitiesById.Find(EntityId);
		if (ParentEntity == nullptr)
		{
			return;
		}

		const bool bAlreadyLinked = OutProvenanceLinks.ContainsByPredicate(
			[&EntityId](const FHyperTwistMemoryProvenanceLink& ExistingLink)
			{
				return ExistingLink.ParentEntityId == EntityId;
			}
		);
		if (bAlreadyLinked)
		{
			return;
		}

		OutProvenanceLinks.Add(MakeProvenanceLink(*ParentEntity, SourceLabel));
	}

	FHyperTwistMemoryLaneContract MakeLaneContract(
		const EHyperTwistMemoryLane Lane,
		const TCHAR* LaneId,
		const TCHAR* DisplayLabel,
		const EHyperTwistMemoryAuthorityKind AuthorityKind,
		const TCHAR* DefaultSettingsKey,
		const TCHAR* DefaultFeatureGateId,
		const bool bCurrentEvidencePresent,
		const TCHAR* Summary
	)
	{
		FHyperTwistMemoryLaneContract LaneContract;
		LaneContract.Lane = Lane;
		LaneContract.LaneId = LaneId;
		LaneContract.DisplayLabel = DisplayLabel;
		LaneContract.AuthorityKind = AuthorityKind;
		LaneContract.DefaultSettingsKey = DefaultSettingsKey;
		LaneContract.DefaultFeatureGateId = DefaultFeatureGateId;
		LaneContract.bFirstPartyOwned = true;
		LaneContract.bCurrentEvidencePresent = bCurrentEvidencePresent;
		LaneContract.Summary = Summary;
		return LaneContract;
	}

	FHyperTwistMemoryFeatureGate MakeFeatureGate(
		const TCHAR* GateId,
		const TCHAR* SettingsKey,
		const TCHAR* DisplayLabel,
		const EHyperTwistMemoryLane Lane,
		const EHyperTwistMemoryFeatureGateDefaultState DefaultState,
		const bool bUserControllable,
		const bool bDisableAllowed,
		const TCHAR* Summary
	)
	{
		FHyperTwistMemoryFeatureGate FeatureGate;
		FeatureGate.GateId = GateId;
		FeatureGate.SettingsKey = SettingsKey;
		FeatureGate.DisplayLabel = DisplayLabel;
		FeatureGate.Lane = Lane;
		FeatureGate.DefaultState = DefaultState;
		FeatureGate.bUserControllable = bUserControllable;
		FeatureGate.bDisableAllowed = bDisableAllowed;
		FeatureGate.Summary = Summary;
		return FeatureGate;
	}

	FHyperTwistMemorySettingsProfile MakeSettingsProfile(
		const TCHAR* ProfileId,
		const TCHAR* DisplayLabel,
		const EHyperTwistMemoryContextAssemblyProfile ContextAssemblyProfile,
		const TArray<FString>& EnabledFeatureGateIds,
		const TArray<FString>& DisabledFeatureGateIds,
		const TCHAR* Summary
	)
	{
		FHyperTwistMemorySettingsProfile SettingsProfile;
		SettingsProfile.ProfileId = ProfileId;
		SettingsProfile.DisplayLabel = DisplayLabel;
		SettingsProfile.ContextAssemblyProfile = ContextAssemblyProfile;
		SettingsProfile.EnabledFeatureGateIds = EnabledFeatureGateIds;
		SettingsProfile.DisabledFeatureGateIds = DisabledFeatureGateIds;
		SettingsProfile.Summary = Summary;
		return SettingsProfile;
	}

	void AddEntity(
		FHyperTwistMemoryLedgerState& LedgerState,
		TMap<FString, FHyperTwistMemoryEntityDescriptor>& EntitiesById,
		const FHyperTwistMemoryEntityDescriptor& Entity
	)
	{
		if (!Entity.IsStructurallyValid() || EntitiesById.Contains(Entity.EntityId))
		{
			return;
		}

		LedgerState.Entities.Add(Entity);
		EntitiesById.Add(Entity.EntityId, Entity);

		switch (Entity.AuthorityKind)
		{
		case EHyperTwistMemoryAuthorityKind::Authoritative:
			++LedgerState.AuthoritativeEntityCount;
			break;
		case EHyperTwistMemoryAuthorityKind::SemiAuthoritative:
			++LedgerState.SemiAuthoritativeEntityCount;
			break;
		case EHyperTwistMemoryAuthorityKind::DerivedOnly:
			++LedgerState.DerivedEntityCount;
			break;
		default:
			break;
		}
	}

	void AddUniqueString(TArray<FString>& Values, const FString& Value)
	{
		if (!Value.IsEmpty() && !Values.Contains(Value))
		{
			Values.Add(Value);
		}
	}

	void AddChronicleEvent(
		FHyperTwistMemoryChronicleContinuityState& ChronicleContinuityState,
		const FHyperTwistMemoryChronicleEventEntry& ChronicleEvent
	)
	{
		if (!ChronicleEvent.IsStructurallyValid()
			|| ChronicleContinuityState.ChronicleEvents.ContainsByPredicate(
				[&ChronicleEvent](const FHyperTwistMemoryChronicleEventEntry& ExistingEvent)
				{
					return ExistingEvent.EventId == ChronicleEvent.EventId;
				}))
		{
			return;
		}

		ChronicleContinuityState.ChronicleEvents.Add(ChronicleEvent);
	}

	void AddSessionGroup(
		FHyperTwistMemoryChronicleContinuityState& ChronicleContinuityState,
		const FHyperTwistMemorySessionGroup& SessionGroup
	)
	{
		if (!SessionGroup.IsStructurallyValid()
			|| ChronicleContinuityState.SessionGroups.ContainsByPredicate(
				[&SessionGroup](const FHyperTwistMemorySessionGroup& ExistingGroup)
				{
					return ExistingGroup.GroupId == SessionGroup.GroupId;
				}))
		{
			return;
		}

		ChronicleContinuityState.SessionGroups.Add(SessionGroup);
	}

	void AddResumePack(
		FHyperTwistMemoryChronicleContinuityState& ChronicleContinuityState,
		const FHyperTwistMemoryResumePack& ResumePack
	)
	{
		if (!ResumePack.IsStructurallyValid()
			|| ChronicleContinuityState.ResumePacks.ContainsByPredicate(
				[&ResumePack](const FHyperTwistMemoryResumePack& ExistingPack)
				{
					return ExistingPack.PackId == ResumePack.PackId;
				}))
		{
			return;
		}

		ChronicleContinuityState.ResumePacks.Add(ResumePack);
	}

	void AddContinuityGuard(
		FHyperTwistMemoryChronicleContinuityState& ChronicleContinuityState,
		const FHyperTwistMemoryContinuityGuard& ContinuityGuard
	)
	{
		if (!ContinuityGuard.IsStructurallyValid()
			|| ChronicleContinuityState.ContinuityGuards.ContainsByPredicate(
				[&ContinuityGuard](const FHyperTwistMemoryContinuityGuard& ExistingGuard)
				{
					return ExistingGuard.GuardId == ContinuityGuard.GuardId;
				}))
		{
			return;
		}

		ChronicleContinuityState.ContinuityGuards.Add(ContinuityGuard);
	}

	struct FHyperTwistMemoryRecallCandidate
	{
		FString MatchId;
		FString MatchKind;
		FString Headline;
		FString UserId;
		FString DeckId;
		FString SourceEntityId;
		FString SourceRecordKind;
		FString SourceRecordId;
		FString ReferenceUtc;
		EHyperTwistMemoryLane Lane = EHyperTwistMemoryLane::None;
		EHyperTwistMemoryAuthorityKind AuthorityKind = EHyperTwistMemoryAuthorityKind::None;
		FString SearchableText;
		TArray<FHyperTwistMemoryProvenanceLink> ProvenanceLinks;

		bool IsStructurallyValid() const
		{
			return !MatchId.IsEmpty()
				&& !MatchKind.IsEmpty()
				&& !Headline.IsEmpty()
				&& !UserId.IsEmpty()
				&& !SourceEntityId.IsEmpty()
				&& !SourceRecordKind.IsEmpty()
				&& !SourceRecordId.IsEmpty()
				&& !ReferenceUtc.IsEmpty()
				&& Lane != EHyperTwistMemoryLane::None
				&& AuthorityKind != EHyperTwistMemoryAuthorityKind::None;
		}
	};

	void AddRecallCandidate(
		TArray<FHyperTwistMemoryRecallCandidate>& Candidates,
		const FHyperTwistMemoryRecallCandidate& Candidate
	)
	{
		if (!Candidate.IsStructurallyValid()
			|| Candidates.ContainsByPredicate(
				[&Candidate](const FHyperTwistMemoryRecallCandidate& ExistingCandidate)
				{
					return ExistingCandidate.MatchId == Candidate.MatchId;
				}))
		{
			return;
		}

		Candidates.Add(Candidate);
	}

	void AddUniqueProvenanceLink(
		TArray<FHyperTwistMemoryProvenanceLink>& ProvenanceLinks,
		const FHyperTwistMemoryProvenanceLink& ProvenanceLink
	)
	{
		if (!ProvenanceLink.IsStructurallyValid()
			|| ProvenanceLinks.ContainsByPredicate(
				[&ProvenanceLink](const FHyperTwistMemoryProvenanceLink& ExistingLink)
				{
					return ExistingLink.ParentEntityId == ProvenanceLink.ParentEntityId
						&& ExistingLink.ParentSourceLabel == ProvenanceLink.ParentSourceLabel;
				}))
		{
			return;
		}

		ProvenanceLinks.Add(ProvenanceLink);
	}

	void AddSharedContextProjection(
		FHyperTwistMemoryRecallSharedContextState& RecallState,
		const FHyperTwistMemorySharedContextProjection& Projection
	)
	{
		if (!Projection.IsStructurallyValid()
			|| RecallState.SharedContextProjections.ContainsByPredicate(
				[&Projection](const FHyperTwistMemorySharedContextProjection& ExistingProjection)
				{
					return ExistingProjection.ProjectionId == Projection.ProjectionId;
				}))
		{
			return;
		}

		RecallState.SharedContextProjections.Add(Projection);
	}

	FString NormalizeSearchText(const FString& Input)
	{
		FString Normalized;
		Normalized.Reserve(Input.Len());
		bool bLastWasSpace = true;
		for (const TCHAR Character : Input)
		{
			if (FChar::IsAlnum(Character))
			{
				Normalized.AppendChar(FChar::ToLower(Character));
				bLastWasSpace = false;
			}
			else if (!bLastWasSpace)
			{
				Normalized.AppendChar(TEXT(' '));
				bLastWasSpace = true;
			}
		}

		return Normalized.TrimStartAndEnd();
	}

	TArray<FString> TokenizeSearchText(const FString& Input)
	{
		TArray<FString> Tokens;
		NormalizeSearchText(Input).ParseIntoArrayWS(Tokens);

		TArray<FString> UniqueTokens;
		for (const FString& Token : Tokens)
		{
			AddUniqueString(UniqueTokens, Token);
		}

		return UniqueTokens;
	}

	void AppendSearchFragment(FString& SearchableText, const FString& Fragment)
	{
		const FString TrimmedFragment = Fragment.TrimStartAndEnd();
		if (TrimmedFragment.IsEmpty())
		{
			return;
		}

		if (!SearchableText.IsEmpty())
		{
			SearchableText.AppendChar(TEXT(' '));
		}

		SearchableText += TrimmedFragment;
	}

	bool HasAuthoritativeProvenance(const TArray<FHyperTwistMemoryProvenanceLink>& ProvenanceLinks)
	{
		return ProvenanceLinks.ContainsByPredicate(
			[](const FHyperTwistMemoryProvenanceLink& ProvenanceLink)
			{
				return ProvenanceLink.bParentAuthoritative;
			}
		);
	}

	bool IsFeatureGateEnabledForProfile(
		const FString& GateId,
		const FHyperTwistMemoryFeatureGate& FeatureGate,
		const FHyperTwistMemorySettingsProfile& EconomicRetentionProfile,
		const FHyperTwistMemorySettingsProfile& MaxRetentionProfile,
		const EHyperTwistMemoryContextAssemblyProfile ContextAssemblyProfile
	)
	{
		const FHyperTwistMemorySettingsProfile* ActiveProfile = nullptr;
		switch (ContextAssemblyProfile)
		{
		case EHyperTwistMemoryContextAssemblyProfile::EconomicRetentionMode:
			ActiveProfile = &EconomicRetentionProfile;
			break;
		case EHyperTwistMemoryContextAssemblyProfile::MaxRetentionMode:
			ActiveProfile = &MaxRetentionProfile;
			break;
		default:
			break;
		}

		if (ActiveProfile == nullptr)
		{
			return FeatureGate.DefaultState !=
				EHyperTwistMemoryFeatureGateDefaultState::DisabledByDefault;
		}

		if (ActiveProfile->DisabledFeatureGateIds.Contains(GateId))
		{
			return false;
		}
		if (ActiveProfile->EnabledFeatureGateIds.Contains(GateId))
		{
			return true;
		}

		return FeatureGate.DefaultState !=
			EHyperTwistMemoryFeatureGateDefaultState::DisabledByDefault;
	}

	void AppendSourceEntityIdsFromProvenance(
		TArray<FString>& OutSourceEntityIds,
		const TArray<FHyperTwistMemoryProvenanceLink>& ProvenanceLinks
	)
	{
		for (const FHyperTwistMemoryProvenanceLink& ProvenanceLink : ProvenanceLinks)
		{
			AddUniqueString(OutSourceEntityIds, ProvenanceLink.ParentEntityId);
		}
	}

	int32 ResolveLanePriority(const EHyperTwistMemoryLane Lane)
	{
		switch (Lane)
		{
		case EHyperTwistMemoryLane::RecallRetrieval:
			return 40;
		case EHyperTwistMemoryLane::SharedCoordination:
			return 35;
		case EHyperTwistMemoryLane::CognitiveConsolidated:
			return 30;
		case EHyperTwistMemoryLane::ContinuityResume:
			return 25;
		case EHyperTwistMemoryLane::ChronicleCapture:
			return 20;
		case EHyperTwistMemoryLane::ProceduralWorkflow:
			return 15;
		default:
			return 0;
		}
	}

	FString ResolveSessionGroupSourceRecordKind(const FHyperTwistMemorySessionGroup& SessionGroup)
	{
		if (SessionGroup.GroupKind == TEXT("training-session"))
		{
			return TEXT("training-run-record");
		}
		if (SessionGroup.GroupKind == TEXT("review-plan"))
		{
			return TEXT("training-review-plan");
		}
		if (SessionGroup.GroupKind == TEXT("coach-session-queue"))
		{
			return TEXT("coach-session-queue");
		}

		return SessionGroup.GroupKind;
	}

	FString ResolveResumePackSourceRecordKind(const FHyperTwistMemoryResumePack& ResumePack)
	{
		if (ResumePack.PackKind == TEXT("training-session-resume"))
		{
			return TEXT("training-run-record");
		}
		if (ResumePack.PackKind == TEXT("review-plan-resume"))
		{
			return TEXT("training-review-plan");
		}
		if (ResumePack.PackKind == TEXT("coach-session-queue-resume"))
		{
			return TEXT("coach-session-queue");
		}

		return ResumePack.PackKind;
	}

	FString ResolveSessionGroupSourceEntityId(const FHyperTwistMemorySessionGroup& SessionGroup)
	{
		if (SessionGroup.GroupKind == TEXT("training-session"))
		{
			return FString::Printf(
				TEXT("memory-entity/chronicle/run-record/%s"),
				*SessionGroup.RootTrainingSessionId
			);
		}
		if (SessionGroup.GroupKind == TEXT("review-plan"))
		{
			return FString::Printf(
				TEXT("memory-entity/workflow/review-plan/%s"),
				*SessionGroup.RootReviewPlanId
			);
		}
		if (SessionGroup.GroupKind == TEXT("coach-session-queue"))
		{
			return FString::Printf(
				TEXT("memory-entity/workflow/coach-session-queue/%s"),
				*SessionGroup.RootQueueId
			);
		}

		return FString();
	}

	FString ResolveResumePackSourceEntityId(const FHyperTwistMemoryResumePack& ResumePack)
	{
		if (ResumePack.PackKind == TEXT("training-session-resume"))
		{
			return FString::Printf(
				TEXT("memory-entity/chronicle/run-record/%s"),
				*ResumePack.ResumeTargetId
			);
		}
		if (ResumePack.PackKind == TEXT("review-plan-resume"))
		{
			return FString::Printf(
				TEXT("memory-entity/workflow/review-plan/%s"),
				*ResumePack.ResumeTargetId
			);
		}
		if (ResumePack.PackKind == TEXT("coach-session-queue-resume"))
		{
			return FString::Printf(
				TEXT("memory-entity/workflow/coach-session-queue/%s"),
				*ResumePack.ResumeTargetId
			);
		}

		return FString();
	}

	void CollectEntityLineage(
		const TMap<FString, FHyperTwistMemoryEntityDescriptor>& EntitiesById,
		const FString& EntityId,
		TSet<FString>& VisitedEntityIds,
		TArray<FString>& OutLineageEntityIds,
		TArray<FString>& OutSourceLabels,
		bool& bOutHasAuthoritativeLineage
	)
	{
		if (EntityId.IsEmpty() || VisitedEntityIds.Contains(EntityId))
		{
			return;
		}

		VisitedEntityIds.Add(EntityId);

		const FHyperTwistMemoryEntityDescriptor* Entity = EntitiesById.Find(EntityId);
		if (Entity == nullptr)
		{
			return;
		}

		AddUniqueString(OutLineageEntityIds, EntityId);
		if (Entity->AuthorityKind == EHyperTwistMemoryAuthorityKind::Authoritative)
		{
			bOutHasAuthoritativeLineage = true;
		}

		for (const FHyperTwistMemoryProvenanceLink& ProvenanceLink : Entity->ProvenanceLinks)
		{
			AddUniqueString(OutSourceLabels, ProvenanceLink.ParentSourceLabel);
			if (ProvenanceLink.bParentAuthoritative)
			{
				bOutHasAuthoritativeLineage = true;
			}

			CollectEntityLineage(
				EntitiesById,
				ProvenanceLink.ParentEntityId,
				VisitedEntityIds,
				OutLineageEntityIds,
				OutSourceLabels,
				bOutHasAuthoritativeLineage
			);
		}
	}

	int32 ScoreRecallCandidate(
		const FHyperTwistMemoryRecallCandidate& Candidate,
		const TArray<FString>& QueryTokens,
		TArray<FString>& OutMatchedTokens
	)
	{
		OutMatchedTokens.Reset();
		const FString NormalizedSearchableText =
			NormalizeSearchText(Candidate.SearchableText);

		for (const FString& QueryToken : QueryTokens)
		{
			if (!QueryToken.IsEmpty() && NormalizedSearchableText.Contains(QueryToken))
			{
				AddUniqueString(OutMatchedTokens, QueryToken);
			}
		}

		if (OutMatchedTokens.Num() == 0)
		{
			return 0;
		}

		int32 Score = OutMatchedTokens.Num() * 100 + ResolveLanePriority(Candidate.Lane);
		if (Candidate.MatchKind == TEXT("remember-focus"))
		{
			Score += 25;
		}
		if (Candidate.AuthorityKind == EHyperTwistMemoryAuthorityKind::Authoritative)
		{
			Score += 10;
		}
		if (HasAuthoritativeProvenance(Candidate.ProvenanceLinks))
		{
			Score += 5;
		}

		return Score;
	}

	FHyperTwistMemorySharedContextRule MakeSharedContextRule(
		const TCHAR* RuleId,
		const TCHAR* ContextId,
		const TCHAR* DisplayLabel,
		const EHyperTwistMemoryLane SourceLane,
		const TArray<FString>& AllowedRecordKinds,
		const TArray<FString>& AllowedTargetSurfaces,
		const bool bSessionLocalOnly,
		const bool bRevocable,
		const bool bRequiresAuthoritativeProvenance,
		const TCHAR* Summary
	)
	{
		FHyperTwistMemorySharedContextRule Rule;
		Rule.RuleId = RuleId;
		Rule.ContextId = ContextId;
		Rule.DisplayLabel = DisplayLabel;
		Rule.SourceLane = SourceLane;
		Rule.AllowedRecordKinds = AllowedRecordKinds;
		Rule.AllowedTargetSurfaces = AllowedTargetSurfaces;
		Rule.bSessionLocalOnly = bSessionLocalOnly;
		Rule.bRevocable = bRevocable;
		Rule.bRequiresAuthoritativeProvenance = bRequiresAuthoritativeProvenance;
		Rule.Summary = Summary;
		return Rule;
	}

	FString ResolveRunRecordReferenceUtc(
		const FHyperTwistTrainingRunRecord& RunRecord,
		const FString& ResolvedReferenceUtc
	)
	{
		if (!RunRecord.LastUpdatedAtUtc.IsEmpty())
		{
			return RunRecord.LastUpdatedAtUtc;
		}

		if (!RunRecord.Session.EndedAtUtc.IsEmpty())
		{
			return RunRecord.Session.EndedAtUtc;
		}

		if (!RunRecord.Summary.LastCompletedAtUtc.IsEmpty())
		{
			return RunRecord.Summary.LastCompletedAtUtc;
		}

		if (!RunRecord.Session.StartedAtUtc.IsEmpty())
		{
			return RunRecord.Session.StartedAtUtc;
		}

		return ResolvedReferenceUtc;
	}

	FString ResolveReviewPlanReferenceUtc(
		const FHyperTwistTrainingReviewPlanState& ReviewPlan,
		const FString& ResolvedReferenceUtc
	)
	{
		if (!ReviewPlan.CompletedAtUtc.IsEmpty())
		{
			return ReviewPlan.CompletedAtUtc;
		}

		if (!ReviewPlan.StartedAtUtc.IsEmpty())
		{
			return ReviewPlan.StartedAtUtc;
		}

		if (!ReviewPlan.CreatedAtUtc.IsEmpty())
		{
			return ReviewPlan.CreatedAtUtc;
		}

		if (!ReviewPlan.ReferenceUtc.IsEmpty())
		{
			return ReviewPlan.ReferenceUtc;
		}

		return ResolvedReferenceUtc;
	}

	FString ResolveQueueStateReferenceUtc(
		const FHyperTwistTrainingCoachSessionQueueState& QueueState,
		const FString& ResolvedReferenceUtc
	)
	{
		if (!QueueState.LastUpdatedAtUtc.IsEmpty())
		{
			return QueueState.LastUpdatedAtUtc;
		}

		if (!QueueState.ReferenceUtc.IsEmpty())
		{
			return QueueState.ReferenceUtc;
		}

		return ResolvedReferenceUtc;
	}

	bool HasOpenTrainingSession(const FHyperTwistTrainingRunRecord& RunRecord)
	{
		return !RunRecord.bCompleted
			|| RunRecord.Session.SessionState != EHyperTwistTrainingSessionState::Completed
			|| RunRecord.RemainingCaseIds.Num() > 0;
	}

	bool HasOpenReviewPlan(const FHyperTwistTrainingReviewPlanState& ReviewPlan)
	{
		return !ReviewPlan.bCompleted;
	}

	bool IsQueueEntryOpen(const EHyperTwistTrainingCoachSessionQueueEntryState EntryState)
	{
		return EntryState == EHyperTwistTrainingCoachSessionQueueEntryState::Pending
			|| EntryState == EHyperTwistTrainingCoachSessionQueueEntryState::Deferred
			|| EntryState == EHyperTwistTrainingCoachSessionQueueEntryState::Ready
			|| EntryState == EHyperTwistTrainingCoachSessionQueueEntryState::InProgress;
	}

	bool HasOpenQueue(const FHyperTwistTrainingCoachSessionQueueState& QueueState)
	{
		return QueueState.PendingEntryCount > 0
			|| QueueState.DeferredEntryCount > 0
			|| QueueState.ReadyEntryCount > 0
			|| QueueState.InProgressEntryCount > 0;
	}

	int32 CountOpenReviewEntries(const FHyperTwistTrainingReviewPlanState& ReviewPlan)
	{
		int32 OpenEntryCount = 0;
		for (const FHyperTwistTrainingReviewPlanEntry& Entry : ReviewPlan.Entries)
		{
			if (Entry.EntryState != EHyperTwistTrainingReviewPlanEntryState::Completed
				&& Entry.EntryState != EHyperTwistTrainingReviewPlanEntryState::Skipped)
			{
				++OpenEntryCount;
			}
		}

		return OpenEntryCount;
	}

	int32 CountOpenQueueEntries(const FHyperTwistTrainingCoachSessionQueueState& QueueState)
	{
		int32 OpenEntryCount = 0;
		for (const FHyperTwistTrainingCoachSessionQueueStateEntry& Entry : QueueState.Entries)
		{
			if (IsQueueEntryOpen(Entry.EntryState))
			{
				++OpenEntryCount;
			}
		}

		return OpenEntryCount;
	}

	TArray<FString> CollectRunFocusCaseIds(const FHyperTwistTrainingRunRecord& RunRecord)
	{
		TArray<FString> FocusCaseIds;
		for (const FString& RemainingCaseId : RunRecord.RemainingCaseIds)
		{
			AddUniqueString(FocusCaseIds, RemainingCaseId);
		}

		for (const FHyperTwistTrainingAttempt& Attempt : RunRecord.Attempts)
		{
			AddUniqueString(FocusCaseIds, Attempt.CaseId);
		}

		for (const FHyperTwistTrainingReviewHistoryEntry& ReviewEntry : RunRecord.ReviewHistory)
		{
			AddUniqueString(FocusCaseIds, ReviewEntry.CaseId);
		}

		if (FocusCaseIds.Num() == 0)
		{
			AddUniqueString(FocusCaseIds, RunRecord.Session.CurrentCaseId);
		}

		return FocusCaseIds;
	}

	TArray<FString> CollectReviewPlanFocusCaseIds(
		const FHyperTwistTrainingReviewPlanState& ReviewPlan,
		const bool bOpenOnly
	)
	{
		TArray<FString> FocusCaseIds;
		for (const FHyperTwistTrainingReviewPlanEntry& Entry : ReviewPlan.Entries)
		{
			if (bOpenOnly
				&& Entry.EntryState == EHyperTwistTrainingReviewPlanEntryState::Completed)
			{
				continue;
			}

			AddUniqueString(FocusCaseIds, Entry.CaseId);
		}

		return FocusCaseIds;
	}

	TArray<FString> CollectQueueFocusCaseIds(
		const FHyperTwistTrainingCoachSessionQueueState& QueueState,
		const bool bOpenOnly
	)
	{
		TArray<FString> FocusCaseIds;
		for (const FHyperTwistTrainingCoachSessionQueueStateEntry& Entry : QueueState.Entries)
		{
			if (bOpenOnly && !IsQueueEntryOpen(Entry.EntryState))
			{
				continue;
			}

			for (const FString& FocusCaseId : Entry.FocusCaseIds)
			{
				AddUniqueString(FocusCaseIds, FocusCaseId);
			}
		}

		return FocusCaseIds;
	}

	FString ResolveQueueHistoryEventKindToken(
		const EHyperTwistTrainingCoachSessionQueueEventKind EventKind
	)
	{
		switch (EventKind)
		{
		case EHyperTwistTrainingCoachSessionQueueEventKind::Queued:
			return TEXT("queued");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Ready:
			return TEXT("ready");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Started:
			return TEXT("started");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Deferred:
			return TEXT("deferred");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Promoted:
			return TEXT("promoted");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Completed:
			return TEXT("completed");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Skipped:
			return TEXT("skipped");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Expired:
			return TEXT("expired");
		default:
			return TEXT("unknown");
		}
	}

	FString ResolveQueueHistoryEventLabel(
		const EHyperTwistTrainingCoachSessionQueueEventKind EventKind
	)
	{
		switch (EventKind)
		{
		case EHyperTwistTrainingCoachSessionQueueEventKind::Queued:
			return TEXT("Coach Session Queued");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Ready:
			return TEXT("Coach Session Ready");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Started:
			return TEXT("Coach Session Started");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Deferred:
			return TEXT("Coach Session Deferred");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Promoted:
			return TEXT("Coach Session Promoted");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Completed:
			return TEXT("Coach Session Completed");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Skipped:
			return TEXT("Coach Session Skipped");
		case EHyperTwistTrainingCoachSessionQueueEventKind::Expired:
			return TEXT("Coach Session Expired");
		default:
			return TEXT("Coach Session Event");
		}
	}
}

FHyperTwistMemoryLedgerState UHyperTwistMemoryCoreLibrary::DeriveMemoryLedgerState(
	const FHyperTwistTrainingRepositoryState& RepositoryState,
	const FString& UserId,
	const FString& ReferenceUtc
)
{
	FHyperTwistMemoryLedgerState LedgerState;
	if (UserId.IsEmpty())
	{
		return LedgerState;
	}

	const FString ResolvedReferenceUtc =
		HyperTwistMemoryCoreLibraryInternal::ResolveReferenceUtc(ReferenceUtc);
	LedgerState.UserId = UserId;
	LedgerState.ReferenceUtc = ResolvedReferenceUtc;

	LedgerState.LaneContracts = {
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::IdentityPolicy,
			TEXT("memory-lane/identity-policy"),
			TEXT("Preferences"),
			EHyperTwistMemoryAuthorityKind::Authoritative,
			TEXT("memory.identity_policy.enabled"),
			TEXT("memory-gate/identity-policy"),
			true,
			TEXT("First-party trust, consent, and retention policy surfaces.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::WorkspaceRecall,
			TEXT("memory-lane/workspace-recall"),
			TEXT("Workspace Recall"),
			EHyperTwistMemoryAuthorityKind::Authoritative,
			TEXT("memory.workspace_recall.enabled"),
			TEXT("memory-gate/workspace-recall"),
			true,
			TEXT("First-party cockpit state, focus anchors, and recent context.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::ChronicleCapture,
			TEXT("memory-lane/chronicle-capture"),
			TEXT("Training Chronicle"),
			EHyperTwistMemoryAuthorityKind::Authoritative,
			TEXT("memory.chronicle_capture.enabled"),
			TEXT("memory-gate/chronicle-capture"),
			true,
			TEXT("Append-only training and runtime event evidence.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::ContinuityResume,
			TEXT("memory-lane/continuity-resume"),
			TEXT("Session Continuity"),
			EHyperTwistMemoryAuthorityKind::Authoritative,
			TEXT("memory.continuity_resume.enabled"),
			TEXT("memory-gate/continuity-resume"),
			true,
			TEXT("First-party session continuity and resume pointers.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::SharedCoordination,
			TEXT("memory-lane/shared-coordination"),
			TEXT("Shared Context"),
			EHyperTwistMemoryAuthorityKind::SemiAuthoritative,
			TEXT("memory.shared_coordination.enabled"),
			TEXT("memory-gate/shared-coordination"),
			true,
			TEXT("Scoped shared context across coach, replay, and sidecar flows.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::RecallRetrieval,
			TEXT("memory-lane/recall-retrieval"),
			TEXT("Smart Recall"),
			EHyperTwistMemoryAuthorityKind::SemiAuthoritative,
			TEXT("memory.recall_retrieval.enabled"),
			TEXT("memory-gate/recall-retrieval"),
			true,
			TEXT("Rebuildable retrieval and history-search indexes.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::CognitiveConsolidated,
			TEXT("memory-lane/cognitive-consolidated"),
			TEXT("Coach Memory"),
			EHyperTwistMemoryAuthorityKind::SemiAuthoritative,
			TEXT("memory.cognitive_consolidated.enabled"),
			TEXT("memory-gate/cognitive-consolidated"),
			true,
			TEXT("Provenance-backed long-term training state and coach follow-up signals.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::KnowledgeWiki,
			TEXT("memory-lane/knowledge-wiki"),
			TEXT("Training Atlas"),
			EHyperTwistMemoryAuthorityKind::Authoritative,
			TEXT("memory.knowledge_wiki.enabled"),
			TEXT("memory-gate/knowledge-wiki"),
			true,
			TEXT("Browsable and reviewable curriculum and knowledge objects.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::UserNotes,
			TEXT("memory-lane/user-notes"),
			TEXT("Training Notes"),
			EHyperTwistMemoryAuthorityKind::Authoritative,
			TEXT("memory.user_notes.enabled"),
			TEXT("memory-gate/user-notes"),
			false,
			TEXT("User-authored note content remains separate and explicitly owned.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::ProvenanceLedger,
			TEXT("memory-lane/provenance-ledger"),
			TEXT("Memory Ledger"),
			EHyperTwistMemoryAuthorityKind::Authoritative,
			TEXT("memory.provenance_ledger.enabled"),
			TEXT("memory-gate/provenance-ledger"),
			true,
			TEXT("Lineage and trust ledger for every non-raw memory surface.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::DerivedCompacted,
			TEXT("memory-lane/derived-compacted"),
			TEXT("Compact Views"),
			EHyperTwistMemoryAuthorityKind::DerivedOnly,
			TEXT("memory.derived_compacted.enabled"),
			TEXT("memory-gate/derived-compacted"),
			true,
			TEXT("Discardable compact summaries and reduced context packets.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeLaneContract(
			EHyperTwistMemoryLane::ProceduralWorkflow,
			TEXT("memory-lane/procedural-workflow"),
			TEXT("Workflow Memory"),
			EHyperTwistMemoryAuthorityKind::Authoritative,
			TEXT("memory.procedural_workflow.enabled"),
			TEXT("memory-gate/procedural-workflow"),
			true,
			TEXT("Durable templates, drill workflows, queues, and follow-up routines.")
		)
	};

	LedgerState.FeatureGates = {
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/identity-policy"),
			TEXT("memory.identity_policy.enabled"),
			TEXT("Identity Policy"),
			EHyperTwistMemoryLane::IdentityPolicy,
			EHyperTwistMemoryFeatureGateDefaultState::RequiredEnabled,
			false,
			false,
			TEXT("Keep consent, retention, and provider policy first-party owned.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/workspace-recall"),
			TEXT("memory.workspace_recall.enabled"),
			TEXT("Workspace Recall"),
			EHyperTwistMemoryLane::WorkspaceRecall,
			EHyperTwistMemoryFeatureGateDefaultState::RequiredEnabled,
			false,
			false,
			TEXT("Preserve cockpit state and focus anchors as first-party authority.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/chronicle-capture"),
			TEXT("memory.chronicle_capture.enabled"),
			TEXT("Chronicle Capture"),
			EHyperTwistMemoryLane::ChronicleCapture,
			EHyperTwistMemoryFeatureGateDefaultState::RequiredEnabled,
			false,
			false,
			TEXT("Keep append-only chronicle evidence active for later provenance.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/continuity-resume"),
			TEXT("memory.continuity_resume.enabled"),
			TEXT("Continuity Resume"),
			EHyperTwistMemoryLane::ContinuityResume,
			EHyperTwistMemoryFeatureGateDefaultState::RequiredEnabled,
			false,
			false,
			TEXT("Keep resume pointers and active continuity fragments available.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/shared-coordination"),
			TEXT("memory.shared_coordination.enabled"),
			TEXT("Shared Coordination"),
			EHyperTwistMemoryLane::SharedCoordination,
			EHyperTwistMemoryFeatureGateDefaultState::EnabledByDefault,
			true,
			true,
			TEXT("Allow revocable shared context without promoting it to durable cognition.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/recall-retrieval"),
			TEXT("memory.recall_retrieval.enabled"),
			TEXT("Recall Retrieval"),
			EHyperTwistMemoryLane::RecallRetrieval,
			EHyperTwistMemoryFeatureGateDefaultState::EnabledByDefault,
			true,
			true,
			TEXT("Permit rebuildable history search and retrieval indexes.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/cognitive-consolidated"),
			TEXT("memory.cognitive_consolidated.enabled"),
			TEXT("Cognitive Consolidated"),
			EHyperTwistMemoryLane::CognitiveConsolidated,
			EHyperTwistMemoryFeatureGateDefaultState::EnabledByDefault,
			true,
			true,
			TEXT("Expose provenance-backed coach-memory and follow-up consolidation.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/knowledge-wiki"),
			TEXT("memory.knowledge_wiki.enabled"),
			TEXT("Knowledge Wiki"),
			EHyperTwistMemoryLane::KnowledgeWiki,
			EHyperTwistMemoryFeatureGateDefaultState::EnabledByDefault,
			true,
			true,
			TEXT("Keep curated knowledge available without promoting raw chronicle data.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/user-notes"),
			TEXT("memory.user_notes.enabled"),
			TEXT("User Notes"),
			EHyperTwistMemoryLane::UserNotes,
			EHyperTwistMemoryFeatureGateDefaultState::DisabledByDefault,
			true,
			true,
			TEXT("Do not auto-enable note capture until explicit user ownership is active.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/provenance-ledger"),
			TEXT("memory.provenance_ledger.enabled"),
			TEXT("Provenance Ledger"),
			EHyperTwistMemoryLane::ProvenanceLedger,
			EHyperTwistMemoryFeatureGateDefaultState::RequiredEnabled,
			false,
			false,
			TEXT("Require lineage preservation for every non-raw memory surface.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/derived-compacted"),
			TEXT("memory.derived_compacted.enabled"),
			TEXT("Derived Compacted"),
			EHyperTwistMemoryLane::DerivedCompacted,
			EHyperTwistMemoryFeatureGateDefaultState::EnabledByDefault,
			true,
			true,
			TEXT("Allow discardable compact views and reduced context packets.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeFeatureGate(
			TEXT("memory-gate/procedural-workflow"),
			TEXT("memory.procedural_workflow.enabled"),
			TEXT("Procedural Workflow"),
			EHyperTwistMemoryLane::ProceduralWorkflow,
			EHyperTwistMemoryFeatureGateDefaultState::RequiredEnabled,
			false,
			false,
			TEXT("Keep templates, queues, and follow-up workflows first-party owned.")
		)
	};

	LedgerState.EconomicRetentionProfile =
		HyperTwistMemoryCoreLibraryInternal::MakeSettingsProfile(
			TEXT("memory-profile/economic-retention"),
			TEXT("Economic-Retention Mode"),
			EHyperTwistMemoryContextAssemblyProfile::EconomicRetentionMode,
			{
				TEXT("memory-gate/identity-policy"),
				TEXT("memory-gate/workspace-recall"),
				TEXT("memory-gate/chronicle-capture"),
				TEXT("memory-gate/continuity-resume"),
				TEXT("memory-gate/knowledge-wiki"),
				TEXT("memory-gate/provenance-ledger"),
				TEXT("memory-gate/procedural-workflow")
			},
			{
				TEXT("memory-gate/shared-coordination"),
				TEXT("memory-gate/recall-retrieval"),
				TEXT("memory-gate/cognitive-consolidated"),
				TEXT("memory-gate/user-notes"),
				TEXT("memory-gate/derived-compacted")
			},
			TEXT("Minimum active memory posture while preserving first-party contracts and provenance.")
		);
	LedgerState.MaxRetentionProfile =
		HyperTwistMemoryCoreLibraryInternal::MakeSettingsProfile(
			TEXT("memory-profile/max-retention"),
			TEXT("Max-Retention Mode"),
			EHyperTwistMemoryContextAssemblyProfile::MaxRetentionMode,
			{
				TEXT("memory-gate/identity-policy"),
				TEXT("memory-gate/workspace-recall"),
				TEXT("memory-gate/chronicle-capture"),
				TEXT("memory-gate/continuity-resume"),
				TEXT("memory-gate/shared-coordination"),
				TEXT("memory-gate/recall-retrieval"),
				TEXT("memory-gate/cognitive-consolidated"),
				TEXT("memory-gate/knowledge-wiki"),
				TEXT("memory-gate/provenance-ledger"),
				TEXT("memory-gate/derived-compacted"),
				TEXT("memory-gate/procedural-workflow")
			},
			{
				TEXT("memory-gate/user-notes")
			},
			TEXT("High-retention posture for broader context assembly before uncertainty becomes dangerous.")
		);

	TMap<FString, FHyperTwistMemoryEntityDescriptor> EntitiesById;
	TMap<FString, FString> RunRecordEntityIdByDeckCaseKey;
	TMap<FString, FString> LearnerStateEntityIdByDeckCaseKey;
	TMap<FString, FString> ReviewPlanEntityIdByPlanId;
	TMap<FString, FString> CoachPlanEntityIdByPlanId;
	TMap<FString, FString> QueueEntityIdByQueueId;
	FString PolicyEntityId;
	FString LedgerContractEntityId;
	FString FirstRunRecordEntityId;
	FString FirstLearnerStateEntityId;
	FString FirstReviewPlanEntityId;
	FString FirstCoachPlanEntityId;
	FString FirstQueueEntityId;
	FString ReviewProgramEntityId;
	FString CoachMemorySnapshotEntityId;
	FString LearnerProfileEntityId;

	{
		FHyperTwistMemoryEntityDescriptor PolicyEntity;
		PolicyEntity.EntityId = FString::Printf(
			TEXT("memory-entity/policy/current/%s"),
			*UserId
		);
		PolicyEntity.RecordKind = TEXT("memory-policy-profile");
		PolicyEntity.DisplayLabel = TEXT("Memory Policy Profile");
		PolicyEntity.UserId = UserId;
		PolicyEntity.ReferenceUtc = ResolvedReferenceUtc;
		PolicyEntity.Lane = EHyperTwistMemoryLane::IdentityPolicy;
		PolicyEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::Authoritative;
		HyperTwistMemoryCoreLibraryInternal::AddEntity(LedgerState, EntitiesById, PolicyEntity);
		PolicyEntityId = PolicyEntity.EntityId;
	}

	{
		FHyperTwistMemoryEntityDescriptor LedgerContractEntity;
		LedgerContractEntity.EntityId = FString::Printf(
			TEXT("memory-entity/provenance/ledger/current/%s"),
			*UserId
		);
		LedgerContractEntity.RecordKind = TEXT("memory-ledger-contract");
		LedgerContractEntity.DisplayLabel = TEXT("Memory Ledger Contract");
		LedgerContractEntity.UserId = UserId;
		LedgerContractEntity.ReferenceUtc = ResolvedReferenceUtc;
		LedgerContractEntity.Lane = EHyperTwistMemoryLane::ProvenanceLedger;
		LedgerContractEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::Authoritative;
		HyperTwistMemoryCoreLibraryInternal::AddEntity(LedgerState, EntitiesById, LedgerContractEntity);
		LedgerContractEntityId = LedgerContractEntity.EntityId;
	}

	for (const FHyperTwistTrainingRunRecord& RunRecord : RepositoryState.RunRecords)
	{
		if (RunRecord.Session.UserId != UserId || !RunRecord.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryEntityDescriptor RunEntity;
		RunEntity.EntityId = FString::Printf(
			TEXT("memory-entity/chronicle/run-record/%s"),
			*RunRecord.Session.TrainingSessionId
		);
		RunEntity.RecordKind = TEXT("training-run-record");
		RunEntity.DisplayLabel = TEXT("Training Run Record");
		RunEntity.UserId = UserId;
		RunEntity.DeckId = RunRecord.Session.DeckId;
		RunEntity.ReferenceUtc =
			RunRecord.LastUpdatedAtUtc.IsEmpty() ? ResolvedReferenceUtc : RunRecord.LastUpdatedAtUtc;
		RunEntity.Lane = EHyperTwistMemoryLane::ChronicleCapture;
		RunEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::Authoritative;
		HyperTwistMemoryCoreLibraryInternal::AddEntity(LedgerState, EntitiesById, RunEntity);

		if (FirstRunRecordEntityId.IsEmpty())
		{
			FirstRunRecordEntityId = RunEntity.EntityId;
		}

		for (const FHyperTwistTrainingAttempt& Attempt : RunRecord.Attempts)
		{
			if (Attempt.CaseId.IsEmpty())
			{
				continue;
			}

			const FString CaseKey = HyperTwistMemoryCoreLibraryInternal::MakeDeckCaseKey(
				RunRecord.Session.DeckId,
				Attempt.CaseId
			);
			RunRecordEntityIdByDeckCaseKey.FindOrAdd(CaseKey) = RunEntity.EntityId;
		}
	}

	for (const FHyperTwistTrainingReviewPlanState& ReviewPlan : RepositoryState.ReviewPlans)
	{
		if (ReviewPlan.UserId != UserId || !ReviewPlan.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryEntityDescriptor ReviewPlanEntity;
		ReviewPlanEntity.EntityId = FString::Printf(
			TEXT("memory-entity/workflow/review-plan/%s"),
			*ReviewPlan.PlanId
		);
		ReviewPlanEntity.RecordKind = TEXT("training-review-plan");
		ReviewPlanEntity.DisplayLabel = TEXT("Training Review Plan");
		ReviewPlanEntity.UserId = UserId;
		ReviewPlanEntity.DeckId = ReviewPlan.SourceDeckId;
		ReviewPlanEntity.ReferenceUtc =
			ReviewPlan.ReferenceUtc.IsEmpty() ? ResolvedReferenceUtc : ReviewPlan.ReferenceUtc;
		ReviewPlanEntity.Lane = EHyperTwistMemoryLane::ProceduralWorkflow;
		ReviewPlanEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::Authoritative;
		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			ReviewPlanEntity
		);

		ReviewPlanEntityIdByPlanId.Add(ReviewPlan.PlanId, ReviewPlanEntity.EntityId);
		if (FirstReviewPlanEntityId.IsEmpty())
		{
			FirstReviewPlanEntityId = ReviewPlanEntity.EntityId;
		}
	}

	for (const FHyperTwistTrainingSessionTemplate& SessionTemplate : RepositoryState.StoredSessionTemplates)
	{
		if (SessionTemplate.UserId != UserId || !SessionTemplate.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryEntityDescriptor SessionTemplateEntity;
		SessionTemplateEntity.EntityId = FString::Printf(
			TEXT("memory-entity/workflow/session-template/%s"),
			*SessionTemplate.TemplateId
		);
		SessionTemplateEntity.RecordKind = TEXT("training-session-template");
		SessionTemplateEntity.DisplayLabel = TEXT("Training Session Template");
		SessionTemplateEntity.UserId = UserId;
		SessionTemplateEntity.DeckId = SessionTemplate.FocusDeckId;
		SessionTemplateEntity.ReferenceUtc =
			SessionTemplate.LastUpdatedAtUtc.IsEmpty()
				? ResolvedReferenceUtc
				: SessionTemplate.LastUpdatedAtUtc;
		SessionTemplateEntity.Lane = EHyperTwistMemoryLane::ProceduralWorkflow;
		SessionTemplateEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::Authoritative;
		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			SessionTemplateEntity
		);
	}

	for (const FHyperTwistTrainingMethodDrillFavoriteEntry& FavoriteEntry :
		RepositoryState.StoredMethodDrillFavorites)
	{
		if (FavoriteEntry.UserId != UserId || !FavoriteEntry.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryEntityDescriptor FavoriteEntity;
		FavoriteEntity.EntityId = FString::Printf(
			TEXT("memory-entity/workflow/method-drill-favorite/%s/%s"),
			*FavoriteEntry.DrillId,
			*FavoriteEntry.CaseId
		);
		FavoriteEntity.RecordKind = TEXT("method-drill-favorite");
		FavoriteEntity.DisplayLabel = TEXT("Method Drill Favorite");
		FavoriteEntity.UserId = UserId;
		FavoriteEntity.DeckId = FavoriteEntry.SourceDeckId;
		FavoriteEntity.ReferenceUtc =
			FavoriteEntry.AddedAtUtc.IsEmpty() ? ResolvedReferenceUtc : FavoriteEntry.AddedAtUtc;
		FavoriteEntity.Lane = EHyperTwistMemoryLane::ProceduralWorkflow;
		FavoriteEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::Authoritative;
		HyperTwistMemoryCoreLibraryInternal::AddEntity(LedgerState, EntitiesById, FavoriteEntity);
	}

	for (const FHyperTwistTrainingMethodDrillBatch& DrillBatch :
		RepositoryState.StoredMethodDrillBatches)
	{
		if (DrillBatch.UserId != UserId || !DrillBatch.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryEntityDescriptor DrillBatchEntity;
		DrillBatchEntity.EntityId = FString::Printf(
			TEXT("memory-entity/workflow/method-drill-batch/%s"),
			*DrillBatch.BatchId
		);
		DrillBatchEntity.RecordKind = TEXT("method-drill-batch");
		DrillBatchEntity.DisplayLabel = TEXT("Method Drill Batch");
		DrillBatchEntity.UserId = UserId;
		DrillBatchEntity.DeckId = DrillBatch.SourceDeckId;
		DrillBatchEntity.ReferenceUtc =
			DrillBatch.LastUpdatedAtUtc.IsEmpty() ? ResolvedReferenceUtc : DrillBatch.LastUpdatedAtUtc;
		DrillBatchEntity.Lane = EHyperTwistMemoryLane::ProceduralWorkflow;
		DrillBatchEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::Authoritative;
		HyperTwistMemoryCoreLibraryInternal::AddEntity(LedgerState, EntitiesById, DrillBatchEntity);
	}

	for (const FHyperTwistTrainingCoachActionPlan& CoachActionPlan :
		RepositoryState.StoredCoachActionPlans)
	{
		if (CoachActionPlan.UserId != UserId || !CoachActionPlan.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryEntityDescriptor CoachPlanEntity;
		CoachPlanEntity.EntityId = FString::Printf(
			TEXT("memory-entity/workflow/coach-action-plan/%s"),
			*CoachActionPlan.PlanId
		);
		CoachPlanEntity.RecordKind = TEXT("coach-action-plan");
		CoachPlanEntity.DisplayLabel = TEXT("Coach Action Plan");
		CoachPlanEntity.UserId = UserId;
		CoachPlanEntity.DeckId = CoachActionPlan.FocusDeckId;
		CoachPlanEntity.ReferenceUtc =
			CoachActionPlan.ReferenceUtc.IsEmpty() ? ResolvedReferenceUtc : CoachActionPlan.ReferenceUtc;
		CoachPlanEntity.Lane = EHyperTwistMemoryLane::ProceduralWorkflow;
		CoachPlanEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::Authoritative;
		HyperTwistMemoryCoreLibraryInternal::AddEntity(LedgerState, EntitiesById, CoachPlanEntity);

		CoachPlanEntityIdByPlanId.Add(CoachActionPlan.PlanId, CoachPlanEntity.EntityId);
		if (FirstCoachPlanEntityId.IsEmpty())
		{
			FirstCoachPlanEntityId = CoachPlanEntity.EntityId;
		}
	}

	for (const FHyperTwistTrainingCoachSessionQueueState& QueueState :
		RepositoryState.StoredCoachSessionQueues)
	{
		if (QueueState.UserId != UserId || !QueueState.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryEntityDescriptor QueueEntity;
		QueueEntity.EntityId = FString::Printf(
			TEXT("memory-entity/workflow/coach-session-queue/%s"),
			*QueueState.QueueId
		);
		QueueEntity.RecordKind = TEXT("coach-session-queue");
		QueueEntity.DisplayLabel = TEXT("Coach Session Queue");
		QueueEntity.UserId = UserId;
		QueueEntity.DeckId = QueueState.FocusDeckId;
		QueueEntity.ReferenceUtc =
			QueueState.LastUpdatedAtUtc.IsEmpty() ? ResolvedReferenceUtc : QueueState.LastUpdatedAtUtc;
		QueueEntity.Lane = EHyperTwistMemoryLane::ProceduralWorkflow;
		QueueEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::Authoritative;
		HyperTwistMemoryCoreLibraryInternal::AddEntity(LedgerState, EntitiesById, QueueEntity);

		QueueEntityIdByQueueId.Add(QueueState.QueueId, QueueEntity.EntityId);
		if (FirstQueueEntityId.IsEmpty())
		{
			FirstQueueEntityId = QueueEntity.EntityId;
		}
	}

	for (const FHyperTwistTrainingCaseLearnerState& LearnerState : RepositoryState.LearnerStates)
	{
		if (LearnerState.UserId != UserId || !LearnerState.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryEntityDescriptor LearnerStateEntity;
		LearnerStateEntity.EntityId = FString::Printf(
			TEXT("memory-entity/cognitive/case-learner-state/%s/%s"),
			*LearnerState.DeckId,
			*LearnerState.CaseId
		);
		LearnerStateEntity.RecordKind = TEXT("case-learner-state");
		LearnerStateEntity.DisplayLabel = TEXT("Case Learner State");
		LearnerStateEntity.UserId = UserId;
		LearnerStateEntity.DeckId = LearnerState.DeckId;
		LearnerStateEntity.ReferenceUtc =
			LearnerState.LastReviewedAtUtc.IsEmpty()
				? (LearnerState.DueAtUtc.IsEmpty() ? ResolvedReferenceUtc : LearnerState.DueAtUtc)
				: LearnerState.LastReviewedAtUtc;
		LearnerStateEntity.Lane = EHyperTwistMemoryLane::CognitiveConsolidated;
		LearnerStateEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::SemiAuthoritative;
		LearnerStateEntity.bDerived = true;

		const FString CaseKey = HyperTwistMemoryCoreLibraryInternal::MakeDeckCaseKey(
			LearnerState.DeckId,
			LearnerState.CaseId
		);
		if (const FString* RunEntityId = RunRecordEntityIdByDeckCaseKey.Find(CaseKey))
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				*RunEntityId,
				TEXT("chronicle-run-record"),
				LearnerStateEntity.ProvenanceLinks
			);
		}
		if (LearnerStateEntity.ProvenanceLinks.Num() == 0 && !FirstRunRecordEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstRunRecordEntityId,
				TEXT("chronicle-run-record"),
				LearnerStateEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			LearnerStateEntity
		);
		LearnerStateEntityIdByDeckCaseKey.Add(CaseKey, LearnerStateEntity.EntityId);
		if (FirstLearnerStateEntityId.IsEmpty())
		{
			FirstLearnerStateEntityId = LearnerStateEntity.EntityId;
		}
	}

	const FHyperTwistTrainingReviewProgramSummary ReviewProgramSummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveReviewProgramSummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	if (ReviewProgramSummary.IsStructurallyValid())
	{
		FHyperTwistMemoryEntityDescriptor ReviewProgramEntity;
		ReviewProgramEntity.EntityId = FString::Printf(
			TEXT("memory-entity/recall/review-program-summary/%s"),
			*UserId
		);
		ReviewProgramEntity.RecordKind = TEXT("review-program-summary");
		ReviewProgramEntity.DisplayLabel = TEXT("Review Program Summary");
		ReviewProgramEntity.UserId = UserId;
		ReviewProgramEntity.DeckId = ReviewProgramSummary.FocusDeckId;
		ReviewProgramEntity.ReferenceUtc = ReviewProgramSummary.ReferenceUtc;
		ReviewProgramEntity.Lane = EHyperTwistMemoryLane::RecallRetrieval;
		ReviewProgramEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::SemiAuthoritative;
		ReviewProgramEntity.bDerived = true;
		if (const FString* ReviewPlanEntityId =
				ReviewPlanEntityIdByPlanId.Find(ReviewProgramSummary.CurrentPlanId))
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				*ReviewPlanEntityId,
				TEXT("review-plan"),
				ReviewProgramEntity.ProvenanceLinks
			);
		}
		if (ReviewProgramEntity.ProvenanceLinks.Num() == 0)
		{
			if (const FString* ReviewPlanEntityId =
					ReviewPlanEntityIdByPlanId.Find(ReviewProgramSummary.LastCompletedPlanId))
			{
				HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
					EntitiesById,
					*ReviewPlanEntityId,
					TEXT("review-plan"),
					ReviewProgramEntity.ProvenanceLinks
				);
			}
		}
		if (ReviewProgramEntity.ProvenanceLinks.Num() == 0 && !FirstReviewPlanEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstReviewPlanEntityId,
				TEXT("review-plan"),
				ReviewProgramEntity.ProvenanceLinks
			);
		}
		if (ReviewProgramEntity.ProvenanceLinks.Num() == 0 && !FirstRunRecordEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstRunRecordEntityId,
				TEXT("chronicle-run-record"),
				ReviewProgramEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			ReviewProgramEntity
		);
		ReviewProgramEntityId = ReviewProgramEntity.EntityId;
	}

	for (const FHyperTwistTrainingCoachSessionQueueState& QueueState :
		RepositoryState.StoredCoachSessionQueues)
	{
		if (QueueState.UserId != UserId || QueueState.QueueId.IsEmpty())
		{
			continue;
		}

		const FHyperTwistTrainingCoachSessionQueueExecutionSummary QueueExecutionSummary =
			UHyperTwistTrainingRepositoryLibrary::DeriveCoachSessionQueueExecutionSummary(
				RepositoryState,
				UserId,
				QueueState.QueueId,
				ResolvedReferenceUtc
			);
		if (!QueueExecutionSummary.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryEntityDescriptor QueueExecutionEntity;
		QueueExecutionEntity.EntityId = FString::Printf(
			TEXT("memory-entity/shared-coordination/queue-execution-summary/%s"),
			*QueueState.QueueId
		);
		QueueExecutionEntity.RecordKind = TEXT("coach-session-queue-execution-summary");
		QueueExecutionEntity.DisplayLabel = TEXT("Coach Session Queue Execution Summary");
		QueueExecutionEntity.UserId = UserId;
		QueueExecutionEntity.DeckId = QueueExecutionSummary.FocusDeckId;
		QueueExecutionEntity.ReferenceUtc = QueueExecutionSummary.ReferenceUtc;
		QueueExecutionEntity.Lane = EHyperTwistMemoryLane::SharedCoordination;
		QueueExecutionEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::SemiAuthoritative;
		QueueExecutionEntity.bDerived = true;
		if (const FString* QueueEntityId = QueueEntityIdByQueueId.Find(QueueState.QueueId))
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				*QueueEntityId,
				TEXT("queue-state"),
				QueueExecutionEntity.ProvenanceLinks
			);
		}
		if (QueueExecutionEntity.ProvenanceLinks.Num() == 0 && !FirstQueueEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstQueueEntityId,
				TEXT("queue-state"),
				QueueExecutionEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			QueueExecutionEntity
		);
	}

	const FHyperTwistTrainingCoachMemorySnapshot CoachMemorySnapshot =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachMemorySnapshot(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	if (!CoachMemorySnapshot.UserId.IsEmpty() && !CoachMemorySnapshot.ReferenceUtc.IsEmpty())
	{
		FHyperTwistMemoryEntityDescriptor CoachMemoryEntity;
		CoachMemoryEntity.EntityId = FString::Printf(
			TEXT("memory-entity/cognitive/coach-memory-snapshot/%s"),
			*UserId
		);
		CoachMemoryEntity.RecordKind = TEXT("coach-memory-snapshot");
		CoachMemoryEntity.DisplayLabel = TEXT("Coach Memory Snapshot");
		CoachMemoryEntity.UserId = UserId;
		CoachMemoryEntity.DeckId = CoachMemorySnapshot.FocusDeckId;
		CoachMemoryEntity.ReferenceUtc = CoachMemorySnapshot.ReferenceUtc;
		CoachMemoryEntity.Lane = EHyperTwistMemoryLane::CognitiveConsolidated;
		CoachMemoryEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::SemiAuthoritative;
		CoachMemoryEntity.bDerived = true;
		if (!ReviewProgramEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				ReviewProgramEntityId,
				TEXT("review-program-summary"),
				CoachMemoryEntity.ProvenanceLinks
			);
		}
		if (!CoachMemorySnapshot.WeakCaseIds.IsEmpty())
		{
			const FString CaseKey = HyperTwistMemoryCoreLibraryInternal::MakeDeckCaseKey(
				CoachMemorySnapshot.FocusDeckId,
				CoachMemorySnapshot.WeakCaseIds[0]
			);
			if (const FString* LearnerStateEntityId = LearnerStateEntityIdByDeckCaseKey.Find(CaseKey))
			{
				HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
					EntitiesById,
					*LearnerStateEntityId,
					TEXT("case-learner-state"),
					CoachMemoryEntity.ProvenanceLinks
				);
			}
		}
		if (CoachMemoryEntity.ProvenanceLinks.Num() == 0 && !FirstLearnerStateEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstLearnerStateEntityId,
				TEXT("case-learner-state"),
				CoachMemoryEntity.ProvenanceLinks
			);
		}
		if (!FirstCoachPlanEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstCoachPlanEntityId,
				TEXT("coach-action-plan"),
				CoachMemoryEntity.ProvenanceLinks
			);
		}
		if (CoachMemoryEntity.ProvenanceLinks.Num() == 0 && !FirstRunRecordEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstRunRecordEntityId,
				TEXT("chronicle-run-record"),
				CoachMemoryEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			CoachMemoryEntity
		);
		CoachMemorySnapshotEntityId = CoachMemoryEntity.EntityId;
	}

	const FHyperTwistTrainingCoachClosureMemorySummary CoachClosureSummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachClosureMemorySummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	if (CoachClosureSummary.IsStructurallyValid())
	{
		FHyperTwistMemoryEntityDescriptor CoachClosureEntity;
		CoachClosureEntity.EntityId = FString::Printf(
			TEXT("memory-entity/cognitive/coach-closure-memory-summary/%s"),
			*UserId
		);
		CoachClosureEntity.RecordKind = TEXT("coach-closure-memory-summary");
		CoachClosureEntity.DisplayLabel = TEXT("Coach Closure Memory Summary");
		CoachClosureEntity.UserId = UserId;
		CoachClosureEntity.DeckId = CoachClosureSummary.FocusDeckId;
		CoachClosureEntity.ReferenceUtc = CoachClosureSummary.ReferenceUtc;
		CoachClosureEntity.Lane = EHyperTwistMemoryLane::CognitiveConsolidated;
		CoachClosureEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::SemiAuthoritative;
		CoachClosureEntity.bDerived = true;
		if (const FString* CoachPlanEntityId =
				CoachPlanEntityIdByPlanId.Find(CoachClosureSummary.FocusRootPlanId))
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				*CoachPlanEntityId,
				TEXT("coach-action-plan"),
				CoachClosureEntity.ProvenanceLinks
			);
		}
		if (CoachClosureEntity.ProvenanceLinks.Num() == 0 && !CoachMemorySnapshotEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				CoachMemorySnapshotEntityId,
				TEXT("coach-memory-snapshot"),
				CoachClosureEntity.ProvenanceLinks
			);
		}
		if (CoachClosureEntity.ProvenanceLinks.Num() == 0 && !FirstCoachPlanEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstCoachPlanEntityId,
				TEXT("coach-action-plan"),
				CoachClosureEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			CoachClosureEntity
		);
	}

	const FHyperTwistTrainingCoachRecommendationHistorySummary RecommendationHistorySummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachRecommendationHistorySummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	if (RecommendationHistorySummary.IsStructurallyValid())
	{
		FHyperTwistMemoryEntityDescriptor RecommendationHistoryEntity;
		RecommendationHistoryEntity.EntityId = FString::Printf(
			TEXT("memory-entity/cognitive/coach-recommendation-history-summary/%s"),
			*UserId
		);
		RecommendationHistoryEntity.RecordKind = TEXT("coach-recommendation-history-summary");
		RecommendationHistoryEntity.DisplayLabel = TEXT("Coach Recommendation History Summary");
		RecommendationHistoryEntity.UserId = UserId;
		RecommendationHistoryEntity.DeckId = RecommendationHistorySummary.FocusDeckId;
		RecommendationHistoryEntity.ReferenceUtc = RecommendationHistorySummary.ReferenceUtc;
		RecommendationHistoryEntity.Lane = EHyperTwistMemoryLane::CognitiveConsolidated;
		RecommendationHistoryEntity.AuthorityKind =
			EHyperTwistMemoryAuthorityKind::SemiAuthoritative;
		RecommendationHistoryEntity.bDerived = true;
		if (const FString* CoachPlanEntityId =
				CoachPlanEntityIdByPlanId.Find(RecommendationHistorySummary.LatestPlanId))
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				*CoachPlanEntityId,
				TEXT("coach-action-plan"),
				RecommendationHistoryEntity.ProvenanceLinks
			);
		}
		if (RecommendationHistoryEntity.ProvenanceLinks.Num() == 0 &&
			!CoachMemorySnapshotEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				CoachMemorySnapshotEntityId,
				TEXT("coach-memory-snapshot"),
				RecommendationHistoryEntity.ProvenanceLinks
			);
		}
		if (RecommendationHistoryEntity.ProvenanceLinks.Num() == 0 && !FirstCoachPlanEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstCoachPlanEntityId,
				TEXT("coach-action-plan"),
				RecommendationHistoryEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			RecommendationHistoryEntity
		);
	}

	const FHyperTwistTrainingCoachCarryForwardPolicySummary CarryForwardSummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachCarryForwardPolicySummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	if (CarryForwardSummary.IsStructurallyValid())
	{
		FHyperTwistMemoryEntityDescriptor CarryForwardEntity;
		CarryForwardEntity.EntityId = FString::Printf(
			TEXT("memory-entity/cognitive/coach-carry-forward-policy-summary/%s"),
			*UserId
		);
		CarryForwardEntity.RecordKind = TEXT("coach-carry-forward-policy-summary");
		CarryForwardEntity.DisplayLabel = TEXT("Coach Carry-Forward Policy Summary");
		CarryForwardEntity.UserId = UserId;
		CarryForwardEntity.DeckId = CarryForwardSummary.FocusDeckId;
		CarryForwardEntity.ReferenceUtc = CarryForwardSummary.ReferenceUtc;
		CarryForwardEntity.Lane = EHyperTwistMemoryLane::CognitiveConsolidated;
		CarryForwardEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::SemiAuthoritative;
		CarryForwardEntity.bDerived = true;
		if (!CoachMemorySnapshotEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				CoachMemorySnapshotEntityId,
				TEXT("coach-memory-snapshot"),
				CarryForwardEntity.ProvenanceLinks
			);
		}
		if (CarryForwardEntity.ProvenanceLinks.Num() == 0 && !FirstCoachPlanEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstCoachPlanEntityId,
				TEXT("coach-action-plan"),
				CarryForwardEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			CarryForwardEntity
		);
	}

	const FHyperTwistTrainingCoachArchivePolicySummary ArchivePolicySummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachArchivePolicySummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	if (ArchivePolicySummary.IsStructurallyValid())
	{
		FHyperTwistMemoryEntityDescriptor ArchivePolicyEntity;
		ArchivePolicyEntity.EntityId = FString::Printf(
			TEXT("memory-entity/cognitive/coach-archive-policy-summary/%s"),
			*UserId
		);
		ArchivePolicyEntity.RecordKind = TEXT("coach-archive-policy-summary");
		ArchivePolicyEntity.DisplayLabel = TEXT("Coach Archive Policy Summary");
		ArchivePolicyEntity.UserId = UserId;
		ArchivePolicyEntity.DeckId = ArchivePolicySummary.FocusDeckId;
		ArchivePolicyEntity.ReferenceUtc = ArchivePolicySummary.ReferenceUtc;
		ArchivePolicyEntity.Lane = EHyperTwistMemoryLane::CognitiveConsolidated;
		ArchivePolicyEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::SemiAuthoritative;
		ArchivePolicyEntity.bDerived = true;
		if (!CoachMemorySnapshotEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				CoachMemorySnapshotEntityId,
				TEXT("coach-memory-snapshot"),
				ArchivePolicyEntity.ProvenanceLinks
			);
		}
		if (ArchivePolicyEntity.ProvenanceLinks.Num() == 0 && !FirstQueueEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstQueueEntityId,
				TEXT("queue-state"),
				ArchivePolicyEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			ArchivePolicyEntity
		);
	}

	const FHyperTwistTrainingLearnerProfile LearnerProfile =
		UHyperTwistTrainingRepositoryLibrary::DeriveLearnerProfile(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	if (!LearnerProfile.UserId.IsEmpty() && !LearnerProfile.ReferenceUtc.IsEmpty())
	{
		FHyperTwistMemoryEntityDescriptor LearnerProfileEntity;
		LearnerProfileEntity.EntityId = FString::Printf(
			TEXT("memory-entity/compact/learner-profile/%s"),
			*UserId
		);
		LearnerProfileEntity.RecordKind = TEXT("learner-profile-summary");
		LearnerProfileEntity.DisplayLabel = TEXT("Learner Profile Summary");
		LearnerProfileEntity.UserId = UserId;
		LearnerProfileEntity.DeckId = LearnerProfile.FavoriteDeckId;
		LearnerProfileEntity.ReferenceUtc = LearnerProfile.ReferenceUtc;
		LearnerProfileEntity.Lane = EHyperTwistMemoryLane::DerivedCompacted;
		LearnerProfileEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::DerivedOnly;
		LearnerProfileEntity.bDerived = true;
		if (!FirstLearnerStateEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstLearnerStateEntityId,
				TEXT("case-learner-state"),
				LearnerProfileEntity.ProvenanceLinks
			);
		}
		if (LearnerProfileEntity.ProvenanceLinks.Num() == 0 && !FirstRunRecordEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				FirstRunRecordEntityId,
				TEXT("chronicle-run-record"),
				LearnerProfileEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			LearnerProfileEntity
		);
		LearnerProfileEntityId = LearnerProfileEntity.EntityId;
	}

	{
		FHyperTwistMemoryEntityDescriptor LedgerOverviewEntity;
		LedgerOverviewEntity.EntityId = FString::Printf(
			TEXT("memory-entity/compact/ledger-overview/%s"),
			*UserId
		);
		LedgerOverviewEntity.RecordKind = TEXT("memory-ledger-overview");
		LedgerOverviewEntity.DisplayLabel = TEXT("Memory Ledger Overview");
		LedgerOverviewEntity.UserId = UserId;
		LedgerOverviewEntity.ReferenceUtc = ResolvedReferenceUtc;
		LedgerOverviewEntity.Lane = EHyperTwistMemoryLane::DerivedCompacted;
		LedgerOverviewEntity.AuthorityKind = EHyperTwistMemoryAuthorityKind::DerivedOnly;
		LedgerOverviewEntity.bDerived = true;
		if (!LearnerProfileEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				LearnerProfileEntityId,
				TEXT("learner-profile-summary"),
				LedgerOverviewEntity.ProvenanceLinks
			);
		}
		if (!ReviewProgramEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				ReviewProgramEntityId,
				TEXT("review-program-summary"),
				LedgerOverviewEntity.ProvenanceLinks
			);
		}
		if (!CoachMemorySnapshotEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				CoachMemorySnapshotEntityId,
				TEXT("coach-memory-snapshot"),
				LedgerOverviewEntity.ProvenanceLinks
			);
		}
		if (LedgerOverviewEntity.ProvenanceLinks.Num() == 0 && !LedgerContractEntityId.IsEmpty())
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				EntitiesById,
				LedgerContractEntityId,
				TEXT("memory-ledger-contract"),
				LedgerOverviewEntity.ProvenanceLinks
			);
		}

		HyperTwistMemoryCoreLibraryInternal::AddEntity(
			LedgerState,
			EntitiesById,
			LedgerOverviewEntity
		);
	}

	return LedgerState;
}

FHyperTwistMemoryChronicleContinuityState
	UHyperTwistMemoryCoreLibrary::DeriveMemoryChronicleContinuityState(
		const FHyperTwistTrainingRepositoryState& RepositoryState,
		const FString& UserId,
		const FString& ReferenceUtc
	)
{
	FHyperTwistMemoryChronicleContinuityState ChronicleContinuityState;
	if (UserId.IsEmpty())
	{
		return ChronicleContinuityState;
	}

	const FString ResolvedReferenceUtc =
		HyperTwistMemoryCoreLibraryInternal::ResolveReferenceUtc(ReferenceUtc);
	ChronicleContinuityState.UserId = UserId;
	ChronicleContinuityState.ReferenceUtc = ResolvedReferenceUtc;

	const FHyperTwistMemoryLedgerState MemoryLedgerState = DeriveMemoryLedgerState(
		RepositoryState,
		UserId,
		ResolvedReferenceUtc
	);

	TMap<FString, FHyperTwistMemoryEntityDescriptor> LedgerEntitiesById;
	for (const FHyperTwistMemoryEntityDescriptor& LedgerEntity : MemoryLedgerState.Entities)
	{
		LedgerEntitiesById.Add(LedgerEntity.EntityId, LedgerEntity);
	}

	TMap<FString, TArray<FString>> QueueHistoryEventIdsByQueueId;
	TMap<FString, FString> SessionGroupIdByRunRecordId;
	TMap<FString, FString> SessionGroupIdByReviewPlanId;
	TMap<FString, FString> SessionGroupIdByQueueId;
	const FString LedgerContractEntityId = FString::Printf(
		TEXT("memory-entity/provenance/ledger/current/%s"),
		*UserId
	);

	for (const FHyperTwistTrainingRunRecord& RunRecord : RepositoryState.RunRecords)
	{
		if (!RunRecord.IsStructurallyValid() || RunRecord.Session.UserId != UserId)
		{
			continue;
		}

		const FString RunEntityId = FString::Printf(
			TEXT("memory-entity/chronicle/run-record/%s"),
			*RunRecord.Session.TrainingSessionId
		);

		FHyperTwistMemoryChronicleEventEntry ChronicleEvent;
		ChronicleEvent.EventId = FString::Printf(
			TEXT("memory-chronicle-event/run-record/%s"),
			*RunRecord.Session.TrainingSessionId
		);
		ChronicleEvent.EventKind = TEXT("training-run-record");
		ChronicleEvent.DisplayLabel =
			HyperTwistMemoryCoreLibraryInternal::HasOpenTrainingSession(RunRecord)
			? TEXT("Open Training Session")
			: TEXT("Completed Training Session");
		ChronicleEvent.UserId = UserId;
		ChronicleEvent.DeckId = RunRecord.Session.DeckId;
		ChronicleEvent.RootRecordId = RunRecord.Session.TrainingSessionId;
		ChronicleEvent.RelatedTrainingSessionId = RunRecord.Session.TrainingSessionId;
		ChronicleEvent.RecordedAtUtc =
			HyperTwistMemoryCoreLibraryInternal::ResolveRunRecordReferenceUtc(
				RunRecord,
				ResolvedReferenceUtc
			);
		ChronicleEvent.Lane = EHyperTwistMemoryLane::ChronicleCapture;
		ChronicleEvent.bOpenContinuity =
			HyperTwistMemoryCoreLibraryInternal::HasOpenTrainingSession(RunRecord);
		HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
			LedgerEntitiesById,
			RunEntityId,
			TEXT("training-run-record"),
			ChronicleEvent.ProvenanceLinks
		);
		HyperTwistMemoryCoreLibraryInternal::AddChronicleEvent(
			ChronicleContinuityState,
			ChronicleEvent
		);

		FHyperTwistMemorySessionGroup SessionGroup;
		SessionGroup.GroupId = FString::Printf(
			TEXT("memory-session-group/training-session/%s"),
			*RunRecord.Session.TrainingSessionId
		);
		SessionGroup.GroupKind = TEXT("training-session");
		SessionGroup.Headline = ChronicleEvent.DisplayLabel;
		SessionGroup.UserId = UserId;
		SessionGroup.DeckId = RunRecord.Session.DeckId;
		SessionGroup.RootRecordId = RunRecord.Session.TrainingSessionId;
		SessionGroup.RootTrainingSessionId = RunRecord.Session.TrainingSessionId;
		SessionGroup.ReferenceUtc = ChronicleEvent.RecordedAtUtc;
		SessionGroup.ChronicleEventIds = {ChronicleEvent.EventId};
		SessionGroup.FocusCaseIds =
			HyperTwistMemoryCoreLibraryInternal::CollectRunFocusCaseIds(RunRecord);
		SessionGroup.EventCount = SessionGroup.ChronicleEventIds.Num();
		SessionGroup.bCompleted = !ChronicleEvent.bOpenContinuity;
		SessionGroup.bHasResumeCandidate = ChronicleEvent.bOpenContinuity;
		SessionGroup.ProvenanceLinks = ChronicleEvent.ProvenanceLinks;
		HyperTwistMemoryCoreLibraryInternal::AddSessionGroup(
			ChronicleContinuityState,
			SessionGroup
		);
		SessionGroupIdByRunRecordId.Add(
			RunRecord.Session.TrainingSessionId,
			SessionGroup.GroupId
		);

		if (ChronicleEvent.bOpenContinuity)
		{
			FHyperTwistMemoryResumePack ResumePack;
			ResumePack.PackId = FString::Printf(
				TEXT("memory-resume-pack/training-session/%s"),
				*RunRecord.Session.TrainingSessionId
			);
			ResumePack.PackKind = TEXT("training-session-resume");
			ResumePack.Headline = TEXT("Resume Training Session");
			ResumePack.UserId = UserId;
			ResumePack.DeckId = RunRecord.Session.DeckId;
			ResumePack.ResumeTargetId = RunRecord.Session.TrainingSessionId;
			ResumePack.ResumeActionId = TEXT("resume-training-session");
			ResumePack.ReferenceUtc = ChronicleEvent.RecordedAtUtc;
			ResumePack.ChronicleGroupIds = {SessionGroup.GroupId};
			ResumePack.FocusCaseIds = SessionGroup.FocusCaseIds;
			ResumePack.PendingItemCount = FMath::Max(1, RunRecord.RemainingCaseIds.Num());
			ResumePack.bTimeSensitive =
				RunRecord.Session.SessionState == EHyperTwistTrainingSessionState::Active;
			ResumePack.ProvenanceLinks = ChronicleEvent.ProvenanceLinks;
			HyperTwistMemoryCoreLibraryInternal::AddResumePack(
				ChronicleContinuityState,
				ResumePack
			);
		}
	}

	for (const FHyperTwistTrainingReviewPlanState& ReviewPlan : RepositoryState.ReviewPlans)
	{
		if (!ReviewPlan.IsStructurallyValid() || ReviewPlan.UserId != UserId)
		{
			continue;
		}

		const FString ReviewPlanEntityId = FString::Printf(
			TEXT("memory-entity/workflow/review-plan/%s"),
			*ReviewPlan.PlanId
		);

		FHyperTwistMemoryChronicleEventEntry ChronicleEvent;
		ChronicleEvent.EventId = FString::Printf(
			TEXT("memory-chronicle-event/review-plan/%s"),
			*ReviewPlan.PlanId
		);
		ChronicleEvent.EventKind = TEXT("training-review-plan");
		ChronicleEvent.DisplayLabel =
			HyperTwistMemoryCoreLibraryInternal::HasOpenReviewPlan(ReviewPlan)
				? TEXT("Open Review Plan")
				: TEXT("Completed Review Plan");
		ChronicleEvent.UserId = UserId;
		ChronicleEvent.DeckId = ReviewPlan.SourceDeckId;
		ChronicleEvent.RootRecordId = ReviewPlan.PlanId;
		ChronicleEvent.RelatedReviewPlanId = ReviewPlan.PlanId;
		ChronicleEvent.RecordedAtUtc =
			HyperTwistMemoryCoreLibraryInternal::ResolveReviewPlanReferenceUtc(
				ReviewPlan,
				ResolvedReferenceUtc
			);
		ChronicleEvent.Lane = EHyperTwistMemoryLane::ContinuityResume;
		ChronicleEvent.bOpenContinuity =
			HyperTwistMemoryCoreLibraryInternal::HasOpenReviewPlan(ReviewPlan);
		HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
			LedgerEntitiesById,
			ReviewPlanEntityId,
			TEXT("training-review-plan"),
			ChronicleEvent.ProvenanceLinks
		);
		HyperTwistMemoryCoreLibraryInternal::AddChronicleEvent(
			ChronicleContinuityState,
			ChronicleEvent
		);

		FHyperTwistMemorySessionGroup SessionGroup;
		SessionGroup.GroupId = FString::Printf(
			TEXT("memory-session-group/review-plan/%s"),
			*ReviewPlan.PlanId
		);
		SessionGroup.GroupKind = TEXT("review-plan");
		SessionGroup.Headline = ChronicleEvent.DisplayLabel;
		SessionGroup.UserId = UserId;
		SessionGroup.DeckId = ReviewPlan.SourceDeckId;
		SessionGroup.RootRecordId = ReviewPlan.PlanId;
		SessionGroup.RootReviewPlanId = ReviewPlan.PlanId;
		SessionGroup.ReferenceUtc = ChronicleEvent.RecordedAtUtc;
		SessionGroup.ChronicleEventIds = {ChronicleEvent.EventId};
		SessionGroup.FocusCaseIds =
			HyperTwistMemoryCoreLibraryInternal::CollectReviewPlanFocusCaseIds(
				ReviewPlan,
				false
			);
		SessionGroup.EventCount = SessionGroup.ChronicleEventIds.Num();
		SessionGroup.bCompleted = !ChronicleEvent.bOpenContinuity;
		SessionGroup.bHasResumeCandidate = ChronicleEvent.bOpenContinuity;
		SessionGroup.ProvenanceLinks = ChronicleEvent.ProvenanceLinks;
		HyperTwistMemoryCoreLibraryInternal::AddSessionGroup(
			ChronicleContinuityState,
			SessionGroup
		);
		SessionGroupIdByReviewPlanId.Add(ReviewPlan.PlanId, SessionGroup.GroupId);

		if (ChronicleEvent.bOpenContinuity)
		{
			FHyperTwistMemoryResumePack ResumePack;
			ResumePack.PackId = FString::Printf(
				TEXT("memory-resume-pack/review-plan/%s"),
				*ReviewPlan.PlanId
			);
			ResumePack.PackKind = TEXT("review-plan-resume");
			ResumePack.Headline = TEXT("Resume Review Plan");
			ResumePack.UserId = UserId;
			ResumePack.DeckId = ReviewPlan.SourceDeckId;
			ResumePack.ResumeTargetId = ReviewPlan.PlanId;
			ResumePack.ResumeActionId = TEXT("resume-review-plan");
			ResumePack.ReferenceUtc = ChronicleEvent.RecordedAtUtc;
			ResumePack.ChronicleGroupIds = {SessionGroup.GroupId};
			ResumePack.FocusCaseIds =
				HyperTwistMemoryCoreLibraryInternal::CollectReviewPlanFocusCaseIds(
					ReviewPlan,
					true
				);
			ResumePack.PendingItemCount = FMath::Max(
				1,
				HyperTwistMemoryCoreLibraryInternal::CountOpenReviewEntries(ReviewPlan)
			);
			ResumePack.bTimeSensitive = ReviewPlan.StartedAtUtc.IsEmpty();
			ResumePack.ProvenanceLinks = ChronicleEvent.ProvenanceLinks;
			HyperTwistMemoryCoreLibraryInternal::AddResumePack(
				ChronicleContinuityState,
				ResumePack
			);
		}
	}

	for (const FHyperTwistTrainingCoachSessionQueueHistoryEntry& QueueHistoryEntry :
		RepositoryState.StoredCoachSessionQueueHistory)
	{
		if (!QueueHistoryEntry.IsStructurallyValid() || QueueHistoryEntry.UserId != UserId)
		{
			continue;
		}

		const FString QueueEntityId = FString::Printf(
			TEXT("memory-entity/workflow/coach-session-queue/%s"),
			*QueueHistoryEntry.QueueId
		);

		FHyperTwistMemoryChronicleEventEntry ChronicleEvent;
		ChronicleEvent.EventId = FString::Printf(
			TEXT("memory-chronicle-event/coach-session-queue-history/%s"),
			*QueueHistoryEntry.HistoryEntryId
		);
		ChronicleEvent.EventKind = FString::Printf(
			TEXT("coach-session-queue-history/%s"),
			*HyperTwistMemoryCoreLibraryInternal::ResolveQueueHistoryEventKindToken(
				QueueHistoryEntry.EventKind)
		);
		ChronicleEvent.DisplayLabel =
			HyperTwistMemoryCoreLibraryInternal::ResolveQueueHistoryEventLabel(
				QueueHistoryEntry.EventKind
			);
		ChronicleEvent.UserId = UserId;
		ChronicleEvent.DeckId = QueueHistoryEntry.FocusDeckId;
		ChronicleEvent.RootRecordId = QueueHistoryEntry.HistoryEntryId;
		ChronicleEvent.RelatedTrainingSessionId = QueueHistoryEntry.SourceTrainingSessionId;
		ChronicleEvent.RelatedQueueId = QueueHistoryEntry.QueueId;
		ChronicleEvent.RecordedAtUtc = QueueHistoryEntry.EventAtUtc;
		ChronicleEvent.Lane = EHyperTwistMemoryLane::ChronicleCapture;
		ChronicleEvent.bOpenContinuity = QueueHistoryEntry.NewEntryState
			== EHyperTwistTrainingCoachSessionQueueEntryState::InProgress;
		HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
			LedgerEntitiesById,
			QueueEntityId,
			TEXT("coach-session-queue"),
			ChronicleEvent.ProvenanceLinks
		);
		if (!QueueHistoryEntry.SourceTrainingSessionId.IsEmpty())
		{
			const FString RunEntityId = FString::Printf(
				TEXT("memory-entity/chronicle/run-record/%s"),
				*QueueHistoryEntry.SourceTrainingSessionId
			);
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				LedgerEntitiesById,
				RunEntityId,
				TEXT("training-run-record"),
				ChronicleEvent.ProvenanceLinks
			);
		}
		HyperTwistMemoryCoreLibraryInternal::AddChronicleEvent(
			ChronicleContinuityState,
			ChronicleEvent
		);
		QueueHistoryEventIdsByQueueId.FindOrAdd(QueueHistoryEntry.QueueId).Add(
			ChronicleEvent.EventId
		);
	}

	for (const FHyperTwistTrainingCoachSessionQueueState& QueueState :
		RepositoryState.StoredCoachSessionQueues)
	{
		if (!QueueState.IsStructurallyValid() || QueueState.UserId != UserId)
		{
			continue;
		}

		const FString QueueEntityId = FString::Printf(
			TEXT("memory-entity/workflow/coach-session-queue/%s"),
			*QueueState.QueueId
		);

		FHyperTwistMemoryChronicleEventEntry ChronicleEvent;
		ChronicleEvent.EventId = FString::Printf(
			TEXT("memory-chronicle-event/coach-session-queue/%s"),
			*QueueState.QueueId
		);
		ChronicleEvent.EventKind = TEXT("coach-session-queue");
		ChronicleEvent.DisplayLabel =
			HyperTwistMemoryCoreLibraryInternal::HasOpenQueue(QueueState)
				? TEXT("Open Coach Session Queue")
				: TEXT("Completed Coach Session Queue");
		ChronicleEvent.UserId = UserId;
		ChronicleEvent.DeckId = QueueState.FocusDeckId;
		ChronicleEvent.RootRecordId = QueueState.QueueId;
		ChronicleEvent.RelatedTrainingSessionId = QueueState.ActiveTrainingSessionId;
		ChronicleEvent.RelatedQueueId = QueueState.QueueId;
		ChronicleEvent.RecordedAtUtc =
			HyperTwistMemoryCoreLibraryInternal::ResolveQueueStateReferenceUtc(
				QueueState,
				ResolvedReferenceUtc
			);
		ChronicleEvent.Lane = EHyperTwistMemoryLane::ContinuityResume;
		ChronicleEvent.bOpenContinuity =
			HyperTwistMemoryCoreLibraryInternal::HasOpenQueue(QueueState);
		HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
			LedgerEntitiesById,
			QueueEntityId,
			TEXT("coach-session-queue"),
			ChronicleEvent.ProvenanceLinks
		);
		if (!QueueState.ActiveTrainingSessionId.IsEmpty())
		{
			const FString RunEntityId = FString::Printf(
				TEXT("memory-entity/chronicle/run-record/%s"),
				*QueueState.ActiveTrainingSessionId
			);
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				LedgerEntitiesById,
				RunEntityId,
				TEXT("training-run-record"),
				ChronicleEvent.ProvenanceLinks
			);
		}
		HyperTwistMemoryCoreLibraryInternal::AddChronicleEvent(
			ChronicleContinuityState,
			ChronicleEvent
		);

		TArray<FString> QueueEventIds = {ChronicleEvent.EventId};
		if (const TArray<FString>* QueueHistoryEventIds =
				QueueHistoryEventIdsByQueueId.Find(QueueState.QueueId))
		{
			for (const FString& QueueHistoryEventId : *QueueHistoryEventIds)
			{
				HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
					QueueEventIds,
					QueueHistoryEventId
				);
			}
		}

		FHyperTwistMemorySessionGroup SessionGroup;
		SessionGroup.GroupId = FString::Printf(
			TEXT("memory-session-group/coach-session-queue/%s"),
			*QueueState.QueueId
		);
		SessionGroup.GroupKind = TEXT("coach-session-queue");
		SessionGroup.Headline = ChronicleEvent.DisplayLabel;
		SessionGroup.UserId = UserId;
		SessionGroup.DeckId = QueueState.FocusDeckId;
		SessionGroup.RootRecordId = QueueState.QueueId;
		SessionGroup.RootQueueId = QueueState.QueueId;
		SessionGroup.ReferenceUtc = ChronicleEvent.RecordedAtUtc;
		SessionGroup.ChronicleEventIds = QueueEventIds;
		SessionGroup.FocusCaseIds =
			HyperTwistMemoryCoreLibraryInternal::CollectQueueFocusCaseIds(
				QueueState,
				false
			);
		SessionGroup.EventCount = SessionGroup.ChronicleEventIds.Num();
		SessionGroup.bCompleted = !ChronicleEvent.bOpenContinuity;
		SessionGroup.bHasResumeCandidate = ChronicleEvent.bOpenContinuity;
		SessionGroup.ProvenanceLinks = ChronicleEvent.ProvenanceLinks;
		HyperTwistMemoryCoreLibraryInternal::AddSessionGroup(
			ChronicleContinuityState,
			SessionGroup
		);
		SessionGroupIdByQueueId.Add(QueueState.QueueId, SessionGroup.GroupId);

		if (ChronicleEvent.bOpenContinuity)
		{
			FHyperTwistMemoryResumePack ResumePack;
			ResumePack.PackId = FString::Printf(
				TEXT("memory-resume-pack/coach-session-queue/%s"),
				*QueueState.QueueId
			);
			ResumePack.PackKind = TEXT("coach-session-queue-resume");
			ResumePack.Headline = TEXT("Resume Coach Session Queue");
			ResumePack.UserId = UserId;
			ResumePack.DeckId = QueueState.FocusDeckId;
			ResumePack.ResumeTargetId = QueueState.QueueId;
			ResumePack.ResumeActionId = TEXT("resume-coach-session-queue");
			ResumePack.ReferenceUtc = ChronicleEvent.RecordedAtUtc;
			ResumePack.ChronicleGroupIds = {SessionGroup.GroupId};
			ResumePack.FocusCaseIds =
				HyperTwistMemoryCoreLibraryInternal::CollectQueueFocusCaseIds(
					QueueState,
					true
				);
			ResumePack.PendingItemCount = FMath::Max(
				1,
				HyperTwistMemoryCoreLibraryInternal::CountOpenQueueEntries(QueueState)
			);
			ResumePack.bTimeSensitive = !QueueState.ActiveEntryId.IsEmpty();
			ResumePack.ProvenanceLinks = ChronicleEvent.ProvenanceLinks;
			HyperTwistMemoryCoreLibraryInternal::AddResumePack(
				ChronicleContinuityState,
				ResumePack
			);
		}
	}

	const FHyperTwistTrainingRepositoryIntegrityReport IntegrityReport =
		UHyperTwistTrainingRepositoryLibrary::DeriveRepositoryIntegrityReport(RepositoryState);

	const bool bHasGeneralIntegrityIssue = IntegrityReport.InvalidRunRecordCount > 0
		|| IntegrityReport.DuplicateRunRecordCount > 0
		|| IntegrityReport.InvalidLearnerStateCount > 0
		|| IntegrityReport.DuplicateLearnerStateCount > 0
		|| IntegrityReport.InvalidReviewPlanCount > 0
		|| IntegrityReport.DuplicateReviewPlanCount > 0
		|| IntegrityReport.InvalidStoredSessionTemplateCount > 0
		|| IntegrityReport.DuplicateStoredSessionTemplateCount > 0
		|| IntegrityReport.InvalidMethodDrillFavoriteCount > 0
		|| IntegrityReport.DuplicateMethodDrillFavoriteCount > 0
		|| IntegrityReport.InvalidMethodDrillBatchCount > 0
		|| IntegrityReport.DuplicateMethodDrillBatchCount > 0
		|| IntegrityReport.InvalidFriendLinkCount > 0
		|| IntegrityReport.DuplicateFriendLinkCount > 0
		|| IntegrityReport.InvalidNotificationCount > 0
		|| IntegrityReport.DuplicateNotificationCount > 0
		|| IntegrityReport.InvalidChallengeCount > 0
		|| IntegrityReport.DuplicateChallengeCount > 0;

	const bool bHasReviewContinuityIssue = IntegrityReport.OutOfSyncLearnerStateCount > 0
		|| IntegrityReport.OutOfSyncReviewPlanCount > 0;
	const bool bHasCoachLineageIssue = IntegrityReport.InvalidCoachActionPlanCount > 0
		|| IntegrityReport.DuplicateCoachActionPlanCount > 0
		|| IntegrityReport.MissingCoachActionPlanSourceSessionCount > 0
		|| IntegrityReport.MissingCoachActionPlanSourceReviewPlanCount > 0
		|| IntegrityReport.OrphanedCoachActionPlanParentCount > 0
		|| IntegrityReport.OrphanedCoachActionPlanRootCount > 0
		|| IntegrityReport.CyclicCoachActionPlanLineageCount > 0
		|| IntegrityReport.BrokenCoachActionPlanDepthCount > 0
		|| IntegrityReport.OutOfSyncCoachActionPlanCount > 0;
	const bool bHasQueueContinuityIssue = IntegrityReport.InvalidCoachSessionQueueCount > 0
		|| IntegrityReport.DuplicateCoachSessionQueueCount > 0
		|| IntegrityReport.OutOfSyncCoachSessionQueueCount > 0
		|| IntegrityReport.MissingCoachSessionQueueSourceSessionCount > 0
		|| IntegrityReport.InvalidCoachSessionQueueActiveEntryCount > 0
		|| IntegrityReport.MissingCoachSessionQueueActiveSessionCount > 0
		|| IntegrityReport.InvalidCoachSessionQueueHistoryCount > 0
		|| IntegrityReport.DuplicateCoachSessionQueueHistoryCount > 0
		|| IntegrityReport.OutOfSyncCoachSessionQueueHistoryCount > 0
		|| IntegrityReport.MissingCoachSessionQueueHistorySourceSessionCount > 0
		|| IntegrityReport.MissingCoachSessionQueueHistoryQueueCount > 0
		|| IntegrityReport.MissingCoachSessionQueueHistoryEntryCount > 0;
	const bool bHasSmartDeviceContinuityIssue = IntegrityReport.InvalidSmartDeviceSessionCount > 0
		|| IntegrityReport.DuplicateSmartDeviceSessionCount > 0
		|| IntegrityReport.MissingSmartDeviceSessionSourceSessionCount > 0
		|| IntegrityReport.InvalidSmartDeviceEventFrameCount > 0
		|| IntegrityReport.DuplicateSmartDeviceEventFrameCount > 0
		|| IntegrityReport.MissingSmartDeviceEventSourceSessionCount > 0
		|| IntegrityReport.MissingSmartDeviceEventSessionRecordCount > 0
		|| IntegrityReport.MissingSmartDeviceEventAttemptLinkCount > 0;

	if (bHasGeneralIntegrityIssue)
	{
		FHyperTwistMemoryContinuityGuard ContinuityGuard;
		ContinuityGuard.GuardId = FString::Printf(
			TEXT("memory-continuity-guard/repository-integrity/%s"),
			*UserId
		);
		ContinuityGuard.GuardKind = TEXT("repository-integrity");
		ContinuityGuard.Headline = TEXT("Repository integrity repair required");
		ContinuityGuard.UserId = UserId;
		ContinuityGuard.ReferenceUtc = ResolvedReferenceUtc;
		ContinuityGuard.Severity = EHyperTwistMemoryContinuityGuardSeverity::Advisory;
		ContinuityGuard.bRequiresManualReview = true;
		ContinuityGuard.RepairActions = IntegrityReport.RepairActions;
		HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
			LedgerEntitiesById,
			LedgerContractEntityId,
			TEXT("memory-ledger-contract"),
			ContinuityGuard.ProvenanceLinks
		);
		HyperTwistMemoryCoreLibraryInternal::AddContinuityGuard(
			ChronicleContinuityState,
			ContinuityGuard
		);
	}

	if (bHasReviewContinuityIssue)
	{
		FHyperTwistMemoryContinuityGuard ContinuityGuard;
		ContinuityGuard.GuardId = FString::Printf(
			TEXT("memory-continuity-guard/review-program/%s"),
			*UserId
		);
		ContinuityGuard.GuardKind = TEXT("review-program-continuity");
		ContinuityGuard.Headline = TEXT("Review continuity requires reconciliation");
		ContinuityGuard.UserId = UserId;
		ContinuityGuard.ReferenceUtc = ResolvedReferenceUtc;
		ContinuityGuard.Severity = EHyperTwistMemoryContinuityGuardSeverity::Warning;
		ContinuityGuard.bRequiresManualReview = true;
		ContinuityGuard.RepairActions = IntegrityReport.RepairActions;
		for (const FHyperTwistTrainingReviewPlanState& ReviewPlan : RepositoryState.ReviewPlans)
		{
			HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
				ContinuityGuard.RelatedRecordIds,
				ReviewPlan.PlanId
			);
			if (!ReviewPlan.PlanId.IsEmpty())
			{
				const FString ReviewPlanEntityId = FString::Printf(
					TEXT("memory-entity/workflow/review-plan/%s"),
					*ReviewPlan.PlanId
				);
				HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
					LedgerEntitiesById,
					ReviewPlanEntityId,
					TEXT("training-review-plan"),
					ContinuityGuard.ProvenanceLinks
				);
				break;
			}
		}
		HyperTwistMemoryCoreLibraryInternal::AddContinuityGuard(
			ChronicleContinuityState,
			ContinuityGuard
		);
	}

	if (bHasCoachLineageIssue)
	{
		FHyperTwistMemoryContinuityGuard ContinuityGuard;
		ContinuityGuard.GuardId = FString::Printf(
			TEXT("memory-continuity-guard/coach-lineage/%s"),
			*UserId
		);
		ContinuityGuard.GuardKind = TEXT("coach-lineage");
		ContinuityGuard.Headline = TEXT("Coach follow-up lineage is broken");
		ContinuityGuard.UserId = UserId;
		ContinuityGuard.ReferenceUtc = ResolvedReferenceUtc;
		ContinuityGuard.Severity = EHyperTwistMemoryContinuityGuardSeverity::Blocking;
		ContinuityGuard.bBlocksResume = true;
		ContinuityGuard.bRequiresManualReview = true;
		ContinuityGuard.RepairActions = IntegrityReport.RepairActions;
		for (const FHyperTwistTrainingCoachActionPlan& CoachActionPlan :
			RepositoryState.StoredCoachActionPlans)
		{
			HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
				ContinuityGuard.RelatedRecordIds,
				CoachActionPlan.PlanId
			);
			if (!CoachActionPlan.PlanId.IsEmpty())
			{
				const FString CoachPlanEntityId = FString::Printf(
					TEXT("memory-entity/workflow/coach-action-plan/%s"),
					*CoachActionPlan.PlanId
				);
				HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
					LedgerEntitiesById,
					CoachPlanEntityId,
					TEXT("coach-action-plan"),
					ContinuityGuard.ProvenanceLinks
				);
				break;
			}
		}
		if (ContinuityGuard.ProvenanceLinks.Num() == 0)
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				LedgerEntitiesById,
				LedgerContractEntityId,
				TEXT("memory-ledger-contract"),
				ContinuityGuard.ProvenanceLinks
			);
		}
		HyperTwistMemoryCoreLibraryInternal::AddContinuityGuard(
			ChronicleContinuityState,
			ContinuityGuard
		);
	}

	if (bHasQueueContinuityIssue)
	{
		FHyperTwistMemoryContinuityGuard ContinuityGuard;
		ContinuityGuard.GuardId = FString::Printf(
			TEXT("memory-continuity-guard/coach-session-queue/%s"),
			*UserId
		);
		ContinuityGuard.GuardKind = TEXT("coach-session-queue");
		ContinuityGuard.Headline = TEXT("Coach session queue continuity is broken");
		ContinuityGuard.UserId = UserId;
		ContinuityGuard.ReferenceUtc = ResolvedReferenceUtc;
		ContinuityGuard.Severity = EHyperTwistMemoryContinuityGuardSeverity::Blocking;
		ContinuityGuard.bBlocksResume = true;
		ContinuityGuard.bRequiresManualReview = true;
		ContinuityGuard.RepairActions = IntegrityReport.RepairActions;
		for (const FHyperTwistTrainingCoachSessionQueueState& QueueState :
			RepositoryState.StoredCoachSessionQueues)
		{
			HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
				ContinuityGuard.RelatedRecordIds,
				QueueState.QueueId
			);
			if (!QueueState.QueueId.IsEmpty())
			{
				const FString QueueEntityId = FString::Printf(
					TEXT("memory-entity/workflow/coach-session-queue/%s"),
					*QueueState.QueueId
				);
				HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
					LedgerEntitiesById,
					QueueEntityId,
					TEXT("coach-session-queue"),
					ContinuityGuard.ProvenanceLinks
				);
				break;
			}
		}
		if (ContinuityGuard.ProvenanceLinks.Num() == 0)
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				LedgerEntitiesById,
				LedgerContractEntityId,
				TEXT("memory-ledger-contract"),
				ContinuityGuard.ProvenanceLinks
			);
		}
		HyperTwistMemoryCoreLibraryInternal::AddContinuityGuard(
			ChronicleContinuityState,
			ContinuityGuard
		);
	}

	if (bHasSmartDeviceContinuityIssue)
	{
		FHyperTwistMemoryContinuityGuard ContinuityGuard;
		ContinuityGuard.GuardId = FString::Printf(
			TEXT("memory-continuity-guard/smart-device/%s"),
			*UserId
		);
		ContinuityGuard.GuardKind = TEXT("smart-device-continuity");
		ContinuityGuard.Headline = TEXT("Smart-device continuity requires review");
		ContinuityGuard.UserId = UserId;
		ContinuityGuard.ReferenceUtc = ResolvedReferenceUtc;
		ContinuityGuard.Severity = EHyperTwistMemoryContinuityGuardSeverity::Warning;
		ContinuityGuard.bRequiresManualReview = true;
		ContinuityGuard.RepairActions = IntegrityReport.RepairActions;
		HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
			LedgerEntitiesById,
			LedgerContractEntityId,
			TEXT("memory-ledger-contract"),
			ContinuityGuard.ProvenanceLinks
		);
		HyperTwistMemoryCoreLibraryInternal::AddContinuityGuard(
			ChronicleContinuityState,
			ContinuityGuard
		);
	}

	for (FHyperTwistMemorySessionGroup& SessionGroup : ChronicleContinuityState.SessionGroups)
	{
		if ((SessionGroup.GroupKind == TEXT("review-plan") && bHasReviewContinuityIssue)
			|| (SessionGroup.GroupKind == TEXT("coach-session-queue")
				&& (bHasCoachLineageIssue || bHasQueueContinuityIssue)))
		{
			SessionGroup.bRequiresContinuityGuard = true;
		}
	}

	for (FHyperTwistMemoryResumePack& ResumePack : ChronicleContinuityState.ResumePacks)
	{
		if ((ResumePack.PackKind == TEXT("review-plan-resume") && bHasReviewContinuityIssue)
			|| (ResumePack.PackKind == TEXT("coach-session-queue-resume")
				&& (bHasCoachLineageIssue || bHasQueueContinuityIssue)))
		{
			ResumePack.bNeedsContinuityGuard = true;
		}
	}

	for (const FHyperTwistMemoryChronicleEventEntry& ChronicleEvent :
		ChronicleContinuityState.ChronicleEvents)
	{
		if (ChronicleEvent.Lane == EHyperTwistMemoryLane::ChronicleCapture)
		{
			++ChronicleContinuityState.ChronicleCaptureEventCount;
		}
		else if (ChronicleEvent.Lane == EHyperTwistMemoryLane::ContinuityResume)
		{
			++ChronicleContinuityState.ContinuityResumeEventCount;
		}
	}

	for (const FHyperTwistMemorySessionGroup& SessionGroup :
		ChronicleContinuityState.SessionGroups)
	{
		if (!SessionGroup.bCompleted)
		{
			++ChronicleContinuityState.OpenSessionGroupCount;
		}
	}

	ChronicleContinuityState.ResumeRequiredCount =
		ChronicleContinuityState.ResumePacks.Num();

	for (const FHyperTwistMemoryContinuityGuard& ContinuityGuard :
		ChronicleContinuityState.ContinuityGuards)
	{
		if (ContinuityGuard.Severity == EHyperTwistMemoryContinuityGuardSeverity::Blocking)
		{
			++ChronicleContinuityState.BlockingGuardCount;
		}
	}

	ChronicleContinuityState.bHasRepositoryContinuityIssues =
		ChronicleContinuityState.ContinuityGuards.Num() > 0;

	if (!ChronicleContinuityState.IsStructurallyValid())
	{
		return FHyperTwistMemoryChronicleContinuityState();
	}

	return ChronicleContinuityState;
}

FHyperTwistMemoryRecallSharedContextState
	UHyperTwistMemoryCoreLibrary::DeriveMemoryRecallSharedContextState(
		const FHyperTwistTrainingRepositoryState& RepositoryState,
		const FString& UserId,
		const FString& ReferenceUtc,
		const FString& QueryText
	)
{
	FHyperTwistMemoryRecallSharedContextState RecallState;
	if (UserId.IsEmpty())
	{
		return RecallState;
	}

	const FString ResolvedReferenceUtc =
		HyperTwistMemoryCoreLibraryInternal::ResolveReferenceUtc(ReferenceUtc);
	RecallState.UserId = UserId;
	RecallState.ReferenceUtc = ResolvedReferenceUtc;
	RecallState.QueryText = QueryText.TrimStartAndEnd().IsEmpty()
		? TEXT("resume review coach history")
		: QueryText.TrimStartAndEnd();
	RecallState.QueryTokens =
		HyperTwistMemoryCoreLibraryInternal::TokenizeSearchText(RecallState.QueryText);
	if (RecallState.QueryTokens.Num() == 0)
	{
		RecallState.QueryText = TEXT("resume review coach history");
		RecallState.QueryTokens =
			HyperTwistMemoryCoreLibraryInternal::TokenizeSearchText(RecallState.QueryText);
	}

	RecallState.SharedContextRules = {
		HyperTwistMemoryCoreLibraryInternal::MakeSharedContextRule(
			TEXT("memory-shared-rule/coach-follow-up"),
			TEXT("coach-follow-up"),
			TEXT("Coach Follow-Up"),
			EHyperTwistMemoryLane::SharedCoordination,
			{
				TEXT("review-program-summary"),
				TEXT("coach-session-queue-execution-summary"),
				TEXT("coach-memory-snapshot"),
				TEXT("coach-closure-memory-summary"),
				TEXT("coach-recommendation-history-summary")
			},
			{
				TEXT("coach-panel"),
				TEXT("companion-follow-up-brief")
			},
			true,
			true,
			true,
			TEXT("Share only bounded coach/review summaries into follow-up work.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeSharedContextRule(
			TEXT("memory-shared-rule/replay-review"),
			TEXT("replay-review"),
			TEXT("Replay Review"),
			EHyperTwistMemoryLane::ContinuityResume,
			{
				TEXT("training-run-record"),
				TEXT("training-review-plan")
			},
			{
				TEXT("replay-review-panel"),
				TEXT("attempt-inspector")
			},
			true,
			true,
			true,
			TEXT("Expose revocable review continuity into replay and attempt inspection only.")
		),
		HyperTwistMemoryCoreLibraryInternal::MakeSharedContextRule(
			TEXT("memory-shared-rule/sidecar-brief"),
			TEXT("sidecar-brief"),
			TEXT("Sidecar Brief"),
			EHyperTwistMemoryLane::RecallRetrieval,
			{
				TEXT("review-program-summary"),
				TEXT("coach-session-queue-execution-summary"),
				TEXT("coach-memory-snapshot"),
				TEXT("training-review-plan")
			},
			{
				TEXT("speech-sidecar-brief"),
				TEXT("recognition-handoff")
			},
			true,
			true,
			true,
			TEXT("Permit narrow shared briefings without exporting raw chronicle data.")
		)
	};

	const FHyperTwistMemoryLedgerState MemoryLedgerState = DeriveMemoryLedgerState(
		RepositoryState,
		UserId,
		ResolvedReferenceUtc
	);
	const FHyperTwistMemoryChronicleContinuityState ChronicleContinuityState =
		DeriveMemoryChronicleContinuityState(RepositoryState, UserId, ResolvedReferenceUtc);

	TMap<FString, FHyperTwistMemoryEntityDescriptor> LedgerEntitiesById;
	for (const FHyperTwistMemoryEntityDescriptor& Entity : MemoryLedgerState.Entities)
	{
		LedgerEntitiesById.Add(Entity.EntityId, Entity);
	}

	TArray<HyperTwistMemoryCoreLibraryInternal::FHyperTwistMemoryRecallCandidate> Candidates;
	for (const FHyperTwistMemoryEntityDescriptor& Entity : MemoryLedgerState.Entities)
	{
		if (Entity.UserId != UserId)
		{
			continue;
		}

		const bool bRecallRelevantEntity =
			Entity.Lane == EHyperTwistMemoryLane::RecallRetrieval
			|| Entity.Lane == EHyperTwistMemoryLane::SharedCoordination
			|| Entity.Lane == EHyperTwistMemoryLane::CognitiveConsolidated
			|| Entity.Lane == EHyperTwistMemoryLane::ProceduralWorkflow;
		if (!bRecallRelevantEntity)
		{
			continue;
		}

		HyperTwistMemoryCoreLibraryInternal::FHyperTwistMemoryRecallCandidate Candidate;
		Candidate.MatchId = FString::Printf(
			TEXT("memory-recall-match/entity/%s"),
			*Entity.EntityId
		);
		Candidate.MatchKind =
			Entity.Lane == EHyperTwistMemoryLane::RecallRetrieval
				? TEXT("history-search")
				: (Entity.Lane == EHyperTwistMemoryLane::SharedCoordination
					? TEXT("shared-summary")
					: TEXT("coach-recall"));
		Candidate.Headline = Entity.DisplayLabel;
		Candidate.UserId = UserId;
		Candidate.DeckId = Entity.DeckId;
		Candidate.SourceEntityId = Entity.EntityId;
		Candidate.SourceRecordKind = Entity.RecordKind;
		Candidate.SourceRecordId = Entity.EntityId;
		Candidate.ReferenceUtc = Entity.ReferenceUtc;
		Candidate.Lane = Entity.Lane;
		Candidate.AuthorityKind = Entity.AuthorityKind;
		Candidate.ProvenanceLinks = Entity.ProvenanceLinks;
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			Entity.DisplayLabel
		);
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			Entity.RecordKind.Replace(TEXT("-"), TEXT(" "))
		);
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			Entity.DeckId
		);
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			Entity.EntityId
		);
		HyperTwistMemoryCoreLibraryInternal::AddRecallCandidate(Candidates, Candidate);
	}

	for (const FHyperTwistMemorySessionGroup& SessionGroup :
		ChronicleContinuityState.SessionGroups)
	{
		const FString SourceRecordKind =
			HyperTwistMemoryCoreLibraryInternal::ResolveSessionGroupSourceRecordKind(
				SessionGroup
			);
		const FString SourceEntityId =
			HyperTwistMemoryCoreLibraryInternal::ResolveSessionGroupSourceEntityId(
				SessionGroup
			);
		const FHyperTwistMemoryEntityDescriptor* SourceEntity =
			LedgerEntitiesById.Find(SourceEntityId);

		HyperTwistMemoryCoreLibraryInternal::FHyperTwistMemoryRecallCandidate Candidate;
		Candidate.MatchId = FString::Printf(
			TEXT("memory-recall-match/session-group/%s"),
			*SessionGroup.GroupId
		);
		Candidate.MatchKind = TEXT("history-search");
		Candidate.Headline = SessionGroup.Headline;
		Candidate.UserId = UserId;
		Candidate.DeckId = SessionGroup.DeckId;
		Candidate.SourceEntityId = SourceEntityId;
		Candidate.SourceRecordKind = SourceRecordKind;
		Candidate.SourceRecordId = SessionGroup.RootRecordId;
		Candidate.ReferenceUtc = SessionGroup.ReferenceUtc;
		Candidate.Lane = SourceEntity != nullptr
			? SourceEntity->Lane
			: EHyperTwistMemoryLane::ContinuityResume;
		Candidate.AuthorityKind = SourceEntity != nullptr
			? SourceEntity->AuthorityKind
			: EHyperTwistMemoryAuthorityKind::Authoritative;
		Candidate.ProvenanceLinks = SessionGroup.ProvenanceLinks;
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			SessionGroup.GroupKind.Replace(TEXT("-"), TEXT(" "))
		);
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			SessionGroup.Headline
		);
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			FString::Join(SessionGroup.FocusCaseIds, TEXT(" "))
		);
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			SessionGroup.bHasResumeCandidate
				? TEXT("open resume current history")
				: TEXT("completed history")
		);
		HyperTwistMemoryCoreLibraryInternal::AddRecallCandidate(Candidates, Candidate);
	}

	for (const FHyperTwistMemoryResumePack& ResumePack :
		ChronicleContinuityState.ResumePacks)
	{
		const FString SourceRecordKind =
			HyperTwistMemoryCoreLibraryInternal::ResolveResumePackSourceRecordKind(ResumePack);
		const FString SourceEntityId =
			HyperTwistMemoryCoreLibraryInternal::ResolveResumePackSourceEntityId(ResumePack);
		const FHyperTwistMemoryEntityDescriptor* SourceEntity =
			LedgerEntitiesById.Find(SourceEntityId);

		HyperTwistMemoryCoreLibraryInternal::FHyperTwistMemoryRecallCandidate Candidate;
		Candidate.MatchId = FString::Printf(
			TEXT("memory-recall-match/resume-pack/%s"),
			*ResumePack.PackId
		);
		Candidate.MatchKind = TEXT("remember-focus");
		Candidate.Headline = ResumePack.Headline;
		Candidate.UserId = UserId;
		Candidate.DeckId = ResumePack.DeckId;
		Candidate.SourceEntityId = SourceEntityId;
		Candidate.SourceRecordKind = SourceRecordKind;
		Candidate.SourceRecordId = ResumePack.ResumeTargetId;
		Candidate.ReferenceUtc = ResumePack.ReferenceUtc;
		Candidate.Lane = SourceEntity != nullptr
			? SourceEntity->Lane
			: EHyperTwistMemoryLane::ContinuityResume;
		Candidate.AuthorityKind = SourceEntity != nullptr
			? SourceEntity->AuthorityKind
			: EHyperTwistMemoryAuthorityKind::Authoritative;
		Candidate.ProvenanceLinks = ResumePack.ProvenanceLinks;
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			ResumePack.PackKind.Replace(TEXT("-"), TEXT(" "))
		);
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			ResumePack.Headline
		);
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			FString::Join(ResumePack.FocusCaseIds, TEXT(" "))
		);
		HyperTwistMemoryCoreLibraryInternal::AppendSearchFragment(
			Candidate.SearchableText,
			TEXT("resume remember current pending history")
		);
		HyperTwistMemoryCoreLibraryInternal::AddRecallCandidate(Candidates, Candidate);
	}

	TArray<FHyperTwistMemoryRecallMatch> ScoredMatches;
	for (const HyperTwistMemoryCoreLibraryInternal::FHyperTwistMemoryRecallCandidate& Candidate :
		Candidates)
	{
		TArray<FString> MatchedTokens;
		const int32 MatchScore = HyperTwistMemoryCoreLibraryInternal::ScoreRecallCandidate(
			Candidate,
			RecallState.QueryTokens,
			MatchedTokens
		);
		if (MatchScore <= 0)
		{
			continue;
		}

		FHyperTwistMemoryRecallMatch RecallMatch;
		RecallMatch.MatchId = Candidate.MatchId;
		RecallMatch.MatchKind = Candidate.MatchKind;
		RecallMatch.Headline = Candidate.Headline;
		RecallMatch.UserId = Candidate.UserId;
		RecallMatch.DeckId = Candidate.DeckId;
		RecallMatch.SourceEntityId = Candidate.SourceEntityId;
		RecallMatch.SourceRecordKind = Candidate.SourceRecordKind;
		RecallMatch.SourceRecordId = Candidate.SourceRecordId;
		RecallMatch.ReferenceUtc = Candidate.ReferenceUtc;
		RecallMatch.Lane = Candidate.Lane;
		RecallMatch.AuthorityKind = Candidate.AuthorityKind;
		RecallMatch.MatchScore = MatchScore;
		RecallMatch.ProvenanceLinks = Candidate.ProvenanceLinks;
		for (const FString& MatchedToken : MatchedTokens)
		{
			RecallMatch.MatchReasonLines.Add(
				FString::Printf(TEXT("Matched query token '%s'."), *MatchedToken)
			);
		}
		if (Candidate.MatchKind == TEXT("remember-focus"))
		{
			RecallMatch.MatchReasonLines.Add(
				TEXT("Pinned as revivable current-work memory rather than passive history.")
			);
		}
		if (HyperTwistMemoryCoreLibraryInternal::HasAuthoritativeProvenance(
				Candidate.ProvenanceLinks))
		{
			RecallMatch.MatchReasonLines.Add(
				TEXT("Retains direct authoritative provenance.")
			);
		}

		if (RecallMatch.IsStructurallyValid())
		{
			ScoredMatches.Add(RecallMatch);
		}
	}

	ScoredMatches.Sort(
		[](const FHyperTwistMemoryRecallMatch& Left, const FHyperTwistMemoryRecallMatch& Right)
		{
			if (Left.MatchScore != Right.MatchScore)
			{
				return Left.MatchScore > Right.MatchScore;
			}

			return Left.Headline < Right.Headline;
		}
	);
	if (ScoredMatches.Num() > 12)
	{
		ScoredMatches.SetNum(12);
	}

	RecallState.RecallMatches = MoveTemp(ScoredMatches);

	for (const FHyperTwistMemoryRecallMatch& RecallMatch : RecallState.RecallMatches)
	{
		FHyperTwistMemoryProvenanceDrillDownEntry DrillDownEntry;
		DrillDownEntry.DrillDownId = FString::Printf(
			TEXT("memory-provenance-drilldown/%s"),
			*RecallMatch.MatchId
		);
		DrillDownEntry.RootEntityId = RecallMatch.SourceEntityId;
		DrillDownEntry.RootRecordKind = RecallMatch.SourceRecordKind;
		DrillDownEntry.Headline = RecallMatch.Headline;
		DrillDownEntry.Lane = RecallMatch.Lane;
		DrillDownEntry.AuthorityKind = RecallMatch.AuthorityKind;
		DrillDownEntry.ProvenanceLinks = RecallMatch.ProvenanceLinks;

		TSet<FString> VisitedEntityIds;
		HyperTwistMemoryCoreLibraryInternal::CollectEntityLineage(
			LedgerEntitiesById,
			RecallMatch.SourceEntityId,
			VisitedEntityIds,
			DrillDownEntry.LineageEntityIds,
			DrillDownEntry.SourceLabels,
			DrillDownEntry.bHasAuthoritativeLineage
		);
		if (DrillDownEntry.LineageEntityIds.Num() == 0)
		{
			HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
				DrillDownEntry.LineageEntityIds,
				RecallMatch.SourceEntityId
			);
		}
		DrillDownEntry.ProvenanceDepth =
			FMath::Max(DrillDownEntry.LineageEntityIds.Num() - 1, 0);

		if (DrillDownEntry.IsStructurallyValid()
			&& !RecallState.ProvenanceDrillDownEntries.ContainsByPredicate(
				[&DrillDownEntry](
					const FHyperTwistMemoryProvenanceDrillDownEntry& ExistingEntry)
				{
					return ExistingEntry.RootEntityId == DrillDownEntry.RootEntityId;
				}))
		{
			RecallState.ProvenanceDrillDownEntries.Add(DrillDownEntry);
		}
	}

	for (const FHyperTwistMemorySharedContextRule& SharedContextRule :
		RecallState.SharedContextRules)
	{
		FHyperTwistMemorySharedContextProjection Projection;
		Projection.ProjectionId = FString::Printf(
			TEXT("memory-shared-projection/%s/%s"),
			*SharedContextRule.ContextId,
			*UserId
		);
		Projection.ContextId = SharedContextRule.ContextId;
		Projection.Headline = SharedContextRule.DisplayLabel;
		Projection.UserId = UserId;
		Projection.ReferenceUtc = ResolvedReferenceUtc;
		Projection.RuleId = SharedContextRule.RuleId;
		Projection.bRevocable = SharedContextRule.bRevocable;
		Projection.bSessionLocalOnly = SharedContextRule.bSessionLocalOnly;
		Projection.bRequiresAuthoritativeProvenance =
			SharedContextRule.bRequiresAuthoritativeProvenance;

		for (const FHyperTwistMemoryRecallMatch& RecallMatch : RecallState.RecallMatches)
		{
			if (!SharedContextRule.AllowedRecordKinds.Contains(RecallMatch.SourceRecordKind))
			{
				continue;
			}

			const bool bQualifiesForSharedContext = !SharedContextRule.bRequiresAuthoritativeProvenance
				|| RecallMatch.AuthorityKind == EHyperTwistMemoryAuthorityKind::Authoritative
				|| HyperTwistMemoryCoreLibraryInternal::HasAuthoritativeProvenance(
					RecallMatch.ProvenanceLinks);
			if (!bQualifiesForSharedContext)
			{
				continue;
			}

			HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
				Projection.RelatedMatchIds,
				RecallMatch.MatchId
			);
			HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
				Projection.RelatedEntityIds,
				RecallMatch.SourceEntityId
			);
			for (const FHyperTwistMemoryProvenanceLink& ProvenanceLink :
				RecallMatch.ProvenanceLinks)
			{
				HyperTwistMemoryCoreLibraryInternal::AddUniqueProvenanceLink(
					Projection.ProvenanceLinks,
					ProvenanceLink
				);
			}
		}

		HyperTwistMemoryCoreLibraryInternal::AddSharedContextProjection(
			RecallState,
			Projection
		);
	}

	RecallState.RecallResultCount = RecallState.RecallMatches.Num();
	for (const FHyperTwistMemoryRecallMatch& RecallMatch : RecallState.RecallMatches)
	{
		if (RecallMatch.AuthorityKind == EHyperTwistMemoryAuthorityKind::Authoritative)
		{
			++RecallState.AuthoritativeRecallCount;
		}
		else if (RecallMatch.AuthorityKind ==
			EHyperTwistMemoryAuthorityKind::SemiAuthoritative)
		{
			++RecallState.SemiAuthoritativeRecallCount;
		}
	}

	RecallState.SharedContextProjectionCount =
		RecallState.SharedContextProjections.Num();
	RecallState.bHasScopedSharedContext =
		RecallState.SharedContextProjectionCount > 0;

	if (!RecallState.IsStructurallyValid())
	{
		return FHyperTwistMemoryRecallSharedContextState();
	}

	return RecallState;
}

FHyperTwistMemoryCognitiveConsolidationState
	UHyperTwistMemoryCoreLibrary::DeriveMemoryCognitiveConsolidationState(
		const FHyperTwistTrainingRepositoryState& RepositoryState,
		const FString& UserId,
		const FString& ReferenceUtc
	)
{
	FHyperTwistMemoryCognitiveConsolidationState CognitiveState;
	if (UserId.IsEmpty())
	{
		return CognitiveState;
	}

	const FString ResolvedReferenceUtc =
		HyperTwistMemoryCoreLibraryInternal::ResolveReferenceUtc(ReferenceUtc);
	CognitiveState.UserId = UserId;
	CognitiveState.ReferenceUtc = ResolvedReferenceUtc;

	const FHyperTwistMemoryLedgerState MemoryLedgerState = DeriveMemoryLedgerState(
		RepositoryState,
		UserId,
		ResolvedReferenceUtc
	);

	TMap<FString, FHyperTwistMemoryEntityDescriptor> LedgerEntitiesById;
	for (const FHyperTwistMemoryEntityDescriptor& Entity : MemoryLedgerState.Entities)
	{
		LedgerEntitiesById.Add(Entity.EntityId, Entity);
	}

	const FString ReviewProgramEntityId = FString::Printf(
		TEXT("memory-entity/recall/review-program-summary/%s"),
		*UserId
	);
	const FString CoachMemoryEntityId = FString::Printf(
		TEXT("memory-entity/cognitive/coach-memory-snapshot/%s"),
		*UserId
	);
	const FString CoachClosureEntityId = FString::Printf(
		TEXT("memory-entity/cognitive/coach-closure-memory-summary/%s"),
		*UserId
	);
	const FString RecommendationHistoryEntityId = FString::Printf(
		TEXT("memory-entity/cognitive/coach-recommendation-history-summary/%s"),
		*UserId
	);
	const FString CarryForwardEntityId = FString::Printf(
		TEXT("memory-entity/cognitive/coach-carry-forward-policy-summary/%s"),
		*UserId
	);
	const FString ArchivePolicyEntityId = FString::Printf(
		TEXT("memory-entity/cognitive/coach-archive-policy-summary/%s"),
		*UserId
	);

	TMap<FString, int32> FactIndexById;

	auto AppendEntityProvenanceChain =
		[&LedgerEntitiesById](
			const FString& EntityId,
			const FString& SourceLabel,
			TArray<FHyperTwistMemoryProvenanceLink>& ProvenanceLinks)
		{
			if (EntityId.IsEmpty())
			{
				return;
			}

			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				LedgerEntitiesById,
				EntityId,
				SourceLabel,
				ProvenanceLinks
			);

			const FHyperTwistMemoryEntityDescriptor* Entity = LedgerEntitiesById.Find(EntityId);
			if (Entity == nullptr)
			{
				return;
			}

			for (const FHyperTwistMemoryProvenanceLink& ProvenanceLink : Entity->ProvenanceLinks)
			{
				HyperTwistMemoryCoreLibraryInternal::AddUniqueProvenanceLink(
					ProvenanceLinks,
					ProvenanceLink
				);
			}
		};

	auto AddFact =
		[&](const FHyperTwistMemoryCognitiveFact& Fact)
		{
			if (!Fact.IsStructurallyValid() || FactIndexById.Contains(Fact.FactId))
			{
				return;
			}

			const int32 NewIndex = CognitiveState.Facts.Add(Fact);
			FactIndexById.Add(Fact.FactId, NewIndex);
		};

	auto AddContradiction =
		[&](const FHyperTwistMemoryCognitiveContradiction& Contradiction)
		{
			if (!Contradiction.IsStructurallyValid()
				|| CognitiveState.Contradictions.ContainsByPredicate(
					[&Contradiction](
						const FHyperTwistMemoryCognitiveContradiction& ExistingContradiction)
					{
						return ExistingContradiction.ContradictionId ==
							Contradiction.ContradictionId;
					}))
			{
				return;
			}

			CognitiveState.Contradictions.Add(Contradiction);
		};

	auto AddSupersession =
		[&](const FHyperTwistMemoryCognitiveSupersession& Supersession)
		{
			if (!Supersession.IsStructurallyValid()
				|| CognitiveState.Supersessions.ContainsByPredicate(
					[&Supersession](
						const FHyperTwistMemoryCognitiveSupersession& ExistingSupersession)
					{
						return ExistingSupersession.SupersessionId ==
							Supersession.SupersessionId;
					}))
			{
				return;
			}

			CognitiveState.Supersessions.Add(Supersession);
		};

	auto AddConfidenceDecay =
		[&](const FHyperTwistMemoryConfidenceDecayEntry& ConfidenceDecay)
		{
			if (!ConfidenceDecay.IsStructurallyValid()
				|| CognitiveState.ConfidenceDecays.ContainsByPredicate(
					[&ConfidenceDecay](
						const FHyperTwistMemoryConfidenceDecayEntry& ExistingDecay)
					{
						return ExistingDecay.DecayId == ConfidenceDecay.DecayId;
					}))
			{
				return;
			}

			CognitiveState.ConfidenceDecays.Add(ConfidenceDecay);
		};

	auto ClampConfidence = [](const int32 Score)
	{
		return FMath::Clamp(Score, 0, 100);
	};

	auto MakeFact =
		[&](
			const FString& FactId,
			const FString& FactFamily,
			const FString& FactKind,
			const FString& Headline,
			const FString& DeckId,
			const TArray<FString>& SourceEntityIds,
			const FString& SummaryLine,
			const int32 ConfidenceScore,
			const int32 EvidenceCount)
		{
			FHyperTwistMemoryCognitiveFact Fact;
			Fact.FactId = FactId;
			Fact.FactFamily = FactFamily;
			Fact.FactKind = FactKind;
			Fact.Headline = Headline;
			Fact.UserId = UserId;
			Fact.DeckId = DeckId;
			Fact.ReferenceUtc = ResolvedReferenceUtc;
			Fact.SourceEntityIds = SourceEntityIds;
			Fact.SummaryLine = SummaryLine;
			Fact.ConfidenceScore = ClampConfidence(ConfidenceScore);
			Fact.EvidenceCount = FMath::Max(1, EvidenceCount);
			Fact.bActive = true;
			for (const FString& SourceEntityId : SourceEntityIds)
			{
				AppendEntityProvenanceChain(
					SourceEntityId,
					FactFamily,
					Fact.ProvenanceLinks
				);
			}

			return Fact;
		};

	auto ResolveFactPolarity = [](const FString& FactKind)
	{
		if (FactKind.Contains(TEXT("active"))
			|| FactKind.Contains(TEXT("risk"))
			|| FactKind.Contains(TEXT("persistent")))
		{
			return 1;
		}
		if (FactKind.Contains(TEXT("stable"))
			|| FactKind.Contains(TEXT("settled"))
			|| FactKind.Contains(TEXT("stabilized")))
		{
			return -1;
		}

		return 0;
	};

	auto RegisterFactContradiction =
		[&](
			const FString& FactFamily,
			const FHyperTwistMemoryCognitiveFact& LeftFact,
			const FHyperTwistMemoryCognitiveFact& RightFact)
		{
			FHyperTwistMemoryCognitiveContradiction Contradiction;
			Contradiction.ContradictionId = FString::Printf(
				TEXT("memory-cognitive-contradiction/%s/%s"),
				*FactFamily,
				*UserId
			);
			Contradiction.FactFamily = FactFamily;
			Contradiction.Headline = FString::Printf(
				TEXT("Conflicting cognitive signals exist for %s"),
				*FactFamily.Replace(TEXT("-"), TEXT(" "))
			);
			Contradiction.UserId = UserId;
			Contradiction.ReferenceUtc = ResolvedReferenceUtc;
			Contradiction.LeftFactId = LeftFact.FactId;
			Contradiction.RightFactId = RightFact.FactId;
			Contradiction.ResolutionLabel =
				TEXT("Prefer the higher-confidence signal while keeping contradiction review explicit.");
			Contradiction.bBlocksPromotion = true;
			Contradiction.bNeedsManualReview = true;
			Contradiction.ProvenanceLinks = LeftFact.ProvenanceLinks;
			for (const FHyperTwistMemoryProvenanceLink& ProvenanceLink : RightFact.ProvenanceLinks)
			{
				HyperTwistMemoryCoreLibraryInternal::AddUniqueProvenanceLink(
					Contradiction.ProvenanceLinks,
					ProvenanceLink
				);
			}
			AddContradiction(Contradiction);

			if (const int32* LeftIndex = FactIndexById.Find(LeftFact.FactId))
			{
				HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
					CognitiveState.Facts[*LeftIndex].ContradictionIds,
					Contradiction.ContradictionId
				);
				CognitiveState.Facts[*LeftIndex].bRequiresReview = true;
			}
			if (const int32* RightIndex = FactIndexById.Find(RightFact.FactId))
			{
				HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
					CognitiveState.Facts[*RightIndex].ContradictionIds,
					Contradiction.ContradictionId
				);
				CognitiveState.Facts[*RightIndex].bRequiresReview = true;
			}

			const FHyperTwistMemoryCognitiveFact* Winner =
				LeftFact.ConfidenceScore >= RightFact.ConfidenceScore
					? &LeftFact
					: &RightFact;
			const FHyperTwistMemoryCognitiveFact* Loser =
				Winner == &LeftFact ? &RightFact : &LeftFact;

			if (FMath::Abs(LeftFact.ConfidenceScore - RightFact.ConfidenceScore) >= 5)
			{
				FHyperTwistMemoryCognitiveSupersession Supersession;
				Supersession.SupersessionId = FString::Printf(
					TEXT("memory-cognitive-supersession/%s/%s/%s"),
					*FactFamily,
					*Loser->FactId,
					*UserId
				);
				Supersession.FactFamily = FactFamily;
				Supersession.UserId = UserId;
				Supersession.ReferenceUtc = ResolvedReferenceUtc;
				Supersession.PriorFactId = Loser->FactId;
				Supersession.CurrentFactId = Winner->FactId;
				Supersession.ReasonLabel =
					TEXT("Higher-confidence current signal supersedes the weaker stale derived conclusion.");
				Supersession.bResolvedByHigherConfidence = true;
				Supersession.ProvenanceLinks = Loser->ProvenanceLinks;
				for (const FHyperTwistMemoryProvenanceLink& ProvenanceLink : Winner->ProvenanceLinks)
				{
					HyperTwistMemoryCoreLibraryInternal::AddUniqueProvenanceLink(
						Supersession.ProvenanceLinks,
						ProvenanceLink
					);
				}
				AddSupersession(Supersession);

				if (const int32* LoserIndex = FactIndexById.Find(Loser->FactId))
				{
					CognitiveState.Facts[*LoserIndex].SupersededByFactId = Winner->FactId;
					CognitiveState.Facts[*LoserIndex].bActive = false;
					CognitiveState.Facts[*LoserIndex].bRequiresReview = true;
				}
			}
		};

	auto ApplyFactDecay =
		[&](const FString& FactId, const FString& TriggerLabel, const int32 Penalty)
		{
			const int32* FactIndex = FactIndexById.Find(FactId);
			if (FactIndex == nullptr || Penalty <= 0)
			{
				return;
			}

			FHyperTwistMemoryCognitiveFact& Fact = CognitiveState.Facts[*FactIndex];
			const int32 PreviousConfidence = Fact.ConfidenceScore;
			const int32 CurrentConfidence =
				ClampConfidence(Fact.ConfidenceScore - Penalty);
			if (CurrentConfidence >= PreviousConfidence)
			{
				return;
			}

			FHyperTwistMemoryConfidenceDecayEntry DecayEntry;
			DecayEntry.DecayId = FString::Printf(
				TEXT("memory-confidence-decay/%s/%s"),
				*Fact.FactId,
				*TriggerLabel.Replace(TEXT(" "), TEXT("-"))
			);
			DecayEntry.FactId = Fact.FactId;
			DecayEntry.UserId = UserId;
			DecayEntry.ReferenceUtc = ResolvedReferenceUtc;
			DecayEntry.TriggerLabel = TriggerLabel;
			DecayEntry.PreviousConfidenceScore = PreviousConfidence;
			DecayEntry.CurrentConfidenceScore = CurrentConfidence;
			DecayEntry.bBelowPromotionThreshold = CurrentConfidence < 50;
			DecayEntry.ProvenanceLinks = Fact.ProvenanceLinks;
			AddConfidenceDecay(DecayEntry);

			Fact.ConfidenceScore = CurrentConfidence;
			Fact.bRequiresReview = true;
		};

	const FHyperTwistTrainingReviewProgramSummary ReviewProgramSummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveReviewProgramSummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	const FHyperTwistTrainingCoachMemorySnapshot CoachMemorySnapshot =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachMemorySnapshot(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	const FHyperTwistTrainingCoachClosureMemorySummary CoachClosureSummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachClosureMemorySummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	const FHyperTwistTrainingCoachRecommendationHistorySummary RecommendationHistorySummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachRecommendationHistorySummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	const FHyperTwistTrainingCoachCarryForwardPolicySummary CarryForwardSummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachCarryForwardPolicySummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	const FHyperTwistTrainingCoachArchivePolicySummary ArchivePolicySummary =
		UHyperTwistTrainingRepositoryLibrary::DeriveCoachArchivePolicySummary(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);

	if (ReviewProgramSummary.IsStructurallyValid())
	{
		const bool bHasActiveReviewPressure =
			ReviewProgramSummary.PendingPlanCount > 0
			|| ReviewProgramSummary.ProgramPressureScore >= 0.2f
			|| ReviewProgramSummary.CarryoverCaseCount > 0;
		if (bHasActiveReviewPressure)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/review-pressure-active/%s"), *UserId),
				TEXT("review-pressure"),
				TEXT("active-review-pressure"),
				TEXT("Review pressure remains active"),
				ReviewProgramSummary.FocusDeckId,
				{ReviewProgramEntityId},
				TEXT("Open review plans and carryover still require active attention."),
				60 + ReviewProgramSummary.PendingPlanCount * 4
					+ FMath::RoundToInt(ReviewProgramSummary.ProgramPressureScore * 10.0f),
				FMath::Max(1, ReviewProgramSummary.PendingPlanCount + ReviewProgramSummary.CarryoverCaseCount)
			));
		}

		if (ReviewProgramSummary.CompletedPlanCount > 0
			&& ReviewProgramSummary.AveragePlanProgressRatio >= 0.5f)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/review-pressure-stabilized/%s"), *UserId),
				TEXT("review-pressure"),
				TEXT("stabilized-review-pressure"),
				TEXT("Review program shows stabilization"),
				ReviewProgramSummary.FocusDeckId,
				{ReviewProgramEntityId},
				TEXT("Completed review work and sustained progress indicate a stabilizing review posture."),
				52 + ReviewProgramSummary.CompletedPlanCount * 4
					+ FMath::RoundToInt(ReviewProgramSummary.AveragePlanProgressRatio * 12.0f),
				FMath::Max(1, ReviewProgramSummary.CompletedPlanCount)
			));
		}
	}

	if (CoachClosureSummary.IsStructurallyValid() || RecommendationHistorySummary.IsStructurallyValid())
	{
		const bool bHasActiveFollowUpPressure =
			CoachClosureSummary.bHasFollowUpPressure
			|| RecommendationHistorySummary.FollowUpReadySequenceCount > 0
			|| RecommendationHistorySummary.FollowUpLanePlanCount > 0
			|| CoachMemorySnapshot.PendingReviewPlanIds.Num() > 0
			|| CoachMemorySnapshot.SchedulePressureCaseIds.Num() > 0;
		if (bHasActiveFollowUpPressure)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/follow-up-active/%s"), *UserId),
				TEXT("follow-up-posture"),
				TEXT("active-follow-up-pressure"),
				TEXT("Coach follow-up pressure remains active"),
				!CoachClosureSummary.FocusDeckId.IsEmpty()
					? CoachClosureSummary.FocusDeckId
					: RecommendationHistorySummary.FocusDeckId,
				{CoachClosureEntityId, RecommendationHistoryEntityId},
				TEXT("Follow-up-ready sequences and recommendation history still signal unresolved coaching pressure."),
				62 + CoachClosureSummary.FollowUpReadySequenceCount * 3
					+ RecommendationHistorySummary.FollowUpReadySequenceCount * 3,
				FMath::Max(1, CoachClosureSummary.FollowUpReadySequenceCount
					+ RecommendationHistorySummary.FollowUpReadySequenceCount
					+ RecommendationHistorySummary.FollowUpLanePlanCount
					+ CoachMemorySnapshot.PendingReviewPlanIds.Num()
					+ CoachMemorySnapshot.SchedulePressureCaseIds.Num())
			));
		}

		if ((CoachClosureSummary.ClosedSequenceCount > CoachClosureSummary.EscalatedSequenceCount
				&& CoachClosureSummary.ArchivedResolvedCaseCount > 0)
			|| CoachMemorySnapshot.ArchivedResolvedCaseIds.Num() > 0)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/follow-up-stabilized/%s"), *UserId),
				TEXT("follow-up-posture"),
				TEXT("stabilized-follow-up-posture"),
				TEXT("Coach follow-up posture shows stabilization"),
				CoachClosureSummary.FocusDeckId,
				{CoachClosureEntityId, RecommendationHistoryEntityId},
				TEXT("Closed sequences and archived resolved cases indicate a stabilizing follow-up posture."),
				55 + CoachClosureSummary.ClosedSequenceCount * 3
					+ FMath::RoundToInt(CoachClosureSummary.AverageClosureScore * 10.0f),
				FMath::Max(1, CoachClosureSummary.ClosedSequenceCount
					+ CoachClosureSummary.ArchivedResolvedCaseCount
					+ CoachMemorySnapshot.ArchivedResolvedCaseIds.Num())
			));
		}
	}

	{
		const bool bHasActiveCarryForward =
			CarryForwardSummary.bHasActiveCarryForwardPressure
			|| CarryForwardSummary.PinnedCarryForwardCaseCount > 0
			|| CarryForwardSummary.RecurringCarryForwardCaseCount > 0
			|| CarryForwardSummary.EscalationCarryForwardCaseCount > 0;
		if (bHasActiveCarryForward)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/carry-forward-active/%s"), *UserId),
				TEXT("carry-forward-posture"),
				TEXT("active-carry-forward-pressure"),
				TEXT("Carry-forward pressure remains active"),
				CarryForwardSummary.FocusDeckId,
				{CarryForwardEntityId, CoachMemoryEntityId},
				TEXT("Pinned, recurring, or escalation carry-forward cases still require durable attention."),
				60 + CarryForwardSummary.PinnedCarryForwardCaseCount * 4
					+ CarryForwardSummary.EscalationCarryForwardCaseCount * 5,
				FMath::Max(1, CarryForwardSummary.PinnedCarryForwardCaseCount
					+ CarryForwardSummary.RecurringCarryForwardCaseCount
					+ CarryForwardSummary.EscalationCarryForwardCaseCount)
			));
		}

		if (CarryForwardSummary.SuppressedResolvedCaseCount > 0)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/carry-forward-settled/%s"), *UserId),
				TEXT("carry-forward-posture"),
				TEXT("settled-carry-forward-posture"),
				TEXT("Carry-forward posture shows settled resolved work"),
				CarryForwardSummary.FocusDeckId,
				{CarryForwardEntityId, CoachMemoryEntityId},
				TEXT("Suppressed resolved resurfacing indicates older carry-forward pressure has partially settled."),
				54 + CarryForwardSummary.SuppressedResolvedCaseCount * 4,
				FMath::Max(1, CarryForwardSummary.SuppressedResolvedCaseCount)
			));
		}
	}

	{
		const bool bHasArchiveRisk =
			ArchivePolicySummary.ReopenRiskArchivedCaseCount > 0
			|| ArchivePolicySummary.EscalationRetainedCaseCount > 0
			|| ArchivePolicySummary.RetainedCarryForwardCaseCount > 0;
		if (bHasArchiveRisk)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/archive-risk/%s"), *UserId),
				TEXT("archive-posture"),
				TEXT("archive-reopen-risk"),
				TEXT("Archived work still carries reopen risk"),
				ArchivePolicySummary.FocusDeckId,
				{ArchivePolicyEntityId, CoachMemoryEntityId},
				TEXT("Reopen-risk and retained carry-forward cases show that archived conclusions are not fully settled."),
				58 + ArchivePolicySummary.ReopenRiskArchivedCaseCount * 5
					+ ArchivePolicySummary.EscalationRetainedCaseCount * 4,
				FMath::Max(1, ArchivePolicySummary.ReopenRiskArchivedCaseCount
					+ ArchivePolicySummary.EscalationRetainedCaseCount
					+ ArchivePolicySummary.RetainedCarryForwardCaseCount)
			));
		}

		if (ArchivePolicySummary.StableLongTermArchivedCaseCount > 0
			|| ArchivePolicySummary.LongTermArchivedCaseCount > 0)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/archive-stable/%s"), *UserId),
				TEXT("archive-posture"),
				TEXT("stable-archive-posture"),
				TEXT("Archived work shows stable long-term resolution"),
				ArchivePolicySummary.FocusDeckId,
				{ArchivePolicyEntityId, CoachMemoryEntityId},
				TEXT("Stable long-term archived cases indicate settled closure over older coaching work."),
				53 + ArchivePolicySummary.StableLongTermArchivedCaseCount * 4,
				FMath::Max(1, ArchivePolicySummary.StableLongTermArchivedCaseCount
					+ ArchivePolicySummary.LongTermArchivedCaseCount)
			));
		}
	}

	if (!CoachMemorySnapshot.UserId.IsEmpty())
	{
		if (CoachMemorySnapshot.PersistentCoachWeakCaseIds.Num() > 0
			|| CoachMemorySnapshot.EscalationCaseIds.Num() > 0)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/weak-case-persistent/%s"), *UserId),
				TEXT("weak-case-posture"),
				TEXT("persistent-weak-case-pressure"),
				TEXT("Persistent weak-case pressure remains visible"),
				CoachMemorySnapshot.FocusDeckId,
				{CoachMemoryEntityId},
				TEXT("Persistent weak cases and escalation cases continue to shape long-term coach memory."),
				57 + CoachMemorySnapshot.PersistentCoachWeakCaseIds.Num() * 3
					+ CoachMemorySnapshot.EscalationCaseIds.Num() * 4,
				FMath::Max(1, CoachMemorySnapshot.PersistentCoachWeakCaseIds.Num()
					+ CoachMemorySnapshot.EscalationCaseIds.Num())
			));
		}

		if (CoachMemorySnapshot.ArchivedResolvedCaseIds.Num() > 0
			&& CoachMemorySnapshot.PersistentCoachWeakCaseIds.Num() == 0)
		{
			AddFact(MakeFact(
				FString::Printf(TEXT("memory-cognitive-fact/weak-case-stable/%s"), *UserId),
				TEXT("weak-case-posture"),
				TEXT("stable-weak-case-posture"),
				TEXT("Weak-case posture has stabilized"),
				CoachMemorySnapshot.FocusDeckId,
				{CoachMemoryEntityId},
				TEXT("Archived resolved coach cases remain while persistent weak-case pressure has cleared."),
				51 + CoachMemorySnapshot.ArchivedResolvedCaseIds.Num() * 3,
				FMath::Max(1, CoachMemorySnapshot.ArchivedResolvedCaseIds.Num())
			));
		}
	}

	if (RecommendationHistorySummary.IsStructurallyValid()
		&& RecommendationHistorySummary.PreferredGuidanceLane
			!= EHyperTwistTrainingCoachGuidanceLane::None)
	{
		AddFact(MakeFact(
			FString::Printf(TEXT("memory-cognitive-fact/guidance-dominant/%s"), *UserId),
			TEXT("guidance-posture"),
			TEXT("dominant-guidance-lane"),
			TEXT("Current coach guidance lane is stable enough to retain"),
			RecommendationHistorySummary.FocusDeckId,
			{RecommendationHistoryEntityId},
			TEXT("Recommendation history exposes a dominant guidance lane worth retaining as bounded coach memory."),
			56 + RecommendationHistorySummary.PlanCount * 2,
			FMath::Max(1, RecommendationHistorySummary.PlanCount)
		));
	}

	TMap<FString, TArray<FString>> FactIdsByFamily;
	for (const FHyperTwistMemoryCognitiveFact& Fact : CognitiveState.Facts)
	{
		FactIdsByFamily.FindOrAdd(Fact.FactFamily).Add(Fact.FactId);
	}

	for (const TPair<FString, TArray<FString>>& FamilyPair : FactIdsByFamily)
	{
		const FString& FactFamily = FamilyPair.Key;
		const TArray<FString>& FamilyFactIds = FamilyPair.Value;

		const FHyperTwistMemoryCognitiveFact* PositiveFact = nullptr;
		const FHyperTwistMemoryCognitiveFact* NegativeFact = nullptr;
		for (const FString& FactId : FamilyFactIds)
		{
			const int32* FactIndex = FactIndexById.Find(FactId);
			if (FactIndex == nullptr)
			{
				continue;
			}

			const FHyperTwistMemoryCognitiveFact& Fact = CognitiveState.Facts[*FactIndex];
			const int32 Polarity = ResolveFactPolarity(Fact.FactKind);
			if (Polarity > 0
				&& (PositiveFact == nullptr || Fact.ConfidenceScore > PositiveFact->ConfidenceScore))
			{
				PositiveFact = &Fact;
			}
			else if (
				Polarity < 0
				&& (NegativeFact == nullptr || Fact.ConfidenceScore > NegativeFact->ConfidenceScore))
			{
				NegativeFact = &Fact;
			}
		}

		if (PositiveFact == nullptr || NegativeFact == nullptr)
		{
			continue;
		}

		RegisterFactContradiction(FactFamily, *PositiveFact, *NegativeFact);
	}

	if (CognitiveState.Contradictions.Num() == 0)
	{
		const FHyperTwistMemoryCognitiveFact* ActiveFact = nullptr;
		const FHyperTwistMemoryCognitiveFact* StableFact = nullptr;
		for (const FHyperTwistMemoryCognitiveFact& Fact : CognitiveState.Facts)
		{
			const int32 Polarity = ResolveFactPolarity(Fact.FactKind);
			if (Polarity > 0 && ActiveFact == nullptr)
			{
				ActiveFact = &Fact;
			}
			else if (Polarity < 0 && StableFact == nullptr)
			{
				StableFact = &Fact;
			}
		}

		if (ActiveFact != nullptr && StableFact != nullptr)
		{
			RegisterFactContradiction(
				TEXT("mixed-coaching-horizon"),
				*ActiveFact,
				*StableFact
			);
		}
	}

	for (FHyperTwistMemoryCognitiveFact& Fact : CognitiveState.Facts)
	{
		if (!HyperTwistMemoryCoreLibraryInternal::HasAuthoritativeProvenance(Fact.ProvenanceLinks))
		{
			ApplyFactDecay(Fact.FactId, TEXT("no-direct-authoritative-lineage"), 8);
		}
		if (Fact.ContradictionIds.Num() > 0)
		{
			ApplyFactDecay(Fact.FactId, TEXT("contradiction-review"), 15);
		}
		if (!Fact.SupersededByFactId.IsEmpty())
		{
			ApplyFactDecay(Fact.FactId, TEXT("superseded-derived-conclusion"), 25);
		}
	}

	for (const FHyperTwistMemoryCognitiveFact& Fact : CognitiveState.Facts)
	{
		if (Fact.bActive)
		{
			++CognitiveState.ActiveFactCount;
		}
		if (!Fact.SupersededByFactId.IsEmpty())
		{
			++CognitiveState.SupersededFactCount;
		}
		if (Fact.ConfidenceScore < 50)
		{
			++CognitiveState.LowConfidenceFactCount;
		}
		if (Fact.bRequiresReview)
		{
			CognitiveState.bHasOpenCognitiveReview = true;
		}
	}

	CognitiveState.ContradictionCount = CognitiveState.Contradictions.Num();
	if (!CognitiveState.bHasOpenCognitiveReview)
	{
		CognitiveState.bHasOpenCognitiveReview =
			CognitiveState.Contradictions.ContainsByPredicate(
				[](const FHyperTwistMemoryCognitiveContradiction& Contradiction)
				{
					return Contradiction.bNeedsManualReview;
				}
			);
	}

	if (!CognitiveState.IsStructurallyValid())
	{
		return FHyperTwistMemoryCognitiveConsolidationState();
	}

	return CognitiveState;
}

FHyperTwistMemoryKnowledgeNotesState
	UHyperTwistMemoryCoreLibrary::DeriveMemoryKnowledgeNotesState(
		const FHyperTwistTrainingRepositoryState& RepositoryState,
		const FString& UserId,
		const FString& ReferenceUtc
	)
{
	FHyperTwistMemoryKnowledgeNotesState KnowledgeNotesState;
	if (UserId.IsEmpty())
	{
		return KnowledgeNotesState;
	}

	const FString ResolvedReferenceUtc =
		HyperTwistMemoryCoreLibraryInternal::ResolveReferenceUtc(ReferenceUtc);
	KnowledgeNotesState.UserId = UserId;
	KnowledgeNotesState.ReferenceUtc = ResolvedReferenceUtc;

	const FHyperTwistMemoryLedgerState MemoryLedgerState = DeriveMemoryLedgerState(
		RepositoryState,
		UserId,
		ResolvedReferenceUtc
	);
	const FHyperTwistMemoryCognitiveConsolidationState CognitiveState =
		DeriveMemoryCognitiveConsolidationState(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	const FHyperTwistTrainingKnowledgeReferenceBundle KnowledgeBundle =
		UHyperTwistTrainingKnowledgeLibrary::MakeHypercubingKnowledgeReferenceBundle();

	if (!KnowledgeBundle.IsStructurallyValid())
	{
		return FHyperTwistMemoryKnowledgeNotesState();
	}

	TMap<FString, FHyperTwistMemoryEntityDescriptor> LedgerEntitiesById;
	for (const FHyperTwistMemoryEntityDescriptor& Entity : MemoryLedgerState.Entities)
	{
		LedgerEntitiesById.Add(Entity.EntityId, Entity);
	}

	const FHyperTwistMemoryLaneContract* KnowledgeLaneContract =
		MemoryLedgerState.LaneContracts.FindByPredicate(
			[](const FHyperTwistMemoryLaneContract& LaneContract)
			{
				return LaneContract.Lane == EHyperTwistMemoryLane::KnowledgeWiki;
			}
		);
	const FHyperTwistMemoryLaneContract* UserNotesLaneContract =
		MemoryLedgerState.LaneContracts.FindByPredicate(
			[](const FHyperTwistMemoryLaneContract& LaneContract)
			{
				return LaneContract.Lane == EHyperTwistMemoryLane::UserNotes;
			}
		);
	const FHyperTwistMemoryFeatureGate* KnowledgeGate =
		MemoryLedgerState.FeatureGates.FindByPredicate(
			[](const FHyperTwistMemoryFeatureGate& FeatureGate)
			{
				return FeatureGate.Lane == EHyperTwistMemoryLane::KnowledgeWiki;
			}
		);
	const FHyperTwistMemoryFeatureGate* UserNotesGate =
		MemoryLedgerState.FeatureGates.FindByPredicate(
			[](const FHyperTwistMemoryFeatureGate& FeatureGate)
			{
				return FeatureGate.Lane == EHyperTwistMemoryLane::UserNotes;
			}
		);
	const FHyperTwistMemoryEntityDescriptor* PolicyEntity =
		MemoryLedgerState.Entities.FindByPredicate(
			[](const FHyperTwistMemoryEntityDescriptor& Entity)
			{
				return Entity.RecordKind == TEXT("memory-policy-profile");
			}
		);
	const FHyperTwistMemoryEntityDescriptor* LedgerContractEntity =
		MemoryLedgerState.Entities.FindByPredicate(
			[](const FHyperTwistMemoryEntityDescriptor& Entity)
			{
				return Entity.RecordKind == TEXT("memory-ledger-contract");
			}
		);

	if (KnowledgeLaneContract == nullptr
		|| UserNotesLaneContract == nullptr
		|| KnowledgeGate == nullptr
		|| UserNotesGate == nullptr
		|| PolicyEntity == nullptr
		|| LedgerContractEntity == nullptr)
	{
		return FHyperTwistMemoryKnowledgeNotesState();
	}

	auto AddKnowledgeObject =
		[&](const FHyperTwistMemoryKnowledgeObject& KnowledgeObject)
		{
			if (!KnowledgeObject.IsStructurallyValid()
				|| KnowledgeNotesState.KnowledgeObjects.ContainsByPredicate(
					[&KnowledgeObject](
						const FHyperTwistMemoryKnowledgeObject& ExistingKnowledgeObject)
					{
						return ExistingKnowledgeObject.ObjectId == KnowledgeObject.ObjectId;
					}))
			{
				return;
			}

			KnowledgeNotesState.KnowledgeObjects.Add(KnowledgeObject);
		};

	auto AddPromotionReview =
		[&](const FHyperTwistMemoryKnowledgePromotionReview& PromotionReview)
		{
			if (!PromotionReview.IsStructurallyValid()
				|| KnowledgeNotesState.PromotionReviews.ContainsByPredicate(
					[&PromotionReview](
						const FHyperTwistMemoryKnowledgePromotionReview& ExistingReview)
					{
						return ExistingReview.ReviewId == PromotionReview.ReviewId;
					}))
			{
				return;
			}

			KnowledgeNotesState.PromotionReviews.Add(PromotionReview);
			switch (PromotionReview.Decision)
			{
			case EHyperTwistMemoryKnowledgePromotionDecision::Approved:
				++KnowledgeNotesState.ApprovedPromotionCount;
				break;
			case EHyperTwistMemoryKnowledgePromotionDecision::Deferred:
				++KnowledgeNotesState.DeferredPromotionCount;
				break;
			case EHyperTwistMemoryKnowledgePromotionDecision::Blocked:
				++KnowledgeNotesState.BlockedPromotionCount;
				break;
			default:
				break;
			}
		};

	auto MakeSyntheticKnowledgeProvenance =
		[&](
			const FString& ParentEntityId,
			const FString& RecordKind,
			const FString& SourceLabel,
			const bool bParentAuthoritative)
		{
			FHyperTwistMemoryProvenanceLink ProvenanceLink;
			ProvenanceLink.ParentEntityId = ParentEntityId;
			ProvenanceLink.ParentLane = EHyperTwistMemoryLane::KnowledgeWiki;
			ProvenanceLink.ParentRecordKind = RecordKind;
			ProvenanceLink.ParentReferenceUtc = ResolvedReferenceUtc;
			ProvenanceLink.ParentSourceLabel = SourceLabel;
			ProvenanceLink.bParentAuthoritative = bParentAuthoritative;
			return ProvenanceLink;
		};

	auto ComposeSourceLabel =
		[](const FHyperTwistTrainingSourceAttribution& SourceAttribution)
		{
			if (!SourceAttribution.SourceTrackId.IsEmpty())
			{
				return FString::Printf(
					TEXT("%s:%s"),
					*SourceAttribution.SourceRepo,
					*SourceAttribution.SourceTrackId
				);
			}

			return SourceAttribution.SourceRepo;
		};

	auto InitializeKnowledgeObject =
		[&](
			const FString& ObjectId,
			const FString& ObjectKind,
			const FString& Title,
			const FString& Summary,
			const FString& ScopeLabel,
			const TArray<FString>& SourceRecordIds,
			const TArray<FString>& Tags)
		{
			FHyperTwistMemoryKnowledgeObject KnowledgeObject;
			KnowledgeObject.ObjectId = ObjectId;
			KnowledgeObject.ObjectKind = ObjectKind;
			KnowledgeObject.Title = Title;
			KnowledgeObject.Summary = Summary;
			KnowledgeObject.UserId = UserId;
			KnowledgeObject.ReferenceUtc = ResolvedReferenceUtc;
			KnowledgeObject.ScopeLabel = ScopeLabel;
			KnowledgeObject.SourceRecordIds = SourceRecordIds;
			KnowledgeObject.Tags = Tags;
			return KnowledgeObject;
		};

	auto AppendAttributionKnowledgeObject =
		[&](
			FHyperTwistMemoryKnowledgeObject& KnowledgeObject,
			const FString& SourceId,
			const FString& RecordKind,
			const FHyperTwistTrainingSourceAttribution& SourceAttribution)
		{
			HyperTwistMemoryCoreLibraryInternal::AddUniqueProvenanceLink(
				KnowledgeObject.ProvenanceLinks,
				MakeSyntheticKnowledgeProvenance(
					SourceId,
					RecordKind,
					ComposeSourceLabel(SourceAttribution),
					true
				)
			);
		};

	for (const FHyperTwistTrainingKnowledgeTaxonomyNode& Node : KnowledgeBundle.TaxonomyNodes)
	{
		if (!Node.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryKnowledgeObject KnowledgeObject = InitializeKnowledgeObject(
			FString::Printf(TEXT("memory-knowledge-object/taxonomy/%s/%s"), *UserId, *Node.NodeId),
			TEXT("taxonomy-node"),
			Node.Title,
			Node.Summary,
			TEXT("curated-reference"),
			{Node.NodeId},
			Node.Tags
		);
		AppendAttributionKnowledgeObject(
			KnowledgeObject,
			FString::Printf(TEXT("knowledge-source/taxonomy/%s"), *Node.NodeId),
			TEXT("training-knowledge-taxonomy-node"),
			Node.SourceAttribution
		);
		AddKnowledgeObject(KnowledgeObject);
	}

	for (const FHyperTwistTrainingNotationReferenceTerm& Term : KnowledgeBundle.NotationTerms)
	{
		if (!Term.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryKnowledgeObject KnowledgeObject = InitializeKnowledgeObject(
			FString::Printf(TEXT("memory-knowledge-object/notation/%s/%s"), *UserId, *Term.TermId),
			TEXT("notation-term"),
			Term.DisplayTerm,
			Term.Meaning,
			TEXT("curated-reference"),
			{Term.TermId},
			Term.Tags
		);
		AppendAttributionKnowledgeObject(
			KnowledgeObject,
			FString::Printf(TEXT("knowledge-source/notation/%s"), *Term.TermId),
			TEXT("training-knowledge-notation-term"),
			Term.SourceAttribution
		);
		AddKnowledgeObject(KnowledgeObject);
	}

	for (const FHyperTwistTrainingProgressionStageReference& Stage :
		KnowledgeBundle.ProgressionStages)
	{
		if (!Stage.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryKnowledgeObject KnowledgeObject = InitializeKnowledgeObject(
			FString::Printf(TEXT("memory-knowledge-object/progression/%s/%s"), *UserId, *Stage.StageId),
			TEXT("progression-stage"),
			Stage.Title,
			Stage.Summary,
			TEXT("curated-reference"),
			{Stage.StageId},
			Stage.Tags
		);
		AppendAttributionKnowledgeObject(
			KnowledgeObject,
			FString::Printf(TEXT("knowledge-source/progression/%s"), *Stage.StageId),
			TEXT("training-knowledge-progression-stage"),
			Stage.SourceAttribution
		);
		AddKnowledgeObject(KnowledgeObject);
	}

	for (const FHyperTwistTrainingSoftwareReference& Reference :
		KnowledgeBundle.SoftwareReferences)
	{
		if (!Reference.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryKnowledgeObject KnowledgeObject = InitializeKnowledgeObject(
			FString::Printf(TEXT("memory-knowledge-object/software/%s/%s"), *UserId, *Reference.SoftwareId),
			TEXT("software-reference"),
			Reference.Title,
			Reference.Summary,
			TEXT("curated-reference"),
			{Reference.SoftwareId},
			Reference.CapabilityTags
		);
		for (const FString& PlatformTag : Reference.PlatformTags)
		{
			HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
				KnowledgeObject.Tags,
				PlatformTag
			);
		}
		AppendAttributionKnowledgeObject(
			KnowledgeObject,
			FString::Printf(TEXT("knowledge-source/software/%s"), *Reference.SoftwareId),
			TEXT("training-knowledge-software-reference"),
			Reference.SourceAttribution
		);
		AddKnowledgeObject(KnowledgeObject);
	}

	for (const FHyperTwistTrainingLeaderboardEventReference& Event :
		KnowledgeBundle.LeaderboardEvents)
	{
		if (!Event.IsStructurallyValid())
		{
			continue;
		}

		FHyperTwistMemoryKnowledgeObject KnowledgeObject = InitializeKnowledgeObject(
			FString::Printf(TEXT("memory-knowledge-object/leaderboard/%s/%s"), *UserId, *Event.EventId),
			TEXT("leaderboard-event"),
			Event.Title,
			Event.MetricLabel,
			TEXT("curated-reference"),
			{Event.EventId},
			Event.Tags
		);
		AppendAttributionKnowledgeObject(
			KnowledgeObject,
			FString::Printf(TEXT("knowledge-source/leaderboard/%s"), *Event.EventId),
			TEXT("training-knowledge-leaderboard-event"),
			Event.SourceAttribution
		);
		AddKnowledgeObject(KnowledgeObject);
	}

	KnowledgeNotesState.CuratedReferenceObjectCount =
		KnowledgeNotesState.KnowledgeObjects.Num();

	for (const FHyperTwistMemoryCognitiveFact& Fact : CognitiveState.Facts)
	{
		FHyperTwistMemoryKnowledgePromotionReview PromotionReview;
		PromotionReview.ReviewId = FString::Printf(
			TEXT("memory-knowledge-review/%s/%s"),
			*UserId,
			*Fact.FactId
		);
		PromotionReview.CandidateFactId = Fact.FactId;
		PromotionReview.ProposedKnowledgeObjectId = FString::Printf(
			TEXT("memory-knowledge-object/promoted/%s/%s"),
			*UserId,
			*Fact.FactId
		);
		PromotionReview.UserId = UserId;
		PromotionReview.ReferenceUtc = ResolvedReferenceUtc;
		PromotionReview.Headline = Fact.Headline;
		PromotionReview.ProvenanceLinks = Fact.ProvenanceLinks;

		if (!Fact.SupersededByFactId.IsEmpty())
		{
			PromotionReview.Decision =
				EHyperTwistMemoryKnowledgePromotionDecision::Blocked;
			PromotionReview.ReasonLabel =
				TEXT("Superseded cognitive facts cannot promote into curated knowledge until a newer reviewed conclusion stabilizes.");
			PromotionReview.bNeedsManualReview = true;
		}
		else if (Fact.ContradictionIds.Num() > 0 || Fact.bRequiresReview)
		{
			PromotionReview.Decision =
				EHyperTwistMemoryKnowledgePromotionDecision::Blocked;
			PromotionReview.ReasonLabel =
				TEXT("Contradicted or review-marked cognitive facts must remain reviewable instead of promoting silently.");
			PromotionReview.bNeedsManualReview = true;
			PromotionReview.BlockingContradictionIds = Fact.ContradictionIds;
		}
		else if (!Fact.bActive || Fact.ConfidenceScore < 70)
		{
			PromotionReview.Decision =
				EHyperTwistMemoryKnowledgePromotionDecision::Deferred;
			PromotionReview.ReasonLabel =
				TEXT("Cognitive facts below the promotion threshold stay deferred until confidence and active posture are stronger.");
		}
		else
		{
			PromotionReview.Decision =
				EHyperTwistMemoryKnowledgePromotionDecision::Approved;
			PromotionReview.ReasonLabel =
				TEXT("Stable high-confidence cognitive facts may promote into reviewable first-party knowledge.");

			FHyperTwistMemoryKnowledgeObject KnowledgeObject = InitializeKnowledgeObject(
				PromotionReview.ProposedKnowledgeObjectId,
				TEXT("promoted-cognitive-insight"),
				Fact.Headline,
				Fact.SummaryLine,
				TEXT("promoted-memory-knowledge"),
				{Fact.FactId},
				{Fact.FactFamily, TEXT("memory-promotion")}
			);
			for (const FHyperTwistMemoryProvenanceLink& ProvenanceLink : Fact.ProvenanceLinks)
			{
				HyperTwistMemoryCoreLibraryInternal::AddUniqueProvenanceLink(
					KnowledgeObject.ProvenanceLinks,
					ProvenanceLink
				);
			}
			AddKnowledgeObject(KnowledgeObject);
		}

		AddPromotionReview(PromotionReview);
	}

	KnowledgeNotesState.bKnowledgeWikiEnabled =
		KnowledgeGate->DefaultState !=
		EHyperTwistMemoryFeatureGateDefaultState::DisabledByDefault;

	KnowledgeNotesState.UserNotesPosture.UserId = UserId;
	KnowledgeNotesState.UserNotesPosture.ReferenceUtc = ResolvedReferenceUtc;
	KnowledgeNotesState.UserNotesPosture.GateId = UserNotesGate->GateId;
	KnowledgeNotesState.UserNotesPosture.SettingsKey = UserNotesGate->SettingsKey;
	KnowledgeNotesState.UserNotesPosture.bOwnershipJustified =
		UserNotesLaneContract->bFirstPartyOwned;
	KnowledgeNotesState.UserNotesPosture.bLaneEnabled =
		UserNotesGate->DefaultState !=
		EHyperTwistMemoryFeatureGateDefaultState::DisabledByDefault;
	KnowledgeNotesState.UserNotesPosture.bAcceptsUserAuthoredContent =
		KnowledgeNotesState.UserNotesPosture.bOwnershipJustified
		&& KnowledgeNotesState.UserNotesPosture.bLaneEnabled;
	KnowledgeNotesState.UserNotesPosture.bRequiresSeparateOwnerActivation =
		!KnowledgeNotesState.UserNotesPosture.bAcceptsUserAuthoredContent;

	if (KnowledgeNotesState.UserNotesPosture.bAcceptsUserAuthoredContent)
	{
		KnowledgeNotesState.UserNotesPosture.Headline =
			TEXT("User-authored note lane is active");
		KnowledgeNotesState.UserNotesPosture.SummaryLine =
			TEXT("User-authored notes are explicitly owned, enabled, and may participate in the bounded memory lane.");
	}
	else
	{
		KnowledgeNotesState.UserNotesPosture.Headline =
			TEXT("User-authored note lane remains separately gated");
		KnowledgeNotesState.UserNotesPosture.SummaryLine =
			TEXT("User-authored notes stay disabled until explicit first-party ownership and activation are proven.");
	}

	HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
		LedgerEntitiesById,
		PolicyEntity->EntityId,
		TEXT("user-notes-policy"),
		KnowledgeNotesState.UserNotesPosture.ProvenanceLinks
	);
	HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
		LedgerEntitiesById,
		LedgerContractEntity->EntityId,
		TEXT("user-notes-ledger"),
		KnowledgeNotesState.UserNotesPosture.ProvenanceLinks
	);

	KnowledgeNotesState.bUserNotesLaneAvailable =
		KnowledgeNotesState.UserNotesPosture.bOwnershipJustified
		&& KnowledgeNotesState.UserNotesPosture.bLaneEnabled
		&& KnowledgeNotesState.UserNotesPosture.bAcceptsUserAuthoredContent;

	if (!KnowledgeNotesState.IsStructurallyValid())
	{
		return FHyperTwistMemoryKnowledgeNotesState();
	}

	return KnowledgeNotesState;
}

FHyperTwistMemoryDerivedAdjunctState
	UHyperTwistMemoryCoreLibrary::DeriveMemoryDerivedAdjunctState(
		const FHyperTwistTrainingRepositoryState& RepositoryState,
		const FString& UserId,
		const FString& ReferenceUtc,
		const EHyperTwistMemoryContextAssemblyProfile ContextAssemblyProfile
	)
{
	FHyperTwistMemoryDerivedAdjunctState DerivedAdjunctState;
	if (UserId.IsEmpty()
		|| ContextAssemblyProfile == EHyperTwistMemoryContextAssemblyProfile::None)
	{
		return DerivedAdjunctState;
	}

	const FString ResolvedReferenceUtc =
		HyperTwistMemoryCoreLibraryInternal::ResolveReferenceUtc(ReferenceUtc);
	DerivedAdjunctState.UserId = UserId;
	DerivedAdjunctState.ReferenceUtc = ResolvedReferenceUtc;
	DerivedAdjunctState.ContextAssemblyProfile = ContextAssemblyProfile;

	const FHyperTwistMemoryLedgerState MemoryLedgerState = DeriveMemoryLedgerState(
		RepositoryState,
		UserId,
		ResolvedReferenceUtc
	);
	const FHyperTwistMemoryChronicleContinuityState ChronicleState =
		DeriveMemoryChronicleContinuityState(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	const FHyperTwistMemoryRecallSharedContextState RecallState =
		DeriveMemoryRecallSharedContextState(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc,
			TEXT("resume review coach history")
		);
	const FHyperTwistMemoryCognitiveConsolidationState CognitiveState =
		DeriveMemoryCognitiveConsolidationState(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);
	const FHyperTwistMemoryKnowledgeNotesState KnowledgeNotesState =
		DeriveMemoryKnowledgeNotesState(
			RepositoryState,
			UserId,
			ResolvedReferenceUtc
		);

	if (!ChronicleState.IsStructurallyValid()
		|| !RecallState.IsStructurallyValid()
		|| !CognitiveState.IsStructurallyValid()
		|| !KnowledgeNotesState.IsStructurallyValid())
	{
		return FHyperTwistMemoryDerivedAdjunctState();
	}

	TMap<FString, FHyperTwistMemoryEntityDescriptor> LedgerEntitiesById;
	for (const FHyperTwistMemoryEntityDescriptor& Entity : MemoryLedgerState.Entities)
	{
		LedgerEntitiesById.Add(Entity.EntityId, Entity);
	}

	const FHyperTwistMemoryLaneContract* DerivedLaneContract =
		MemoryLedgerState.LaneContracts.FindByPredicate(
			[](const FHyperTwistMemoryLaneContract& LaneContract)
			{
				return LaneContract.Lane == EHyperTwistMemoryLane::DerivedCompacted;
			}
		);
	const FHyperTwistMemoryFeatureGate* DerivedGate =
		MemoryLedgerState.FeatureGates.FindByPredicate(
			[](const FHyperTwistMemoryFeatureGate& FeatureGate)
			{
				return FeatureGate.Lane == EHyperTwistMemoryLane::DerivedCompacted;
			}
		);
	const FHyperTwistMemoryEntityDescriptor* PolicyEntity =
		MemoryLedgerState.Entities.FindByPredicate(
			[](const FHyperTwistMemoryEntityDescriptor& Entity)
			{
				return Entity.RecordKind == TEXT("memory-policy-profile");
			}
		);
	const FHyperTwistMemoryEntityDescriptor* LedgerContractEntity =
		MemoryLedgerState.Entities.FindByPredicate(
			[](const FHyperTwistMemoryEntityDescriptor& Entity)
			{
				return Entity.RecordKind == TEXT("memory-ledger-contract");
			}
		);

	if (DerivedLaneContract == nullptr
		|| DerivedGate == nullptr
		|| PolicyEntity == nullptr
		|| LedgerContractEntity == nullptr
		|| DerivedLaneContract->AuthorityKind !=
			EHyperTwistMemoryAuthorityKind::DerivedOnly)
	{
		return FHyperTwistMemoryDerivedAdjunctState();
	}

	DerivedAdjunctState.FeatureGateId = DerivedGate->GateId;
	DerivedAdjunctState.SettingsKey = DerivedGate->SettingsKey;
	DerivedAdjunctState.bDerivedOnlyStorageConfirmed = true;
	DerivedAdjunctState.bRemovableWithoutLineageLoss =
		DerivedGate->bDisableAllowed && DerivedGate->bUserControllable;
	DerivedAdjunctState.bAllFeaturesOffSafe = true;
	DerivedAdjunctState.bDerivedGateActive =
		HyperTwistMemoryCoreLibraryInternal::IsFeatureGateEnabledForProfile(
			DerivedGate->GateId,
			*DerivedGate,
			MemoryLedgerState.EconomicRetentionProfile,
			MemoryLedgerState.MaxRetentionProfile,
			ContextAssemblyProfile
		);

	if (!DerivedAdjunctState.bDerivedGateActive)
	{
		if (!DerivedAdjunctState.IsStructurallyValid())
		{
			return FHyperTwistMemoryDerivedAdjunctState();
		}

		return DerivedAdjunctState;
	}

	auto AppendProvenanceLinks =
		[](
			TArray<FHyperTwistMemoryProvenanceLink>& OutProvenanceLinks,
			const TArray<FHyperTwistMemoryProvenanceLink>& ProvenanceLinks)
		{
			for (const FHyperTwistMemoryProvenanceLink& ProvenanceLink : ProvenanceLinks)
			{
				HyperTwistMemoryCoreLibraryInternal::AddUniqueProvenanceLink(
					OutProvenanceLinks,
					ProvenanceLink
				);
			}
		};

	auto EnsureFallbackProvenance =
		[&](
			TArray<FString>& SourceEntityIds,
			TArray<FHyperTwistMemoryProvenanceLink>& ProvenanceLinks)
		{
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				LedgerEntitiesById,
				PolicyEntity->EntityId,
				TEXT("memory-policy-profile"),
				ProvenanceLinks
			);
			HyperTwistMemoryCoreLibraryInternal::TryAppendEntityProvenance(
				LedgerEntitiesById,
				LedgerContractEntity->EntityId,
				TEXT("memory-ledger-contract"),
				ProvenanceLinks
			);
			HyperTwistMemoryCoreLibraryInternal::AppendSourceEntityIdsFromProvenance(
				SourceEntityIds,
				ProvenanceLinks
			);
		};

	auto JoinTopValues =
		[](const TArray<FString>& Values, const int32 MaxValues)
		{
			FString Joined;
			const int32 ValueCount = FMath::Min(MaxValues, Values.Num());
			for (int32 Index = 0; Index < ValueCount; ++Index)
			{
				if (!Joined.IsEmpty())
				{
					Joined += TEXT(", ");
				}
				Joined += Values[Index];
			}
			return Joined;
		};

	auto AddCompactSummary =
		[&](const FHyperTwistMemoryCompactSummary& CompactSummary)
		{
			if (!CompactSummary.IsStructurallyValid()
				|| DerivedAdjunctState.CompactSummaries.ContainsByPredicate(
					[&CompactSummary](const FHyperTwistMemoryCompactSummary& ExistingSummary)
					{
						return ExistingSummary.SummaryId == CompactSummary.SummaryId;
					}))
			{
				return;
			}

			DerivedAdjunctState.CompactSummaries.Add(CompactSummary);
		};

	auto AddReducedContextPacket =
		[&](const FHyperTwistMemoryReducedContextPacket& ReducedContextPacket)
		{
			if (!ReducedContextPacket.IsStructurallyValid()
				|| DerivedAdjunctState.ReducedContextPackets.ContainsByPredicate(
					[&ReducedContextPacket](
						const FHyperTwistMemoryReducedContextPacket& ExistingPacket)
					{
						return ExistingPacket.PacketId == ReducedContextPacket.PacketId;
					}))
			{
				return;
			}

			DerivedAdjunctState.ReducedContextPackets.Add(ReducedContextPacket);
		};

	auto AddDigestView =
		[&](const FHyperTwistMemoryDigestView& DigestView)
		{
			if (!DigestView.IsStructurallyValid()
				|| DerivedAdjunctState.DigestViews.ContainsByPredicate(
					[&DigestView](const FHyperTwistMemoryDigestView& ExistingDigestView)
					{
						return ExistingDigestView.DigestId == DigestView.DigestId;
					}))
			{
				return;
			}

			DerivedAdjunctState.DigestViews.Add(DigestView);
		};

	auto MakeCompactSummary =
		[&](const FString& SummaryId,
			const FString& SummaryKind,
			const FString& Headline,
			const FString& SummaryText,
			const TArray<FHyperTwistMemoryProvenanceLink>& ProvenanceLinks)
		{
			FHyperTwistMemoryCompactSummary CompactSummary;
			CompactSummary.SummaryId = SummaryId;
			CompactSummary.SummaryKind = SummaryKind;
			CompactSummary.Headline = Headline;
			CompactSummary.SummaryText = SummaryText;
			CompactSummary.UserId = UserId;
			CompactSummary.ReferenceUtc = ResolvedReferenceUtc;
			AppendProvenanceLinks(CompactSummary.ProvenanceLinks, ProvenanceLinks);
			EnsureFallbackProvenance(
				CompactSummary.SourceEntityIds,
				CompactSummary.ProvenanceLinks
			);
			return CompactSummary;
		};

	auto MakeReducedContextPacket =
		[&](const FString& PacketId,
			const FString& PacketKind,
			const FString& Headline,
			const FString& PacketBody,
			const int32 MaxTokenHint,
			const TArray<FHyperTwistMemoryProvenanceLink>& ProvenanceLinks)
		{
			FHyperTwistMemoryReducedContextPacket ReducedContextPacket;
			ReducedContextPacket.PacketId = PacketId;
			ReducedContextPacket.PacketKind = PacketKind;
			ReducedContextPacket.Headline = Headline;
			ReducedContextPacket.PacketBody = PacketBody;
			ReducedContextPacket.UserId = UserId;
			ReducedContextPacket.ReferenceUtc = ResolvedReferenceUtc;
			ReducedContextPacket.MaxTokenHint = MaxTokenHint;
			AppendProvenanceLinks(
				ReducedContextPacket.ProvenanceLinks,
				ProvenanceLinks
			);
			EnsureFallbackProvenance(
				ReducedContextPacket.SourceEntityIds,
				ReducedContextPacket.ProvenanceLinks
			);
			return ReducedContextPacket;
		};

	auto MakeDigestView =
		[&](const FString& DigestId,
			const FString& DigestKind,
			const FString& Title,
			const FString& SummaryLine,
			const TArray<FHyperTwistMemoryProvenanceLink>& ProvenanceLinks)
		{
			FHyperTwistMemoryDigestView DigestView;
			DigestView.DigestId = DigestId;
			DigestView.DigestKind = DigestKind;
			DigestView.Title = Title;
			DigestView.SummaryLine = SummaryLine;
			DigestView.UserId = UserId;
			DigestView.ReferenceUtc = ResolvedReferenceUtc;
			AppendProvenanceLinks(DigestView.ProvenanceLinks, ProvenanceLinks);
			EnsureFallbackProvenance(
				DigestView.SourceEntityIds,
				DigestView.ProvenanceLinks
			);
			return DigestView;
		};

	TArray<FString> RecallHeadlines;
	for (int32 MatchIndex = 0;
		MatchIndex < FMath::Min(2, RecallState.RecallMatches.Num());
		++MatchIndex)
	{
		HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
			RecallHeadlines,
			RecallState.RecallMatches[MatchIndex].Headline
		);
	}

	TArray<FString> KnowledgeTitles;
	for (int32 ObjectIndex = 0;
		ObjectIndex < FMath::Min(3, KnowledgeNotesState.KnowledgeObjects.Num());
		++ObjectIndex)
	{
		HyperTwistMemoryCoreLibraryInternal::AddUniqueString(
			KnowledgeTitles,
			KnowledgeNotesState.KnowledgeObjects[ObjectIndex].Title
		);
	}

	const FHyperTwistMemoryResumePack* PrimaryResumePack =
		ChronicleState.ResumePacks.Num() > 0 ? &ChronicleState.ResumePacks[0] : nullptr;
	const FHyperTwistMemoryRecallMatch* TopRecallMatch =
		RecallState.RecallMatches.Num() > 0 ? &RecallState.RecallMatches[0] : nullptr;
	const FHyperTwistMemoryCognitiveFact* ActiveFact =
		CognitiveState.Facts.FindByPredicate(
			[](const FHyperTwistMemoryCognitiveFact& Fact)
			{
				return Fact.bActive;
			}
		);

	TArray<FHyperTwistMemoryProvenanceLink> OverviewProvenance;
	AppendProvenanceLinks(OverviewProvenance, KnowledgeNotesState.UserNotesPosture.ProvenanceLinks);
	if (ChronicleState.ChronicleEvents.Num() > 0)
	{
		AppendProvenanceLinks(
			OverviewProvenance,
			ChronicleState.ChronicleEvents[0].ProvenanceLinks
		);
	}
	if (ActiveFact != nullptr)
	{
		AppendProvenanceLinks(OverviewProvenance, ActiveFact->ProvenanceLinks);
	}
	if (KnowledgeNotesState.KnowledgeObjects.Num() > 0)
	{
		AppendProvenanceLinks(
			OverviewProvenance,
			KnowledgeNotesState.KnowledgeObjects[0].ProvenanceLinks
		);
	}

	AddCompactSummary(
		MakeCompactSummary(
			FString::Printf(TEXT("memory-compact-summary/overview/%s"), *UserId),
			TEXT("memory-overview"),
			TEXT("Derived memory overview"),
			FString::Printf(
				TEXT("Ledger=%d/%d/%d entities, chronicle=%d events, recall=%d matches, activeFacts=%d, curatedKnowledge=%d."),
				MemoryLedgerState.AuthoritativeEntityCount,
				MemoryLedgerState.SemiAuthoritativeEntityCount,
				MemoryLedgerState.DerivedEntityCount,
				ChronicleState.ChronicleEvents.Num(),
				RecallState.RecallMatches.Num(),
				CognitiveState.ActiveFactCount,
				KnowledgeNotesState.CuratedReferenceObjectCount
			),
			OverviewProvenance
		)
	);

	TArray<FHyperTwistMemoryProvenanceLink> ResumeSummaryProvenance;
	if (PrimaryResumePack != nullptr)
	{
		AppendProvenanceLinks(ResumeSummaryProvenance, PrimaryResumePack->ProvenanceLinks);
	}
	if (RecallState.SharedContextProjections.Num() > 0)
	{
		AppendProvenanceLinks(
			ResumeSummaryProvenance,
			RecallState.SharedContextProjections[0].ProvenanceLinks
		);
	}

	AddCompactSummary(
		MakeCompactSummary(
			FString::Printf(TEXT("memory-compact-summary/resume/%s"), *UserId),
			TEXT("active-resume"),
			TEXT("Continuity and resume overview"),
			FString::Printf(
				TEXT("OpenSessionGroups=%d, ResumePacks=%d, BlockingGuards=%d, SharedProjections=%d."),
				ChronicleState.OpenSessionGroupCount,
				ChronicleState.ResumeRequiredCount,
				ChronicleState.BlockingGuardCount,
				RecallState.SharedContextProjectionCount
			),
			ResumeSummaryProvenance
		)
	);

	TArray<FHyperTwistMemoryProvenanceLink> KnowledgeSummaryProvenance;
	if (KnowledgeNotesState.KnowledgeObjects.Num() > 0)
	{
		AppendProvenanceLinks(
			KnowledgeSummaryProvenance,
			KnowledgeNotesState.KnowledgeObjects[0].ProvenanceLinks
		);
	}
	if (KnowledgeNotesState.PromotionReviews.Num() > 0)
	{
		AppendProvenanceLinks(
			KnowledgeSummaryProvenance,
			KnowledgeNotesState.PromotionReviews[0].ProvenanceLinks
		);
	}
	AppendProvenanceLinks(
		KnowledgeSummaryProvenance,
		KnowledgeNotesState.UserNotesPosture.ProvenanceLinks
	);

	AddCompactSummary(
		MakeCompactSummary(
			FString::Printf(TEXT("memory-compact-summary/knowledge/%s"), *UserId),
			TEXT("knowledge-promotion"),
			TEXT("Knowledge and notes overview"),
			FString::Printf(
				TEXT("Curated=%d, approved=%d, deferred=%d, blocked=%d, userNotes=%s."),
				KnowledgeNotesState.CuratedReferenceObjectCount,
				KnowledgeNotesState.ApprovedPromotionCount,
				KnowledgeNotesState.DeferredPromotionCount,
				KnowledgeNotesState.BlockedPromotionCount,
				KnowledgeNotesState.bUserNotesLaneAvailable
					? TEXT("active")
					: TEXT("separately-gated")
			),
			KnowledgeSummaryProvenance
		)
	);

	TArray<FHyperTwistMemoryProvenanceLink> CoachResumePacketProvenance;
	if (PrimaryResumePack != nullptr)
	{
		AppendProvenanceLinks(
			CoachResumePacketProvenance,
			PrimaryResumePack->ProvenanceLinks
		);
	}
	if (TopRecallMatch != nullptr)
	{
		AppendProvenanceLinks(
			CoachResumePacketProvenance,
			TopRecallMatch->ProvenanceLinks
		);
	}
	if (ActiveFact != nullptr)
	{
		AppendProvenanceLinks(CoachResumePacketProvenance, ActiveFact->ProvenanceLinks);
	}
	AppendProvenanceLinks(
		CoachResumePacketProvenance,
		KnowledgeNotesState.UserNotesPosture.ProvenanceLinks
	);

	const FString ResumeHeadline =
		PrimaryResumePack != nullptr
			? PrimaryResumePack->Headline
			: TEXT("No active resume pack");
	const FString ActiveFactHeadline =
		ActiveFact != nullptr
			? ActiveFact->Headline
			: TEXT("No active cognitive fact");

	AddReducedContextPacket(
		MakeReducedContextPacket(
			FString::Printf(TEXT("memory-reduced-context/coach-resume/%s"), *UserId),
			TEXT("coach-resume-context"),
			TEXT("Coach resume packet"),
			FString::Printf(
				TEXT("Resume=%s. RecallHighlights=%s. ActiveFact=%s. Notes=%s"),
				*ResumeHeadline,
				*JoinTopValues(RecallHeadlines, 2),
				*ActiveFactHeadline,
				*KnowledgeNotesState.UserNotesPosture.SummaryLine
			),
			240,
			CoachResumePacketProvenance
		)
	);

	TArray<FHyperTwistMemoryProvenanceLink> ReviewPacketProvenance;
	if (KnowledgeNotesState.KnowledgeObjects.Num() > 0)
	{
		AppendProvenanceLinks(
			ReviewPacketProvenance,
			KnowledgeNotesState.KnowledgeObjects[0].ProvenanceLinks
		);
	}
	if (KnowledgeNotesState.PromotionReviews.Num() > 0)
	{
		AppendProvenanceLinks(
			ReviewPacketProvenance,
			KnowledgeNotesState.PromotionReviews[0].ProvenanceLinks
		);
	}
	if (CognitiveState.Contradictions.Num() > 0)
	{
		AppendProvenanceLinks(
			ReviewPacketProvenance,
			CognitiveState.Contradictions[0].ProvenanceLinks
		);
	}

	AddReducedContextPacket(
		MakeReducedContextPacket(
			FString::Printf(TEXT("memory-reduced-context/review/%s"), *UserId),
			TEXT("knowledge-review-context"),
			TEXT("Knowledge review packet"),
			FString::Printf(
				TEXT("Knowledge=%s. Promotions approved/deferred/blocked=%d/%d/%d. OpenCognitiveReview=%s."),
				*JoinTopValues(KnowledgeTitles, 3),
				KnowledgeNotesState.ApprovedPromotionCount,
				KnowledgeNotesState.DeferredPromotionCount,
				KnowledgeNotesState.BlockedPromotionCount,
				CognitiveState.bHasOpenCognitiveReview ? TEXT("yes") : TEXT("no")
			),
			220,
			ReviewPacketProvenance
		)
	);

	TArray<FHyperTwistMemoryProvenanceLink> CoachDigestProvenance =
		CoachResumePacketProvenance;
	AddDigestView(
		MakeDigestView(
			FString::Printf(TEXT("memory-digest/coach/%s"), *UserId),
			TEXT("coach-memory-digest"),
			TEXT("Coach memory digest"),
			FString::Printf(
				TEXT("resume=%d recall=%d activeFacts=%d blockingGuards=%d"),
				ChronicleState.ResumeRequiredCount,
				RecallState.RecallResultCount,
				CognitiveState.ActiveFactCount,
				ChronicleState.BlockingGuardCount
			),
			CoachDigestProvenance
		)
	);

	TArray<FHyperTwistMemoryProvenanceLink> KnowledgeDigestProvenance =
		KnowledgeSummaryProvenance;
	AddDigestView(
		MakeDigestView(
			FString::Printf(TEXT("memory-digest/knowledge/%s"), *UserId),
			TEXT("knowledge-memory-digest"),
			TEXT("Knowledge memory digest"),
			FString::Printf(
				TEXT("knowledge=%d approved=%d deferred=%d blocked=%d notes=%s"),
				KnowledgeNotesState.CuratedReferenceObjectCount,
				KnowledgeNotesState.ApprovedPromotionCount,
				KnowledgeNotesState.DeferredPromotionCount,
				KnowledgeNotesState.BlockedPromotionCount,
				KnowledgeNotesState.bUserNotesLaneAvailable
					? TEXT("active")
					: TEXT("gated")
			),
			KnowledgeDigestProvenance
		)
	);

	DerivedAdjunctState.CompactSummaryCount =
		DerivedAdjunctState.CompactSummaries.Num();
	DerivedAdjunctState.ReducedContextPacketCount =
		DerivedAdjunctState.ReducedContextPackets.Num();
	DerivedAdjunctState.DigestViewCount = DerivedAdjunctState.DigestViews.Num();

	if (!DerivedAdjunctState.IsStructurallyValid())
	{
		return FHyperTwistMemoryDerivedAdjunctState();
	}

	return DerivedAdjunctState;
}
