Files
EvoScientist-Multi/EvoScientist/memory/observations/relations.py
T
dinos f2f010a350 feat(memory): observation linking (#307)
* refactor(gateway): create module for launching async/bg agents

* refactor(memory): refactor worker launch around source context & output deltas

* refactor(gateway): generalize async/bg module

* refactor(memory): revamp worker launching

* feat(memory): add observation linking

* test(memory): remove redundant test branches

* fix(memory): make 'supersedes' relation directional

* fix(memory): don't create empty project observation dirs

* fix(memory): schedule direct observations for linking

* fix(cli): wait for observation linker before shutdown

* fix(memory): block arbitrary writes to /memories

* fix(linker): remove `linked_by` attribute from frontmatter

* refactor(linker): rename base relationship to `comlpements`

* fix(cli): bump worker wait to 2m

* feat(tools): catch malformed tool calls & retry

* feat(status): add linking result to statusbar

* fix(linker): don't launch linker when observations are disabled

* fix(memory): use posix paths

* fix(watcher): call abort hook on error status

* fix(watcher): delete thread on failed run creation

* fix(watcher): preserve url

* fix(observation): record session_id, drop unused fields

* fix(memory): reject unsupported worker source types

* refactor(backends): shared memory backend builder

* fix(scheduler): resolve linker inputs outside lock

* fix(memory): dont launch workers / record observations without thread_id

* feat(memory): include related observations in tool results

* fix(memory): skip malformed observation frontmatter

* revert(tools): drop tool error handling changes from this PR

* fix(memory): serialize observation link writes

* fix(memory): queue observations written by aborted workers

* fix(memory): track observation linker launch handoff

* fix(memory): resolve cross-project related observations

* fix(status): avoid recounting reason-only link updates

* fix(memory): avoid rereading file for content

* fix(linker): use neutral prose for bidirectional reasons

* test(memory): coverage for aborted/failed launches

* test(memory): cleanup & helpers

* feat(linker): add observations index hint
2026-06-26 22:20:52 +01:00

157 lines
5.1 KiB
Python

"""Frontmatter-native links between observation memory files."""
from __future__ import annotations
import threading
from datetime import UTC, datetime
from pathlib import Path
from ..types import ObservationRelation
from .store import (
ObservationFrontmatter,
RelatedObservationEntry,
observation_document_by_id,
related_observation_entries,
write_observation_document,
)
_link_write_lock = threading.Lock()
def _relation_value(value: ObservationRelation | str) -> str:
try:
return ObservationRelation(value).value
except ValueError as exc:
allowed = ", ".join(relation.value for relation in ObservationRelation)
raise ValueError(f"relation must be one of: {allowed}") from exc
def _can_write_reverse_relation(relation: str) -> bool:
return relation != ObservationRelation.SUPERSEDES.value
def _upsert_related_observation(
metadata: ObservationFrontmatter,
*,
target_observation_id: str,
relation: str,
reason: str,
linked_at: str,
) -> bool:
entries = related_observation_entries(metadata)
new_entry = RelatedObservationEntry(
id=target_observation_id,
relation=ObservationRelation(relation),
reason=reason,
linked_at=linked_at,
)
for index, entry in enumerate(entries):
if entry.id != target_observation_id:
continue
if (
entry.id == new_entry.id
and entry.relation == new_entry.relation
and entry.reason == new_entry.reason
):
return False
entries[index] = new_entry
metadata.related_observations = entries
return True
entries.append(new_entry)
metadata.related_observations = entries
return True
def link_observation_files(
*,
memory_dir: str | Path,
project_id: str,
source_observation_id: str,
target_observation_id: str,
reason: str,
relation: ObservationRelation = ObservationRelation.COMPLEMENTS,
bidirectional: bool = True,
) -> dict[str, object]:
"""Link two observations by amending their frontmatter metadata."""
source_id = source_observation_id.strip()
target_id = target_observation_id.strip()
reason_text = reason.strip()
relation_text = _relation_value(relation)
if not source_id:
raise ValueError("source_observation_id must not be empty")
if not target_id:
raise ValueError("target_observation_id must not be empty")
if source_id == target_id:
raise ValueError("source_observation_id and target_observation_id must differ")
if not reason_text:
raise ValueError("reason must not be empty")
with _link_write_lock:
source_document = observation_document_by_id(
memory_dir=memory_dir,
project_id=project_id,
observation_id=source_id,
)
target_document = observation_document_by_id(
memory_dir=memory_dir,
project_id=project_id,
observation_id=target_id,
)
missing = [
observation_id
for observation_id, document in (
(source_id, source_document),
(target_id, target_document),
)
if document is None
]
if missing:
return {
"linked": False,
"source_observation_id": source_id,
"target_observation_id": target_id,
"relation": relation_text,
"updated_observation_ids": [],
"missing_observation_ids": missing,
}
linked_at = datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
updates: list[tuple[str, Path, ObservationFrontmatter, str]] = []
assert source_document is not None
source_path, source_metadata, source_body = source_document
if _upsert_related_observation(
source_metadata,
target_observation_id=target_id,
relation=relation_text,
reason=reason_text,
linked_at=linked_at,
):
updates.append((source_id, source_path, source_metadata, source_body))
if bidirectional and _can_write_reverse_relation(relation_text):
assert target_document is not None
target_path, target_metadata, target_body = target_document
if _upsert_related_observation(
target_metadata,
target_observation_id=source_id,
relation=relation_text,
reason=reason_text,
linked_at=linked_at,
):
updates.append((target_id, target_path, target_metadata, target_body))
for _observation_id, path, metadata, body in updates:
write_observation_document(path, metadata=metadata, body=body)
return {
"linked": bool(updates),
"source_observation_id": source_id,
"target_observation_id": target_id,
"relation": relation_text,
"updated_observation_ids": [
observation_id for observation_id, *_ in updates
],
"missing_observation_ids": [],
}