MVP 0,91
This commit is contained in:
1 parent
fd7102e3b3
commit
60f0d2830d
17 files changed
+1502
-257
No files matched your search
+513
-196
@@ -19,6 +19,7 @@ from journal_store import list_versions
|
||||
from writing_profile_infer import SIGNAL_KEYS, infer_features
|
||||
from writing_profile_schema import (
|
||||
ACTION_ALIASES,
|
||||
APPLY_ACTIONS,
|
||||
EXISTING_BEFORE_NEW,
|
||||
LEGACY_STYLE_KEYS,
|
||||
SEED_FACETS,
|
||||
@@ -26,7 +27,11 @@ from writing_profile_schema import (
|
||||
coerce_slug,
|
||||
facet_label,
|
||||
hint_for_context,
|
||||
is_external_only,
|
||||
is_meta_style_text,
|
||||
normalize_evidence_basis,
|
||||
normalize_facet_key,
|
||||
normalize_mode,
|
||||
seed_catalog,
|
||||
valid_slug,
|
||||
)
|
||||
@@ -47,9 +52,22 @@ from writing_profile_store import (
|
||||
snapshot_version,
|
||||
upsert_trait,
|
||||
)
|
||||
from profile_analysis import (
|
||||
KIND_PACKAGE,
|
||||
KIND_PACKAGES,
|
||||
KIND_RESULT,
|
||||
KIND_RESULT_LEGACY,
|
||||
KIND_RESULTS,
|
||||
FORMAT_VERSION as ANALYSIS_FORMAT,
|
||||
expected_result_schema,
|
||||
filter_style_evidence,
|
||||
package_note,
|
||||
render_paste_prompt as render_analysis_prompt,
|
||||
select_corpus_items,
|
||||
semantic_task,
|
||||
)
|
||||
|
||||
KIND_PACKAGE = "kansho.profile_review_package"
|
||||
KIND_RESULT = "kansho.profile_review_result"
|
||||
KIND_PACKAGE_LEGACY = "kansho.profile_review_package"
|
||||
FORMAT_VERSION = 1
|
||||
JSON_BLOCK = re.compile(r"\{.*\}", re.DOTALL)
|
||||
TRIGGERS = {
|
||||
@@ -438,9 +456,10 @@ def review_status(profile_id: str) -> dict:
|
||||
|
||||
|
||||
def _review_mode(profile_id: str, requested: str | None = None) -> str:
|
||||
if requested in {"initial_build", "incremental"}:
|
||||
requested = normalize_mode(requested) or requested
|
||||
if requested in {"initial_build", "review"}:
|
||||
return requested
|
||||
return "incremental" if has_confirmed_profile(profile_id) else "initial_build"
|
||||
return "review" if has_confirmed_profile(profile_id) else "initial_build"
|
||||
|
||||
|
||||
def _corpus_supports_core(corpus: list[dict]) -> bool:
|
||||
@@ -539,39 +558,34 @@ def build_package(
|
||||
raise StoreError("unsupported_target", "Nur Writing-Profile-Review ist gebündelt; Interaction bleibt explizit.")
|
||||
ensure_profile(profile_id)
|
||||
mode = _review_mode(profile_id, mode)
|
||||
if trigger == "explicit_review":
|
||||
enqueue_evidence(
|
||||
profile_id,
|
||||
trigger="explicit_review",
|
||||
excerpt=(
|
||||
"Expliziter Initial Profile Build aus dem historischen Korpus."
|
||||
if mode == "initial_build"
|
||||
else "Explizite Nutzer-Review des Writing Profile."
|
||||
),
|
||||
source_kind="initial_build" if mode == "initial_build" else "explicit",
|
||||
)
|
||||
if mode == "initial_build":
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"UPDATE writing_profiles SET lifecycle = 'initial_pending', updated = datetime('now') WHERE profile_id = ?",
|
||||
(profile_id,),
|
||||
)
|
||||
evidences = _pending_evidence(profile_id)
|
||||
corpus = list_corpus(profile_id, limit=INITIAL_BUILD_SOURCES if mode == "initial_build" else 12)
|
||||
if not evidences and not corpus:
|
||||
raise StoreError("no_evidence", "Keine Review-Evidenz und kein Korpus vorhanden.")
|
||||
evidences = filter_style_evidence(_pending_evidence(profile_id))
|
||||
raw_corpus = list_corpus(profile_id, limit=INITIAL_BUILD_SOURCES)
|
||||
corpus = select_corpus_items(raw_corpus, mode=mode)
|
||||
profile = get_profile(profile_id)
|
||||
facets = profile.get("facets") or []
|
||||
core = next((item for item in facets if item.get("facet_key") == CORE_KEY or item.get("layer") == "core"), None)
|
||||
others = [item for item in facets if item is not core]
|
||||
empty = not corpus and not evidences
|
||||
package = {
|
||||
"kind": KIND_PACKAGE,
|
||||
"format_version": FORMAT_VERSION,
|
||||
"target": "writing",
|
||||
"mode": mode,
|
||||
"instruction": INSTRUCTION_INITIAL if mode == "initial_build" else INSTRUCTION_INCREMENTAL,
|
||||
"instruction": semantic_task(mode),
|
||||
"existing_before_new": list(EXISTING_BEFORE_NEW),
|
||||
"seed_catalog": seed_catalog(),
|
||||
"note": package_note(mode),
|
||||
"kansho_evidence_empty": empty,
|
||||
"selection": {
|
||||
"budget_chars": int(__import__("os").environ.get("KANSHO_PROFILE_PACKAGE_CHARS") or "12000"),
|
||||
"role": "representative current, older baseline, distinct contexts — not a full dump",
|
||||
},
|
||||
"profile": {
|
||||
"version": profile.get("version") or 0,
|
||||
"governance": profile.get("governance") or "learning",
|
||||
@@ -582,40 +596,14 @@ def build_package(
|
||||
},
|
||||
"corpus": [_public_corpus(item) for item in corpus],
|
||||
"evidences": [_public_evidence(item) for item in evidences],
|
||||
"expected_result": {
|
||||
"kind": KIND_RESULT,
|
||||
"format_version": FORMAT_VERSION,
|
||||
"target": "writing",
|
||||
"mode": mode,
|
||||
"changes": [
|
||||
{
|
||||
"layer": "core|facet|trait",
|
||||
"key": "core|autobiographical_journal|dynamischer-slug",
|
||||
"slug": "datengetriebener Trait-Slug",
|
||||
"facet_key": "core|autobiographical_journal|…",
|
||||
"action": "confirm|precisify|rescope|merge|split|create",
|
||||
"proposed_value": "Aussage des Traits oder der Facet",
|
||||
"label": "optional",
|
||||
"rationale": "kurz",
|
||||
"evidence_ids": ["id"],
|
||||
"exemplars": [{"excerpt": "Originalzitat", "occurred_at": "YYYY-MM-DD"}],
|
||||
"merge_slugs": ["optional"],
|
||||
"split_into": [{"slug": "neu", "statement": "…", "facet_key": "…"}],
|
||||
}
|
||||
],
|
||||
},
|
||||
"expected_result": expected_result_schema(mode),
|
||||
"compiled_brief_excluded": True,
|
||||
}
|
||||
return package
|
||||
|
||||
|
||||
def render_paste_prompt(package: dict) -> str:
|
||||
body = json.dumps(package, ensure_ascii=False, indent=2)
|
||||
return (
|
||||
"Kanshō Writing Profile Review. "
|
||||
"Antworte ausschließlich mit einem JSON-Objekt gemäß expected_result. "
|
||||
"Kein Fließtext davor oder danach.\n\n"
|
||||
f"{body}\n"
|
||||
)
|
||||
return render_analysis_prompt(package)
|
||||
|
||||
|
||||
def parse_result(raw) -> dict:
|
||||
@@ -634,8 +622,11 @@ def parse_result(raw) -> dict:
|
||||
raise StoreError("invalid_review_result", "Review-Ergebnis ist kein gültiges JSON.") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise StoreError("invalid_review_result", "Review-Ergebnis muss ein Objekt sein.")
|
||||
if (data.get("kind") or "") != KIND_RESULT:
|
||||
raise StoreError("invalid_review_result", "kind muss kansho.profile_review_result sein.")
|
||||
if data.get("compiled_brief") and not data.get("changes") and not data.get("profile"):
|
||||
raise StoreError("invalid_review_result", "Der aktuelle Brief ist kein Profile-Importformat.")
|
||||
kind = (data.get("kind") or "").strip()
|
||||
if kind not in KIND_RESULTS:
|
||||
raise StoreError("invalid_review_result", "kind muss kansho.profile_analysis_result sein.")
|
||||
version = data.get("format_version", FORMAT_VERSION)
|
||||
try:
|
||||
version = int(version)
|
||||
@@ -643,98 +634,205 @@ def parse_result(raw) -> dict:
|
||||
raise StoreError("unsupported_format", "format_version ungültig.") from exc
|
||||
if version != FORMAT_VERSION:
|
||||
raise StoreError("unsupported_format", f"format_version {version} wird nicht unterstützt.")
|
||||
changes = data.get("changes")
|
||||
if not isinstance(changes, list):
|
||||
mode = normalize_mode(data.get("mode")) or (data.get("mode") or "")
|
||||
raw_changes = data.get("changes")
|
||||
if raw_changes is None:
|
||||
raw_changes = []
|
||||
if not isinstance(raw_changes, list):
|
||||
raise StoreError("invalid_review_result", "changes muss eine Liste sein.")
|
||||
raw_changes = list(raw_changes) + _changes_from_proposal(_proposal_from_result(data))
|
||||
cleaned = []
|
||||
for item in changes:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
layer = (item.get("layer") or "trait").strip()
|
||||
if layer not in LAYERS:
|
||||
continue
|
||||
action = ACTION_ALIASES.get((item.get("action") or "confirm").strip(), (item.get("action") or "confirm").strip())
|
||||
if action not in TRAIT_ACTIONS:
|
||||
continue
|
||||
key = (item.get("key") or item.get("slug") or "").strip()
|
||||
slug = coerce_slug(item.get("slug") or key or item.get("label") or "trait")
|
||||
if layer == "core":
|
||||
key = CORE_KEY
|
||||
slug = CORE_KEY
|
||||
elif layer == "facet":
|
||||
key = normalize_facet_key(key) or JOURNAL_FACET
|
||||
slug_hint = item.get("slug") or ""
|
||||
as_trait = bool(slug_hint) or action == "create" or key in LEGACY_STYLE_KEYS or (
|
||||
valid_slug(key) and key not in SEED_FACETS and key != CORE_KEY
|
||||
)
|
||||
if as_trait:
|
||||
layer = "trait"
|
||||
slug = coerce_slug(slug_hint or key)
|
||||
else:
|
||||
slug = coerce_slug(key)
|
||||
elif not valid_slug(slug):
|
||||
continue
|
||||
facet_key = normalize_facet_key(item.get("facet_key") or (key if layer == "facet" else "") or CORE_KEY) or CORE_KEY
|
||||
if layer == "core":
|
||||
facet_key = CORE_KEY
|
||||
exemplars = []
|
||||
for ex in item.get("exemplars") or []:
|
||||
if isinstance(ex, str) and ex.strip():
|
||||
exemplars.append({"excerpt": ex.strip(), "role": "exemplar"})
|
||||
elif isinstance(ex, dict) and (ex.get("excerpt") or "").strip():
|
||||
exemplars.append(
|
||||
{
|
||||
"excerpt": (ex.get("excerpt") or "").strip(),
|
||||
"role": ex.get("role") or "exemplar",
|
||||
"source_id": ex.get("source_id"),
|
||||
"occurred_at": ex.get("occurred_at"),
|
||||
}
|
||||
)
|
||||
split_into = []
|
||||
for part in item.get("split_into") or []:
|
||||
if not isinstance(part, dict):
|
||||
continue
|
||||
part_slug = coerce_slug(part.get("slug") or part.get("label") or "")
|
||||
if not part_slug:
|
||||
continue
|
||||
split_into.append(
|
||||
{
|
||||
"slug": part_slug,
|
||||
"label": part.get("label") or part_slug,
|
||||
"statement": part.get("statement") or part.get("proposed_value") or "",
|
||||
"facet_key": normalize_facet_key(part.get("facet_key") or facet_key) or facet_key,
|
||||
}
|
||||
)
|
||||
cleaned.append(
|
||||
{
|
||||
"layer": layer,
|
||||
"key": key,
|
||||
"slug": slug,
|
||||
"facet_key": facet_key,
|
||||
"action": action,
|
||||
"proposed_value": item.get("proposed_value") or item.get("statement") or "",
|
||||
"label": item.get("label") or "",
|
||||
"rationale": item.get("rationale") or "",
|
||||
"evidence_ids": [str(eid) for eid in (item.get("evidence_ids") or []) if eid],
|
||||
"exemplars": exemplars,
|
||||
"merge_slugs": [
|
||||
coerce_slug(value)
|
||||
for value in (item.get("merge_slugs") or item.get("merge_ids") or [])
|
||||
if value
|
||||
],
|
||||
"split_into": split_into,
|
||||
"trait_id": item.get("trait_id") or "",
|
||||
}
|
||||
)
|
||||
for item in raw_changes:
|
||||
parsed_change = _parse_change(item)
|
||||
if parsed_change:
|
||||
cleaned.append(parsed_change)
|
||||
basis = normalize_evidence_basis(data.get("evidence_basis"))
|
||||
if not basis:
|
||||
for change in cleaned:
|
||||
basis.extend(item for item in change.get("evidence_basis") or [] if item not in basis)
|
||||
return {
|
||||
"kind": KIND_RESULT,
|
||||
"format_version": FORMAT_VERSION,
|
||||
"target": "writing",
|
||||
"mode": data.get("mode") or "",
|
||||
"mode": mode,
|
||||
"evidence_basis": basis,
|
||||
"uncertainties": [
|
||||
str(item) for item in (data.get("uncertainties") or []) if item
|
||||
],
|
||||
"changes": cleaned,
|
||||
}
|
||||
|
||||
|
||||
def _proposal_from_result(data: dict) -> dict:
|
||||
nested = data.get("profile") if isinstance(data.get("profile"), dict) else {}
|
||||
profile = dict(nested)
|
||||
for key in ("core", "facets", "traits"):
|
||||
if not profile.get(key) and data.get(key):
|
||||
profile[key] = data[key]
|
||||
return profile
|
||||
|
||||
|
||||
def _parse_basis(raw) -> list[str]:
|
||||
return normalize_evidence_basis(raw)
|
||||
|
||||
|
||||
def _changes_from_proposal(profile: dict) -> list[dict]:
|
||||
if not isinstance(profile, dict) or not profile:
|
||||
return []
|
||||
changes = []
|
||||
core = profile.get("core")
|
||||
if isinstance(core, dict):
|
||||
value = core.get("value") or core.get("statement") or core.get("summary") or ""
|
||||
if value:
|
||||
changes.append(
|
||||
{
|
||||
"layer": "core",
|
||||
"key": CORE_KEY,
|
||||
"action": "update",
|
||||
"proposed_value": value,
|
||||
"rationale": core.get("rationale") or core.get("generalizability") or "Profile Proposal Core",
|
||||
"evidence_basis": core.get("evidence_basis") or [],
|
||||
"exemplars": core.get("exemplars") or [],
|
||||
}
|
||||
)
|
||||
for item in profile.get("facets") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
value = item.get("value") or item.get("statement") or item.get("summary") or ""
|
||||
if not value:
|
||||
continue
|
||||
changes.append(
|
||||
{
|
||||
"layer": "facet",
|
||||
"key": item.get("key") or item.get("facet_key") or JOURNAL_FACET,
|
||||
"action": "update",
|
||||
"proposed_value": value,
|
||||
"rationale": item.get("rationale") or "Profile Proposal Facet",
|
||||
"evidence_basis": item.get("evidence_basis") or [],
|
||||
}
|
||||
)
|
||||
for item in profile.get("traits") or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
scope = (item.get("scope") or "").strip()
|
||||
facet_key = item.get("facet_key") or (CORE_KEY if scope == "core" else "") or JOURNAL_FACET
|
||||
changes.append(
|
||||
{
|
||||
"layer": "trait",
|
||||
"slug": item.get("slug") or item.get("key"),
|
||||
"facet_key": facet_key,
|
||||
"action": item.get("action") or "add",
|
||||
"label": item.get("label") or "",
|
||||
"proposed_value": item.get("statement") or item.get("proposed_value") or item.get("summary") or "",
|
||||
"rationale": item.get("rationale") or "Profile Proposal Trait",
|
||||
"evidence_basis": item.get("evidence_basis") or [],
|
||||
"exemplars": item.get("exemplars") or [],
|
||||
"evidence_ids": item.get("evidence_ids") or [],
|
||||
}
|
||||
)
|
||||
return changes
|
||||
|
||||
|
||||
def _parse_change(item: dict | None) -> dict | None:
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
layer = (item.get("layer") or "trait").strip()
|
||||
if layer not in LAYERS:
|
||||
return None
|
||||
action = ACTION_ALIASES.get((item.get("action") or "keep").strip(), (item.get("action") or "keep").strip())
|
||||
if action not in TRAIT_ACTIONS:
|
||||
return None
|
||||
action = ACTION_ALIASES.get(action, action)
|
||||
key = (item.get("key") or item.get("slug") or "").strip()
|
||||
slug = coerce_slug(item.get("slug") or key or item.get("label") or "trait")
|
||||
if layer == "core":
|
||||
key = CORE_KEY
|
||||
slug = CORE_KEY
|
||||
elif layer == "facet":
|
||||
key = normalize_facet_key(key) or JOURNAL_FACET
|
||||
slug_hint = item.get("slug") or ""
|
||||
as_trait = bool(slug_hint) or action == "add" or key in LEGACY_STYLE_KEYS or (
|
||||
valid_slug(key) and key not in SEED_FACETS and key != CORE_KEY
|
||||
)
|
||||
if as_trait:
|
||||
layer = "trait"
|
||||
slug = coerce_slug(slug_hint or key)
|
||||
else:
|
||||
slug = coerce_slug(key)
|
||||
elif not valid_slug(slug):
|
||||
return None
|
||||
facet_key = normalize_facet_key(item.get("facet_key") or (key if layer == "facet" else "") or CORE_KEY) or CORE_KEY
|
||||
if layer == "core":
|
||||
facet_key = CORE_KEY
|
||||
exemplars = []
|
||||
for ex in item.get("exemplars") or []:
|
||||
parsed_ex = _parse_exemplar(ex)
|
||||
if parsed_ex:
|
||||
exemplars.append(parsed_ex)
|
||||
split_into = []
|
||||
for part in item.get("split_into") or []:
|
||||
if not isinstance(part, dict):
|
||||
continue
|
||||
part_slug = coerce_slug(part.get("slug") or part.get("label") or "")
|
||||
if not part_slug:
|
||||
continue
|
||||
split_into.append(
|
||||
{
|
||||
"slug": part_slug,
|
||||
"label": part.get("label") or part_slug,
|
||||
"statement": part.get("statement") or part.get("proposed_value") or "",
|
||||
"facet_key": normalize_facet_key(part.get("facet_key") or facet_key) or facet_key,
|
||||
}
|
||||
)
|
||||
basis = _parse_basis(item.get("evidence_basis"))
|
||||
if not basis and (item.get("evidence_ids") or any(ex.get("source_id") for ex in exemplars)):
|
||||
basis = ["kansho_sources"]
|
||||
if is_external_only(basis):
|
||||
for ex in exemplars:
|
||||
ex.pop("source_id", None)
|
||||
return {
|
||||
"layer": layer,
|
||||
"key": key,
|
||||
"slug": slug,
|
||||
"facet_key": facet_key,
|
||||
"action": action,
|
||||
"proposed_value": item.get("proposed_value") or item.get("statement") or "",
|
||||
"label": item.get("label") or "",
|
||||
"rationale": item.get("rationale") or "",
|
||||
"evidence_ids": [str(eid) for eid in (item.get("evidence_ids") or []) if eid],
|
||||
"evidence_basis": basis,
|
||||
"exemplars": exemplars,
|
||||
"merge_slugs": [
|
||||
coerce_slug(value)
|
||||
for value in (item.get("merge_slugs") or item.get("merge_ids") or [])
|
||||
if value
|
||||
],
|
||||
"split_into": split_into,
|
||||
"trait_id": item.get("trait_id") or "",
|
||||
}
|
||||
|
||||
|
||||
def _parse_exemplar(ex) -> dict | None:
|
||||
if isinstance(ex, str) and ex.strip() and not is_meta_style_text(ex):
|
||||
return {"excerpt": ex.strip(), "role": "exemplar", "evidence_basis": []}
|
||||
if not isinstance(ex, dict):
|
||||
return None
|
||||
excerpt = (ex.get("excerpt") or "").strip()
|
||||
if not excerpt or is_meta_style_text(excerpt):
|
||||
return None
|
||||
basis = _parse_basis(ex.get("evidence_basis"))
|
||||
source_id = ex.get("source_id")
|
||||
if is_external_only(basis):
|
||||
source_id = None
|
||||
return {
|
||||
"excerpt": excerpt,
|
||||
"role": ex.get("role") or "exemplar",
|
||||
"source_id": source_id,
|
||||
"occurred_at": ex.get("occurred_at"),
|
||||
"evidence_basis": basis or (["kansho_sources"] if source_id else []),
|
||||
}
|
||||
|
||||
|
||||
def _store_review(profile_id: str, package: dict, channel: str) -> dict:
|
||||
review_id = str(uuid.uuid4())
|
||||
with get_db() as conn:
|
||||
@@ -805,19 +903,10 @@ def run_api_review(profile_id: str, review_id: str | None = None, *, mode: str |
|
||||
parsed = parse_result(result.get("content") or "")
|
||||
if not parsed.get("mode"):
|
||||
parsed["mode"] = package.get("mode") or ""
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE writing_profile_reviews
|
||||
SET result_json = ?, status = 'proposed'
|
||||
WHERE id = ? AND profile_id = ?
|
||||
""",
|
||||
(json.dumps(parsed, ensure_ascii=False), review_id, profile_id),
|
||||
)
|
||||
applied = apply_result(profile_id, parsed, review_id=review_id, package=package)
|
||||
applied["trace"] = result.get("trace")
|
||||
applied["review_id"] = review_id
|
||||
return applied
|
||||
staged = _stage_proposal(profile_id, parsed, review_id=review_id, package=package)
|
||||
staged["trace"] = result.get("trace")
|
||||
staged["review_id"] = review_id
|
||||
return staged
|
||||
|
||||
|
||||
def import_result(profile_id: str, raw, review_id: str | None = None) -> dict:
|
||||
@@ -855,7 +944,55 @@ def import_result(profile_id: str, raw, review_id: str | None = None) -> dict:
|
||||
)
|
||||
package = _parse_json((row or {}).get("package_json"), {})
|
||||
if not parsed.get("mode"):
|
||||
parsed["mode"] = package.get("mode") or ""
|
||||
parsed["mode"] = package.get("mode") or normalize_mode(parsed.get("mode")) or _review_mode(profile_id)
|
||||
if not parsed.get("changes"):
|
||||
raise StoreError(
|
||||
"empty_review_result",
|
||||
"Keine übernehmbaren Änderungen gefunden. Für initial_build werden core, facets und traits oder eine changes-Liste benötigt.",
|
||||
)
|
||||
return _stage_proposal(profile_id, parsed, review_id=review_id, package=package)
|
||||
|
||||
|
||||
def _known_ids(package: dict) -> set[str]:
|
||||
ids = set()
|
||||
for item in (package.get("evidences") or []) + (package.get("corpus") or []):
|
||||
if item.get("id"):
|
||||
ids.add(str(item["id"]))
|
||||
if item.get("source_id"):
|
||||
ids.add(str(item["source_id"]))
|
||||
return ids
|
||||
|
||||
|
||||
def _unknown_refs(parsed: dict, package: dict) -> list[str]:
|
||||
known = _known_ids(package)
|
||||
unknown = []
|
||||
for change in parsed.get("changes") or []:
|
||||
if is_external_only(change.get("evidence_basis")):
|
||||
continue
|
||||
for eid in change.get("evidence_ids") or []:
|
||||
if str(eid) not in known:
|
||||
unknown.append(str(eid))
|
||||
for ex in change.get("exemplars") or []:
|
||||
source_id = ex.get("source_id")
|
||||
if source_id and str(source_id) not in known:
|
||||
unknown.append(str(source_id))
|
||||
return sorted(set(unknown))
|
||||
|
||||
|
||||
def _stage_proposal(profile_id: str, parsed: dict, *, review_id: str, package: dict) -> dict:
|
||||
unknown = _unknown_refs(parsed, package)
|
||||
current = get_profile(profile_id)
|
||||
for index, change in enumerate(parsed.get("changes") or []):
|
||||
payload = {**change, "index": index, "unknown_refs": [item for item in unknown if item in (change.get("evidence_ids") or [])]}
|
||||
_queue_suggestion(
|
||||
profile_id,
|
||||
change.get("facet_key") or change.get("key") or "",
|
||||
change.get("proposed_value") or "",
|
||||
change.get("rationale") or "",
|
||||
trait_slug=change.get("slug") or "",
|
||||
action=change.get("action") or "update",
|
||||
payload=payload,
|
||||
)
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -865,37 +1002,184 @@ def import_result(profile_id: str, raw, review_id: str | None = None) -> dict:
|
||||
""",
|
||||
(json.dumps(parsed, ensure_ascii=False), review_id, profile_id),
|
||||
)
|
||||
return apply_result(profile_id, parsed, review_id=review_id, package=package)
|
||||
profile = get_profile(profile_id)
|
||||
suggested = len(parsed.get("changes") or [])
|
||||
status = review_status(profile_id)
|
||||
return {
|
||||
**status,
|
||||
"applied": 0,
|
||||
"suggested": suggested,
|
||||
"skipped": 0,
|
||||
"accepted": False,
|
||||
"review_id": review_id,
|
||||
"mode": parsed.get("mode") or package.get("mode"),
|
||||
"unknown_refs": unknown,
|
||||
"proposal": parsed,
|
||||
"result": parsed,
|
||||
"profile": profile,
|
||||
"note": f"{suggested} Vorschläge geprüft. Nichts wurde am Current Profile geändert.",
|
||||
"current_version": current.get("version") or 0,
|
||||
}
|
||||
|
||||
|
||||
def accept_proposal(
|
||||
profile_id: str,
|
||||
review_id: str | None = None,
|
||||
*,
|
||||
indexes: list[int] | None = None,
|
||||
baseline: bool = False,
|
||||
) -> dict:
|
||||
with get_db() as conn:
|
||||
if review_id:
|
||||
row = row_to_dict(
|
||||
conn.execute(
|
||||
"SELECT * FROM writing_profile_reviews WHERE id = ? AND profile_id = ?",
|
||||
(review_id, profile_id),
|
||||
).fetchone()
|
||||
)
|
||||
else:
|
||||
row = row_to_dict(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT * FROM writing_profile_reviews
|
||||
WHERE profile_id = ? AND status = 'proposed'
|
||||
ORDER BY created DESC LIMIT 1
|
||||
""",
|
||||
(profile_id,),
|
||||
).fetchone()
|
||||
)
|
||||
if not row:
|
||||
raise StoreError("not_found", "Kein offenes Profile-Proposal.", 404)
|
||||
parsed = parse_result(_parse_json(row.get("result_json"), {}))
|
||||
package = _parse_json(row.get("package_json"), {})
|
||||
changes = parsed.get("changes") or []
|
||||
remaining = []
|
||||
if indexes is not None:
|
||||
chosen = set(indexes)
|
||||
selected = [changes[i] for i in indexes if 0 <= i < len(changes)]
|
||||
remaining = [item for i, item in enumerate(changes) if i not in chosen]
|
||||
parsed = {**parsed, "changes": selected}
|
||||
return apply_result(
|
||||
profile_id,
|
||||
parsed,
|
||||
review_id=row["id"],
|
||||
package=package,
|
||||
baseline=baseline or ((parsed.get("mode") or package.get("mode")) == "initial_build" and indexes is None),
|
||||
user_accepted=True,
|
||||
remaining=remaining,
|
||||
)
|
||||
|
||||
|
||||
def reject_proposal(profile_id: str, review_id: str | None = None, *, indexes: list[int] | None = None) -> dict:
|
||||
with get_db() as conn:
|
||||
if review_id:
|
||||
row = row_to_dict(
|
||||
conn.execute(
|
||||
"SELECT * FROM writing_profile_reviews WHERE id = ? AND profile_id = ?",
|
||||
(review_id, profile_id),
|
||||
).fetchone()
|
||||
)
|
||||
else:
|
||||
row = row_to_dict(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT * FROM writing_profile_reviews
|
||||
WHERE profile_id = ? AND status IN ('open', 'proposed')
|
||||
ORDER BY created DESC LIMIT 1
|
||||
""",
|
||||
(profile_id,),
|
||||
).fetchone()
|
||||
)
|
||||
if not row:
|
||||
raise StoreError("not_found", "Kein offenes Profile-Proposal.", 404)
|
||||
parsed = parse_result(_parse_json(row.get("result_json"), {})) if row.get("result_json") else {}
|
||||
changes = parsed.get("changes") or []
|
||||
remaining = []
|
||||
if indexes is not None:
|
||||
chosen = set(indexes)
|
||||
remaining = [item for i, item in enumerate(changes) if i not in chosen]
|
||||
if remaining:
|
||||
kept = {**parsed, "changes": remaining}
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE writing_profile_reviews
|
||||
SET result_json = ?, status = 'proposed'
|
||||
WHERE id = ? AND profile_id = ?
|
||||
""",
|
||||
(json.dumps(kept, ensure_ascii=False), row["id"], profile_id),
|
||||
)
|
||||
dropped = {item.get("slug") or item.get("key") for i, item in enumerate(changes) if i in set(indexes)}
|
||||
for slug in dropped:
|
||||
if not slug:
|
||||
continue
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE writing_profile_suggestions
|
||||
SET status = 'rejected', resolved = datetime('now')
|
||||
WHERE profile_id = ? AND status = 'pending' AND (trait_slug = ? OR facet_key = ?)
|
||||
""",
|
||||
(profile_id, slug, slug),
|
||||
)
|
||||
return {
|
||||
"accepted": False,
|
||||
"applied": 0,
|
||||
"review_id": row["id"],
|
||||
"proposal": kept,
|
||||
"result": kept,
|
||||
**review_status(profile_id),
|
||||
"profile": get_profile(profile_id),
|
||||
}
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE writing_profile_reviews
|
||||
SET status = 'dismissed', resolved = datetime('now')
|
||||
WHERE id = ? AND profile_id = ?
|
||||
""",
|
||||
(row["id"], profile_id),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE writing_profile_suggestions
|
||||
SET status = 'rejected', resolved = datetime('now')
|
||||
WHERE profile_id = ? AND status = 'pending'
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
return {"accepted": False, "applied": 0, **review_status(profile_id), "profile": get_profile(profile_id)}
|
||||
|
||||
|
||||
def _refs_from_change(change: dict, evidences: list[dict], corpus: list[dict]) -> list[dict]:
|
||||
refs = []
|
||||
basis = change.get("evidence_basis") or []
|
||||
external_only = is_external_only(basis)
|
||||
by_id = {item.get("id"): item for item in evidences if item.get("id")}
|
||||
by_source = {item.get("id"): item for item in corpus if item.get("id")}
|
||||
for eid in change.get("evidence_ids") or []:
|
||||
item = by_id.get(eid) or by_source.get(eid)
|
||||
if not item:
|
||||
continue
|
||||
excerpt = plain_text(item.get("excerpt") or item.get("body") or "")
|
||||
if not excerpt:
|
||||
continue
|
||||
refs.append(
|
||||
{
|
||||
"role": "evidence",
|
||||
"excerpt": excerpt,
|
||||
"source_id": item.get("source_id") or item.get("id"),
|
||||
"occurred_at": item.get("occurred_at"),
|
||||
}
|
||||
)
|
||||
if not external_only:
|
||||
for eid in change.get("evidence_ids") or []:
|
||||
item = by_id.get(eid) or by_source.get(eid)
|
||||
if not item:
|
||||
continue
|
||||
excerpt = plain_text(item.get("excerpt") or item.get("body") or "")
|
||||
if not excerpt or is_meta_style_text(excerpt):
|
||||
continue
|
||||
refs.append(
|
||||
{
|
||||
"role": "evidence",
|
||||
"excerpt": excerpt,
|
||||
"source_id": item.get("source_id") or item.get("id"),
|
||||
"occurred_at": item.get("occurred_at"),
|
||||
}
|
||||
)
|
||||
for item in change.get("exemplars") or []:
|
||||
excerpt = plain_text(item.get("excerpt") or "")
|
||||
if not excerpt:
|
||||
if not excerpt or is_meta_style_text(excerpt):
|
||||
continue
|
||||
source_id = None if external_only else item.get("source_id")
|
||||
refs.append(
|
||||
{
|
||||
"role": item.get("role") or "exemplar",
|
||||
"excerpt": excerpt,
|
||||
"source_id": item.get("source_id"),
|
||||
"source_id": source_id,
|
||||
"occurred_at": item.get("occurred_at"),
|
||||
}
|
||||
)
|
||||
@@ -912,7 +1196,7 @@ def _apply_change(
|
||||
evidences: list[dict],
|
||||
corpus: list[dict],
|
||||
) -> str:
|
||||
action = change.get("action") or "confirm"
|
||||
action = APPLY_ACTIONS.get(change.get("action") or "keep", change.get("action") or "confirm")
|
||||
layer = change.get("layer") or "trait"
|
||||
value = (change.get("proposed_value") or "").strip()
|
||||
rationale = (change.get("rationale") or "AI Review").strip()
|
||||
@@ -942,6 +1226,9 @@ def _apply_change(
|
||||
|
||||
slug = coerce_slug(change.get("slug") or change.get("key") or "trait")
|
||||
facet_key = normalize_facet_key(change.get("facet_key") or JOURNAL_FACET) or JOURNAL_FACET
|
||||
if action == "remove":
|
||||
retire_trait(profile_id, slug, "retired")
|
||||
return "applied"
|
||||
if action == "create" and not value:
|
||||
return "skipped"
|
||||
if action == "rescope":
|
||||
@@ -1015,45 +1302,38 @@ def apply_result(
|
||||
result: dict,
|
||||
review_id: str | None = None,
|
||||
package: dict | None = None,
|
||||
*,
|
||||
baseline: bool = False,
|
||||
user_accepted: bool = False,
|
||||
remaining: list[dict] | None = None,
|
||||
) -> dict:
|
||||
if not user_accepted:
|
||||
raise StoreError("proposal_not_accepted", "Profile Proposal wird erst nach Nutzerbestätigung übernommen.")
|
||||
parsed = parse_result(result)
|
||||
row = ensure_profile(profile_id)
|
||||
governance = row.get("governance") or "learning"
|
||||
if governance not in GOVERNANCE:
|
||||
governance = "learning"
|
||||
mode = parsed.get("mode") or (package or {}).get("mode") or _review_mode(profile_id)
|
||||
if has_confirmed_profile(profile_id):
|
||||
mode = "incremental"
|
||||
origin = "initial_build" if mode == "initial_build" else "accepted_suggestion"
|
||||
mode = normalize_mode(parsed.get("mode") or (package or {}).get("mode")) or _review_mode(profile_id)
|
||||
origin = "initial_build" if mode == "initial_build" or baseline else "accepted_suggestion"
|
||||
corpus = list_corpus(profile_id, limit=INITIAL_BUILD_SOURCES)
|
||||
evidences = list((package or {}).get("evidences") or []) + _pending_evidence(profile_id, limit=40)
|
||||
allow_core = _corpus_supports_core(corpus)
|
||||
leftover = list(remaining or [])
|
||||
close_review = not leftover
|
||||
snapshot_version(profile_id, cause="before_review")
|
||||
applied = 0
|
||||
suggested = 0
|
||||
skipped = 0
|
||||
for change in parsed.get("changes") or []:
|
||||
if governance == "frozen":
|
||||
if (row.get("governance") or "") == "frozen" and not baseline:
|
||||
skipped += 1
|
||||
continue
|
||||
if governance == "advising" and mode != "initial_build":
|
||||
_queue_suggestion(
|
||||
profile_id,
|
||||
change.get("facet_key") or change.get("key") or "",
|
||||
change.get("proposed_value") or "",
|
||||
change.get("rationale") or "",
|
||||
trait_slug=change.get("slug") or "",
|
||||
action=change.get("action") or "update",
|
||||
payload=change,
|
||||
)
|
||||
suggested += 1
|
||||
continue
|
||||
outcome = _apply_change(
|
||||
profile_id,
|
||||
change,
|
||||
origin=origin,
|
||||
force=mode == "initial_build",
|
||||
allow_core=allow_core,
|
||||
force=True,
|
||||
allow_core=allow_core or baseline,
|
||||
evidences=evidences,
|
||||
corpus=corpus,
|
||||
)
|
||||
@@ -1062,9 +1342,9 @@ def apply_result(
|
||||
else:
|
||||
skipped += 1
|
||||
_assemble_brief(profile_id)
|
||||
if applied or suggested:
|
||||
if applied:
|
||||
snapshot_version(profile_id, cause="accepted_review")
|
||||
if mode == "initial_build" and applied:
|
||||
if close_review and (mode == "initial_build" or baseline) and applied:
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -1080,23 +1360,35 @@ def apply_result(
|
||||
for change in parsed.get("changes") or []
|
||||
for eid in change.get("evidence_ids") or []
|
||||
]
|
||||
applied_slugs = [change.get("slug") or change.get("key") for change in parsed.get("changes") or []]
|
||||
leftover_doc = {**parsed, "changes": leftover} if leftover else None
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"UPDATE writing_profiles SET last_reviewed = datetime('now'), review_ready = 0 WHERE profile_id = ?",
|
||||
(profile_id,),
|
||||
)
|
||||
if close_review:
|
||||
conn.execute(
|
||||
"UPDATE writing_profiles SET last_reviewed = datetime('now'), review_ready = 0 WHERE profile_id = ?",
|
||||
(profile_id,),
|
||||
)
|
||||
if evidence_ids:
|
||||
placeholders = ",".join("?" * len(evidence_ids))
|
||||
conn.execute(
|
||||
f"UPDATE writing_profile_evidence SET status = 'consumed' WHERE profile_id = ? AND id IN ({placeholders})",
|
||||
(profile_id, *evidence_ids),
|
||||
)
|
||||
else:
|
||||
elif close_review:
|
||||
conn.execute(
|
||||
"UPDATE writing_profile_evidence SET status = 'consumed' WHERE profile_id = ? AND status IN ('bundled', 'pending')",
|
||||
(profile_id,),
|
||||
)
|
||||
if review_id:
|
||||
if review_id and leftover_doc:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE writing_profile_reviews
|
||||
SET result_json = ?, status = 'proposed'
|
||||
WHERE id = ? AND profile_id = ?
|
||||
""",
|
||||
(json.dumps(leftover_doc, ensure_ascii=False), review_id, profile_id),
|
||||
)
|
||||
elif review_id:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE writing_profile_reviews
|
||||
@@ -1105,15 +1397,40 @@ def apply_result(
|
||||
""",
|
||||
(review_id, profile_id),
|
||||
)
|
||||
if close_review:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE writing_profile_suggestions
|
||||
SET status = 'accepted', resolved = datetime('now')
|
||||
WHERE profile_id = ? AND status = 'pending'
|
||||
""",
|
||||
(profile_id,),
|
||||
)
|
||||
else:
|
||||
for slug in applied_slugs:
|
||||
if not slug:
|
||||
continue
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE writing_profile_suggestions
|
||||
SET status = 'accepted', resolved = datetime('now')
|
||||
WHERE profile_id = ? AND status = 'pending' AND (trait_slug = ? OR facet_key = ?)
|
||||
""",
|
||||
(profile_id, slug, slug),
|
||||
)
|
||||
_refresh_ready(profile_id)
|
||||
profile = get_profile(profile_id)
|
||||
return {
|
||||
"governance": governance,
|
||||
"mode": mode,
|
||||
"applied": applied,
|
||||
"suggested": suggested,
|
||||
"suggested": len(leftover),
|
||||
"skipped": skipped,
|
||||
"result": parsed,
|
||||
"accepted": True,
|
||||
"baseline": baseline,
|
||||
"review_id": review_id,
|
||||
"proposal": leftover_doc,
|
||||
"result": leftover_doc or parsed,
|
||||
"profile": profile,
|
||||
**review_status(profile_id),
|
||||
}
|
||||
Reference in new issue
Block a user