File size: 10,341 Bytes
c3a3710
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""

Provenance Tracking Module (Phase 5.0)

=======================================

W3C PROV-inspired source tracking for MnemoCore memories.



Tracks the full lifecycle of every MemoryNode:

  - origin: where/how the memory was created

  - lineage: ordered list of transformation events

  - version: incremented on each significant mutation



This is the foundation for:

  - Trust & audit trails (AI Governance)

  - Contradiction resolution

  - Memory-as-a-Service lineage API

  - Source reliability scoring



Public API:

    record = ProvenanceRecord.new(origin_type="observation", agent_id="agent-001")

    record.add_event("consolidated", source_memories=["mem_a", "mem_b"])

    serialized = record.to_dict()

    restored = ProvenanceRecord.from_dict(serialized)

"""

from __future__ import annotations

from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional


# ------------------------------------------------------------------ #
#  Origin types                                                       #
# ------------------------------------------------------------------ #

ORIGIN_TYPES = {
    "observation",      # Direct input from agent or user
    "inference",        # Derived/reasoned by LLM or engine
    "dream",            # Produced by SubconsciousAI dream cycle
    "consolidation",    # Result of SemanticConsolidation merge
    "external_sync",    # Fetched from external source (RSS, API, etc.)
    "user_correction",  # Explicit user override
    "prediction",       # Stored as a future prediction
}


# ------------------------------------------------------------------ #
#  Lineage event                                                      #
# ------------------------------------------------------------------ #

@dataclass
class LineageEvent:
    """

    A single step in a memory's transformation history.



    Examples:

        created       – initial storage

        accessed      – retrieved by a query

        consolidated  – merged into or from a proto-memory cluster

        verified      – reliability confirmed externally

        contradicted  – flagged as contradicting another memory

        updated       – content or metadata modified

        archived      – moved to COLD tier

        expired       – TTL reached or evicted

    """
    event: str
    timestamp: str  # ISO 8601
    actor: Optional[str] = None         # agent_id, "system", "user", etc.
    source_memories: List[str] = field(default_factory=list)  # for consolidation
    outcome: Optional[bool] = None      # for verification events
    notes: Optional[str] = None
    extra: Dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> Dict[str, Any]:
        d: Dict[str, Any] = {
            "event": self.event,
            "timestamp": self.timestamp,
        }
        if self.actor is not None:
            d["actor"] = self.actor
        if self.source_memories:
            d["source_memories"] = self.source_memories
        if self.outcome is not None:
            d["outcome"] = self.outcome
        if self.notes:
            d["notes"] = self.notes
        if self.extra:
            d["extra"] = self.extra
        return d

    @classmethod
    def from_dict(cls, d: Dict[str, Any]) -> "LineageEvent":
        return cls(
            event=d["event"],
            timestamp=d["timestamp"],
            actor=d.get("actor"),
            source_memories=d.get("source_memories", []),
            outcome=d.get("outcome"),
            notes=d.get("notes"),
            extra=d.get("extra", {}),
        )


# ------------------------------------------------------------------ #
#  Origin                                                             #
# ------------------------------------------------------------------ #

@dataclass
class ProvenanceOrigin:
    """Where/how a memory was first created."""

    type: str                           # One of ORIGIN_TYPES
    agent_id: Optional[str] = None
    session_id: Optional[str] = None
    source_url: Optional[str] = None   # For external_sync
    timestamp: str = field(
        default_factory=lambda: datetime.now(timezone.utc).isoformat()
    )

    def to_dict(self) -> Dict[str, Any]:
        d: Dict[str, Any] = {
            "type": self.type,
            "timestamp": self.timestamp,
        }
        if self.agent_id:
            d["agent_id"] = self.agent_id
        if self.session_id:
            d["session_id"] = self.session_id
        if self.source_url:
            d["source_url"] = self.source_url
        return d

    @classmethod
    def from_dict(cls, d: Dict[str, Any]) -> "ProvenanceOrigin":
        return cls(
            type=d.get("type", "observation"),
            agent_id=d.get("agent_id"),
            session_id=d.get("session_id"),
            source_url=d.get("source_url"),
            timestamp=d.get("timestamp", datetime.now(timezone.utc).isoformat()),
        )


# ------------------------------------------------------------------ #
#  ProvenanceRecord β€” the full provenance object on a MemoryNode     #
# ------------------------------------------------------------------ #

@dataclass
class ProvenanceRecord:
    """

    Full provenance object attached to a MemoryNode.



    Designed to be serialized into node.metadata["provenance"] for

    backward compatibility with existing storage layers.

    """

    origin: ProvenanceOrigin
    lineage: List[LineageEvent] = field(default_factory=list)
    version: int = 1
    confidence_source: str = "bayesian_ltp"  # How the confidence score is derived

    # ---- Factory methods ------------------------------------------ #

    @classmethod
    def new(

        cls,

        origin_type: str = "observation",

        agent_id: Optional[str] = None,

        session_id: Optional[str] = None,

        source_url: Optional[str] = None,

        actor: Optional[str] = None,

    ) -> "ProvenanceRecord":
        """Create a fresh ProvenanceRecord and log the 'created' event."""
        now = datetime.now(timezone.utc).isoformat()
        origin = ProvenanceOrigin(
            type=origin_type if origin_type in ORIGIN_TYPES else "observation",
            agent_id=agent_id,
            session_id=session_id,
            source_url=source_url,
            timestamp=now,
        )
        record = cls(origin=origin)
        record.add_event(
            event="created",
            actor=actor or agent_id or "system",
        )
        return record

    # ---- Mutation ------------------------------------------------- #

    def add_event(

        self,

        event: str,

        actor: Optional[str] = None,

        source_memories: Optional[List[str]] = None,

        outcome: Optional[bool] = None,

        notes: Optional[str] = None,

        **extra: Any,

    ) -> "ProvenanceRecord":
        """Append a new lineage event and bump the version counter."""
        evt = LineageEvent(
            event=event,
            timestamp=datetime.now(timezone.utc).isoformat(),
            actor=actor,
            source_memories=source_memories or [],
            outcome=outcome,
            notes=notes,
            extra=extra,
        )
        self.lineage.append(evt)
        self.version += 1
        return self

    def mark_consolidated(

        self,

        source_memory_ids: List[str],

        actor: str = "consolidation_worker",

    ) -> "ProvenanceRecord":
        """Convenience wrapper for consolidation events."""
        return self.add_event(
            event="consolidated",
            actor=actor,
            source_memories=source_memory_ids,
        )

    def mark_verified(

        self,

        success: bool,

        actor: str = "system",

        notes: Optional[str] = None,

    ) -> "ProvenanceRecord":
        """Record a verification outcome."""
        return self.add_event(
            event="verified",
            actor=actor,
            outcome=success,
            notes=notes,
        )

    def mark_contradicted(

        self,

        contradiction_group_id: str,

        actor: str = "contradiction_detector",

    ) -> "ProvenanceRecord":
        """Flag this memory as contradicted."""
        return self.add_event(
            event="contradicted",
            actor=actor,
            contradiction_group_id=contradiction_group_id,
        )

    # ---- Serialization -------------------------------------------- #

    def to_dict(self) -> Dict[str, Any]:
        return {
            "origin": self.origin.to_dict(),
            "lineage": [e.to_dict() for e in self.lineage],
            "version": self.version,
            "confidence_source": self.confidence_source,
        }

    @classmethod
    def from_dict(cls, d: Dict[str, Any]) -> "ProvenanceRecord":
        return cls(
            origin=ProvenanceOrigin.from_dict(d.get("origin", {"type": "observation"})),
            lineage=[LineageEvent.from_dict(e) for e in d.get("lineage", [])],
            version=d.get("version", 1),
            confidence_source=d.get("confidence_source", "bayesian_ltp"),
        )

    # ---- Helpers -------------------------------------------------- #

    @property
    def created_at(self) -> str:
        """ISO timestamp of the creation event."""
        for event in self.lineage:
            if event.event == "created":
                return event.timestamp
        return self.origin.timestamp

    @property
    def last_event(self) -> Optional[LineageEvent]:
        """Most recent lineage event."""
        return self.lineage[-1] if self.lineage else None

    def is_contradicted(self) -> bool:
        return any(e.event == "contradicted" for e in self.lineage)

    def is_verified(self) -> bool:
        return any(
            e.event == "verified" and e.outcome is True for e in self.lineage
        )

    def __repr__(self) -> str:
        return (
            f"ProvenanceRecord(origin_type={self.origin.type!r}, "
            f"version={self.version}, events={len(self.lineage)})"
        )