Coverage for src/governed_harness/memory/store.py: 100%
55 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1from __future__ import annotations
3from dataclasses import dataclass
4from datetime import UTC, datetime
5from typing import Literal
7from governed_harness.domain.enums import MemoryLevel
8from governed_harness.domain.models import MemoryRecord
9from governed_harness.storage.sqlite import SQLiteStateStore
11ExclusionReason = Literal["superseded", "expired", "unapproved", "limit"]
13# Levels that only enter a context after an explicit approval.
14APPROVAL_REQUIRED = frozenset(
15 {MemoryLevel.NORMATIVE, MemoryLevel.PROJECT, MemoryLevel.RETROSPECTIVE}
16)
18_LEVEL_ORDER = {
19 MemoryLevel.NORMATIVE: 0,
20 MemoryLevel.PROJECT: 1,
21 MemoryLevel.TASK: 2,
22 MemoryLevel.RETROSPECTIVE: 3,
23 MemoryLevel.EPHEMERAL: 4,
24}
27@dataclass(frozen=True)
28class MemoryExclusion:
29 """A record that was in scope for a context but did not enter it, with the reason."""
31 memory_id: str
32 level: MemoryLevel
33 key: str
34 reason: ExclusionReason
35 superseded_by: str | None = None
38@dataclass(frozen=True)
39class ContextSelection:
40 records: tuple[MemoryRecord, ...]
41 exclusions: tuple[MemoryExclusion, ...]
44def is_effective(record: MemoryRecord) -> bool:
45 """Whether a record carries authority: approved, or of a level that needs no approval."""
46 return record.approved or record.level not in APPROVAL_REQUIRED
49class MemoryStore:
50 def __init__(self, state: SQLiteStateStore) -> None:
51 self.state = state
53 def put(self, record: MemoryRecord) -> None:
54 self.state.put(
55 "memory",
56 record.memory_id,
57 record,
58 execution_id=record.execution_id,
59 project_id=record.project_id,
60 )
62 def get(self, memory_id: str) -> MemoryRecord:
63 return self.state.get("memory", memory_id, MemoryRecord)
65 def list_project(self, project_id: str) -> list[MemoryRecord]:
66 return self.state.list("memory", MemoryRecord, project_id=project_id)
68 def select(
69 self,
70 *,
71 project_id: str,
72 task_id: str | None,
73 execution_id: str | None,
74 max_records: int = 50,
75 now: datetime | None = None,
76 ) -> ContextSelection:
77 """Select the records that enter a context and say why each other candidate did not.
79 Task records are candidates only for their task and ephemeral records only for their
80 execution; records of other tasks or executions are out of scope and are not listed. A
81 record supersedes another only when it carries authority itself, so an unapproved
82 proposal never displaces an approved record.
83 """
84 instant = now or datetime.now(UTC)
85 candidates = [
86 record
87 for record in self.list_project(project_id)
88 if not (
89 record.level is MemoryLevel.TASK
90 and record.task_id != task_id
91 or record.level is MemoryLevel.EPHEMERAL
92 and record.execution_id != execution_id
93 )
94 ]
95 superseded_by = {
96 record.supersedes: record.memory_id
97 for record in candidates
98 if record.supersedes and is_effective(record)
99 }
100 eligible: list[MemoryRecord] = []
101 exclusions: list[MemoryExclusion] = []
103 def exclude(record: MemoryRecord, reason: ExclusionReason) -> None:
104 exclusions.append(
105 MemoryExclusion(
106 memory_id=record.memory_id,
107 level=record.level,
108 key=record.key,
109 reason=reason,
110 superseded_by=superseded_by.get(record.memory_id),
111 )
112 )
114 for record in candidates:
115 if record.memory_id in superseded_by:
116 exclude(record, "superseded")
117 elif record.valid_until and record.valid_until <= instant:
118 exclude(record, "expired")
119 elif not is_effective(record):
120 exclude(record, "unapproved")
121 else:
122 eligible.append(record)
123 eligible.sort(
124 key=lambda item: (_LEVEL_ORDER[item.level], item.key, item.created_at, item.memory_id)
125 )
126 for record in eligible[max_records:]:
127 exclude(record, "limit")
128 exclusions.sort(key=lambda item: (_LEVEL_ORDER[item.level], item.key, item.memory_id))
129 return ContextSelection(tuple(eligible[:max_records]), tuple(exclusions))
131 def select_context(
132 self,
133 *,
134 project_id: str,
135 task_id: str | None,
136 execution_id: str | None,
137 max_records: int = 50,
138 now: datetime | None = None,
139 ) -> tuple[MemoryRecord, ...]:
140 return self.select(
141 project_id=project_id,
142 task_id=task_id,
143 execution_id=execution_id,
144 max_records=max_records,
145 now=now,
146 ).records