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
36 changes: 36 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,42 @@

## Unreleased

**Temporal validity + review-gated supersession for lessons (Phase 2).**

- Schema: `lessons.jsonl` rows may carry `valid_from` / `valid_until` /
`superseded_by`, and `status` gains `superseded`. All optional — pre-existing
rows stay valid. Markdown frontmatter gets the same fields, normalized in one
place by `recall.frontmatter.temporal_meta` (missing keys read as
`status=current`, unbounded validity).
- Writers stamp going forward: `recall remember` writes `valid_from` (plus
`status: current` when `--reviewed`); claim projection emits `status` and
`valid_from` derived from `source_ts_epoch`; graduate.py stamps
`valid_from=accepted_at` on the new row.
- Supersession is persisted on human accept only: `graduate.py --supersedes`
now flips the OLD row to `status=superseded` with `superseded_by` +
`valid_until` (via `render_lessons.update_lesson`, same flock as
`remove_lesson`), and writes a per-lesson companion markdown under
`memory/semantic/lessons/` so recall indexes one doc per lesson. Candidates
of `kind="supersession"` default `--supersedes` from the candidate itself.
- Dream-cycle contradiction detection is staging-only: the new deterministic
`agent/memory/contradictions.py` (slot-conflict via materialized ClaimState,
predicate-value clash via the topic_keys library, condition overlap — no LLM,
no producer branching) emits `kind="supersession"` candidates onto the
existing review queue. REVIEW_QUEUE.md marks them `SUPERSEDES <old_id>` and
they sort above equal-size patterns (1.5x priority). Unattended cycles never
touch `lessons.jsonl`.
- Retrieval: superseded docs no longer outrank their successors.
`ranking.superseded_policy` (`demote` default | `exclude` | `ignore`) and
`ranking.superseded_penalty` (0.5) apply after the needs_review policy in
`HybridRetriever.query`, the `--expand` rerank seam, the MCP server, and the
daemon; `exclude` also pre-filters at the Qdrant leg
(`exclude_superseded=True`). RRF fusion stays policy-blind.
- `recall trace` renders supersession chains (forward via `superseded_by`,
backward via `supersedes`, cycle-safe, resolved against companion markdown
and lessons.jsonl), and `provenance_label` carries a `superseded` /
`valid_from=` suffix when present.


## v0.8.0 (2026-09-14)

**OMP session ingestion: memory keeps accumulating when your daily driver isn't Claude Code.**
Expand Down
89 changes: 87 additions & 2 deletions agent/memory/auto_dream.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
from archive import archive_stale_workspace
from cluster import _is_activity_log_claim
from decay import DECAY_DAYS, decay_old_entries
from promote import _env_bool, cluster_and_extract, write_candidates
from promote import (_env_bool, cluster_and_extract, write_candidates,
write_supersession_candidates)
from review_state import mark_rejected, write_review_queue_summary
from validate import heuristic_check

Expand Down Expand Up @@ -368,7 +369,17 @@ def _heuristic_prefilter(candidates_dir, semantic_dir):
cand = json.load(f)
except (OSError, json.JSONDecodeError):
continue
check = heuristic_check(cand, existing)
check_target = existing
# A supersession proposal is SUPPOSED to look like the lesson it
# replaces — carve the target out of the duplicate check exactly
# as graduate.py does for --supersedes, or every proposal would be
# auto-rejected as an exact duplicate of its own predecessor.
if cand.get("kind") == "supersession" and cand.get("supersedes"):
check_target = "\n".join(
line for line in existing.splitlines()
if f"id={cand['supersedes']}" not in line
)
check = heuristic_check(cand, check_target)
if not check["passed"]:
reason = ", ".join(check["reasons"])
# Record the specific lesson(s) that triggered the duplicate
Expand All @@ -381,6 +392,46 @@ def _heuristic_prefilter(candidates_dir, semantic_dir):
return rejected


def _stage_contradiction_proposals(candidates_dir, semantic_dir, review_queue,
claim_state=None, cycle_id=""):
"""Detect candidate×lesson contradictions and STAGE proposals only.

Boundary: this never writes lessons.jsonl / LESSONS.md and never calls
graduate.py — applying a supersession is a human-gated action. Runs
after consolidation so slot conflicts can read this cycle's
materialized ClaimState (already on disk; no LLM is invoked here).
Returns the number of proposals newly staged.
"""
import contradictions # local import — avoids cycles at module init
from render_lessons import load_lessons
from review_state import list_candidates

