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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 76 additions & 4 deletions src/powercontext/builtin/artifacts/atomic_memory/extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,20 @@
from __future__ import annotations

from dataclasses import dataclass
from typing import TYPE_CHECKING, Literal
from typing import TYPE_CHECKING, Any, Literal

from pydantic import BaseModel, ConfigDict, Field, JsonValue, TypeAdapter

from powercontext.artifacts import ArtifactRef
from powercontext.builtin.artifacts.atomic_memory.models import AtomicMemoryContent
from powercontext.builtin.artifacts.memory.prompts import MemoryExtractionProfile
from powercontext.builtin.inference import InvalidInferenceOutputError, StructuredGenerator, TokenEstimator
from powercontext.builtin.persistence.records import _canonical_source_text
from powercontext.builtin.persistence.sources import SourceRepository, StoredSource
from powercontext.sources import TEXT_EVIDENCE_PROJECTION_KEY, SourceObservation, SourceRef, TextEvidence
from powercontext.sources import TEXT_EVIDENCE_PROJECTION_KEY, Source, SourceObservation, SourceRef, TextEvidence

_JSON = TypeAdapter(JsonValue)
_TEXT_EVIDENCE_KEY = TEXT_EVIDENCE_PROJECTION_KEY.model_dump(mode="json")

if TYPE_CHECKING:
from powercontext.builtin.artifacts.atomic_memory.reconciliation import (
Expand Down Expand Up @@ -129,6 +131,73 @@ async def extract(self, value: AtomicMemoryExtractionInput) -> tuple[AtomicMemor
return output.candidates


def _duplicates_body(value: JsonValue, body: JsonValue) -> bool:
"""Whether a metadata value is exactly the evidential body text."""

return isinstance(body, str) and value == body


def _wire_repeats_body(value: JsonValue, body_text: JsonValue) -> bool:
"""Whether a wire carrier serializes to exactly the evidential body text."""

return isinstance(body_text, str) and value is not None and _canonical_source_text(value) == body_text


def _is_text_evidence_projection(projection: JsonValue) -> bool:
return isinstance(projection, dict) and projection.get("key") == _TEXT_EVIDENCE_KEY


def _drop_body_carriers(dumped: dict[str, Any], body_text: JsonValue) -> None:
"""Remove content and wire carriers that only reproduce the body text."""

if _duplicates_body(dumped.get("content"), body_text):
dumped.pop("content", None)
if _wire_repeats_body(dumped.get("wire_content"), body_text):
dumped.pop("wire_content", None)
dumped.pop("wire_content_present", None)


def _drop_text_evidence_projection(dumped: dict[str, Any]) -> None:
"""Remove the consumed text-evidence projection and keep the others."""

projections = dumped.get("projections")
if not isinstance(projections, list):
return
remaining = [item for item in projections if not _is_text_evidence_projection(item)]
if remaining:
dumped["projections"] = remaining
else:
dumped.pop("projections", None)


def _compact_source_metadata(value: Source, *, body: JsonValue, body_from_text_projection: bool) -> JsonValue:
"""Keep provenance without re-sending a body that the evidence already carries.

``content`` and each wire carrier are dropped only when they reproduce the body
text. The observation ``payload`` follows the same rule, and the consumed
text-evidence projection is dropped. Every other field, including
``payload.metadata`` and unrelated projections, is kept.
"""

dumped = value.model_dump(mode="json", by_alias=True)
body_text = body.get("content") if isinstance(body, dict) else None
_drop_body_carriers(dumped, body_text)

if not isinstance(value, SourceObservation):
return _JSON.validate_python(dumped)
payload = dumped.get("payload")
if body_from_text_projection:
if isinstance(payload, dict):
compacted = dict(payload)
_drop_body_carriers(compacted, body_text)
if compacted != payload:
dumped["payload"] = compacted
_drop_text_evidence_projection(dumped)
elif payload == body:
dumped.pop("payload", None)
return _JSON.validate_python(dumped)


async def project_atomic_memory_evidence(
stored: StoredSource,
sources: SourceRepository,
Expand All @@ -139,23 +208,26 @@ async def project_atomic_memory_evidence(
"""Expose source-provided dates in content/metadata without synthesizing time."""

value = stored.value
body_from_text_projection = False
if isinstance(value, SourceObservation):
content = value.payload
for projection in value.projections:
if projection.key == TEXT_EVIDENCE_PROJECTION_KEY:
content = TextEvidence.model_validate(projection.value).model_dump(mode="json")
body_from_text_projection = True
break
else:
materialized = await sources.read_value(value)
content = (
materialized.model_dump(mode="json", by_alias=True) if isinstance(materialized, BaseModel) else materialized
)
body = _JSON.validate_python(content)
return AtomicMemoryEvidence(
evidence_id=evidence_id,
source_ref=stored.ref,
journal_position=stored.journal_position,
content=_JSON.validate_python(content),
source_metadata=_JSON.validate_python(value.model_dump(mode="json", by_alias=True)),
content=body,
source_metadata=_compact_source_metadata(value, body=body, body_from_text_projection=body_from_text_projection),
via_artifact=via_artifact,
)

Expand Down
Loading
Loading