This commit is contained in:
Lars committed 2026-08-28 08:40:28 +02:00
1 parent f17b3083e8
commit 4f37991ad1
48 files changed
+4919 -540

No files matched your search

+269 -70
View File
@@ -7,15 +7,25 @@ from context_builder import assemble_text, build_internal_context
from dialogue_store import StoreError, list_conversations_for_day, list_messages
from engine import EngineError, execute_prompt, load_active_prompt, preview_prompt
from journal_policy import require_explicit_generate, source_conversation_ids
from identity_store import is_maskable_label, list_mappings
from identity_store import is_maskable_label, list_mappings, mapping_spellings
from journal_body import clean_title
from journal_editorial import (
choose_editorial_mode,
editorial_instructions,
format_style_examples,
incomplete_syntax_markers,
lexical_similarity,
narration_sources_text,
select_journal_style_examples,
style_example_diagnostics,
writing_profile_trace,
)
from journal_generation_policy import (
assert_journal_prompt_contract,
assert_template_resolved,
compile_selection,
draft_snapshot,
mark_guidelines_used,
policy_trace,
resolve_run_selection,
)
from journal_reconstruct import (
assign_source_ids,
@@ -42,6 +52,9 @@ from providers import generate_provider
from retrieval import retrieve
from writing_profile_store import remember_dialogue_style
JOURNAL_NOT_ACCEPTED = "journal_generation_not_accepted"
JOURNAL_NOT_ACCEPTED_MESSAGE = "Generierung nicht übernommen."
IDENTITY_PLACEHOLDER = re.compile(
r"\[\[\s*(?:SELF|PERSON:[^\]]+|PLACE:[^\]]+|ORG:[^\]]+|PROJECT:[^\]]+|…|\.{2,})\s*\]\]",
@@ -70,7 +83,7 @@ def _split_title(content: str) -> tuple[str, str]:
def _local_narration(reconstruction: dict) -> tuple[str, str]:
"""Fail-closed draft from verified local sources. No leaking model text."""
"""Local source preview only. Never stored as a generated journal draft."""
parts = [str(part).strip() for part in claim_texts(reconstruction) if str(part).strip()]
body = "\n\n".join(parts)
return "Ein Tag", body
@@ -85,6 +98,8 @@ def unattested_journal_content(
"""Journal-only: historical names not in the sources are unattested facts, not a privacy leak.
Title and body are checked together. Placeholders must stay consistent across both.
Attestation is token-based: any attested spelling of a token (canonical or alias)
allows every known spelling of that same token after local demasking.
"""
body = text or ""
allowed = {canonical_token(token).upper().replace(" ", "") for token in (active_tokens or [])}
@@ -96,30 +111,118 @@ def unattested_journal_content(
if token in GENERIC_PLACEHOLDER_INNER or token not in allowed:
return "unattested_placeholder"
sources = "\n".join(source_user or [])
spellings_by_token: dict[str, list[str]] = {}
for item in mappings or []:
label = (item.get("local_label") or "").strip()
token = (item.get("token") or "").strip()
if not label or not token or not is_maskable_label(label):
token = canonical_token(item.get("token") or "").upper().replace(" ", "")
if not token:
continue
if identity_occurrence_count(sources, label, token) > 0:
bucket = spellings_by_token.setdefault(token, [])
seen = {label.casefold() for label in bucket}
for label in mapping_spellings(item):
if not label or label.casefold() in seen:
continue
seen.add(label.casefold())
bucket.append(label)
attested: set[str] = set()
for token, labels in spellings_by_token.items():
for label in labels:
if identity_occurrence_count(sources, label, token) > 0:
attested.add(token)
break
for token, labels in spellings_by_token.items():
if token in attested:
continue
for match in identity_label_pattern(label).finditer(body):
if is_identity_mention(body, match.start(), match.end(), token):
return "unattested_identity"
for label in labels:
if not is_maskable_label(label):
continue
for match in identity_label_pattern(label).finditer(body):
if is_identity_mention(body, match.start(), match.end(), token):
return "unattested_identity"
return None
def _identity_leak_result(purpose: str, exc: EngineError) -> dict:
diag = getattr(exc, "diagnostics", None) or {}
def _reject_generation(
*,
reason: str,
diagnostics: dict | None = None,
source_preview: str = "",
extra: dict | None = None,
) -> None:
diag = dict(diagnostics or {})
trace = dict(diag.get("trace") or {})
extra = dict(extra or {})
trace.update(
{
"purpose": "journal_generate",
"prompt_slug": extra.get("prompt_slug") or trace.get("prompt_slug") or "mvp.journal_generate",
"model_text_accepted": False,
"narration_source": "not_accepted",
"abort_reason": reason,
"source_preview": source_preview,
**extra,
}
)
diag["trace"] = trace
diag["log"] = extra.get("log") or diag.get("log") or trace.get("log") or []
diag["model_text_accepted"] = False
diag["abort_reason"] = reason
diag["provenance_decision"] = extra.get("provenance_decision") or diag.get("provenance_decision")
raise EngineError(
JOURNAL_NOT_ACCEPTED,
JOURNAL_NOT_ACCEPTED_MESSAGE,
409,
diagnostics=diag,
)
def _compose_journal_trace(
reconstruct_result: dict,
narrate_result: dict,
*,
run_log: list[dict],
narrate_prompt: dict,
profile_meta: dict,
style_meta: dict,
dropped: list[str],
extra: dict | None = None,
) -> dict:
reconstruct_trace = _stage_trace(reconstruct_result, "local_source_artifact")
reconstruct_trace.setdefault("purpose", "local_source_artifact")
reconstruct_trace.setdefault("status", "local_ok")
reconstruct_trace.setdefault("stage1", "local_ok")
narrate_trace = _stage_trace(narrate_result, "journal_generate")
narrate_trace.setdefault("prompt_slug", narrate_prompt.get("slug") or "mvp.journal_generate")
narrate_trace["prompt_revision"] = (
narrate_trace.get("prompt_revision")
or narrate_prompt.get("seed_revision")
or ""
)
narrate_trace["writing_profile"] = profile_meta
narrate_trace["style_examples"] = {**style_meta, "dropped": "style_examples" in dropped}
narrate_trace["dropped_optional_blocks"] = dropped
diag = narrate_result.get("diagnostics") or {}
if diag.get("generate_ms") is not None:
narrate_trace["generate_ms"] = diag.get("generate_ms")
if diag.get("prompt_revision"):
narrate_trace["prompt_revision"] = diag.get("prompt_revision")
if diag.get("generate_calls") is not None:
narrate_trace.setdefault("generate_calls", diag.get("generate_calls"))
if diag.get("model"):
narrate_trace.setdefault("model", diag.get("model"))
if diag.get("provider"):
narrate_trace.setdefault("provider", diag.get("provider"))
if diag.get("completion_tokens") is not None:
narrate_trace.setdefault("completion_tokens", diag.get("completion_tokens"))
if extra:
narrate_trace.update(extra)
return {
"content": "",
"trace": {
"purpose": purpose,
"guard": "identity_leak_blocked",
"log": list(diag.get("log") or []),
"response_validation_retry": diag.get("response_validation_retry"),
},
"diagnostics": diag,
**narrate_trace,
"prompt_revision": narrate_trace.get("prompt_revision"),
"writing_profile": profile_meta,
"style_examples": narrate_trace.get("style_examples"),
"dropped_optional_blocks": dropped,
"log": run_log,
"stages": [reconstruct_trace, narrate_trace],
}
@@ -251,6 +354,8 @@ def generate_draft(
conversation_ids: list[str] | None = None,
include_existing: bool = False,
explicit: bool = True,
generation_selection: dict | None = None,
remember_generation_selection: bool = False,
) -> dict:
require_explicit_generate(explicit)
day = get_day(profile_id, journal_day_id)
@@ -261,6 +366,13 @@ def generate_draft(
)
remember_dialogue_style(profile_id, exclude_conversation_ids=selected)
existing_text = _existing_text(profile_id, journal_day_id) if include_existing else ""
selection_ids, persist_meta = resolve_run_selection(
profile_id,
generation_selection,
remember_generation_selection,
)
narrate_prompt = load_active_prompt("mvp.journal_generate")
assert_journal_prompt_contract(narrate_prompt.get("template") or "")
config = generate_provider()
if not config:
@@ -294,12 +406,19 @@ def generate_draft(
for message in assign_source_ids(source_messages)
if message.get("role") == "user" and (message.get("body") or "").strip()
]
editorial_mode = choose_editorial_mode(source_user)
compiled_policy = compile_selection(selection_ids)
policy_meta = policy_trace(
compiled_policy,
source=persist_meta["source"],
remembered=persist_meta["remembered"],
)
profile_meta = writing_profile_trace(profile_id)
style_example_rows = select_journal_style_examples(
profile_id,
exclude_dates=[day.get("calendar_date") or ""],
)
style_examples = format_style_examples(style_example_rows)
style_meta = style_example_diagnostics(style_example_rows)
run_log: list[dict] = []
_event(
run_log,
@@ -309,14 +428,19 @@ def generate_draft(
coverage=reconstruction.get("coverage") or "all_selected_sources",
status="local_ok",
source_count=len(source_user),
editorial_mode=editorial_mode,
writing_profile_present=profile_meta.get("present"),
style_example_count=style_meta.get("count"),
generation_selection_source=policy_meta.get("source"),
generation_selection_keys=",".join(
f"{slot}:{policy_meta.get('keys', {}).get(slot)}"
for slot in ("transformation", "detail", "voice", "narrative")
),
)
reconstruct_result = {
"trace": _local_stage_trace(reconstruction, source_count=len(source_user)),
"content": reconstruction_text(reconstruction),
}
narrate_prompt = load_active_prompt("mvp.journal_generate")
narrate_context = build_internal_context(
profile_id,
space_id=day["space_id"],
@@ -328,8 +452,10 @@ def generate_draft(
conversation_id=selected[0] if selected else None,
reconstruction=narration_sources_text(reconstruction),
style_examples=style_examples,
editorial_mode=editorial_mode,
editorial_instructions=editorial_instructions(editorial_mode),
transformation_instructions=compiled_policy.instructions["transformation_instructions"],
detail_instructions=compiled_policy.instructions["detail_instructions"],
voice_instructions=compiled_policy.instructions["voice_instructions"],
narrative_instructions=compiled_policy.instructions["narrative_instructions"],
)
assembled = assemble_text(narrate_context)
try:
@@ -345,10 +471,13 @@ def generate_draft(
_raise_budget(exc)
if dropped:
_event(run_log, "journal_generate", "budget_pack", dropped=",".join(dropped))
shape_source = "model"
mappings = list_mappings(profile_id)
preview_title, preview_body = _local_narration(reconstruction)
source_preview = f"{preview_title}\n\n{preview_body}".strip()
narrate_result: dict = {}
try:
rendered_preview = preview_prompt(narrate_prompt, assembled)
assert_template_resolved(rendered_preview.get("rendered") or "")
narrate_result = execute_prompt(
narrate_prompt,
profile_id,
@@ -372,44 +501,94 @@ def generate_draft(
combined = f"{title}\n\n{body}".strip()
unattested = unattested_journal_content(combined, source_user, mappings, active_tokens)
if unattested:
title, body = _local_narration(reconstruction)
shape_source = "fallback"
narrate_result = {
**narrate_result,
"content": f"{title}\n\n{body}".strip(),
"trace": {
**(narrate_result.get("trace") or {}),
"guard": "unattested_content_blocked",
"reason": unattested,
},
}
_event(
run_log,
"journal_generate",
"narration_result",
status="local_fallback",
status="not_accepted",
reason=unattested,
)
else:
_event(
run_log,
"journal_generate",
"narration_result",
status="model",
editorial_mode=editorial_mode,
lexical_similarity=lexical_similarity("\n".join(source_user), body),
bundle = _compose_journal_trace(
reconstruct_result,
narrate_result,
run_log=run_log,
narrate_prompt=narrate_prompt,
profile_meta=profile_meta,
style_meta=style_meta,
dropped=dropped,
extra={
"narration_source": "not_accepted",
"model_text_accepted": False,
"provenance_decision": unattested,
"abort_reason": unattested,
"source_preview": source_preview,
"generation_selection": policy_meta,
},
)
_reject_generation(
reason=unattested,
diagnostics={
**(narrate_result.get("diagnostics") or {}),
"trace": bundle,
"log": run_log,
"provenance_decision": unattested,
},
source_preview=source_preview,
extra=bundle,
)
_event(
run_log,
"journal_generate",
"narration_result",
status="model",
lexical_similarity=lexical_similarity("\n".join(source_user), body),
incomplete_syntax=incomplete_syntax_markers(body),
writing_profile_present=profile_meta.get("present"),
)
except EngineError as exc:
if exc.code == JOURNAL_NOT_ACCEPTED:
raise
_stamp_log(run_log, "journal_generate", _log_items(exc))
if exc.code != "response_validation_failed":
diag = dict(exc.diagnostics or {})
diag["log"] = run_log
diag = dict(exc.diagnostics or {})
generate_called = bool(diag.get("generate_called") or diag.get("generate_calls"))
failed_result = {
"diagnostics": diag,
"trace": dict(diag.get("trace") or {}),
"content": "",
}
bundle = _compose_journal_trace(
reconstruct_result,
failed_result,
run_log=run_log,
narrate_prompt=narrate_prompt,
profile_meta=profile_meta,
style_meta=style_meta,
dropped=dropped,
extra={
"narration_source": "not_accepted",
"model_text_accepted": False,
"abort_reason": exc.code,
"source_preview": source_preview,
"generation_selection": policy_meta,
},
)
diag["log"] = run_log
diag["trace"] = bundle
if not generate_called:
raise EngineError(exc.code, exc.message, exc.status_code, diag) from exc
title, body = _local_narration(reconstruction)
shape_source = "fallback"
narrate_result = _identity_leak_result("journal_generate", exc)
narrate_result["content"] = f"{title}\n\n{body}".strip()
_event(run_log, "journal_generate", "narration_result", status="local_fallback", reason="identity_leak_blocked")
_event(
run_log,
"journal_generate",
"narration_result",
status="not_accepted",
reason=exc.code,
)
_reject_generation(
reason=exc.code,
diagnostics=diag,
source_preview=source_preview,
extra=bundle,
)
person_labels = [
(item.get("local_label") or "").strip()
for item in mappings
@@ -421,9 +600,24 @@ def generate_draft(
body,
source_user,
person_labels=person_labels,
source=shape_source,
source="model",
)
before_entries = {item["id"]: item.get("current_version_id") for item in current_entries(profile_id, journal_day_id)}
model = (
((narrate_result.get("diagnostics") or {}).get("actual_model"))
or ((narrate_result.get("trace") or {}).get("model"))
or narrate_result.get("provider")
or ""
)
snapshot = draft_snapshot(compiled_policy, prompt=narrate_prompt, model=str(model or ""))
mark_guidelines_used(
[
compiled_policy.ids["transformation"],
compiled_policy.ids["detail"],
compiled_policy.ids["voice"],
compiled_policy.ids["narrative"],
]
)
draft = insert_draft(
profile_id,
journal_day_id,
@@ -431,25 +625,30 @@ def generate_draft(
body=body,
source_conversation_ids=selected,
source_message_ids=_message_ids(profile_id, selected),
generation_snapshot=snapshot,
)
after_entries = current_entries(profile_id, journal_day_id)
for item in after_entries:
previous = before_entries.get(item["id"])
if previous is not None and previous != item.get("current_version_id"):
raise StoreError("policy_violation", "Generate darf die Nutzerfassung nicht verändern", 500)
reconstruct_trace = _stage_trace(reconstruct_result, "local_source_artifact")
reconstruct_trace.setdefault("purpose", "local_source_artifact")
reconstruct_trace.setdefault("status", "local_ok")
reconstruct_trace.setdefault("stage1", "local_ok")
narrate_trace = _stage_trace(narrate_result, "journal_generate")
narrate_trace["editorial_mode"] = editorial_mode
if shape_source == "model":
narrate_trace["lexical_similarity"] = lexical_similarity("\n".join(source_user), body)
bundle = _compose_journal_trace(
reconstruct_result,
narrate_result,
run_log=run_log,
narrate_prompt=narrate_prompt,
profile_meta=profile_meta,
style_meta=style_meta,
dropped=dropped,
extra={
"narration_source": "model",
"model_text_accepted": True,
"provenance_decision": "accepted",
"lexical_similarity": lexical_similarity("\n".join(source_user), body),
"incomplete_syntax": incomplete_syntax_markers(body),
"generation_selection": policy_meta,
},
)
draft["run_log"] = run_log
draft["trace"] = {
**narrate_trace,
"editorial_mode": editorial_mode,
"log": run_log,
"stages": [reconstruct_trace, narrate_trace],
}
draft["trace"] = bundle
return draft