proposals = contradictions.detect_contradictions(
list_candidates(candidates_dir, status="staged"),
load_lessons(semantic_dir),
claim_state=claim_state,
cycle_id=cycle_id or datetime.datetime.now(datetime.timezone.utc).isoformat(),
)
n = write_supersession_candidates(proposals, candidates_dir)
if n:
try:
write_review_queue_summary(candidates_dir, review_queue)
except Exception:
pass
return n


def _count_contradiction_proposals(candidates_dir, semantic_dir, extra=()):
"""dry_run counterpart: how many proposals WOULD be staged. No writes."""
import contradictions # local import — avoids cycles at module init
from render_lessons import load_lessons
from review_state import list_candidates

pool = list_candidates(candidates_dir, status="staged") + list(extra)
return len(contradictions.detect_contradictions(
pool, load_lessons(semantic_dir)))


def _refresh_pending_summary(brain_root=None):
"""Best-effort regeneration of <brain>/PENDING_REVIEW.md after the
dream cycle changes the candidate set. Called at the end of both
Expand Down Expand Up @@ -828,6 +879,7 @@ def run_dream_cycle():
claims_asserted = 0
llm_calls = 0
llm_errors = {}
cresult = None
try:
import consolidate # local import — avoids cycles at module init
import topic_keys
Expand Down Expand Up @@ -866,6 +918,19 @@ def run_dream_cycle():
except Exception as exc: # pragma: no cover — best-effort
consolidate_summary = f" consolidate_error={exc!r}"

# Contradiction detection: STAGES supersession proposals on the review
# queue — never mutates lessons.jsonl (only human-gated graduate.py
# applies a supersession). After consolidation so slot conflicts can
# read this cycle's materialized claim state.
supersessions_staged = 0
try:
supersessions_staged = _stage_contradiction_proposals(
CANDIDATES, SEMANTIC, REVIEW_QUEUE,
claim_state=cresult.final_state if cresult is not None else None,
)
except Exception as exc: # pragma: no cover — best-effort
consolidate_summary += f" contradictions_error={exc!r}"

lint_summary = _lint_step(_resolve_brain_root(None))

summary = (
Expand All @@ -875,6 +940,7 @@ def run_dream_cycle():
f"burst_skipped={len(burst_telemetry)} "
f"activity_log_skipped={len(activity_log_telemetry)} "
f"activity_log_swept={len(swept)}"
f" supersessions_staged={supersessions_staged}"
f"{consolidate_summary}"
f"{lint_summary}"
)
Expand Down Expand Up @@ -958,6 +1024,12 @@ def run(brain_root=None, namespace="default", dry_run=False):
result["candidates_written"] = len(promotable)
result["burst_skipped"] = len(burst_telemetry)
result["activity_log_skipped"] = len(activity_log_telemetry)
# Report what detection WOULD stage; dry_run writes nothing.
try:
result["supersession_proposals"] = _count_contradiction_proposals(
candidates_dir, semantic_dir, extra=promotable.values())
except Exception as exc:
result["contradictions_error"] = str(exc)
return result

staged = write_candidates(promotable, candidates_dir)
Expand Down Expand Up @@ -988,6 +1060,7 @@ def run(brain_root=None, namespace="default", dry_run=False):
# Consolidate observation-shaped episodic events into the claim
# store. Best-effort: an extraction error here must NOT break the
# nightly dream cycle.
cresult = None
try:
import consolidate # local import — avoids cycles at module init
import topic_keys
Expand All @@ -1007,6 +1080,18 @@ def run(brain_root=None, namespace="default", dry_run=False):
except Exception as exc: # pragma: no cover — best-effort
result["consolidate_error"] = str(exc)

# Contradiction detection: STAGES supersession proposals on the review
# queue — never mutates lessons.jsonl (only human-gated graduate.py
# applies a supersession). After consolidation so slot conflicts can
# read this cycle's materialized claim state.
try:
result["supersession_proposals"] = _stage_contradiction_proposals(
candidates_dir, semantic_dir, review_queue,
claim_state=cresult.final_state if cresult is not None else None,
)
except Exception as exc: # pragma: no cover — best-effort
result["contradictions_error"] = str(exc)

result["lint_summary"] = _lint_step(_resolve_brain_root(brain_root))

# Same shape as the `dream cycle:` line run_dream_cycle() prints, so
Expand Down
Loading
Loading