Keep journal openings from treating finished days as open plans.

A 400-character entry prefix plus plan regex could reopen a completed yesterday as if it were still pending. Openings now take plans only from yesterday's user dialogue, never from saved entries, and skip space recency in the first call.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-09-07 08:25:00 +02:00
1 parent e42f751fdc
commit ec0f8bad55
8 files changed
+108 -19

No files matched your search

+2 -1
View File
@@ -70,6 +70,7 @@ def build_internal_context(
space_id: str | None = None,
journal_day_id: str | None = None,
purpose: str = "dialogue_turn",
include_space_recency: bool = True,
include_existing: bool = False,
conversation_ids: list[str] | None = None,
existing_text: str = "",
@@ -118,7 +119,7 @@ def build_internal_context(
day_messages = read("conversation_messages", profile_id=profile_id, context={"conversation_id": conversation_id})
items.append({"type": "day_messages", "messages": day_messages})
if purpose == "dialogue_turn" and space_id:
if purpose == "dialogue_turn" and space_id and include_space_recency:
prior = retrieve(
profile_id,
{
+39 -9
View File
@@ -1,12 +1,15 @@
"""Journal-specific first impulse. Not a generic continuation or intent engine.
Uses the existing Privacy Gateway, dialogue prompt, guards and request-scoped
trace. Attested plans and open day points come only from user-role sources.
Assistant text is conversation context, never a user fact. Recency is not a pattern.
trace. Attested plans come only from yesterday's user-role dialogue. Open day
points stay on the same journal day. Saved journal entries are completed
narrative, never an opening plan. Assistant text is conversation context, never
a user fact. Recency is not a pattern.
"""
from __future__ import annotations
import re
from datetime import date, timedelta
from context_builder import assemble_text, build_internal_context
from debug_store import persist_engine_error, persist_step
@@ -20,11 +23,14 @@ from retrieval import retrieve
NEUTRAL_OPENING = "Wenn du magst, fang einfach an – ich höre zu."
OPENING_POLICY = (
"Dies ist der erste Impuls dieses Gesprächs. Es gibt hier noch keine Nutzerzeile. "
"Nur belegte Vorhaben aus user-Quellen oder offene user-Punkte desselben Journal Day aufgreifen. "
"Nur belegte Vorhaben aus dem user-Dialog des unmittelbar vorigen Kalendertags "
"oder offene user-Punkte desselben Journal Day aufgreifen. "
"Ein gespeicherter Journal-Eintrag ist abgeschlossene Erzählung, kein offenes Vorhaben. "
"Ein Recency-Treffer ist kein bewiesenes wiederkehrendes Muster. "
"Nicht erwähnt ist nicht geschehen. Ein Plan ist kein Vollzug. "
"Assistententext ist Gesprächskontext, kein Nutzerfakt. "
"Keine Behauptung, ein Vorhaben sei ausgeführt worden."
"Keine Behauptung, ein Vorhaben sei ausgeführt worden. "
"Keine bereits erzählte, abgeschlossene Episode eines früheren Tags als offenen Faden führen."
)
FUTURE_INTENT = re.compile(
@@ -46,6 +52,22 @@ UNEARNED_PATTERN = re.compile(
)
def parse_calendar_date(value: str | None) -> date | None:
raw = (value or "").strip()
if not raw:
return None
try:
return date.fromisoformat(raw)
except ValueError:
return None
def is_previous_calendar_day(source: date | None, current: date | None) -> bool:
if source is None or current is None:
return False
return source == current - timedelta(days=1)
def is_attested_plan(text: str) -> bool:
"""User wording that marks a plan or intention. Not past completion, not overlap."""
body = (text or "").strip()
@@ -88,7 +110,8 @@ def collect_opening_context(profile_id: str, conversation_id: str) -> dict:
journal_day_id = conversation.get("journal_day_id")
if not space_id or not journal_day_id:
raise StoreError("not_journal_conversation", "Erster Impuls nur für einen Journal-Dialog.")
get_day(profile_id, journal_day_id)
day = get_day(profile_id, journal_day_id)
current_date = parse_calendar_date(day.get("calendar_date"))
day_conversations = list_conversations_for_day(profile_id, journal_day_id)
open_points: list[str] = []
@@ -114,6 +137,7 @@ def collect_opening_context(profile_id: str, conversation_id: str) -> dict:
},
)
recency_user: list[str] = []
yesterday_user: list[str] = []
for entry in prior_entries:
excerpt = (entry.get("excerpt") or "").strip()
if excerpt:
@@ -122,15 +146,19 @@ def collect_opening_context(profile_id: str, conversation_id: str) -> dict:
excerpt = (source.get("excerpt") or "").strip()
if excerpt:
recency_user.append(excerpt)
if excerpt and is_previous_calendar_day(
parse_calendar_date(source.get("calendar_date")),
current_date,
):
yesterday_user.append(excerpt)
user_pool = [*open_points, *recency_user]
plans = attested_plans_from_user_texts(user_pool)
plans = attested_plans_from_user_texts(yesterday_user)
has_relevant = bool(plans or open_points)
return {
"space_id": space_id,
"journal_day_id": journal_day_id,
"conversation_id": conversation_id,
"user_texts": user_pool,
"user_texts": [*open_points, *yesterday_user],
"assistant_texts": day_assistant,
"attested_plans": plans,
"open_day_points": open_points,
@@ -230,13 +258,15 @@ def start_journal_opening(profile_id: str, conversation_id: str) -> dict:
journal_day_id=conversation.get("journal_day_id"),
purpose="dialogue_turn",
conversation_ids=day_ids,
include_space_recency=False,
)
assembled = assemble_text(context)
assembled = dict(assembled)
assembled["opening_hint"] = format_opening_hint(facts)
assembled["register_hint"] = (
"Erster Impuls. Noch keine Nutzerzeile in diesem Gespräch. "
"Nur belegte Vorhaben oder offene user-Punkte. Kein Muster aus Recency."
"Nur Vorhaben aus dem user-Dialog von gestern oder offene user-Punkte dieses Tags. "
"Kein Muster aus Recency. Keine abgeschlossene frühere Episode wieder öffnen."
)
prompt = load_active_prompt("mvp.dialogue_turn")
calls = 0
+3 -1
View File
@@ -190,8 +190,9 @@ def _space_recent_sources(profile_id: str, spec: dict[str, Any]) -> list[dict]:
with get_db() as conn:
conversations = conn.execute(
f"""
SELECT c.id, c.updated, c.journal_day_id
SELECT c.id, c.updated, c.journal_day_id, d.calendar_date
FROM conversations c
LEFT JOIN journal_days d ON d.id = c.journal_day_id AND d.profile_id = c.profile_id
WHERE c.profile_id = ? AND c.space_id = ? {extra}
ORDER BY c.updated DESC, c.created DESC
LIMIT ?
@@ -217,6 +218,7 @@ def _space_recent_sources(profile_id: str, spec: dict[str, Any]) -> list[dict]:
{
"conversation_id": conv["id"],
"journal_day_id": conv["journal_day_id"],
"calendar_date": conv["calendar_date"],
"excerpt": excerpt,
}
)
+49
View File
@@ -6,6 +6,8 @@ import sys
import tempfile
from pathlib import Path
from datetime import date
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
@@ -23,6 +25,8 @@ from journal_opening import (
attested_plans_from_user_texts,
collect_opening_context,
is_attested_plan,
is_previous_calendar_day,
parse_calendar_date,
)
from journal_reconstruct import assign_source_ids
from retrieval import pair_user_priority_messages
@@ -58,6 +62,9 @@ def main() -> None:
expect(not is_attested_plan("Heute war der Hafen ruhig. Kirschen am Stand."), "past report is not a plan")
expect(not is_attested_plan("Wir standen vor dem Hafen und aßen Kirschen."), "vor without haben is not a plan")
expect(not is_attested_plan("Hafen Kirschen Wind"), "word overlap is not a plan")
expect(parse_calendar_date("2026-08-29") == date(2026, 8, 29), "calendar date parses")
expect(is_previous_calendar_day(date(2026, 8, 29), date(2026, 8, 30)), "yesterday is previous")
expect(not is_previous_calendar_day(date(2026, 8, 29), date(2026, 9, 3)), "older than yesterday is not previous")
plans = attested_plans_from_user_texts(
["Heute war der Hafen ruhig.", "Morgen wollen wir nach Cres fahren.", "Hafen Kirschen"]
)
@@ -157,6 +164,48 @@ def main() -> None:
expect(overlap_open.json().get("opening", {}).get("kind") == "local_neutral", "overlap falls back to neutral")
expect("Muster" not in (overlap_open.json().get("opening") or {}).get("assistant", {}).get("body", ""), "neutral impulse does not claim a pattern")
done_space, done_day = open_space_day(client, headers, "Abgeschlossen", "2026-08-20")
done_conv = start_conv(client, headers, done_day["day"]["id"])
client.post(
f"/api/journal/conversations/{done_conv.json()['id']}/turn",
headers=headers,
json={"body": "Nachmittag am Strand, abends Eis, dann schlafen."},
)
client.post(
"/api/journal/entries",
headers=headers,
json={
"journal_day_id": done_day["day"]["id"],
"title": "Hitze",
"body": (
"Schon um 6 Uhr schlug mir eine drückende Luft entgegen. "
"Ich hatte überlegt, die Roller auf den nächsten Tag zu schieben. "
"Wir haben sie dann doch geholt und sind den Tag gefahren."
),
"origin": "user_edit",
},
)
later_done = client.post(
f"/api/journal/spaces/{done_space['id']}/days",
headers=headers,
json={"calendar_date": "2026-08-21"},
)
done_open = start_conv(client, headers, later_done.json()["day"]["id"])
done_facts = collect_opening_context(setup.json()["profile_id"], done_open.json()["id"])
expect(not done_facts["attested_plans"], "completed journal entry is not an opening plan")
expect(not done_facts["has_relevant_context"], "a closed earlier day does not keep the next opening relevant")
expect(done_open.json().get("opening", {}).get("kind") == "local_neutral", "completed story falls back to neutral")
stale = client.post(
f"/api/journal/spaces/{plan_space['id']}/days",
headers=headers,
json={"calendar_date": "2026-08-04"},
)
stale_open = start_conv(client, headers, stale.json()["day"]["id"])
stale_facts = collect_opening_context(setup.json()["profile_id"], stale_open.json()["id"])
expect(not any("Cres" in item for item in stale_facts["attested_plans"]), "plan from two days ago is no longer an opening mandate")
expect(stale_open.json().get("opening", {}).get("kind") == "local_neutral", "stale plan uses local neutral")
asst_space, asst_day = open_space_day(client, headers, "Assistent", "2026-08-05")
asst_conv = start_conv(client, headers, asst_day["day"]["id"])
from dialogue_store import append_message