Compare commits
27
Commits
be11f82f84
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89d149684e | ||
|
|
0277039b07 | ||
|
|
011cc9dd81 | ||
|
|
a65ea98b0c | ||
|
|
f7ffd28332 | ||
|
|
3f7c0d71a5 | ||
|
|
cc43fc6409 | ||
|
|
fa1c11c33e | ||
|
|
59921fc5b5 | ||
|
|
bef422a429 | ||
|
|
af6fe55577 | ||
|
|
dd7858347c | ||
|
|
79e4fd0d4b | ||
|
|
3c0213ae74 | ||
|
|
9d79e3e92f | ||
|
|
6ea36f7d1f | ||
|
|
36b9a2e424 | ||
|
|
709370da93 | ||
|
|
0ef3e3bb7a | ||
|
|
ea38528ecf | ||
|
|
9d5befdde9 | ||
|
|
07479f6a9f | ||
|
|
32acdc220b | ||
|
|
326a9a44c8 | ||
|
|
29e3d0ff74 | ||
|
|
ec0f8bad55 | ||
|
|
e42f751fdc |
No files matched your search
@@ -0,0 +1,16 @@
|
||||
.git
|
||||
.gitea
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
**/*.pyc
|
||||
backend/data
|
||||
backend/.env
|
||||
frontend/node_modules
|
||||
frontend/dist
|
||||
local-backups
|
||||
transfer
|
||||
tmp
|
||||
temp
|
||||
docs
|
||||
*.md
|
||||
!frontend/README.md
|
||||
@@ -0,0 +1,37 @@
|
||||
# Compose secrets on the Pi. Copy to /home/lars/docker/kansho/.env and
|
||||
# /home/lars/docker/kansho-dev/.env. Never commit the filled file.
|
||||
# Local Windows development keeps using backend/.env (SQLite, ports 5188/8018).
|
||||
|
||||
# ─── DEV (docker-compose.dev-env.yml) ────────────────────────────────────────
|
||||
# DB_NAME=kansho_dev
|
||||
# DB_USER=kansho_dev
|
||||
# DB_PASSWORD=dev_password_change_me
|
||||
# APP_URL=https://dev.kansho.jinkendo.de
|
||||
# ALLOWED_ORIGINS=https://dev.kansho.jinkendo.de,http://192.168.2.49:3096
|
||||
# KANSHO_ENV=development
|
||||
# KANSHO_ALLOW_REMOTE_DETECT=
|
||||
# KANSHO_FRONTEND_PORT=3096
|
||||
# KANSHO_BACKEND_PORT=8096
|
||||
# KANSHO_PROVIDER_KEY=
|
||||
# KANSHO_DETECT_PROVIDER_KEY=
|
||||
|
||||
# ─── PROD (docker-compose.yml) ───────────────────────────────────────────────
|
||||
DB_NAME=kansho
|
||||
DB_USER=kansho
|
||||
DB_PASSWORD=CHANGE_ME_SECURE_PASSWORD
|
||||
APP_URL=https://kansho.jinkendo.de
|
||||
ALLOWED_ORIGINS=https://kansho.jinkendo.de
|
||||
KANSHO_ENV=production
|
||||
# Transitional until local detect (Ollama). Empty = blocked in production.
|
||||
KANSHO_ALLOW_REMOTE_DETECT=
|
||||
KANSHO_FRONTEND_PORT=3006
|
||||
KANSHO_BACKEND_PORT=8005
|
||||
KANSHO_PROVIDER_KEY=
|
||||
KANSHO_DETECT_PROVIDER_KEY=
|
||||
|
||||
# Betriebsmail. Leer = kein Versand (production/test: Fehler, development: Link nur im Server-Log).
|
||||
# SMTP_HOST=
|
||||
# SMTP_PORT=587
|
||||
# SMTP_USER=
|
||||
# SMTP_PASSWORD=
|
||||
# SMTP_FROM=kansho@example.test
|
||||
@@ -0,0 +1,40 @@
|
||||
name: Deploy Development
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [develop]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Deploy Kanshō to development
|
||||
run: |
|
||||
set -e
|
||||
echo "=== Deploying Kanshō to DEVELOPMENT ==="
|
||||
REPO="http://192.168.2.144:3000/Lars/Kansho.git"
|
||||
TARGET="/home/lars/docker/kansho-dev"
|
||||
mkdir -p "$TARGET"
|
||||
cd "$TARGET"
|
||||
if [ ! -d .git ]; then
|
||||
git clone -b develop "$REPO" .
|
||||
else
|
||||
git fetch origin develop
|
||||
git checkout develop
|
||||
git reset --hard origin/develop
|
||||
fi
|
||||
docker compose -f docker-compose.dev-env.yml build --no-cache backend frontend
|
||||
if ! docker compose -f docker-compose.dev-env.yml up -d --wait; then
|
||||
echo "compose up --wait failed — backend logs:"
|
||||
docker compose -f docker-compose.dev-env.yml logs backend --tail 150 || true
|
||||
docker compose -f docker-compose.dev-env.yml ps || true
|
||||
exit 1
|
||||
fi
|
||||
if ! curl -sf http://localhost:8096/api/health; then
|
||||
echo "DEV API not reachable — backend logs:"
|
||||
docker compose -f docker-compose.dev-env.yml logs backend --tail 150 || true
|
||||
exit 1
|
||||
fi
|
||||
echo "DEV API /api/health OK"
|
||||
curl -sf http://localhost:3096/api/health && echo "DEV frontend proxy /api/health OK"
|
||||
echo "=== Kanshō DEV deploy complete ==="
|
||||
@@ -0,0 +1,40 @@
|
||||
name: Deploy Production
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Deploy Kanshō to production
|
||||
run: |
|
||||
set -e
|
||||
echo "=== Deploying Kanshō to PRODUCTION ==="
|
||||
REPO="http://192.168.2.144:3000/Lars/Kansho.git"
|
||||
TARGET="/home/lars/docker/kansho"
|
||||
mkdir -p "$TARGET"
|
||||
cd "$TARGET"
|
||||
if [ ! -d .git ]; then
|
||||
git clone -b main "$REPO" .
|
||||
else
|
||||
git fetch origin main
|
||||
git checkout main
|
||||
git reset --hard origin/main
|
||||
fi
|
||||
docker compose build --no-cache backend frontend
|
||||
if ! docker compose up -d --wait; then
|
||||
echo "compose up --wait failed — backend logs:"
|
||||
docker compose logs backend --tail 150 || true
|
||||
docker compose ps || true
|
||||
exit 1
|
||||
fi
|
||||
if ! curl -sf http://localhost:8005/api/health; then
|
||||
echo "PROD API not reachable — backend logs:"
|
||||
docker compose logs backend --tail 150 || true
|
||||
exit 1
|
||||
fi
|
||||
echo "PROD API /api/health OK"
|
||||
curl -sf http://localhost:3006/api/health && echo "PROD frontend proxy /api/health OK"
|
||||
echo "=== Kanshō PROD deploy complete ==="
|
||||
@@ -0,0 +1,90 @@
|
||||
name: Test Suite
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [develop]
|
||||
workflow_run:
|
||||
workflows: ["Deploy Development"]
|
||||
types: [completed]
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
pytest-backend:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: pytest against Dev Postgres (kansho_test)
|
||||
run: |
|
||||
set -e
|
||||
APP_DIR="/home/lars/docker/kansho-dev"
|
||||
COMPOSE_FILE="docker-compose.dev-env.yml"
|
||||
echo "pytest uses Dev Postgres (${APP_DIR}); event=${{ github.event_name }}"
|
||||
cd "$APP_DIR"
|
||||
for i in $(seq 1 60); do
|
||||
if [ -f "$APP_DIR/backend/pytest.ini" ] && docker compose -f "$COMPOSE_FILE" exec -T backend true 2>/dev/null; then
|
||||
echo "backend and pytest.ini ready (attempt $i)"
|
||||
break
|
||||
fi
|
||||
if [ "$i" -eq 60 ]; then
|
||||
echo "timeout waiting for Dev checkout/backend"
|
||||
docker compose -f "$COMPOSE_FILE" ps || true
|
||||
ls -la "$APP_DIR/backend" || true
|
||||
exit 1
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
PGUSER="$(docker compose -f "$COMPOSE_FILE" exec -T postgres printenv POSTGRES_USER | tr -d '\r')"
|
||||
echo "test database kansho_test on the existing Dev Postgres (owner ${PGUSER})"
|
||||
docker compose -f "$COMPOSE_FILE" exec -T postgres \
|
||||
psql -U "$PGUSER" -d postgres -v ON_ERROR_STOP=1 \
|
||||
-c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'kansho_test' AND pid <> pg_backend_pid();"
|
||||
docker compose -f "$COMPOSE_FILE" exec -T postgres \
|
||||
psql -U "$PGUSER" -d postgres -v ON_ERROR_STOP=1 \
|
||||
-c "DROP DATABASE IF EXISTS kansho_test;"
|
||||
docker compose -f "$COMPOSE_FILE" exec -T postgres \
|
||||
psql -U "$PGUSER" -d postgres -v ON_ERROR_STOP=1 \
|
||||
-c "CREATE DATABASE kansho_test OWNER ${PGUSER};"
|
||||
docker compose -f "$COMPOSE_FILE" run --rm --no-deps \
|
||||
-v "${APP_DIR}:/src:ro" \
|
||||
-w /src/backend \
|
||||
-e KANSHO_DB_BACKEND=postgres \
|
||||
-e DB_NAME=kansho_test \
|
||||
-e KANSHO_PROVIDER_KEY= \
|
||||
-e KANSHO_DETECT_PROVIDER_KEY= \
|
||||
-e KANSHO_ALLOW_REMOTE_DETECT= \
|
||||
-e PYTHONUTF8=1 \
|
||||
backend sh -lc '
|
||||
set -e
|
||||
unset KANSHO_DB_PATH KANSHO_FAKE_PROVIDER KANSHO_FAKE_DETECT
|
||||
unset KANSHO_PROVIDER_KEY KANSHO_DETECT_PROVIDER_KEY KANSHO_ALLOW_REMOTE_DETECT
|
||||
export KANSHO_PROVIDER_KEY=
|
||||
export KANSHO_DETECT_PROVIDER_KEY=
|
||||
pip install -q -r requirements-dev.txt
|
||||
python -m pytest tests -m "not slow" -ra --tb=short
|
||||
'
|
||||
|
||||
smoke-dev:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Non-destructive smoke against the running Dev app
|
||||
run: |
|
||||
set -e
|
||||
echo "live Dev API (kansho_dev), read-only health"
|
||||
curl -sf http://localhost:8096/api/health
|
||||
echo
|
||||
curl -sf http://localhost:3096/api/health
|
||||
echo
|
||||
echo "LAN smoke OK. Public URL after TLS: https://dev.kansho.jinkendo.de"
|
||||
|
||||
frontend-build:
|
||||
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Frontend production build on Dev checkout
|
||||
run: |
|
||||
set -e
|
||||
APP_DIR="/home/lars/docker/kansho-dev"
|
||||
cd "$APP_DIR/frontend"
|
||||
npm ci
|
||||
npm run build
|
||||
+4
-1
@@ -38,7 +38,7 @@ Thumbs.db
|
||||
*.py[cod]
|
||||
.pytest_cache/
|
||||
|
||||
# Test / local data
|
||||
# Local data (never commit)
|
||||
tmp/
|
||||
temp/
|
||||
data/local/
|
||||
@@ -46,3 +46,6 @@ backend/data/
|
||||
local-backups/
|
||||
*.kansho-backup.zip
|
||||
*.db
|
||||
|
||||
# Personal journal zip was a one-time Gitea transport. Do not re-add.
|
||||
transfer/
|
||||
@@ -20,6 +20,8 @@ Fachliche Konzeption, technische Rahmenarchitektur und der erste **vertikale MVP
|
||||
|
||||
Remote: [gitea.stommer.de/Lars/Kansho](https://gitea.stommer.de/Lars/Kansho.git)
|
||||
|
||||
Die Urlaubs-Laptop-Instanz lief ohne Docker auf SQLite. Heimtransfer, Backup und späterer Server-/Postgres-Pfad: `docs/architecture/technical/environment_handover.md`.
|
||||
|
||||
## Dokumentation zuerst laden
|
||||
|
||||
Nicht alle Kapitel gleichzeitig in den Kontext ziehen. Der Index beschreibt sinnvolle Bundles:
|
||||
@@ -87,6 +89,12 @@ Lokales Backup der Urlaubs-Testdaten (persönlich, unverschlüsselt, ohne `.env`
|
||||
|
||||
Restore bestätigt ausdrücklich, legt vorher ein Sicherheitsbackup an und überschreibt nie still. Backend währenddessen beenden.
|
||||
|
||||
## Transfer auf die Heim-Umgebung
|
||||
|
||||
Persönliche Daten liegen **nicht** beim Provider. Der einmalige Laptop-Transport lief über das selbst gehostete Gitea. Nach dem Restore auf dem Heimrechner `transfer/` aus dem Arbeitsbaum entfernen (Historie behält das Zip).
|
||||
|
||||
Docker/Postgres, Gitea-Deploy und Cutover: `docs/DEPLOYMENT.md` und `docs/architecture/technical/runtime_and_deploy.md`.
|
||||
|
||||
## Lokal weiterarbeiten
|
||||
|
||||
```powershell
|
||||
|
||||
+22
-2
@@ -2,8 +2,10 @@
|
||||
# Env überschreibt die Admin-Werte, wenn gesetzt.
|
||||
|
||||
# development | test | production
|
||||
# production: kein externes Klartext-Detect (Muster oder lokale Detect-URL).
|
||||
# production: externes Klartext-Detect default-off. Ziel bleibt lokales Detect.
|
||||
# Übergang bis Ollama: KANSHO_ALLOW_REMOTE_DETECT=1 (Operator, kein Admin-Flag).
|
||||
# KANSHO_ENV=development
|
||||
# KANSHO_ALLOW_REMOTE_DETECT=
|
||||
|
||||
# Generate: nur maskierter Kontext. Extern: Key Pflicht.
|
||||
KANSHO_PROVIDER_KEY=
|
||||
@@ -12,7 +14,8 @@ KANSHO_PROVIDER_KEY=
|
||||
# KANSHO_PROVIDER_ZDR=1
|
||||
# KANSHO_PROVIDER_NO_TRAIN=1
|
||||
|
||||
# Detect: Klartext nur lokal oder in Development/Test. Leer = Generate-Key mitnutzen (nur Dev/Test).
|
||||
# Detect: lokal (Ollama LAN) oder in Development/Test remote. Production remote nur mit KANSHO_ALLOW_REMOTE_DETECT.
|
||||
# URL/Modell liegen in LLM-Profilen (Admin → Schnittstellen), nicht in der .env.
|
||||
KANSHO_DETECT_PROVIDER_KEY=
|
||||
# KANSHO_DETECT_PROVIDER_URL=https://openrouter.ai/api/v1/chat/completions
|
||||
# KANSHO_DETECT_PROVIDER_MODEL=openai/gpt-4.1-nano
|
||||
@@ -22,3 +25,20 @@ KANSHO_DETECT_PROVIDER_KEY=
|
||||
# Nur Tests
|
||||
# KANSHO_FAKE_PROVIDER=1
|
||||
# KANSHO_FAKE_DETECT=1
|
||||
|
||||
# Docker/Server only. Local Windows stays SQLite (default).
|
||||
# KANSHO_DB_BACKEND=postgres
|
||||
# DB_HOST=postgres
|
||||
# DB_NAME=kansho
|
||||
# DB_USER=kansho
|
||||
# DB_PASSWORD=
|
||||
|
||||
# Betriebsmail für Passwort-Reset und Adressbestätigung. Ohne SMTP schlägt der Versand fehl.
|
||||
# In development wird der Link nur ins Server-Log geschrieben.
|
||||
# SMTP_HOST=
|
||||
# SMTP_PORT=587
|
||||
# SMTP_USER=
|
||||
# SMTP_PASSWORD=
|
||||
# SMTP_FROM=kansho@example.test
|
||||
# APP_URL=http://localhost:5188
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends libpq5 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
ENV PIP_DEFAULT_TIMEOUT=120
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
RUN chmod +x /app/startup.sh \
|
||||
&& mkdir -p /app/data/media
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["/app/startup.sh"]
|
||||
@@ -0,0 +1,468 @@
|
||||
"""Login identifiers, address verification, and one-time reset links."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
from auth import hash_password
|
||||
from db import row_to_dict
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9._]{3,32}$")
|
||||
PUBLIC_COLUMNS = (
|
||||
"id",
|
||||
"email",
|
||||
"name",
|
||||
"role",
|
||||
"status",
|
||||
"tier_id",
|
||||
"created",
|
||||
"username",
|
||||
"secondary_email",
|
||||
"email_verified_at",
|
||||
"secondary_email_verified_at",
|
||||
"pending_email",
|
||||
"pending_secondary_email",
|
||||
)
|
||||
FORGOT_MESSAGE = (
|
||||
"Wenn ein Konto zu dieser Angabe existiert, wurde ein Link an die verifizierten Adressen gesendet."
|
||||
)
|
||||
RESET_MINUTES = 60
|
||||
VERIFY_HOURS = 24
|
||||
LINK_LIMIT = 3
|
||||
|
||||
|
||||
def utc_stamp(moment: datetime | None = None) -> str:
|
||||
current = moment or datetime.utcnow()
|
||||
return current.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
def app_base_url() -> str:
|
||||
return (os.environ.get("APP_URL") or "http://localhost:5188").rstrip("/")
|
||||
|
||||
|
||||
def profile_view(row: dict | None) -> dict | None:
|
||||
if not row:
|
||||
return None
|
||||
data = {key: row.get(key) for key in PUBLIC_COLUMNS}
|
||||
data["email_verified"] = bool(row.get("email_verified_at"))
|
||||
data["secondary_email_verified"] = bool(row.get("secondary_email_verified_at"))
|
||||
return data
|
||||
|
||||
|
||||
def normalize_email(value: str) -> str:
|
||||
email = (value or "").strip().lower()
|
||||
if "@" not in email or email.startswith("@") or email.endswith("@") or " " in email or email.count("@") != 1:
|
||||
raise HTTPException(400, "E-Mail-Adresse ist ungültig")
|
||||
local, domain = email.split("@", 1)
|
||||
if not local or "." not in domain:
|
||||
raise HTTPException(400, "E-Mail-Adresse ist ungültig")
|
||||
return email
|
||||
|
||||
|
||||
def normalize_username(value: str) -> str:
|
||||
username = (value or "").strip().lower()
|
||||
if not USERNAME_RE.match(username):
|
||||
raise HTTPException(400, "Benutzername: 3–32 Zeichen, Buchstaben, Ziffern, Punkt oder Unterstrich")
|
||||
return username
|
||||
|
||||
|
||||
def find_by_login(conn, identifier: str) -> dict | None:
|
||||
key = (identifier or "").strip().lower()
|
||||
if not key:
|
||||
return None
|
||||
return row_to_dict(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT * FROM profiles
|
||||
WHERE lower(email) = ? OR lower(COALESCE(username, '')) = ?
|
||||
""",
|
||||
(key, key),
|
||||
).fetchone()
|
||||
)
|
||||
|
||||
|
||||
def _owner_of_address(conn, email: str, exclude_id: str | None) -> dict | None:
|
||||
return row_to_dict(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT id FROM profiles
|
||||
WHERE (
|
||||
lower(email) = ?
|
||||
OR lower(COALESCE(secondary_email, '')) = ?
|
||||
OR lower(COALESCE(pending_email, '')) = ?
|
||||
OR lower(COALESCE(pending_secondary_email, '')) = ?
|
||||
)
|
||||
AND id != COALESCE(?, '')
|
||||
""",
|
||||
(email, email, email, email, exclude_id or ""),
|
||||
).fetchone()
|
||||
)
|
||||
|
||||
|
||||
def assert_address_free(conn, email: str, exclude_id: str | None) -> None:
|
||||
if _owner_of_address(conn, email, exclude_id):
|
||||
raise HTTPException(409, "E-Mail ist bereits vergeben")
|
||||
|
||||
|
||||
def assert_username_free(conn, username: str, exclude_id: str | None) -> None:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT id FROM profiles
|
||||
WHERE lower(COALESCE(username, '')) = ? AND id != COALESCE(?, '')
|
||||
""",
|
||||
(username, exclude_id or ""),
|
||||
).fetchone()
|
||||
if row:
|
||||
raise HTTPException(409, "Benutzername ist bereits vergeben")
|
||||
|
||||
|
||||
def _recent_count(conn, table: str, profile_id: str) -> int:
|
||||
cutoff = utc_stamp(datetime.utcnow() - timedelta(hours=1))
|
||||
if table not in {"password_reset_tokens", "email_verification_tokens"}:
|
||||
raise HTTPException(500, "Unbekannte Token-Tabelle")
|
||||
row = conn.execute(
|
||||
f"SELECT COUNT(*) AS n FROM {table} WHERE profile_id = ? AND created > ?",
|
||||
(profile_id, cutoff),
|
||||
).fetchone()
|
||||
return int(row["n"])
|
||||
|
||||
|
||||
def issue_password_reset(conn, profile_id: str) -> str | None:
|
||||
if _recent_count(conn, "password_reset_tokens", profile_id) >= LINK_LIMIT:
|
||||
return None
|
||||
raw = secrets.token_urlsafe(32)
|
||||
now = datetime.utcnow()
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO password_reset_tokens (id, profile_id, token_hash, expires_at, created)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
str(uuid.uuid4()),
|
||||
profile_id,
|
||||
hash_token(raw),
|
||||
utc_stamp(now + timedelta(minutes=RESET_MINUTES)),
|
||||
utc_stamp(now),
|
||||
),
|
||||
)
|
||||
return raw
|
||||
|
||||
|
||||
def issue_verification(conn, profile_id: str, purpose: str, email: str) -> str | None:
|
||||
if purpose not in {"primary", "secondary"}:
|
||||
raise HTTPException(400, "Unbekannter Verifikationszweck")
|
||||
if _recent_count(conn, "email_verification_tokens", profile_id) >= LINK_LIMIT:
|
||||
return None
|
||||
raw = secrets.token_urlsafe(32)
|
||||
now = datetime.utcnow()
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO email_verification_tokens
|
||||
(id, profile_id, purpose, email, token_hash, expires_at, created)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
str(uuid.uuid4()),
|
||||
profile_id,
|
||||
purpose,
|
||||
email,
|
||||
hash_token(raw),
|
||||
utc_stamp(now + timedelta(hours=VERIFY_HOURS)),
|
||||
utc_stamp(now),
|
||||
),
|
||||
)
|
||||
return raw
|
||||
|
||||
|
||||
def reset_link(token: str) -> str:
|
||||
return f"{app_base_url()}/reset-password?token={token}"
|
||||
|
||||
|
||||
def verify_link(token: str) -> str:
|
||||
return f"{app_base_url()}/verify-email?token={token}"
|
||||
|
||||
|
||||
def reset_message(token: str) -> tuple[str, str]:
|
||||
body = (
|
||||
"Über diesen Link setzt du das Passwort für Kanshō zurück.\n\n"
|
||||
f"{reset_link(token)}\n\n"
|
||||
"Der Link gilt 60 Minuten und kann nur einmal verwendet werden. "
|
||||
"Wenn du das nicht angefordert hast, ignoriere diese Nachricht."
|
||||
)
|
||||
return "Kanshō – Passwort zurücksetzen", body
|
||||
|
||||
|
||||
def verify_message(token: str) -> tuple[str, str]:
|
||||
body = (
|
||||
"Über diesen Link bestätigst du eine E-Mail-Adresse für Kanshō.\n\n"
|
||||
f"{verify_link(token)}\n\n"
|
||||
"Der Link gilt 24 Stunden und kann nur einmal verwendet werden."
|
||||
)
|
||||
return "Kanshō – E-Mail-Adresse bestätigen", body
|
||||
|
||||
|
||||
def change_notice() -> tuple[str, str]:
|
||||
body = (
|
||||
"Für dieses Kanshō-Konto wurde eine Änderung der E-Mail-Adresse angefordert. "
|
||||
"Wenn du das nicht warst, setze das Passwort zurück."
|
||||
)
|
||||
return "Kanshō – Änderung der E-Mail-Adresse", body
|
||||
|
||||
|
||||
def verified_reset_recipients(profile: dict) -> list[str]:
|
||||
recipients: list[str] = []
|
||||
if profile.get("email_verified_at") and profile.get("email"):
|
||||
recipients.append(profile["email"])
|
||||
if profile.get("secondary_email_verified_at") and profile.get("secondary_email"):
|
||||
recipients.append(profile["secondary_email"])
|
||||
return recipients
|
||||
|
||||
|
||||
def admin_reset_recipients(profile: dict) -> list[str]:
|
||||
recipients: list[str] = []
|
||||
if profile.get("email"):
|
||||
recipients.append(profile["email"])
|
||||
if profile.get("secondary_email_verified_at") and profile.get("secondary_email"):
|
||||
recipients.append(profile["secondary_email"])
|
||||
return recipients
|
||||
|
||||
|
||||
def notice_recipients(profile: dict) -> list[str]:
|
||||
return verified_reset_recipients(profile)
|
||||
|
||||
|
||||
def load_profile(conn, profile_id: str) -> dict | None:
|
||||
return row_to_dict(conn.execute("SELECT * FROM profiles WHERE id = ?", (profile_id,)).fetchone())
|
||||
|
||||
|
||||
def consume_password_reset(conn, token: str, password: str) -> None:
|
||||
if len(password or "") < 4:
|
||||
raise HTTPException(400, "Passwort muss mind. 4 Zeichen haben")
|
||||
now = utc_stamp()
|
||||
row = row_to_dict(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT * FROM password_reset_tokens
|
||||
WHERE token_hash = ? AND used_at IS NULL AND expires_at > ?
|
||||
""",
|
||||
(hash_token(token.strip()), now),
|
||||
).fetchone()
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(400, "Ungültiger oder abgelaufener Link")
|
||||
conn.execute(
|
||||
"UPDATE profiles SET password_hash = ? WHERE id = ?",
|
||||
(hash_password(password), row["profile_id"]),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE password_reset_tokens SET used_at = ? WHERE id = ?",
|
||||
(now, row["id"]),
|
||||
)
|
||||
conn.execute("DELETE FROM sessions WHERE profile_id = ?", (row["profile_id"],))
|
||||
|
||||
|
||||
def consume_verification(conn, token: str) -> dict:
|
||||
now = utc_stamp()
|
||||
row = row_to_dict(
|
||||
conn.execute(
|
||||
"""
|
||||
SELECT * FROM email_verification_tokens
|
||||
WHERE token_hash = ? AND used_at IS NULL AND expires_at > ?
|
||||
""",
|
||||
(hash_token(token.strip()), now),
|
||||
).fetchone()
|
||||
)
|
||||
if not row:
|
||||
raise HTTPException(400, "Ungültiger oder abgelaufener Link")
|
||||
profile = load_profile(conn, row["profile_id"])
|
||||
if not profile:
|
||||
raise HTTPException(400, "Ungültiger oder abgelaufener Link")
|
||||
purpose = row["purpose"]
|
||||
address = row["email"]
|
||||
if purpose == "primary":
|
||||
pending = (profile.get("pending_email") or "").strip().lower()
|
||||
current = (profile.get("email") or "").strip().lower()
|
||||
if pending:
|
||||
if address != pending:
|
||||
raise HTTPException(400, "Ungültiger oder abgelaufener Link")
|
||||
assert_address_free(conn, address, profile["id"])
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE profiles
|
||||
SET email = ?, email_verified_at = ?, pending_email = NULL
|
||||
WHERE id = ?
|
||||
""",
|
||||
(address, now, profile["id"]),
|
||||
)
|
||||
conn.execute("DELETE FROM sessions WHERE profile_id = ?", (profile["id"],))
|
||||
elif address == current:
|
||||
conn.execute(
|
||||
"UPDATE profiles SET email_verified_at = ? WHERE id = ?",
|
||||
(now, profile["id"]),
|
||||
)
|
||||
else:
|
||||
raise HTTPException(400, "Ungültiger oder abgelaufener Link")
|
||||
elif purpose == "secondary":
|
||||
pending = (profile.get("pending_secondary_email") or "").strip().lower()
|
||||
current = (profile.get("secondary_email") or "").strip().lower()
|
||||
if pending:
|
||||
if address != pending:
|
||||
raise HTTPException(400, "Ungültiger oder abgelaufener Link")
|
||||
assert_address_free(conn, address, profile["id"])
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE profiles
|
||||
SET secondary_email = ?, secondary_email_verified_at = ?, pending_secondary_email = NULL
|
||||
WHERE id = ?
|
||||
""",
|
||||
(address, now, profile["id"]),
|
||||
)
|
||||
elif current and address == current:
|
||||
conn.execute(
|
||||
"UPDATE profiles SET secondary_email_verified_at = ? WHERE id = ?",
|
||||
(now, profile["id"]),
|
||||
)
|
||||
else:
|
||||
raise HTTPException(400, "Ungültiger oder abgelaufener Link")
|
||||
else:
|
||||
raise HTTPException(400, "Ungültiger oder abgelaufener Link")
|
||||
conn.execute(
|
||||
"UPDATE email_verification_tokens SET used_at = ? WHERE id = ?",
|
||||
(now, row["id"]),
|
||||
)
|
||||
updated = load_profile(conn, profile["id"])
|
||||
viewed = profile_view(updated)
|
||||
if viewed is None:
|
||||
raise HTTPException(400, "Ungültiger oder abgelaufener Link")
|
||||
return viewed
|
||||
|
||||
|
||||
def _queue_verification(conn, profile: dict, purpose: str, address: str) -> tuple[str, str] | None:
|
||||
raw = issue_verification(conn, profile["id"], purpose, address)
|
||||
if not raw:
|
||||
return None
|
||||
return verify_message(raw)
|
||||
|
||||
|
||||
def apply_identifier_edits(
|
||||
conn,
|
||||
profile: dict,
|
||||
*,
|
||||
username: str | None = None,
|
||||
email: str | None = None,
|
||||
secondary_email: str | None = None,
|
||||
username_set: bool = False,
|
||||
email_set: bool = False,
|
||||
secondary_set: bool = False,
|
||||
) -> list[tuple[list[str], str, str]]:
|
||||
"""Apply username and address edits. Returns mails as (recipients, subject, body)."""
|
||||
jobs: list[tuple[list[str], str, str]] = []
|
||||
if username_set:
|
||||
if username is None or username.strip() == "":
|
||||
conn.execute("UPDATE profiles SET username = NULL WHERE id = ?", (profile["id"],))
|
||||
else:
|
||||
cleaned = normalize_username(username)
|
||||
assert_username_free(conn, cleaned, profile["id"])
|
||||
conn.execute("UPDATE profiles SET username = ? WHERE id = ?", (cleaned, profile["id"]))
|
||||
profile = load_profile(conn, profile["id"]) or profile
|
||||
if email_set and email is not None:
|
||||
cleaned = normalize_email(email)
|
||||
current = (profile.get("email") or "").strip().lower()
|
||||
secondary = (profile.get("secondary_email") or "").strip().lower()
|
||||
pending_secondary = (profile.get("pending_secondary_email") or "").strip().lower()
|
||||
if cleaned == current:
|
||||
pass
|
||||
else:
|
||||
if cleaned == secondary or cleaned == pending_secondary:
|
||||
raise HTTPException(409, "E-Mail ist bereits vergeben")
|
||||
assert_address_free(conn, cleaned, profile["id"])
|
||||
conn.execute("UPDATE profiles SET pending_email = ? WHERE id = ?", (cleaned, profile["id"]))
|
||||
queued = _queue_verification(conn, profile, "primary", cleaned)
|
||||
if queued:
|
||||
subject, body = queued
|
||||
jobs.append(([cleaned], subject, body))
|
||||
notice = notice_recipients(profile)
|
||||
notice = [item for item in notice if item != cleaned]
|
||||
if notice:
|
||||
jobs.append((notice, *change_notice()))
|
||||
else:
|
||||
raise HTTPException(429, "Zu viele Bestätigungslinks. Bitte später erneut versuchen.")
|
||||
profile = load_profile(conn, profile["id"]) or profile
|
||||
if secondary_set:
|
||||
if secondary_email is None or secondary_email.strip() == "":
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE profiles
|
||||
SET secondary_email = NULL,
|
||||
secondary_email_verified_at = NULL,
|
||||
pending_secondary_email = NULL
|
||||
WHERE id = ?
|
||||
""",
|
||||
(profile["id"],),
|
||||
)
|
||||
else:
|
||||
cleaned = normalize_email(secondary_email)
|
||||
current_primary = (profile.get("email") or "").strip().lower()
|
||||
pending_primary = (profile.get("pending_email") or "").strip().lower()
|
||||
current_secondary = (profile.get("secondary_email") or "").strip().lower()
|
||||
if cleaned == current_primary or cleaned == pending_primary:
|
||||
raise HTTPException(409, "E-Mail ist bereits vergeben")
|
||||
if cleaned == current_secondary and profile.get("secondary_email_verified_at") and not profile.get("pending_secondary_email"):
|
||||
pass
|
||||
else:
|
||||
assert_address_free(conn, cleaned, profile["id"])
|
||||
conn.execute(
|
||||
"UPDATE profiles SET pending_secondary_email = ? WHERE id = ?",
|
||||
(cleaned, profile["id"]),
|
||||
)
|
||||
queued = _queue_verification(conn, profile, "secondary", cleaned)
|
||||
if queued:
|
||||
subject, body = queued
|
||||
jobs.append(([cleaned], subject, body))
|
||||
notice = [item for item in notice_recipients(profile) if item != cleaned]
|
||||
if notice:
|
||||
jobs.append((notice, *change_notice()))
|
||||
else:
|
||||
raise HTTPException(429, "Zu viele Bestätigungslinks. Bitte später erneut versuchen.")
|
||||
return jobs
|
||||
|
||||
|
||||
def deliver_jobs(jobs: list[tuple[list[str], str, str]]) -> None:
|
||||
from mailer import send_mail
|
||||
|
||||
for recipients, subject, body in jobs:
|
||||
send_mail(recipients, subject, body)
|
||||
|
||||
|
||||
def resend_verification(conn, profile: dict, purpose: str) -> tuple[list[str], str, str]:
|
||||
if purpose == "primary":
|
||||
target = (profile.get("pending_email") or "").strip().lower()
|
||||
if not target and not profile.get("email_verified_at"):
|
||||
target = (profile.get("email") or "").strip().lower()
|
||||
if not target or (profile.get("email_verified_at") and not profile.get("pending_email")):
|
||||
raise HTTPException(400, "Keine offene Bestätigung für die primäre E-Mail")
|
||||
elif purpose == "secondary":
|
||||
target = (profile.get("pending_secondary_email") or "").strip().lower()
|
||||
if not target and profile.get("secondary_email") and not profile.get("secondary_email_verified_at"):
|
||||
target = profile["secondary_email"].strip().lower()
|
||||
if not target or (
|
||||
profile.get("secondary_email_verified_at") and not profile.get("pending_secondary_email")
|
||||
):
|
||||
raise HTTPException(400, "Keine offene Bestätigung für die zweite E-Mail")
|
||||
else:
|
||||
raise HTTPException(400, "Unbekannter Verifikationszweck")
|
||||
queued = _queue_verification(conn, profile, purpose, target)
|
||||
if not queued:
|
||||
raise HTTPException(429, "Zu viele Bestätigungslinks. Bitte später erneut versuchen.")
|
||||
subject, body = queued
|
||||
return [target], subject, body
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"seed_revision": "2026-08-27-generation-guidelines-v1",
|
||||
"seed_revision": "2026-08-29-voice-legacy-immutable-v1",
|
||||
"purpose": "journal_generate",
|
||||
"max_instruction_chars": 1000,
|
||||
"max_label_chars": 80,
|
||||
@@ -79,31 +79,120 @@
|
||||
{
|
||||
"id": "journal-generate-voice-neutral",
|
||||
"guideline_key": "neutral",
|
||||
"label": "neutral",
|
||||
"summary": "Neutraler Journalstil, Writing Profile nur als leise Tendenz.",
|
||||
"instruction": "Schreibe in einem neutralen Journalstil. Das Writing Profile höchstens als leise Tendenz."
|
||||
"label": "Ohne persönliches Profil",
|
||||
"summary": "Natürlicher, neutraler Journalstil ohne Writing Profile und ohne Stilbeispiele.",
|
||||
"instruction": "Schreibe in einem natürlichen, neutralen Journalstil. Der aktuelle Tagesdialog ist nur Inhaltsquelle, nicht Stilvorlage.",
|
||||
"style_context": {
|
||||
"include_core": false,
|
||||
"include_facet": false,
|
||||
"include_traits": false,
|
||||
"include_style_examples": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "journal-generate-voice-light",
|
||||
"guideline_key": "light",
|
||||
"label": "dezent",
|
||||
"summary": "Rhythmus und Wortwahl des Writing Profiles zurückhaltend.",
|
||||
"instruction": "Nimm Rhythmus und Wortwahl des Writing Profiles zurückhaltend auf."
|
||||
"label": "Persönliche Stimme dezent",
|
||||
"summary": "Zurückhaltende Orientierung am Schreibkern, ohne Facet, Traits oder Beispiele.",
|
||||
"instruction": "Orientiere dich zurückhaltend am mitgegebenen Schreibkern. Übernimm daraus keine Ereignisse, Personen oder Bewertungen.",
|
||||
"style_context": {
|
||||
"include_core": true,
|
||||
"include_facet": false,
|
||||
"include_traits": false,
|
||||
"include_style_examples": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "journal-generate-voice-noticeable",
|
||||
"guideline_key": "noticeable",
|
||||
"label": "spürbar",
|
||||
"summary": "Writing Profile spürbar, ohne in den Vordergrund zu treten.",
|
||||
"instruction": "Wende das Writing Profile spürbar an, ohne es in den Vordergrund zu stellen."
|
||||
"instruction": "Wende das Writing Profile spürbar an, ohne es in den Vordergrund zu stellen.",
|
||||
"style_context": {
|
||||
"include_core": true,
|
||||
"include_facet": true,
|
||||
"include_traits": true,
|
||||
"include_style_examples": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "journal-generate-voice-clear",
|
||||
"guideline_key": "clear",
|
||||
"label": "deutlich",
|
||||
"summary": "Rhythmus, Wortwahl und Reflexionsdichte des Writing Profiles deutlich.",
|
||||
"label": "Persönliche Stimme deutlich",
|
||||
"summary": "Deutliche Orientierung an Tonlage, Rhythmus und Wortwahl des Profils.",
|
||||
"instruction": "Wende Tonlage, Rhythmus und Wortwahl des mitgegebenen Writing Profiles deutlich an, ohne den Text künstlich zu literarisieren. Übernimm daraus keine Ereignisse, Personen oder Bewertungen.",
|
||||
"is_default": true,
|
||||
"style_context": {
|
||||
"include_core": true,
|
||||
"include_facet": true,
|
||||
"include_traits": true,
|
||||
"include_style_examples": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "journal-generate-voice-with-examples",
|
||||
"guideline_key": "with_examples",
|
||||
"label": "Persönliche Stimme mit Beispielen",
|
||||
"summary": "Deutliche Profilanwendung; historische Texte nur als sprachliche Referenz.",
|
||||
"instruction": "Wende Tonlage, Rhythmus und Wortwahl des mitgegebenen Writing Profiles deutlich an. STYLE_EXAMPLES sind ausschließlich sprachliche Referenz; ihre Ereignisse, Personen, Orte und Bewertungen gehören nicht zum heutigen Tag.",
|
||||
"style_context": {
|
||||
"include_core": true,
|
||||
"include_facet": true,
|
||||
"include_traits": true,
|
||||
"include_style_examples": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "journal-generate-voice-legacy-neutral",
|
||||
"guideline_key": "legacy_neutral",
|
||||
"label": "Legacy – vor Stilkontextsteuerung · neutral",
|
||||
"summary": "Rekonstruierte frühere Semantik: Neutraler Journalstil, Writing Profile nur als leise Tendenz.",
|
||||
"instruction": "Schreibe in einem neutralen Journalstil. Das Writing Profile höchstens als leise Tendenz.",
|
||||
"style_context": {
|
||||
"include_core": true,
|
||||
"include_facet": true,
|
||||
"include_traits": true,
|
||||
"include_style_examples": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "journal-generate-voice-legacy-light",
|
||||
"guideline_key": "legacy_light",
|
||||
"label": "Legacy – vor Stilkontextsteuerung · dezent",
|
||||
"summary": "Rekonstruierte frühere Semantik: Rhythmus und Wortwahl des Writing Profiles zurückhaltend.",
|
||||
"instruction": "Nimm Rhythmus und Wortwahl des Writing Profiles zurückhaltend auf.",
|
||||
"style_context": {
|
||||
"include_core": true,
|
||||
"include_facet": true,
|
||||
"include_traits": true,
|
||||
"include_style_examples": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "journal-generate-voice-legacy-noticeable",
|
||||
"guideline_key": "legacy_noticeable",
|
||||
"label": "Legacy – vor Stilkontextsteuerung · spürbar",
|
||||
"summary": "Rekonstruierte frühere Semantik: Writing Profile spürbar, ohne in den Vordergrund zu treten.",
|
||||
"instruction": "Wende das Writing Profile spürbar an, ohne es in den Vordergrund zu stellen.",
|
||||
"style_context": {
|
||||
"include_core": true,
|
||||
"include_facet": true,
|
||||
"include_traits": true,
|
||||
"include_style_examples": true
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "journal-generate-voice-legacy-clear",
|
||||
"guideline_key": "legacy_clear",
|
||||
"label": "Legacy – vor Stilkontextsteuerung · deutlich",
|
||||
"summary": "Rekonstruierte frühere Semantik: Rhythmus, Wortwahl und Reflexionsdichte des Writing Profiles deutlich.",
|
||||
"instruction": "Wende Rhythmus, Wortwahl und Reflexionsdichte des Writing Profiles deutlich an, ohne den Text künstlich zu literarisieren.",
|
||||
"is_default": true
|
||||
"style_context": {
|
||||
"include_core": true,
|
||||
"include_facet": true,
|
||||
"include_traits": true,
|
||||
"include_style_examples": true
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
@@ -17,8 +17,8 @@
|
||||
"category": "mvp",
|
||||
"prompt_type": "base",
|
||||
"required_feature": "ai_calls",
|
||||
"template": "Du redigierst einen persönlichen Tagebucheintrag in der Ich-Form.\n\nAUFGABE\nFormuliere aus CURRENT_DAY_SOURCES einen lesenswerten, eigenständigen Journaltext. Die Quellen bestimmen, was geschehen ist. WRITING_PROFILE bestimmt, wie es erzählt wird. Quellsyntax, Rechtschreibfehler und Dialogstruktur sind keine Ausgabevorlage.\n\nBEARBEITUNG\n{{transformation_instructions}}\n{{detail_instructions}}\n{{voice_instructions}}\n{{narrative_instructions}}\n\nINHALTSTREUE\nVerändere keine Ereignisse, Beteiligten, Orte, Zeiten oder zeitlichen Abläufe. Erhalte Verneinungen, Unsicherheiten, Korrekturen, ausdrücklich genannte Gefühle und Bewertungen sowie den Unterschied zwischen Plan und Vollzug. Ergänze keine neuen Tatsachen, Ursachen, Motive, Gefühle oder Hintergrundinformationen. Übergänge dürfen verbinden, aber nichts erklären, was die Quellen nicht erklären. Bei unklaren Satzfragmenten nicht raten, sondern neutral umformulieren oder nur den unverständlichen Teil weglassen.\n\nSTIL\nKorrigiere Rechtschreibung, Grammatik und Zeichensetzung. Verbessere Satzbau, Rhythmus, Übergänge und Absätze. Fasse echte Wiederholungen zusammen. Formuliere schwache oder fehlerhafte Stellen eigenständig neu. Gute persönliche Formulierungen dürfen erhalten bleiben. STYLE_EXAMPLES dienen ausschließlich als Stilreferenz; ihre Inhalte gehören nicht zum heutigen Tag.\nDie Quellen können aus Fließtext, Stichpunkten und Satzfragmenten bestehen. Behandle jede Passage entsprechend ihrer Form: Redigiere vorhandenen Fließtext, verwandle Stichpunkte und Fragmente in vollständige Prosa und verbinde beides zu einem einheitlichen Eintrag. Zwinge nicht den gesamten Tag in einen einzigen Quellenmodus.\n\nDATENSCHUTZ\nÜbernimm vorhandene Platzhalter wie [[PERSON:01]] unverändert. Erzeuge keine neuen Platzhalter und schreibe keine Klarnamen an ihre Stelle.\n\nKONTEXT\n\nWRITING_PROFILE\n{{writing_profile}}\n\nSTYLE_EXAMPLES\n{{style_examples}}\n\nCURRENT_DAY_SOURCES\n{{reconstruction}}\n\nEXISTING_TEXT\n{{existing_text}}\n\nAUSGABE\nErste Zeile: eine kurze passende Überschrift ohne neue Tatsachen. Danach zusammenhängende, natürlich gegliederte Absätze. Keine Aufzählung und keine Meta-Erklärung.\n",
|
||||
"seed_revision": "2026-08-27-journal-mixed-sources-v1"
|
||||
"template": "Du redigierst einen persönlichen Tagebucheintrag in der Ich-Form.\n\nAUFGABE\nFormuliere aus CURRENT_DAY_SOURCES einen lesenswerten, eigenständigen Journaltext. Die Quellen bestimmen, was geschehen ist. Ein mitgegebenes WRITING_PROFILE bestimmt, wie es erzählt wird; fehlt es, gilt nur die Stimmanweisung. Quellsyntax, Rechtschreibfehler und Dialogstruktur sind keine Ausgabevorlage.\n\nBEARBEITUNG\n{{transformation_instructions}}\n{{detail_instructions}}\n{{voice_instructions}}\n{{narrative_instructions}}\n\nINHALTSTREUE\nVerändere keine Ereignisse, Beteiligten, Orte, Zeiten oder zeitlichen Abläufe. Erhalte Verneinungen, Unsicherheiten, Korrekturen, ausdrücklich genannte Gefühle und Bewertungen sowie den Unterschied zwischen Plan und Vollzug. Ergänze keine neuen Tatsachen, Ursachen, Motive, Gefühle oder Hintergrundinformationen. Übergänge dürfen verbinden, aber nichts erklären, was die Quellen nicht erklären. Bei unklaren Satzfragmenten nicht raten, sondern neutral umformulieren oder nur den unverständlichen Teil weglassen.\n\nSTIL\nKorrigiere Rechtschreibung, Grammatik und Zeichensetzung. Verbessere Satzbau, Rhythmus, Übergänge und Absätze. Fasse echte Wiederholungen zusammen. Formuliere schwache oder fehlerhafte Stellen eigenständig neu. Gute persönliche Formulierungen dürfen erhalten bleiben. Der aktuelle Tagesdialog ist keine Stilvorlage.\nDie Quellen können aus Fließtext, Stichpunkten und Satzfragmenten bestehen. Behandle jede Passage entsprechend ihrer Form: Redigiere vorhandenen Fließtext, verwandle Stichpunkte und Fragmente in vollständige Prosa und verbinde beides zu einem einheitlichen Eintrag. Zwinge nicht den gesamten Tag in einen einzigen Quellenmodus.\n\nDATENSCHUTZ\nÜbernimm vorhandene Platzhalter wie [[PERSON:01]] unverändert. Erzeuge keine neuen Platzhalter und schreibe keine Klarnamen an ihre Stelle.\n\nKONTEXT\n{{writing_profile}}{{style_examples}}\nCURRENT_DAY_SOURCES\n{{reconstruction}}\n\nEXISTING_TEXT\n{{existing_text}}\n\nAUSGABE\nErste Zeile: eine kurze passende Überschrift ohne neue Tatsachen. Danach zusammenhängende, natürlich gegliederte Absätze. Keine Aufzählung und keine Meta-Erklärung.\n",
|
||||
"seed_revision": "2026-08-29-voice-legacy-immutable-v1"
|
||||
},
|
||||
{
|
||||
"id": "mvp-journal-reconstruct",
|
||||
@@ -38,8 +38,8 @@
|
||||
"category": "privacy",
|
||||
"prompt_type": "base",
|
||||
"required_feature": "ai_calls",
|
||||
"seed_revision": "2026-08-27-detect-ground-v1",
|
||||
"template": "Untersuche den gesamten Text semantisch. Entscheide kontextabhängig, nicht nach Großschreibung oder Namensähnlichkeit allein.\n\nSchützenswert ist eine konkrete Bezeichnung oder Information, durch die eine natürliche Person, ein genauer persönlicher Ort, eine Organisation, ein privates Projekt oder ein anderer im Produktrahmen definierter Identifikator erkennbar werden kann. Allgemeine Gegenstände, Tätigkeiten, Lebensmittel, Räume und Beschreibungen sind keine Identitäten, sofern sie im konkreten Satz nicht als Eigenname oder identifizierende Information verwendet werden.\n\nErlaubte entity_type-Werte ausschließlich: PERSON, PLACE, ORG, PROJECT.\n\nKontrast, keine Wortliste:\n- «Sushi kam ins Wohnzimmer» kann eine Person bezeichnen.\n- «Ich aß Sushi» bezeichnet ein Gericht.\n- «Ich arbeitete am privaten Projekt Aurora» kann ein schützenswertes Projekt bezeichnen.\n- «Ich ging auf den Balkon» bezeichnet keinen Eigennamen.\n- «Ich traf Anna» bezeichnet eine Person.\n\nNur das identifizierende Wort oder die identifizierende Wortgruppe, nicht den ganzen Satz. Offsets beziehen sich ausschließlich auf den gelieferten Text nach «Text:», 0-basiert, end ausschließlich. text muss ein exakter Substring dieses Texts sein, nicht aus den Beispielen oben. Wenn Offsets unsicher sind, kopiere trotzdem das identifizierende Wort zeichengetreu.\n\nKeine Tokens, keine Platzhalter, keine kanonischen Namen, keine Aliase, keine zusätzlichen Felder.\n\nAntworte nur mit JSON. Form: {\"entities\":[{\"start\":<zahl>,\"end\":<zahl>,\"text\":\"<exakter Substring>\",\"entity_type\":\"PERSON\"}]}\nNichts schützenswert: {\"entities\":[]}\n\nText:\n{{source_text}}\n"
|
||||
"seed_revision": "2026-09-08-detect-homonym-v1",
|
||||
"template": "Untersuche den gesamten Text semantisch. Entscheide kontextabhängig, nicht nach Großschreibung oder Namensähnlichkeit allein.\n\nSchützenswert ist eine konkrete Bezeichnung oder Information, durch die eine natürliche Person, ein genauer persönlicher Ort, eine Organisation, ein privates Projekt oder ein anderer im Produktrahmen definierter Identifikator erkennbar werden kann. Allgemeine Gegenstände, Tätigkeiten, Lebensmittel, Räume und Beschreibungen sind keine Identitäten, sofern sie im konkreten Satz nicht als Eigenname oder identifizierende Information verwendet werden.\n\nErlaubte entity_type-Werte ausschließlich: PERSON, PLACE, ORG, PROJECT.\nEin Lebensmittel oder Gericht ist keine Entität. Nicht als FOOD oder einen anderen Typ melden, sondern weglassen. Derselbe Wortlaut kann im selben Text Person und Gericht sein; nur die identifizierende Nennung gehört in entities.\n\nKontrast, keine Wortliste:\n- «Sushi kam ins Wohnzimmer» kann eine Person bezeichnen.\n- «Ich aß Sushi» bezeichnet ein Gericht.\n- «Ich arbeitete am privaten Projekt Aurora» kann ein schützenswertes Projekt bezeichnen.\n- «Ich ging auf den Balkon» bezeichnet keinen Eigennamen.\n- «Ich traf Anna» bezeichnet eine Person.\n\nNur das identifizierende Wort oder die identifizierende Wortgruppe, nicht den ganzen Satz. Offsets beziehen sich ausschließlich auf den gelieferten Text nach «Text:», 0-basiert, end ausschließlich. text muss ein exakter Substring dieses Texts sein, nicht aus den Beispielen oben. Wenn Offsets unsicher sind, kopiere trotzdem das identifizierende Wort zeichengetreu.\n\nKeine Tokens, keine Platzhalter, keine kanonischen Namen, keine Aliase, keine zusätzlichen Felder.\n\nAntworte nur mit JSON. Form: {\"entities\":[{\"start\":<zahl>,\"end\":<zahl>,\"text\":\"<exakter Substring>\",\"entity_type\":\"PERSON\"}]}\nNichts schützenswert: {\"entities\":[]}\n\nText:\n{{source_text}}\n"
|
||||
},
|
||||
{
|
||||
"id": "mvp-profile-review",
|
||||
|
||||
@@ -70,11 +70,13 @@ 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 = "",
|
||||
reconstruction: str = "",
|
||||
day_spec: dict | None = None,
|
||||
writing_profile: str | None = None,
|
||||
style_examples: str = "",
|
||||
transformation_instructions: str = "",
|
||||
detail_instructions: str = "",
|
||||
@@ -117,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,
|
||||
{
|
||||
@@ -151,9 +153,12 @@ def build_internal_context(
|
||||
items.append({"type": "space_recent_sources", "sources": recent_sources})
|
||||
|
||||
if purpose == "journal_generate":
|
||||
if writing_profile is None:
|
||||
from writing_profile_store import compile_task_brief
|
||||
|
||||
brief = compile_task_brief(profile_id, "journal_generate")
|
||||
else:
|
||||
brief = writing_profile
|
||||
items.append({"type": "writing_profile", "compiled_brief": brief})
|
||||
items.append({"type": "style_examples", "body": style_examples or ""})
|
||||
items.append({"type": "transformation_instructions", "text": transformation_instructions or ""})
|
||||
|
||||
+196
-34
@@ -1,4 +1,8 @@
|
||||
"""SQLite persistence for the local frame. PostgreSQL remains the later target."""
|
||||
"""Persistence for the local frame.
|
||||
|
||||
SQLite is the Windows/test engine. PostgreSQL 16 is the Docker/server engine.
|
||||
Switch at connect time via KANSHO_DB_BACKEND / DB_HOST; stores keep SQLite-shaped SQL.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
@@ -6,18 +10,81 @@ import os
|
||||
import sqlite3
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
DATA_DIR = Path(__file__).resolve().parent / "data"
|
||||
from sql_compat import (
|
||||
adapt_sql,
|
||||
postgres_connect_kwargs,
|
||||
rewrite_catalog_sql,
|
||||
split_sql,
|
||||
sqlite_schema_to_postgres,
|
||||
use_postgres,
|
||||
)
|
||||
|
||||
_env_data = (os.environ.get("KANSHO_DATA_DIR") or "").strip()
|
||||
DATA_DIR = Path(_env_data) if _env_data else Path(__file__).resolve().parent / "data"
|
||||
SCHEMA_PATH = Path(__file__).resolve().parent / "schema.sql"
|
||||
SEED_PATH = Path(__file__).resolve().parent / "config" / "platform_seed.json"
|
||||
PROMPTS_SEED_PATH = Path(__file__).resolve().parent / "config" / "prompts.seed.json"
|
||||
_env_db = os.environ.get("KANSHO_DB_PATH")
|
||||
DB_PATH = Path(_env_db) if _env_db else DATA_DIR / "kansho.sqlite"
|
||||
|
||||
SQLITE_HISTORY_MIGRATIONS = (
|
||||
"001_frame",
|
||||
"002_platform",
|
||||
"003_dialogue_memory",
|
||||
"004_mvp_journal",
|
||||
"005_provider_settings",
|
||||
"006_writing_profile_dialogue_style",
|
||||
"007_journal_day_scratch",
|
||||
"008_journal_source_refs",
|
||||
"009_conversation_signals",
|
||||
"010_profile_governance",
|
||||
"011_profile_review",
|
||||
"012_profile_shell",
|
||||
"013_journal_generate_narration",
|
||||
"014_identity_registry",
|
||||
"015_journal_generation_settings",
|
||||
"016_generation_instruction_fragments",
|
||||
"017_generation_guidelines",
|
||||
"018_debug_runs",
|
||||
"019_debug_run_placement",
|
||||
"020_voice_style_context",
|
||||
"021_voice_legacy_immutable",
|
||||
)
|
||||
|
||||
_PROFILE_COLUMNS = {
|
||||
"status": "TEXT NOT NULL DEFAULT 'active'",
|
||||
"tier_id": "TEXT NOT NULL DEFAULT 'local'",
|
||||
"username": "TEXT",
|
||||
"secondary_email": "TEXT",
|
||||
"email_verified_at": "TEXT",
|
||||
"secondary_email_verified_at": "TEXT",
|
||||
"pending_email": "TEXT",
|
||||
"pending_secondary_email": "TEXT",
|
||||
}
|
||||
_ACCOUNT_INDEXES = (
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS profiles_username_lower_idx
|
||||
ON profiles (lower(username))
|
||||
WHERE username IS NOT NULL AND username <> ''
|
||||
""",
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS profiles_secondary_email_lower_idx
|
||||
ON profiles (lower(secondary_email))
|
||||
WHERE secondary_email IS NOT NULL AND secondary_email <> ''
|
||||
""",
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS profiles_pending_email_lower_idx
|
||||
ON profiles (lower(pending_email))
|
||||
WHERE pending_email IS NOT NULL AND pending_email <> ''
|
||||
""",
|
||||
"""
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS profiles_pending_secondary_email_lower_idx
|
||||
ON profiles (lower(pending_secondary_email))
|
||||
WHERE pending_secondary_email IS NOT NULL AND pending_secondary_email <> ''
|
||||
""",
|
||||
)
|
||||
_PROMPT_COLUMNS = {
|
||||
"description": "TEXT NOT NULL DEFAULT ''",
|
||||
"category": "TEXT NOT NULL DEFAULT 'uncategorized'",
|
||||
@@ -66,6 +133,9 @@ _JOURNAL_DAY_COLUMNS = {
|
||||
_JOURNAL_DRAFT_COLUMNS = {
|
||||
"generation_snapshot": "TEXT NOT NULL DEFAULT '{}'",
|
||||
}
|
||||
_GUIDELINE_COLUMNS = {
|
||||
"style_context_json": "TEXT NOT NULL DEFAULT '{}'",
|
||||
}
|
||||
_DEBUG_RUN_COLUMNS = {
|
||||
"space_id": "TEXT",
|
||||
"journal_day_id": "TEXT",
|
||||
@@ -85,7 +155,61 @@ _IDENTITY_MAPPING_COLUMNS = {
|
||||
}
|
||||
|
||||
|
||||
def _connect() -> sqlite3.Connection:
|
||||
class PostgresCompat:
|
||||
"""sqlite3-like execute/commit surface over psycopg, with SQL translation."""
|
||||
|
||||
def __init__(self, raw: Any):
|
||||
self._raw = raw
|
||||
|
||||
def execute(self, sql: str, params: Any = None):
|
||||
special = rewrite_catalog_sql(sql)
|
||||
if special:
|
||||
adapted, extra = special
|
||||
args = extra if extra is not None else params
|
||||
else:
|
||||
adapted = adapt_sql(sql)
|
||||
args = params
|
||||
if args is None:
|
||||
return self._raw.execute(adapted)
|
||||
return self._raw.execute(adapted, args)
|
||||
|
||||
def executemany(self, sql: str, seq_of_params: Any):
|
||||
adapted = adapt_sql(sql)
|
||||
cursor = None
|
||||
for params in seq_of_params:
|
||||
cursor = self._raw.execute(adapted, params)
|
||||
return cursor
|
||||
|
||||
def executescript(self, script: str):
|
||||
for statement in split_sql(sqlite_schema_to_postgres(script)):
|
||||
self._raw.execute(statement)
|
||||
return self
|
||||
|
||||
def commit(self):
|
||||
self._raw.commit()
|
||||
|
||||
def rollback(self):
|
||||
self._raw.rollback()
|
||||
|
||||
def close(self):
|
||||
self._raw.close()
|
||||
|
||||
|
||||
def _connect_postgres() -> PostgresCompat:
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
kwargs = postgres_connect_kwargs()
|
||||
if "conninfo" in kwargs:
|
||||
raw = psycopg.connect(kwargs["conninfo"], row_factory=dict_row)
|
||||
else:
|
||||
raw = psycopg.connect(row_factory=dict_row, **kwargs)
|
||||
return PostgresCompat(raw)
|
||||
|
||||
|
||||
def _connect():
|
||||
if use_postgres():
|
||||
return _connect_postgres()
|
||||
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(DB_PATH, timeout=30)
|
||||
conn.row_factory = sqlite3.Row
|
||||
@@ -106,32 +230,53 @@ def get_db():
|
||||
conn.close()
|
||||
|
||||
|
||||
def row_to_dict(row: sqlite3.Row | None) -> dict | None:
|
||||
def row_to_dict(row: Any) -> dict | None:
|
||||
if row is None:
|
||||
return None
|
||||
return dict(row)
|
||||
|
||||
|
||||
def _column_names(conn: sqlite3.Connection, table: str) -> set[str]:
|
||||
def _column_names(conn: Any, table: str) -> set[str]:
|
||||
rows = conn.execute(f"PRAGMA table_info({table})").fetchall()
|
||||
return {row["name"] for row in rows}
|
||||
|
||||
|
||||
def _ensure_columns(conn: sqlite3.Connection, table: str, columns: dict[str, str]) -> None:
|
||||
def _ensure_columns(conn: Any, table: str, columns: dict[str, str]) -> None:
|
||||
existing = _column_names(conn, table)
|
||||
for name, ddl in columns.items():
|
||||
if name not in existing:
|
||||
conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {ddl}")
|
||||
|
||||
|
||||
def _mark(conn: sqlite3.Connection, migration_id: str) -> None:
|
||||
def _mark(conn: Any, migration_id: str) -> None:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO schema_migrations (id) VALUES (?)",
|
||||
(migration_id,),
|
||||
)
|
||||
|
||||
|
||||
def _seed_platform(conn: sqlite3.Connection) -> None:
|
||||
def _ensure_account_identifiers(conn: Any) -> None:
|
||||
"""Add login identifiers on existing SQLite files and grandfather current emails once."""
|
||||
_ensure_columns(conn, "profiles", _PROFILE_COLUMNS)
|
||||
for statement in _ACCOUNT_INDEXES:
|
||||
conn.execute(statement)
|
||||
row = conn.execute(
|
||||
"SELECT id FROM schema_migrations WHERE id = ?",
|
||||
("027_account_identifiers",),
|
||||
).fetchone()
|
||||
if row:
|
||||
return
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE profiles
|
||||
SET email_verified_at = COALESCE(created, datetime('now'))
|
||||
WHERE email_verified_at IS NULL OR email_verified_at = ''
|
||||
"""
|
||||
)
|
||||
_mark(conn, "027_account_identifiers")
|
||||
|
||||
|
||||
def _seed_platform(conn: Any) -> None:
|
||||
seed = json.loads(SEED_PATH.read_text(encoding="utf-8"))
|
||||
for tier in seed.get("tiers", []):
|
||||
conn.execute(
|
||||
@@ -168,7 +313,7 @@ def _seed_platform(conn: sqlite3.Connection) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _seed_prompts(conn: sqlite3.Connection) -> None:
|
||||
def _seed_prompts(conn: Any) -> None:
|
||||
"""Prompts come from JSON/DB, never from Python string literals.
|
||||
|
||||
Untouched system prompts (template == default_template) receive the seed.
|
||||
@@ -211,7 +356,7 @@ def _seed_prompts(conn: sqlite3.Connection) -> None:
|
||||
SET name = ?, description = ?, category = ?, prompt_type = ?,
|
||||
required_feature = ?, is_system_default = 1, default_template = ?,
|
||||
seed_revision = ?,
|
||||
template = CASE WHEN ? THEN ? ELSE template END,
|
||||
template = CASE WHEN ? = 1 THEN ? ELSE template END,
|
||||
updated = datetime('now')
|
||||
WHERE slug = ?
|
||||
""",
|
||||
@@ -243,7 +388,7 @@ def _parse_legacy_ids(raw: str | None) -> list[str]:
|
||||
|
||||
|
||||
def _insert_source_refs(
|
||||
conn: sqlite3.Connection,
|
||||
conn: Any,
|
||||
table: str,
|
||||
owner_col: str,
|
||||
owner_id: str,
|
||||
@@ -272,7 +417,7 @@ def _insert_source_refs(
|
||||
)
|
||||
|
||||
|
||||
def migrate_journal_source_refs(conn: sqlite3.Connection) -> None:
|
||||
def migrate_journal_source_refs(conn: Any) -> None:
|
||||
"""Copy JSON id lists into relational source-ref tables without touching Source."""
|
||||
existing = {
|
||||
row["name"]
|
||||
@@ -320,7 +465,7 @@ def migrate_journal_source_refs(conn: sqlite3.Connection) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _migrate_writing_profile_dialogue_style(conn: sqlite3.Connection) -> None:
|
||||
def _migrate_writing_profile_dialogue_style(conn: Any) -> None:
|
||||
"""Existing DBs keep the old CHECK; recreate so dialogue_style is a valid source kind."""
|
||||
row = row_to_dict(
|
||||
conn.execute(
|
||||
@@ -351,7 +496,7 @@ def _migrate_writing_profile_dialogue_style(conn: sqlite3.Connection) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _migrate_writing_profile_shell(conn: sqlite3.Connection) -> None:
|
||||
def _migrate_writing_profile_shell(conn: Any) -> None:
|
||||
"""Layers stay; inferred count-facets are not the profile. Manual style keys become traits."""
|
||||
from writing_profile_schema import LEGACY_STYLE_KEYS, coerce_slug, facet_layer, normalize_facet_key
|
||||
|
||||
@@ -446,7 +591,36 @@ def _migrate_writing_profile_shell(conn: sqlite3.Connection) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _seed_runtime(conn: Any) -> None:
|
||||
_seed_platform(conn)
|
||||
_seed_prompts(conn)
|
||||
from provider_settings import seed_provider_settings
|
||||
from journal_generation_policy import backfill_missing_settings, seed_generation_instructions
|
||||
|
||||
seed_provider_settings(conn)
|
||||
seed_generation_instructions(conn)
|
||||
backfill_missing_settings(conn)
|
||||
seed_generation_instructions(conn)
|
||||
seed_generation_instructions(conn)
|
||||
|
||||
|
||||
def refresh_runtime_seed() -> None:
|
||||
"""Re-seed catalog rows after a data truncate. Schema must already exist."""
|
||||
with get_db() as conn:
|
||||
_seed_runtime(conn)
|
||||
from writing_profile_store import bootstrap_from_existing
|
||||
|
||||
bootstrap_from_existing()
|
||||
|
||||
|
||||
def init_db() -> None:
|
||||
if use_postgres():
|
||||
from db_init import ensure_postgres_ready
|
||||
|
||||
ensure_postgres_ready()
|
||||
refresh_runtime_seed()
|
||||
return
|
||||
|
||||
schema = SCHEMA_PATH.read_text(encoding="utf-8")
|
||||
with get_db() as conn:
|
||||
conn.executescript(schema)
|
||||
@@ -455,8 +629,9 @@ def init_db() -> None:
|
||||
_seed_prompts(conn)
|
||||
from provider_settings import seed_provider_settings
|
||||
|
||||
_ensure_columns(conn, "provider_settings", {"profile_id": "TEXT"})
|
||||
seed_provider_settings(conn)
|
||||
_ensure_columns(conn, "profiles", _PROFILE_COLUMNS)
|
||||
_ensure_account_identifiers(conn)
|
||||
_ensure_columns(conn, "conversations", _CONVERSATION_COLUMNS)
|
||||
_ensure_columns(conn, "journal_days", _JOURNAL_DAY_COLUMNS)
|
||||
_ensure_columns(conn, "journal_drafts", _JOURNAL_DRAFT_COLUMNS)
|
||||
@@ -468,33 +643,20 @@ def init_db() -> None:
|
||||
migrate_journal_source_refs(conn)
|
||||
_migrate_writing_profile_shell(conn)
|
||||
_ensure_columns(conn, "identity_mappings", _IDENTITY_MAPPING_COLUMNS)
|
||||
_ensure_columns(conn, "label_sense_cues", {"excerpt": "TEXT NOT NULL DEFAULT ''"})
|
||||
from identity_store import migrate_legacy_identity_rows
|
||||
|
||||
migrate_legacy_identity_rows(conn)
|
||||
_mark(conn, "001_frame")
|
||||
_mark(conn, "002_platform")
|
||||
_mark(conn, "003_dialogue_memory")
|
||||
_mark(conn, "004_mvp_journal")
|
||||
_mark(conn, "005_provider_settings")
|
||||
_mark(conn, "006_writing_profile_dialogue_style")
|
||||
_mark(conn, "007_journal_day_scratch")
|
||||
_mark(conn, "008_journal_source_refs")
|
||||
_mark(conn, "009_conversation_signals")
|
||||
_mark(conn, "010_profile_governance")
|
||||
_mark(conn, "011_profile_review")
|
||||
_mark(conn, "012_profile_shell")
|
||||
_mark(conn, "013_journal_generate_narration")
|
||||
_mark(conn, "014_identity_registry")
|
||||
for migration_id in SQLITE_HISTORY_MIGRATIONS:
|
||||
_mark(conn, migration_id)
|
||||
from journal_generation_policy import backfill_missing_settings, seed_generation_instructions
|
||||
|
||||
_ensure_columns(conn, "generation_guidelines", _GUIDELINE_COLUMNS)
|
||||
seed_generation_instructions(conn)
|
||||
backfill_missing_settings(conn)
|
||||
_mark(conn, "015_journal_generation_settings")
|
||||
_mark(conn, "016_generation_instruction_fragments")
|
||||
_mark(conn, "017_generation_guidelines")
|
||||
_mark(conn, "018_debug_runs")
|
||||
_ensure_columns(conn, "debug_runs", _DEBUG_RUN_COLUMNS)
|
||||
_mark(conn, "019_debug_run_placement")
|
||||
seed_generation_instructions(conn)
|
||||
seed_generation_instructions(conn)
|
||||
from writing_profile_store import bootstrap_from_existing
|
||||
|
||||
bootstrap_from_existing()
|
||||
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Wait for PostgreSQL, load schema.sql, apply numbered SQL migrations. Fail-fast."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from sql_compat import postgres_connect_kwargs, split_sql, sqlite_schema_to_postgres, use_postgres
|
||||
|
||||
SCHEMA_PATH = Path(__file__).resolve().parent / "schema.sql"
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parent / "migrations"
|
||||
SQLITE_HISTORY_MIGRATIONS = (
|
||||
"001_frame",
|
||||
"002_platform",
|
||||
"003_dialogue_memory",
|
||||
"004_mvp_journal",
|
||||
"005_provider_settings",
|
||||
"006_writing_profile_dialogue_style",
|
||||
"007_journal_day_scratch",
|
||||
"008_journal_source_refs",
|
||||
"009_conversation_signals",
|
||||
"010_profile_governance",
|
||||
"011_profile_review",
|
||||
"012_profile_shell",
|
||||
"013_journal_generate_narration",
|
||||
"014_identity_registry",
|
||||
"015_journal_generation_settings",
|
||||
"016_generation_instruction_fragments",
|
||||
"017_generation_guidelines",
|
||||
"018_debug_runs",
|
||||
"019_debug_run_placement",
|
||||
"020_voice_style_context",
|
||||
"021_voice_legacy_immutable",
|
||||
)
|
||||
_LEADING_DIGITS = re.compile(r"^(\d{3})_.*\.sql$")
|
||||
_schema_ready = False
|
||||
|
||||
|
||||
def mark_schema_dirty() -> None:
|
||||
"""Call after DROP SCHEMA so the next init_db reloads schema.sql."""
|
||||
global _schema_ready
|
||||
_schema_ready = False
|
||||
|
||||
|
||||
def _connect_raw():
|
||||
import psycopg
|
||||
|
||||
kwargs = postgres_connect_kwargs()
|
||||
if "conninfo" in kwargs:
|
||||
return psycopg.connect(kwargs["conninfo"], autocommit=False)
|
||||
return psycopg.connect(autocommit=False, **kwargs)
|
||||
|
||||
|
||||
def wait_for_postgres(max_retries: int = 30) -> None:
|
||||
print("Checking PostgreSQL connection...")
|
||||
last_error = None
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
conn = _connect_raw()
|
||||
conn.close()
|
||||
print("PostgreSQL ready")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001 — fail-fast after retries
|
||||
last_error = exc
|
||||
print(f" waiting ({attempt}/{max_retries})")
|
||||
time.sleep(2)
|
||||
print(f"PostgreSQL not ready: {last_error}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def _table_exists(conn, name: str) -> bool:
|
||||
row = conn.execute(
|
||||
"""
|
||||
SELECT 1 FROM information_schema.tables
|
||||
WHERE table_schema = 'public' AND table_name = %s
|
||||
""",
|
||||
(name,),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
|
||||
def _load_schema(conn) -> None:
|
||||
sql = sqlite_schema_to_postgres(SCHEMA_PATH.read_text(encoding="utf-8"))
|
||||
for statement in split_sql(sql):
|
||||
conn.execute(statement)
|
||||
print("Schema loaded from schema.sql (Postgres dialect)")
|
||||
|
||||
|
||||
def _applied_ids(conn) -> set[str]:
|
||||
rows = conn.execute("SELECT id FROM schema_migrations").fetchall()
|
||||
return {row[0] for row in rows}
|
||||
|
||||
|
||||
def _record(conn, migration_id: str) -> None:
|
||||
conn.execute(
|
||||
"INSERT INTO schema_migrations (id) VALUES (%s) ON CONFLICT (id) DO NOTHING",
|
||||
(migration_id,),
|
||||
)
|
||||
|
||||
|
||||
def _migration_files() -> list[tuple[str, Path]]:
|
||||
if not MIGRATIONS_DIR.is_dir():
|
||||
return []
|
||||
rows: list[tuple[str, Path]] = []
|
||||
for path in sorted(MIGRATIONS_DIR.iterdir()):
|
||||
match = _LEADING_DIGITS.match(path.name)
|
||||
if not match or path.suffix != ".sql":
|
||||
continue
|
||||
rows.append((path.stem, path))
|
||||
return rows
|
||||
|
||||
|
||||
def apply_schema_and_migrations() -> None:
|
||||
conn = _connect_raw()
|
||||
try:
|
||||
if not _table_exists(conn, "schema_migrations"):
|
||||
_load_schema(conn)
|
||||
conn.commit()
|
||||
applied = _applied_ids(conn)
|
||||
if "001_frame" not in applied:
|
||||
for migration_id in SQLITE_HISTORY_MIGRATIONS:
|
||||
_record(conn, migration_id)
|
||||
conn.commit()
|
||||
print("Recorded SQLite history 001-021 as applied (greenfield Postgres schema)")
|
||||
applied = _applied_ids(conn)
|
||||
for stem, path in _migration_files():
|
||||
if stem in applied:
|
||||
continue
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
for statement in split_sql(sql):
|
||||
conn.execute(statement)
|
||||
_record(conn, stem)
|
||||
conn.commit()
|
||||
print(f"Applied migration {stem}")
|
||||
except Exception as exc:
|
||||
conn.rollback()
|
||||
print(f"Database initialization failed: {exc}")
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def ensure_postgres_ready() -> None:
|
||||
global _schema_ready
|
||||
if not use_postgres():
|
||||
return
|
||||
if _schema_ready:
|
||||
return
|
||||
wait_for_postgres()
|
||||
try:
|
||||
apply_schema_and_migrations()
|
||||
except Exception:
|
||||
sys.exit(1)
|
||||
_schema_ready = True
|
||||
|
||||
|
||||
def main() -> None:
|
||||
os.environ.setdefault("KANSHO_DB_BACKEND", "postgres")
|
||||
ensure_postgres_ready()
|
||||
print("db_init complete")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+56
-9
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
import uuid
|
||||
@@ -36,6 +37,8 @@ LAYER_FOR_PURPOSE = {
|
||||
"journal_reconstruct": "journalrekonstruktion",
|
||||
"profile_review": "profilreview",
|
||||
}
|
||||
SANITIZE_MAX_DEPTH = 80
|
||||
LOGGER = logging.getLogger("kansho.debug")
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
@@ -78,18 +81,26 @@ def should_persist(profile_id: str | None) -> bool:
|
||||
return persist_enabled() and _is_admin(profile_id)
|
||||
|
||||
|
||||
def sanitize(value: Any) -> Any:
|
||||
def sanitize(value: Any, *, _stack: set[int] | None = None, _depth: int = 0) -> Any:
|
||||
if _depth > SANITIZE_MAX_DEPTH:
|
||||
return None
|
||||
if isinstance(value, (dict, list, tuple)):
|
||||
stack = _stack if _stack is not None else set()
|
||||
ident = id(value)
|
||||
if ident in stack:
|
||||
return None
|
||||
stack.add(ident)
|
||||
try:
|
||||
if isinstance(value, dict):
|
||||
cleaned = {}
|
||||
for key, item in value.items():
|
||||
if key in FORBIDDEN_KEYS:
|
||||
continue
|
||||
cleaned[key] = sanitize(item)
|
||||
cleaned[key] = sanitize(item, _stack=stack, _depth=_depth + 1)
|
||||
return cleaned
|
||||
if isinstance(value, list):
|
||||
return [sanitize(item) for item in value]
|
||||
if isinstance(value, tuple):
|
||||
return [sanitize(item) for item in value]
|
||||
return [sanitize(item, _stack=stack, _depth=_depth + 1) for item in value]
|
||||
finally:
|
||||
stack.discard(ident)
|
||||
return value
|
||||
|
||||
|
||||
@@ -251,12 +262,42 @@ def persist_engine_error(
|
||||
journal_day_id: str | None = None,
|
||||
extra: dict | None = None,
|
||||
) -> str | None:
|
||||
try:
|
||||
diag = dict(getattr(exc, "diagnostics", None) or {})
|
||||
merged = dict(extra or {})
|
||||
merged.setdefault("code", getattr(exc, "code", None))
|
||||
merged.setdefault("message", getattr(exc, "message", None) or str(exc))
|
||||
if diag.get("log") is not None:
|
||||
merged.setdefault("run_log", diag.get("log"))
|
||||
log = diag.get("log")
|
||||
if log is not None:
|
||||
merged.setdefault("run_log", list(log) if isinstance(log, list) else log)
|
||||
trace = diag.get("trace") if isinstance(diag.get("trace"), dict) else {}
|
||||
try:
|
||||
from privacy_gateway import compact_diagnostics, public_cost_report
|
||||
|
||||
compact = compact_diagnostics({**diag, **trace, **merged})
|
||||
for key, value in compact.items():
|
||||
merged.setdefault(key, value)
|
||||
merged.setdefault("cost_report", public_cost_report({**diag, **merged}))
|
||||
except Exception:
|
||||
LOGGER.exception("Kompakte Fehlerdiagnose konnte nicht erzeugt werden.")
|
||||
for key in (
|
||||
"generation_selection",
|
||||
"style_application",
|
||||
"abort_reason",
|
||||
"detect_attempts",
|
||||
"detect_passes",
|
||||
"detect_partial_discarded",
|
||||
"contract_violation",
|
||||
"invalid_entity_type",
|
||||
"omitted_non_identity_types",
|
||||
"generate_called",
|
||||
):
|
||||
if merged.get(key) is None:
|
||||
if diag.get(key) is not None:
|
||||
merged[key] = diag.get(key)
|
||||
elif trace.get(key) is not None:
|
||||
merged[key] = trace.get(key)
|
||||
merged.setdefault("generate_called", False)
|
||||
return persist_step(
|
||||
profile_id,
|
||||
purpose=purpose,
|
||||
@@ -266,9 +307,15 @@ def persist_engine_error(
|
||||
subject_id=subject_id,
|
||||
conversation_id=conversation_id,
|
||||
journal_day_id=journal_day_id,
|
||||
trace=diag.get("trace"),
|
||||
trace=trace or None,
|
||||
extra=merged,
|
||||
)
|
||||
except Exception:
|
||||
LOGGER.exception(
|
||||
"Diagnosepersistenz fehlgeschlagen; ursprünglicher Fehler bleibt %s",
|
||||
getattr(exc, "code", type(exc).__name__),
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _parse_payload(raw: str | None) -> dict:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,620 @@
|
||||
"""Student-first detect pipeline with optional teacher comparison.
|
||||
|
||||
Cues stay local. OpenRouter/GLiNER never create identities. Compact counters
|
||||
carry no plaintext labels.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from detect_learning import (
|
||||
MODE_LEARNING_MANUAL,
|
||||
MODE_STUDENT,
|
||||
_CUE_BARE,
|
||||
_DECISION_ASK,
|
||||
_DECISION_IDENTITY,
|
||||
_DECISION_NOT,
|
||||
_align_user_span,
|
||||
_mention_fields,
|
||||
_resolve_user_span,
|
||||
_token_for_label,
|
||||
_word_matches,
|
||||
apply_learned_decisions,
|
||||
auto_resolve_ambiguous,
|
||||
cue_for_mention,
|
||||
decision_for_mention,
|
||||
get_cue_decision,
|
||||
get_detect_operating_mode,
|
||||
get_local_ner_settings,
|
||||
get_sense,
|
||||
is_bypass_mode,
|
||||
is_learning_mode,
|
||||
learning_stage,
|
||||
merge_gliner_candidates,
|
||||
record_cue,
|
||||
supplement_kinship_candidates,
|
||||
)
|
||||
from entity_detect import DetectError, detect_personal_egress
|
||||
from identity_store import ENTITY_TYPES, is_maskable_label
|
||||
|
||||
KIND_DIFF = "diff"
|
||||
KIND_MANUAL = "manual"
|
||||
KIND_CONFIRM_REMOTE = "confirm_remote"
|
||||
|
||||
PROTECTING_TYPES = set(ENTITY_TYPES)
|
||||
FOOD_TYPES = frozenset(
|
||||
{"FOOD", "DISH", "MEAL", "CUISINE", "FOODSTUFF", "INGREDIENT", "food", "dish"}
|
||||
)
|
||||
TYPE_MAP = {
|
||||
"person": "PERSON",
|
||||
"place": "PLACE",
|
||||
"org": "ORG",
|
||||
"organization": "ORG",
|
||||
"project": "PROJECT",
|
||||
"food": "FOOD",
|
||||
"dish": "DISH",
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class MentionSpan:
|
||||
text: str
|
||||
start: int
|
||||
end: int
|
||||
entity_type: str
|
||||
protection: str
|
||||
source: str
|
||||
confirmed_cue: bool = False
|
||||
cue: str = _CUE_BARE
|
||||
|
||||
def key(self) -> tuple[int, int, str]:
|
||||
return (self.start, self.end, self.text.casefold())
|
||||
|
||||
|
||||
@dataclass
|
||||
class StudentResult:
|
||||
mappings: list[dict] = field(default_factory=list)
|
||||
candidates: list[dict] = field(default_factory=list)
|
||||
spans: list[MentionSpan] = field(default_factory=list)
|
||||
gliner_missing: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class TeacherResult:
|
||||
spans: list[MentionSpan] = field(default_factory=list)
|
||||
mappings: list[dict] = field(default_factory=list)
|
||||
ok: bool = True
|
||||
error: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class PipelineResult:
|
||||
mappings: list[dict]
|
||||
candidates: list[dict]
|
||||
kind: str = KIND_DIFF
|
||||
need_review: bool = False
|
||||
need_remote_confirm: bool = False
|
||||
counters: dict[str, int] = field(default_factory=dict)
|
||||
mode: str = ""
|
||||
|
||||
|
||||
def empty_counters() -> dict[str, int]:
|
||||
return {
|
||||
"diff_agree": 0,
|
||||
"diff_only_student": 0,
|
||||
"diff_only_teacher": 0,
|
||||
"diff_type_conflict": 0,
|
||||
"diff_new_identity": 0,
|
||||
"diff_cue_reinforced": 0,
|
||||
}
|
||||
|
||||
|
||||
def map_entity_type(raw: str) -> str:
|
||||
token = (raw or "").strip()
|
||||
if token.upper() in PROTECTING_TYPES or token.upper() in {item.upper() for item in FOOD_TYPES}:
|
||||
mapped = TYPE_MAP.get(token.lower())
|
||||
return mapped or token.upper()
|
||||
return TYPE_MAP.get(token.lower()) or token.upper()
|
||||
|
||||
|
||||
def protects(entity_type: str) -> bool:
|
||||
kind = map_entity_type(entity_type)
|
||||
if kind in FOOD_TYPES or kind.upper() in {item.upper() for item in FOOD_TYPES}:
|
||||
return False
|
||||
return kind in PROTECTING_TYPES
|
||||
|
||||
|
||||
def types_equivalent(left: str, right: str) -> bool:
|
||||
a, b = map_entity_type(left), map_entity_type(right)
|
||||
if a in FOOD_TYPES or b in FOOD_TYPES or a in {"FOOD", "DISH"} or b in {"FOOD", "DISH"}:
|
||||
return a == b
|
||||
if protects(a) and protects(b):
|
||||
return True
|
||||
return a == b
|
||||
|
||||
|
||||
def _contains(outer: MentionSpan, inner: MentionSpan) -> bool:
|
||||
return outer.start <= inner.start and inner.end <= outer.end and outer.end > outer.start
|
||||
|
||||
|
||||
def same_mention(left: MentionSpan, right: MentionSpan) -> bool:
|
||||
if left.text.casefold() == right.text.casefold() and left.start == right.start and left.end == right.end:
|
||||
return True
|
||||
if _contains(left, right) or _contains(right, left):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _collapse_same_protection(spans: list[MentionSpan]) -> list[MentionSpan]:
|
||||
if not spans:
|
||||
return []
|
||||
remaining = list(spans)
|
||||
chosen: list[MentionSpan] = []
|
||||
while remaining:
|
||||
current = remaining.pop(0)
|
||||
cluster = [current]
|
||||
rest = []
|
||||
for item in remaining:
|
||||
if same_mention(current, item):
|
||||
cluster.append(item)
|
||||
else:
|
||||
rest.append(item)
|
||||
remaining = rest
|
||||
protections = {item.protection for item in cluster}
|
||||
if len(protections) > 1:
|
||||
chosen.extend(cluster)
|
||||
continue
|
||||
chosen.append(max(cluster, key=lambda item: (item.end - item.start, -item.start)))
|
||||
return chosen
|
||||
|
||||
|
||||
def _user_span_for_mapping(mapping: dict, user_body: str, rendered: str = "") -> tuple[int, int] | None:
|
||||
return _resolve_user_span(
|
||||
user_body,
|
||||
mapping.get("start"),
|
||||
mapping.get("end"),
|
||||
mapping.get("local_label") or "",
|
||||
rendered,
|
||||
)
|
||||
|
||||
|
||||
def _mapping_from_user_span(
|
||||
mappings: list[dict],
|
||||
label: str,
|
||||
user_body: str,
|
||||
start: int,
|
||||
end: int,
|
||||
entity_type: str,
|
||||
rendered: str,
|
||||
) -> dict:
|
||||
aligned = _align_user_span(rendered, user_body, start, end)
|
||||
kind = entity_type if entity_type in ENTITY_TYPES else "PERSON"
|
||||
return {
|
||||
"token": _token_for_label(mappings, label, kind),
|
||||
"local_label": label,
|
||||
"canonical_label": label,
|
||||
"demask_label": label,
|
||||
"entity_type": kind,
|
||||
"source": "request_local",
|
||||
"start": aligned[0],
|
||||
"end": aligned[1],
|
||||
"aliases": [],
|
||||
"labels": [label],
|
||||
}
|
||||
|
||||
|
||||
def run_student_path(profile_id: str, user_body: str, rendered: str = "") -> StudentResult:
|
||||
mappings: list[dict] = []
|
||||
candidates: list[dict] = []
|
||||
spans: list[MentionSpan] = []
|
||||
text = user_body or ""
|
||||
for match in _word_matches(text):
|
||||
label = match.group(0)
|
||||
if not is_maskable_label(label):
|
||||
continue
|
||||
start, end = match.start(), match.end()
|
||||
verdict = decision_for_mention(profile_id, label, text, start, end, rendered)
|
||||
cue = cue_for_mention(text, start, end, label, rendered)
|
||||
if verdict == _DECISION_IDENTITY:
|
||||
mappings.append(_mapping_from_user_span(mappings, label, text, start, end, "PERSON", rendered))
|
||||
spans.append(
|
||||
MentionSpan(label, start, end, "PERSON", _DECISION_IDENTITY, "cue", True, cue)
|
||||
)
|
||||
elif verdict == _DECISION_NOT:
|
||||
spans.append(
|
||||
MentionSpan(label, start, end, "FOOD", _DECISION_NOT, "cue", True, cue)
|
||||
)
|
||||
elif get_sense(profile_id, label)["ambiguous"]:
|
||||
aligned = _align_user_span(rendered, text, start, end)
|
||||
candidates.append(
|
||||
{
|
||||
"id": str(uuid.uuid4()),
|
||||
"text": label,
|
||||
"entity_type": "PERSON",
|
||||
"start": aligned[0],
|
||||
"end": aligned[1],
|
||||
**_mention_fields(text, start, end, label, rendered),
|
||||
"ambiguous": True,
|
||||
}
|
||||
)
|
||||
candidates, mappings = supplement_kinship_candidates(
|
||||
profile_id, candidates, mappings, text, rendered
|
||||
)
|
||||
candidates, mappings = auto_resolve_ambiguous(profile_id, candidates, mappings)
|
||||
bound = {(span.start, span.end, span.text.casefold()) for span in spans}
|
||||
for item in candidates:
|
||||
resolved = _resolve_user_span(
|
||||
text,
|
||||
item.get("user_start", item.get("start")),
|
||||
item.get("user_end", item.get("end")),
|
||||
item.get("text") or "",
|
||||
rendered,
|
||||
)
|
||||
if resolved:
|
||||
bound.add((resolved[0], resolved[1], (item.get("text") or "").casefold()))
|
||||
settings = get_local_ner_settings()
|
||||
gliner_missing = False
|
||||
if settings.get("enabled"):
|
||||
from gliner_client import extract_entities
|
||||
|
||||
raw = extract_entities(text, url=settings.get("url"))
|
||||
if raw is None:
|
||||
gliner_missing = True
|
||||
else:
|
||||
usable = []
|
||||
for item in raw:
|
||||
try:
|
||||
start, end = int(item["start"]), int(item["end"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
label = (item.get("text") or "").casefold()
|
||||
if any(
|
||||
not (end <= left or start >= right) and folded == label
|
||||
for left, right, folded in bound
|
||||
) or any(left <= start and end <= right for left, right, _folded in bound):
|
||||
continue
|
||||
usable.append(item)
|
||||
candidates, mappings = merge_gliner_candidates(
|
||||
profile_id, candidates, mappings, text, rendered, usable
|
||||
)
|
||||
candidates, mappings = apply_learned_decisions(profile_id, candidates, mappings, text, rendered)
|
||||
for item in candidates:
|
||||
resolved = _resolve_user_span(
|
||||
text,
|
||||
item.get("user_start", item.get("start")),
|
||||
item.get("user_end", item.get("end")),
|
||||
item.get("text") or "",
|
||||
rendered,
|
||||
)
|
||||
if not resolved:
|
||||
continue
|
||||
suggested = item.get("suggested") or _DECISION_IDENTITY
|
||||
kind = item.get("entity_type") or "PERSON"
|
||||
protection = _DECISION_NOT if suggested == _DECISION_NOT else _DECISION_IDENTITY
|
||||
entity = "FOOD" if protection == _DECISION_NOT else kind
|
||||
spans.append(
|
||||
MentionSpan(
|
||||
item.get("text") or "",
|
||||
resolved[0],
|
||||
resolved[1],
|
||||
entity,
|
||||
protection,
|
||||
"candidate",
|
||||
False,
|
||||
item.get("cue") or _CUE_BARE,
|
||||
)
|
||||
)
|
||||
return StudentResult(
|
||||
mappings=mappings,
|
||||
candidates=candidates,
|
||||
spans=_collapse_same_protection(spans),
|
||||
gliner_missing=gliner_missing,
|
||||
)
|
||||
|
||||
|
||||
def blank_cue_safe_forms(profile_id: str, user_body: str, rendered: str = "") -> str:
|
||||
chars = list(user_body or "")
|
||||
for match in _word_matches(user_body or ""):
|
||||
label = match.group(0)
|
||||
if not is_maskable_label(label):
|
||||
continue
|
||||
verdict = decision_for_mention(
|
||||
profile_id, label, user_body, match.start(), match.end(), rendered
|
||||
)
|
||||
if verdict not in {_DECISION_IDENTITY, _DECISION_NOT}:
|
||||
continue
|
||||
for index in range(match.start(), match.end()):
|
||||
chars[index] = " "
|
||||
return "".join(chars)
|
||||
|
||||
|
||||
def _teacher_span(label: str, start: int, end: int, entity_type: str) -> MentionSpan:
|
||||
kind = map_entity_type(entity_type)
|
||||
protection = _DECISION_IDENTITY if protects(kind) else _DECISION_NOT
|
||||
return MentionSpan(label, start, end, kind, protection, "teacher", False)
|
||||
|
||||
|
||||
def run_teacher(
|
||||
profile_id: str,
|
||||
user_body: str,
|
||||
*,
|
||||
stage: int = 1,
|
||||
rendered: str = "",
|
||||
) -> TeacherResult:
|
||||
source = user_body or ""
|
||||
if stage >= 2:
|
||||
source = blank_cue_safe_forms(profile_id, user_body, rendered)
|
||||
try:
|
||||
outcome = detect_personal_egress(profile_id, source)
|
||||
except DetectError as exc:
|
||||
return TeacherResult(ok=False, error=exc.code)
|
||||
spans: list[MentionSpan] = []
|
||||
for mapping in outcome.mappings or []:
|
||||
label = mapping.get("local_label") or ""
|
||||
start, end = mapping.get("start"), mapping.get("end")
|
||||
resolved = None
|
||||
if start is not None and end is not None:
|
||||
left, right = int(start), int(end)
|
||||
if 0 <= left < right <= len(user_body) and user_body[left:right].casefold() == label.casefold():
|
||||
resolved = (left, right)
|
||||
if not resolved:
|
||||
resolved = _resolve_user_span(user_body, start, end, label, user_body)
|
||||
if not resolved:
|
||||
continue
|
||||
spans.append(
|
||||
_teacher_span(label, resolved[0], resolved[1], mapping.get("entity_type") or "PERSON")
|
||||
)
|
||||
omitted = list((outcome.stats.omitted_non_identity_types or []) if outcome.stats else [])
|
||||
for kind in omitted:
|
||||
if map_entity_type(kind) in FOOD_TYPES or kind.upper() in {"FOOD", "DISH"}:
|
||||
continue
|
||||
return TeacherResult(spans=_collapse_same_protection(spans), mappings=list(outcome.mappings or []), ok=True)
|
||||
|
||||
|
||||
def _candidate_from_span(
|
||||
span: MentionSpan,
|
||||
user_body: str,
|
||||
rendered: str,
|
||||
*,
|
||||
suggested: str,
|
||||
reason: str,
|
||||
) -> dict:
|
||||
aligned = _align_user_span(rendered, user_body, span.start, span.end)
|
||||
kind = span.entity_type if span.entity_type in ENTITY_TYPES else "PERSON"
|
||||
return {
|
||||
"id": str(uuid.uuid4()),
|
||||
"text": span.text,
|
||||
"entity_type": kind,
|
||||
"start": aligned[0],
|
||||
"end": aligned[1],
|
||||
**_mention_fields(user_body, span.start, span.end, span.text, rendered),
|
||||
"ambiguous": False,
|
||||
"suggested": suggested,
|
||||
"reason": reason,
|
||||
}
|
||||
|
||||
|
||||
def compare_mentions(
|
||||
profile_id: str,
|
||||
user_body: str,
|
||||
student_spans: list[MentionSpan],
|
||||
teacher_spans: list[MentionSpan],
|
||||
rendered: str = "",
|
||||
) -> tuple[list[dict], dict[str, int]]:
|
||||
counters = empty_counters()
|
||||
review: list[dict] = []
|
||||
used_teacher: set[int] = set()
|
||||
student_list = _collapse_same_protection(student_spans)
|
||||
teacher_list = _collapse_same_protection(teacher_spans)
|
||||
|
||||
def take_teacher(index: int) -> MentionSpan:
|
||||
used_teacher.add(index)
|
||||
return teacher_list[index]
|
||||
|
||||
for student in student_list:
|
||||
match_index = next(
|
||||
(
|
||||
index
|
||||
for index, teacher in enumerate(teacher_list)
|
||||
if index not in used_teacher and same_mention(student, teacher)
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match_index is None:
|
||||
counters["diff_only_student"] += 1
|
||||
if student.confirmed_cue:
|
||||
continue
|
||||
if student.protection == _DECISION_IDENTITY:
|
||||
counters["diff_new_identity"] += 1
|
||||
review.append(
|
||||
_candidate_from_span(
|
||||
student, user_body, rendered, suggested=_DECISION_IDENTITY, reason="only_student"
|
||||
)
|
||||
)
|
||||
continue
|
||||
teacher = take_teacher(match_index)
|
||||
if student.protection != teacher.protection or (
|
||||
protects(student.entity_type) != protects(teacher.entity_type)
|
||||
):
|
||||
counters["diff_type_conflict"] += 1
|
||||
if student.confirmed_cue:
|
||||
continue
|
||||
review.append(
|
||||
_candidate_from_span(
|
||||
student,
|
||||
user_body,
|
||||
rendered,
|
||||
suggested=student.protection,
|
||||
reason="type_conflict",
|
||||
)
|
||||
)
|
||||
continue
|
||||
if types_equivalent(student.entity_type, teacher.entity_type) or (
|
||||
student.protection == teacher.protection
|
||||
):
|
||||
counters["diff_agree"] += 1
|
||||
if student.confirmed_cue:
|
||||
record_cue(profile_id, student.text, student.cue, student.protection)
|
||||
counters["diff_cue_reinforced"] += 1
|
||||
elif student.protection == _DECISION_IDENTITY:
|
||||
learned = get_cue_decision(profile_id, student.text, student.cue)
|
||||
if learned == _DECISION_IDENTITY:
|
||||
record_cue(profile_id, student.text, student.cue, _DECISION_IDENTITY)
|
||||
counters["diff_cue_reinforced"] += 1
|
||||
else:
|
||||
counters["diff_new_identity"] += 1
|
||||
review.append(
|
||||
_candidate_from_span(
|
||||
student, user_body, rendered, suggested=_DECISION_IDENTITY, reason="new_identity"
|
||||
)
|
||||
)
|
||||
for index, teacher in enumerate(teacher_list):
|
||||
if index in used_teacher:
|
||||
continue
|
||||
counters["diff_only_teacher"] += 1
|
||||
cue = cue_for_mention(user_body, teacher.start, teacher.end, teacher.text, rendered)
|
||||
learned = get_cue_decision(profile_id, teacher.text, cue)
|
||||
if learned:
|
||||
continue
|
||||
if teacher.protection == _DECISION_IDENTITY:
|
||||
counters["diff_new_identity"] += 1
|
||||
review.append(
|
||||
_candidate_from_span(
|
||||
teacher, user_body, rendered, suggested=_DECISION_IDENTITY, reason="only_teacher"
|
||||
)
|
||||
)
|
||||
return review, counters
|
||||
|
||||
|
||||
def _remote_confirm_candidate(user_body: str) -> dict:
|
||||
snippet = (user_body or "")[:80]
|
||||
return {
|
||||
"id": str(uuid.uuid4()),
|
||||
"text": "Klartext-Detect",
|
||||
"entity_type": "PERSON",
|
||||
"start": 0,
|
||||
"end": 0,
|
||||
"excerpt": snippet,
|
||||
"highlight_start": None,
|
||||
"highlight_end": None,
|
||||
"user_start": None,
|
||||
"user_end": None,
|
||||
"cue": _CUE_BARE,
|
||||
"ambiguous": False,
|
||||
"suggested": _DECISION_NOT,
|
||||
"reason": KIND_CONFIRM_REMOTE,
|
||||
}
|
||||
|
||||
|
||||
def prepare_detect_pipeline(profile_id: str, user_body: str, rendered: str = "") -> PipelineResult:
|
||||
mode = get_detect_operating_mode()
|
||||
counters = empty_counters()
|
||||
if is_bypass_mode(mode):
|
||||
return PipelineResult(mappings=[], candidates=[], kind=KIND_DIFF, mode=mode, counters=counters)
|
||||
student = run_student_path(profile_id, user_body, rendered)
|
||||
if mode == MODE_STUDENT:
|
||||
if student.gliner_missing:
|
||||
return PipelineResult(
|
||||
mappings=student.mappings,
|
||||
candidates=[_remote_confirm_candidate(user_body)],
|
||||
kind=KIND_CONFIRM_REMOTE,
|
||||
need_review=True,
|
||||
need_remote_confirm=True,
|
||||
counters=counters,
|
||||
mode=mode,
|
||||
)
|
||||
return PipelineResult(
|
||||
mappings=student.mappings,
|
||||
candidates=[],
|
||||
kind=KIND_DIFF,
|
||||
counters=counters,
|
||||
mode=mode,
|
||||
)
|
||||
if mode == MODE_LEARNING_MANUAL or student.gliner_missing:
|
||||
return PipelineResult(
|
||||
mappings=student.mappings,
|
||||
candidates=student.candidates,
|
||||
kind=KIND_MANUAL,
|
||||
need_review=bool(student.candidates),
|
||||
counters=counters,
|
||||
mode=mode,
|
||||
)
|
||||
teacher = run_teacher(profile_id, user_body, stage=learning_stage(mode), rendered=rendered)
|
||||
if not teacher.ok:
|
||||
return PipelineResult(
|
||||
mappings=student.mappings,
|
||||
candidates=student.candidates,
|
||||
kind=KIND_MANUAL,
|
||||
need_review=bool(student.candidates),
|
||||
counters=counters,
|
||||
mode=mode,
|
||||
)
|
||||
review, counters = compare_mentions(
|
||||
profile_id, user_body, student.spans, teacher.spans, rendered
|
||||
)
|
||||
merged = list(student.mappings)
|
||||
seen = {
|
||||
(
|
||||
item.get("start"),
|
||||
item.get("end"),
|
||||
(item.get("local_label") or "").casefold(),
|
||||
)
|
||||
for item in merged
|
||||
}
|
||||
for mapping in teacher.mappings:
|
||||
key = (mapping.get("start"), mapping.get("end"), (mapping.get("local_label") or "").casefold())
|
||||
if key in seen:
|
||||
continue
|
||||
label = mapping.get("local_label") or ""
|
||||
resolved = _resolve_user_span(
|
||||
user_body, mapping.get("start"), mapping.get("end"), label, user_body
|
||||
)
|
||||
if resolved:
|
||||
cue = cue_for_mention(user_body, resolved[0], resolved[1], label, rendered)
|
||||
if get_cue_decision(profile_id, label, cue) == _DECISION_NOT:
|
||||
continue
|
||||
merged.append(mapping)
|
||||
seen.add(key)
|
||||
return PipelineResult(
|
||||
mappings=merged,
|
||||
candidates=review,
|
||||
kind=KIND_DIFF,
|
||||
need_review=bool(review),
|
||||
counters=counters,
|
||||
mode=mode,
|
||||
)
|
||||
|
||||
|
||||
def compact_diff_counters(counters: dict[str, int] | None) -> dict[str, int]:
|
||||
payload = empty_counters()
|
||||
for key in payload:
|
||||
payload[key] = int((counters or {}).get(key) or 0)
|
||||
return payload
|
||||
|
||||
|
||||
def apply_remote_confirm(profile_id: str, pending: dict, decisions: list[dict]) -> list[dict]:
|
||||
"""After the user allows plaintext detect, run teacher on the user line."""
|
||||
approved = any((item.get("decision") or "").strip() == _DECISION_IDENTITY for item in decisions)
|
||||
if not approved:
|
||||
raise DetectError(
|
||||
"remote_detect_declined",
|
||||
"Klartext-Detect wurde nicht bestätigt.",
|
||||
403,
|
||||
)
|
||||
user_body = pending.get("user_body") or ""
|
||||
teacher = run_teacher(profile_id, user_body, stage=1)
|
||||
if not teacher.ok:
|
||||
raise DetectError(teacher.error or "detect_provider_unavailable", "Lehrer-Detect ist nicht erreichbar.")
|
||||
merged = list(pending.get("mappings") or [])
|
||||
seen = {
|
||||
(item.get("start"), item.get("end"), (item.get("local_label") or "").casefold())
|
||||
for item in merged
|
||||
}
|
||||
for mapping in teacher.mappings:
|
||||
key = (mapping.get("start"), mapping.get("end"), (mapping.get("local_label") or "").casefold())
|
||||
if key in seen:
|
||||
continue
|
||||
merged.append(mapping)
|
||||
seen.add(key)
|
||||
return merged
|
||||
@@ -339,7 +339,7 @@ def list_conversations_for_day(profile_id: str, journal_day_id: str) -> list[dic
|
||||
(SELECT COUNT(*) FROM messages m WHERE m.conversation_id = c.id) AS message_count
|
||||
FROM conversations c
|
||||
WHERE c.profile_id = ? AND c.journal_day_id = ?
|
||||
ORDER BY c.created, c.rowid
|
||||
ORDER BY c.created, c.id
|
||||
""",
|
||||
(profile_id, journal_day_id),
|
||||
).fetchall()
|
||||
|
||||
+144
-23
@@ -7,9 +7,19 @@ import re
|
||||
from context_builder import assemble_text, build_internal_context, is_closing_turn
|
||||
from conversation_signals import infer_signals
|
||||
from debug_store import persist_engine_error, persist_step
|
||||
from detect_learning import (
|
||||
apply_review_decisions,
|
||||
confirm_known_identity_spans,
|
||||
drop_pending,
|
||||
is_bypass_mode,
|
||||
load_pending,
|
||||
save_pending,
|
||||
suppress_known_non_identity,
|
||||
)
|
||||
from detect_pipeline import KIND_CONFIRM_REMOTE, prepare_detect_pipeline
|
||||
from dialogue_store import append_message, get_conversation, list_messages, update_conversation_signals
|
||||
from engine import EngineError, execute_prompt, load_active_prompt
|
||||
from entity_detect import DETECT_DIALOGUE_FALLBACK_CODES
|
||||
from engine import EngineError, execute_prompt, load_active_prompt, preview_prompt
|
||||
from entity_detect import DETECT_DIALOGUE_FALLBACK_CODES, DetectError
|
||||
from writing_profile_store import remember_dialogue_style
|
||||
from profile_review import consider_dialogue
|
||||
|
||||
@@ -302,23 +312,22 @@ def visible_for_role(payload: dict, role: str | None) -> dict:
|
||||
return cleaned
|
||||
|
||||
|
||||
def run_turn(profile_id: str, conversation_id: str, body: str, message_id: str | None = None) -> dict:
|
||||
conversation = get_conversation(profile_id, conversation_id)
|
||||
user = append_message(profile_id, conversation_id, body, role="user", message_id=message_id)
|
||||
context = build_internal_context(
|
||||
profile_id,
|
||||
conversation_id=conversation_id,
|
||||
space_id=conversation.get("space_id"),
|
||||
journal_day_id=conversation.get("journal_day_id"),
|
||||
purpose="dialogue_turn",
|
||||
)
|
||||
assembled = assemble_text(context)
|
||||
prompt = load_active_prompt("mvp.dialogue_turn")
|
||||
def _finish_turn(
|
||||
profile_id: str,
|
||||
conversation_id: str,
|
||||
user: dict,
|
||||
assembled: dict,
|
||||
prompt: dict,
|
||||
*,
|
||||
precomputed_mappings: list[dict] | None = None,
|
||||
) -> dict:
|
||||
calls = 0
|
||||
result = None
|
||||
impulse = ""
|
||||
decision: dict = {"operation": "unparsed", "label": "nicht erkannt", "parsed": False}
|
||||
call_traces: list[dict] = []
|
||||
working = dict(assembled)
|
||||
working["user_body"] = user.get("body") or working.get("user_body") or ""
|
||||
try:
|
||||
while calls < 2:
|
||||
result = execute_prompt(
|
||||
@@ -326,7 +335,8 @@ def run_turn(profile_id: str, conversation_id: str, body: str, message_id: str |
|
||||
profile_id,
|
||||
purpose="dialogue_turn",
|
||||
data_class="B",
|
||||
context=assembled,
|
||||
context=working,
|
||||
precomputed_mappings=precomputed_mappings if calls == 0 else None,
|
||||
)
|
||||
calls += 1
|
||||
if result.get("trace"):
|
||||
@@ -335,16 +345,16 @@ def run_turn(profile_id: str, conversation_id: str, body: str, message_id: str |
|
||||
if not content:
|
||||
raise EngineError("empty_provider_response", "Der Provider lieferte keine Antwort.")
|
||||
impulse, decision = parse_turn_payload(content)
|
||||
if not needs_repair(impulse, assembled):
|
||||
if not needs_repair(impulse, working):
|
||||
break
|
||||
decision = {**decision, "guard": "impulse_rejected"}
|
||||
assembled = dict(assembled)
|
||||
assembled["dialogue_context"] = (
|
||||
(assembled.get("dialogue_context") or "") + "\n\n" + repair_note(impulse, assembled)
|
||||
working = dict(working)
|
||||
working["dialogue_context"] = (
|
||||
(working.get("dialogue_context") or "") + "\n\n" + repair_note(impulse, working)
|
||||
)
|
||||
if needs_repair(impulse, assembled):
|
||||
if needs_repair(impulse, working):
|
||||
parsed_ok = bool(decision.get("parsed"))
|
||||
impulse = local_hold(last_user_text(assembled))
|
||||
impulse = local_hold(last_user_text(working))
|
||||
decision = {
|
||||
"operation": "fortfuehren",
|
||||
"label": OPERATIONS["fortfuehren"],
|
||||
@@ -369,7 +379,7 @@ def run_turn(profile_id: str, conversation_id: str, body: str, message_id: str |
|
||||
},
|
||||
)
|
||||
raise
|
||||
impulse = local_hold(last_user_text(assembled))
|
||||
impulse = local_hold(last_user_text(working))
|
||||
decision = {
|
||||
"operation": "fortfuehren",
|
||||
"label": OPERATIONS["fortfuehren"],
|
||||
@@ -388,7 +398,7 @@ def run_turn(profile_id: str, conversation_id: str, body: str, message_id: str |
|
||||
infer_signals(user_bodies, decision.get("operation")),
|
||||
)
|
||||
remember_dialogue_style(profile_id)
|
||||
consider_dialogue(profile_id, body)
|
||||
consider_dialogue(profile_id, user.get("body") or "")
|
||||
trace = result.get("trace") if result else None
|
||||
persist_step(
|
||||
profile_id,
|
||||
@@ -416,3 +426,114 @@ def run_turn(profile_id: str, conversation_id: str, body: str, message_id: str |
|
||||
"decision": decision,
|
||||
"trace": trace,
|
||||
}
|
||||
|
||||
|
||||
def _review_pause_payload(review_id: str, candidates: list[dict], kind: str, purpose: str = "dialogue_turn") -> dict:
|
||||
return {
|
||||
"id": review_id,
|
||||
"candidates": candidates,
|
||||
"kind": kind,
|
||||
"purpose": purpose,
|
||||
}
|
||||
|
||||
|
||||
def _learning_pause(profile_id: str, conversation_id: str, user: dict, assembled: dict, prompt: dict) -> dict | None:
|
||||
preview = preview_prompt(prompt, assembled)
|
||||
rendered = preview.get("rendered") or ""
|
||||
user_body = user.get("body") or ""
|
||||
result = prepare_detect_pipeline(profile_id, user_body, rendered)
|
||||
mappings = list(result.mappings or [])
|
||||
if not result.need_review and not result.candidates:
|
||||
confirm_known_identity_spans(profile_id, mappings, user_body)
|
||||
mappings = suppress_known_non_identity(profile_id, mappings, user_body)
|
||||
return _finish_turn(
|
||||
profile_id,
|
||||
conversation_id,
|
||||
user,
|
||||
assembled,
|
||||
prompt,
|
||||
precomputed_mappings=mappings,
|
||||
)
|
||||
review_id = save_pending(
|
||||
profile_id,
|
||||
conversation_id,
|
||||
user.get("id") or "",
|
||||
{
|
||||
"mappings": mappings,
|
||||
"candidates": result.candidates,
|
||||
"user_body": user_body,
|
||||
"kind": result.kind,
|
||||
"counters": result.counters,
|
||||
"purpose": "dialogue_turn",
|
||||
},
|
||||
)
|
||||
return {
|
||||
"conversation": get_conversation(profile_id, conversation_id),
|
||||
"user": user,
|
||||
"assistant": None,
|
||||
"calls": 0,
|
||||
"messages": list_messages(profile_id, conversation_id),
|
||||
"pending_mask_review": _review_pause_payload(review_id, result.candidates, result.kind),
|
||||
}
|
||||
|
||||
|
||||
def run_turn(profile_id: str, conversation_id: str, body: str, message_id: str | None = None) -> dict:
|
||||
conversation = get_conversation(profile_id, conversation_id)
|
||||
user = append_message(profile_id, conversation_id, body, role="user", message_id=message_id)
|
||||
context = build_internal_context(
|
||||
profile_id,
|
||||
conversation_id=conversation_id,
|
||||
space_id=conversation.get("space_id"),
|
||||
journal_day_id=conversation.get("journal_day_id"),
|
||||
purpose="dialogue_turn",
|
||||
)
|
||||
assembled = assemble_text(context)
|
||||
prompt = load_active_prompt("mvp.dialogue_turn")
|
||||
if is_bypass_mode():
|
||||
return _finish_turn(profile_id, conversation_id, user, assembled, prompt)
|
||||
paused = _learning_pause(profile_id, conversation_id, user, assembled, prompt)
|
||||
if paused is not None:
|
||||
return paused
|
||||
return _finish_turn(profile_id, conversation_id, user, assembled, prompt)
|
||||
|
||||
|
||||
def continue_turn(profile_id: str, conversation_id: str, review_id: str, decisions: list[dict]) -> dict:
|
||||
pending = load_pending(profile_id, review_id)
|
||||
if not pending or pending.get("conversation_id") != conversation_id:
|
||||
raise EngineError("mask_review_missing", "Die Maskierungsprüfung ist nicht mehr gültig.", 404)
|
||||
if pending.get("purpose") == "journal_generate":
|
||||
raise EngineError("mask_review_missing", "Diese Prüfung gehört zum Journalentwurf.", 409)
|
||||
if pending.get("kind") == KIND_CONFIRM_REMOTE:
|
||||
try:
|
||||
from detect_pipeline import apply_remote_confirm
|
||||
|
||||
mappings = apply_remote_confirm(profile_id, pending, decisions)
|
||||
except DetectError as exc:
|
||||
raise EngineError(exc.code, exc.message, getattr(exc, "status_code", 403)) from exc
|
||||
else:
|
||||
mappings = apply_review_decisions(profile_id, pending, decisions)
|
||||
drop_pending(profile_id, review_id)
|
||||
conversation = get_conversation(profile_id, conversation_id)
|
||||
context = build_internal_context(
|
||||
profile_id,
|
||||
conversation_id=conversation_id,
|
||||
space_id=conversation.get("space_id"),
|
||||
journal_day_id=conversation.get("journal_day_id"),
|
||||
purpose="dialogue_turn",
|
||||
)
|
||||
assembled = assemble_text(context)
|
||||
prompt = load_active_prompt("mvp.dialogue_turn")
|
||||
user = {"id": pending.get("user_message_id"), "body": pending.get("user_body") or ""}
|
||||
messages = list_messages(profile_id, conversation_id)
|
||||
for item in messages:
|
||||
if item.get("id") == pending.get("user_message_id"):
|
||||
user = item
|
||||
break
|
||||
return _finish_turn(
|
||||
profile_id,
|
||||
conversation_id,
|
||||
user,
|
||||
assembled,
|
||||
prompt,
|
||||
precomputed_mappings=mappings,
|
||||
)
|
||||
@@ -75,6 +75,8 @@ def execute_prompt(
|
||||
disable_context_compression: bool = False,
|
||||
budget=None,
|
||||
diagnostics: dict[str, Any] | None = None,
|
||||
precomputed_mappings: list[dict] | None = None,
|
||||
detect_counters: dict | None = None,
|
||||
) -> dict:
|
||||
preview = preview_prompt(prompt, context)
|
||||
feature_id = prompt.get("required_feature") or "ai_calls"
|
||||
@@ -100,6 +102,7 @@ def execute_prompt(
|
||||
payload={
|
||||
"rendered": preview["rendered"],
|
||||
"source_text": source_text,
|
||||
"user_body": (ctx.get("user_body") or user_source_text(ctx.get("dialogue_context") or "")).strip(),
|
||||
"privacy_tokens": preview["privacy_tokens"],
|
||||
"prompt_slug": prompt.get("slug"),
|
||||
"prompt_revision": prompt.get("seed_revision") or "",
|
||||
@@ -107,6 +110,8 @@ def execute_prompt(
|
||||
"disable_context_compression": disable_context_compression,
|
||||
"budget": budget,
|
||||
"diagnostics": diagnostics or {},
|
||||
"precomputed_mappings": precomputed_mappings,
|
||||
"detect_counters": detect_counters or {},
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
@@ -91,7 +91,7 @@ def increment_feature_usage(profile_id: str, feature_id: str) -> None:
|
||||
INSERT INTO user_feature_usage (profile_id, feature_id, period_key, used)
|
||||
VALUES (?, ?, ?, 1)
|
||||
ON CONFLICT(profile_id, feature_id, period_key)
|
||||
DO UPDATE SET used = used + 1
|
||||
DO UPDATE SET used = user_feature_usage.used + 1
|
||||
""",
|
||||
(profile_id, feature_id, period),
|
||||
)
|
||||
|
||||
+443
-104
@@ -5,6 +5,7 @@ spans and types only, never tokens, never a durable registry write.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import contextvars
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
@@ -30,17 +31,47 @@ from providers import ChatResult, ProviderError, complete_chat, detect_provider
|
||||
DETECT_CHUNK_CHARS = 4000
|
||||
DETECT_CHUNK_OVERLAP = 250
|
||||
DETECT_TIMEOUT = 90.0
|
||||
DETECT_TIMEOUT_LOCAL = 300.0
|
||||
DETECT_MAX_TOKENS = 1024
|
||||
DETECT_MAX_TOKENS_LOCAL = 256
|
||||
JSON_BLOCK = re.compile(r"\{.*\}", re.DOTALL)
|
||||
ALLOWED_ENTITY_FIELDS = frozenset({"start", "end", "text", "entity_type"})
|
||||
ALLOWED_ROOT_FIELDS = frozenset({"entities"})
|
||||
TYPE_PRIORITY = {"PERSON": 0, "PROJECT": 1, "ORG": 2, "PLACE": 3}
|
||||
NON_IDENTITY_ENTITY_TYPES = frozenset(
|
||||
{
|
||||
"FOOD",
|
||||
"DISH",
|
||||
"MEAL",
|
||||
"CUISINE",
|
||||
"FOODSTUFF",
|
||||
"INGREDIENT",
|
||||
}
|
||||
)
|
||||
|
||||
ERROR_DETECT_UNAVAILABLE = "detect_provider_unavailable"
|
||||
ERROR_DETECT_INCOMPLETE = "detect_incomplete"
|
||||
ERROR_DETECT_INVALID = "detect_invalid_output"
|
||||
ERROR_DETECT_TRUNCATED = "detect_truncated"
|
||||
ERROR_DETECT_CHUNK = "detect_chunk_failed"
|
||||
DETECT_MAX_PASSES = 2
|
||||
DETECT_CONTRACT_RETRY_CODES = frozenset(
|
||||
{
|
||||
ERROR_DETECT_INVALID,
|
||||
ERROR_DETECT_TRUNCATED,
|
||||
ERROR_DETECT_INCOMPLETE,
|
||||
}
|
||||
)
|
||||
SCHEMA_RETRY_HINT = (
|
||||
"Der vorherige Durchgang hat das verbindliche Schema nicht erfüllt. "
|
||||
"Antworte ausschließlich mit dem geforderten JSON-Objekt. "
|
||||
"Nur die Felder start, end, text und entity_type sind zulässig. "
|
||||
"Nur entity_type-Werte PERSON, PLACE, ORG, PROJECT. "
|
||||
"Lebensmittel und Gerichte weglassen, nicht als FOOD oder anderen Typ melden. "
|
||||
"Offsets sind 0-basiert und end ausschließlich, bezogen auf den Text nach «Text:». "
|
||||
"text muss ein exakter Substring dieses Texts sein. "
|
||||
"Keine zusätzlichen Felder, keine Tokens, keine Platzhalter, keine Erklärungen."
|
||||
)
|
||||
DETECT_DIALOGUE_FALLBACK_CODES = frozenset(
|
||||
{
|
||||
ERROR_DETECT_INVALID,
|
||||
@@ -117,8 +148,15 @@ class DetectionStats:
|
||||
completion_tokens: int = 0
|
||||
total_tokens: int = 0
|
||||
cost: float = 0.0
|
||||
cost_known: bool = False
|
||||
detect_ms: int = 0
|
||||
abort_reason: str | None = None
|
||||
detect_passes: int = 0
|
||||
detect_partial_discarded: bool = False
|
||||
detect_attempts: list[dict[str, Any]] = field(default_factory=list)
|
||||
contract_violation: str | None = None
|
||||
invalid_entity_type: str | None = None
|
||||
omitted_non_identity_types: list[str] = field(default_factory=list)
|
||||
|
||||
def public(self) -> dict[str, Any]:
|
||||
payload = {
|
||||
@@ -138,11 +176,25 @@ class DetectionStats:
|
||||
"detect_prompt_tokens": self.prompt_tokens,
|
||||
"detect_completion_tokens": self.completion_tokens,
|
||||
"detect_total_tokens": self.total_tokens,
|
||||
"detect_cost": self.cost,
|
||||
"detect_ms": self.detect_ms,
|
||||
"detect_passes": self.detect_passes,
|
||||
"detect_partial_discarded": self.detect_partial_discarded,
|
||||
"detect_attempts": [dict(item) for item in self.detect_attempts],
|
||||
"generate_called": False,
|
||||
}
|
||||
if self.cost_known:
|
||||
payload["detect_cost"] = self.cost
|
||||
payload["detect_cost_unknown"] = False
|
||||
else:
|
||||
payload["detect_cost_unknown"] = True
|
||||
if self.abort_reason:
|
||||
payload["abort_reason"] = self.abort_reason
|
||||
if self.contract_violation:
|
||||
payload["contract_violation"] = self.contract_violation
|
||||
if self.invalid_entity_type:
|
||||
payload["invalid_entity_type"] = self.invalid_entity_type
|
||||
if self.omitted_non_identity_types:
|
||||
payload["omitted_non_identity_types"] = list(self.omitted_non_identity_types)
|
||||
return payload
|
||||
|
||||
|
||||
@@ -153,36 +205,55 @@ class DetectionOutcome:
|
||||
local_identities: list[dict]
|
||||
|
||||
|
||||
_injected_spans: list[dict] | None = None
|
||||
_injected_fail: DetectError | None = None
|
||||
_injected_truncated: bool = False
|
||||
_injected_spans: contextvars.ContextVar[list[dict] | None] = contextvars.ContextVar(
|
||||
"kansho_detect_spans",
|
||||
default=None,
|
||||
)
|
||||
_injected_fail: contextvars.ContextVar[DetectError | None] = contextvars.ContextVar(
|
||||
"kansho_detect_fail",
|
||||
default=None,
|
||||
)
|
||||
_injected_truncated: contextvars.ContextVar[bool] = contextvars.ContextVar(
|
||||
"kansho_detect_truncated",
|
||||
default=False,
|
||||
)
|
||||
_injected_script: contextvars.ContextVar[Any] = contextvars.ContextVar(
|
||||
"kansho_detect_script",
|
||||
default=None,
|
||||
)
|
||||
|
||||
|
||||
def install_test_spans(spans: list[dict] | None) -> None:
|
||||
"""Test-only span injection. Production never calls this."""
|
||||
global _injected_spans
|
||||
_injected_spans = None if spans is None else [dict(item) for item in spans]
|
||||
_injected_spans.set(None if spans is None else [dict(item) for item in spans])
|
||||
|
||||
|
||||
def install_test_detect_failure(error: DetectError | None) -> None:
|
||||
global _injected_fail
|
||||
_injected_fail = error
|
||||
_injected_fail.set(error)
|
||||
|
||||
|
||||
def install_test_truncated(flag: bool = True) -> None:
|
||||
global _injected_truncated
|
||||
_injected_truncated = bool(flag)
|
||||
_injected_truncated.set(bool(flag))
|
||||
|
||||
|
||||
def install_test_detect_script(handler=None) -> None:
|
||||
"""Test-only per-attempt chunk script. Production never calls this.
|
||||
|
||||
handler(attempt, chunk_index, chunk_text, offset, schema_retry=...) may return
|
||||
entity lists, raw JSON, ChatResult, or DetectError. Attempt is 1-based.
|
||||
"""
|
||||
_injected_script.set(handler)
|
||||
|
||||
|
||||
def reset_detect_test_hooks() -> None:
|
||||
global _injected_spans, _injected_fail, _injected_truncated
|
||||
_injected_spans = None
|
||||
_injected_fail = None
|
||||
_injected_truncated = False
|
||||
_injected_spans.set(None)
|
||||
_injected_fail.set(None)
|
||||
_injected_truncated.set(False)
|
||||
_injected_script.set(None)
|
||||
|
||||
|
||||
def uses_llm_detect(config) -> bool:
|
||||
"""Local detect stays a provider role. Remote plaintext detect is development/test only."""
|
||||
"""Local detect stays a provider role. Remote plaintext detect needs an explicit allow."""
|
||||
if not config or config.mode != "http":
|
||||
return False
|
||||
if config.local:
|
||||
@@ -295,25 +366,41 @@ def _contract_fake_spans(text: str) -> list[dict]:
|
||||
return found
|
||||
|
||||
|
||||
def _contract_error(
|
||||
message: str,
|
||||
*,
|
||||
violation: str,
|
||||
code: str = ERROR_DETECT_INVALID,
|
||||
invalid_entity_type: str | None = None,
|
||||
status_code: int = 503,
|
||||
) -> DetectError:
|
||||
diagnostics: dict[str, Any] = {"contract_violation": violation}
|
||||
if invalid_entity_type:
|
||||
delivered = re.sub(r"[^A-Z0-9_:-]", "", str(invalid_entity_type).strip().upper())[:40]
|
||||
if delivered:
|
||||
diagnostics["invalid_entity_type"] = delivered
|
||||
return DetectError(code, message, status_code, diagnostics)
|
||||
|
||||
|
||||
def _parse_detect_json(raw: str) -> dict:
|
||||
text = (raw or "").strip()
|
||||
if text.startswith("```"):
|
||||
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.IGNORECASE | re.DOTALL).strip()
|
||||
match = JSON_BLOCK.search(text)
|
||||
if not match:
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-Antwort war kein gültiges JSON.")
|
||||
raise _contract_error("Detect-Antwort war kein gültiges JSON.", violation="invalid_json")
|
||||
try:
|
||||
data = json.loads(match.group(0))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-Antwort war kein gültiges JSON.") from exc
|
||||
raise _contract_error("Detect-Antwort war kein gültiges JSON.", violation="invalid_json") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-Antwort muss ein Objekt mit entities sein.")
|
||||
raise _contract_error("Detect-Antwort muss ein Objekt mit entities sein.", violation="invalid_json")
|
||||
extra = set(data.keys()) - ALLOWED_ROOT_FIELDS
|
||||
if extra:
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-Antwort enthält unerwartete Felder.")
|
||||
raise _contract_error("Detect-Antwort enthält unerwartete Felder.", violation="extra_fields")
|
||||
items = data.get("entities")
|
||||
if not isinstance(items, list):
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-entities muss eine Liste sein.")
|
||||
raise _contract_error("Detect-entities muss eine Liste sein.", violation="invalid_json")
|
||||
return data
|
||||
|
||||
|
||||
@@ -362,15 +449,62 @@ def _ground_span(chunk_text: str, start: int, end: int, text: str) -> tuple[int,
|
||||
return best[0], best[1], source[best[0] : best[1]]
|
||||
|
||||
|
||||
def _delivered_entity_type(raw: Any) -> str:
|
||||
if not isinstance(raw, str):
|
||||
return ""
|
||||
return re.sub(r"[^A-Z0-9_:-]", "", raw.strip().upper())[:40]
|
||||
|
||||
|
||||
def _identity_mention(chunk_text: str, start: int, end: int) -> bool:
|
||||
from privacy_gateway import is_identity_mention
|
||||
|
||||
return is_identity_mention(chunk_text, start, end, "PERSON:00")
|
||||
|
||||
|
||||
def _span_from_non_identity(item: dict, chunk_text: str, chunk_index: int) -> DetectedSpan | None:
|
||||
"""Food/dish types are not identities. Keep only a person-shaped mention of the same word."""
|
||||
text = item.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return None
|
||||
try:
|
||||
start = int(item.get("start") or 0)
|
||||
except (TypeError, ValueError):
|
||||
start = 0
|
||||
try:
|
||||
end = int(item.get("end") or 0)
|
||||
except (TypeError, ValueError):
|
||||
end = 0
|
||||
grounded = _ground_span(chunk_text, start, end, text)
|
||||
if not grounded:
|
||||
return None
|
||||
left, right, local_text = grounded
|
||||
if not _identity_mention(chunk_text, left, right):
|
||||
return None
|
||||
return DetectedSpan(
|
||||
start=left,
|
||||
end=right,
|
||||
text=local_text,
|
||||
entity_type="PERSON",
|
||||
chunk_index=chunk_index,
|
||||
)
|
||||
|
||||
|
||||
def validate_detected_entity(item: Any, chunk_text: str, chunk_index: int) -> DetectedSpan | None:
|
||||
if not isinstance(item, dict):
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-Entity muss ein Objekt sein.")
|
||||
raise _contract_error("Detect-Entity muss ein Objekt sein.", violation="invalid_entity")
|
||||
if "token" in item or "placeholder" in item:
|
||||
raise _contract_error("Detect darf keine Tokens festlegen.", violation="extra_fields")
|
||||
raw_type = item.get("entity_type")
|
||||
delivered = _delivered_entity_type(raw_type)
|
||||
kind = normalize_entity_type(raw_type if isinstance(raw_type, str) else "", default="")
|
||||
if not kind and delivered in NON_IDENTITY_ENTITY_TYPES:
|
||||
return _span_from_non_identity(item, chunk_text, chunk_index)
|
||||
extra = set(item.keys()) - ALLOWED_ENTITY_FIELDS
|
||||
if extra:
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-Entity enthält unerwartete Felder.")
|
||||
raise _contract_error("Detect-Entity enthält unerwartete Felder.", violation="extra_fields")
|
||||
missing = ALLOWED_ENTITY_FIELDS - set(item.keys())
|
||||
if missing:
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-Entity ist unvollständig.")
|
||||
raise _contract_error("Detect-Entity ist unvollständig.", violation="missing_fields")
|
||||
try:
|
||||
start = int(item["start"])
|
||||
except (TypeError, ValueError):
|
||||
@@ -381,17 +515,22 @@ def validate_detected_entity(item: Any, chunk_text: str, chunk_index: int) -> De
|
||||
end = 0
|
||||
text = item.get("text")
|
||||
if not isinstance(text, str):
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-text fehlt.")
|
||||
raise _contract_error("Detect-text fehlt.", violation="missing_fields")
|
||||
if not text.strip():
|
||||
return None
|
||||
if "token" in item or "placeholder" in item:
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect darf keine Tokens festlegen.")
|
||||
kind = normalize_entity_type(item.get("entity_type"), default="")
|
||||
raise _contract_error("Detect-text ist leer.", violation="invalid_text")
|
||||
if not kind:
|
||||
raise DetectError(ERROR_DETECT_INVALID, "Detect-entity_type ist nicht erlaubt.")
|
||||
delivered_raw = raw_type if isinstance(raw_type, str) else ""
|
||||
raise _contract_error(
|
||||
"Detect-entity_type ist nicht erlaubt.",
|
||||
violation="unknown_entity_type",
|
||||
invalid_entity_type=delivered_raw,
|
||||
)
|
||||
grounded = _ground_span(chunk_text, start, end, text)
|
||||
if not grounded:
|
||||
return None
|
||||
raise _contract_error(
|
||||
"Detect-Offsets sind nicht im Chunk verankert.",
|
||||
violation="unusable_offsets",
|
||||
)
|
||||
left, right, local_text = grounded
|
||||
return DetectedSpan(start=left, end=right, text=local_text, entity_type=kind, chunk_index=chunk_index)
|
||||
|
||||
@@ -419,40 +558,74 @@ def resolve_overlaps(spans: list[DetectedSpan]) -> list[DetectedSpan]:
|
||||
|
||||
def _add_usage(stats: DetectionStats, usage: dict | None) -> None:
|
||||
data = usage or {}
|
||||
if data.get("prompt_tokens") is not None:
|
||||
stats.prompt_tokens += int(data.get("prompt_tokens") or 0)
|
||||
if data.get("completion_tokens") is not None:
|
||||
stats.completion_tokens += int(data.get("completion_tokens") or 0)
|
||||
if data.get("total_tokens") is not None:
|
||||
stats.total_tokens += int(data.get("total_tokens") or 0)
|
||||
extra = data.get("cost")
|
||||
if extra is None:
|
||||
extra = data.get("total_cost")
|
||||
if extra is not None:
|
||||
try:
|
||||
stats.cost += float(data.get("cost") or 0)
|
||||
stats.cost += float(extra)
|
||||
stats.cost_known = True
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _llm_chunk(config, excerpt: str) -> ChatResult:
|
||||
def detect_chat_limits(config) -> tuple[float, int]:
|
||||
"""Remote detect stays at 90s/1024. Local CPU hosts need a longer wait and a shorter cap."""
|
||||
if getattr(config, "local", False):
|
||||
return DETECT_TIMEOUT_LOCAL, DETECT_MAX_TOKENS_LOCAL
|
||||
return DETECT_TIMEOUT, DETECT_MAX_TOKENS
|
||||
|
||||
|
||||
def _llm_chunk(config, excerpt: str, *, schema_retry: bool = False) -> ChatResult:
|
||||
prompt = resolve_template(
|
||||
_detect_prompt()["template"],
|
||||
{"source_text": excerpt, "known_labels": ""},
|
||||
)
|
||||
if schema_retry:
|
||||
prompt = f"{prompt.rstrip()}\n\n{SCHEMA_RETRY_HINT}"
|
||||
timeout, max_tokens = detect_chat_limits(config)
|
||||
return complete_chat(
|
||||
config,
|
||||
[{"role": "user", "content": prompt}],
|
||||
timeout=DETECT_TIMEOUT,
|
||||
max_tokens=DETECT_MAX_TOKENS,
|
||||
timeout=timeout,
|
||||
max_tokens=max_tokens,
|
||||
disable_context_compression=True,
|
||||
)
|
||||
|
||||
|
||||
def _entities_from_result(result: ChatResult, chunk_text: str, chunk_index: int) -> list[DetectedSpan]:
|
||||
def _note_omitted_type(stats: DetectionStats | None, delivered: str) -> None:
|
||||
if not stats or not delivered or delivered not in NON_IDENTITY_ENTITY_TYPES:
|
||||
return
|
||||
if delivered not in stats.omitted_non_identity_types:
|
||||
stats.omitted_non_identity_types.append(delivered)
|
||||
|
||||
|
||||
def _entities_from_result(
|
||||
result: ChatResult,
|
||||
chunk_text: str,
|
||||
chunk_index: int,
|
||||
stats: DetectionStats | None = None,
|
||||
) -> list[DetectedSpan]:
|
||||
if (result.finish_reason or "").lower() in {"length", "max_tokens"}:
|
||||
raise DetectError(
|
||||
ERROR_DETECT_TRUNCATED,
|
||||
"Detect-Ausgabe wurde abgeschnitten. Generate wird nicht freigegeben.",
|
||||
diagnostics={"contract_violation": "truncated"},
|
||||
)
|
||||
data = _parse_detect_json(result.content or "")
|
||||
spans: list[DetectedSpan] = []
|
||||
for item in data.get("entities") or []:
|
||||
span = validate_detected_entity(item, chunk_text, chunk_index)
|
||||
if span is not None:
|
||||
if span is None:
|
||||
delivered = _delivered_entity_type(item.get("entity_type") if isinstance(item, dict) else "")
|
||||
_note_omitted_type(stats, delivered)
|
||||
continue
|
||||
spans.append(span)
|
||||
return spans
|
||||
|
||||
@@ -571,18 +744,197 @@ def _merge_confirmed_safety_net(text: str, mappings: list[dict], profile_id: str
|
||||
return mappings + extra, hits
|
||||
|
||||
|
||||
def _merge_pass_stats(overall: DetectionStats, pass_stats: DetectionStats) -> None:
|
||||
overall.detect_calls += pass_stats.detect_calls
|
||||
overall.prompt_tokens += pass_stats.prompt_tokens
|
||||
overall.completion_tokens += pass_stats.completion_tokens
|
||||
overall.total_tokens += pass_stats.total_tokens
|
||||
overall.chunk_count = pass_stats.chunk_count
|
||||
overall.chunks_ok = pass_stats.chunks_ok
|
||||
overall.detect_note = pass_stats.detect_note or overall.detect_note
|
||||
overall.detect_model = pass_stats.detect_model or overall.detect_model
|
||||
if pass_stats.cost_known:
|
||||
overall.cost_known = True
|
||||
overall.cost += pass_stats.cost
|
||||
for kind in pass_stats.omitted_non_identity_types:
|
||||
if kind not in overall.omitted_non_identity_types:
|
||||
overall.omitted_non_identity_types.append(kind)
|
||||
|
||||
|
||||
def _pass_snapshot(
|
||||
pass_stats: DetectionStats,
|
||||
*,
|
||||
attempt: int,
|
||||
coverage: bool,
|
||||
abort: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
row: dict[str, Any] = {
|
||||
"attempt": attempt,
|
||||
"schema_retry": attempt > 1,
|
||||
"chunk_count": pass_stats.chunk_count,
|
||||
"chunks_ok": pass_stats.chunks_ok,
|
||||
"detect_calls": pass_stats.detect_calls,
|
||||
"full_detection_coverage": coverage,
|
||||
"detect_prompt_tokens": pass_stats.prompt_tokens,
|
||||
"detect_completion_tokens": pass_stats.completion_tokens,
|
||||
"detect_total_tokens": pass_stats.total_tokens,
|
||||
"detect_ms": pass_stats.detect_ms,
|
||||
}
|
||||
if pass_stats.cost_known:
|
||||
row["detect_cost"] = pass_stats.cost
|
||||
row["detect_cost_unknown"] = False
|
||||
else:
|
||||
row["detect_cost_unknown"] = True
|
||||
if abort:
|
||||
row["abort_reason"] = abort
|
||||
if pass_stats.contract_violation:
|
||||
row["contract_violation"] = pass_stats.contract_violation
|
||||
if pass_stats.invalid_entity_type:
|
||||
row["invalid_entity_type"] = pass_stats.invalid_entity_type
|
||||
if pass_stats.omitted_non_identity_types:
|
||||
row["omitted_non_identity_types"] = list(pass_stats.omitted_non_identity_types)
|
||||
return row
|
||||
|
||||
|
||||
def _script_result(raw: Any, *, model: str | None) -> ChatResult:
|
||||
if isinstance(raw, DetectError):
|
||||
raise raw
|
||||
if isinstance(raw, ChatResult):
|
||||
return raw
|
||||
if isinstance(raw, str):
|
||||
return ChatResult(content=raw, model=model, usage={}, finish_reason="stop")
|
||||
if isinstance(raw, dict) and "entities" in raw:
|
||||
return ChatResult(content=json.dumps(raw), model=model, usage={}, finish_reason="stop")
|
||||
if isinstance(raw, list):
|
||||
return ChatResult(
|
||||
content=json.dumps({"entities": raw}),
|
||||
model=model,
|
||||
usage={},
|
||||
finish_reason="stop",
|
||||
)
|
||||
raise _contract_error("Detect-Testskript lieferte keine verwertbare Antwort.", violation="invalid_json")
|
||||
|
||||
|
||||
def _chunk_chat_result(
|
||||
config,
|
||||
chunk_text: str,
|
||||
*,
|
||||
offset: int,
|
||||
index: int,
|
||||
attempt: int,
|
||||
schema_retry: bool,
|
||||
stats: DetectionStats,
|
||||
) -> ChatResult:
|
||||
if _injected_truncated.get():
|
||||
raise DetectError(
|
||||
ERROR_DETECT_TRUNCATED,
|
||||
"Detect-Ausgabe wurde abgeschnitten. Generate wird nicht freigegeben.",
|
||||
diagnostics={"contract_violation": "truncated"},
|
||||
)
|
||||
script = _injected_script.get()
|
||||
if script is not None:
|
||||
stats.detect_note = "injected"
|
||||
try:
|
||||
raw = script(attempt, index, chunk_text, offset, schema_retry=schema_retry)
|
||||
except TypeError:
|
||||
raw = script(attempt, index, chunk_text, offset)
|
||||
return _script_result(raw, model=config.model)
|
||||
spans = _injected_spans.get()
|
||||
if spans is not None:
|
||||
raw_items = [
|
||||
item
|
||||
for item in spans
|
||||
if int(item.get("start") or 0) >= offset
|
||||
and int(item.get("end") or 0) <= offset + len(chunk_text)
|
||||
]
|
||||
local_items = []
|
||||
for item in raw_items:
|
||||
local = dict(item)
|
||||
local["start"] = int(item["start"]) - offset
|
||||
local["end"] = int(item["end"]) - offset
|
||||
local_items.append(local)
|
||||
stats.detect_note = "injected"
|
||||
return ChatResult(
|
||||
content=json.dumps({"entities": local_items}),
|
||||
model=config.model,
|
||||
usage={},
|
||||
finish_reason="stop",
|
||||
)
|
||||
if config.mode == "fake":
|
||||
stats.detect_note = "fake"
|
||||
return ChatResult(
|
||||
content=json.dumps({"entities": _contract_fake_spans(chunk_text)}),
|
||||
model=config.model,
|
||||
usage={},
|
||||
finish_reason="stop",
|
||||
)
|
||||
if uses_llm_detect(config):
|
||||
try:
|
||||
result = _llm_chunk(config, chunk_text, schema_retry=schema_retry)
|
||||
except PlaceholderError as exc:
|
||||
raise DetectError(exc.code, exc.message) from exc
|
||||
except ProviderError as exc:
|
||||
raise DetectError(
|
||||
ERROR_DETECT_CHUNK,
|
||||
"Ein Detect-Chunk ist fehlgeschlagen. Generate wird nicht freigegeben.",
|
||||
exc.status_code,
|
||||
) from exc
|
||||
stats.detect_note = "local_llm" if config.local else "remote_llm"
|
||||
stats.detect_model = result.model or stats.detect_model
|
||||
return result
|
||||
raise DetectError(
|
||||
ERROR_DETECT_UNAVAILABLE,
|
||||
"Semantische Detection ist nicht verfügbar. Generate wird nicht freigegeben.",
|
||||
)
|
||||
|
||||
|
||||
def _run_detection_pass(
|
||||
config,
|
||||
chunks: list[tuple[int, str]],
|
||||
*,
|
||||
attempt: int,
|
||||
schema_retry: bool,
|
||||
stats: DetectionStats,
|
||||
) -> list[DetectedSpan]:
|
||||
collected: list[DetectedSpan] = []
|
||||
for index, (offset, chunk_text) in enumerate(chunks):
|
||||
result = _chunk_chat_result(
|
||||
config,
|
||||
chunk_text,
|
||||
offset=offset,
|
||||
index=index,
|
||||
attempt=attempt,
|
||||
schema_retry=schema_retry,
|
||||
stats=stats,
|
||||
)
|
||||
stats.detect_calls += 1
|
||||
_add_usage(stats, result.usage)
|
||||
spans = _entities_from_result(result, chunk_text, index, stats)
|
||||
collected.extend(_to_global(span, offset) for span in spans)
|
||||
stats.chunks_ok += 1
|
||||
if stats.chunks_ok != stats.chunk_count:
|
||||
raise DetectError(
|
||||
ERROR_DETECT_INCOMPLETE,
|
||||
"Detection hat nicht alle Chunks geprüft. Generate wird nicht freigegeben.",
|
||||
diagnostics={"contract_violation": "incomplete"},
|
||||
)
|
||||
return collected
|
||||
|
||||
|
||||
def detect_personal_egress(profile_id: str | None, source_text: str) -> DetectionOutcome:
|
||||
"""Full semantic detection of the personal generate-egress. Fail closed if incomplete."""
|
||||
started = time.perf_counter()
|
||||
stats = DetectionStats(source_chars=len(source_text or ""))
|
||||
if _injected_fail is not None:
|
||||
stats.abort_reason = _injected_fail.code
|
||||
injected_fail = _injected_fail.get()
|
||||
if injected_fail is not None:
|
||||
stats.abort_reason = injected_fail.code
|
||||
stats.detect_ms = int((time.perf_counter() - started) * 1000)
|
||||
stats.detect_passes = 0
|
||||
raise DetectError(
|
||||
_injected_fail.code,
|
||||
_injected_fail.message,
|
||||
_injected_fail.status_code,
|
||||
{**(_injected_fail.diagnostics or {}), **stats.public()},
|
||||
injected_fail.code,
|
||||
injected_fail.message,
|
||||
injected_fail.status_code,
|
||||
{**(injected_fail.diagnostics or {}), **stats.public()},
|
||||
)
|
||||
config = detect_provider()
|
||||
if not config:
|
||||
@@ -606,83 +958,70 @@ def detect_personal_egress(profile_id: str | None, source_text: str) -> Detectio
|
||||
chunks = split_detect_chunks(source_text or "")
|
||||
stats.chunk_count = len(chunks)
|
||||
collected: list[DetectedSpan] = []
|
||||
last_error: DetectError | None = None
|
||||
for attempt in range(1, DETECT_MAX_PASSES + 1):
|
||||
pass_stats = DetectionStats(
|
||||
source_chars=stats.source_chars,
|
||||
detect_provider=stats.detect_provider,
|
||||
detect_model=stats.detect_model,
|
||||
chunk_count=len(chunks),
|
||||
)
|
||||
pass_started = time.perf_counter()
|
||||
try:
|
||||
for index, (offset, chunk_text) in enumerate(chunks):
|
||||
if _injected_truncated:
|
||||
raise DetectError(
|
||||
ERROR_DETECT_TRUNCATED,
|
||||
"Detect-Ausgabe wurde abgeschnitten. Generate wird nicht freigegeben.",
|
||||
collected = _run_detection_pass(
|
||||
config,
|
||||
chunks,
|
||||
attempt=attempt,
|
||||
schema_retry=attempt > 1,
|
||||
stats=pass_stats,
|
||||
)
|
||||
if _injected_spans is not None:
|
||||
raw_items = [
|
||||
item
|
||||
for item in _injected_spans
|
||||
if int(item.get("start") or 0) >= offset
|
||||
and int(item.get("end") or 0) <= offset + len(chunk_text)
|
||||
]
|
||||
local_items = []
|
||||
for item in raw_items:
|
||||
local = dict(item)
|
||||
local["start"] = int(item["start"]) - offset
|
||||
local["end"] = int(item["end"]) - offset
|
||||
local_items.append(local)
|
||||
result = ChatResult(
|
||||
content=json.dumps({"entities": local_items}),
|
||||
model=config.model,
|
||||
usage={},
|
||||
finish_reason="stop",
|
||||
pass_stats.full_detection_coverage = True
|
||||
pass_stats.detect_ms = int((time.perf_counter() - pass_started) * 1000)
|
||||
_merge_pass_stats(stats, pass_stats)
|
||||
stats.detect_attempts.append(
|
||||
_pass_snapshot(pass_stats, attempt=attempt, coverage=True)
|
||||
)
|
||||
stats.detect_note = "injected"
|
||||
elif config.mode == "fake":
|
||||
fake_items = _contract_fake_spans(chunk_text)
|
||||
result = ChatResult(
|
||||
content=json.dumps({"entities": fake_items}),
|
||||
model=config.model,
|
||||
usage={},
|
||||
finish_reason="stop",
|
||||
)
|
||||
stats.detect_note = "fake"
|
||||
elif uses_llm_detect(config):
|
||||
try:
|
||||
result = _llm_chunk(config, chunk_text)
|
||||
except PlaceholderError as exc:
|
||||
raise DetectError(exc.code, exc.message) from exc
|
||||
except ProviderError as exc:
|
||||
raise DetectError(
|
||||
ERROR_DETECT_CHUNK,
|
||||
"Ein Detect-Chunk ist fehlgeschlagen. Generate wird nicht freigegeben.",
|
||||
exc.status_code,
|
||||
) from exc
|
||||
stats.detect_note = "local_llm" if config.local else "remote_llm"
|
||||
stats.detect_model = result.model or stats.detect_model
|
||||
else:
|
||||
raise DetectError(
|
||||
ERROR_DETECT_UNAVAILABLE,
|
||||
"Semantische Detection ist nicht verfügbar. Generate wird nicht freigegeben.",
|
||||
)
|
||||
stats.detect_calls += 1
|
||||
_add_usage(stats, result.usage)
|
||||
spans = _entities_from_result(result, chunk_text, index)
|
||||
collected.extend(_to_global(span, offset) for span in spans)
|
||||
stats.chunks_ok += 1
|
||||
last_error = None
|
||||
break
|
||||
except DetectError as exc:
|
||||
inner = dict(exc.diagnostics or {})
|
||||
pass_stats.abort_reason = exc.code
|
||||
pass_stats.contract_violation = inner.get("contract_violation")
|
||||
pass_stats.invalid_entity_type = inner.get("invalid_entity_type")
|
||||
pass_stats.full_detection_coverage = False
|
||||
pass_stats.detect_ms = int((time.perf_counter() - pass_started) * 1000)
|
||||
_merge_pass_stats(stats, pass_stats)
|
||||
stats.detect_attempts.append(
|
||||
_pass_snapshot(pass_stats, attempt=attempt, coverage=False, abort=exc.code)
|
||||
)
|
||||
collected = []
|
||||
last_error = DetectError(exc.code, exc.message, exc.status_code, inner)
|
||||
retryable = exc.code in DETECT_CONTRACT_RETRY_CODES
|
||||
if attempt < DETECT_MAX_PASSES and retryable:
|
||||
stats.detect_partial_discarded = True
|
||||
continue
|
||||
stats.abort_reason = exc.code
|
||||
stats.contract_violation = pass_stats.contract_violation
|
||||
stats.invalid_entity_type = pass_stats.invalid_entity_type
|
||||
stats.full_detection_coverage = False
|
||||
stats.detect_passes = attempt
|
||||
stats.detect_ms = int((time.perf_counter() - started) * 1000)
|
||||
raise DetectError(
|
||||
exc.code,
|
||||
exc.message,
|
||||
exc.status_code,
|
||||
{**(exc.diagnostics or {}), **stats.public()},
|
||||
{**inner, **stats.public()},
|
||||
) from exc
|
||||
if stats.chunks_ok != stats.chunk_count:
|
||||
stats.abort_reason = ERROR_DETECT_INCOMPLETE
|
||||
if last_error is not None:
|
||||
stats.detect_passes = len(stats.detect_attempts)
|
||||
stats.detect_ms = int((time.perf_counter() - started) * 1000)
|
||||
raise DetectError(
|
||||
ERROR_DETECT_INCOMPLETE,
|
||||
"Detection hat nicht alle Chunks geprüft. Generate wird nicht freigegeben.",
|
||||
diagnostics=stats.public(),
|
||||
last_error.code,
|
||||
last_error.message,
|
||||
last_error.status_code,
|
||||
{**(last_error.diagnostics or {}), **stats.public()},
|
||||
)
|
||||
stats.detect_passes = len(stats.detect_attempts)
|
||||
merged = _dedupe_spans(collected)
|
||||
confirmed = list_confirmed_identities(profile_id) if profile_id else []
|
||||
mappings, request_local, confirmed_from_spans = _assign_request_tokens(merged, confirmed)
|
||||
|
||||
+21
-2
@@ -26,7 +26,7 @@ def load_env_file(path: Path | None = None) -> None:
|
||||
|
||||
|
||||
def runtime_env() -> str:
|
||||
"""development/test may use remote plaintext detect. production must not."""
|
||||
"""development/test may use remote plaintext detect. production must not, unless overridden."""
|
||||
raw = (os.environ.get("KANSHO_ENV") or "").strip().lower()
|
||||
if raw in {"production", "prod"}:
|
||||
return "production"
|
||||
@@ -37,8 +37,27 @@ def runtime_env() -> str:
|
||||
return "development"
|
||||
|
||||
|
||||
def env_flag(name: str) -> bool:
|
||||
raw = (os.environ.get(name) or "").strip().lower()
|
||||
return raw in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def remote_plaintext_detect_reason() -> str:
|
||||
"""Why remote detect is allowed or blocked. Never logs secrets."""
|
||||
if runtime_env() != "production":
|
||||
return "non_production"
|
||||
if env_flag("KANSHO_ALLOW_REMOTE_DETECT"):
|
||||
return "operator_override"
|
||||
return "blocked"
|
||||
|
||||
|
||||
def allows_remote_plaintext_detect() -> bool:
|
||||
return runtime_env() != "production"
|
||||
"""Remote plaintext detect is default-off in production.
|
||||
|
||||
Endbetrieb remains local detect. Until Ollama is connected, an operator
|
||||
may set KANSHO_ALLOW_REMOTE_DETECT. That does not disable the gateway.
|
||||
"""
|
||||
return remote_plaintext_detect_reason() != "blocked"
|
||||
|
||||
|
||||
def upsert_env_value(name: str, value: str, path: Path | None = None) -> None:
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Stateless client for the LAN GLiNER spike. Fail-soft; never logs request text."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse, urlunparse
|
||||
|
||||
import httpx
|
||||
|
||||
from providers import is_local_url
|
||||
|
||||
log = logging.getLogger("gliner_client")
|
||||
|
||||
DEFAULT_URL = "http://192.168.2.144:8090"
|
||||
DEFAULT_LABELS = ("person", "place", "organization", "project", "dish", "food")
|
||||
IDENTITY_LABELS = {
|
||||
"person": "PERSON",
|
||||
"place": "PLACE",
|
||||
"organization": "ORG",
|
||||
"project": "PROJECT",
|
||||
}
|
||||
NON_IDENTITY_LABELS = frozenset({"dish", "food"})
|
||||
EXTRACT_TIMEOUT = 8.0
|
||||
HEALTH_TIMEOUT = 2.0
|
||||
|
||||
|
||||
def normalize_base_url(url: str | None) -> str:
|
||||
raw = (url or DEFAULT_URL).strip() or DEFAULT_URL
|
||||
parsed = urlparse(raw)
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
return DEFAULT_URL
|
||||
path = (parsed.path or "").rstrip("/")
|
||||
return urlunparse((parsed.scheme, parsed.netloc, path, "", "", ""))
|
||||
|
||||
|
||||
def gliner_identity_type(label: str) -> str | None:
|
||||
return IDENTITY_LABELS.get((label or "").strip().lower())
|
||||
|
||||
|
||||
def is_gliner_non_identity(label: str) -> bool:
|
||||
return (label or "").strip().lower() in NON_IDENTITY_LABELS
|
||||
|
||||
|
||||
def health(url: str | None = None) -> dict[str, Any]:
|
||||
"""Ping GLiNER. Never include request text. Fail-soft."""
|
||||
base = normalize_base_url(url)
|
||||
if not is_local_url(base):
|
||||
return {"ok": False, "status": "rejected", "reason": "not_local"}
|
||||
try:
|
||||
response = httpx.get(f"{base}/health", timeout=HEALTH_TIMEOUT)
|
||||
except httpx.HTTPError:
|
||||
return {"ok": False, "status": "unreachable", "url": base}
|
||||
if response.status_code >= 400:
|
||||
return {"ok": False, "status": "http_error", "http_status": response.status_code}
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
return {"ok": False, "status": "invalid"}
|
||||
if not isinstance(payload, dict):
|
||||
return {"ok": False, "status": "invalid"}
|
||||
status = (payload.get("status") or "").strip() or "ok"
|
||||
return {
|
||||
"ok": status == "ok",
|
||||
"status": status,
|
||||
"model": payload.get("model") or "",
|
||||
"offline": bool(payload.get("offline")),
|
||||
}
|
||||
|
||||
|
||||
def extract_entities(text: str, url: str | None = None) -> list[dict] | None:
|
||||
"""Return spans or None if the service cannot be used. Empty list is a valid miss."""
|
||||
body = text or ""
|
||||
if not body.strip():
|
||||
return []
|
||||
base = normalize_base_url(url)
|
||||
if not is_local_url(base):
|
||||
log.info("gliner skipped: url is not local")
|
||||
return None
|
||||
try:
|
||||
response = httpx.post(
|
||||
f"{base}/v1/extract",
|
||||
json={"text": body, "labels": list(DEFAULT_LABELS)},
|
||||
timeout=EXTRACT_TIMEOUT,
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
log.info("gliner extract unreachable chars=%s", len(body))
|
||||
return None
|
||||
if response.status_code >= 400:
|
||||
log.info("gliner extract http=%s chars=%s", response.status_code, len(body))
|
||||
return None
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
return None
|
||||
raw = payload.get("spans") if isinstance(payload, dict) else None
|
||||
if not isinstance(raw, list):
|
||||
return None
|
||||
spans = []
|
||||
for item in raw:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
start = int(item["start"])
|
||||
end = int(item["end"])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
label = str(item.get("text") or "")
|
||||
kind = str(item.get("label") or "")
|
||||
if start < 0 or end <= start or not label or not kind:
|
||||
continue
|
||||
spans.append(
|
||||
{
|
||||
"text": label,
|
||||
"start": start,
|
||||
"end": end,
|
||||
"label": kind,
|
||||
"score": item.get("score"),
|
||||
}
|
||||
)
|
||||
log.info("gliner extract chars=%s spans=%s", len(body), len(spans))
|
||||
return spans
|
||||
@@ -11,6 +11,11 @@ import re
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
from journal_body import plain_text
|
||||
from journal_generation_policy import (
|
||||
EMPTY_STYLE_CONTEXT,
|
||||
STYLE_CONTEXT_KEYS,
|
||||
normalize_style_context,
|
||||
)
|
||||
from writing_profile_schema import is_meta_style_text, recency_weight
|
||||
from writing_profile_store import (
|
||||
clip_field,
|
||||
@@ -23,7 +28,7 @@ STYLE_EXAMPLE_MAX = 2
|
||||
STYLE_EXAMPLE_CHARS = 900
|
||||
MIN_EXAMPLE_CHARS = 40
|
||||
|
||||
GENERATE_SEED_REVISION = "2026-08-27-journal-mixed-sources-v1"
|
||||
GENERATE_SEED_REVISION = "2026-08-29-voice-legacy-immutable-v1"
|
||||
|
||||
EMPTY_STYLE_EXAMPLES = (
|
||||
"Keine historischen Stilbeispiele. Es gilt nur WRITING_PROFILE "
|
||||
@@ -82,8 +87,18 @@ def style_example_diagnostics(examples: list[dict]) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def writing_profile_trace(profile_id: str) -> dict:
|
||||
"""Presence metadata only. No profile text, no labels."""
|
||||
def writing_profile_trace(
|
||||
profile_id: str,
|
||||
*,
|
||||
style_context: dict | None = None,
|
||||
brief: str | None = None,
|
||||
trait_count: int | None = None,
|
||||
) -> dict:
|
||||
"""Presence metadata only. No profile text, no labels.
|
||||
|
||||
When style_context or a compiled brief is supplied, the flags describe the
|
||||
effective provider input rather than the stored profile inventory.
|
||||
"""
|
||||
from writing_profile_store import (
|
||||
NEUTRAL_JOURNAL_STYLE,
|
||||
compile_task_brief,
|
||||
@@ -93,6 +108,7 @@ def writing_profile_trace(profile_id: str) -> dict:
|
||||
|
||||
confirmed = has_confirmed_profile(profile_id)
|
||||
profile = get_profile(profile_id)
|
||||
context = normalize_style_context(style_context, slot="voice") if style_context is not None else None
|
||||
core = ((profile.get("core") or {}).get("value") or "").strip()
|
||||
facet = next(
|
||||
(
|
||||
@@ -107,15 +123,30 @@ def writing_profile_trace(profile_id: str) -> dict:
|
||||
for item in profile.get("traits") or []
|
||||
if item.get("status") == "active" and (item.get("statement") or "").strip()
|
||||
]
|
||||
brief = compile_task_brief(profile_id, "journal_generate")
|
||||
if brief is None:
|
||||
brief = compile_task_brief(
|
||||
profile_id,
|
||||
"journal_generate",
|
||||
include_core=True if context is None else context["include_core"],
|
||||
include_facet=True if context is None else context["include_facet"],
|
||||
include_traits=True if context is None else context["include_traits"],
|
||||
)
|
||||
has_core = "Core:" in (brief or "")
|
||||
has_facet = "Facet-Delta:" in (brief or "") or "Autobiografisches Journaling" in (brief or "")
|
||||
if trait_count is None:
|
||||
trait_count = sum(1 for line in (brief or "").splitlines() if line.startswith("- "))
|
||||
present = bool(brief and brief != NEUTRAL_JOURNAL_STYLE)
|
||||
return {
|
||||
"confirmed": confirmed,
|
||||
"present": bool(confirmed and brief and brief != NEUTRAL_JOURNAL_STYLE),
|
||||
"present": present,
|
||||
"neutral_fallback": brief == NEUTRAL_JOURNAL_STYLE,
|
||||
"has_core": bool(confirmed and core),
|
||||
"has_facet": bool(confirmed and facet),
|
||||
"trait_count": len(traits) if confirmed else 0,
|
||||
"has_core": has_core,
|
||||
"has_facet": has_facet,
|
||||
"trait_count": int(trait_count or 0),
|
||||
"brief_chars": len(brief or ""),
|
||||
"inventory_has_core": bool(confirmed and core),
|
||||
"inventory_has_facet": bool(confirmed and facet),
|
||||
"inventory_trait_count": len(traits) if confirmed else 0,
|
||||
}
|
||||
|
||||
|
||||
@@ -156,6 +187,247 @@ def format_style_examples(examples: list[dict]) -> str:
|
||||
return "\n".join(part for part in lines if part).strip()
|
||||
|
||||
|
||||
def wrap_style_block(title: str, body: str) -> str:
|
||||
text = (body or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
return f"{title}\n{text}\n"
|
||||
|
||||
|
||||
def _estimated_tokens(text: str) -> int:
|
||||
from prompt_budget import estimate_tokens
|
||||
|
||||
body = text or ""
|
||||
if not body:
|
||||
return 0
|
||||
return estimate_tokens(body)
|
||||
|
||||
|
||||
def compile_journal_style_application(
|
||||
profile_id: str,
|
||||
style_context: dict | None,
|
||||
*,
|
||||
exclude_dates: list[str] | None = None,
|
||||
exclude_entry_ids: list[str] | None = None,
|
||||
) -> dict:
|
||||
"""Select only the style sources released by the voice guideline.
|
||||
|
||||
Returns prompt fragments and an effective trace. Empty sections stay empty
|
||||
so the prompt builder can omit their headings.
|
||||
"""
|
||||
from writing_profile_store import (
|
||||
NEUTRAL_JOURNAL_STYLE,
|
||||
compile_task_brief,
|
||||
has_confirmed_profile,
|
||||
)
|
||||
|
||||
context = normalize_style_context(style_context or EMPTY_STYLE_CONTEXT, slot="voice")
|
||||
confirmed = has_confirmed_profile(profile_id)
|
||||
omitted: list[dict] = []
|
||||
requested = {key: bool(context.get(key)) for key in STYLE_CONTEXT_KEYS}
|
||||
|
||||
def omit(part: str, reason: str) -> None:
|
||||
omitted.append({"part": part, "reason": reason})
|
||||
|
||||
if not requested["include_core"]:
|
||||
omit("core", "not_selected")
|
||||
if not requested["include_facet"]:
|
||||
omit("facet", "not_selected")
|
||||
if not requested["include_traits"]:
|
||||
omit("traits", "not_selected")
|
||||
if not requested["include_style_examples"]:
|
||||
omit("style_examples", "not_selected")
|
||||
|
||||
wants_profile = any(requested[key] for key in ("include_core", "include_facet", "include_traits"))
|
||||
brief = compile_task_brief(
|
||||
profile_id,
|
||||
"journal_generate",
|
||||
include_core=requested["include_core"],
|
||||
include_facet=requested["include_facet"],
|
||||
include_traits=requested["include_traits"],
|
||||
)
|
||||
if wants_profile and not confirmed:
|
||||
for part, flag in (
|
||||
("core", "include_core"),
|
||||
("facet", "include_facet"),
|
||||
("traits", "include_traits"),
|
||||
):
|
||||
if requested[flag] and not any(item["part"] == part and item["reason"] == "unconfirmed" for item in omitted):
|
||||
omit(part, "unconfirmed")
|
||||
elif confirmed:
|
||||
if requested["include_core"] and "Core:" not in (brief or ""):
|
||||
omit("core", "empty")
|
||||
if requested["include_facet"] and "Facet-Delta:" not in (brief or "") and "Autobiografisches Journaling" not in (brief or ""):
|
||||
omit("facet", "empty")
|
||||
if requested["include_traits"] and not any(line.startswith("- ") for line in (brief or "").splitlines()):
|
||||
omit("traits", "empty")
|
||||
|
||||
example_rows: list[dict] = []
|
||||
examples_text = ""
|
||||
if requested["include_style_examples"]:
|
||||
example_rows = select_journal_style_examples(
|
||||
profile_id,
|
||||
exclude_dates=exclude_dates,
|
||||
exclude_entry_ids=exclude_entry_ids,
|
||||
)
|
||||
if example_rows:
|
||||
examples_text = format_style_examples(example_rows)
|
||||
else:
|
||||
omit("style_examples", "empty")
|
||||
|
||||
profile_block = wrap_style_block("WRITING_PROFILE", brief)
|
||||
examples_block = wrap_style_block("STYLE_EXAMPLES", examples_text)
|
||||
trait_count = sum(1 for line in (brief or "").splitlines() if line.startswith("- "))
|
||||
core_included = "Core:" in (brief or "")
|
||||
facet_included = "Facet-Delta:" in (brief or "") or "Autobiografisches Journaling" in (brief or "")
|
||||
return {
|
||||
"style_context": context,
|
||||
"brief": brief,
|
||||
"profile_block": profile_block,
|
||||
"style_examples": examples_text,
|
||||
"examples_block": examples_block,
|
||||
"example_rows": example_rows,
|
||||
"omitted": omitted,
|
||||
"requested": requested,
|
||||
"effective": {
|
||||
"include_core": core_included,
|
||||
"include_facet": facet_included,
|
||||
"include_traits": trait_count > 0,
|
||||
"include_style_examples": bool(example_rows),
|
||||
"trait_count": trait_count,
|
||||
"style_example_count": len(example_rows),
|
||||
"neutral_fallback": brief == NEUTRAL_JOURNAL_STYLE,
|
||||
"blocks": [
|
||||
{
|
||||
"key": "writing_profile",
|
||||
"included": bool(profile_block),
|
||||
"chars": len(profile_block),
|
||||
"estimated_tokens": _estimated_tokens(profile_block),
|
||||
},
|
||||
{
|
||||
"key": "core",
|
||||
"included": core_included,
|
||||
"chars": len(brief.split("Autobiografisches Journaling")[0]) if core_included else 0,
|
||||
"estimated_tokens": _estimated_tokens(brief) if core_included and not facet_included and trait_count == 0 else 0,
|
||||
},
|
||||
{
|
||||
"key": "facet",
|
||||
"included": facet_included,
|
||||
"chars": 0,
|
||||
"estimated_tokens": 0,
|
||||
},
|
||||
{
|
||||
"key": "traits",
|
||||
"included": trait_count > 0,
|
||||
"count": trait_count,
|
||||
"chars": 0,
|
||||
"estimated_tokens": 0,
|
||||
},
|
||||
{
|
||||
"key": "style_examples",
|
||||
"included": bool(examples_block),
|
||||
"count": len(example_rows),
|
||||
"chars": len(examples_block),
|
||||
"estimated_tokens": _estimated_tokens(examples_block),
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def style_application_trace(
|
||||
compiled_policy,
|
||||
bundle: dict,
|
||||
*,
|
||||
dropped: list[str] | None = None,
|
||||
) -> dict:
|
||||
dropped = list(dropped or [])
|
||||
omitted = [dict(item) for item in bundle.get("omitted") or []]
|
||||
effective = dict(bundle.get("effective") or {})
|
||||
example_rows = list(bundle.get("example_rows") or [])
|
||||
profile_block = bundle.get("profile_block") or ""
|
||||
examples_block = bundle.get("examples_block") or ""
|
||||
if "style_examples" in dropped:
|
||||
examples_block = ""
|
||||
example_rows = []
|
||||
effective["include_style_examples"] = False
|
||||
effective["style_example_count"] = 0
|
||||
if not any(item.get("part") == "style_examples" and item.get("reason") == "budget" for item in omitted):
|
||||
omitted.append({"part": "style_examples", "reason": "budget"})
|
||||
for block in effective.get("blocks") or []:
|
||||
if block.get("key") == "style_examples":
|
||||
block["included"] = False
|
||||
block["count"] = 0
|
||||
block["chars"] = 0
|
||||
block["estimated_tokens"] = 0
|
||||
brief = bundle.get("brief") or ""
|
||||
core_chars = 0
|
||||
facet_chars = 0
|
||||
trait_chars = 0
|
||||
if "Core:" in brief:
|
||||
core_part = brief.split("Autobiografisches Journaling")[0]
|
||||
core_chars = len(core_part.strip())
|
||||
if "Autobiografisches Journaling" in brief:
|
||||
rest = brief.split("Autobiografisches Journaling", 1)[1]
|
||||
facet_part = rest.split("\n- ", 1)[0]
|
||||
facet_chars = len(("Autobiografisches Journaling" + facet_part).strip())
|
||||
trait_lines = [line for line in brief.splitlines() if line.startswith("- ")]
|
||||
trait_chars = sum(len(line) for line in trait_lines)
|
||||
blocks = [
|
||||
{
|
||||
"key": "writing_profile",
|
||||
"included": bool(profile_block.strip()),
|
||||
"chars": len(profile_block),
|
||||
"estimated_tokens": _estimated_tokens(profile_block),
|
||||
},
|
||||
{
|
||||
"key": "core",
|
||||
"included": "Core:" in brief,
|
||||
"chars": core_chars,
|
||||
"estimated_tokens": _estimated_tokens(brief.split("\n", 1)[0] if "Core:" in brief else ""),
|
||||
},
|
||||
{
|
||||
"key": "facet",
|
||||
"included": "Autobiografisches Journaling" in brief,
|
||||
"chars": facet_chars,
|
||||
"estimated_tokens": _estimated_tokens("Autobiografisches Journaling" + brief.split("Autobiografisches Journaling", 1)[1].split("\n- ", 1)[0] if "Autobiografisches Journaling" in brief else ""),
|
||||
},
|
||||
{
|
||||
"key": "traits",
|
||||
"included": bool(trait_lines),
|
||||
"count": len(trait_lines),
|
||||
"chars": trait_chars,
|
||||
"estimated_tokens": _estimated_tokens("\n".join(trait_lines)),
|
||||
},
|
||||
{
|
||||
"key": "style_examples",
|
||||
"included": bool(examples_block.strip()),
|
||||
"count": len(example_rows),
|
||||
"chars": len(examples_block),
|
||||
"estimated_tokens": _estimated_tokens(examples_block),
|
||||
},
|
||||
]
|
||||
requested = bundle.get("requested") or dict(EMPTY_STYLE_CONTEXT)
|
||||
return {
|
||||
"id": compiled_policy.ids.get("voice") if compiled_policy else "",
|
||||
"key": compiled_policy.keys.get("voice") if compiled_policy else "",
|
||||
"label": compiled_policy.labels.get("voice") if compiled_policy else "",
|
||||
"revision": compiled_policy.revisions.get("voice") if compiled_policy else 1,
|
||||
"cloned_from": (compiled_policy.cloned_from.get("voice") if compiled_policy else "") or "",
|
||||
"requested": requested,
|
||||
"effective": {
|
||||
"include_core": any(block["key"] == "core" and block["included"] for block in blocks),
|
||||
"include_facet": any(block["key"] == "facet" and block["included"] for block in blocks),
|
||||
"trait_count": len(trait_lines),
|
||||
"style_example_count": len(example_rows),
|
||||
"neutral_fallback": bool((bundle.get("effective") or {}).get("neutral_fallback")),
|
||||
"blocks": blocks,
|
||||
},
|
||||
"omitted": omitted,
|
||||
"dropped_optional_blocks": dropped,
|
||||
}
|
||||
|
||||
|
||||
def _content_digest(text: str) -> str:
|
||||
body = re.sub(r"\s+", " ", plain_text(text or "")).strip().lower()
|
||||
return hashlib.sha256(body.encode("utf-8")).hexdigest()
|
||||
|
||||
+128
-11
@@ -5,17 +5,26 @@ import re
|
||||
|
||||
from context_builder import assemble_text, build_internal_context
|
||||
from debug_store import persist_engine_error, persist_step
|
||||
from detect_learning import (
|
||||
apply_review_decisions,
|
||||
drop_pending,
|
||||
is_bypass_mode,
|
||||
load_pending,
|
||||
save_pending,
|
||||
)
|
||||
from detect_pipeline import KIND_CONFIRM_REMOTE, apply_remote_confirm, prepare_detect_pipeline
|
||||
from dialogue_store import StoreError, list_conversations_for_day, list_messages
|
||||
from engine import EngineError, execute_prompt, load_active_prompt, preview_prompt
|
||||
from entity_detect import DetectError
|
||||
from journal_policy import require_explicit_generate, source_conversation_ids
|
||||
from identity_store import is_maskable_label, list_mappings, mapping_spellings
|
||||
from journal_body import clean_title
|
||||
from journal_editorial import (
|
||||
format_style_examples,
|
||||
compile_journal_style_application,
|
||||
incomplete_syntax_markers,
|
||||
lexical_similarity,
|
||||
narration_sources_text,
|
||||
select_journal_style_examples,
|
||||
style_application_trace,
|
||||
style_example_diagnostics,
|
||||
writing_profile_trace,
|
||||
)
|
||||
@@ -26,6 +35,7 @@ from journal_generation_policy import (
|
||||
draft_snapshot,
|
||||
mark_guidelines_used,
|
||||
policy_trace,
|
||||
prompt_without_orphaned_style_example_rule,
|
||||
resolve_run_selection,
|
||||
)
|
||||
from journal_reconstruct import (
|
||||
@@ -45,6 +55,7 @@ from prompt_budget import (
|
||||
from privacy_gateway import (
|
||||
GENERIC_PLACEHOLDER_INNER,
|
||||
canonical_token,
|
||||
compact_diagnostics,
|
||||
identity_label_pattern,
|
||||
identity_occurrence_count,
|
||||
is_identity_mention,
|
||||
@@ -201,6 +212,8 @@ def _compose_journal_trace(
|
||||
narrate_trace["writing_profile"] = profile_meta
|
||||
narrate_trace["style_examples"] = {**style_meta, "dropped": "style_examples" in dropped}
|
||||
narrate_trace["dropped_optional_blocks"] = dropped
|
||||
if extra and extra.get("style_application"):
|
||||
narrate_trace["style_application"] = extra["style_application"]
|
||||
diag = narrate_result.get("diagnostics") or {}
|
||||
if diag.get("generate_ms") is not None:
|
||||
narrate_trace["generate_ms"] = diag.get("generate_ms")
|
||||
@@ -221,8 +234,9 @@ def _compose_journal_trace(
|
||||
"prompt_revision": narrate_trace.get("prompt_revision"),
|
||||
"writing_profile": profile_meta,
|
||||
"style_examples": narrate_trace.get("style_examples"),
|
||||
"style_application": narrate_trace.get("style_application") or (extra or {}).get("style_application"),
|
||||
"dropped_optional_blocks": dropped,
|
||||
"log": run_log,
|
||||
"log": [dict(item) if isinstance(item, dict) else item for item in run_log],
|
||||
"stages": [reconstruct_trace, narrate_trace],
|
||||
}
|
||||
|
||||
@@ -264,11 +278,17 @@ def _raise_budget(exc: JournalBudgetError) -> None:
|
||||
|
||||
|
||||
def _stage_trace(result: dict, fallback_purpose: str) -> dict:
|
||||
trace = dict(result.get("trace") or {})
|
||||
if result.get("diagnostics"):
|
||||
trace["budget"] = result.get("diagnostics")
|
||||
elif not trace.get("budget"):
|
||||
source = result.get("trace")
|
||||
trace = dict(source) if isinstance(source, dict) else {}
|
||||
budget_src = result.get("diagnostics")
|
||||
if not isinstance(budget_src, dict):
|
||||
budget_src = trace.get("budget") if isinstance(trace.get("budget"), dict) else None
|
||||
if isinstance(budget_src, dict):
|
||||
trace["budget"] = compact_diagnostics(budget_src)
|
||||
else:
|
||||
trace["budget"] = None
|
||||
if "log" in trace and isinstance(trace["log"], list):
|
||||
trace["log"] = [dict(item) if isinstance(item, dict) else item for item in trace["log"]]
|
||||
trace["purpose"] = trace.get("purpose") or fallback_purpose
|
||||
return trace
|
||||
|
||||
@@ -333,7 +353,11 @@ def pack_narration_context(
|
||||
candidate = dict(assembled)
|
||||
candidate["style_examples"] = examples
|
||||
candidate["existing_text"] = existing
|
||||
rendered = preview_prompt(prompt, candidate)["rendered"]
|
||||
fit_prompt = prompt_without_orphaned_style_example_rule(
|
||||
prompt,
|
||||
include_style_examples=bool((examples or "").strip()),
|
||||
)
|
||||
rendered = preview_prompt(fit_prompt, candidate)["rendered"]
|
||||
try:
|
||||
assert_input_fits(budget, rendered)
|
||||
if not examples and style_examples:
|
||||
@@ -357,6 +381,7 @@ def generate_draft(
|
||||
explicit: bool = True,
|
||||
generation_selection: dict | None = None,
|
||||
remember_generation_selection: bool = False,
|
||||
precomputed_mappings: list[dict] | None = None,
|
||||
) -> dict:
|
||||
try:
|
||||
draft = _generate_draft(
|
||||
@@ -367,6 +392,7 @@ def generate_draft(
|
||||
explicit=explicit,
|
||||
generation_selection=generation_selection,
|
||||
remember_generation_selection=remember_generation_selection,
|
||||
precomputed_mappings=precomputed_mappings,
|
||||
)
|
||||
except EngineError as exc:
|
||||
persist_engine_error(
|
||||
@@ -379,6 +405,8 @@ def generate_draft(
|
||||
extra={"conversation_ids": conversation_ids or []},
|
||||
)
|
||||
raise
|
||||
if draft.get("pending_mask_review"):
|
||||
return draft
|
||||
persist_step(
|
||||
profile_id,
|
||||
purpose="journal_generate",
|
||||
@@ -408,6 +436,7 @@ def _generate_draft(
|
||||
explicit: bool = True,
|
||||
generation_selection: dict | None = None,
|
||||
remember_generation_selection: bool = False,
|
||||
precomputed_mappings: list[dict] | None = None,
|
||||
) -> dict:
|
||||
require_explicit_generate(explicit)
|
||||
day = get_day(profile_id, journal_day_id)
|
||||
@@ -464,12 +493,20 @@ def _generate_draft(
|
||||
source=persist_meta["source"],
|
||||
remembered=persist_meta["remembered"],
|
||||
)
|
||||
profile_meta = writing_profile_trace(profile_id)
|
||||
style_example_rows = select_journal_style_examples(
|
||||
style_bundle = compile_journal_style_application(
|
||||
profile_id,
|
||||
compiled_policy.style_context,
|
||||
exclude_dates=[day.get("calendar_date") or ""],
|
||||
)
|
||||
style_examples = format_style_examples(style_example_rows)
|
||||
profile_meta = writing_profile_trace(
|
||||
profile_id,
|
||||
style_context=compiled_policy.style_context,
|
||||
brief=style_bundle.get("brief") or "",
|
||||
trait_count=(style_bundle.get("effective") or {}).get("trait_count"),
|
||||
)
|
||||
style_example_rows = list(style_bundle.get("example_rows") or [])
|
||||
style_examples = style_bundle.get("examples_block") or ""
|
||||
writing_profile = style_bundle.get("profile_block") or ""
|
||||
style_meta = style_example_diagnostics(style_example_rows)
|
||||
run_log: list[dict] = []
|
||||
_event(
|
||||
@@ -503,6 +540,7 @@ def _generate_draft(
|
||||
existing_text=existing_text,
|
||||
conversation_id=selected[0] if selected else None,
|
||||
reconstruction=narration_sources_text(reconstruction),
|
||||
writing_profile=writing_profile,
|
||||
style_examples=style_examples,
|
||||
transformation_instructions=compiled_policy.instructions["transformation_instructions"],
|
||||
detail_instructions=compiled_policy.instructions["detail_instructions"],
|
||||
@@ -523,13 +561,61 @@ def _generate_draft(
|
||||
_raise_budget(exc)
|
||||
if dropped:
|
||||
_event(run_log, "journal_generate", "budget_pack", dropped=",".join(dropped))
|
||||
style_app = style_application_trace(compiled_policy, style_bundle, dropped=dropped)
|
||||
if "style_examples" in dropped:
|
||||
style_meta = {**style_example_diagnostics([]), "dropped": True, "dropped_reason": "budget"}
|
||||
else:
|
||||
style_meta = {**style_meta, "dropped": False}
|
||||
profile_meta["brief_chars"] = len((assembled.get("writing_profile") or "").strip())
|
||||
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:
|
||||
narrate_prompt = prompt_without_orphaned_style_example_rule(
|
||||
narrate_prompt,
|
||||
include_style_examples=bool((assembled.get("style_examples") or "").strip()),
|
||||
)
|
||||
rendered_preview = preview_prompt(narrate_prompt, assembled)
|
||||
assert_template_resolved(rendered_preview.get("rendered") or "")
|
||||
detect_mappings = precomputed_mappings
|
||||
if detect_mappings is None and not is_bypass_mode():
|
||||
user_text = "\n".join(source_user)
|
||||
pipe = prepare_detect_pipeline(profile_id, user_text, "")
|
||||
if (pipe.need_review or pipe.candidates) and selected:
|
||||
review_id = save_pending(
|
||||
profile_id,
|
||||
selected[0],
|
||||
"",
|
||||
{
|
||||
"mappings": pipe.mappings,
|
||||
"candidates": pipe.candidates,
|
||||
"user_body": user_text,
|
||||
"kind": pipe.kind,
|
||||
"counters": pipe.counters,
|
||||
"purpose": "journal_generate",
|
||||
"generate": {
|
||||
"journal_day_id": journal_day_id,
|
||||
"conversation_ids": selected,
|
||||
"include_existing": include_existing,
|
||||
"generation_selection": generation_selection,
|
||||
"remember_generation_selection": remember_generation_selection,
|
||||
},
|
||||
},
|
||||
)
|
||||
return {
|
||||
"pending_mask_review": {
|
||||
"id": review_id,
|
||||
"candidates": pipe.candidates,
|
||||
"kind": pipe.kind,
|
||||
"purpose": "journal_generate",
|
||||
},
|
||||
"run_log": run_log,
|
||||
"trace": None,
|
||||
}
|
||||
detect_mappings = pipe.mappings
|
||||
assembled = dict(assembled)
|
||||
assembled["user_body"] = "\n".join(source_user)
|
||||
narrate_result = execute_prompt(
|
||||
narrate_prompt,
|
||||
profile_id,
|
||||
@@ -539,6 +625,7 @@ def _generate_draft(
|
||||
max_tokens=narrate_budget.reserved_output_tokens,
|
||||
disable_context_compression=True,
|
||||
budget=narrate_budget,
|
||||
precomputed_mappings=detect_mappings,
|
||||
)
|
||||
_stamp_log(run_log, "journal_generate", _log_items(narrate_result))
|
||||
title, body = _split_title(narrate_result.get("content") or "")
|
||||
@@ -575,6 +662,7 @@ def _generate_draft(
|
||||
"abort_reason": unattested,
|
||||
"source_preview": source_preview,
|
||||
"generation_selection": policy_meta,
|
||||
"style_application": style_app,
|
||||
},
|
||||
)
|
||||
_reject_generation(
|
||||
@@ -622,6 +710,7 @@ def _generate_draft(
|
||||
"abort_reason": exc.code,
|
||||
"source_preview": source_preview,
|
||||
"generation_selection": policy_meta,
|
||||
"style_application": style_app,
|
||||
},
|
||||
)
|
||||
diag["log"] = run_log
|
||||
@@ -700,6 +789,7 @@ def _generate_draft(
|
||||
"lexical_similarity": lexical_similarity("\n".join(source_user), body),
|
||||
"incomplete_syntax": incomplete_syntax_markers(body),
|
||||
"generation_selection": policy_meta,
|
||||
"style_application": style_app,
|
||||
"stored_title": title,
|
||||
"stored_body": body,
|
||||
"reply": stored,
|
||||
@@ -708,3 +798,30 @@ def _generate_draft(
|
||||
draft["run_log"] = run_log
|
||||
draft["trace"] = bundle
|
||||
return draft
|
||||
|
||||
|
||||
def continue_journal_generate(profile_id: str, journal_day_id: str, review_id: str, decisions: list[dict]) -> dict:
|
||||
pending = load_pending(profile_id, review_id)
|
||||
if not pending or pending.get("purpose") != "journal_generate":
|
||||
raise EngineError("mask_review_missing", "Die Maskierungsprüfung ist nicht mehr gültig.", 404)
|
||||
generate = pending.get("generate") or {}
|
||||
if generate.get("journal_day_id") != journal_day_id:
|
||||
raise EngineError("mask_review_missing", "Die Maskierungsprüfung ist nicht mehr gültig.", 404)
|
||||
if pending.get("kind") == KIND_CONFIRM_REMOTE:
|
||||
try:
|
||||
mappings = apply_remote_confirm(profile_id, pending, decisions)
|
||||
except DetectError as exc:
|
||||
raise EngineError(exc.code, exc.message, getattr(exc, "status_code", 403)) from exc
|
||||
else:
|
||||
mappings = apply_review_decisions(profile_id, pending, decisions)
|
||||
drop_pending(profile_id, review_id)
|
||||
return generate_draft(
|
||||
profile_id,
|
||||
journal_day_id,
|
||||
conversation_ids=generate.get("conversation_ids"),
|
||||
include_existing=bool(generate.get("include_existing")),
|
||||
explicit=True,
|
||||
generation_selection=generate.get("generation_selection"),
|
||||
remember_generation_selection=bool(generate.get("remember_generation_selection")),
|
||||
precomputed_mappings=mappings,
|
||||
)
|
||||
@@ -63,6 +63,46 @@ MAX_LABEL_CHARS = 80
|
||||
MAX_SUMMARY_CHARS = 160
|
||||
KEY_RE = re.compile(r"^[a-z][a-z0-9_]{0,40}$")
|
||||
SEED_PATH = Path(__file__).resolve().parent / "config" / "generation_instructions.seed.json"
|
||||
STYLE_CONTEXT_KEYS = (
|
||||
"include_core",
|
||||
"include_facet",
|
||||
"include_traits",
|
||||
"include_style_examples",
|
||||
)
|
||||
EMPTY_STYLE_CONTEXT = {key: False for key in STYLE_CONTEXT_KEYS}
|
||||
FULL_STYLE_CONTEXT = {key: True for key in STYLE_CONTEXT_KEYS}
|
||||
LEGACY_VOICE_STYLE_CONTEXT = {
|
||||
"neutral": dict(EMPTY_STYLE_CONTEXT),
|
||||
"light": {**EMPTY_STYLE_CONTEXT, "include_core": True},
|
||||
"noticeable": {
|
||||
"include_core": True,
|
||||
"include_facet": True,
|
||||
"include_traits": True,
|
||||
"include_style_examples": False,
|
||||
},
|
||||
"clear": {
|
||||
"include_core": True,
|
||||
"include_facet": True,
|
||||
"include_traits": True,
|
||||
"include_style_examples": False,
|
||||
},
|
||||
"with_examples": dict(FULL_STYLE_CONTEXT),
|
||||
"legacy_neutral": dict(FULL_STYLE_CONTEXT),
|
||||
"legacy_light": dict(FULL_STYLE_CONTEXT),
|
||||
"legacy_noticeable": dict(FULL_STYLE_CONTEXT),
|
||||
"legacy_clear": dict(FULL_STYLE_CONTEXT),
|
||||
}
|
||||
LEGACY_COMPARISON_KEYS = frozenset(
|
||||
{
|
||||
"legacy_neutral",
|
||||
"legacy_light",
|
||||
"legacy_noticeable",
|
||||
"legacy_clear",
|
||||
}
|
||||
)
|
||||
STYLE_EXAMPLES_STANDING_SENTENCE = (
|
||||
"STYLE_EXAMPLES dienen ausschließlich als Stilreferenz; ihre Inhalte gehören nicht zum heutigen Tag. "
|
||||
)
|
||||
PUBLIC_FIELDS = (
|
||||
"id",
|
||||
"purpose",
|
||||
@@ -108,6 +148,8 @@ class CompiledPolicy:
|
||||
revisions: dict[str, int]
|
||||
instructions: dict[str, str]
|
||||
seed_revision: str
|
||||
style_context: dict[str, bool]
|
||||
cloned_from: dict[str, str]
|
||||
|
||||
|
||||
def load_seed_document() -> dict:
|
||||
@@ -118,6 +160,95 @@ def _as_bool(raw) -> bool:
|
||||
return bool(int(raw)) if not isinstance(raw, bool) else raw
|
||||
|
||||
|
||||
def default_style_context_for_key(guideline_key: str, *, slot: str) -> dict[str, bool]:
|
||||
if slot != "voice":
|
||||
return {}
|
||||
mapped = LEGACY_VOICE_STYLE_CONTEXT.get((guideline_key or "").strip())
|
||||
if mapped:
|
||||
return dict(mapped)
|
||||
return dict(FULL_STYLE_CONTEXT)
|
||||
|
||||
|
||||
def normalize_style_context(raw, *, slot: str, required: bool = False) -> dict[str, bool]:
|
||||
if slot != "voice":
|
||||
if raw in (None, "", {}, []):
|
||||
return {}
|
||||
raise CatalogError(
|
||||
"Stilkontext gehört nur zur Dimension Persönliche Stimme.",
|
||||
code="invalid_generation_guideline",
|
||||
status_code=400,
|
||||
)
|
||||
if raw in (None, "", {}):
|
||||
if required:
|
||||
raise CatalogError(
|
||||
"Die Stilanwendung braucht eine Stilkontext-Konfiguration.",
|
||||
code="invalid_generation_guideline",
|
||||
status_code=400,
|
||||
)
|
||||
return dict(EMPTY_STYLE_CONTEXT)
|
||||
if not isinstance(raw, dict):
|
||||
raise CatalogError(
|
||||
"style_context muss ein Objekt mit den vier Stilquellen sein.",
|
||||
code="invalid_generation_guideline",
|
||||
status_code=400,
|
||||
)
|
||||
unknown = sorted(set(raw) - set(STYLE_CONTEXT_KEYS))
|
||||
if unknown:
|
||||
raise CatalogError(
|
||||
"Unbekannte Stilquellen: " + ", ".join(unknown),
|
||||
code="invalid_generation_guideline",
|
||||
status_code=400,
|
||||
)
|
||||
missing = [key for key in STYLE_CONTEXT_KEYS if key not in raw]
|
||||
if missing and required:
|
||||
raise CatalogError(
|
||||
"style_context ist unvollständig: " + ", ".join(missing),
|
||||
code="invalid_generation_guideline",
|
||||
status_code=400,
|
||||
)
|
||||
parsed: dict[str, bool] = dict(EMPTY_STYLE_CONTEXT)
|
||||
for key in STYLE_CONTEXT_KEYS:
|
||||
if key not in raw:
|
||||
continue
|
||||
value = raw[key]
|
||||
if isinstance(value, bool):
|
||||
parsed[key] = value
|
||||
elif value in (0, 1):
|
||||
parsed[key] = bool(value)
|
||||
else:
|
||||
raise CatalogError(
|
||||
f"{key} muss wahr oder falsch sein, keine Gewichtung.",
|
||||
code="invalid_generation_guideline",
|
||||
status_code=400,
|
||||
)
|
||||
return parsed
|
||||
|
||||
|
||||
def parse_style_context_json(raw, *, slot: str, guideline_key: str = "") -> dict[str, bool]:
|
||||
if slot != "voice":
|
||||
return {}
|
||||
text = (raw or "").strip()
|
||||
if not text or text in ("{}", "null"):
|
||||
return default_style_context_for_key(guideline_key, slot=slot)
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return default_style_context_for_key(guideline_key, slot=slot)
|
||||
if not isinstance(data, dict) or not any(key in data for key in STYLE_CONTEXT_KEYS):
|
||||
return default_style_context_for_key(guideline_key, slot=slot)
|
||||
try:
|
||||
return normalize_style_context(data, slot=slot, required=False)
|
||||
except CatalogError:
|
||||
return default_style_context_for_key(guideline_key, slot=slot)
|
||||
|
||||
|
||||
def style_context_json(context: dict[str, bool] | None, *, slot: str) -> str:
|
||||
if slot != "voice":
|
||||
return "{}"
|
||||
payload = normalize_style_context(context or EMPTY_STYLE_CONTEXT, slot=slot, required=False)
|
||||
return json.dumps(payload, ensure_ascii=False, sort_keys=True)
|
||||
|
||||
|
||||
def _limits() -> tuple[int, int, int]:
|
||||
seed = load_seed_document()
|
||||
return (
|
||||
@@ -156,6 +287,11 @@ def _row(item: dict | None, *, include_instruction: bool = False) -> dict | None
|
||||
payload["revision"] = int(item.get("revision") or 1)
|
||||
payload["sort_order"] = int(item.get("sort_order") or 0)
|
||||
payload["guideline_key"] = item.get("guideline_key") or ""
|
||||
payload["style_context"] = parse_style_context_json(
|
||||
item.get("style_context_json"),
|
||||
slot=item.get("slot") or "",
|
||||
guideline_key=payload["guideline_key"],
|
||||
)
|
||||
if include_instruction:
|
||||
payload["instruction"] = item.get("instruction") or ""
|
||||
payload["seed_id"] = item.get("seed_id") or ""
|
||||
@@ -222,6 +358,7 @@ def active_user_options(purpose: str = PURPOSE_JOURNAL) -> dict[str, list[dict]]
|
||||
"summary": item["summary"],
|
||||
"revision": item["revision"],
|
||||
"is_default": item["is_default"],
|
||||
"style_context": item.get("style_context") or {},
|
||||
}
|
||||
for item in items
|
||||
if item["slot"] == slot
|
||||
@@ -296,6 +433,12 @@ def compile_selection(
|
||||
revisions={slot: int(chosen[slot].get("revision") or 1) for slot in USER_SLOTS},
|
||||
instructions=instructions,
|
||||
seed_revision=revision,
|
||||
style_context=parse_style_context_json(
|
||||
chosen["voice"].get("style_context_json"),
|
||||
slot="voice",
|
||||
guideline_key=chosen["voice"].get("guideline_key") or "",
|
||||
),
|
||||
cloned_from={slot: chosen[slot].get("cloned_from") or "" for slot in USER_SLOTS},
|
||||
)
|
||||
|
||||
|
||||
@@ -313,6 +456,8 @@ def policy_trace(
|
||||
"labels": dict(compiled.labels),
|
||||
"revisions": dict(compiled.revisions),
|
||||
"seed_revision": compiled.seed_revision,
|
||||
"style_context": dict(compiled.style_context),
|
||||
"cloned_from": dict(compiled.cloned_from),
|
||||
}
|
||||
|
||||
|
||||
@@ -336,6 +481,8 @@ def draft_snapshot(compiled: CompiledPolicy, *, prompt: dict | None = None, mode
|
||||
"key": compiled.keys["voice"],
|
||||
"label": compiled.labels["voice"],
|
||||
"revision": compiled.revisions["voice"],
|
||||
"cloned_from": compiled.cloned_from.get("voice") or "",
|
||||
"style_context": dict(compiled.style_context),
|
||||
},
|
||||
"narrative": {
|
||||
"id": compiled.ids["narrative"],
|
||||
@@ -397,6 +544,25 @@ def assert_template_resolved(rendered: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
def omit_orphaned_style_example_rule(template: str) -> str:
|
||||
"""Drop the standing STYLE_EXAMPLES sentence when no example block is sent."""
|
||||
text = template or ""
|
||||
return text.replace(STYLE_EXAMPLES_STANDING_SENTENCE, "").replace(
|
||||
"STYLE_EXAMPLES dienen ausschließlich als Stilreferenz; ihre Inhalte gehören nicht zum heutigen Tag.",
|
||||
"",
|
||||
)
|
||||
|
||||
|
||||
def prompt_without_orphaned_style_example_rule(prompt: dict, *, include_style_examples: bool) -> dict:
|
||||
if include_style_examples:
|
||||
return prompt
|
||||
template = prompt.get("template") or ""
|
||||
cleaned = omit_orphaned_style_example_rule(template)
|
||||
if cleaned == template:
|
||||
return prompt
|
||||
return {**prompt, "template": cleaned}
|
||||
|
||||
|
||||
def load_selection(profile_id: str) -> dict[str, str] | None:
|
||||
with get_db() as conn:
|
||||
row = row_to_dict(
|
||||
@@ -497,21 +663,28 @@ def mark_guidelines_used(ids: list[str]) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _write_fields(raw: dict) -> dict:
|
||||
def _write_fields(raw: dict, *, slot: str) -> dict:
|
||||
max_instruction, max_label, max_summary = _limits()
|
||||
style_context = normalize_style_context(
|
||||
raw.get("style_context"),
|
||||
slot=slot,
|
||||
required=False,
|
||||
)
|
||||
return {
|
||||
"guideline_key": _clean_key(raw.get("guideline_key") or raw.get("key")),
|
||||
"label": _clean_text(raw.get("label"), "label", max_chars=max_label),
|
||||
"summary": _clean_text(raw.get("summary"), "summary", max_chars=max_summary, allow_empty=True),
|
||||
"instruction": _clean_text(raw.get("instruction"), "instruction", max_chars=max_instruction),
|
||||
"sort_order": int(raw.get("sort_order") or 0),
|
||||
"style_context": style_context,
|
||||
"style_context_json": style_context_json(style_context, slot=slot),
|
||||
}
|
||||
|
||||
|
||||
def create_guideline(purpose: str, slot: str, body: dict) -> dict:
|
||||
if slot not in ALLOWED_SLOTS:
|
||||
raise CatalogError("Unbekannter Slot.", code="invalid_generation_guideline", status_code=400)
|
||||
fields = _write_fields(body)
|
||||
fields = _write_fields(body, slot=slot)
|
||||
guideline_id = str(uuid.uuid4())
|
||||
with get_db() as conn:
|
||||
count = conn.execute(
|
||||
@@ -521,11 +694,11 @@ def create_guideline(purpose: str, slot: str, body: dict) -> dict:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO generation_guidelines (
|
||||
id, purpose, slot, guideline_key, label, summary, instruction, sort_order,
|
||||
id, purpose, slot, guideline_key, label, summary, instruction, style_context_json, sort_order,
|
||||
status, revision, cloned_from, is_default, is_system_seed, seed_id, seed_revision,
|
||||
created, updated
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL, 0, 0, '', '', datetime('now'), datetime('now'))
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL, 0, 0, '', '', datetime('now'), datetime('now'))
|
||||
""",
|
||||
(
|
||||
guideline_id,
|
||||
@@ -535,6 +708,7 @@ def create_guideline(purpose: str, slot: str, body: dict) -> dict:
|
||||
fields["label"],
|
||||
fields["summary"],
|
||||
fields["instruction"],
|
||||
fields["style_context_json"],
|
||||
fields["sort_order"] if body.get("sort_order") is not None else int(count) + 1,
|
||||
STATUS_DRAFT,
|
||||
),
|
||||
@@ -557,11 +731,11 @@ def clone_guideline(guideline_id: str) -> dict:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO generation_guidelines (
|
||||
id, purpose, slot, guideline_key, label, summary, instruction, sort_order,
|
||||
id, purpose, slot, guideline_key, label, summary, instruction, style_context_json, sort_order,
|
||||
status, revision, cloned_from, is_default, is_system_seed, seed_id, seed_revision,
|
||||
created, updated
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, '', ?, datetime('now'), datetime('now'))
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, '', ?, datetime('now'), datetime('now'))
|
||||
""",
|
||||
(
|
||||
new_id,
|
||||
@@ -571,6 +745,14 @@ def clone_guideline(guideline_id: str) -> dict:
|
||||
current["label"],
|
||||
current["summary"],
|
||||
current["instruction"],
|
||||
current.get("style_context_json") or style_context_json(
|
||||
parse_style_context_json(
|
||||
current.get("style_context_json"),
|
||||
slot=current.get("slot") or "",
|
||||
guideline_key=current.get("guideline_key") or "",
|
||||
),
|
||||
slot=current.get("slot") or "",
|
||||
),
|
||||
int(current.get("sort_order") or 0),
|
||||
STATUS_DRAFT,
|
||||
int(current.get("revision") or 1) + 1,
|
||||
@@ -591,13 +773,20 @@ def update_guideline(guideline_id: str, body: dict) -> dict:
|
||||
code="guideline_immutable",
|
||||
status_code=409,
|
||||
)
|
||||
fields = _write_fields({**current, **body, "guideline_key": body.get("guideline_key") or current["guideline_key"]})
|
||||
merged = {**current, **body, "guideline_key": body.get("guideline_key") or current["guideline_key"]}
|
||||
if "style_context" not in body:
|
||||
merged["style_context"] = parse_style_context_json(
|
||||
current.get("style_context_json"),
|
||||
slot=current.get("slot") or "",
|
||||
guideline_key=current.get("guideline_key") or "",
|
||||
)
|
||||
fields = _write_fields(merged, slot=current.get("slot") or "")
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE generation_guidelines
|
||||
SET guideline_key = ?, label = ?, summary = ?, instruction = ?, sort_order = ?,
|
||||
updated = datetime('now')
|
||||
SET guideline_key = ?, label = ?, summary = ?, instruction = ?, style_context_json = ?,
|
||||
sort_order = ?, updated = datetime('now')
|
||||
WHERE id = ?
|
||||
""",
|
||||
(
|
||||
@@ -605,6 +794,7 @@ def update_guideline(guideline_id: str, body: dict) -> dict:
|
||||
fields["label"],
|
||||
fields["summary"],
|
||||
fields["instruction"],
|
||||
fields["style_context_json"],
|
||||
fields["sort_order"],
|
||||
guideline_id,
|
||||
),
|
||||
@@ -622,6 +812,16 @@ def publish_guideline(guideline_id: str) -> dict:
|
||||
_clean_text(current.get("label"), "label", max_chars=max_label)
|
||||
_clean_text(current.get("summary"), "summary", max_chars=max_summary, allow_empty=True)
|
||||
_clean_text(current.get("instruction"), "instruction", max_chars=max_instruction)
|
||||
if current.get("slot") == "voice":
|
||||
normalize_style_context(
|
||||
parse_style_context_json(
|
||||
current.get("style_context_json"),
|
||||
slot="voice",
|
||||
guideline_key=current.get("guideline_key") or "",
|
||||
),
|
||||
slot="voice",
|
||||
required=True,
|
||||
)
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"UPDATE generation_guidelines SET status = ?, updated = datetime('now') WHERE id = ?",
|
||||
@@ -711,6 +911,7 @@ def reset_seed_drafts(purpose: str = PURPOSE_JOURNAL) -> dict:
|
||||
"summary": item.get("summary") or "",
|
||||
"instruction": item.get("instruction") or "",
|
||||
"sort_order": index,
|
||||
"style_context": item.get("style_context") or {},
|
||||
},
|
||||
)
|
||||
)
|
||||
@@ -725,12 +926,17 @@ def preview_selection(selection: dict[str, str], *, purpose: str = PURPOSE_JOURN
|
||||
compiled = compile_selection(selection, purpose=purpose)
|
||||
prompt = load_active_prompt("mvp.journal_generate")
|
||||
assert_journal_prompt_contract(prompt.get("template") or "")
|
||||
include_examples = bool(compiled.style_context.get("include_style_examples"))
|
||||
prompt = prompt_without_orphaned_style_example_rule(
|
||||
prompt,
|
||||
include_style_examples=include_examples,
|
||||
)
|
||||
rendered = preview_prompt(
|
||||
prompt,
|
||||
{
|
||||
**compiled.instructions,
|
||||
"writing_profile": "(nicht enthalten)",
|
||||
"style_examples": "(nicht enthalten)",
|
||||
"style_examples": "(Stilbeispiele)" if include_examples else "",
|
||||
"reconstruction": "(nicht enthalten)",
|
||||
"existing_text": "",
|
||||
},
|
||||
@@ -746,6 +952,8 @@ def preview_selection(selection: dict[str, str], *, purpose: str = PURPOSE_JOURN
|
||||
"keys": dict(compiled.keys),
|
||||
"labels": dict(compiled.labels),
|
||||
"revisions": dict(compiled.revisions),
|
||||
"cloned_from": dict(compiled.cloned_from),
|
||||
"style_context": dict(compiled.style_context),
|
||||
},
|
||||
"seed_revision": compiled.seed_revision,
|
||||
}
|
||||
@@ -758,6 +966,7 @@ def _seed_rows(seed: dict, purpose: str) -> list[tuple]:
|
||||
for slot in ALLOWED_SLOTS:
|
||||
variants = (slots.get(slot) or {}).get("variants") or []
|
||||
for index, item in enumerate(variants):
|
||||
context = normalize_style_context(item.get("style_context") or {}, slot=slot, required=False)
|
||||
rows.append(
|
||||
(
|
||||
item.get("id") or str(uuid.uuid4()),
|
||||
@@ -767,6 +976,7 @@ def _seed_rows(seed: dict, purpose: str) -> list[tuple]:
|
||||
item.get("label") or "",
|
||||
item.get("summary") or "",
|
||||
item.get("instruction") or "",
|
||||
style_context_json(context, slot=slot),
|
||||
index,
|
||||
STATUS_ACTIVE,
|
||||
1,
|
||||
@@ -779,9 +989,132 @@ def _seed_rows(seed: dict, purpose: str) -> list[tuple]:
|
||||
return rows
|
||||
|
||||
|
||||
def seed_generation_instructions(conn) -> None:
|
||||
"""Insert missing seed guidelines. Never overwrite published or admin-created rows."""
|
||||
seed = load_seed_document()
|
||||
def _semantic_signature(item: dict | None = None, *, seed_row: tuple | None = None) -> tuple:
|
||||
if seed_row is not None:
|
||||
slot = seed_row[2] or ""
|
||||
key = seed_row[3] or ""
|
||||
return (
|
||||
key,
|
||||
seed_row[4] or "",
|
||||
seed_row[5] or "",
|
||||
seed_row[6] or "",
|
||||
style_context_json(
|
||||
parse_style_context_json(seed_row[7], slot=slot, guideline_key=key),
|
||||
slot=slot,
|
||||
),
|
||||
)
|
||||
slot = (item or {}).get("slot") or ""
|
||||
key = (item or {}).get("guideline_key") or ""
|
||||
return (
|
||||
key,
|
||||
(item or {}).get("label") or "",
|
||||
(item or {}).get("summary") or "",
|
||||
(item or {}).get("instruction") or "",
|
||||
style_context_json(
|
||||
parse_style_context_json((item or {}).get("style_context_json"), slot=slot, guideline_key=key),
|
||||
slot=slot,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _successor_id(base_id: str, revision: int) -> str:
|
||||
root = re.sub(r"-r\d+$", "", base_id or "")
|
||||
return f"{root}-r{int(revision)}"
|
||||
|
||||
|
||||
def _catalog_maps(conn, purpose: str) -> tuple[dict, dict]:
|
||||
rows = [row_to_dict(row) for row in conn.execute(
|
||||
"SELECT * FROM generation_guidelines WHERE purpose = ?",
|
||||
(purpose,),
|
||||
).fetchall()]
|
||||
by_id = {row["id"]: row for row in rows}
|
||||
by_seed_id = {row["seed_id"]: row for row in rows if row.get("seed_id")}
|
||||
return by_id, by_seed_id
|
||||
|
||||
|
||||
def _find_existing_seed_row(by_id: dict, by_seed_id: dict, seed_row: tuple, all_rows: list[dict]) -> dict | None:
|
||||
current = by_id.get(seed_row[0]) or by_seed_id.get(seed_row[13])
|
||||
if current:
|
||||
return current
|
||||
key = seed_row[3] or ""
|
||||
slot = seed_row[2] or ""
|
||||
if key not in LEGACY_COMPARISON_KEYS:
|
||||
return None
|
||||
for item in all_rows:
|
||||
if item.get("slot") == slot and item.get("guideline_key") == key:
|
||||
return item
|
||||
return None
|
||||
|
||||
|
||||
def _find_matching_successor(all_rows: list[dict], predecessor_id: str, seed_row: tuple) -> dict | None:
|
||||
wanted = _semantic_signature(seed_row=seed_row)
|
||||
for item in all_rows:
|
||||
if (item.get("cloned_from") or "") != predecessor_id:
|
||||
continue
|
||||
if _semantic_signature(item) == wanted:
|
||||
return item
|
||||
return None
|
||||
|
||||
|
||||
def _insert_seed_guideline(
|
||||
conn,
|
||||
seed_row: tuple,
|
||||
*,
|
||||
guideline_id: str | None = None,
|
||||
cloned_from: str | None = None,
|
||||
revision: int | None = None,
|
||||
is_default: int | None = None,
|
||||
) -> None:
|
||||
row_id = guideline_id or seed_row[0]
|
||||
seed_id = row_id if guideline_id else seed_row[13]
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO generation_guidelines (
|
||||
id, purpose, slot, guideline_key, label, summary, instruction, style_context_json, sort_order,
|
||||
status, revision, cloned_from, is_default, is_system_seed, seed_id, seed_revision,
|
||||
created, updated
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
|
||||
""",
|
||||
(
|
||||
row_id,
|
||||
seed_row[1],
|
||||
seed_row[2],
|
||||
seed_row[3],
|
||||
seed_row[4],
|
||||
seed_row[5],
|
||||
seed_row[6],
|
||||
seed_row[7],
|
||||
seed_row[8],
|
||||
STATUS_ACTIVE,
|
||||
int(revision if revision is not None else seed_row[10] or 1),
|
||||
cloned_from,
|
||||
int(is_default if is_default is not None else seed_row[11] or 0),
|
||||
1,
|
||||
seed_id,
|
||||
seed_row[14],
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _assign_slot_default(conn, purpose: str, slot: str, guideline_id: str) -> None:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE generation_guidelines
|
||||
SET is_default = CASE WHEN id = ? THEN 1 ELSE 0 END, updated = datetime('now')
|
||||
WHERE purpose = ? AND slot = ? AND status = ?
|
||||
""",
|
||||
(guideline_id, purpose, slot, STATUS_ACTIVE),
|
||||
)
|
||||
|
||||
|
||||
def seed_generation_instructions(conn, seed: dict | None = None) -> None:
|
||||
"""Insert missing seed guidelines. Never rewrite existing IDs, clones, or archives.
|
||||
|
||||
A semantic change in the seed creates a new successor ID. New defaults may
|
||||
point at that successor. Stored selections keep their previous IDs.
|
||||
"""
|
||||
seed = seed if seed is not None else load_seed_document()
|
||||
purpose = seed.get("purpose") or PURPOSE_JOURNAL
|
||||
conn.execute(
|
||||
"""
|
||||
@@ -791,34 +1124,42 @@ def seed_generation_instructions(conn) -> None:
|
||||
""",
|
||||
(STATUS_ARCHIVED, purpose, LEGACY_SOURCE_MODE_SLOT, STATUS_ARCHIVED),
|
||||
)
|
||||
existing = {
|
||||
row["id"]
|
||||
for row in conn.execute("SELECT id FROM generation_guidelines WHERE purpose = ?", (purpose,)).fetchall()
|
||||
}
|
||||
existing_seed_ids = {
|
||||
row["seed_id"]
|
||||
for row in conn.execute(
|
||||
"SELECT seed_id FROM generation_guidelines WHERE purpose = ? AND seed_id != ''",
|
||||
(purpose,),
|
||||
).fetchall()
|
||||
if row["seed_id"]
|
||||
}
|
||||
for row in _seed_rows(seed, purpose):
|
||||
row_id = row[0]
|
||||
seed_id = row[12]
|
||||
if row_id in existing or seed_id in existing_seed_ids:
|
||||
by_id, by_seed_id = _catalog_maps(conn, purpose)
|
||||
all_rows = list(by_id.values())
|
||||
current = _find_existing_seed_row(by_id, by_seed_id, row, all_rows)
|
||||
if current:
|
||||
if not _as_bool(current.get("is_system_seed", 0)):
|
||||
continue
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO generation_guidelines (
|
||||
id, purpose, slot, guideline_key, label, summary, instruction, sort_order,
|
||||
status, revision, cloned_from, is_default, is_system_seed, seed_id, seed_revision,
|
||||
created, updated
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, datetime('now'), datetime('now'))
|
||||
""",
|
||||
if current.get("status") != STATUS_ACTIVE:
|
||||
continue
|
||||
if _semantic_signature(current) == _semantic_signature(seed_row=row):
|
||||
continue
|
||||
successor = _find_matching_successor(all_rows, current["id"], row)
|
||||
if successor:
|
||||
if row[11] and successor.get("status") == STATUS_ACTIVE:
|
||||
_assign_slot_default(conn, purpose, row[2], successor["id"])
|
||||
continue
|
||||
next_revision = int(current.get("revision") or 1) + 1
|
||||
taken = set(by_id)
|
||||
successor_id = _successor_id(current["id"], next_revision)
|
||||
while successor_id in taken:
|
||||
next_revision += 1
|
||||
successor_id = _successor_id(current["id"], next_revision)
|
||||
_insert_seed_guideline(
|
||||
conn,
|
||||
row,
|
||||
guideline_id=successor_id,
|
||||
cloned_from=current["id"],
|
||||
revision=next_revision,
|
||||
is_default=int(row[11] or 0),
|
||||
)
|
||||
if row[11]:
|
||||
_assign_slot_default(conn, purpose, row[2], successor_id)
|
||||
continue
|
||||
_insert_seed_guideline(conn, row)
|
||||
if row[11]:
|
||||
_assign_slot_default(conn, purpose, row[2], row[0])
|
||||
|
||||
|
||||
def backfill_missing_settings(conn) -> None:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -285,7 +285,7 @@ def current_entries(profile_id: str, journal_day_id: str) -> list[dict]:
|
||||
FROM journal_entries e
|
||||
LEFT JOIN journal_entry_versions v ON v.id = e.current_version_id
|
||||
WHERE e.profile_id = ? AND e.journal_day_id = ? AND e.deleted_at IS NULL
|
||||
ORDER BY e.created, e.rowid
|
||||
ORDER BY e.created, e.id
|
||||
""",
|
||||
(profile_id, journal_day_id),
|
||||
).fetchall()
|
||||
@@ -514,7 +514,7 @@ def list_space_entries(profile_id: str, space_id: str) -> list[dict]:
|
||||
JOIN journal_days d ON d.id = e.journal_day_id
|
||||
LEFT JOIN journal_entry_versions v ON v.id = e.current_version_id
|
||||
WHERE e.profile_id = ? AND e.space_id = ? AND e.deleted_at IS NULL
|
||||
ORDER BY d.calendar_date DESC, e.created ASC, e.rowid ASC
|
||||
ORDER BY d.calendar_date DESC, e.created ASC, e.id ASC
|
||||
""",
|
||||
(profile_id, space_id),
|
||||
).fetchall()
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Operational mail for account links. No dialogue content, no model egress."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import smtplib
|
||||
from email.message import EmailMessage
|
||||
|
||||
from env_loader import env_flag, runtime_env
|
||||
|
||||
log = logging.getLogger("kansho.mail")
|
||||
|
||||
OUTBOX: list[dict] = []
|
||||
|
||||
|
||||
class MailNotConfigured(RuntimeError):
|
||||
"""SMTP is required and neither configured nor in the development log path."""
|
||||
|
||||
|
||||
def clear_outbox() -> None:
|
||||
OUTBOX.clear()
|
||||
|
||||
|
||||
def smtp_configured() -> bool:
|
||||
return bool((os.environ.get("SMTP_HOST") or "").strip() and (os.environ.get("SMTP_FROM") or "").strip())
|
||||
|
||||
|
||||
def send_mail(recipients: list[str], subject: str, body: str) -> None:
|
||||
cleaned: list[str] = []
|
||||
for item in recipients:
|
||||
address = (item or "").strip().lower()
|
||||
if address and address not in cleaned:
|
||||
cleaned.append(address)
|
||||
if not cleaned:
|
||||
raise MailNotConfigured("Mailversand ist nicht konfiguriert")
|
||||
if env_flag("KANSHO_FAKE_MAIL"):
|
||||
OUTBOX.append({"to": cleaned, "subject": subject, "body": body})
|
||||
return
|
||||
host = (os.environ.get("SMTP_HOST") or "").strip()
|
||||
sender = (os.environ.get("SMTP_FROM") or "").strip()
|
||||
if not host or not sender:
|
||||
if runtime_env() == "development":
|
||||
log.warning("Kansho mail (development, SMTP fehlt): %s", body)
|
||||
return
|
||||
raise MailNotConfigured("Mailversand ist nicht konfiguriert")
|
||||
port = int((os.environ.get("SMTP_PORT") or "587").strip() or "587")
|
||||
user = (os.environ.get("SMTP_USER") or "").strip()
|
||||
password = os.environ.get("SMTP_PASSWORD") or ""
|
||||
message = EmailMessage()
|
||||
message["Subject"] = subject
|
||||
message["From"] = sender
|
||||
message["To"] = ", ".join(cleaned)
|
||||
message.set_content(body)
|
||||
if port == 465:
|
||||
with smtplib.SMTP_SSL(host, port, timeout=20) as smtp:
|
||||
if user:
|
||||
smtp.login(user, password)
|
||||
smtp.send_message(message)
|
||||
return
|
||||
with smtplib.SMTP(host, port, timeout=20) as smtp:
|
||||
smtp.starttls()
|
||||
if user:
|
||||
smtp.login(user, password)
|
||||
smtp.send_message(message)
|
||||
+24
-1
@@ -2,6 +2,8 @@ from env_loader import load_env_file
|
||||
|
||||
load_env_file()
|
||||
|
||||
import os
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
@@ -10,11 +12,32 @@ import data_layer_dialogue # noqa: F401
|
||||
from routers import admin, auth, dialogue, generation_instructions, journal, placeholders, prompts, subscription, users
|
||||
from version import APP_VERSION
|
||||
|
||||
|
||||
def allowed_origins() -> list[str]:
|
||||
origins = [
|
||||
"http://localhost:5188",
|
||||
"http://127.0.0.1:5188",
|
||||
"https://kansho.jinkendo.de",
|
||||
"https://dev.kansho.jinkendo.de",
|
||||
]
|
||||
extra = (os.environ.get("ALLOWED_ORIGINS") or os.environ.get("KANSHO_ALLOWED_ORIGINS") or "").strip()
|
||||
if extra:
|
||||
origins.extend(item.strip() for item in extra.split(",") if item.strip())
|
||||
app_url = (os.environ.get("APP_URL") or "").strip().rstrip("/")
|
||||
if app_url:
|
||||
origins.append(app_url)
|
||||
seen: list[str] = []
|
||||
for item in origins:
|
||||
if item not in seen:
|
||||
seen.append(item)
|
||||
return seen
|
||||
|
||||
|
||||
app = FastAPI(title="Kanshō", version=APP_VERSION)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["http://localhost:5188", "http://127.0.0.1:5188"],
|
||||
allow_origins=allowed_origins(),
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Postgres runtime baseline for Kanshō.
|
||||
-- Greenfield schema is backend/schema.sql translated at startup
|
||||
-- (datetime('now') → CURRENT_TIMESTAMP::text). Historical SQLite
|
||||
-- inline migrations 001-021 are recorded as applied, not replayed.
|
||||
-- Future incremental DDL belongs in 023_*.sql and later.
|
||||
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- LLM profiles: named, reusable generate/detect endpoint+model presets.
|
||||
-- Keys stay in env. Active assignment remains provider_settings.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS llm_profiles (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
url TEXT NOT NULL DEFAULT '',
|
||||
model TEXT NOT NULL DEFAULT '',
|
||||
zdr INTEGER NOT NULL DEFAULT 1,
|
||||
no_train INTEGER NOT NULL DEFAULT 1,
|
||||
created TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP::text,
|
||||
updated TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP::text
|
||||
);
|
||||
|
||||
ALTER TABLE provider_settings ADD COLUMN IF NOT EXISTS profile_id TEXT;
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Transitional learning detect: user-confirmed label senses, pending mask review.
|
||||
-- Detect output still does not auto-activate identities.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS label_senses (
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
normalized_label TEXT NOT NULL,
|
||||
identity_hits INTEGER NOT NULL DEFAULT 0,
|
||||
non_identity_hits INTEGER NOT NULL DEFAULT 0,
|
||||
updated TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP::text,
|
||||
PRIMARY KEY (profile_id, normalized_label)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pending_mask_reviews (
|
||||
id TEXT PRIMARY KEY,
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
conversation_id TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
|
||||
user_message_id TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL DEFAULT '{}',
|
||||
created TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP::text
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_pending_mask_reviews_conv
|
||||
ON pending_mask_reviews (profile_id, conversation_id);
|
||||
@@ -0,0 +1,12 @@
|
||||
-- Remember mask-review decisions per local context cue (previous word).
|
||||
-- Not a word list: cues come from the user line, e.g. Frau vs. a food mention.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS label_sense_cues (
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
normalized_label TEXT NOT NULL,
|
||||
cue TEXT NOT NULL,
|
||||
decision TEXT NOT NULL,
|
||||
hits INTEGER NOT NULL DEFAULT 1,
|
||||
updated TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP::text,
|
||||
PRIMARY KEY (profile_id, normalized_label, cue)
|
||||
);
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Mini-passages beside each cue so local detect/GLiNER can pre-decide from context.
|
||||
ALTER TABLE label_sense_cues ADD COLUMN IF NOT EXISTS excerpt TEXT NOT NULL DEFAULT '';
|
||||
@@ -0,0 +1,49 @@
|
||||
-- Account identifiers, verified addresses, and one-time mail tokens.
|
||||
-- Existing primary addresses are grandfathered as verified once.
|
||||
|
||||
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS username TEXT;
|
||||
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS secondary_email TEXT;
|
||||
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS email_verified_at TEXT;
|
||||
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS secondary_email_verified_at TEXT;
|
||||
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS pending_email TEXT;
|
||||
ALTER TABLE profiles ADD COLUMN IF NOT EXISTS pending_secondary_email TEXT;
|
||||
|
||||
UPDATE profiles
|
||||
SET email_verified_at = COALESCE(NULLIF(created, ''), CURRENT_TIMESTAMP::text)
|
||||
WHERE email_verified_at IS NULL OR email_verified_at = '';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS password_reset_tokens (
|
||||
id TEXT PRIMARY KEY,
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TEXT NOT NULL,
|
||||
used_at TEXT,
|
||||
created TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP::text
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS email_verification_tokens (
|
||||
id TEXT PRIMARY KEY,
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
purpose TEXT NOT NULL CHECK (purpose IN ('primary', 'secondary')),
|
||||
email TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TEXT NOT NULL,
|
||||
used_at TEXT,
|
||||
created TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP::text
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS profiles_username_lower_idx
|
||||
ON profiles (lower(username))
|
||||
WHERE username IS NOT NULL AND username <> '';
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS profiles_secondary_email_lower_idx
|
||||
ON profiles (lower(secondary_email))
|
||||
WHERE secondary_email IS NOT NULL AND secondary_email <> '';
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS profiles_pending_email_lower_idx
|
||||
ON profiles (lower(pending_email))
|
||||
WHERE pending_email IS NOT NULL AND pending_email <> '';
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS profiles_pending_secondary_email_lower_idx
|
||||
ON profiles (lower(pending_secondary_email))
|
||||
WHERE pending_secondary_email IS NOT NULL AND pending_secondary_email <> '';
|
||||
@@ -110,7 +110,7 @@ def _parse_model_row(row: dict) -> ModelWindow | None:
|
||||
)
|
||||
|
||||
|
||||
def _fetch_catalog(url: str, key: str) -> dict[str, dict]:
|
||||
def _request_models_payload(url: str, key: str) -> list:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if key:
|
||||
headers["Authorization"] = f"Bearer {key}"
|
||||
@@ -143,6 +143,11 @@ def _fetch_catalog(url: str, key: str) -> dict[str, dict]:
|
||||
status_code=503,
|
||||
diagnostics={"models_url": url, "reason": "unexpected_shape"},
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def _fetch_catalog(url: str, key: str) -> dict[str, dict]:
|
||||
rows = _request_models_payload(url, key)
|
||||
parsed: dict[str, dict] = {}
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
@@ -249,3 +254,90 @@ def resolve_generate_metadata(config, *, now: float | None = None) -> ModelWindo
|
||||
diagnostics={"model": model, "reason": "model_not_in_catalog"},
|
||||
)
|
||||
return _window_from_cache(fetched[model], model=model)
|
||||
|
||||
|
||||
def list_provider_models(config) -> list[dict]:
|
||||
"""Model ids for the admin picker. Soft-fail; free-text remains valid."""
|
||||
if not config or getattr(config, "mode", None) == "fake":
|
||||
return []
|
||||
url = getattr(config, "url", "") or ""
|
||||
if not url:
|
||||
return []
|
||||
key = getattr(config, "key", "") or ""
|
||||
items = _list_openai_models(url, key)
|
||||
if items:
|
||||
return items
|
||||
return _list_ollama_tags(url)
|
||||
|
||||
|
||||
def list_models_for_url(url: str, key: str = "") -> list[dict]:
|
||||
from providers import ProviderConfig, is_local_url
|
||||
|
||||
url = (url or "").strip()
|
||||
if not url:
|
||||
return []
|
||||
local = is_local_url(url)
|
||||
return list_provider_models(
|
||||
ProviderConfig(
|
||||
role="generate",
|
||||
name="ollama" if local else "openrouter",
|
||||
mode="http",
|
||||
url=url,
|
||||
model="",
|
||||
key=key,
|
||||
local=local,
|
||||
zdr=True,
|
||||
no_train=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _list_openai_models(chat_url: str, key: str) -> list[dict]:
|
||||
catalog_key = models_url(chat_url)
|
||||
try:
|
||||
rows = _request_models_payload(catalog_key, key)
|
||||
except JournalBudgetError:
|
||||
return []
|
||||
return _ids_from_rows(rows, id_keys=("id",))
|
||||
|
||||
|
||||
def _list_ollama_tags(chat_url: str) -> list[dict]:
|
||||
parsed = urlparse(chat_url or "")
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
return []
|
||||
tags_url = f"{parsed.scheme}://{parsed.netloc}/api/tags"
|
||||
headers = {"Content-Type": "application/json"}
|
||||
try:
|
||||
response = httpx.get(tags_url, headers=headers, timeout=8.0)
|
||||
except httpx.HTTPError:
|
||||
return []
|
||||
if response.status_code >= 400:
|
||||
return []
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
return []
|
||||
rows = payload.get("models") if isinstance(payload, dict) else payload
|
||||
if not isinstance(rows, list):
|
||||
return []
|
||||
return _ids_from_rows(rows, id_keys=("name", "model", "id"))
|
||||
|
||||
|
||||
def _ids_from_rows(rows: list, *, id_keys: tuple[str, ...]) -> list[dict]:
|
||||
seen: set[str] = set()
|
||||
items: list[dict] = []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
model_id = ""
|
||||
for key in id_keys:
|
||||
model_id = str(row.get(key) or "").strip()
|
||||
if model_id:
|
||||
break
|
||||
if not model_id or model_id in seen:
|
||||
continue
|
||||
seen.add(model_id)
|
||||
name = str(row.get("name") or model_id).strip() or model_id
|
||||
items.append({"id": model_id, "name": name})
|
||||
items.sort(key=lambda item: item["id"])
|
||||
return items
|
||||
+234
-3
@@ -85,6 +85,27 @@ COMPACT_DIAGNOSTIC_KEYS = (
|
||||
"detect_cost",
|
||||
"detect_ms",
|
||||
"generate_called",
|
||||
"generate_requested",
|
||||
"http_status",
|
||||
"provider_message",
|
||||
"provider_code",
|
||||
"timeout_s",
|
||||
"cost_report",
|
||||
"detect_passes",
|
||||
"detect_partial_discarded",
|
||||
"detect_attempts",
|
||||
"contract_violation",
|
||||
"invalid_entity_type",
|
||||
"omitted_non_identity_types",
|
||||
"detect_cost_unknown",
|
||||
"diff_agree",
|
||||
"diff_only_student",
|
||||
"diff_only_teacher",
|
||||
"diff_type_conflict",
|
||||
"diff_new_identity",
|
||||
"diff_cue_reinforced",
|
||||
"generation_selection",
|
||||
"style_application",
|
||||
)
|
||||
|
||||
ERROR_EGRESS_VALIDATION = "egress_validation_failed"
|
||||
@@ -165,14 +186,159 @@ class MaskingManifest:
|
||||
}
|
||||
|
||||
|
||||
def _snapshot_plain(value: Any, *, _stack: set[int] | None = None) -> Any:
|
||||
"""Acyclic copy of compact diagnostic values. Drops cyclic back-references."""
|
||||
if value is None or isinstance(value, (str, int, float, bool)):
|
||||
return value
|
||||
if isinstance(value, (dict, list, tuple)):
|
||||
stack = _stack or set()
|
||||
ident = id(value)
|
||||
if ident in stack:
|
||||
return None
|
||||
stack = set(stack)
|
||||
stack.add(ident)
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
str(key): _snapshot_plain(item, _stack=stack)
|
||||
for key, item in value.items()
|
||||
if key not in {"trace", "diagnostics", "intern", "egress", "raw", "reply", "prompt", "messages"}
|
||||
}
|
||||
return [_snapshot_plain(item, _stack=stack) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def compact_diagnostics(data: dict[str, Any] | None) -> dict[str, Any]:
|
||||
payload = {}
|
||||
for key in COMPACT_DIAGNOSTIC_KEYS:
|
||||
if data and key in data and data[key] is not None:
|
||||
payload[key] = data[key]
|
||||
payload[key] = _snapshot_plain(data[key])
|
||||
return payload
|
||||
|
||||
|
||||
def _as_cost(value: Any) -> float | None:
|
||||
if value is None or value == "":
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _format_usd(value: float) -> str:
|
||||
text = f"{value:.6f}".rstrip("0").rstrip(".")
|
||||
return f"{text.replace('.', ',')} USD"
|
||||
|
||||
|
||||
def _first_present(*values: Any) -> Any:
|
||||
for value in values:
|
||||
if value is not None:
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def public_cost_report(diagnostics: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""User-facing billed/unbilled summary. No prompts, no mapping labels."""
|
||||
data = diagnostics or {}
|
||||
nested = data.get("trace") if isinstance(data.get("trace"), dict) else {}
|
||||
budget = nested.get("budget") if isinstance(nested.get("budget"), dict) else {}
|
||||
generate_called = bool(
|
||||
data.get("generate_called")
|
||||
or data.get("generate_calls")
|
||||
or nested.get("generate_called")
|
||||
or nested.get("generate_calls")
|
||||
)
|
||||
generate_requested = bool(
|
||||
data.get("generate_requested")
|
||||
or nested.get("generate_requested")
|
||||
or generate_called
|
||||
)
|
||||
detect_calls = _first_present(data.get("detect_calls"), nested.get("detect_calls"))
|
||||
try:
|
||||
detect_calls_n = int(detect_calls) if detect_calls is not None else 0
|
||||
except (TypeError, ValueError):
|
||||
detect_calls_n = 0
|
||||
detect_called = detect_calls_n > 0
|
||||
generate_cost = _as_cost(_first_present(data.get("cost"), budget.get("cost")))
|
||||
detect_cost = _as_cost(_first_present(data.get("detect_cost"), nested.get("detect_cost")))
|
||||
known = [item for item in (detect_cost, generate_cost) if item is not None]
|
||||
total = sum(known) if known else None
|
||||
if (detect_cost or 0) > 0 or (generate_cost or 0) > 0:
|
||||
billed = "yes"
|
||||
elif generate_requested and generate_cost is None:
|
||||
billed = "unknown"
|
||||
elif detect_called and detect_cost is None and not generate_called:
|
||||
billed = "unknown"
|
||||
else:
|
||||
billed = "no"
|
||||
parts: list[str] = []
|
||||
if detect_called or detect_cost is not None:
|
||||
if detect_cost is not None:
|
||||
parts.append(f"Detect {_format_usd(detect_cost)}")
|
||||
elif detect_called:
|
||||
parts.append("Detect aufgerufen, Kosten unbekannt")
|
||||
if generate_called and generate_cost is not None:
|
||||
parts.append(f"Generate {_format_usd(generate_cost)}")
|
||||
elif generate_called:
|
||||
parts.append("Generate abgeschlossen, Kosten unbekannt")
|
||||
elif generate_requested:
|
||||
parts.append("Generate-Aufruf gesendet, Kosten unbekannt")
|
||||
else:
|
||||
parts.append("Generate nicht aufgerufen")
|
||||
if billed == "yes":
|
||||
note = "Beim Anbieter sind Kosten entstanden"
|
||||
if parts:
|
||||
note += ": " + "; ".join(parts) + "."
|
||||
else:
|
||||
note += "."
|
||||
elif billed == "unknown":
|
||||
note = "Ob beim Anbieter Kosten entstanden sind, ist unbekannt"
|
||||
if parts:
|
||||
note += " (" + "; ".join(parts) + ")."
|
||||
else:
|
||||
note += "."
|
||||
else:
|
||||
if detect_called or generate_requested or generate_called:
|
||||
note = "Beim Anbieter sind für diesen Lauf keine Kosten ausgewiesen"
|
||||
if parts:
|
||||
note += " (" + "; ".join(parts) + ")."
|
||||
else:
|
||||
note += "."
|
||||
else:
|
||||
note = "Es wurde kein Provider aufgerufen. Es sind keine Kosten entstanden."
|
||||
return {
|
||||
"generate_called": generate_called,
|
||||
"generate_requested": generate_requested,
|
||||
"detect_called": detect_called,
|
||||
"detect_calls": detect_calls_n,
|
||||
"cost": generate_cost,
|
||||
"detect_cost": detect_cost,
|
||||
"total_cost": total,
|
||||
"billed": billed,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
def public_error_detail(exc) -> dict[str, Any]:
|
||||
diagnostics = dict(getattr(exc, "diagnostics", None) or {})
|
||||
report = public_cost_report(diagnostics)
|
||||
if report and diagnostics.get("cost_report") is None:
|
||||
diagnostics["cost_report"] = report
|
||||
detail: dict[str, Any] = {
|
||||
"code": getattr(exc, "code", None) or "error",
|
||||
"message": getattr(exc, "message", None) or str(exc),
|
||||
"cost_report": report,
|
||||
}
|
||||
http_status = diagnostics.get("http_status")
|
||||
if http_status is not None:
|
||||
detail["http_status"] = http_status
|
||||
provider_message = diagnostics.get("provider_message")
|
||||
if provider_message:
|
||||
detail["provider_message"] = provider_message
|
||||
if diagnostics:
|
||||
detail["diagnostics"] = diagnostics
|
||||
return detail
|
||||
|
||||
|
||||
_LOG_FORBIDDEN_KEYS = frozenset(
|
||||
{
|
||||
"local_label",
|
||||
@@ -227,6 +393,7 @@ def _raise_with_log(
|
||||
diagnostics["purpose"] = purpose
|
||||
if extra:
|
||||
diagnostics.update({key: value for key, value in extra.items() if value is not None})
|
||||
diagnostics["cost_report"] = public_cost_report(diagnostics)
|
||||
raise PrivacyGatewayError(exc.code, exc.message, exc.status_code, diagnostics) from exc
|
||||
|
||||
|
||||
@@ -835,6 +1002,14 @@ def _fake_complete(purpose: str, rendered: str) -> str:
|
||||
return '{"operation":"erleben_vertiefen","impulse":"' + impulse + '"}'
|
||||
|
||||
|
||||
def _generate_timeout(purpose: str) -> float:
|
||||
if purpose in JOURNAL_PURPOSES:
|
||||
return 90
|
||||
if purpose == "profile_review":
|
||||
return 120
|
||||
return 60
|
||||
|
||||
|
||||
def complete_model(messages: list[dict], policy: dict[str, Any]) -> ChatResult:
|
||||
config = generate_provider()
|
||||
if not config:
|
||||
@@ -851,7 +1026,7 @@ def complete_model(messages: list[dict], policy: dict[str, Any]) -> ChatResult:
|
||||
return complete_chat(
|
||||
config,
|
||||
messages,
|
||||
timeout=90 if (policy.get("purpose") in JOURNAL_PURPOSES) else 60,
|
||||
timeout=_generate_timeout(policy.get("purpose") or ""),
|
||||
max_tokens=policy.get("max_tokens"),
|
||||
disable_context_compression=bool(policy.get("disable_context_compression")),
|
||||
)
|
||||
@@ -886,7 +1061,53 @@ def complete(request: GatewayRequest) -> GatewayResult:
|
||||
detect_note = None
|
||||
detect_stats: dict[str, Any] = {}
|
||||
local_identities: list[dict[str, Any]] = []
|
||||
precomputed = request.payload.get("precomputed_mappings") if request.payload else None
|
||||
try:
|
||||
if precomputed is not None:
|
||||
mappings = list(precomputed)
|
||||
extra = dict((request.payload or {}).get("detect_counters") or {})
|
||||
detect_stats = {
|
||||
"detect_note": "precomputed_learning_review",
|
||||
"full_detection_coverage": True,
|
||||
"semantic_identity_guaranteed": False,
|
||||
**{key: extra[key] for key in extra if key.startswith("diff_")},
|
||||
}
|
||||
local_identities = [
|
||||
{
|
||||
"local_label": item.get("local_label"),
|
||||
"token": item.get("token"),
|
||||
"entity_type": item.get("entity_type"),
|
||||
"source": item.get("source"),
|
||||
}
|
||||
for item in mappings
|
||||
]
|
||||
detect_name = "learning_review"
|
||||
else:
|
||||
from detect_learning import is_bypass_mode
|
||||
from detect_pipeline import compact_diff_counters, prepare_detect_pipeline
|
||||
|
||||
user_body = str((request.payload or {}).get("user_body") or "").strip()
|
||||
if request.profile_id and not is_bypass_mode() and user_body:
|
||||
pipe = prepare_detect_pipeline(request.profile_id, user_body, rendered)
|
||||
mappings = list(pipe.mappings or [])
|
||||
detect_stats = {
|
||||
"detect_note": "student_path" if not pipe.need_review else "student_path_unreviewed",
|
||||
"full_detection_coverage": True,
|
||||
"semantic_identity_guaranteed": False,
|
||||
**compact_diff_counters(pipe.counters),
|
||||
}
|
||||
detect_name = "student_path"
|
||||
detect_note = detect_stats["detect_note"]
|
||||
local_identities = [
|
||||
{
|
||||
"local_label": item.get("local_label"),
|
||||
"token": item.get("token"),
|
||||
"entity_type": item.get("entity_type"),
|
||||
"source": item.get("source"),
|
||||
}
|
||||
for item in mappings
|
||||
]
|
||||
else:
|
||||
outcome = detect_personal_egress(request.profile_id, rendered)
|
||||
mappings = outcome.mappings
|
||||
detect_stats = outcome.stats.public()
|
||||
@@ -911,7 +1132,13 @@ def complete(request: GatewayRequest) -> GatewayResult:
|
||||
exc.code,
|
||||
user_detect_message(exc.code, exc.message),
|
||||
exc.status_code,
|
||||
{"log": events, "purpose": request.purpose, "generate_called": False, **detect_stats},
|
||||
{
|
||||
"log": events,
|
||||
"purpose": request.purpose,
|
||||
"generate_called": False,
|
||||
"generate_requested": False,
|
||||
**detect_stats,
|
||||
},
|
||||
) from exc
|
||||
_log_event(
|
||||
events,
|
||||
@@ -945,6 +1172,7 @@ def complete(request: GatewayRequest) -> GatewayResult:
|
||||
diagnostics.update(summary)
|
||||
diagnostics.update({key: value for key, value in detect_stats.items() if value is not None})
|
||||
diagnostics["generate_called"] = False
|
||||
diagnostics["generate_requested"] = False
|
||||
if request.purpose in JOURNAL_PURPOSES:
|
||||
if budget is None:
|
||||
_log_event(events, started, "budget", status="error", code="model_metadata_unknown")
|
||||
@@ -1079,6 +1307,8 @@ def complete(request: GatewayRequest) -> GatewayResult:
|
||||
purpose=request.purpose,
|
||||
model=config.model if config else None,
|
||||
)
|
||||
diagnostics["generate_requested"] = True
|
||||
request_trace["generate_requested"] = True
|
||||
chat = complete_model([{"role": "user", "content": masked}], model_policy)
|
||||
usages.append(chat.usage or {})
|
||||
diagnostics["generate_called"] = True
|
||||
@@ -1198,6 +1428,7 @@ def public_trace(trace: dict | None) -> dict | None:
|
||||
"detect_ms": trace.get("detect_ms"),
|
||||
"generate_ms": (trace.get("budget") or {}).get("generate_ms") if isinstance(trace.get("budget"), dict) else trace.get("generate_ms"),
|
||||
"generate_called": trace.get("generate_called"),
|
||||
"generate_requested": trace.get("generate_requested"),
|
||||
"mapping_count": trace.get("mapping_count"),
|
||||
"available_mapping_count": trace.get("available_mapping_count"),
|
||||
"active_mapping_count": trace.get("active_mapping_count"),
|
||||
|
||||
@@ -911,7 +911,24 @@ def run_api_review(profile_id: str, review_id: str | None = None, *, mode: str |
|
||||
subject_id=review_id or "",
|
||||
)
|
||||
raise
|
||||
try:
|
||||
parsed = parse_result(result.get("content") or "")
|
||||
except StoreError as exc:
|
||||
diag = dict(result.get("diagnostics") or {})
|
||||
if result.get("trace") is not None:
|
||||
diag.setdefault("trace", result.get("trace"))
|
||||
diag["generate_called"] = True if diag.get("generate_called") is None else diag.get("generate_called")
|
||||
diag["generate_requested"] = True
|
||||
diag["abort_reason"] = exc.code
|
||||
wrapped = EngineError(exc.code, exc.message, getattr(exc, "status_code", 400), diag)
|
||||
persist_engine_error(
|
||||
profile_id,
|
||||
purpose="profile_review",
|
||||
exc=wrapped,
|
||||
subject_type="writing_profile_review",
|
||||
subject_id=review_id or "",
|
||||
)
|
||||
raise wrapped from exc
|
||||
if not parsed.get("mode"):
|
||||
parsed["mode"] = package.get("mode") or ""
|
||||
staged = _stage_proposal(profile_id, parsed, review_id=review_id, package=package)
|
||||
|
||||
+337
-14
@@ -3,14 +3,23 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from db import get_db
|
||||
from env_loader import allows_remote_plaintext_detect, runtime_env, upsert_env_value
|
||||
from detect_learning import get_detect_operating_mode
|
||||
from env_loader import (
|
||||
allows_remote_plaintext_detect,
|
||||
remote_plaintext_detect_reason,
|
||||
runtime_env,
|
||||
upsert_env_value,
|
||||
)
|
||||
|
||||
SEED_PATH = Path(__file__).resolve().parent / "config" / "providers.seed.json"
|
||||
ROLES = ("generate", "detect")
|
||||
OLLAMA_LAN_ID = "llm-ollama-lan"
|
||||
OLLAMA_LAN_URL = "http://192.168.2.144:11434/v1/chat/completions"
|
||||
_KEY_ENV = {
|
||||
"generate": "KANSHO_PROVIDER_KEY",
|
||||
"detect": "KANSHO_DETECT_PROVIDER_KEY",
|
||||
@@ -23,7 +32,7 @@ ROLE_META = {
|
||||
},
|
||||
"detect": {
|
||||
"title": "Maskierung",
|
||||
"task": "Eigener Detect-Endpunkt. Vollständige semantische Detection des persönlichen Egress. Externes Klartext-Detect nur Development/Test. Produktiv: lokales Detect-Modell. Kein Pattern-Fallback.",
|
||||
"task": "Eigener Detect-Endpunkt und eigenes Modell. Vollständige semantische Detection des persönlichen Egress. Ziel: lokales Detect-Modell (Ollama). Übergang: externes Klartext-Detect nur mit Operator-Freigabe. Kein Pattern-Fallback.",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -36,6 +45,38 @@ class SettingsError(Exception):
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
def _validate_url(url: str) -> str:
|
||||
url = (url or "").strip()
|
||||
if not url:
|
||||
return ""
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise SettingsError("provider_url_invalid", "URL muss http(s) sein.")
|
||||
return url
|
||||
|
||||
|
||||
def _profile_row(conn, profile_id: str) -> dict | None:
|
||||
row = conn.execute("SELECT * FROM llm_profiles WHERE id = ?", (profile_id,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def _public_profile(row: dict) -> dict:
|
||||
from providers import is_local_url
|
||||
|
||||
url = row.get("url") or ""
|
||||
return {
|
||||
"id": row.get("id") or "",
|
||||
"title": row.get("title") or "",
|
||||
"name": row.get("name") or "",
|
||||
"url": url,
|
||||
"model": row.get("model") or "",
|
||||
"zdr": bool(row.get("zdr", 1)),
|
||||
"no_train": bool(row.get("no_train", 1)),
|
||||
"local": is_local_url(url),
|
||||
"updated": row.get("updated") or "",
|
||||
}
|
||||
|
||||
|
||||
def seed_provider_settings(conn) -> None:
|
||||
items = json.loads(SEED_PATH.read_text(encoding="utf-8"))
|
||||
for item in items:
|
||||
@@ -59,6 +100,237 @@ def seed_provider_settings(conn) -> None:
|
||||
1 if item.get("no_train", True) else 0,
|
||||
),
|
||||
)
|
||||
seed_llm_profiles(conn)
|
||||
|
||||
|
||||
def seed_llm_profiles(conn) -> None:
|
||||
"""Named presets. Existing rows are not overwritten. Keys never stored."""
|
||||
ollama = conn.execute("SELECT * FROM llm_profiles WHERE id = ?", (OLLAMA_LAN_ID,)).fetchone()
|
||||
if not ollama:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO llm_profiles (id, title, name, url, model, zdr, no_train)
|
||||
VALUES (?, ?, ?, ?, ?, 1, 1)
|
||||
""",
|
||||
(OLLAMA_LAN_ID, "Ollama (LAN)", "ollama", OLLAMA_LAN_URL, "phi3:mini"),
|
||||
)
|
||||
elif not (dict(ollama).get("model") or "").strip():
|
||||
conn.execute(
|
||||
"UPDATE llm_profiles SET model = ?, updated = datetime('now') WHERE id = ?",
|
||||
("phi3:mini", OLLAMA_LAN_ID),
|
||||
)
|
||||
for role in ROLES:
|
||||
row = conn.execute("SELECT * FROM provider_settings WHERE role = ?", (role,)).fetchone()
|
||||
if not row:
|
||||
continue
|
||||
data = dict(row)
|
||||
profile_id = (data.get("profile_id") or "").strip()
|
||||
if profile_id and _profile_row(conn, profile_id):
|
||||
continue
|
||||
url = (data.get("url") or "").strip()
|
||||
model = (data.get("model") or "").strip()
|
||||
if not url:
|
||||
continue
|
||||
match = conn.execute(
|
||||
"SELECT id FROM llm_profiles WHERE url = ? AND model = ? ORDER BY created LIMIT 1",
|
||||
(url, model),
|
||||
).fetchone()
|
||||
if match:
|
||||
chosen = match["id"]
|
||||
else:
|
||||
chosen = f"llm-{role}-current"
|
||||
if _profile_row(conn, chosen):
|
||||
chosen = str(uuid.uuid4())
|
||||
title = "Sprachmodell (aktuell)" if role == "generate" else "Maskierung (aktuell)"
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO llm_profiles (id, title, name, url, model, zdr, no_train)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
chosen,
|
||||
title,
|
||||
data.get("name") or "",
|
||||
url,
|
||||
model,
|
||||
1 if data.get("zdr", 1) else 0,
|
||||
1 if data.get("no_train", 1) else 0,
|
||||
),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE provider_settings SET profile_id = ? WHERE role = ?",
|
||||
(chosen, role),
|
||||
)
|
||||
|
||||
|
||||
def list_profiles() -> list[dict]:
|
||||
with get_db() as conn:
|
||||
rows = conn.execute("SELECT * FROM llm_profiles ORDER BY title, created").fetchall()
|
||||
return [_public_profile(dict(row)) for row in rows]
|
||||
|
||||
|
||||
def get_profile(profile_id: str) -> dict | None:
|
||||
with get_db() as conn:
|
||||
row = _profile_row(conn, profile_id)
|
||||
return _public_profile(row) if row else None
|
||||
|
||||
|
||||
def _write_profile(
|
||||
conn,
|
||||
profile_id: str,
|
||||
*,
|
||||
title: str,
|
||||
name: str,
|
||||
url: str,
|
||||
model: str,
|
||||
zdr: bool,
|
||||
no_train: bool,
|
||||
) -> dict:
|
||||
title = (title or "").strip()
|
||||
if not title:
|
||||
raise SettingsError("profile_title_required", "Ein Profil braucht einen Namen.")
|
||||
url = _validate_url(url)
|
||||
if not url:
|
||||
raise SettingsError("provider_url_required", "Ein Profil braucht eine URL.")
|
||||
model = (model or "").strip()
|
||||
name = (name or "").strip()
|
||||
existing = _profile_row(conn, profile_id)
|
||||
if existing:
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE llm_profiles
|
||||
SET title = ?, name = ?, url = ?, model = ?, zdr = ?, no_train = ?, updated = datetime('now')
|
||||
WHERE id = ?
|
||||
""",
|
||||
(title, name, url, model, 1 if zdr else 0, 1 if no_train else 0, profile_id),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO llm_profiles (id, title, name, url, model, zdr, no_train)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(profile_id, title, name, url, model, 1 if zdr else 0, 1 if no_train else 0),
|
||||
)
|
||||
for role in ROLES:
|
||||
active = conn.execute(
|
||||
"SELECT role FROM provider_settings WHERE role = ? AND profile_id = ?",
|
||||
(role, profile_id),
|
||||
).fetchone()
|
||||
if not active:
|
||||
continue
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE provider_settings
|
||||
SET name = ?, url = ?, model = ?, zdr = ?, no_train = ?, updated = datetime('now')
|
||||
WHERE role = ?
|
||||
""",
|
||||
(name, url, model, 1 if zdr else 0, 1 if no_train else 0, role),
|
||||
)
|
||||
row = _profile_row(conn, profile_id)
|
||||
return _public_profile(row or {})
|
||||
|
||||
|
||||
def create_profile(*, title: str, name: str, url: str, model: str, zdr: bool, no_train: bool) -> dict:
|
||||
profile_id = str(uuid.uuid4())
|
||||
with get_db() as conn:
|
||||
return _write_profile(
|
||||
conn,
|
||||
profile_id,
|
||||
title=title,
|
||||
name=name,
|
||||
url=url,
|
||||
model=model,
|
||||
zdr=zdr,
|
||||
no_train=no_train,
|
||||
)
|
||||
|
||||
|
||||
def update_profile(
|
||||
profile_id: str,
|
||||
*,
|
||||
title: str,
|
||||
name: str,
|
||||
url: str,
|
||||
model: str,
|
||||
zdr: bool,
|
||||
no_train: bool,
|
||||
) -> dict:
|
||||
with get_db() as conn:
|
||||
if not _profile_row(conn, profile_id):
|
||||
raise SettingsError("profile_missing", "Profil fehlt.", 404)
|
||||
return _write_profile(
|
||||
conn,
|
||||
profile_id,
|
||||
title=title,
|
||||
name=name,
|
||||
url=url,
|
||||
model=model,
|
||||
zdr=zdr,
|
||||
no_train=no_train,
|
||||
)
|
||||
|
||||
|
||||
def delete_profile(profile_id: str) -> None:
|
||||
with get_db() as conn:
|
||||
if not _profile_row(conn, profile_id):
|
||||
raise SettingsError("profile_missing", "Profil fehlt.", 404)
|
||||
used = conn.execute(
|
||||
"SELECT role FROM provider_settings WHERE profile_id = ?",
|
||||
(profile_id,),
|
||||
).fetchall()
|
||||
if used:
|
||||
roles = ", ".join(row["role"] for row in used)
|
||||
raise SettingsError(
|
||||
"profile_in_use",
|
||||
f"Profil ist noch der Stufe {roles} zugeordnet. Zuerst ein anderes Profil wählen.",
|
||||
)
|
||||
from detect_learning import get_local_ner_settings, set_local_ner_settings
|
||||
|
||||
if get_local_ner_settings().get("passage_profile_id") == profile_id:
|
||||
set_local_ner_settings(passage_profile_id="")
|
||||
conn.execute("DELETE FROM llm_profiles WHERE id = ?", (profile_id,))
|
||||
|
||||
|
||||
def activate_profile(role: str, profile_id: str) -> dict:
|
||||
if role not in ROLES:
|
||||
raise SettingsError("unknown_provider_role", "Unbekannte Provider-Rolle.")
|
||||
with get_db() as conn:
|
||||
row = _profile_row(conn, profile_id)
|
||||
if not row:
|
||||
raise SettingsError("profile_missing", "Profil fehlt.", 404)
|
||||
url = (row.get("url") or "").strip()
|
||||
model = (row.get("model") or "").strip()
|
||||
if role == "generate" and not url:
|
||||
raise SettingsError("provider_url_required", "Das Sprachmodell braucht eine URL.")
|
||||
if role == "detect" and not url:
|
||||
raise SettingsError("provider_url_required", "Die Maskierung braucht eine URL.")
|
||||
if not model:
|
||||
raise SettingsError("provider_model_required", "Das Profil braucht ein Modell.")
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO provider_settings (role, name, url, model, zdr, no_train, profile_id, updated)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
ON CONFLICT(role) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
url = excluded.url,
|
||||
model = excluded.model,
|
||||
zdr = excluded.zdr,
|
||||
no_train = excluded.no_train,
|
||||
profile_id = excluded.profile_id,
|
||||
updated = datetime('now')
|
||||
""",
|
||||
(
|
||||
role,
|
||||
row.get("name") or "",
|
||||
url,
|
||||
model,
|
||||
1 if row.get("zdr", 1) else 0,
|
||||
1 if row.get("no_train", 1) else 0,
|
||||
profile_id,
|
||||
),
|
||||
)
|
||||
return get_setting(role) or {}
|
||||
|
||||
|
||||
def get_setting(role: str) -> dict | None:
|
||||
@@ -69,34 +341,71 @@ def get_setting(role: str) -> dict | None:
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def upsert_setting(role: str, *, name: str, url: str, model: str, zdr: bool, no_train: bool) -> dict:
|
||||
def upsert_setting(
|
||||
role: str,
|
||||
*,
|
||||
name: str,
|
||||
url: str,
|
||||
model: str,
|
||||
zdr: bool,
|
||||
no_train: bool,
|
||||
profile_id: str | None = None,
|
||||
save_as_title: str | None = None,
|
||||
) -> dict:
|
||||
if role not in ROLES:
|
||||
raise SettingsError("unknown_provider_role", "Unbekannte Provider-Rolle.")
|
||||
url = (url or "").strip()
|
||||
url = _validate_url(url)
|
||||
model = (model or "").strip()
|
||||
name = (name or "").strip()
|
||||
if role == "generate" and not url:
|
||||
raise SettingsError("provider_url_required", "Das Sprachmodell braucht eine URL.")
|
||||
if url:
|
||||
parsed = urlparse(url)
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
||||
raise SettingsError("provider_url_invalid", "URL muss http(s) sein.")
|
||||
if role == "generate" and not model:
|
||||
raise SettingsError("provider_model_required", "Das Sprachmodell braucht ein Modell.")
|
||||
title = (save_as_title or "").strip()
|
||||
with get_db() as conn:
|
||||
current = conn.execute("SELECT * FROM provider_settings WHERE role = ?", (role,)).fetchone()
|
||||
current_id = (dict(current).get("profile_id") if current else "") or ""
|
||||
chosen = (profile_id or "").strip() or current_id
|
||||
if title:
|
||||
chosen = str(uuid.uuid4())
|
||||
_write_profile(
|
||||
conn,
|
||||
chosen,
|
||||
title=title,
|
||||
name=name,
|
||||
url=url,
|
||||
model=model,
|
||||
zdr=zdr,
|
||||
no_train=no_train,
|
||||
)
|
||||
elif chosen:
|
||||
existing = _profile_row(conn, chosen)
|
||||
if not existing:
|
||||
raise SettingsError("profile_missing", "Profil fehlt.", 404)
|
||||
_write_profile(
|
||||
conn,
|
||||
chosen,
|
||||
title=existing.get("title") or title or role,
|
||||
name=name,
|
||||
url=url,
|
||||
model=model,
|
||||
zdr=zdr,
|
||||
no_train=no_train,
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO provider_settings (role, name, url, model, zdr, no_train, updated)
|
||||
VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
INSERT INTO provider_settings (role, name, url, model, zdr, no_train, profile_id, updated)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
|
||||
ON CONFLICT(role) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
url = excluded.url,
|
||||
model = excluded.model,
|
||||
zdr = excluded.zdr,
|
||||
no_train = excluded.no_train,
|
||||
profile_id = excluded.profile_id,
|
||||
updated = datetime('now')
|
||||
""",
|
||||
(role, name, url, model, 1 if zdr else 0, 1 if no_train else 0),
|
||||
(role, name, url, model, 1 if zdr else 0, 1 if no_train else 0, chosen or None),
|
||||
)
|
||||
return get_setting(role) or {}
|
||||
|
||||
@@ -111,11 +420,11 @@ def set_role_key(role: str, key: str) -> None:
|
||||
|
||||
|
||||
def public_role_status(role: str) -> dict:
|
||||
from providers import _is_local_url, detect_provider, generate_provider
|
||||
from providers import detect_provider, generate_provider, is_local_url
|
||||
|
||||
row = get_setting(role) or {}
|
||||
config = generate_provider() if role == "generate" else detect_provider()
|
||||
local = _is_local_url(row.get("url") or "")
|
||||
local = is_local_url(row.get("url") or "")
|
||||
own_key = bool((os.environ.get(_KEY_ENV[role]) or "").strip())
|
||||
generate_key = bool((os.environ.get(_KEY_ENV["generate"]) or "").strip())
|
||||
if own_key:
|
||||
@@ -134,6 +443,7 @@ def public_role_status(role: str) -> dict:
|
||||
"model": row.get("model") or "",
|
||||
"zdr": bool(row.get("zdr", 1)),
|
||||
"no_train": bool(row.get("no_train", 1)),
|
||||
"profile_id": row.get("profile_id") or "",
|
||||
"local": local,
|
||||
"key_present": key_source != "none",
|
||||
"key_source": key_source,
|
||||
@@ -141,6 +451,7 @@ def public_role_status(role: str) -> dict:
|
||||
"mode": config.mode if config else "unconfigured",
|
||||
"remote_plaintext_detect": bool(config and not config.local and config.mode == "http" and role == "detect"),
|
||||
"remote_plaintext_allowed": allows_remote_plaintext_detect() if role == "detect" else None,
|
||||
"remote_plaintext_reason": remote_plaintext_detect_reason() if role == "detect" else None,
|
||||
"updated": row.get("updated") or "",
|
||||
}
|
||||
|
||||
@@ -148,6 +459,18 @@ def public_role_status(role: str) -> dict:
|
||||
def public_status() -> dict:
|
||||
return {
|
||||
"roles": [public_role_status(role) for role in ROLES],
|
||||
"profiles": list_profiles(),
|
||||
"runtime_env": runtime_env(),
|
||||
"note": "Zwei Einträge: Maskierung (Detect) und Sprachmodell. Semantische Detection ist Pflicht vor Generate. Externes Klartext-Detect nur Development/Test. Produktiv lokal. Keys nur in backend/.env.",
|
||||
"note": "LLM-Profile speichern URL und Modell je Endpunkt. Maskierung und Sprachmodell wählen je ein Profil. Semantische Detection ist Pflicht vor Generate. LAN-Ollama gilt als lokal. Keys nur in .env.",
|
||||
"remote_plaintext_reason": remote_plaintext_detect_reason(),
|
||||
"remote_plaintext_allowed": allows_remote_plaintext_detect(),
|
||||
"ollama_url": OLLAMA_LAN_URL,
|
||||
"detect_operating_mode": get_detect_operating_mode(),
|
||||
"local_ner": _local_ner_status(),
|
||||
}
|
||||
|
||||
|
||||
def _local_ner_status() -> dict:
|
||||
from detect_learning import get_local_ner_settings
|
||||
|
||||
return get_local_ner_settings()
|
||||
+102
-9
@@ -1,6 +1,8 @@
|
||||
"""Two independently configured OpenAI-compatible providers: generate vs detect."""
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
@@ -28,6 +30,53 @@ class ProviderError(Exception):
|
||||
self.diagnostics = diagnostics or {}
|
||||
|
||||
|
||||
PROVIDER_MESSAGE_MAX = 240
|
||||
_PROVIDER_USAGE_KEYS = ("prompt_tokens", "completion_tokens", "total_tokens", "cost", "total_cost")
|
||||
|
||||
|
||||
def provider_error_diagnostics(status_code: int, body: str, *, extra: dict | None = None) -> dict:
|
||||
"""Compact provider failure fields. No prompt body, no mapping labels."""
|
||||
diagnostics: dict = {"http_status": status_code}
|
||||
if extra:
|
||||
diagnostics.update({key: value for key, value in extra.items() if value is not None})
|
||||
parsed = None
|
||||
try:
|
||||
parsed = json.loads(body or "")
|
||||
except (TypeError, ValueError, json.JSONDecodeError):
|
||||
parsed = None
|
||||
if isinstance(parsed, dict):
|
||||
err = parsed.get("error")
|
||||
if isinstance(err, str) and err.strip():
|
||||
diagnostics["provider_message"] = err.strip()[:PROVIDER_MESSAGE_MAX]
|
||||
elif isinstance(err, dict):
|
||||
msg = str(err.get("message") or err.get("msg") or "").strip()
|
||||
if msg:
|
||||
diagnostics["provider_message"] = msg[:PROVIDER_MESSAGE_MAX]
|
||||
code = err.get("code") or err.get("type")
|
||||
if code:
|
||||
diagnostics["provider_code"] = str(code)[:80]
|
||||
usage = parsed.get("usage")
|
||||
if isinstance(usage, dict):
|
||||
kept = {key: usage[key] for key in _PROVIDER_USAGE_KEYS if usage.get(key) is not None}
|
||||
if kept:
|
||||
diagnostics["usage"] = kept
|
||||
if kept.get("cost") is not None:
|
||||
diagnostics["cost"] = kept["cost"]
|
||||
elif kept.get("total_cost") is not None:
|
||||
diagnostics["cost"] = kept["total_cost"]
|
||||
return diagnostics
|
||||
|
||||
|
||||
def _reject_message(role: str, status_code: int, diagnostics: dict) -> str:
|
||||
base = f"{role}-Provider hat die Anfrage abgelehnt"
|
||||
if status_code:
|
||||
base += f" (HTTP {status_code})"
|
||||
snippet = (diagnostics.get("provider_message") or "").strip()
|
||||
if snippet:
|
||||
return f"{base}: {snippet}"
|
||||
return f"{base}."
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProviderConfig:
|
||||
role: str
|
||||
@@ -59,9 +108,27 @@ def _truthy(name: str) -> bool:
|
||||
return os.environ.get(name, "").strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def is_local_url(url: str) -> bool:
|
||||
"""Loopback, RFC1918/ULA and .local stay in the local trusted zone.
|
||||
|
||||
Homelab Ollama (e.g. 192.168.2.144) is local, not an external provider.
|
||||
"""
|
||||
host = (urlparse(url or "").hostname or "").lower()
|
||||
if not host:
|
||||
return False
|
||||
if host in {"localhost", "127.0.0.1", "::1", "ollama"}:
|
||||
return True
|
||||
if host.endswith(".local"):
|
||||
return True
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
except ValueError:
|
||||
return False
|
||||
return bool(ip.is_loopback or ip.is_private or ip.is_link_local)
|
||||
|
||||
|
||||
def _is_local_url(url: str) -> bool:
|
||||
host = (urlparse(url).hostname or "").lower()
|
||||
return host in {"localhost", "127.0.0.1", "::1", "ollama"}
|
||||
return is_local_url(url)
|
||||
|
||||
|
||||
def _setting(role: str) -> dict:
|
||||
@@ -77,9 +144,9 @@ def _text(env_name: str, db_value: str | None, default: str = "") -> str:
|
||||
env = (os.environ.get(env_name) or "").strip()
|
||||
if env:
|
||||
return env
|
||||
if db_value:
|
||||
return str(db_value).strip()
|
||||
if db_value is None:
|
||||
return default
|
||||
return str(db_value).strip()
|
||||
|
||||
|
||||
def _flag(env_name: str, db_value, default: bool = True) -> bool:
|
||||
@@ -107,9 +174,11 @@ def generate_provider() -> ProviderConfig | None:
|
||||
key = (os.environ.get("KANSHO_PROVIDER_KEY") or "").strip()
|
||||
url = _text("KANSHO_PROVIDER_URL", row.get("url"), "https://openrouter.ai/api/v1/chat/completions")
|
||||
model = _text("KANSHO_PROVIDER_MODEL", row.get("model"), "openai/gpt-4o-mini")
|
||||
local = _is_local_url(url)
|
||||
local = is_local_url(url)
|
||||
zdr = local or _flag("KANSHO_PROVIDER_ZDR", row.get("zdr"), True)
|
||||
no_train = local or _flag("KANSHO_PROVIDER_NO_TRAIN", row.get("no_train"), True)
|
||||
if not url or not model:
|
||||
return None
|
||||
if not local and not key:
|
||||
return None
|
||||
if not local and (not zdr or not no_train):
|
||||
@@ -145,8 +214,10 @@ def detect_provider() -> ProviderConfig | None:
|
||||
if not url:
|
||||
return None
|
||||
model = _text("KANSHO_DETECT_PROVIDER_MODEL", row.get("model"), "openai/gpt-4.1-nano")
|
||||
if not model:
|
||||
return None
|
||||
key = (os.environ.get("KANSHO_DETECT_PROVIDER_KEY") or "").strip()
|
||||
local = _is_local_url(url)
|
||||
local = is_local_url(url)
|
||||
if not key and not local:
|
||||
key = (os.environ.get("KANSHO_PROVIDER_KEY") or "").strip()
|
||||
zdr = local or _flag("KANSHO_DETECT_ZDR", row.get("zdr"), True)
|
||||
@@ -193,23 +264,45 @@ def complete_chat(
|
||||
headers["X-Title"] = "Kansho"
|
||||
try:
|
||||
response = httpx.post(config.url, json=payload, headers=headers, timeout=timeout)
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ProviderError(
|
||||
"provider_timeout",
|
||||
f"{config.role}-Provider hat nicht innerhalb von {int(timeout)} Sekunden geantwortet.",
|
||||
504,
|
||||
diagnostics={"timeout_s": timeout, "generate_requested": True},
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise ProviderError("provider_unreachable", f"{config.role}-Provider ist nicht erreichbar.") from exc
|
||||
raise ProviderError(
|
||||
"provider_unreachable",
|
||||
f"{config.role}-Provider ist nicht erreichbar.",
|
||||
503,
|
||||
diagnostics={"generate_requested": True},
|
||||
) from exc
|
||||
if response.status_code >= 400:
|
||||
body = ""
|
||||
try:
|
||||
body = response.text or ""
|
||||
except Exception:
|
||||
body = ""
|
||||
diagnostics = provider_error_diagnostics(
|
||||
response.status_code,
|
||||
body,
|
||||
extra={"context_compression": compression, "generate_requested": True},
|
||||
)
|
||||
if CONTEXT_LENGTH_REJECT.search(body):
|
||||
raise ProviderError(
|
||||
"provider_context_length_rejected",
|
||||
"Der Anbieter hat die Anfrage wegen der Kontextlänge abgelehnt. "
|
||||
"Kanshō hat den Tagesdialog nicht automatisch gekürzt.",
|
||||
502,
|
||||
diagnostics={"http_status": response.status_code, "context_compression": compression},
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
raise ProviderError(
|
||||
"provider_rejected",
|
||||
_reject_message(config.role, response.status_code, diagnostics),
|
||||
502,
|
||||
diagnostics=diagnostics,
|
||||
)
|
||||
raise ProviderError("provider_rejected", f"{config.role}-Provider hat die Anfrage abgelehnt.")
|
||||
data = response.json()
|
||||
try:
|
||||
content = data["choices"][0]["message"]["content"]
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
# Default python collector is disabled; tests/conftest.py collects each
|
||||
# test_*.py as one case via main(). That keeps the existing scripts until
|
||||
# they are split into native pytest functions.
|
||||
python_files = __pytest_default_collector_disabled__.py
|
||||
python_functions = test_*
|
||||
addopts = -ra --tb=short
|
||||
markers =
|
||||
unit: no Postgres; safe on Windows SQLite checkouts
|
||||
integration: API/store tests on kansho_test (never kansho_dev)
|
||||
slow: long-running; omitted in the default Gitea command
|
||||
@@ -0,0 +1,3 @@
|
||||
# CI / local test runner. Install on top of requirements.txt:
|
||||
# pip install -r requirements.txt -r requirements-dev.txt
|
||||
pytest>=8.0
|
||||
@@ -3,3 +3,4 @@ uvicorn[standard]==0.34.0
|
||||
bcrypt==4.2.1
|
||||
httpx==0.28.1
|
||||
python-multipart==0.0.20
|
||||
psycopg[binary]==3.2.6
|
||||
@@ -95,7 +95,7 @@ def _day_messages(profile_id: str, spec: dict[str, Any]) -> list[dict]:
|
||||
FROM messages m
|
||||
JOIN conversations c ON c.id = m.conversation_id
|
||||
WHERE m.profile_id = ? AND c.journal_day_id = ? AND m.conversation_id IN ({placeholders})
|
||||
ORDER BY c.created, c.rowid, m.seq, m.id
|
||||
ORDER BY c.created, c.id, m.seq, m.id
|
||||
LIMIT ?
|
||||
""",
|
||||
(profile_id, journal_day_id, *conversation_ids, fetch_limit),
|
||||
@@ -107,7 +107,7 @@ def _day_messages(profile_id: str, spec: dict[str, Any]) -> list[dict]:
|
||||
FROM messages m
|
||||
JOIN conversations c ON c.id = m.conversation_id
|
||||
WHERE m.profile_id = ? AND c.journal_day_id = ?
|
||||
ORDER BY c.created, c.rowid, m.seq, m.id
|
||||
ORDER BY c.created, c.id, m.seq, m.id
|
||||
LIMIT ?
|
||||
""",
|
||||
(profile_id, journal_day_id, fetch_limit),
|
||||
@@ -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,
|
||||
}
|
||||
)
|
||||
|
||||
+171
-1
@@ -2,6 +2,7 @@ from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel, Field
|
||||
import json
|
||||
import os
|
||||
|
||||
from auth import require_admin_dep
|
||||
from db import get_db
|
||||
@@ -19,6 +20,7 @@ from debug_store import (
|
||||
settings_payload,
|
||||
)
|
||||
from dialogue_store import StoreError, get_conversation, inventory, list_conversations, list_derived_for_conversation, list_messages
|
||||
from detect_learning import list_senses
|
||||
from identity_store import (
|
||||
confirm_identity,
|
||||
confirm_review_proposal,
|
||||
@@ -30,7 +32,18 @@ from identity_store import (
|
||||
list_review_proposals,
|
||||
update_identity,
|
||||
)
|
||||
from provider_settings import ROLES, SettingsError, public_status, set_role_key, upsert_setting
|
||||
from provider_settings import (
|
||||
ROLES,
|
||||
SettingsError,
|
||||
activate_profile,
|
||||
create_profile,
|
||||
delete_profile,
|
||||
list_profiles,
|
||||
public_status,
|
||||
set_role_key,
|
||||
update_profile,
|
||||
upsert_setting,
|
||||
)
|
||||
from version import APP_VERSION, BUILD_DATE, MODULE_VERSIONS
|
||||
|
||||
router = APIRouter(prefix="/api/admin", tags=["admin"])
|
||||
@@ -196,14 +209,110 @@ class ProviderUpdate(BaseModel):
|
||||
model: str = ""
|
||||
zdr: bool = True
|
||||
no_train: bool = True
|
||||
profile_id: str | None = None
|
||||
save_as_title: str | None = None
|
||||
key: str | None = Field(default=None, description="Write-only. Never returned.")
|
||||
|
||||
|
||||
class LlmProfileWrite(BaseModel):
|
||||
title: str
|
||||
name: str = ""
|
||||
url: str
|
||||
model: str = ""
|
||||
zdr: bool = True
|
||||
no_train: bool = True
|
||||
|
||||
|
||||
class ActivateProfile(BaseModel):
|
||||
profile_id: str
|
||||
|
||||
|
||||
class DetectModeWrite(BaseModel):
|
||||
mode: str
|
||||
|
||||
|
||||
class LocalNerWrite(BaseModel):
|
||||
enabled: bool | None = None
|
||||
url: str | None = None
|
||||
passage_profile_id: str | None = None
|
||||
|
||||
|
||||
@router.put("/providers/detect-mode")
|
||||
def admin_set_detect_mode(body: DetectModeWrite, session: dict = Depends(require_admin_dep)):
|
||||
from detect_learning import set_detect_operating_mode
|
||||
from provider_settings import public_status as provider_public_status
|
||||
|
||||
try:
|
||||
set_detect_operating_mode(body.mode)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": "invalid_detect_operating_mode",
|
||||
"message": "Detect-Modus muss student, learning_full, learning_reduced, learning_manual oder bypass sein.",
|
||||
},
|
||||
)
|
||||
return provider_public_status()
|
||||
|
||||
|
||||
@router.put("/providers/local-ner")
|
||||
def admin_set_local_ner(body: LocalNerWrite, session: dict = Depends(require_admin_dep)):
|
||||
from detect_learning import set_local_ner_settings
|
||||
from provider_settings import public_status as provider_public_status
|
||||
|
||||
try:
|
||||
set_local_ner_settings(
|
||||
enabled=body.enabled,
|
||||
url=body.url,
|
||||
passage_profile_id=body.passage_profile_id,
|
||||
)
|
||||
except ValueError as exc:
|
||||
code = str(exc)
|
||||
if code == "gliner_url_not_local":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={
|
||||
"code": code,
|
||||
"message": "GLiNER-URL muss in der lokalen Trusted Zone liegen.",
|
||||
},
|
||||
) from exc
|
||||
if code == "passage_profile_missing":
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={"code": code, "message": "Das Klärungs-Profil fehlt."},
|
||||
) from exc
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail={"code": "invalid_local_ner", "message": "Lokale NER-Einstellung ungültig."},
|
||||
) from exc
|
||||
return provider_public_status()
|
||||
|
||||
|
||||
@router.get("/providers")
|
||||
def admin_providers(session: dict = Depends(require_admin_dep)):
|
||||
return public_status()
|
||||
|
||||
|
||||
@router.get("/providers/models")
|
||||
def admin_provider_models(url: str | None = None, session: dict = Depends(require_admin_dep)):
|
||||
from model_catalog import list_models_for_url, list_provider_models
|
||||
from providers import detect_provider, generate_provider
|
||||
|
||||
if url:
|
||||
key = ""
|
||||
from providers import is_local_url
|
||||
|
||||
if not is_local_url(url):
|
||||
key = (os.environ.get("KANSHO_PROVIDER_KEY") or "").strip()
|
||||
return {"url": url, "models": list_models_for_url(url, key)}
|
||||
return {
|
||||
"roles": {
|
||||
"generate": list_provider_models(generate_provider()),
|
||||
"detect": list_provider_models(detect_provider()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.put("/providers/{role}")
|
||||
def admin_update_provider(role: str, body: ProviderUpdate, session: dict = Depends(require_admin_dep)):
|
||||
if role not in ROLES:
|
||||
@@ -216,6 +325,8 @@ def admin_update_provider(role: str, body: ProviderUpdate, session: dict = Depen
|
||||
model=body.model,
|
||||
zdr=body.zdr,
|
||||
no_train=body.no_train,
|
||||
profile_id=body.profile_id,
|
||||
save_as_title=body.save_as_title,
|
||||
)
|
||||
if body.key is not None and body.key.strip():
|
||||
set_role_key(role, body.key)
|
||||
@@ -224,6 +335,64 @@ def admin_update_provider(role: str, body: ProviderUpdate, session: dict = Depen
|
||||
return public_status()
|
||||
|
||||
|
||||
@router.post("/providers/{role}/activate")
|
||||
def admin_activate_provider(role: str, body: ActivateProfile, session: dict = Depends(require_admin_dep)):
|
||||
if role not in ROLES:
|
||||
raise HTTPException(status_code=404, detail={"code": "unknown_provider_role", "message": "Unbekannte Provider-Rolle."})
|
||||
try:
|
||||
activate_profile(role, body.profile_id)
|
||||
except SettingsError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
|
||||
return public_status()
|
||||
|
||||
|
||||
@router.get("/llm-profiles")
|
||||
def admin_list_profiles(session: dict = Depends(require_admin_dep)):
|
||||
return {"profiles": list_profiles()}
|
||||
|
||||
|
||||
@router.post("/llm-profiles")
|
||||
def admin_create_profile(body: LlmProfileWrite, session: dict = Depends(require_admin_dep)):
|
||||
try:
|
||||
profile = create_profile(
|
||||
title=body.title,
|
||||
name=body.name,
|
||||
url=body.url,
|
||||
model=body.model,
|
||||
zdr=body.zdr,
|
||||
no_train=body.no_train,
|
||||
)
|
||||
except SettingsError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
|
||||
return {"profile": profile, **public_status()}
|
||||
|
||||
|
||||
@router.put("/llm-profiles/{profile_id}")
|
||||
def admin_update_profile(profile_id: str, body: LlmProfileWrite, session: dict = Depends(require_admin_dep)):
|
||||
try:
|
||||
profile = update_profile(
|
||||
profile_id,
|
||||
title=body.title,
|
||||
name=body.name,
|
||||
url=body.url,
|
||||
model=body.model,
|
||||
zdr=body.zdr,
|
||||
no_train=body.no_train,
|
||||
)
|
||||
except SettingsError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
|
||||
return {"profile": profile, **public_status()}
|
||||
|
||||
|
||||
@router.delete("/llm-profiles/{profile_id}")
|
||||
def admin_delete_profile(profile_id: str, session: dict = Depends(require_admin_dep)):
|
||||
try:
|
||||
delete_profile(profile_id)
|
||||
except SettingsError as exc:
|
||||
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
|
||||
return public_status()
|
||||
|
||||
|
||||
class IdentityWrite(BaseModel):
|
||||
canonical_label: str = ""
|
||||
entity_type: str = "PERSON"
|
||||
@@ -257,6 +426,7 @@ def admin_identities(session: dict = Depends(require_admin_dep)):
|
||||
return {
|
||||
"registry": list_registry(profile_id),
|
||||
"proposals": list_review_proposals(profile_id, include_dismissed=True),
|
||||
"senses": list_senses(profile_id),
|
||||
"note": "Nur lokale bestätigte Registry und unbestätigte Vorschläge. Kein externer Egress.",
|
||||
"backup": (
|
||||
"Vor einer Bereinigung die lokale Datei backend/data/kansho.sqlite kopieren. "
|
||||
|
||||
+97
-11
@@ -5,8 +5,25 @@ import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from account_access import (
|
||||
FORGOT_MESSAGE,
|
||||
consume_password_reset,
|
||||
consume_verification,
|
||||
deliver_jobs,
|
||||
find_by_login,
|
||||
issue_password_reset,
|
||||
issue_verification,
|
||||
load_profile,
|
||||
normalize_email,
|
||||
profile_view,
|
||||
resend_verification,
|
||||
reset_message,
|
||||
verified_reset_recipients,
|
||||
verify_message,
|
||||
)
|
||||
from auth import create_session, hash_password, require_auth, verify_password
|
||||
from db import get_db, row_to_dict
|
||||
from db import get_db
|
||||
from mailer import MailNotConfigured
|
||||
from version import APP_VERSION
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
@@ -23,6 +40,23 @@ class SetupRequest(BaseModel):
|
||||
password: str = Field(min_length=4)
|
||||
|
||||
|
||||
class ForgotRequest(BaseModel):
|
||||
email: str = Field(min_length=1)
|
||||
|
||||
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
token: str = Field(min_length=10)
|
||||
password: str = Field(min_length=4)
|
||||
|
||||
|
||||
class VerifyEmailRequest(BaseModel):
|
||||
token: str = Field(min_length=10)
|
||||
|
||||
|
||||
class ResendVerificationRequest(BaseModel):
|
||||
purpose: str
|
||||
|
||||
|
||||
def _profile_count() -> int:
|
||||
with get_db() as conn:
|
||||
row = conn.execute("SELECT COUNT(*) AS n FROM profiles").fetchone()
|
||||
@@ -43,15 +77,22 @@ def auth_status():
|
||||
def setup(req: SetupRequest):
|
||||
if _profile_count() > 0:
|
||||
raise HTTPException(409, "Setup ist bereits abgeschlossen")
|
||||
email = normalize_email(req.email)
|
||||
profile_id = str(uuid.uuid4())
|
||||
jobs: list[tuple[list[str], str, str]] = []
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO profiles (id, email, name, password_hash, role)
|
||||
VALUES (?, ?, ?, ?, 'admin')
|
||||
""",
|
||||
(profile_id, req.email.lower().strip(), req.name.strip(), hash_password(req.password)),
|
||||
(profile_id, email, req.name.strip(), hash_password(req.password)),
|
||||
)
|
||||
raw = issue_verification(conn, profile_id, "primary", email)
|
||||
if raw:
|
||||
subject, body = verify_message(raw)
|
||||
jobs.append(([email], subject, body))
|
||||
_send_or_log_failure(jobs)
|
||||
token, expires = create_session(profile_id)
|
||||
return {
|
||||
"token": token,
|
||||
@@ -62,15 +103,20 @@ def setup(req: SetupRequest):
|
||||
}
|
||||
|
||||
|
||||
def _send_or_log_failure(jobs: list[tuple[list[str], str, str]]) -> bool:
|
||||
if not jobs:
|
||||
return True
|
||||
try:
|
||||
deliver_jobs(jobs)
|
||||
except MailNotConfigured:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
def login(req: LoginRequest):
|
||||
with get_db() as conn:
|
||||
prof = row_to_dict(
|
||||
conn.execute(
|
||||
"SELECT * FROM profiles WHERE email = ?",
|
||||
(req.email.lower().strip(),),
|
||||
).fetchone()
|
||||
)
|
||||
prof = find_by_login(conn, req.email)
|
||||
if not prof or not verify_password(req.password, prof["password_hash"]):
|
||||
raise HTTPException(401, "Ungültige Zugangsdaten")
|
||||
if (prof.get("status") or "active") != "active":
|
||||
@@ -95,9 +141,49 @@ def logout(session: dict = Depends(require_auth)):
|
||||
@router.get("/me")
|
||||
def me(session: dict = Depends(require_auth)):
|
||||
with get_db() as conn:
|
||||
prof = row_to_dict(
|
||||
conn.execute("SELECT id, email, name, role, status, tier_id FROM profiles WHERE id = ?", (session["profile_id"],)).fetchone()
|
||||
)
|
||||
prof = profile_view(load_profile(conn, session["profile_id"]))
|
||||
if not prof:
|
||||
raise HTTPException(401, "Profil nicht gefunden")
|
||||
return prof
|
||||
|
||||
|
||||
@router.post("/forgot-password")
|
||||
def forgot_password(req: ForgotRequest):
|
||||
jobs: list[tuple[list[str], str, str]] = []
|
||||
with get_db() as conn:
|
||||
prof = find_by_login(conn, req.email)
|
||||
if prof and (prof.get("status") or "active") == "active":
|
||||
recipients = verified_reset_recipients(prof)
|
||||
if recipients:
|
||||
raw = issue_password_reset(conn, prof["id"])
|
||||
if raw:
|
||||
subject, body = reset_message(raw)
|
||||
jobs.append((recipients, subject, body))
|
||||
_send_or_log_failure(jobs)
|
||||
return {"ok": True, "message": FORGOT_MESSAGE}
|
||||
|
||||
|
||||
@router.post("/reset-password")
|
||||
def reset_password(req: ResetPasswordRequest):
|
||||
with get_db() as conn:
|
||||
consume_password_reset(conn, req.token, req.password)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/verify-email")
|
||||
def verify_email(req: VerifyEmailRequest):
|
||||
with get_db() as conn:
|
||||
return consume_verification(conn, req.token)
|
||||
|
||||
|
||||
@router.post("/resend-verification")
|
||||
def resend(req: ResendVerificationRequest, session: dict = Depends(require_auth)):
|
||||
with get_db() as conn:
|
||||
profile = load_profile(conn, session["profile_id"])
|
||||
if not profile:
|
||||
raise HTTPException(401, "Profil nicht gefunden")
|
||||
recipients, subject, body = resend_verification(conn, profile, req.purpose)
|
||||
jobs = [(recipients, subject, body)]
|
||||
if not _send_or_log_failure(jobs):
|
||||
raise HTTPException(503, "Mailversand ist nicht konfiguriert")
|
||||
return {"ok": True}
|
||||
@@ -7,8 +7,10 @@ from auth import require_auth
|
||||
from context_builder import build_internal_context
|
||||
from continuity import checkpoint_usage_session, close_usage_session
|
||||
from derived_kinds import catalog
|
||||
from dialogue_turn import run_turn, visible_for_role
|
||||
from detect_learning import pending_for_conversation
|
||||
from dialogue_turn import continue_turn, run_turn, visible_for_role
|
||||
from engine import EngineError
|
||||
from privacy_gateway import public_error_detail
|
||||
from dialogue_store import (
|
||||
StoreError,
|
||||
append_message,
|
||||
@@ -31,11 +33,7 @@ router = APIRouter(prefix="/api/dialogue", tags=["dialogue"])
|
||||
|
||||
|
||||
def _http(exc: StoreError | EngineError):
|
||||
detail = {"code": exc.code, "message": exc.message}
|
||||
extra = getattr(exc, "diagnostics", None)
|
||||
if extra:
|
||||
detail["diagnostics"] = extra
|
||||
raise HTTPException(status_code=exc.status_code, detail=detail) from exc
|
||||
raise HTTPException(status_code=exc.status_code, detail=public_error_detail(exc)) from exc
|
||||
|
||||
|
||||
class SessionWrite(BaseModel):
|
||||
@@ -54,6 +52,11 @@ class MessageWrite(BaseModel):
|
||||
id: str | None = None
|
||||
|
||||
|
||||
class MaskReviewWrite(BaseModel):
|
||||
review_id: str
|
||||
decisions: list[dict] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ThreadWrite(BaseModel):
|
||||
title: str = ""
|
||||
status: str = "open"
|
||||
@@ -143,6 +146,9 @@ def get_one_conversation(conversation_id: str, session: dict = Depends(require_a
|
||||
conv = get_conversation(session["profile_id"], conversation_id)
|
||||
conv["messages"] = list_messages(session["profile_id"], conversation_id)
|
||||
conv["derived"] = list_derived_for_conversation(session["profile_id"], conversation_id)
|
||||
pending = pending_for_conversation(session["profile_id"], conversation_id)
|
||||
if pending:
|
||||
conv["pending_mask_review"] = pending
|
||||
return conv
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
@@ -175,6 +181,17 @@ def conversation_turn(conversation_id: str, req: MessageWrite, session: dict = D
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/conversations/{conversation_id}/turn/review")
|
||||
def conversation_turn_review(conversation_id: str, req: MaskReviewWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return visible_for_role(
|
||||
continue_turn(session["profile_id"], conversation_id, req.review_id, req.decisions),
|
||||
session.get("role"),
|
||||
)
|
||||
except (StoreError, EngineError) as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.get("/conversations/{conversation_id}/messages")
|
||||
def get_messages(conversation_id: str, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
|
||||
@@ -31,6 +31,7 @@ class GuidelineWrite(BaseModel):
|
||||
label: str | None = None
|
||||
summary: str | None = None
|
||||
instruction: str | None = None
|
||||
style_context: dict | None = None
|
||||
sort_order: int | None = None
|
||||
|
||||
|
||||
|
||||
@@ -5,11 +5,12 @@ from fastapi.responses import FileResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from auth import require_auth
|
||||
from detect_learning import pending_for_conversation
|
||||
from dialogue_store import StoreError, delete_conversation, get_conversation, list_messages
|
||||
from dialogue_turn import run_turn, visible_for_role
|
||||
from privacy_gateway import GatewayRequest, inspect
|
||||
from dialogue_turn import continue_turn, run_turn, visible_for_role
|
||||
from privacy_gateway import GatewayRequest, inspect, public_error_detail
|
||||
from engine import EngineError
|
||||
from journal_generate import generate_draft
|
||||
from journal_generate import continue_journal_generate, generate_draft
|
||||
from journal_generation_policy import settings_payload
|
||||
from journal_opening import maybe_open_journal_conversation
|
||||
from journal_policy import PolicyError
|
||||
@@ -76,11 +77,7 @@ router = APIRouter(prefix="/api/journal", tags=["journal"])
|
||||
|
||||
|
||||
def _http(exc: StoreError | PolicyError | EngineError):
|
||||
detail = {"code": exc.code, "message": exc.message}
|
||||
extra = getattr(exc, "diagnostics", None)
|
||||
if extra:
|
||||
detail["diagnostics"] = extra
|
||||
raise HTTPException(status_code=exc.status_code, detail=detail) from exc
|
||||
raise HTTPException(status_code=exc.status_code, detail=public_error_detail(exc)) from exc
|
||||
|
||||
|
||||
class SpaceWrite(BaseModel):
|
||||
@@ -100,6 +97,11 @@ class TurnWrite(BaseModel):
|
||||
id: str | None = None
|
||||
|
||||
|
||||
class MaskReviewWrite(BaseModel):
|
||||
review_id: str
|
||||
decisions: list[dict] = Field(default_factory=list)
|
||||
|
||||
|
||||
class GenerateWrite(BaseModel):
|
||||
conversation_ids: list[str] | None = None
|
||||
include_existing: bool = False
|
||||
@@ -290,7 +292,11 @@ def remove_conversation(conversation_id: str, session: dict = Depends(require_au
|
||||
def read_conversation(conversation_id: str, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
conv = get_conversation(session["profile_id"], conversation_id)
|
||||
return {"conversation": conv, "messages": list_messages(session["profile_id"], conversation_id)}
|
||||
payload = {"conversation": conv, "messages": list_messages(session["profile_id"], conversation_id)}
|
||||
pending = pending_for_conversation(session["profile_id"], conversation_id)
|
||||
if pending:
|
||||
payload["pending_mask_review"] = pending
|
||||
return payload
|
||||
except StoreError as exc:
|
||||
_http(exc)
|
||||
|
||||
@@ -312,6 +318,17 @@ def conversation_turn(conversation_id: str, body: TurnWrite, session: dict = Dep
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/conversations/{conversation_id}/turn/review")
|
||||
def conversation_turn_review(conversation_id: str, body: MaskReviewWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return visible_for_role(
|
||||
continue_turn(session["profile_id"], conversation_id, body.review_id, body.decisions),
|
||||
session.get("role"),
|
||||
)
|
||||
except (StoreError, EngineError) as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.get("/generation-settings")
|
||||
def read_generation_settings(session: dict = Depends(require_auth)):
|
||||
return settings_payload(session["profile_id"])
|
||||
@@ -336,6 +353,22 @@ def generate(journal_day_id: str, body: GenerateWrite, session: dict = Depends(r
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/days/{journal_day_id}/generate/review")
|
||||
def generate_review(journal_day_id: str, body: MaskReviewWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
return visible_for_role(
|
||||
continue_journal_generate(
|
||||
session["profile_id"],
|
||||
journal_day_id,
|
||||
body.review_id,
|
||||
body.decisions,
|
||||
),
|
||||
session.get("role"),
|
||||
)
|
||||
except (StoreError, PolicyError, EngineError) as exc:
|
||||
_http(exc)
|
||||
|
||||
|
||||
@router.post("/entries")
|
||||
def write_entry(body: EntryWrite, session: dict = Depends(require_auth)):
|
||||
try:
|
||||
|
||||
+132
-17
@@ -5,19 +5,34 @@ import uuid
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from account_access import (
|
||||
admin_reset_recipients,
|
||||
apply_identifier_edits,
|
||||
assert_address_free,
|
||||
assert_username_free,
|
||||
deliver_jobs,
|
||||
issue_password_reset,
|
||||
issue_verification,
|
||||
load_profile,
|
||||
normalize_email,
|
||||
normalize_username,
|
||||
profile_view,
|
||||
reset_message,
|
||||
verify_message,
|
||||
)
|
||||
from auth import hash_password, require_admin_dep, require_auth
|
||||
from db import get_db, row_to_dict
|
||||
from db import get_db
|
||||
from mailer import MailNotConfigured
|
||||
|
||||
router = APIRouter(prefix="/api/users", tags=["users"])
|
||||
|
||||
PUBLIC_FIELDS = "id, email, name, role, status, tier_id, created"
|
||||
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
email: str
|
||||
name: str = Field(min_length=1)
|
||||
password: str = Field(min_length=4)
|
||||
role: str = "user"
|
||||
username: str | None = None
|
||||
|
||||
|
||||
class PatchUserRequest(BaseModel):
|
||||
@@ -25,6 +40,16 @@ class PatchUserRequest(BaseModel):
|
||||
role: str | None = None
|
||||
status: str | None = None
|
||||
password: str | None = None
|
||||
username: str | None = None
|
||||
email: str | None = None
|
||||
secondary_email: str | None = None
|
||||
|
||||
|
||||
class SelfPatchRequest(BaseModel):
|
||||
username: str | None = None
|
||||
email: str | None = None
|
||||
secondary_email: str | None = None
|
||||
password: str | None = None
|
||||
|
||||
|
||||
def _active_admin_count(conn, exclude_id: str | None = None) -> int:
|
||||
@@ -40,45 +65,104 @@ def _active_admin_count(conn, exclude_id: str | None = None) -> int:
|
||||
return int(row["n"])
|
||||
|
||||
|
||||
def _send_jobs(jobs: list[tuple[list[str], str, str]]) -> bool:
|
||||
if not jobs:
|
||||
return True
|
||||
try:
|
||||
deliver_jobs(jobs)
|
||||
except MailNotConfigured:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_users(session: dict = Depends(require_admin_dep)):
|
||||
with get_db() as conn:
|
||||
rows = conn.execute(f"SELECT {PUBLIC_FIELDS} FROM profiles ORDER BY created").fetchall()
|
||||
return [row_to_dict(row) for row in rows]
|
||||
rows = conn.execute("SELECT * FROM profiles ORDER BY created").fetchall()
|
||||
return [profile_view(dict(row)) for row in rows]
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_user(req: CreateUserRequest, session: dict = Depends(require_admin_dep)):
|
||||
if req.role not in {"user", "admin"}:
|
||||
raise HTTPException(400, "Rolle muss user oder admin sein")
|
||||
email = normalize_email(req.email)
|
||||
username = normalize_username(req.username) if req.username and req.username.strip() else None
|
||||
profile_id = str(uuid.uuid4())
|
||||
jobs: list[tuple[list[str], str, str]] = []
|
||||
try:
|
||||
with get_db() as conn:
|
||||
assert_address_free(conn, email, None)
|
||||
if username:
|
||||
assert_username_free(conn, username, None)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO profiles (id, email, name, password_hash, role, status, tier_id)
|
||||
VALUES (?, ?, ?, ?, ?, 'active', 'local')
|
||||
INSERT INTO profiles (id, email, name, password_hash, role, status, tier_id, username)
|
||||
VALUES (?, ?, ?, ?, ?, 'active', 'local', ?)
|
||||
""",
|
||||
(
|
||||
profile_id,
|
||||
req.email.lower().strip(),
|
||||
email,
|
||||
req.name.strip(),
|
||||
hash_password(req.password),
|
||||
req.role,
|
||||
username,
|
||||
),
|
||||
)
|
||||
prof = row_to_dict(conn.execute(f"SELECT {PUBLIC_FIELDS} FROM profiles WHERE id = ?", (profile_id,)).fetchone())
|
||||
raw = issue_verification(conn, profile_id, "primary", email)
|
||||
if raw:
|
||||
subject, body = verify_message(raw)
|
||||
jobs.append(([email], subject, body))
|
||||
prof = profile_view(load_profile(conn, profile_id))
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
if "UNIQUE" in str(exc).upper():
|
||||
raise HTTPException(409, "E-Mail ist bereits vergeben") from exc
|
||||
raise
|
||||
if not _send_jobs(jobs):
|
||||
prof = dict(prof or {})
|
||||
prof["mail_sent"] = False
|
||||
return prof
|
||||
|
||||
|
||||
@router.patch("/me")
|
||||
def patch_me(req: SelfPatchRequest, session: dict = Depends(require_auth)):
|
||||
provided = req.model_fields_set
|
||||
jobs: list[tuple[list[str], str, str]] = []
|
||||
with get_db() as conn:
|
||||
current = load_profile(conn, session["profile_id"])
|
||||
if not current:
|
||||
raise HTTPException(401, "Profil nicht gefunden")
|
||||
if req.password:
|
||||
if len(req.password) < 4:
|
||||
raise HTTPException(400, "Passwort muss mind. 4 Zeichen haben")
|
||||
conn.execute(
|
||||
"UPDATE profiles SET password_hash = ? WHERE id = ?",
|
||||
(hash_password(req.password), current["id"]),
|
||||
)
|
||||
jobs = apply_identifier_edits(
|
||||
conn,
|
||||
current,
|
||||
username=req.username,
|
||||
email=req.email,
|
||||
secondary_email=req.secondary_email,
|
||||
username_set="username" in provided,
|
||||
email_set="email" in provided,
|
||||
secondary_set="secondary_email" in provided,
|
||||
)
|
||||
prof = profile_view(load_profile(conn, current["id"]))
|
||||
if not _send_jobs(jobs):
|
||||
raise HTTPException(503, "Die Adresse ist vorgemerkt, der Mailversand ist nicht konfiguriert.")
|
||||
return prof
|
||||
|
||||
|
||||
@router.patch("/{profile_id}")
|
||||
def patch_user(profile_id: str, req: PatchUserRequest, session: dict = Depends(require_admin_dep)):
|
||||
provided = req.model_fields_set
|
||||
jobs: list[tuple[list[str], str, str]] = []
|
||||
with get_db() as conn:
|
||||
current = row_to_dict(conn.execute("SELECT * FROM profiles WHERE id = ?", (profile_id,)).fetchone())
|
||||
current = load_profile(conn, profile_id)
|
||||
if not current:
|
||||
raise HTTPException(404, "Nutzer nicht gefunden")
|
||||
name = req.name.strip() if req.name is not None else current["name"]
|
||||
@@ -105,18 +189,49 @@ def patch_user(profile_id: str, req: PatchUserRequest, session: dict = Depends(r
|
||||
)
|
||||
if status == "disabled":
|
||||
conn.execute("DELETE FROM sessions WHERE profile_id = ?", (profile_id,))
|
||||
return row_to_dict(conn.execute(f"SELECT {PUBLIC_FIELDS} FROM profiles WHERE id = ?", (profile_id,)).fetchone())
|
||||
current = load_profile(conn, profile_id) or current
|
||||
jobs = apply_identifier_edits(
|
||||
conn,
|
||||
current,
|
||||
username=req.username,
|
||||
email=req.email,
|
||||
secondary_email=req.secondary_email,
|
||||
username_set="username" in provided,
|
||||
email_set="email" in provided,
|
||||
secondary_set="secondary_email" in provided,
|
||||
)
|
||||
prof = profile_view(load_profile(conn, profile_id))
|
||||
if not _send_jobs(jobs):
|
||||
raise HTTPException(503, "Die Adresse ist vorgemerkt, der Mailversand ist nicht konfiguriert.")
|
||||
return prof
|
||||
|
||||
|
||||
@router.post("/{profile_id}/password-reset")
|
||||
def admin_password_reset(profile_id: str, session: dict = Depends(require_admin_dep)):
|
||||
if profile_id == session["profile_id"]:
|
||||
raise HTTPException(400, "Den eigenen Reset startest du über die Anmeldung")
|
||||
jobs: list[tuple[list[str], str, str]] = []
|
||||
with get_db() as conn:
|
||||
profile = load_profile(conn, profile_id)
|
||||
if not profile:
|
||||
raise HTTPException(404, "Nutzer nicht gefunden")
|
||||
recipients = admin_reset_recipients(profile)
|
||||
if not recipients:
|
||||
raise HTTPException(400, "Für dieses Konto ist keine E-Mail hinterlegt")
|
||||
raw = issue_password_reset(conn, profile_id)
|
||||
if not raw:
|
||||
raise HTTPException(429, "Zu viele Reset-Links. Bitte später erneut versuchen.")
|
||||
subject, body = reset_message(raw)
|
||||
jobs.append((recipients, subject, body))
|
||||
if not _send_jobs(jobs):
|
||||
raise HTTPException(503, "Mailversand ist nicht konfiguriert")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
def my_account(session: dict = Depends(require_auth)):
|
||||
with get_db() as conn:
|
||||
prof = row_to_dict(
|
||||
conn.execute(
|
||||
f"SELECT {PUBLIC_FIELDS} FROM profiles WHERE id = ?",
|
||||
(session["profile_id"],),
|
||||
).fetchone()
|
||||
)
|
||||
prof = profile_view(load_profile(conn, session["profile_id"]))
|
||||
if not prof:
|
||||
raise HTTPException(401, "Profil nicht gefunden")
|
||||
return prof
|
||||
@@ -40,6 +40,12 @@ CREATE TABLE IF NOT EXISTS profiles (
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')),
|
||||
tier_id TEXT NOT NULL DEFAULT 'local' REFERENCES tiers(id),
|
||||
session_days INTEGER NOT NULL DEFAULT 30,
|
||||
username TEXT,
|
||||
secondary_email TEXT,
|
||||
email_verified_at TEXT,
|
||||
secondary_email_verified_at TEXT,
|
||||
pending_email TEXT,
|
||||
pending_secondary_email TEXT,
|
||||
created TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
@@ -50,6 +56,26 @@ CREATE TABLE IF NOT EXISTS sessions (
|
||||
created TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS password_reset_tokens (
|
||||
id TEXT PRIMARY KEY,
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TEXT NOT NULL,
|
||||
used_at TEXT,
|
||||
created TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS email_verification_tokens (
|
||||
id TEXT PRIMARY KEY,
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
purpose TEXT NOT NULL CHECK (purpose IN ('primary', 'secondary')),
|
||||
email TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
expires_at TEXT NOT NULL,
|
||||
used_at TEXT,
|
||||
created TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_feature_restrictions (
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
feature_id TEXT NOT NULL REFERENCES features(id) ON DELETE CASCADE,
|
||||
@@ -230,6 +256,38 @@ CREATE TABLE IF NOT EXISTS identity_review_proposals (
|
||||
UNIQUE (profile_id, observed_label, entity_type)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS label_senses (
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
normalized_label TEXT NOT NULL,
|
||||
identity_hits INTEGER NOT NULL DEFAULT 0,
|
||||
non_identity_hits INTEGER NOT NULL DEFAULT 0,
|
||||
updated TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (profile_id, normalized_label)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS label_sense_cues (
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
normalized_label TEXT NOT NULL,
|
||||
cue TEXT NOT NULL,
|
||||
decision TEXT NOT NULL,
|
||||
hits INTEGER NOT NULL DEFAULT 1,
|
||||
excerpt TEXT NOT NULL DEFAULT '',
|
||||
updated TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
PRIMARY KEY (profile_id, normalized_label, cue)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS pending_mask_reviews (
|
||||
id TEXT PRIMARY KEY,
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
conversation_id TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
|
||||
user_message_id TEXT NOT NULL,
|
||||
payload_json TEXT NOT NULL DEFAULT '{}',
|
||||
created TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_pending_mask_reviews_conv
|
||||
ON pending_mask_reviews (profile_id, conversation_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS journal_days (
|
||||
id TEXT PRIMARY KEY,
|
||||
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
|
||||
@@ -455,6 +513,18 @@ CREATE TABLE IF NOT EXISTS writing_profile_versions (
|
||||
UNIQUE (profile_id, seq)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS llm_profiles (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
url TEXT NOT NULL DEFAULT '',
|
||||
model TEXT NOT NULL DEFAULT '',
|
||||
zdr INTEGER NOT NULL DEFAULT 1,
|
||||
no_train INTEGER NOT NULL DEFAULT 1,
|
||||
created TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS provider_settings (
|
||||
role TEXT PRIMARY KEY CHECK (role IN ('generate', 'detect')),
|
||||
name TEXT NOT NULL DEFAULT '',
|
||||
@@ -462,6 +532,7 @@ CREATE TABLE IF NOT EXISTS provider_settings (
|
||||
model TEXT NOT NULL DEFAULT '',
|
||||
zdr INTEGER NOT NULL DEFAULT 1,
|
||||
no_train INTEGER NOT NULL DEFAULT 1,
|
||||
profile_id TEXT,
|
||||
updated TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
@@ -482,6 +553,7 @@ CREATE TABLE IF NOT EXISTS generation_guidelines (
|
||||
label TEXT NOT NULL,
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
instruction TEXT NOT NULL,
|
||||
style_context_json TEXT NOT NULL DEFAULT '{}',
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('draft', 'active', 'archived')),
|
||||
revision INTEGER NOT NULL DEFAULT 1,
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Translate SQLite-oriented SQL so the same stores can run against PostgreSQL.
|
||||
|
||||
Windows without Docker still uses SQLite for the running app. Docker/Server and
|
||||
the test suite use PostgreSQL (`KANSHO_DB_BACKEND=postgres`). Identity, keys and
|
||||
journal bodies are not logged here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
_INSERT_OR_IGNORE = re.compile(r"INSERT\s+OR\s+IGNORE\s+INTO", re.IGNORECASE)
|
||||
_ROWID_COL = re.compile(r"\.rowid\b", re.IGNORECASE)
|
||||
_ON_CONFLICT_PAREN = re.compile(r"ON\s+CONFLICT\s*\(", re.IGNORECASE)
|
||||
_PRAGMA_TABLE = re.compile(
|
||||
r"^\s*PRAGMA\s+table_info\(\s*['\"]?(\w+)['\"]?\s*\)\s*;?\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_SQLITE_MASTER_TABLES = re.compile(
|
||||
r"^\s*SELECT\s+name\s+FROM\s+sqlite_master\s+WHERE\s+type\s*=\s*'table'\s*;?\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_SQLITE_MASTER_SQL = re.compile(
|
||||
r"^\s*SELECT\s+sql\s+FROM\s+sqlite_master\s+WHERE\s+type\s*=\s*'table'\s+AND\s+name\s*=\s*\?\s*;?\s*$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def use_postgres() -> bool:
|
||||
"""Decide the engine at connect time, not at import time.
|
||||
|
||||
Explicit KANSHO_DB_BACKEND wins. KANSHO_DB_PATH without an explicit postgres
|
||||
backend keeps the Windows local app on SQLite. Tests set postgres and DB_NAME
|
||||
kansho_test on the Dev instance, never kansho_dev.
|
||||
"""
|
||||
raw = (os.environ.get("KANSHO_DB_BACKEND") or "").strip().lower()
|
||||
if raw in {"sqlite", "sqlite3"}:
|
||||
return False
|
||||
if raw in {"postgres", "postgresql", "pg"}:
|
||||
return True
|
||||
if (os.environ.get("KANSHO_DB_PATH") or "").strip():
|
||||
return False
|
||||
url = (os.environ.get("DATABASE_URL") or "").strip().lower()
|
||||
if url.startswith("postgres"):
|
||||
return True
|
||||
if (os.environ.get("DB_HOST") or "").strip():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def postgres_connect_kwargs() -> dict:
|
||||
url = (os.environ.get("DATABASE_URL") or "").strip()
|
||||
if url:
|
||||
return {"conninfo": url}
|
||||
host = (os.environ.get("DB_HOST") or "postgres").strip() or "postgres"
|
||||
port = int((os.environ.get("DB_PORT") or "5432").strip() or "5432")
|
||||
dbname = (os.environ.get("DB_NAME") or "kansho").strip() or "kansho"
|
||||
user = (os.environ.get("DB_USER") or "kansho").strip() or "kansho"
|
||||
password = os.environ.get("DB_PASSWORD") or ""
|
||||
return {
|
||||
"host": host,
|
||||
"port": port,
|
||||
"dbname": dbname,
|
||||
"user": user,
|
||||
"password": password,
|
||||
}
|
||||
|
||||
|
||||
def sqlite_schema_to_postgres(sql: str) -> str:
|
||||
return sql.replace("datetime('now')", "CURRENT_TIMESTAMP::text")
|
||||
|
||||
|
||||
def replace_placeholders(sql: str) -> str:
|
||||
"""Replace SQLite `?` placeholders with psycopg `%s`, ignoring quoted text."""
|
||||
out: list[str] = []
|
||||
i = 0
|
||||
in_single = False
|
||||
in_double = False
|
||||
while i < len(sql):
|
||||
ch = sql[i]
|
||||
if ch == "'" and not in_double:
|
||||
if in_single and i + 1 < len(sql) and sql[i + 1] == "'":
|
||||
out.append("''")
|
||||
i += 2
|
||||
continue
|
||||
in_single = not in_single
|
||||
out.append(ch)
|
||||
i += 1
|
||||
continue
|
||||
if ch == '"' and not in_single:
|
||||
in_double = not in_double
|
||||
out.append(ch)
|
||||
i += 1
|
||||
continue
|
||||
if ch == "?" and not in_single and not in_double:
|
||||
out.append("%s")
|
||||
i += 1
|
||||
continue
|
||||
out.append(ch)
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def adapt_sql(sql: str) -> str:
|
||||
"""Make a SQLite-shaped statement runnable on PostgreSQL."""
|
||||
sql = sqlite_schema_to_postgres(sql)
|
||||
sql = _ROWID_COL.sub(".id", sql)
|
||||
sql = _ON_CONFLICT_PAREN.sub("ON CONFLICT (", sql)
|
||||
used_ignore = bool(_INSERT_OR_IGNORE.search(sql))
|
||||
sql = _INSERT_OR_IGNORE.sub("INSERT INTO", sql)
|
||||
if used_ignore and re.search(r"ON\s+CONFLICT", sql, re.IGNORECASE) is None:
|
||||
stripped = sql.rstrip()
|
||||
ended = stripped.endswith(";")
|
||||
if ended:
|
||||
stripped = stripped[:-1].rstrip()
|
||||
stripped = f"{stripped} ON CONFLICT DO NOTHING"
|
||||
sql = stripped + (";" if ended else "")
|
||||
return replace_placeholders(sql)
|
||||
|
||||
|
||||
def rewrite_catalog_sql(sql: str) -> tuple[str, tuple | None] | None:
|
||||
"""Rewrite SQLite catalog queries. Returns (sql, extra_params) or None."""
|
||||
match = _PRAGMA_TABLE.match(sql)
|
||||
if match:
|
||||
return (
|
||||
"""
|
||||
SELECT column_name AS name
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = %s
|
||||
ORDER BY ordinal_position
|
||||
""",
|
||||
(match.group(1).lower(),),
|
||||
)
|
||||
if _SQLITE_MASTER_TABLES.match(sql):
|
||||
return (
|
||||
"""
|
||||
SELECT tablename AS name
|
||||
FROM pg_catalog.pg_tables
|
||||
WHERE schemaname = 'public'
|
||||
""",
|
||||
None,
|
||||
)
|
||||
if _SQLITE_MASTER_SQL.match(sql):
|
||||
return ("SELECT NULL AS sql WHERE FALSE", None)
|
||||
return None
|
||||
|
||||
|
||||
def split_sql(script: str) -> list[str]:
|
||||
"""Split a SQL script into statements, respecting quotes."""
|
||||
statements: list[str] = []
|
||||
buf: list[str] = []
|
||||
in_single = False
|
||||
in_double = False
|
||||
i = 0
|
||||
while i < len(script):
|
||||
ch = script[i]
|
||||
if ch == "'" and not in_double:
|
||||
if in_single and i + 1 < len(script) and script[i + 1] == "'":
|
||||
buf.append("''")
|
||||
i += 2
|
||||
continue
|
||||
in_single = not in_single
|
||||
buf.append(ch)
|
||||
i += 1
|
||||
continue
|
||||
if ch == '"' and not in_single:
|
||||
in_double = not in_double
|
||||
buf.append(ch)
|
||||
i += 1
|
||||
continue
|
||||
if ch == ";" and not in_single and not in_double:
|
||||
stmt = "".join(buf).strip()
|
||||
if stmt:
|
||||
statements.append(stmt)
|
||||
buf = []
|
||||
i += 1
|
||||
continue
|
||||
buf.append(ch)
|
||||
i += 1
|
||||
tail = "".join(buf).strip()
|
||||
if tail:
|
||||
statements.append(tail)
|
||||
return statements
|
||||
@@ -0,0 +1,250 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot SQLite → PostgreSQL copy for the laptop/home journal instance.
|
||||
|
||||
Probe on a copy, never on the only backup. Does not send data to providers.
|
||||
Media files are copied separately into the destination media root.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from sql_compat import postgres_connect_kwargs
|
||||
|
||||
SCHEMA_PATH = Path(__file__).resolve().parent / "schema.sql"
|
||||
DEFAULT_SQLITE = Path(__file__).resolve().parent / "data" / "kansho.sqlite"
|
||||
DEFAULT_MEDIA = Path(__file__).resolve().parent / "data" / "media"
|
||||
|
||||
# Parent tables first — matches schema.sql CREATE order.
|
||||
TABLES = [
|
||||
"schema_migrations",
|
||||
"tiers",
|
||||
"features",
|
||||
"tier_limits",
|
||||
"profiles",
|
||||
"sessions",
|
||||
"user_feature_restrictions",
|
||||
"user_feature_usage",
|
||||
"ai_prompts",
|
||||
"usage_sessions",
|
||||
"conversations",
|
||||
"messages",
|
||||
"threads",
|
||||
"conversation_threads",
|
||||
"spaces",
|
||||
"thread_spaces",
|
||||
"derived_records",
|
||||
"handoffs",
|
||||
"external_refs",
|
||||
"re_grounding_events",
|
||||
"identity_mappings",
|
||||
"identity_review_proposals",
|
||||
"label_senses",
|
||||
"label_sense_cues",
|
||||
"pending_mask_reviews",
|
||||
"journal_days",
|
||||
"journal_drafts",
|
||||
"journal_entries",
|
||||
"journal_entry_versions",
|
||||
"journal_draft_source_refs",
|
||||
"journal_entry_version_source_refs",
|
||||
"media_assets",
|
||||
"writing_profiles",
|
||||
"writing_profile_sources",
|
||||
"writing_profile_facets",
|
||||
"writing_profile_traits",
|
||||
"writing_profile_trait_refs",
|
||||
"writing_profile_suggestions",
|
||||
"interaction_profiles",
|
||||
"interaction_preferences",
|
||||
"interaction_suggestions",
|
||||
"writing_profile_evidence",
|
||||
"writing_profile_reviews",
|
||||
"writing_profile_versions",
|
||||
"llm_profiles",
|
||||
"provider_settings",
|
||||
"journal_generation_selection",
|
||||
"generation_guidelines",
|
||||
"app_settings",
|
||||
"debug_runs",
|
||||
]
|
||||
|
||||
|
||||
def _sqlite_path() -> Path:
|
||||
env = (os.environ.get("KANSHO_DB_PATH") or "").strip()
|
||||
if env:
|
||||
return Path(env)
|
||||
data_dir = (os.environ.get("KANSHO_DATA_DIR") or "").strip()
|
||||
if data_dir:
|
||||
return Path(data_dir) / "kansho.sqlite"
|
||||
return DEFAULT_SQLITE
|
||||
|
||||
|
||||
def _media_root() -> Path:
|
||||
env = (os.environ.get("KANSHO_MEDIA_ROOT") or "").strip()
|
||||
if env:
|
||||
return Path(env)
|
||||
data_dir = (os.environ.get("KANSHO_DATA_DIR") or "").strip()
|
||||
if data_dir:
|
||||
return Path(data_dir) / "media"
|
||||
return DEFAULT_MEDIA
|
||||
|
||||
|
||||
def _connect_pg():
|
||||
import psycopg
|
||||
|
||||
kwargs = postgres_connect_kwargs()
|
||||
if "conninfo" in kwargs:
|
||||
return psycopg.connect(kwargs["conninfo"])
|
||||
return psycopg.connect(**kwargs)
|
||||
|
||||
|
||||
def _pg_columns(conn, table: str) -> list[str]:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT column_name
|
||||
FROM information_schema.columns
|
||||
WHERE table_schema = 'public' AND table_name = %s
|
||||
ORDER BY ordinal_position
|
||||
""",
|
||||
(table,),
|
||||
).fetchall()
|
||||
return [row[0] for row in rows]
|
||||
|
||||
|
||||
def _sqlite_rows(sqlite_path: Path, table: str) -> list[dict]:
|
||||
conn = sqlite3.connect(str(sqlite_path))
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
rows = conn.execute(f"SELECT * FROM {table}").fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
except sqlite3.OperationalError:
|
||||
return []
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _copy_media(src: Path, dest: Path) -> int:
|
||||
if not src.is_dir():
|
||||
print(f"No media directory at {src}")
|
||||
return 0
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
count = 0
|
||||
for path in src.rglob("*"):
|
||||
if not path.is_file():
|
||||
continue
|
||||
relative = path.relative_to(src)
|
||||
target = dest / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(path, target)
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def migrate(sqlite_path: Path, media_src: Path, media_dest: Path, replace: bool) -> dict[str, tuple[int, int]]:
|
||||
if not sqlite_path.is_file():
|
||||
raise SystemExit(f"SQLite not found: {sqlite_path}")
|
||||
|
||||
pg = _connect_pg()
|
||||
stats: dict[str, tuple[int, int]] = {}
|
||||
try:
|
||||
existing = pg.execute("SELECT COUNT(*) FROM profiles").fetchone()[0]
|
||||
seeds = pg.execute("SELECT COUNT(*) FROM tiers").fetchone()[0]
|
||||
if existing and not replace:
|
||||
raise SystemExit(
|
||||
f"PostgreSQL already has {existing} profiles. Pass --replace after a probe copy, not on the only backup."
|
||||
)
|
||||
if seeds and not replace:
|
||||
raise SystemExit(
|
||||
"PostgreSQL already has platform seeds from startup. "
|
||||
"Pass --replace to load a SQLite snapshot onto this instance (no user profiles yet is OK)."
|
||||
)
|
||||
if replace:
|
||||
print(f"Replacing Postgres snapshot (profiles={existing}, seed_tiers={seeds})")
|
||||
for table in reversed(TABLES):
|
||||
pg.execute(f"TRUNCATE TABLE {table} CASCADE")
|
||||
|
||||
for table in TABLES:
|
||||
rows = _sqlite_rows(sqlite_path, table)
|
||||
columns = _pg_columns(pg, table)
|
||||
if not columns:
|
||||
print(f" skip {table} (missing in Postgres schema)")
|
||||
stats[table] = (len(rows), 0)
|
||||
continue
|
||||
if not rows:
|
||||
print(f" {table}: empty")
|
||||
stats[table] = (0, 0)
|
||||
continue
|
||||
usable = [col for col in columns if col in rows[0]]
|
||||
placeholders = ", ".join(["%s"] * len(usable))
|
||||
col_sql = ", ".join(usable)
|
||||
sql = f"INSERT INTO {table} ({col_sql}) VALUES ({placeholders})"
|
||||
values = [tuple(row.get(col) for col in usable) for row in rows]
|
||||
with pg.cursor() as cur:
|
||||
cur.executemany(sql, values)
|
||||
count = pg.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
|
||||
print(f" {table}: {len(rows)} → {count}")
|
||||
stats[table] = (len(rows), int(count))
|
||||
pg.execute(
|
||||
"""
|
||||
UPDATE profiles
|
||||
SET email_verified_at = COALESCE(NULLIF(created, ''), CURRENT_TIMESTAMP::text)
|
||||
WHERE email_verified_at IS NULL OR email_verified_at = ''
|
||||
"""
|
||||
)
|
||||
pg.execute(
|
||||
"INSERT INTO schema_migrations (id) VALUES (%s) ON CONFLICT (id) DO NOTHING",
|
||||
("022_postgres_runtime_baseline",),
|
||||
)
|
||||
pg.commit()
|
||||
except Exception:
|
||||
pg.rollback()
|
||||
raise
|
||||
finally:
|
||||
pg.close()
|
||||
|
||||
copied = _copy_media(media_src, media_dest)
|
||||
print(f"Media files copied: {copied} → {media_dest}")
|
||||
return stats
|
||||
|
||||
|
||||
def verify(stats: dict[str, tuple[int, int]]) -> None:
|
||||
failed = False
|
||||
print("\nVerification")
|
||||
for table, (src, dest) in stats.items():
|
||||
if table == "schema_migrations" and dest == src + 1:
|
||||
print(f" ok {table:36} sqlite={src:5} postgres={dest:5} (incl. 022)")
|
||||
continue
|
||||
mark = "ok" if src == dest else "MISMATCH"
|
||||
if src != dest:
|
||||
failed = True
|
||||
print(f" {mark:8} {table:36} sqlite={src:5} postgres={dest:5}")
|
||||
if failed:
|
||||
raise SystemExit("Row counts do not match")
|
||||
print("Row counts match")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Copy Kanshō SQLite data into PostgreSQL")
|
||||
parser.add_argument("--sqlite", type=Path, default=_sqlite_path())
|
||||
parser.add_argument("--media-src", type=Path, default=_media_root())
|
||||
parser.add_argument("--media-dest", type=Path, default=Path(os.environ.get("KANSHO_MEDIA_DEST") or "/app/data/media"))
|
||||
parser.add_argument("--confirm", action="store_true", help="Required. Refuse a silent copy.")
|
||||
parser.add_argument("--replace", action="store_true", help="Truncate Postgres tables first")
|
||||
args = parser.parse_args()
|
||||
if not args.confirm:
|
||||
raise SystemExit("Refusing to copy personal data without --confirm")
|
||||
print(f"SQLite source: {args.sqlite}")
|
||||
print(f"Media source: {args.media_src}")
|
||||
print(f"Media dest: {args.media_dest}")
|
||||
stats = migrate(args.sqlite, args.media_src, args.media_dest, args.replace)
|
||||
verify(stats)
|
||||
print("Import complete. Check entry/message counts and one media GET before Prod.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
echo "=== Kanshō backend startup ==="
|
||||
python /app/db_init.py
|
||||
echo "=== starting uvicorn ==="
|
||||
exec uvicorn main:app --host 0.0.0.0 --port 8000
|
||||
@@ -0,0 +1,100 @@
|
||||
"""pytest runner for the existing test_*.py scripts.
|
||||
|
||||
Each file stays one case (`main()`) until it is split into native pytest
|
||||
functions. Schema is loaded once per session; each integration file only
|
||||
truncates data so kansho_dev is never the target and CI does not reload
|
||||
schema.sql twenty times.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from tests.harness import ( # noqa: E402
|
||||
apply_module_env,
|
||||
is_postgres_test_database,
|
||||
prepare_test_env,
|
||||
reset_postgres_data,
|
||||
reset_postgres_schema,
|
||||
)
|
||||
|
||||
UNIT_MODULES = frozenset(
|
||||
{
|
||||
"test_sql_compat",
|
||||
"test_local_backup",
|
||||
"test_provenance",
|
||||
"test_model_catalog",
|
||||
"test_local_url",
|
||||
"test_privacy_detect_eval",
|
||||
"test_journal_shape",
|
||||
"test_journal_body",
|
||||
"test_writing_profile",
|
||||
"test_gliner_client",
|
||||
"test_detect_pipeline",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def pytest_configure(config: pytest.Config) -> None:
|
||||
prepare_test_env()
|
||||
|
||||
|
||||
def pytest_collect_file(file_path: Path, parent: pytest.Collector):
|
||||
if file_path.suffix == ".py" and file_path.name.startswith("test_"):
|
||||
return KanshoScriptModule.from_parent(parent, path=file_path)
|
||||
return None
|
||||
|
||||
|
||||
def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
|
||||
for item in items:
|
||||
stem = Path(str(item.path)).stem
|
||||
marker = pytest.mark.unit if stem in UNIT_MODULES else pytest.mark.integration
|
||||
item.add_marker(marker)
|
||||
|
||||
|
||||
class KanshoScriptModule(pytest.Module):
|
||||
def collect(self):
|
||||
module = self.obj
|
||||
main = getattr(module, "main", None)
|
||||
if main is None or not callable(main):
|
||||
pytest.fail(f"{self.path.name} has no callable main()")
|
||||
yield pytest.Function.from_parent(self, name="test_main", callobj=main)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def _session_postgres():
|
||||
if not is_postgres_test_database():
|
||||
pytest.skip(
|
||||
"integration requires KANSHO_DB_BACKEND=postgres and DB_NAME ending _test "
|
||||
"(Gitea: kansho_test on the Dev Postgres, never kansho_dev)"
|
||||
)
|
||||
reset_postgres_schema()
|
||||
from db import init_db
|
||||
|
||||
init_db()
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def _module_backend(request: pytest.FixtureRequest):
|
||||
source = Path(str(request.path))
|
||||
stem = source.stem
|
||||
saved = dict(os.environ)
|
||||
try:
|
||||
apply_module_env(source)
|
||||
if stem in UNIT_MODULES:
|
||||
yield
|
||||
return
|
||||
request.getfixturevalue("_session_postgres")
|
||||
reset_postgres_data()
|
||||
yield
|
||||
finally:
|
||||
os.environ.clear()
|
||||
os.environ.update(saved)
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Postgres test engine on the existing Dev instance.
|
||||
|
||||
Two Compose Postgres instances exist: Dev and Prod. Tests use the Dev
|
||||
instance, database `kansho_test` beside `kansho_dev`. That is not a third
|
||||
server. The suite drops and recreates `public` on the test database only,
|
||||
so personal Dev/Prod journals are not wiped.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
LIVE_DB_NAMES = frozenset(
|
||||
{
|
||||
"kansho",
|
||||
"kansho_dev",
|
||||
"postgres",
|
||||
"template0",
|
||||
"template1",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _backend() -> str:
|
||||
return (os.environ.get("KANSHO_DB_BACKEND") or "").strip().lower()
|
||||
|
||||
|
||||
def _db_name() -> str:
|
||||
return (os.environ.get("DB_NAME") or "").strip()
|
||||
|
||||
|
||||
def is_postgres_test_database() -> bool:
|
||||
if _backend() not in {"postgres", "postgresql", "pg"}:
|
||||
return False
|
||||
name = _db_name().lower()
|
||||
if not name or name in LIVE_DB_NAMES:
|
||||
return False
|
||||
return name.endswith("_test")
|
||||
|
||||
|
||||
def prepare_test_env() -> None:
|
||||
"""Fail-closed defaults. Do not keep Compose provider keys or leftover fakes."""
|
||||
os.environ["KANSHO_PROVIDER_KEY"] = ""
|
||||
os.environ["KANSHO_DETECT_PROVIDER_KEY"] = ""
|
||||
os.environ.pop("KANSHO_DB_PATH", None)
|
||||
os.environ.pop("KANSHO_FAKE_PROVIDER", None)
|
||||
os.environ.pop("KANSHO_FAKE_DETECT", None)
|
||||
os.environ.pop("KANSHO_ALLOW_REMOTE_DETECT", None)
|
||||
|
||||
|
||||
def apply_module_env(source) -> None:
|
||||
"""Restore per-file env so pytest does not leak fakes/keys across scripts."""
|
||||
from pathlib import Path
|
||||
|
||||
prepare_test_env()
|
||||
text = Path(source).read_text(encoding="utf-8")
|
||||
if 'os.environ["KANSHO_FAKE_PROVIDER"] = "1"' in text or "os.environ['KANSHO_FAKE_PROVIDER'] = '1'" in text:
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
if (
|
||||
'os.environ["KANSHO_FAKE_DETECT"] = "1"' in text
|
||||
or "os.environ['KANSHO_FAKE_DETECT'] = '1'" in text
|
||||
or 'os.environ.setdefault("KANSHO_FAKE_DETECT", "1")' in text
|
||||
):
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
|
||||
|
||||
def _require_test_database() -> None:
|
||||
if is_postgres_test_database():
|
||||
return
|
||||
backend = _backend()
|
||||
if backend not in {"postgres", "postgresql", "pg"}:
|
||||
raise SystemExit(
|
||||
"Backend-Tests laufen gegen PostgreSQL (KANSHO_DB_BACKEND=postgres), "
|
||||
"dieselbe Engine wie Dev und Prod. SQLite-Testdateien sind abgelöst. "
|
||||
"Gitea nutzt auf der Dev-Postgres die Datenbank kansho_test "
|
||||
"(neben kansho_dev, keine dritte Instanz)."
|
||||
)
|
||||
name = _db_name().lower()
|
||||
if not name:
|
||||
raise SystemExit(
|
||||
"DB_NAME fehlt. Tests nutzen auf der Dev-Postgres die Datenbank kansho_test, "
|
||||
"nicht kansho_dev."
|
||||
)
|
||||
raise SystemExit(
|
||||
f"DB_NAME={_db_name()!r} ist für Tests gesperrt. "
|
||||
"Die Suite setzt das Schema zurück und darf daher nicht kansho oder kansho_dev treffen."
|
||||
)
|
||||
|
||||
|
||||
def reset_postgres_schema() -> None:
|
||||
import psycopg
|
||||
|
||||
from db_init import mark_schema_dirty
|
||||
from sql_compat import postgres_connect_kwargs
|
||||
|
||||
kwargs = postgres_connect_kwargs()
|
||||
if "conninfo" in kwargs:
|
||||
conn = psycopg.connect(kwargs["conninfo"], autocommit=True)
|
||||
else:
|
||||
conn = psycopg.connect(autocommit=True, **kwargs)
|
||||
try:
|
||||
conn.execute("DROP SCHEMA IF EXISTS public CASCADE")
|
||||
conn.execute("CREATE SCHEMA public")
|
||||
conn.execute("GRANT ALL ON SCHEMA public TO PUBLIC")
|
||||
conn.execute("GRANT ALL ON SCHEMA public TO CURRENT_USER")
|
||||
finally:
|
||||
conn.close()
|
||||
mark_schema_dirty()
|
||||
|
||||
|
||||
def reset_postgres_data() -> None:
|
||||
"""Clear rows on kansho_test without reloading schema.sql."""
|
||||
import psycopg
|
||||
|
||||
from sql_compat import postgres_connect_kwargs
|
||||
|
||||
kwargs = postgres_connect_kwargs()
|
||||
if "conninfo" in kwargs:
|
||||
conn = psycopg.connect(kwargs["conninfo"], autocommit=True)
|
||||
else:
|
||||
conn = psycopg.connect(autocommit=True, **kwargs)
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT tablename FROM pg_tables
|
||||
WHERE schemaname = 'public' AND tablename <> 'schema_migrations'
|
||||
"""
|
||||
).fetchall()
|
||||
names = [row[0] for row in rows]
|
||||
if names:
|
||||
joined = ", ".join('"' + name.replace('"', '""') + '"' for name in names)
|
||||
conn.execute(f"TRUNCATE TABLE {joined} RESTART IDENTITY CASCADE")
|
||||
finally:
|
||||
conn.close()
|
||||
from db import refresh_runtime_seed
|
||||
|
||||
refresh_runtime_seed()
|
||||
|
||||
|
||||
def configure_test_engine() -> None:
|
||||
"""Reset kansho_test. pytest uses the fixture in tests/conftest.py instead."""
|
||||
prepare_test_env()
|
||||
_require_test_database()
|
||||
try:
|
||||
reset_postgres_schema()
|
||||
except Exception as exc: # noqa: BLE001 — fail before the suite touches a live DB
|
||||
print(f"Postgres-Testschema konnte nicht zurückgesetzt werden: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1) from exc
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Account identifiers, reset links, and address verification."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_PROVIDER_KEY"] = ""
|
||||
os.environ["KANSHO_DETECT_PROVIDER_KEY"] = ""
|
||||
os.environ["KANSHO_FAKE_MAIL"] = "1"
|
||||
os.environ["KANSHO_ENV"] = "test"
|
||||
os.environ["APP_URL"] = "http://localhost:5188"
|
||||
if (os.environ.get("KANSHO_DB_BACKEND") or "").strip().lower() not in {"postgres", "postgresql", "pg"}:
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.mkdtemp(prefix="kansho-account-")) / "account.sqlite")
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
|
||||
from db import get_db
|
||||
from mailer import OUTBOX, clear_outbox
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
def auth_header(token: str) -> dict:
|
||||
return {"X-Auth-Token": token}
|
||||
|
||||
|
||||
def mail_tokens() -> list[str]:
|
||||
found: list[str] = []
|
||||
for item in OUTBOX:
|
||||
found.extend(re.findall(r"token=([A-Za-z0-9_\-]+)", item["body"]))
|
||||
return found
|
||||
|
||||
|
||||
def main() -> None:
|
||||
clear_outbox()
|
||||
with TestClient(app) as client:
|
||||
setup = client.post(
|
||||
"/api/auth/setup",
|
||||
json={"email": "lars@example.test", "name": "Lars", "password": "test-pass"},
|
||||
)
|
||||
expect(setup.status_code == 200, f"setup {setup.text}")
|
||||
token = setup.json()["token"]
|
||||
headers = auth_header(token)
|
||||
verify_tokens = mail_tokens()
|
||||
expect(len(verify_tokens) == 1, "setup sends one verification link")
|
||||
verified = client.post("/api/auth/verify-email", json={"token": verify_tokens[0]})
|
||||
expect(verified.status_code == 200 and verified.json()["email_verified"] is True, "admin email verified")
|
||||
clear_outbox()
|
||||
|
||||
me = client.get("/api/auth/me", headers=headers)
|
||||
expect(me.status_code == 200, "session survives initial verification")
|
||||
admin_id = me.json()["id"]
|
||||
|
||||
blocked = client.patch(
|
||||
f"/api/users/{admin_id}",
|
||||
headers=headers,
|
||||
json={"status": "disabled"},
|
||||
)
|
||||
expect(blocked.status_code == 400, f"last admin cannot be disabled {blocked.text}")
|
||||
|
||||
created = client.post(
|
||||
"/api/users",
|
||||
headers=headers,
|
||||
json={
|
||||
"email": "ute@example.test",
|
||||
"name": "Ute",
|
||||
"password": "user-pass",
|
||||
"role": "user",
|
||||
"username": "ute.user",
|
||||
},
|
||||
)
|
||||
expect(created.status_code == 200 and created.json()["username"] == "ute.user", f"create with username {created.text}")
|
||||
expect(created.json()["email_verified"] is False, "new primary email starts unverified")
|
||||
clear_outbox()
|
||||
|
||||
by_name = client.post("/api/auth/login", json={"email": "Ute.User", "password": "user-pass"})
|
||||
expect(by_name.status_code == 200, f"login by username {by_name.text}")
|
||||
|
||||
unknown = client.post("/api/auth/forgot-password", json={"email": "missing@example.test"})
|
||||
known = client.post("/api/auth/forgot-password", json={"email": "lars@example.test"})
|
||||
expect(unknown.status_code == 200 and known.status_code == 200, "forgot password always 200")
|
||||
expect(unknown.json() == known.json(), "forgot password does not reveal whether the account exists")
|
||||
expect(len(mail_tokens()) == 1, "reset mail only for the verified account")
|
||||
reset_token = mail_tokens()[0]
|
||||
clear_outbox()
|
||||
|
||||
changed = client.post(
|
||||
"/api/auth/reset-password",
|
||||
json={"token": reset_token, "password": "new-pass"},
|
||||
)
|
||||
expect(changed.status_code == 200, f"reset password {changed.text}")
|
||||
stale = client.get("/api/auth/me", headers=headers)
|
||||
expect(stale.status_code == 401, "reset deletes sessions")
|
||||
old_password = client.post("/api/auth/login", json={"email": "lars@example.test", "password": "test-pass"})
|
||||
expect(old_password.status_code == 401, "old password rejected")
|
||||
relogin = client.post("/api/auth/login", json={"email": "lars@example.test", "password": "new-pass"})
|
||||
expect(relogin.status_code == 200, "login with reset password")
|
||||
headers = auth_header(relogin.json()["token"])
|
||||
again = client.post("/api/auth/reset-password", json={"token": reset_token, "password": "other-pass"})
|
||||
expect(again.status_code == 400, "reset token is single use")
|
||||
|
||||
client.post("/api/auth/forgot-password", json={"email": "lars@example.test"})
|
||||
expired_token = mail_tokens()[0]
|
||||
clear_outbox()
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"UPDATE password_reset_tokens SET expires_at = ? WHERE token_hash IS NOT NULL",
|
||||
("2000-01-01 00:00:00",),
|
||||
)
|
||||
expired = client.post(
|
||||
"/api/auth/reset-password",
|
||||
json={"token": expired_token, "password": "newer-pass"},
|
||||
)
|
||||
expect(expired.status_code == 400, "expired reset token is rejected")
|
||||
|
||||
clear_outbox()
|
||||
renamed = client.patch(
|
||||
"/api/users/me",
|
||||
headers=headers,
|
||||
json={"email": "lars.new@example.test"},
|
||||
)
|
||||
expect(renamed.status_code == 200, f"email change queued {renamed.text}")
|
||||
expect(renamed.json()["email"] == "lars@example.test", "login email unchanged until verification")
|
||||
expect(renamed.json()["pending_email"] == "lars.new@example.test", "pending email stored")
|
||||
still = client.post("/api/auth/login", json={"email": "lars@example.test", "password": "new-pass"})
|
||||
expect(still.status_code == 200, "old email still logs in")
|
||||
confirm = client.post("/api/auth/verify-email", json={"token": mail_tokens()[0]})
|
||||
expect(confirm.status_code == 200 and confirm.json()["email"] == "lars.new@example.test", "verified address becomes login")
|
||||
gone = client.post("/api/auth/login", json={"email": "lars@example.test", "password": "new-pass"})
|
||||
expect(gone.status_code == 401, "previous email stops working")
|
||||
moved = client.post("/api/auth/login", json={"email": "lars.new@example.test", "password": "new-pass"})
|
||||
expect(moved.status_code == 200, "new email logs in")
|
||||
headers = auth_header(moved.json()["token"])
|
||||
|
||||
clear_outbox()
|
||||
other = client.post(
|
||||
f"/api/users/{created.json()['id']}/password-reset",
|
||||
headers=headers,
|
||||
)
|
||||
expect(other.status_code == 200, f"admin reset for another user {other.text}")
|
||||
expect(len(mail_tokens()) == 1, "admin reset sends one link")
|
||||
self_reset = client.post(f"/api/users/{moved.json()['profile_id']}/password-reset", headers=headers)
|
||||
expect(self_reset.status_code == 400, "admin cannot reset the own account via the admin endpoint")
|
||||
|
||||
os.environ.pop("KANSHO_FAKE_MAIL", None)
|
||||
os.environ.pop("SMTP_HOST", None)
|
||||
os.environ.pop("SMTP_FROM", None)
|
||||
os.environ["KANSHO_ENV"] = "test"
|
||||
failed = client.post(
|
||||
f"/api/users/{created.json()['id']}/password-reset",
|
||||
headers=headers,
|
||||
)
|
||||
expect(failed.status_code == 503, f"admin reset without SMTP fails closed {failed.text}")
|
||||
|
||||
secondary_login = client.post(
|
||||
"/api/auth/login",
|
||||
json={"email": "ute.second@example.test", "password": "user-pass"},
|
||||
)
|
||||
expect(secondary_login.status_code == 401, "unknown address is not a login")
|
||||
|
||||
print("Account access tests passed.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -11,10 +11,8 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-arch-correction-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from db import get_db, migrate_journal_source_refs
|
||||
|
||||
@@ -11,11 +11,9 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
REPO = ROOT.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-debug-persist-test.sqlite")
|
||||
os.environ["KANSHO_MEDIA_ROOT"] = str(Path(tempfile.gettempdir()) / "kansho-debug-persist-media")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
Path(os.environ["KANSHO_MEDIA_ROOT"]).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
"""Bounded detect-contract retry, acyclic diagnostics, persist must not hide EngineError.
|
||||
|
||||
Run from backend/: python tests/test_detect_contract_retry.py
|
||||
Fake detect/provider only. No live calls.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from debug_store import persist_engine_error, sanitize
|
||||
from engine import EngineError
|
||||
from entity_detect import (
|
||||
DetectError,
|
||||
detect_personal_egress,
|
||||
install_test_detect_failure,
|
||||
install_test_detect_script,
|
||||
reset_detect_test_hooks,
|
||||
split_detect_chunks,
|
||||
validate_detected_entity,
|
||||
)
|
||||
from journal_generate import _compose_journal_trace, _stage_trace
|
||||
from main import app
|
||||
from privacy_gateway import GatewayRequest, PrivacyGatewayError, complete, reset_debug
|
||||
from providers import ChatResult
|
||||
|
||||
|
||||
USAGE_A = {"prompt_tokens": 10, "completion_tokens": 3, "total_tokens": 13, "cost": 0.001}
|
||||
USAGE_B = {"prompt_tokens": 8, "completion_tokens": 2, "total_tokens": 10, "cost": 0.0005}
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
def header(token: str) -> dict:
|
||||
return {"X-Auth-Token": token}
|
||||
|
||||
|
||||
def _ids(obj, stack=None) -> bool:
|
||||
"""True if obj is acyclic."""
|
||||
if not isinstance(obj, (dict, list, tuple)):
|
||||
return True
|
||||
stack = stack or set()
|
||||
ident = id(obj)
|
||||
if ident in stack:
|
||||
return False
|
||||
stack.add(ident)
|
||||
try:
|
||||
items = obj.values() if isinstance(obj, dict) else obj
|
||||
return all(_ids(item, stack) for item in items)
|
||||
finally:
|
||||
stack.discard(ident)
|
||||
|
||||
|
||||
def _budget_is_not_diagnostics(payload: dict) -> bool:
|
||||
diag = payload.get("diagnostics") if isinstance(payload.get("diagnostics"), dict) else payload
|
||||
trace = diag.get("trace") if isinstance(diag.get("trace"), dict) else {}
|
||||
budget = trace.get("budget")
|
||||
if budget is diag:
|
||||
return False
|
||||
for stage in trace.get("stages") or []:
|
||||
if isinstance(stage, dict) and stage.get("budget") is diag:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _run(profile_id: str, rendered: str, purpose: str = "dialogue_turn"):
|
||||
return complete(
|
||||
GatewayRequest(
|
||||
prompt_id="detect-retry-test",
|
||||
purpose=purpose,
|
||||
data_class="B",
|
||||
profile_id=profile_id,
|
||||
payload={"rendered": rendered, "source_text": rendered},
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _chat(entities: list[dict], usage: dict) -> ChatResult:
|
||||
return ChatResult(
|
||||
content=json.dumps({"entities": entities}),
|
||||
model="fake-detect",
|
||||
usage=usage,
|
||||
finish_reason="stop",
|
||||
)
|
||||
|
||||
|
||||
def _invalid_type():
|
||||
return [{"start": 0, "end": 1, "text": "x", "entity_type": "HUMAN"}]
|
||||
|
||||
|
||||
def _extra_field():
|
||||
return [{"start": 0, "end": 1, "text": "x", "entity_type": "PERSON", "score": 0.9}]
|
||||
|
||||
|
||||
def _missing_field():
|
||||
return [{"start": 0, "text": "x", "entity_type": "PERSON"}]
|
||||
|
||||
|
||||
def _bad_offset(chunk_text: str):
|
||||
return [{"start": 0, "end": 5, "text": "ZZZXQ", "entity_type": "PERSON"}]
|
||||
|
||||
|
||||
def open_space_day(client, headers, title="Alltag", date="2026-08-29"):
|
||||
space = client.post("/api/journal/spaces", headers=headers, json={"title": title})
|
||||
expect(space.status_code == 200, f"create space {space.status_code}")
|
||||
day = client.post(
|
||||
f"/api/journal/spaces/{space.json()['id']}/days",
|
||||
headers=headers,
|
||||
json={"calendar_date": date},
|
||||
)
|
||||
expect(day.status_code == 200, f"open day {day.status_code}")
|
||||
return space.json(), day.json()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
reset_debug()
|
||||
reset_detect_test_hooks()
|
||||
|
||||
sample = "Ich traf Anna."
|
||||
try:
|
||||
validate_detected_entity(
|
||||
{"start": 0, "end": 4, "text": "Anna", "entity_type": "HUMAN"},
|
||||
sample,
|
||||
0,
|
||||
)
|
||||
typed = False
|
||||
except DetectError as exc:
|
||||
typed = exc.code == "detect_invalid_output"
|
||||
expect((exc.diagnostics or {}).get("invalid_entity_type") == "HUMAN", "unknown type is recorded without the span text")
|
||||
expect((exc.diagnostics or {}).get("contract_violation") == "unknown_entity_type", "unknown type has a violation category")
|
||||
expect("Anna" not in json.dumps(exc.diagnostics or {}), "span plaintext is not stored on the type violation")
|
||||
expect(typed, "unknown entity_type is a contract error")
|
||||
|
||||
cyclic = {}
|
||||
nested = {"budget": cyclic, "stages": [cyclic]}
|
||||
cyclic["trace"] = nested
|
||||
cyclic["local_label"] = "secret-name"
|
||||
cleaned = sanitize(cyclic)
|
||||
expect(cleaned is not None, "cyclic sanitize returns a value")
|
||||
expect(_ids(cleaned), "sanitized cyclic input is acyclic")
|
||||
expect("local_label" not in json.dumps(cleaned), "sanitize still drops mapping labels")
|
||||
expect(json.dumps(cleaned, default=str), "sanitized cyclic input is JSON-serializable")
|
||||
|
||||
with TestClient(app) as client:
|
||||
setup = client.post(
|
||||
"/api/auth/setup",
|
||||
json={"email": "lars@example.test", "name": "Lars", "password": "test-pass"},
|
||||
)
|
||||
expect(setup.status_code == 200, "setup")
|
||||
token = setup.json()["token"]
|
||||
headers = header(token)
|
||||
profile_id = setup.json()["profile_id"]
|
||||
|
||||
calls = []
|
||||
|
||||
def retry_then_ok(attempt, chunk_index, chunk_text, offset, schema_retry=False):
|
||||
usage = USAGE_A if attempt == 1 else USAGE_B
|
||||
calls.append((attempt, chunk_index, schema_retry))
|
||||
if attempt == 1:
|
||||
return _chat(_invalid_type(), usage)
|
||||
return _chat([], usage)
|
||||
|
||||
long_body = (
|
||||
"WRITING_PROFILE\nkurze trockene Saetze. " * 12
|
||||
+ "STYLE_EXAMPLES\nDer Abend blieb ruhig. " * 12
|
||||
+ "CURRENT_DAY_SOURCES\nHeute der Markt, danach der Hafen. "
|
||||
)
|
||||
with patch("entity_detect.DETECT_CHUNK_CHARS", 90), patch("entity_detect.DETECT_CHUNK_OVERLAP", 12):
|
||||
chunks = split_detect_chunks(long_body, chunk_chars=90, overlap=12)
|
||||
expect(len(chunks) >= 2, "long profile+examples text is chunked")
|
||||
install_test_detect_script(retry_then_ok)
|
||||
try:
|
||||
outcome = detect_personal_egress(profile_id, long_body)
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
attempts = {item[0] for item in calls}
|
||||
expect(attempts == {1, 2}, "invalid first pass starts a second full pass")
|
||||
first_chunks = [item[1] for item in calls if item[0] == 1]
|
||||
second_chunks = [item[1] for item in calls if item[0] == 2]
|
||||
expect(second_chunks == list(range(len(chunks))), "second pass re-checks every chunk")
|
||||
expect(first_chunks == [0], "failed first pass stops at the invalid chunk and discards partials")
|
||||
expect(any(item[2] for item in calls if item[0] == 2), "second pass is marked as schema retry")
|
||||
expect(not any(item[2] for item in calls if item[0] == 1), "first pass has no schema retry hint")
|
||||
expect(outcome.stats.detect_partial_discarded is True, "partial first-pass spans are discarded")
|
||||
expect(outcome.stats.detect_passes == 2, "successful retry records two passes")
|
||||
expect(outcome.stats.detect_calls == len(calls), "detect calls sum both passes")
|
||||
expect(outcome.stats.cost_known is True, "injected usage keeps known detect cost")
|
||||
expected_cost = USAGE_A["cost"] * len(first_chunks) + USAGE_B["cost"] * len(second_chunks)
|
||||
expect(abs(outcome.stats.cost - expected_cost) < 1e-9, "detect costs of both passes are aggregated")
|
||||
expect(
|
||||
abs(
|
||||
outcome.stats.prompt_tokens
|
||||
- (USAGE_A["prompt_tokens"] * len(first_chunks) + USAGE_B["prompt_tokens"] * len(second_chunks))
|
||||
)
|
||||
< 1e-9,
|
||||
"detect tokens of both passes are aggregated",
|
||||
)
|
||||
expect(outcome.stats.full_detection_coverage is True, "valid second pass has full coverage")
|
||||
expect(outcome.stats.detect_ms >= 0, "retry records duration")
|
||||
|
||||
generate_n = {"n": 0}
|
||||
|
||||
def count_generate(messages, policy):
|
||||
generate_n["n"] += 1
|
||||
from privacy_gateway import _fake_complete
|
||||
|
||||
return ChatResult(content=_fake_complete(policy.get("purpose") or "", messages[0].get("content") or ""), model="fake")
|
||||
|
||||
install_test_detect_script(retry_then_ok)
|
||||
generate_n["n"] = 0
|
||||
with patch("privacy_gateway.complete_model", count_generate):
|
||||
try:
|
||||
ran = _run(profile_id, "Heute der Markt und danach der Hafen.")
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
expect(ran.trace.get("generate_called") is True, "valid retry allows exactly one narration call")
|
||||
expect(generate_n["n"] == 1, "narration runs once after a recovered detect pass")
|
||||
expect(_ids(ran.diagnostics or {}), "successful diagnostics are acyclic")
|
||||
expect(_ids(ran.trace or {}), "successful trace is acyclic")
|
||||
|
||||
def always_invalid(attempt, chunk_index, chunk_text, offset, schema_retry=False):
|
||||
return _chat(_invalid_type(), USAGE_A)
|
||||
|
||||
generate_n["n"] = 0
|
||||
install_test_detect_script(always_invalid)
|
||||
blocked = None
|
||||
with patch("privacy_gateway.complete_model", count_generate):
|
||||
try:
|
||||
_run(profile_id, "Heute der Markt und danach der Hafen.")
|
||||
except PrivacyGatewayError as exc:
|
||||
blocked = exc
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
expect(blocked is not None and blocked.code == "detect_invalid_output", "two invalid passes fail closed")
|
||||
expect(generate_n["n"] == 0, "invalid detect never calls narration")
|
||||
expect(blocked.diagnostics.get("generate_called") is False, "final abort keeps generate_called false")
|
||||
expect(blocked.diagnostics.get("detect_passes") == 2, "both invalid passes are counted")
|
||||
expect(blocked.diagnostics.get("contract_violation") == "unknown_entity_type", "final abort keeps the violation category")
|
||||
expect(blocked.diagnostics.get("invalid_entity_type") == "HUMAN", "delivered type is stored without span text")
|
||||
expect(blocked.diagnostics.get("detect_partial_discarded") is True, "failed retry discarded the first pass")
|
||||
expect(_ids(blocked.diagnostics), "failed diagnostics are acyclic")
|
||||
expect("HUMAN" in json.dumps(blocked.diagnostics), "invalid type remains visible")
|
||||
expect("secret" not in json.dumps(blocked.diagnostics).lower(), "no extra identity payload")
|
||||
expect(blocked.status_code != 500, "detect abort is not a generic 500")
|
||||
|
||||
def extra_then_fail(attempt, chunk_index, chunk_text, offset, schema_retry=False):
|
||||
return _chat(_extra_field(), USAGE_A)
|
||||
|
||||
install_test_detect_script(extra_then_fail)
|
||||
extra_err = None
|
||||
try:
|
||||
detect_personal_egress(profile_id, "Heute der Markt.")
|
||||
except DetectError as exc:
|
||||
extra_err = exc
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
expect(extra_err is not None and extra_err.diagnostics.get("contract_violation") == "extra_fields", "extra fields fail closed after retry")
|
||||
|
||||
def missing_then_fail(attempt, chunk_index, chunk_text, offset, schema_retry=False):
|
||||
return _chat(_missing_field(), USAGE_A)
|
||||
|
||||
install_test_detect_script(missing_then_fail)
|
||||
missing_err = None
|
||||
try:
|
||||
detect_personal_egress(profile_id, "Heute der Markt.")
|
||||
except DetectError as exc:
|
||||
missing_err = exc
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
expect(missing_err is not None and missing_err.diagnostics.get("contract_violation") == "missing_fields", "missing fields fail closed after retry")
|
||||
|
||||
def offset_then_fail(attempt, chunk_index, chunk_text, offset, schema_retry=False):
|
||||
return _chat(_bad_offset(chunk_text), USAGE_A)
|
||||
|
||||
install_test_detect_script(offset_then_fail)
|
||||
offset_err = None
|
||||
try:
|
||||
detect_personal_egress(profile_id, "Heute der Markt.")
|
||||
except DetectError as exc:
|
||||
offset_err = exc
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
expect(offset_err is not None and offset_err.diagnostics.get("contract_violation") == "unusable_offsets", "unusable offsets fail closed after retry")
|
||||
|
||||
net_calls = []
|
||||
|
||||
def network_fail(attempt, chunk_index, chunk_text, offset, schema_retry=False):
|
||||
net_calls.append(attempt)
|
||||
raise DetectError("detect_chunk_failed", "chunk failed")
|
||||
|
||||
install_test_detect_script(network_fail)
|
||||
net_err = None
|
||||
try:
|
||||
detect_personal_egress(profile_id, "Heute der Markt.")
|
||||
except DetectError as exc:
|
||||
net_err = exc
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
expect(net_err is not None and net_err.code == "detect_chunk_failed", "provider/chunk failure stays distinct")
|
||||
expect(net_calls == [1], "network-like chunk failure is not doubled by the contract retry")
|
||||
|
||||
install_test_detect_failure(DetectError("detect_chunk_failed", "chunk failed"))
|
||||
immediate = None
|
||||
try:
|
||||
detect_personal_egress(profile_id, "Heute der Markt.")
|
||||
except DetectError as exc:
|
||||
immediate = exc
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
expect(immediate is not None and immediate.diagnostics.get("detect_passes") == 0, "injected provider failure does not start a contract retry")
|
||||
|
||||
mixed = []
|
||||
|
||||
def worker(kind: str):
|
||||
reset_debug()
|
||||
seen = []
|
||||
|
||||
def script(attempt, chunk_index, chunk_text, offset, schema_retry=False):
|
||||
seen.append((kind, attempt))
|
||||
if attempt == 1:
|
||||
entity_type = "HUMAN" if kind == "alpha" else "ANIMAL"
|
||||
return _chat([{"start": 0, "end": 1, "text": "x", "entity_type": entity_type}], USAGE_A)
|
||||
return _chat([], USAGE_B)
|
||||
|
||||
install_test_detect_script(script)
|
||||
try:
|
||||
out = detect_personal_egress(profile_id, f"Heute der Markt {kind}.")
|
||||
mixed.append((kind, tuple(seen), out.stats.invalid_entity_type, out.stats.detect_calls, id(out.stats)))
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
one = pool.submit(worker, "alpha")
|
||||
two = pool.submit(worker, "beta")
|
||||
one.result()
|
||||
two.result()
|
||||
kinds = {item[0] for item in mixed}
|
||||
expect(kinds == {"alpha", "beta"}, "parallel detect retries both complete")
|
||||
by_kind = {item[0]: item for item in mixed}
|
||||
expect(
|
||||
all(kind == row[0] for row in by_kind.values() for kind, _attempt in row[1]),
|
||||
"parallel scripts stay on their request",
|
||||
)
|
||||
expect(by_kind["alpha"][2] in (None, "HUMAN"), "alpha does not keep beta's type")
|
||||
expect(by_kind["beta"][2] in (None, "ANIMAL"), "beta does not keep alpha's type")
|
||||
expect(by_kind["alpha"][4] != by_kind["beta"][4], "parallel stats objects are distinct")
|
||||
|
||||
failed = {
|
||||
"diagnostics": {"generate_called": False, "detect_cost": 0.001, "cost": None, "purpose": "journal_generate"},
|
||||
"trace": {"purpose": "journal_generate", "generate_called": False},
|
||||
"content": "",
|
||||
}
|
||||
staged = _stage_trace(failed, "journal_generate")
|
||||
expect(staged.get("budget") is not failed["diagnostics"], "stage budget is a snapshot, not the live diagnostics object")
|
||||
failed["diagnostics"]["trace"] = {"budget": staged.get("budget")}
|
||||
expect(_ids(failed), "attaching the snapshot does not create a diagnostics cycle")
|
||||
composed = _compose_journal_trace(
|
||||
{"trace": {"purpose": "local_source_artifact"}, "diagnostics": {"prompt_tokens": 0}},
|
||||
failed,
|
||||
run_log=[{"kind": "detect", "status": "error"}],
|
||||
narrate_prompt={"slug": "mvp.journal_generate", "seed_revision": "test"},
|
||||
profile_meta={"present": False},
|
||||
style_meta={"count": 0},
|
||||
dropped=[],
|
||||
extra={"generation_selection": {"voice_id": "journal-generate-voice-clear"}, "style_application": {"include_core": False}},
|
||||
)
|
||||
failed["diagnostics"]["trace"] = composed
|
||||
expect(_ids(failed["diagnostics"]), "composed journal diagnostics stay acyclic")
|
||||
expect(_budget_is_not_diagnostics(failed), "composed budget is not a back-reference")
|
||||
expect(json.dumps(sanitize(failed), default=str), "composed failure is serializable")
|
||||
|
||||
space, day = open_space_day(client, headers)
|
||||
day_id = day["day"]["id"]
|
||||
conv = client.post(
|
||||
f"/api/journal/days/{day_id}/conversations",
|
||||
headers=headers,
|
||||
json={"title": "Gespräch"},
|
||||
)
|
||||
turn = client.post(
|
||||
f"/api/journal/conversations/{conv.json()['id']}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Heute war der Markt voll und danach der Hafen ruhig."},
|
||||
)
|
||||
expect(turn.status_code == 200, f"turn {turn.status_code}")
|
||||
|
||||
enabled = client.put("/api/admin/debug", headers=headers, json={"persist_enabled": True})
|
||||
expect(enabled.status_code == 200 and enabled.json()["persist_enabled"] is True, "persist enabled")
|
||||
before = client.get("/api/admin/debug/runs", headers=headers).json()["runs"]
|
||||
|
||||
install_test_detect_script(always_invalid)
|
||||
try:
|
||||
gen = client.post(
|
||||
f"/api/journal/days/{day_id}/generate",
|
||||
headers=headers,
|
||||
json={"conversation_ids": [conv.json()["id"]]},
|
||||
)
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
expect(gen.status_code == 503, f"journal detect abort status {gen.status_code}")
|
||||
detail = gen.json()["detail"]
|
||||
expect(detail["code"] == "detect_invalid_output", "API keeps the detect contract code")
|
||||
expect(detail["code"] != "error" and gen.status_code != 500, "detect abort is not HTTP 500")
|
||||
expect("Angaben" in (detail.get("message") or ""), "API uses the user-facing detect message")
|
||||
expect(detail.get("cost_report"), "API includes a cost report")
|
||||
expect(detail["cost_report"].get("generate_called") is False, "cost report says generate was not called")
|
||||
expect(
|
||||
(detail.get("diagnostics") or {}).get("generate_called") is False,
|
||||
"diagnostics keep generate_called false",
|
||||
)
|
||||
expect(_ids(detail), "API error payload is acyclic")
|
||||
expect(_budget_is_not_diagnostics(detail), "API error budget is not a diagnostics alias")
|
||||
after = client.get("/api/admin/debug/runs", headers=headers).json()["runs"]
|
||||
error_runs = [
|
||||
item
|
||||
for item in after
|
||||
if item.get("purpose") == "journal_generate" and item.get("status") == "error"
|
||||
]
|
||||
expect(len(error_runs) == 1, "failed journal request is stored exactly once")
|
||||
run = error_runs[0]
|
||||
expect(run.get("journal_day_id") == day_id, "error run is attached to the journal day")
|
||||
detail_run = client.get(f"/api/admin/debug/runs/{run['id']}", headers=headers)
|
||||
expect(detail_run.status_code == 200, f"error run detail {detail_run.status_code}")
|
||||
payload = detail_run.json().get("payload") or {}
|
||||
expect(payload.get("code") == "detect_invalid_output", "stored run keeps the detect code")
|
||||
expect(payload.get("generate_called") is False, "stored run records generate_called false")
|
||||
expect(payload.get("detect_passes") == 2, "stored run records both detect passes")
|
||||
expect(payload.get("detect_partial_discarded") is True, "stored run records discarded partials")
|
||||
expect(payload.get("contract_violation") == "unknown_entity_type", "stored run records the violation")
|
||||
expect(payload.get("invalid_entity_type") == "HUMAN", "stored run records the delivered type")
|
||||
expect(payload.get("generation_selection") or (payload.get("trace") or {}).get("generation_selection"), "stored run keeps generation selection")
|
||||
expect("local_label" not in json.dumps(payload), "stored run has no mapping labels")
|
||||
exported = client.get(
|
||||
f"/api/admin/debug/export?format=json&journal_day_id={day_id}&purpose=journal_generate",
|
||||
headers=headers,
|
||||
)
|
||||
expect(exported.status_code == 200, f"error run export {exported.status_code}")
|
||||
document = exported.json()
|
||||
encoded = json.dumps(document)
|
||||
expect(encoded, "exported error run is JSON-serializable")
|
||||
expect("detect_invalid_output" in encoded, "export contains the detect code")
|
||||
|
||||
hidden = EngineError("detect_invalid_output", "Persönliche Angaben konnten nicht sicher zugeordnet werden.", 503)
|
||||
with patch("debug_store.persist_step", side_effect=RuntimeError("persist boom")):
|
||||
persist_engine_error(profile_id, purpose="journal_generate", exc=hidden, journal_day_id=day_id)
|
||||
install_test_detect_script(always_invalid)
|
||||
try:
|
||||
with patch("debug_store.persist_step", side_effect=RuntimeError("persist boom")):
|
||||
gen_hidden = client.post(
|
||||
f"/api/journal/days/{day_id}/generate",
|
||||
headers=headers,
|
||||
json={"conversation_ids": [conv.json()["id"]]},
|
||||
)
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
expect(gen_hidden.status_code == 503, f"persist failure keeps detect status {gen_hidden.status_code}")
|
||||
expect(gen_hidden.json()["detail"]["code"] == "detect_invalid_output", "persist failure does not replace EngineError")
|
||||
expect(gen_hidden.status_code != 500, "persist failure is not HTTP 500")
|
||||
|
||||
reset_detect_test_hooks()
|
||||
control_space, control_day = open_space_day(client, headers, "Kontrolle", "2026-08-28")
|
||||
control_conv = client.post(
|
||||
f"/api/journal/days/{control_day['day']['id']}/conversations",
|
||||
headers=headers,
|
||||
json={"title": "Gespräch"},
|
||||
)
|
||||
control_turn = client.post(
|
||||
f"/api/journal/conversations/{control_conv.json()['id']}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Heute Tee auf dem Balkon, danach nur der Wind."},
|
||||
)
|
||||
expect(control_turn.status_code == 200, "control turn")
|
||||
control = client.post(
|
||||
f"/api/journal/days/{control_day['day']['id']}/generate",
|
||||
headers=headers,
|
||||
json={"conversation_ids": [control_conv.json()["id"]]},
|
||||
)
|
||||
expect(control.status_code == 200, f"control generate without profile {control.status_code}")
|
||||
expect((control.json().get("trace") or {}).get("generate_called") is True, "control run still narrates once")
|
||||
expect(_ids(control.json().get("trace") or {}), "control trace is acyclic")
|
||||
|
||||
client.put("/api/admin/debug", headers=headers, json={"persist_enabled": False})
|
||||
|
||||
print("ALL TESTS PASSED")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,446 @@
|
||||
"""Transitional learning detect: senses from dialogue review, admin mode switch.
|
||||
|
||||
Fake detect/provider only. Run from backend/: python tests/test_detect_learning.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from detect_learning import (
|
||||
cue_for_mention,
|
||||
decision_for_mention,
|
||||
excerpt_view,
|
||||
get_cue_decision,
|
||||
get_detect_operating_mode,
|
||||
get_sense,
|
||||
merge_gliner_candidates,
|
||||
passage_provider,
|
||||
record_cue,
|
||||
record_sense,
|
||||
set_detect_operating_mode,
|
||||
try_local_passage_decision,
|
||||
)
|
||||
from detect_pipeline import (
|
||||
MentionSpan,
|
||||
compact_diff_counters,
|
||||
compare_mentions,
|
||||
map_entity_type,
|
||||
prepare_detect_pipeline,
|
||||
same_mention,
|
||||
)
|
||||
from providers import ChatResult, ProviderConfig
|
||||
from dialogue_turn import visible_for_role
|
||||
from identity_store import list_confirmed_identities
|
||||
from main import app
|
||||
from privacy_gateway import reset_debug
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
def status_ok(response, label: str) -> None:
|
||||
if response.status_code != 200:
|
||||
detail = response.json() if response.headers.get("content-type", "").startswith("application/json") else {}
|
||||
code = detail.get("detail", {}).get("code") if isinstance(detail, dict) else None
|
||||
expect(False, f"{label} HTTP {response.status_code} {code or ''}".strip())
|
||||
expect(True, label)
|
||||
|
||||
|
||||
def header(token: str) -> dict:
|
||||
return {"X-Auth-Token": token}
|
||||
|
||||
|
||||
def open_conv(client: TestClient, headers: dict) -> str:
|
||||
space = client.post("/api/journal/spaces", headers=headers, json={"title": "Alltag"})
|
||||
day = client.post(
|
||||
f"/api/journal/spaces/{space.json()['id']}/days",
|
||||
headers=headers,
|
||||
json={"calendar_date": "2026-09-08"},
|
||||
)
|
||||
conv = client.post(
|
||||
f"/api/journal/days/{day.json()['day']['id']}/conversations",
|
||||
headers=headers,
|
||||
json={"title": "Gespräch"},
|
||||
)
|
||||
return conv.json()["id"]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
reset_debug()
|
||||
with TestClient(app) as client:
|
||||
setup = client.post(
|
||||
"/api/auth/setup",
|
||||
json={"email": "lars@example.test", "name": "Lars", "password": "test-pass"},
|
||||
)
|
||||
headers = header(setup.json()["token"])
|
||||
profile_id = setup.json()["profile_id"]
|
||||
|
||||
providers = client.get("/api/admin/providers", headers=headers)
|
||||
expect(providers.status_code == 200, "providers status")
|
||||
expect(providers.json()["detect_operating_mode"] == "bypass", "fake-env default is bypass")
|
||||
expect(get_detect_operating_mode() == "bypass", "store default in tests is bypass")
|
||||
ner = providers.json().get("local_ner") or {}
|
||||
expect(ner.get("enabled") is False, "GLiNER is off by default")
|
||||
detect_before = next(item for item in providers.json()["roles"] if item["role"] == "detect")
|
||||
remote_gliner = client.put(
|
||||
"/api/admin/providers/local-ner",
|
||||
headers=headers,
|
||||
json={"url": "https://openrouter.ai/api/v1"},
|
||||
)
|
||||
expect(remote_gliner.status_code == 400, "GLiNER URL must stay local")
|
||||
enabled = client.put(
|
||||
"/api/admin/providers/local-ner",
|
||||
headers=headers,
|
||||
json={"enabled": True, "url": "http://192.168.2.144:8090"},
|
||||
)
|
||||
status_ok(enabled, "enable local GLiNER")
|
||||
expect(enabled.json()["local_ner"]["enabled"] is True, "GLiNER enabled flag persisted")
|
||||
expect(enabled.json()["local_ner"]["url"] == "http://192.168.2.144:8090", "GLiNER LAN URL persisted")
|
||||
detect_after = next(item for item in enabled.json()["roles"] if item["role"] == "detect")
|
||||
expect(detect_after.get("url") == detect_before.get("url"), "OpenRouter detect URL is unchanged")
|
||||
client.put("/api/admin/providers/local-ner", headers=headers, json={"enabled": False})
|
||||
|
||||
bad = client.put("/api/admin/providers/detect-mode", headers=headers, json={"mode": "wordlist"})
|
||||
expect(bad.status_code == 400, "invalid detect mode is rejected")
|
||||
|
||||
conv_semantic = open_conv(client, headers)
|
||||
semantic_turn = client.post(
|
||||
f"/api/journal/conversations/{conv_semantic}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Anna kam vorbei."},
|
||||
)
|
||||
status_ok(semantic_turn, "bypass turn")
|
||||
expect(not semantic_turn.json().get("pending_mask_review"), "bypass mode does not pause for review")
|
||||
expect(any(item.get("role") == "assistant" for item in semantic_turn.json().get("messages") or []), "bypass turn gets an assistant")
|
||||
|
||||
switched = client.put("/api/admin/providers/detect-mode", headers=headers, json={"mode": "learning"})
|
||||
status_ok(switched, "switch to learning alias")
|
||||
expect(switched.json()["detect_operating_mode"] == "learning_full", "learning alias stores learning_full")
|
||||
|
||||
conv = open_conv(client, headers)
|
||||
paused = client.post(
|
||||
f"/api/journal/conversations/{conv}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Anna kam vorbei."},
|
||||
)
|
||||
status_ok(paused, "learning pause")
|
||||
review = paused.json().get("pending_mask_review") or {}
|
||||
expect(bool(review.get("id")), "learning mode returns a review id")
|
||||
expect(paused.json().get("assistant") is None, "paused turn has no assistant")
|
||||
candidates = review.get("candidates") or []
|
||||
anna = next((item for item in candidates if item.get("text") == "Anna"), None)
|
||||
expect(anna is not None, "Anna is a review candidate")
|
||||
hidden = visible_for_role({"pending_mask_review": review, "trace": {"egress": "x"}}, "user")
|
||||
expect("pending_mask_review" in hidden, "users still receive the mask review")
|
||||
expect("trace" not in hidden, "users do not receive the detect trace")
|
||||
|
||||
reloaded = client.get(f"/api/journal/conversations/{conv}", headers=headers)
|
||||
expect(reloaded.json().get("pending_mask_review", {}).get("id") == review["id"], "pending review survives reload")
|
||||
|
||||
missing = client.post(
|
||||
f"/api/journal/conversations/{conv}/turn/review",
|
||||
headers=headers,
|
||||
json={"review_id": "missing", "decisions": []},
|
||||
)
|
||||
expect(missing.status_code == 404, "unknown review is gone")
|
||||
|
||||
identity = client.post(
|
||||
f"/api/journal/conversations/{conv}/turn/review",
|
||||
headers=headers,
|
||||
json={
|
||||
"review_id": review["id"],
|
||||
"decisions": [{"id": anna["id"], "decision": "identity"}],
|
||||
},
|
||||
)
|
||||
status_ok(identity, "identity review")
|
||||
expect(not identity.json().get("pending_mask_review"), "review continue clears the pause")
|
||||
expect(any(item.get("role") == "assistant" for item in identity.json().get("messages") or []), "continue produces an assistant")
|
||||
confirmed = list_confirmed_identities(profile_id)
|
||||
expect(any((item.get("canonical_label") or "").casefold() == "anna" for item in confirmed), "identity review confirms the registry")
|
||||
sense = get_sense(profile_id, "Anna")
|
||||
expect(sense["identity_hits"] >= 1 and not sense["ambiguous"], "Anna is identity-only")
|
||||
|
||||
second = client.post(
|
||||
f"/api/journal/conversations/{conv}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Anna hat später angerufen."},
|
||||
)
|
||||
status_ok(second, "second Anna turn")
|
||||
expect(not second.json().get("pending_mask_review"), "identity-only spelling skips the popup")
|
||||
|
||||
food_conv = open_conv(client, headers)
|
||||
food = client.post(
|
||||
f"/api/journal/conversations/{food_conv}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Hanna aß mit uns."},
|
||||
)
|
||||
status_ok(food, "hanna pause")
|
||||
food_review = food.json().get("pending_mask_review") or {}
|
||||
food_candidates = food_review.get("candidates") or []
|
||||
hanna = next((item for item in food_candidates if item.get("text") == "Hanna"), None)
|
||||
expect(hanna is not None, "Hanna is a review candidate")
|
||||
declined = client.post(
|
||||
f"/api/journal/conversations/{food_conv}/turn/review",
|
||||
headers=headers,
|
||||
json={
|
||||
"review_id": food_review["id"],
|
||||
"decisions": [{"id": hanna["id"], "decision": "not_identity"}],
|
||||
},
|
||||
)
|
||||
status_ok(declined, "not_identity review")
|
||||
expect(not any((item.get("canonical_label") or "").casefold() == "hanna" for item in list_confirmed_identities(profile_id)), "not_identity does not confirm Hanna")
|
||||
expect(get_sense(profile_id, "Hanna")["non_identity_hits"] >= 1, "not_identity records a sense")
|
||||
hanna_again = client.post(
|
||||
f"/api/journal/conversations/{food_conv}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Hanna aß mit uns."},
|
||||
)
|
||||
status_ok(hanna_again, "second Hanna turn")
|
||||
expect(
|
||||
not hanna_again.json().get("pending_mask_review"),
|
||||
"stored Hanna cue is not re-asked against teacher PERSON",
|
||||
)
|
||||
|
||||
record_sense(profile_id, "Clarissa", identity=True)
|
||||
record_sense(profile_id, "Clarissa", identity=False)
|
||||
expect(get_sense(profile_id, "Clarissa")["ambiguous"], "both senses mark Clarissa as ambiguous")
|
||||
amb_conv = open_conv(client, headers)
|
||||
with patch("detect_learning.try_local_passage_decision", return_value="not_identity"):
|
||||
amb = client.post(
|
||||
f"/api/journal/conversations/{amb_conv}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Clarissa lag auf dem Tisch."},
|
||||
)
|
||||
status_ok(amb, "ambiguous local passage")
|
||||
expect(not amb.json().get("pending_mask_review"), "local passage can finish without a popup")
|
||||
expect(any(item.get("role") == "assistant" for item in amb.json().get("messages") or []), "local passage still generates")
|
||||
|
||||
kin_conv = open_conv(client, headers)
|
||||
kin = client.post(
|
||||
f"/api/journal/conversations/{kin_conv}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Ich war mit meinem Sohn Leon im Park."},
|
||||
)
|
||||
status_ok(kin, "kinship Leon pause")
|
||||
kin_review = kin.json().get("pending_mask_review") or {}
|
||||
kin_names = [item.get("text") for item in kin_review.get("candidates") or []]
|
||||
expect("Leon" in kin_names, "Sohn Leon is offered even when Detect does not report it")
|
||||
leon = next((item for item in kin_review.get("candidates") or [] if item.get("text") == "Leon"), None)
|
||||
expect(leon is not None, "Leon candidate id is present")
|
||||
kin_done = client.post(
|
||||
f"/api/journal/conversations/{kin_conv}/turn/review",
|
||||
headers=headers,
|
||||
json={
|
||||
"review_id": kin_review["id"],
|
||||
"decisions": [{"id": leon["id"], "decision": "identity"}],
|
||||
},
|
||||
)
|
||||
status_ok(kin_done, "Leon identity review")
|
||||
kin_again = client.post(
|
||||
f"/api/journal/conversations/{kin_conv}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Ich war mit meinem Sohn Leon im Park."},
|
||||
)
|
||||
status_ok(kin_again, "second Leon turn")
|
||||
expect(not kin_again.json().get("pending_mask_review"), "confirmed Sohn Leon skips the popup")
|
||||
|
||||
sushi_conv = open_conv(client, headers)
|
||||
sushi = client.post(
|
||||
f"/api/journal/conversations/{sushi_conv}/turn",
|
||||
headers=headers,
|
||||
json={
|
||||
"body": (
|
||||
"Gestern bin ich mit meiner Frau Sushi und meinem Sohn Rohan "
|
||||
"Sushi essen gegangen. Das Restaurant hat mich dabei total beeindruckt."
|
||||
)
|
||||
},
|
||||
)
|
||||
status_ok(sushi, "homonym sentence pause")
|
||||
sushi_names = [item.get("text") for item in (sushi.json().get("pending_mask_review") or {}).get("candidates") or []]
|
||||
expect("Rohan" in sushi_names, "Rohan from Sohn is a candidate")
|
||||
expect("Sushi" in sushi_names, "Sushi from Frau is a candidate")
|
||||
expect("Restaurant" not in sushi_names, "plain Restaurant is not kinship-offered")
|
||||
sushi_hits = [
|
||||
item
|
||||
for item in (sushi.json().get("pending_mask_review") or {}).get("candidates") or []
|
||||
if item.get("text") == "Sushi"
|
||||
]
|
||||
expect(len(sushi_hits) >= 2, "both Sushi mentions are offered")
|
||||
expect(
|
||||
sushi_hits[0].get("highlight_start") != sushi_hits[1].get("highlight_start"),
|
||||
"the two Sushi mentions highlight different offsets",
|
||||
)
|
||||
for item in sushi_hits:
|
||||
excerpt = item.get("excerpt") or ""
|
||||
start = item.get("highlight_start")
|
||||
end = item.get("highlight_end")
|
||||
expect(excerpt[start:end] == "Sushi", "highlight covers the Sushi token")
|
||||
|
||||
homonym = (
|
||||
"Gestern bin ich mit meiner Frau Sushi und meinem Sohn Rohan "
|
||||
"Sushi essen gegangen."
|
||||
)
|
||||
first_at = homonym.index("Sushi")
|
||||
second_at = homonym.rindex("Sushi")
|
||||
first = excerpt_view(homonym, first_at, first_at + 5, "Sushi")
|
||||
second = excerpt_view(homonym, second_at, second_at + 5, "Sushi")
|
||||
expect(first["highlight_start"] < second["highlight_start"], "person Sushi sits left of dish Sushi")
|
||||
expect(first["excerpt"][first["highlight_start"]:first["highlight_end"]] == "Sushi", "first highlight is Sushi")
|
||||
expect(second["excerpt"][second["highlight_start"]:second["highlight_end"]] == "Sushi", "second highlight is Sushi")
|
||||
prefix = "SYSTEM\n"
|
||||
mapped = excerpt_view(
|
||||
homonym,
|
||||
len(prefix) + second_at,
|
||||
len(prefix) + second_at + 5,
|
||||
"Sushi",
|
||||
prefix + homonym,
|
||||
)
|
||||
expect(mapped["highlight_start"] == second["highlight_start"], "rendered detect offsets map to the dish Sushi")
|
||||
expect(cue_for_mention(homonym, first_at, first_at + 5, "Sushi") == "frau", "person Sushi attaches to Frau")
|
||||
expect(cue_for_mention(homonym, second_at, second_at + 5, "Sushi") == "rohan", "dish Sushi stays distinct from Frau")
|
||||
appos = "Sushi, meine Frau war erkältet."
|
||||
appos_at = appos.index("Sushi")
|
||||
expect(cue_for_mention(appos, appos_at, appos_at + 5, "Sushi") == "frau", "apposition Sushi, meine Frau binds Frau")
|
||||
far = "Meine Frau und ich aßen Sushi."
|
||||
far_at = far.rindex("Sushi")
|
||||
expect(cue_for_mention(far, far_at, far_at + 5, "Sushi") != "frau", "Frau elsewhere in the sentence does not bind the dish")
|
||||
|
||||
sushi_review = sushi.json().get("pending_mask_review") or {}
|
||||
sushi_decisions = []
|
||||
for item in sushi_review.get("candidates") or []:
|
||||
label = item.get("text")
|
||||
cue = item.get("cue")
|
||||
if label == "Sushi" and cue != "frau":
|
||||
sushi_decisions.append({"id": item["id"], "decision": "not_identity"})
|
||||
else:
|
||||
sushi_decisions.append({"id": item["id"], "decision": "identity"})
|
||||
sushi_done = client.post(
|
||||
f"/api/journal/conversations/{sushi_conv}/turn/review",
|
||||
headers=headers,
|
||||
json={"review_id": sushi_review["id"], "decisions": sushi_decisions},
|
||||
)
|
||||
status_ok(sushi_done, "homonym review")
|
||||
expect(get_cue_decision(profile_id, "Sushi", "frau") == "identity", "Frau Sushi is stored as identity")
|
||||
expect(get_cue_decision(profile_id, "Sushi", "rohan") == "not_identity", "dish Sushi after Rohan is stored")
|
||||
expect(get_cue_decision(profile_id, "Rohan", "sohn") == "identity", "Sohn Rohan cue is stored")
|
||||
sushi_again = client.post(
|
||||
f"/api/journal/conversations/{sushi_conv}/turn",
|
||||
headers=headers,
|
||||
json={
|
||||
"body": (
|
||||
"Gestern bin ich mit meiner Frau Sushi und meinem Sohn Rohan "
|
||||
"Sushi essen gegangen. Das Restaurant hat mich dabei total beeindruckt."
|
||||
)
|
||||
},
|
||||
)
|
||||
status_ok(sushi_again, "repeat homonym sentence")
|
||||
expect(not sushi_again.json().get("pending_mask_review"), "same reviewed sentence does not re-ask")
|
||||
|
||||
dish = "Ich aß Sushi."
|
||||
dish_at = dish.index("Sushi")
|
||||
food_spans = [{"text": "Sushi", "start": dish_at, "end": dish_at + 5, "label": "food", "score": 0.8}]
|
||||
food_cands, _maps = merge_gliner_candidates(profile_id, [], [], dish, dish, food_spans)
|
||||
expect(
|
||||
any(item.get("text") == "Sushi" and item.get("suggested") == "not_identity" for item in food_cands),
|
||||
"GLiNER food span suggests not_identity",
|
||||
)
|
||||
person_line = "Ich war mit meiner Frau Sushi unterwegs."
|
||||
person_at = person_line.index("Sushi")
|
||||
gliner_miss = [{"text": "Sushi", "start": person_at, "end": person_at + 5, "label": "food", "score": 0.9}]
|
||||
merged, _maps = merge_gliner_candidates(profile_id, [], [], person_line, person_line, gliner_miss)
|
||||
expect(
|
||||
not any(item.get("suggested") == "not_identity" for item in merged),
|
||||
"GLiNER food does not override Frau attachment",
|
||||
)
|
||||
expect(
|
||||
decision_for_mention(profile_id, "Sushi", person_line, person_at, person_at + 5, person_line) == "identity",
|
||||
"learned Frau cue wins over GLiNER food",
|
||||
)
|
||||
dish_line = "Ich aß Sushi."
|
||||
dish_pos = dish_line.index("Sushi")
|
||||
expect(
|
||||
decision_for_mention(profile_id, "Sushi", dish_line, dish_pos, dish_pos + 5, dish_line) == "ask",
|
||||
"Tag-21: identity hits plus new cue stay visible",
|
||||
)
|
||||
person = MentionSpan("Sushi", 20, 25, "PERSON", "identity", "cue", True, "frau")
|
||||
food = MentionSpan("Sushi", 20, 25, "FOOD", "not_identity", "teacher", False, "aß")
|
||||
expect(same_mention(person, food), "same offsets are the same mention")
|
||||
wrapped = MentionSpan("Frau Sushi", 15, 25, "PERSON", "identity", "teacher", False, "frau")
|
||||
expect(same_mention(person, wrapped), "contained Sushi matches Frau Sushi")
|
||||
expect(map_entity_type("person") == "PERSON", "GLiNER person maps to PERSON")
|
||||
guessed = MentionSpan("Sushi", 20, 25, "PERSON", "identity", "candidate", False, "aß")
|
||||
review, counters = compare_mentions(profile_id, dish_line, [guessed], [food], dish_line)
|
||||
expect(counters["diff_type_conflict"] >= 1, "FOOD versus PERSON is a type conflict")
|
||||
expect(any(item.get("reason") == "type_conflict" for item in review), "unconfirmed type conflict is offered")
|
||||
confirmed_dish = MentionSpan("Sushi", 20, 25, "FOOD", "not_identity", "cue", True, "rohan")
|
||||
teacher_person = MentionSpan("Sushi", 20, 25, "PERSON", "identity", "teacher", False, "rohan")
|
||||
kept, kept_counters = compare_mentions(
|
||||
profile_id, dish_line, [confirmed_dish], [teacher_person], dish_line
|
||||
)
|
||||
expect(kept_counters["diff_type_conflict"] >= 1, "confirmed cue still counts the type conflict")
|
||||
expect(not kept, "confirmed cue is not re-asked on type conflict")
|
||||
compact = compact_diff_counters(counters)
|
||||
dumped = str(compact)
|
||||
expect("Sushi" not in dumped and "Frau" not in dumped, "compact diff counters carry no plaintext")
|
||||
expect(set(compact) == {
|
||||
"diff_agree",
|
||||
"diff_only_student",
|
||||
"diff_only_teacher",
|
||||
"diff_type_conflict",
|
||||
"diff_new_identity",
|
||||
"diff_cue_reinforced",
|
||||
}, "compact counters are the agreed keys")
|
||||
set_detect_operating_mode("learning_reduced")
|
||||
expect(get_detect_operating_mode() == "learning_reduced", "stage 2 mode persists")
|
||||
set_detect_operating_mode("learning_manual")
|
||||
expect(get_detect_operating_mode() == "learning_manual", "manual mode persists")
|
||||
set_detect_operating_mode("student")
|
||||
pipe = prepare_detect_pipeline(profile_id, "Anna kam vorbei.", "Anna kam vorbei.")
|
||||
expect(pipe.mode == "student", "student path is selectable")
|
||||
expect(not pipe.need_review, "zielpfad does not open a teacher popup")
|
||||
record_sense(profile_id, "Sushi", identity=True)
|
||||
record_cue(profile_id, "Sushi", "frau", "identity", "meine Frau Sushi")
|
||||
expect(
|
||||
decision_for_mention(profile_id, "Sushi", "Ich aß Sushi.", dish_pos, dish_pos + 5) == "ask",
|
||||
"Tag-21 remains ask after more identity hits",
|
||||
)
|
||||
|
||||
fake_passage = ProviderConfig(
|
||||
role="passage",
|
||||
name="ollama",
|
||||
mode="http",
|
||||
url="http://192.168.2.144:11434/v1/chat/completions",
|
||||
model="phi3:mini",
|
||||
key="",
|
||||
local=True,
|
||||
zdr=True,
|
||||
no_train=True,
|
||||
)
|
||||
with patch("detect_learning.passage_provider", return_value=fake_passage):
|
||||
with patch("providers.complete_chat", return_value=ChatResult(content='{"decision":"not_identity"}')) as chat:
|
||||
decided = try_local_passage_decision("Rohan Sushi essen", "Sushi")
|
||||
expect(decided == "not_identity", "passage profile can decide without local Detect")
|
||||
expect(chat.called, "passage uses complete_chat")
|
||||
expect(passage_provider() is None, "no passage profile means no silent detect fallback")
|
||||
|
||||
back = client.put("/api/admin/providers/detect-mode", headers=headers, json={"mode": "semantic"})
|
||||
expect(back.json()["detect_operating_mode"] == "bypass", "semantic alias stores bypass")
|
||||
full = client.put("/api/admin/providers/detect-mode", headers=headers, json={"mode": "learning_full"})
|
||||
expect(full.json()["detect_operating_mode"] == "learning_full", "learning_full is accepted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Unit tests for student/teacher comparison. No database."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
os.environ.setdefault("KANSHO_PROVIDER_KEY", "")
|
||||
os.environ.setdefault("KANSHO_DETECT_PROVIDER_KEY", "")
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from detect_learning import canonicalize_detect_mode, decision_for_mention
|
||||
from detect_pipeline import (
|
||||
MentionSpan,
|
||||
compact_diff_counters,
|
||||
compare_mentions,
|
||||
map_entity_type,
|
||||
protects,
|
||||
same_mention,
|
||||
types_equivalent,
|
||||
)
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
expect(canonicalize_detect_mode("learning") == "learning_full", "learning aliases to learning_full")
|
||||
expect(canonicalize_detect_mode("semantic") == "bypass", "semantic aliases to bypass")
|
||||
expect(canonicalize_detect_mode("wordlist") is None, "unknown mode is rejected")
|
||||
expect(map_entity_type("person") == "PERSON", "person maps to PERSON")
|
||||
expect(map_entity_type("place") == "PLACE", "place maps to PLACE")
|
||||
expect(protects("PERSON") and not protects("FOOD"), "PERSON protects, FOOD does not")
|
||||
expect(types_equivalent("PERSON", "PLACE"), "similar protectable types are equivalent")
|
||||
expect(not types_equivalent("FOOD", "PERSON"), "FOOD versus PERSON is never equivalent")
|
||||
guessed = MentionSpan("Sushi", 20, 25, "PERSON", "identity", "candidate", False, "aß")
|
||||
teacher_food = MentionSpan("Sushi", 20, 25, "FOOD", "not_identity", "teacher", False, "aß")
|
||||
offered, offered_counters = compare_mentions("p", "Ich aß Sushi.", [guessed], [teacher_food])
|
||||
expect(offered_counters["diff_type_conflict"] == 1, "unconfirmed FOOD versus PERSON is counted")
|
||||
expect(any(item.get("reason") == "type_conflict" for item in offered), "unconfirmed type conflict is offered")
|
||||
confirmed = MentionSpan("Sushi", 20, 25, "FOOD", "not_identity", "cue", True, "rohan")
|
||||
teacher_person = MentionSpan("Sushi", 20, 25, "PERSON", "identity", "teacher", False, "rohan")
|
||||
kept, kept_counters = compare_mentions("p", "Rohan Sushi essen", [confirmed], [teacher_person])
|
||||
expect(kept_counters["diff_type_conflict"] == 1, "confirmed cue still counts FOOD versus PERSON")
|
||||
expect(not kept, "confirmed cue is not re-asked on type conflict")
|
||||
inner = MentionSpan("Sushi", 20, 25, "PERSON", "identity", "cue", True, "frau")
|
||||
outer = MentionSpan("Frau Sushi", 15, 25, "PERSON", "identity", "teacher", False, "frau")
|
||||
expect(same_mention(inner, outer), "contained span is the same mention")
|
||||
food = MentionSpan("Sushi", 20, 25, "FOOD", "not_identity", "teacher", False, "aß")
|
||||
expect(same_mention(inner, food), "same offsets stay one mention even when types differ")
|
||||
compact = compact_diff_counters({"diff_agree": 2, "diff_type_conflict": 1, "label": "Sushi"})
|
||||
expect(compact["diff_agree"] == 2 and compact["diff_type_conflict"] == 1, "known counters are kept")
|
||||
expect("label" not in compact and "Sushi" not in str(compact), "compact counters drop plaintext")
|
||||
with patch("detect_learning.get_cue_decision", return_value=None), patch(
|
||||
"detect_learning.get_sense",
|
||||
return_value={"identity_hits": 3, "non_identity_hits": 0, "ambiguous": False},
|
||||
), patch("detect_learning.cue_for_mention", return_value="aß"):
|
||||
expect(
|
||||
decision_for_mention("p", "Sushi", "Ich aß Sushi.", 7, 12) == "ask",
|
||||
"Tag-21: identity-only sense does not lock a new cue",
|
||||
)
|
||||
with patch("detect_learning.get_cue_decision", return_value="identity"), patch(
|
||||
"detect_learning.cue_for_mention", return_value="frau"
|
||||
):
|
||||
expect(
|
||||
decision_for_mention("p", "Sushi", "meine Frau Sushi", 11, 16) == "identity",
|
||||
"stored cue remains binding",
|
||||
)
|
||||
print("detect pipeline unit ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -9,8 +9,6 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-dialogue-test.sqlite")
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
|
||||
@@ -10,10 +10,8 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-frame-test.sqlite")
|
||||
os.environ["KANSHO_PROVIDER_KEY"] = ""
|
||||
os.environ["KANSHO_DETECT_PROVIDER_KEY"] = ""
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
@@ -89,6 +87,9 @@ def main() -> None:
|
||||
expect(providers.status_code == 200, "admin providers")
|
||||
roles = {item["role"]: item for item in providers.json()["roles"]}
|
||||
expect(set(roles) == {"generate", "detect"}, "two provider roles")
|
||||
expect(providers.json()["remote_plaintext_allowed"] is True, "test runtime allows remote detect")
|
||||
expect(providers.json()["remote_plaintext_reason"] == "non_production", "tests are not production")
|
||||
expect(providers.json().get("detect_operating_mode") == "learning_full", "detect mode defaults to learning stage 1")
|
||||
expect(roles["generate"]["ready"] is False, "generate fail-closed without key")
|
||||
expect("sk-" not in providers.text, "provider status has no secret")
|
||||
expect("KANSHO_PROVIDER_KEY=" not in providers.text, "env assignment not leaked")
|
||||
@@ -107,6 +108,37 @@ def main() -> None:
|
||||
expect(saved.status_code == 200, f"save generate settings {saved.text}")
|
||||
saved_roles = {item["role"]: item for item in saved.json()["roles"]}
|
||||
expect(saved_roles["generate"]["model"] == "openai/gpt-4o", "generate model persisted")
|
||||
expect("profiles" in saved.json(), "llm profiles are listed")
|
||||
titles = {item["title"] for item in saved.json()["profiles"]}
|
||||
expect("Ollama (LAN)" in titles, "LAN Ollama profile is seeded")
|
||||
ollama = next(item for item in saved.json()["profiles"] if item["title"] == "Ollama (LAN)")
|
||||
expect(ollama["local"] is True, "LAN Ollama is a local trusted endpoint")
|
||||
expect(ollama["url"].startswith("http://192.168.2.144:11434"), "Ollama URL is the agreed LAN host")
|
||||
|
||||
switched = client.put(
|
||||
"/api/admin/llm-profiles/" + ollama["id"],
|
||||
headers=headers,
|
||||
json={
|
||||
"title": "Ollama (LAN)",
|
||||
"name": "ollama",
|
||||
"url": ollama["url"],
|
||||
"model": "llama3.1:latest",
|
||||
"zdr": True,
|
||||
"no_train": True,
|
||||
},
|
||||
)
|
||||
expect(switched.status_code == 200, f"save ollama model {switched.text}")
|
||||
activated = client.post(
|
||||
"/api/admin/providers/detect/activate",
|
||||
headers=headers,
|
||||
json={"profile_id": ollama["id"]},
|
||||
)
|
||||
expect(activated.status_code == 200, f"activate ollama detect {activated.text}")
|
||||
detect_role = {item["role"]: item for item in activated.json()["roles"]}["detect"]
|
||||
expect(detect_role["local"] is True, "detect uses local ollama after profile switch")
|
||||
expect(detect_role["model"] == "llama3.1:latest", "detect keeps the saved ollama model")
|
||||
generate_role = {item["role"]: item for item in activated.json()["roles"]}["generate"]
|
||||
expect(generate_role["model"] == "openai/gpt-4o", "generate profile stays on its own model")
|
||||
|
||||
unknown = client.put(
|
||||
"/api/admin/providers/training",
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
"""GLiNER client: local URL only, fail-soft, no request text in logs."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import httpx
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ.setdefault("KANSHO_PROVIDER_KEY", "")
|
||||
os.environ.setdefault("KANSHO_DETECT_PROVIDER_KEY", "")
|
||||
|
||||
from gliner_client import DEFAULT_URL, extract_entities, health, normalize_base_url
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
class _Resp:
|
||||
def __init__(self, status_code: int, payload):
|
||||
self.status_code = status_code
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
def main() -> None:
|
||||
expect(normalize_base_url("http://192.168.2.144:8090/") == DEFAULT_URL, "default GLiNER URL is normalized")
|
||||
expect(extract_entities("Anna", url="https://openrouter.ai/api/v1") is None, "OpenRouter URL is rejected")
|
||||
expect(health("https://openrouter.ai").get("reason") == "not_local", "health rejects non-local URL")
|
||||
|
||||
with patch("gliner_client.httpx.post", return_value=_Resp(200, {"spans": [{"text": "Anna", "start": 0, "end": 4, "label": "person", "score": 0.9}]})):
|
||||
spans = extract_entities("Anna kam.", url="http://192.168.2.144:8090")
|
||||
expect(spans == [{"text": "Anna", "start": 0, "end": 4, "label": "person", "score": 0.9}], "extract returns spans")
|
||||
|
||||
with patch("gliner_client.httpx.post", side_effect=httpx.ConnectError("down")):
|
||||
expect(extract_entities("Anna kam.", url="http://192.168.2.144:8090") is None, "extract is fail-soft on errors")
|
||||
|
||||
with patch("gliner_client.httpx.get", return_value=_Resp(200, {"status": "ok", "model": "urchade/gliner_multi-v2.1", "offline": True})):
|
||||
ping = health("http://192.168.2.144:8090")
|
||||
expect(ping.get("ok") is True and ping.get("offline") is True, "health reports ready offline model")
|
||||
print("gliner client: OK")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -10,10 +10,8 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-identity-registry-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from identity_store import STATUS_LEGACY, list_confirmed_identities, list_registry
|
||||
|
||||
@@ -11,10 +11,8 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-journal-budget-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
@@ -873,7 +871,7 @@ def test_generate_flow(client: TestClient, headers: dict) -> None:
|
||||
expect("Vielleicht bleibe ich kürzer" in narrate, "omitted labels do not drop canonical hedges")
|
||||
expect("assistant:" not in (gen.json().get("body") or ""), "draft body has no assistant lines")
|
||||
expect("WRITING_PROFILE" in narrate or "Neutraler Journalstil" in narrate or "Core:" in narrate, "writing profile reaches generate")
|
||||
expect("STYLE_EXAMPLES" in narrate, "style examples are labeled separately from day facts")
|
||||
expect("STYLE_EXAMPLES" not in narrate, "default voice does not label a style-examples block")
|
||||
expect("Erzählmerkmale" not in (narrate.split("\nCURRENT_DAY_SOURCES\n")[0] if "\nCURRENT_DAY_SOURCES\n" in narrate else narrate), "day dialogue is not a style brief")
|
||||
|
||||
reset_debug()
|
||||
|
||||
@@ -10,10 +10,8 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-journal-editorial-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from db import get_db, init_db
|
||||
@@ -71,7 +69,6 @@ def test_prompt_contract() -> None:
|
||||
text = prompt.get("template") or ""
|
||||
expect("INHALTSTREUE" in text, "prompt keeps hard content rules")
|
||||
expect("CURRENT_DAY_SOURCES" in text, "prompt labels current-day facts")
|
||||
expect("STYLE_EXAMPLES" in text, "prompt labels style examples")
|
||||
expect("WRITING_PROFILE" in text, "prompt labels the writing profile")
|
||||
expect("{{transformation_instructions}}" in text, "prompt injects compiled transformation instructions")
|
||||
expect("{{detail_instructions}}" in text, "prompt injects compiled detail instructions")
|
||||
@@ -253,8 +250,9 @@ def main() -> None:
|
||||
intern = intern_of(gen.json())
|
||||
expect(MIXED_SOURCES_INSTRUCTION in intern, "unified mixed-source instruction reaches the model")
|
||||
expect("CURRENT_DAY_SOURCES" in intern, "day facts are labeled")
|
||||
expect("STYLE_EXAMPLES" in intern, "style examples are labeled")
|
||||
expect("WRITING_PROFILE" in intern, "writing profile is labeled")
|
||||
expect("\nSTYLE_EXAMPLES\n" not in intern, "default voice does not attach a style-example section")
|
||||
expect("STYLE_EXAMPLES" not in intern, "default voice has no orphaned STYLE_EXAMPLES reference")
|
||||
expect("WRITING_PROFILE" in intern, "writing profile heading or instruction remains")
|
||||
expect("Überarbeite den Text substanziell" in intern, "default transformation policy reaches the prompt")
|
||||
expect("Erhalte sämtliche belegten Ereignisse" in intern, "default detail policy reaches the prompt")
|
||||
expect("Neutraler Journalstil" in intern, "without a confirmed profile the neutral fallback is used")
|
||||
|
||||
@@ -9,10 +9,8 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-journal-eval-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from db import init_db
|
||||
from journal_editorial import GENERATE_SEED_REVISION
|
||||
@@ -49,7 +47,7 @@ def main() -> None:
|
||||
expect("{{source_mode_instructions}}" not in templates[VARIANT_CURRENT], "current variant has no source-mode placeholder")
|
||||
expect("Zwinge nicht den gesamten Tag in einen einzigen Quellenmodus." in templates[VARIANT_CURRENT], "current variant has mixed-source instruction")
|
||||
expect("ich gieng zum laden" not in templates[VARIANT_CURRENT], "current variant has no synthetic examples")
|
||||
expect(GENERATE_SEED_REVISION == "2026-08-27-journal-mixed-sources-v1", "eval tracks the seeded revision constant")
|
||||
expect(GENERATE_SEED_REVISION == "2026-08-29-voice-legacy-immutable-v1", "eval tracks the seeded revision constant")
|
||||
|
||||
required_classes = {
|
||||
"already_narrative_with_errors",
|
||||
|
||||
@@ -12,10 +12,8 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
FRONTEND = ROOT.parent / "frontend"
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-journal-guidelines-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from db import get_db, init_db
|
||||
@@ -60,7 +58,6 @@ HARD_FACTS = (
|
||||
"Plan und Vollzug",
|
||||
"Verneinungen",
|
||||
"Unsicherheiten",
|
||||
"STYLE_EXAMPLES dienen ausschließlich als Stilreferenz",
|
||||
"[[PERSON:01]]",
|
||||
)
|
||||
BANNED_CODE_PHRASES = (
|
||||
@@ -101,6 +98,11 @@ REQUIRED_KEYS = {
|
||||
("voice", "light"),
|
||||
("voice", "noticeable"),
|
||||
("voice", "clear"),
|
||||
("voice", "with_examples"),
|
||||
("voice", "legacy_neutral"),
|
||||
("voice", "legacy_light"),
|
||||
("voice", "legacy_noticeable"),
|
||||
("voice", "legacy_clear"),
|
||||
("narrative", "chronicle"),
|
||||
("narrative", "structured"),
|
||||
("narrative", "weighted"),
|
||||
@@ -209,7 +211,9 @@ def test_runtime_has_no_numeric_policy() -> None:
|
||||
continue
|
||||
expect(not has_token(text, token), f"{path.name} has no {token}")
|
||||
day = (FRONTEND / "src" / "pages" / "JournalDayPage.jsx").read_text(encoding="utf-8")
|
||||
expect('type="range"' not in day, "journal page has no sliders")
|
||||
expect("Stilquellen" in day, "voice select can show which style sources apply")
|
||||
expect("type=\"range\"" not in day, "journal page has no extra sliders for style context")
|
||||
expect(day.count("<select") == 1, "journal page maps four slots onto one select, not extra style-context fields")
|
||||
expect("policy-slider" not in day, "journal page has no slider class")
|
||||
expect("SLOT_SELECTS" in day, "journal page names the four selects")
|
||||
expect(day.count("slot:") >= 4, "journal page has four independent slots")
|
||||
@@ -224,7 +228,10 @@ def test_runtime_has_no_numeric_policy() -> None:
|
||||
admin = (FRONTEND / "src" / "pages" / "AdminGenerationPage.jsx").read_text(encoding="utf-8")
|
||||
expect("<textarea" not in admin.split("generation-admin-editor")[0], "admin overview has no textareas")
|
||||
expect(admin.count("<textarea") == 1, "admin opens one instruction editor at a time")
|
||||
expect("Öffnen" in admin, "admin overview has open action")
|
||||
expect("Stilquellen für diese Ausprägung" in admin, "admin edits style context with the instruction")
|
||||
expect("Vorgänger" in admin, "admin shows predecessor or clone origin")
|
||||
expect("include_core" in admin, "admin names core inclusion")
|
||||
expect("Writing-Profile-Core" in admin, "admin labels core in German product terms")
|
||||
expect("backend/config/" not in admin, "admin copy does not advertise seed file paths")
|
||||
expect("Quellenmodus" not in admin, "admin has no source-mode management")
|
||||
expect("source_mode" not in admin, "admin source has no source_mode slot")
|
||||
@@ -239,6 +246,8 @@ def test_runtime_has_no_numeric_policy() -> None:
|
||||
expect("Chunks technisch verarbeitet" in trace_ui, "trace separates technical chunk coverage")
|
||||
expect("Semantische Identitätserkennung" in trace_ui, "trace names semantic uncertainty")
|
||||
expect("nicht garantiert" in trace_ui, "trace does not claim semantic completeness")
|
||||
expect("Stilanwendung" in trace_ui, "trace shows requested versus effective style application")
|
||||
expect("cloned_from" in trace_ui, "trace can show the predecessor id")
|
||||
expect("Gespeicherter Entwurf" in trace_ui, "trace shows the stored draft")
|
||||
expect("Technisch verarbeitete Chunks bedeuten keine vollständige" in trace_ui, "trace explains coverage is not identity certainty")
|
||||
|
||||
@@ -275,8 +284,22 @@ def test_seed_and_compiler() -> None:
|
||||
"default narrative instruction matches the seed",
|
||||
)
|
||||
expect(defaults.seed_revision == SEED["seed_revision"], "compiled policy names the seed revision")
|
||||
expect(defaults.style_context["include_core"] is True, "default voice includes core")
|
||||
expect(defaults.style_context["include_facet"] is True, "default voice includes facet")
|
||||
expect(defaults.style_context["include_traits"] is True, "default voice includes traits")
|
||||
expect(defaults.style_context["include_style_examples"] is False, "default voice omits style examples")
|
||||
expect("source_mode_instructions" not in defaults.instructions, "compiler has no source-mode instruction")
|
||||
|
||||
free = compile_selection({**default_selection_ids(), "voice_id": seed_id("voice", "neutral")})
|
||||
expect(free.style_context == {
|
||||
"include_core": False,
|
||||
"include_facet": False,
|
||||
"include_traits": False,
|
||||
"include_style_examples": False,
|
||||
}, "profile-free voice selects no style sources")
|
||||
examples = compile_selection({**default_selection_ids(), "voice_id": seed_id("voice", "with_examples")})
|
||||
expect(all(examples.style_context.values()), "with-examples voice selects all style sources")
|
||||
|
||||
low = compile_selection(low_ids())
|
||||
high = compile_selection(high_ids())
|
||||
expect(low.keys["transformation"] == "correction", "low transformation is named")
|
||||
@@ -389,18 +412,19 @@ def test_prompt_contract() -> None:
|
||||
expect("{{editorial_mode}}" not in text, "prompt has no editorial_mode placeholder")
|
||||
expect("{{editorial_instructions}}" not in text, "prompt has no editorial_instructions placeholder")
|
||||
expect(MIXED_SOURCES_INSTRUCTION in text, "prompt contains the mixed-source instruction")
|
||||
expect("STYLE_EXAMPLES dienen ausschließlich" not in text, "standing prompt has no orphaned STYLE_EXAMPLES sentence")
|
||||
for fact in HARD_FACTS:
|
||||
expect(fact in text, f"hard fact rule remains: {fact}")
|
||||
expect("ich gieng zum laden" not in text, "no synthetic prose example")
|
||||
expect("nachbarhund im garten" not in text, "no synthetic notes example")
|
||||
expect("EDITORIAL_MODE" not in text, "source mode is not a user-facing prompt heading")
|
||||
expect(GENERATE_SEED_REVISION == "2026-08-27-journal-mixed-sources-v1", "seed revision constant tracks mixed sources")
|
||||
expect(GENERATE_SEED_REVISION == "2026-08-29-voice-legacy-immutable-v1", "seed revision constant tracks immutable voice catalog")
|
||||
with get_db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT seed_revision, template, default_template FROM ai_prompts WHERE slug = ?",
|
||||
("mvp.journal_generate",),
|
||||
).fetchone()
|
||||
expect(row["seed_revision"] == "2026-08-27-journal-mixed-sources-v1", "untouched default is updated to mixed sources")
|
||||
expect(row["seed_revision"] == "2026-08-29-voice-legacy-immutable-v1", "untouched default is updated to immutable voice catalog")
|
||||
expect(row["template"] == row["default_template"], "untouched template matches the seed")
|
||||
expect("source_mode" not in (SEED.get("slots") or {}), "source modes stay out of the seed")
|
||||
|
||||
@@ -1019,7 +1043,7 @@ def main() -> None:
|
||||
).fetchone()
|
||||
expect("{{transformation_instructions}}" in (row["default_template"] or ""), "default template still tracks mixed sources")
|
||||
expect(MIXED_SOURCES_INSTRUCTION in (row["default_template"] or ""), "default template has mixed-source instruction")
|
||||
expect(row["seed_revision"] == "2026-08-27-journal-mixed-sources-v1", "revision updates even when template is custom")
|
||||
expect(row["seed_revision"] == "2026-08-29-voice-legacy-immutable-v1", "revision updates even when template is custom")
|
||||
|
||||
readable = snapshot_summary(
|
||||
{
|
||||
|
||||
@@ -11,10 +11,8 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-journal-narration-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from db import get_db, init_db
|
||||
@@ -51,7 +49,7 @@ def test_active_prompt_contract() -> None:
|
||||
text = prompt.get("template") or ""
|
||||
expect("INHALTSTREUE" in text, "active prompt keeps hard content rules")
|
||||
expect("CURRENT_DAY_SOURCES" in text, "active prompt labels current-day facts")
|
||||
expect("STYLE_EXAMPLES" in text, "active prompt labels style examples")
|
||||
expect("{{style_examples}}" in text, "active prompt still has the style-examples slot")
|
||||
expect("Rechtschreibung" in text or "korrigieren" in text, "active prompt allows spelling and grammar fixes")
|
||||
expect("Verneinungen" in text and "Unsicherheiten" in text, "active prompt keeps semantic uncertainty")
|
||||
expect("keine neuen tatsachen" in text.lower(), "active prompt still forbids new facts")
|
||||
@@ -67,7 +65,7 @@ def test_active_prompt_contract() -> None:
|
||||
"SELECT seed_revision, template, default_template FROM ai_prompts WHERE slug = ?",
|
||||
("mvp.journal_generate",),
|
||||
).fetchone()
|
||||
expect(row["seed_revision"] == "2026-08-27-journal-mixed-sources-v1", "system prompt revision is stored")
|
||||
expect(row["seed_revision"] == "2026-08-29-voice-legacy-immutable-v1", "system prompt revision is stored")
|
||||
expect(row["template"] == row["default_template"], "untouched install uses the seeded template")
|
||||
|
||||
|
||||
@@ -313,7 +311,7 @@ def main() -> None:
|
||||
("mvp.journal_generate",),
|
||||
).fetchone()
|
||||
expect("INHALTSTREUE" in (row["default_template"] or ""), "default template still tracks the seed")
|
||||
expect(row["seed_revision"] == "2026-08-27-journal-mixed-sources-v1", "revision updates even when template is custom")
|
||||
expect(row["seed_revision"] == "2026-08-29-voice-legacy-immutable-v1", "revision updates even when template is custom")
|
||||
|
||||
print("journal narration tests passed.")
|
||||
|
||||
|
||||
@@ -6,14 +6,14 @@ import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from datetime import date
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-opening-test.sqlite")
|
||||
os.environ["KANSHO_MEDIA_ROOT"] = str(Path(tempfile.gettempdir()) / "kansho-opening-media")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
Path(os.environ["KANSHO_MEDIA_ROOT"]).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
@@ -23,6 +23,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 +60,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 +162,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
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
"""Style-application variants control which writing-profile parts reach generate."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from db import get_db, init_db
|
||||
from journal_editorial import (
|
||||
compile_journal_style_application,
|
||||
style_application_trace,
|
||||
)
|
||||
from journal_generation_policy import (
|
||||
clone_guideline,
|
||||
compile_selection,
|
||||
default_selection_ids,
|
||||
get_guideline,
|
||||
save_selection,
|
||||
seed_generation_instructions,
|
||||
)
|
||||
from journal_generate import pack_narration_context
|
||||
from main import app
|
||||
from privacy_gateway import install_test_recorder, reset_debug
|
||||
from prompt_budget import JournalBudget
|
||||
from writing_profile_store import (
|
||||
compile_task_brief,
|
||||
import_text,
|
||||
set_lifecycle,
|
||||
update_facet,
|
||||
upsert_trait,
|
||||
)
|
||||
|
||||
|
||||
CORE_MARK = "ZXCORE_MARKER kurze trockene Saetze"
|
||||
FACET_MARK = "ZXFACET_MARKER ruhige Abendreflexion"
|
||||
TRAIT_MARK = "ZXTRAIT_MARKER keine rhythmischen Aufzaehlungen"
|
||||
EXAMPLE_MARK = "ZXEXAMPLE_MARKER Der Hafen blieb hinter der Faehre"
|
||||
TODAY_MARK = "ZXTODAY_MARKER am heutigen Markt"
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
def header(token: str) -> dict:
|
||||
return {"X-Auth-Token": token}
|
||||
|
||||
|
||||
def intern_of(payload: dict) -> str:
|
||||
for stage in (payload.get("trace") or {}).get("stages") or []:
|
||||
if stage.get("purpose") == "journal_generate":
|
||||
return stage.get("intern") or ""
|
||||
return (payload.get("trace") or {}).get("intern") or ""
|
||||
|
||||
|
||||
def style_region(intern: str) -> str:
|
||||
return (intern or "").split("\nCURRENT_DAY_SOURCES\n")[0]
|
||||
|
||||
|
||||
def has_heading(intern: str, title: str) -> bool:
|
||||
body = intern or ""
|
||||
return f"\n{title}\n" in body or body.startswith(f"{title}\n")
|
||||
|
||||
|
||||
def seed_id(slot: str, key: str) -> str:
|
||||
from journal_generation_policy import load_seed_document
|
||||
|
||||
seed = load_seed_document()
|
||||
for item in (seed.get("slots") or {}).get(slot, {}).get("variants") or []:
|
||||
if item.get("guideline_key") == key:
|
||||
return item["id"]
|
||||
raise SystemExit(f"FAIL: missing seed {slot}/{key}")
|
||||
|
||||
|
||||
def selection_of(voice_key: str) -> dict[str, str]:
|
||||
ids = default_selection_ids()
|
||||
ids["voice_id"] = seed_id("voice", voice_key)
|
||||
return ids
|
||||
|
||||
|
||||
def ensure_local_profile(profile_id: str = "style-context-local") -> str:
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT OR IGNORE INTO profiles (id, email, name, password_hash, role)
|
||||
VALUES (?, ?, ?, ?, 'user')
|
||||
""",
|
||||
(profile_id, f"{profile_id}@example.test", "Style", "x"),
|
||||
)
|
||||
return profile_id
|
||||
|
||||
|
||||
def install_profile(profile_id: str) -> None:
|
||||
update_facet(profile_id, "core", value=CORE_MARK)
|
||||
update_facet(profile_id, "autobiographical_journal", value=FACET_MARK)
|
||||
upsert_trait(
|
||||
profile_id,
|
||||
slug="journal-rhythm",
|
||||
facet_key="autobiographical_journal",
|
||||
label="Rhythmus",
|
||||
statement=TRAIT_MARK,
|
||||
origin="manual",
|
||||
)
|
||||
set_lifecycle(profile_id, "confirmed")
|
||||
import_text(
|
||||
profile_id,
|
||||
EXAMPLE_MARK + " in knappen ruhigen Saetzen ohne Pathoswolken.",
|
||||
occurred_at="2026-07-01",
|
||||
)
|
||||
|
||||
|
||||
def test_compile_flags() -> None:
|
||||
init_db()
|
||||
profile_id = ensure_local_profile()
|
||||
install_profile(profile_id)
|
||||
full = compile_task_brief(profile_id)
|
||||
expect(CORE_MARK in full and FACET_MARK in full and TRAIT_MARK in full, "full brief keeps selected parts")
|
||||
core_only = compile_task_brief(
|
||||
profile_id,
|
||||
include_core=True,
|
||||
include_facet=False,
|
||||
include_traits=False,
|
||||
)
|
||||
expect(CORE_MARK in core_only, "core-only brief keeps core")
|
||||
expect(FACET_MARK not in core_only, "core-only brief omits facet")
|
||||
expect(TRAIT_MARK not in core_only, "core-only brief omits traits")
|
||||
none = compile_task_brief(
|
||||
profile_id,
|
||||
include_core=False,
|
||||
include_facet=False,
|
||||
include_traits=False,
|
||||
)
|
||||
expect(none == "", "no selected profile parts yield an empty brief")
|
||||
bundle = compile_journal_style_application(profile_id, compile_selection(selection_of("neutral")).style_context)
|
||||
expect(bundle["profile_block"] == "", "profile-free omits the wrapped profile block")
|
||||
expect(bundle["examples_block"] == "", "profile-free omits the wrapped examples block")
|
||||
|
||||
|
||||
def test_budget_omission_in_effective_trace() -> None:
|
||||
init_db()
|
||||
prompt = {
|
||||
"id": "style-pack",
|
||||
"slug": "mvp.journal_generate",
|
||||
"prompt_type": "base",
|
||||
"template": "{{writing_profile}}{{style_examples}}DAY\n{{reconstruction}}\nOLD\n{{existing_text}}\n",
|
||||
}
|
||||
assembled = {
|
||||
"writing_profile": "WRITING_PROFILE\nCore: kurze Sätze.\n",
|
||||
"reconstruction": "Heute Markt.",
|
||||
"style_examples": "",
|
||||
"existing_text": "",
|
||||
}
|
||||
huge = "Stil " + ("Beispielwort " * 400)
|
||||
from engine import preview_prompt
|
||||
from prompt_budget import estimate_tokens
|
||||
|
||||
rendered = preview_prompt(prompt, assembled)["rendered"]
|
||||
budget = JournalBudget(
|
||||
model="fake",
|
||||
purpose="journal_generate",
|
||||
effective_context_window=32_768,
|
||||
reserved_output_tokens=256,
|
||||
safety_margin=0.15,
|
||||
available_input_tokens=estimate_tokens(rendered) + 80,
|
||||
chars_per_token=2.0,
|
||||
)
|
||||
packed, dropped = pack_narration_context(
|
||||
prompt,
|
||||
budget,
|
||||
assembled,
|
||||
style_examples=huge,
|
||||
existing_text="Bestehende Fassung",
|
||||
include_existing=True,
|
||||
)
|
||||
expect("style_examples" in dropped, "budget drops style examples first")
|
||||
expect("Beispielwort" not in (packed.get("style_examples") or ""), "dropped examples leave the packed prompt")
|
||||
compiled = compile_selection(selection_of("with_examples"))
|
||||
bundle = {
|
||||
"requested": dict(compiled.style_context),
|
||||
"brief": "Core: kurze Sätze.",
|
||||
"profile_block": assembled["writing_profile"],
|
||||
"examples_block": huge,
|
||||
"example_rows": [{"kind": "imported_text", "excerpt": huge}],
|
||||
"omitted": [],
|
||||
"effective": {"neutral_fallback": False, "trait_count": 0},
|
||||
}
|
||||
trace = style_application_trace(compiled, bundle, dropped=dropped)
|
||||
expect(trace["effective"]["style_example_count"] == 0, "effective trace has no examples after budget drop")
|
||||
expect(
|
||||
any(item.get("part") == "style_examples" and item.get("reason") == "budget" for item in trace["omitted"]),
|
||||
"budget drop is recorded on the effective trace",
|
||||
)
|
||||
expect(trace["id"] == seed_id("voice", "with_examples"), "trace keeps the requested voice id")
|
||||
expect(trace["revision"] == 1, "trace keeps the requested revision")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
test_compile_flags()
|
||||
test_budget_omission_in_effective_trace()
|
||||
|
||||
from tests.harness import reset_postgres_data
|
||||
|
||||
reset_postgres_data()
|
||||
reset_debug()
|
||||
with TestClient(app) as client:
|
||||
setup = client.post(
|
||||
"/api/auth/setup",
|
||||
json={"email": "voice@example.test", "name": "Ada", "password": "test-pass"},
|
||||
)
|
||||
headers = header(setup.json()["token"])
|
||||
profile_id = setup.json()["profile_id"]
|
||||
install_profile(profile_id)
|
||||
|
||||
space = client.post("/api/journal/spaces", headers=headers, json={"title": "Stil"})
|
||||
day = client.post(
|
||||
f"/api/journal/spaces/{space.json()['id']}/days",
|
||||
headers=headers,
|
||||
json={"calendar_date": "2026-08-29"},
|
||||
)
|
||||
conv = client.post(
|
||||
f"/api/journal/days/{day.json()['day']['id']}/conversations",
|
||||
headers=headers,
|
||||
json={"title": "Tag"},
|
||||
)
|
||||
turn = client.post(
|
||||
f"/api/journal/conversations/{conv.json()['id']}/turn",
|
||||
headers=headers,
|
||||
json={"body": f"Ich war am Markt. {TODAY_MARK}. Vielleicht bleibe ich kürzer."},
|
||||
)
|
||||
expect(turn.status_code == 200, f"turn {turn.status_code}")
|
||||
day_id = day.json()["day"]["id"]
|
||||
conv_id = conv.json()["id"]
|
||||
|
||||
def generate(voice_key: str) -> dict:
|
||||
reset_debug()
|
||||
recorder = install_test_recorder()
|
||||
result = client.post(
|
||||
f"/api/journal/days/{day_id}/generate",
|
||||
headers=headers,
|
||||
json={
|
||||
"conversation_ids": [conv_id],
|
||||
"generation_selection": selection_of(voice_key),
|
||||
"remember_generation_selection": False,
|
||||
},
|
||||
)
|
||||
expect(result.status_code == 200, f"{voice_key} generate {result.status_code}")
|
||||
payload = result.json()
|
||||
intern = intern_of(payload)
|
||||
style = style_region(intern)
|
||||
app_trace = (payload.get("trace") or {}).get("style_application") or {}
|
||||
calls = [item.get("purpose") for item in recorder]
|
||||
expect(calls == ["journal_generate"], f"{voice_key} still uses exactly one narration call")
|
||||
expect(app_trace.get("id") == seed_id("voice", voice_key), f"{voice_key} id reaches the trace")
|
||||
expect(app_trace.get("key") == voice_key, f"{voice_key} key reaches the trace")
|
||||
expect(app_trace.get("revision") == 1, f"{voice_key} revision reaches the trace")
|
||||
expect(
|
||||
(payload.get("trace") or {}).get("generation_selection", {}).get("ids", {}).get("voice")
|
||||
== seed_id("voice", voice_key),
|
||||
f"{voice_key} selection id matches prompt/trace",
|
||||
)
|
||||
expect(TODAY_MARK not in style, f"{voice_key} does not use today as a style example")
|
||||
expect(TODAY_MARK in intern.split("\nCURRENT_DAY_SOURCES\n")[-1], f"{voice_key} keeps today as content")
|
||||
expect("keine neuen Tatsachen" in intern, f"{voice_key} keeps fact fidelity")
|
||||
expect("[[PERSON:01]]" in intern, f"{voice_key} keeps privacy placeholders")
|
||||
return {"payload": payload, "intern": intern, "style": style, "trace": app_trace}
|
||||
|
||||
free = generate("neutral")
|
||||
expect(not has_heading(free["intern"], "WRITING_PROFILE"), "profile-free omits the profile heading")
|
||||
expect(not has_heading(free["intern"], "STYLE_EXAMPLES"), "profile-free omits the examples heading")
|
||||
expect("STYLE_EXAMPLES" not in free["intern"], "profile-free has no orphaned STYLE_EXAMPLES reference")
|
||||
expect(CORE_MARK not in free["intern"], "profile-free sends no core")
|
||||
expect(FACET_MARK not in free["intern"], "profile-free sends no facet")
|
||||
expect(TRAIT_MARK not in free["intern"], "profile-free sends no traits")
|
||||
expect(EXAMPLE_MARK not in free["intern"], "profile-free sends no style examples")
|
||||
expect(free["trace"]["effective"]["include_core"] is False, "profile-free effective core is no")
|
||||
expect(free["trace"]["effective"]["style_example_count"] == 0, "profile-free effective examples are zero")
|
||||
|
||||
light = generate("light")
|
||||
expect(CORE_MARK in light["style"], "light sends core")
|
||||
expect(FACET_MARK not in light["intern"], "light does not send facet even indirectly")
|
||||
expect(TRAIT_MARK not in light["intern"], "light does not send traits even indirectly")
|
||||
expect(EXAMPLE_MARK not in light["intern"], "light does not send examples even indirectly")
|
||||
expect(has_heading(light["intern"], "WRITING_PROFILE"), "light keeps a profile heading")
|
||||
expect(not has_heading(light["intern"], "STYLE_EXAMPLES"), "light omits the examples heading")
|
||||
expect("STYLE_EXAMPLES" not in light["intern"], "light has no orphaned STYLE_EXAMPLES reference")
|
||||
expect(light["trace"]["effective"]["include_core"] is True, "light effective core is yes")
|
||||
expect(light["trace"]["effective"]["include_facet"] is False, "light effective facet is no")
|
||||
expect(light["trace"]["effective"]["trait_count"] == 0, "light effective traits are zero")
|
||||
|
||||
clear = generate("clear")
|
||||
expect(CORE_MARK in clear["style"], "clear sends core")
|
||||
expect(FACET_MARK in clear["style"], "clear sends the relevant facet")
|
||||
expect(TRAIT_MARK in clear["style"], "clear sends traits")
|
||||
expect(EXAMPLE_MARK not in clear["intern"], "clear does not send examples")
|
||||
expect(not has_heading(clear["intern"], "STYLE_EXAMPLES"), "clear omits the examples heading")
|
||||
expect("STYLE_EXAMPLES" not in clear["intern"], "clear has no orphaned STYLE_EXAMPLES reference")
|
||||
expect(clear["trace"]["effective"]["include_core"] is True, "clear effective core is yes")
|
||||
expect(clear["trace"]["effective"]["include_facet"] is True, "clear effective facet is yes")
|
||||
expect(clear["trace"]["effective"]["trait_count"] >= 1, "clear effective traits are counted")
|
||||
expect(clear["trace"]["effective"]["style_example_count"] == 0, "clear effective examples are zero")
|
||||
|
||||
examples = generate("with_examples")
|
||||
expect(CORE_MARK in examples["style"], "with-examples sends core")
|
||||
expect(FACET_MARK in examples["style"], "with-examples sends facet")
|
||||
expect(TRAIT_MARK in examples["style"], "with-examples sends traits")
|
||||
expect(EXAMPLE_MARK in examples["style"], "with-examples sends style examples")
|
||||
expect(has_heading(examples["intern"], "STYLE_EXAMPLES"), "with-examples labels the examples block")
|
||||
expect("ausschließlich als Stilreferenz" in examples["intern"] or "sprachliche" in examples["style"], "examples stay style-only")
|
||||
expect("keine Tatsachen des heutigen" in examples["style"] or "nicht übernommen" in examples["style"], "example facts are forbidden")
|
||||
expect(examples["trace"]["effective"]["style_example_count"] >= 1, "with-examples effective count is used")
|
||||
expect(EXAMPLE_MARK not in (examples["payload"].get("body") or ""), "example facts are not copied into today's draft")
|
||||
|
||||
settings = client.get("/api/journal/generation-settings", headers=headers).json()
|
||||
voice_options = settings["options"]["voice"]
|
||||
free_opt = next(item for item in voice_options if item["id"] == seed_id("voice", "neutral"))
|
||||
expect(free_opt["style_context"]["include_core"] is False, "generation-settings expose style context without prompt text")
|
||||
expect("instruction" not in free_opt, "generation-settings still hide prompt wording")
|
||||
|
||||
save_selection(profile_id, selection_of("neutral"))
|
||||
remembered = generate("noticeable")
|
||||
expect(CORE_MARK in remembered["style"], "legacy noticeable remains selectable")
|
||||
profile_run = client.post(
|
||||
f"/api/journal/days/{day_id}/generate",
|
||||
headers=headers,
|
||||
json={"conversation_ids": [conv_id]},
|
||||
)
|
||||
expect(profile_run.status_code == 200, f"stored selection generate {profile_run.status_code}")
|
||||
stored_intern = intern_of(profile_run.json())
|
||||
expect(not has_heading(stored_intern, "WRITING_PROFILE"), "stored profile-free selection stays profile-free")
|
||||
expect(CORE_MARK not in stored_intern, "stored profile-free selection still omits core")
|
||||
|
||||
cloned = clone_guideline(seed_id("voice", "clear"))
|
||||
original_instruction = get_guideline(seed_id("voice", "clear"), include_instruction=True)["instruction"]
|
||||
with get_db() as conn:
|
||||
seed_generation_instructions(conn)
|
||||
expect(
|
||||
get_guideline(seed_id("voice", "clear"), include_instruction=True)["instruction"] == original_instruction,
|
||||
"seed refresh does not replace the published original with a clone",
|
||||
)
|
||||
expect(
|
||||
get_guideline(cloned["id"], include_instruction=True)["style_context"]["include_core"] is True,
|
||||
"cloned voice keeps the structured style context",
|
||||
)
|
||||
|
||||
def compile_one(key: str) -> str:
|
||||
bundle = compile_journal_style_application(profile_id, compile_selection(selection_of(key)).style_context)
|
||||
return (bundle.get("brief") or "") + "\n" + (bundle.get("style_examples") or "")
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
first = pool.submit(compile_one, "neutral")
|
||||
second = pool.submit(compile_one, "with_examples")
|
||||
free_text = first.result()
|
||||
example_text = second.result()
|
||||
expect(CORE_MARK not in free_text, "parallel profile-free compile stays empty")
|
||||
expect(CORE_MARK in example_text and EXAMPLE_MARK in example_text, "parallel with-examples compile keeps all parts")
|
||||
expect(EXAMPLE_MARK not in free_text, "parallel requests do not mix style configurations")
|
||||
|
||||
print("journal style context tests passed.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,355 @@
|
||||
"""Legacy comparison voices and immutable seed IDs after style-context control."""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from db import get_db, init_db
|
||||
from journal_generation_policy import (
|
||||
PURPOSE_JOURNAL,
|
||||
archive_guideline,
|
||||
clone_guideline,
|
||||
compile_selection,
|
||||
default_selection_ids,
|
||||
get_guideline,
|
||||
list_guidelines,
|
||||
load_seed_document,
|
||||
load_selection,
|
||||
publish_guideline,
|
||||
save_selection,
|
||||
seed_generation_instructions,
|
||||
update_guideline,
|
||||
)
|
||||
from journal_editorial import format_style_examples
|
||||
from main import app
|
||||
from privacy_gateway import install_test_recorder, reset_debug
|
||||
|
||||
|
||||
# Reconstructed from git HEAD `backend/config/generation_instructions.seed.json`
|
||||
# (commit 4f37991, seed_revision 2026-08-27-generation-guidelines-v1).
|
||||
HEAD_VOICE = {
|
||||
"neutral": {
|
||||
"id": "journal-generate-voice-neutral",
|
||||
"instruction": "Schreibe in einem neutralen Journalstil. Das Writing Profile höchstens als leise Tendenz.",
|
||||
"label": "neutral",
|
||||
"summary": "Neutraler Journalstil, Writing Profile nur als leise Tendenz.",
|
||||
},
|
||||
"light": {
|
||||
"id": "journal-generate-voice-light",
|
||||
"instruction": "Nimm Rhythmus und Wortwahl des Writing Profiles zurückhaltend auf.",
|
||||
"label": "dezent",
|
||||
"summary": "Rhythmus und Wortwahl des Writing Profiles zurückhaltend.",
|
||||
},
|
||||
"noticeable": {
|
||||
"id": "journal-generate-voice-noticeable",
|
||||
"instruction": "Wende das Writing Profile spürbar an, ohne es in den Vordergrund zu stellen.",
|
||||
"label": "spürbar",
|
||||
"summary": "Writing Profile spürbar, ohne in den Vordergrund zu treten.",
|
||||
},
|
||||
"clear": {
|
||||
"id": "journal-generate-voice-clear",
|
||||
"instruction": "Wende Rhythmus, Wortwahl und Reflexionsdichte des Writing Profiles deutlich an, ohne den Text künstlich zu literarisieren.",
|
||||
"label": "deutlich",
|
||||
"summary": "Rhythmus, Wortwahl und Reflexionsdichte des Writing Profiles deutlich.",
|
||||
},
|
||||
}
|
||||
FULL_STYLE_CONTEXT = {
|
||||
"include_core": True,
|
||||
"include_facet": True,
|
||||
"include_traits": True,
|
||||
"include_style_examples": True,
|
||||
}
|
||||
CURRENT_VOICE_IDS = {
|
||||
"neutral": "journal-generate-voice-neutral",
|
||||
"light": "journal-generate-voice-light",
|
||||
"noticeable": "journal-generate-voice-noticeable",
|
||||
"clear": "journal-generate-voice-clear",
|
||||
"with_examples": "journal-generate-voice-with-examples",
|
||||
}
|
||||
LEGACY_KEYS = ("legacy_neutral", "legacy_light", "legacy_noticeable", "legacy_clear")
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
def header(token: str) -> dict:
|
||||
return {"X-Auth-Token": token}
|
||||
|
||||
|
||||
def intern_of(payload: dict) -> str:
|
||||
for stage in (payload.get("trace") or {}).get("stages") or []:
|
||||
if stage.get("purpose") == "journal_generate":
|
||||
return stage.get("intern") or ""
|
||||
return (payload.get("trace") or {}).get("intern") or ""
|
||||
|
||||
|
||||
def seed_id(slot: str, key: str) -> str:
|
||||
seed = load_seed_document()
|
||||
for item in (seed.get("slots") or {}).get(slot, {}).get("variants") or []:
|
||||
if item.get("guideline_key") == key:
|
||||
return item["id"]
|
||||
raise SystemExit(f"FAIL: missing seed {slot}/{key}")
|
||||
|
||||
|
||||
def voice_rows() -> list[dict]:
|
||||
return list_guidelines(PURPOSE_JOURNAL, slot="voice", include_instruction=True)
|
||||
|
||||
|
||||
def snapshot_current_voices() -> dict:
|
||||
return {
|
||||
item["id"]: {
|
||||
"instruction": item["instruction"],
|
||||
"label": item["label"],
|
||||
"summary": item["summary"],
|
||||
"style_context": dict(item["style_context"]),
|
||||
"is_default": item["is_default"],
|
||||
"revision": item["revision"],
|
||||
"status": item["status"],
|
||||
}
|
||||
for item in voice_rows()
|
||||
if item["id"] in CURRENT_VOICE_IDS.values()
|
||||
}
|
||||
|
||||
|
||||
def test_current_variants_and_legacy_seed() -> None:
|
||||
init_db()
|
||||
before = snapshot_current_voices()
|
||||
expect(CURRENT_VOICE_IDS["clear"] in before, "current default voice id remains")
|
||||
expect(before[CURRENT_VOICE_IDS["clear"]]["is_default"] is True, "current default stays on Persönliche Stimme deutlich")
|
||||
expect(
|
||||
before[CURRENT_VOICE_IDS["neutral"]]["style_context"]["include_core"] is False,
|
||||
"current profile-free voice keeps an empty style context",
|
||||
)
|
||||
expect(
|
||||
default_selection_ids()["voice_id"] == CURRENT_VOICE_IDS["clear"],
|
||||
"catalog default still points at the current clear id",
|
||||
)
|
||||
|
||||
with get_db() as conn:
|
||||
seed_generation_instructions(conn)
|
||||
seed_generation_instructions(conn)
|
||||
after = snapshot_current_voices()
|
||||
expect(before == after, "reseeding does not change current voice ids or semantics")
|
||||
|
||||
legacy = [item for item in voice_rows() if item["guideline_key"] in LEGACY_KEYS]
|
||||
expect(len(legacy) == 4, "legacy comparison voices are inserted once")
|
||||
expect(len({item["id"] for item in legacy}) == 4, "legacy voices have distinct ids")
|
||||
expect(all(not item["is_default"] for item in legacy), "legacy voices are not default")
|
||||
expect(all(item["status"] == "active" for item in legacy), "legacy voices are selectable")
|
||||
expect(
|
||||
all(item["style_context"] == FULL_STYLE_CONTEXT for item in legacy),
|
||||
"legacy voices reconstruct the former full style context",
|
||||
)
|
||||
by_key = {item["guideline_key"]: item for item in legacy}
|
||||
for old_key, spec in HEAD_VOICE.items():
|
||||
row = by_key[f"legacy_{old_key}"]
|
||||
expect(row["id"] != spec["id"], f"legacy {old_key} uses a new stable id")
|
||||
expect(row["instruction"] == spec["instruction"], f"legacy {old_key} keeps the reconstructed instruction")
|
||||
expect("Legacy – vor Stilkontextsteuerung" in row["label"], f"legacy {old_key} is labeled as pre-style-context")
|
||||
expect(row["id"].startswith("journal-generate-voice-legacy-"), f"legacy {old_key} id is namespaced")
|
||||
|
||||
|
||||
def test_stored_selection_and_clones_and_archives() -> None:
|
||||
init_db()
|
||||
profile_id = "legacy-immutable-user"
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT OR IGNORE INTO profiles (id, email, name, password_hash, role)
|
||||
VALUES (?, ?, ?, ?, 'user')
|
||||
""",
|
||||
(profile_id, "legacy@example.test", "Legacy", "x"),
|
||||
)
|
||||
stored = default_selection_ids()
|
||||
stored["voice_id"] = CURRENT_VOICE_IDS["neutral"]
|
||||
save_selection(profile_id, stored)
|
||||
cloned = clone_guideline(CURRENT_VOICE_IDS["clear"])
|
||||
original_clone_instruction = "CLONE MUST STAY"
|
||||
update_guideline(
|
||||
cloned["id"],
|
||||
{
|
||||
"guideline_key": "clone_clear",
|
||||
"label": "Klon",
|
||||
"summary": "Admin-Klon",
|
||||
"instruction": original_clone_instruction,
|
||||
"style_context": {
|
||||
"include_core": True,
|
||||
"include_facet": False,
|
||||
"include_traits": False,
|
||||
"include_style_examples": False,
|
||||
},
|
||||
},
|
||||
)
|
||||
published_clone = publish_guideline(clone_guideline(CURRENT_VOICE_IDS["light"])["id"])
|
||||
archived = archive_guideline(published_clone["id"])
|
||||
archived_instruction = get_guideline(archived["id"], include_instruction=True)["instruction"]
|
||||
archived_status = archived["status"]
|
||||
|
||||
with get_db() as conn:
|
||||
seed_generation_instructions(conn)
|
||||
expect(load_selection(profile_id)["voice_id"] == CURRENT_VOICE_IDS["neutral"], "stored selection is not rewritten")
|
||||
expect(
|
||||
get_guideline(cloned["id"], include_instruction=True)["instruction"] == original_clone_instruction,
|
||||
"admin clone is not overwritten by seed",
|
||||
)
|
||||
expect(get_guideline(archived["id"], include_instruction=True)["status"] == archived_status, "archived variant stays archived")
|
||||
expect(
|
||||
get_guideline(archived["id"], include_instruction=True)["instruction"] == archived_instruction,
|
||||
"archived variant is not rewritten",
|
||||
)
|
||||
expect(
|
||||
get_guideline(CURRENT_VOICE_IDS["clear"], include_instruction=True)["is_default"] is True,
|
||||
"current default is not reset by a legacy seed pass",
|
||||
)
|
||||
|
||||
|
||||
def test_later_semantic_seed_creates_successor() -> None:
|
||||
init_db()
|
||||
profile_id = "legacy-successor-user"
|
||||
with get_db() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT OR IGNORE INTO profiles (id, email, name, password_hash, role)
|
||||
VALUES (?, ?, ?, ?, 'user')
|
||||
""",
|
||||
(profile_id, "succ@example.test", "Succ", "x"),
|
||||
)
|
||||
stored = default_selection_ids()
|
||||
save_selection(profile_id, stored)
|
||||
original = get_guideline(CURRENT_VOICE_IDS["clear"], include_instruction=True)
|
||||
mutated = copy.deepcopy(load_seed_document())
|
||||
for item in mutated["slots"]["voice"]["variants"]:
|
||||
if item.get("id") == CURRENT_VOICE_IDS["clear"]:
|
||||
item["instruction"] = "CHANGED FUTURE SEMANTICS FOR CLEAR"
|
||||
item["label"] = "Persönliche Stimme deutlich (neu)"
|
||||
break
|
||||
mutated["seed_revision"] = "2026-08-30-future-voice-v1"
|
||||
with get_db() as conn:
|
||||
seed_generation_instructions(conn, mutated)
|
||||
seed_generation_instructions(conn, mutated)
|
||||
kept = get_guideline(CURRENT_VOICE_IDS["clear"], include_instruction=True)
|
||||
expect(kept["instruction"] == original["instruction"], "future seed does not overwrite the existing variant id")
|
||||
expect(kept["label"] == original["label"], "future seed does not change the existing label")
|
||||
successors = [
|
||||
item
|
||||
for item in voice_rows()
|
||||
if item.get("cloned_from") == CURRENT_VOICE_IDS["clear"]
|
||||
and item["instruction"] == "CHANGED FUTURE SEMANTICS FOR CLEAR"
|
||||
]
|
||||
expect(len(successors) == 1, "changed semantics are inserted once as a successor")
|
||||
successor = successors[0]
|
||||
expect(successor["id"] != CURRENT_VOICE_IDS["clear"], "successor uses a new id")
|
||||
expect(successor["revision"] == int(original["revision"]) + 1, "successor raises the revision")
|
||||
expect(successor["cloned_from"] == CURRENT_VOICE_IDS["clear"], "successor records the predecessor")
|
||||
expect(successor["is_default"] is True, "new default may point at the successor")
|
||||
expect(kept["is_default"] is False, "previous default is released when the seed names a new default")
|
||||
expect(
|
||||
load_selection(profile_id)["voice_id"] == CURRENT_VOICE_IDS["clear"],
|
||||
"stored selection keeps the previous id after a semantic successor is added",
|
||||
)
|
||||
compiled = compile_selection({**default_selection_ids(), "voice_id": CURRENT_VOICE_IDS["clear"]})
|
||||
expect(compiled.ids["voice"] == CURRENT_VOICE_IDS["clear"], "previous id remains selectable with its old meaning")
|
||||
expect(compiled.cloned_from["voice"] == "", "original current variant has no predecessor")
|
||||
compiled_new = compile_selection({**default_selection_ids(), "voice_id": successor["id"]})
|
||||
expect(compiled_new.cloned_from["voice"] == CURRENT_VOICE_IDS["clear"], "compiled policy exposes the predecessor")
|
||||
|
||||
|
||||
def test_legacy_generate_trace_and_prompt() -> None:
|
||||
from tests.harness import reset_postgres_data
|
||||
|
||||
reset_postgres_data()
|
||||
client = TestClient(app)
|
||||
setup = client.post(
|
||||
"/api/auth/setup",
|
||||
json={"email": "legacy-gen@example.test", "password": "pass-pass", "name": "Legacy"},
|
||||
)
|
||||
expect(setup.status_code == 200, f"setup {setup.status_code}")
|
||||
token = setup.json()["token"]
|
||||
headers = header(token)
|
||||
space = client.post("/api/journal/spaces", headers=headers, json={"title": "Urlaub"})
|
||||
expect(space.status_code == 200, f"space {space.status_code}")
|
||||
day = client.post(
|
||||
f"/api/journal/spaces/{space.json()['id']}/days",
|
||||
headers=headers,
|
||||
json={"calendar_date": "2026-08-29"},
|
||||
)
|
||||
conv = client.post(
|
||||
f"/api/journal/days/{day.json()['day']['id']}/conversations",
|
||||
headers=headers,
|
||||
json={"title": "Tag"},
|
||||
)
|
||||
turn = client.post(
|
||||
f"/api/journal/conversations/{conv.json()['id']}/turn",
|
||||
headers=headers,
|
||||
json={"body": "Ich war am Markt. Vielleicht bleibe ich kürzer."},
|
||||
)
|
||||
expect(turn.status_code == 200, f"turn {turn.status_code}")
|
||||
day_id = day.json()["day"]["id"]
|
||||
conv_id = conv.json()["id"]
|
||||
selection = default_selection_ids()
|
||||
|
||||
reset_debug()
|
||||
recorder = install_test_recorder()
|
||||
current = client.post(
|
||||
f"/api/journal/days/{day_id}/generate",
|
||||
headers=headers,
|
||||
json={"conversation_ids": [conv_id], "generation_selection": selection, "remember_generation_selection": False},
|
||||
)
|
||||
expect(current.status_code == 200, f"current generate {current.status_code}")
|
||||
current_payload = current.json()
|
||||
current_intern = intern_of(current_payload)
|
||||
current_trace = (current_payload.get("trace") or {}).get("style_application") or {}
|
||||
expect([item.get("purpose") for item in recorder] == ["journal_generate"], "current path still uses one narration call")
|
||||
expect(current_trace.get("id") == CURRENT_VOICE_IDS["clear"], "trace keeps the current voice id")
|
||||
expect(current_trace.get("revision") == 1, "trace keeps the current revision")
|
||||
expect("STYLE_EXAMPLES" not in current_intern, "current default prompt has no STYLE_EXAMPLES reference")
|
||||
expect("\nSTYLE_EXAMPLES\n" not in current_intern, "current default prompt has no example block")
|
||||
|
||||
formatted = format_style_examples(
|
||||
[{"kind": "journal_entry", "occurred_at": "2026-08-01", "excerpt": "Nur ein Stilbeispiel."}]
|
||||
)
|
||||
expect("keine Tatsachen des heutigen" in formatted or "nicht übernommen" in formatted, "examples stay style-only when present")
|
||||
|
||||
reset_debug()
|
||||
recorder = install_test_recorder()
|
||||
selection["voice_id"] = seed_id("voice", "legacy_neutral")
|
||||
legacy = client.post(
|
||||
f"/api/journal/days/{day_id}/generate",
|
||||
headers=headers,
|
||||
json={"conversation_ids": [conv_id], "generation_selection": selection, "remember_generation_selection": False},
|
||||
)
|
||||
expect(legacy.status_code == 200, f"legacy generate {legacy.status_code}")
|
||||
payload = legacy.json()
|
||||
intern = intern_of(payload)
|
||||
app_trace = (payload.get("trace") or {}).get("style_application") or {}
|
||||
expect([item.get("purpose") for item in recorder] == ["journal_generate"], "legacy path still uses one narration call")
|
||||
expect(app_trace.get("id") == seed_id("voice", "legacy_neutral"), "legacy trace uses the reconstructed id")
|
||||
expect(app_trace.get("revision") == 1, "legacy trace uses the reconstructed revision")
|
||||
expect(app_trace.get("key") == "legacy_neutral", "legacy trace names the reconstructed key")
|
||||
expect("höchstens als leise Tendenz" in intern, "legacy instruction reaches the provider prompt")
|
||||
expect(app_trace.get("requested", {}).get("include_style_examples") is True, "legacy requests the former full style context")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
test_current_variants_and_legacy_seed()
|
||||
test_stored_selection_and_clones_and_archives()
|
||||
test_later_semantic_seed_creates_successor()
|
||||
test_legacy_generate_trace_and_prompt()
|
||||
print("journal style legacy immutable tests passed.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -9,11 +9,9 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-trash-test.sqlite")
|
||||
os.environ["KANSHO_MEDIA_ROOT"] = str(Path(tempfile.gettempdir()) / "kansho-trash-media")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
Path(os.environ["KANSHO_MEDIA_ROOT"]).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Local trusted-zone URL tests. No database."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
os.environ.setdefault("KANSHO_PROVIDER_KEY", "")
|
||||
os.environ.setdefault("KANSHO_DETECT_PROVIDER_KEY", "")
|
||||
Path(tempfile.gettempdir()).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from entity_detect import (
|
||||
DETECT_MAX_TOKENS,
|
||||
DETECT_MAX_TOKENS_LOCAL,
|
||||
DETECT_TIMEOUT,
|
||||
DETECT_TIMEOUT_LOCAL,
|
||||
detect_chat_limits,
|
||||
)
|
||||
from providers import ProviderConfig, is_local_url
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
expect(is_local_url("http://127.0.0.1:11434/v1/chat/completions"), "loopback is local")
|
||||
expect(is_local_url("http://localhost:11434/v1/chat/completions"), "localhost is local")
|
||||
expect(is_local_url("http://192.168.2.144:8090"), "RFC1918 GLiNER host is local")
|
||||
expect(is_local_url("http://10.0.0.8:11434/v1/chat/completions"), "10/8 is local")
|
||||
expect(is_local_url("http://ollama:11434/v1/chat/completions"), "compose hostname ollama is local")
|
||||
expect(not is_local_url("https://openrouter.ai/api/v1/chat/completions"), "OpenRouter is not local")
|
||||
expect(not is_local_url("https://8.8.8.8/v1/chat/completions"), "public IP is not local")
|
||||
remote = ProviderConfig(
|
||||
role="detect",
|
||||
name="openrouter",
|
||||
mode="http",
|
||||
url="https://openrouter.ai/api/v1/chat/completions",
|
||||
model="openai/gpt-4.1-nano",
|
||||
key="x",
|
||||
local=False,
|
||||
zdr=True,
|
||||
no_train=True,
|
||||
)
|
||||
local = ProviderConfig(
|
||||
role="detect",
|
||||
name="ollama",
|
||||
mode="http",
|
||||
url="http://192.168.2.144:11434/v1/chat/completions",
|
||||
model="phi3:mini",
|
||||
key="",
|
||||
local=True,
|
||||
zdr=True,
|
||||
no_train=True,
|
||||
)
|
||||
expect(detect_chat_limits(remote) == (DETECT_TIMEOUT, DETECT_MAX_TOKENS), "remote detect keeps 90s/1024")
|
||||
expect(
|
||||
detect_chat_limits(local) == (DETECT_TIMEOUT_LOCAL, DETECT_MAX_TOKENS_LOCAL),
|
||||
"local detect waits 300s with a 256-token cap",
|
||||
)
|
||||
print("local url tests passed.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -10,12 +10,14 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-model-catalog-test.sqlite")
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
os.environ.setdefault("KANSHO_PROVIDER_KEY", "")
|
||||
os.environ.setdefault("KANSHO_DETECT_PROVIDER_KEY", "")
|
||||
Path(tempfile.gettempdir()).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from model_catalog import (
|
||||
ModelWindow,
|
||||
catalog_ttl,
|
||||
list_provider_models,
|
||||
reset_catalog,
|
||||
resolve_generate_metadata,
|
||||
)
|
||||
@@ -180,12 +182,66 @@ def test_env_fallback_and_fail_closed() -> None:
|
||||
_restore_env(previous)
|
||||
|
||||
|
||||
def test_list_provider_models() -> None:
|
||||
reset_catalog()
|
||||
payload = {
|
||||
"data": [
|
||||
{"id": "openai/gpt-4.1-nano", "name": "GPT 4.1 Nano"},
|
||||
{"id": "openai/gpt-5.4", "context_length": 128000},
|
||||
{"id": "openai/gpt-4.1-nano"},
|
||||
]
|
||||
}
|
||||
with patch("model_catalog.httpx.get", lambda *args, **kwargs: FakeResponse(payload)):
|
||||
items = list_provider_models(_openrouter_config())
|
||||
expect([item["id"] for item in items] == ["openai/gpt-4.1-nano", "openai/gpt-5.4"], "picker lists unique ids")
|
||||
with patch("model_catalog.httpx.get", lambda *args, **kwargs: FakeResponse({"nope": True})):
|
||||
expect(list_provider_models(_openrouter_config()) == [], "picker soft-fails on bad catalog")
|
||||
fake = ProviderConfig(
|
||||
role="generate",
|
||||
name="fake",
|
||||
mode="fake",
|
||||
url="",
|
||||
model="fake",
|
||||
key="",
|
||||
local=True,
|
||||
zdr=True,
|
||||
no_train=True,
|
||||
)
|
||||
expect(list_provider_models(fake) == [], "fake provider has no catalog")
|
||||
|
||||
|
||||
def test_list_ollama_tags() -> None:
|
||||
reset_catalog()
|
||||
|
||||
def fake_get(url, *args, **kwargs):
|
||||
if str(url).endswith("/api/tags"):
|
||||
return FakeResponse({"models": [{"name": "llama3.1:latest"}, {"name": "qwen2.5:7b"}]})
|
||||
return FakeResponse({"nope": True})
|
||||
|
||||
config = ProviderConfig(
|
||||
role="detect",
|
||||
name="ollama",
|
||||
mode="http",
|
||||
url="http://192.168.2.144:11434/v1/chat/completions",
|
||||
model="llama3.1:latest",
|
||||
key="",
|
||||
local=True,
|
||||
zdr=True,
|
||||
no_train=True,
|
||||
)
|
||||
with patch("model_catalog.httpx.get", fake_get):
|
||||
items = list_provider_models(config)
|
||||
expect([item["id"] for item in items] == ["llama3.1:latest", "qwen2.5:7b"], "ollama tags fill the picker")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
test_reads_context_and_completion()
|
||||
test_model_not_in_catalog()
|
||||
test_incomplete_metadata()
|
||||
test_cache_hit_and_ttl_expiry()
|
||||
test_env_fallback_and_fail_closed()
|
||||
test_list_provider_models()
|
||||
test_list_ollama_tags()
|
||||
print("model catalog tests passed.")
|
||||
|
||||
|
||||
|
||||
@@ -9,11 +9,9 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-mvp-journal-test.sqlite")
|
||||
os.environ["KANSHO_MEDIA_ROOT"] = str(Path(tempfile.gettempdir()) / "kansho-mvp-journal-media")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
Path(os.environ["KANSHO_MEDIA_ROOT"]).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
@@ -327,7 +325,7 @@ def main() -> None:
|
||||
"WRITING_PROFILE" in narrate_intern or "Neutraler Journalstil" in narrate_intern or "Core:" in narrate_intern,
|
||||
"A style brief reaches generate",
|
||||
)
|
||||
expect("STYLE_EXAMPLES" in narrate_intern, "A style examples block is labeled")
|
||||
expect("STYLE_EXAMPLES" not in narrate_intern, "A default voice does not attach a style-examples block")
|
||||
style_part = narrate_intern.split("\nCURRENT_DAY_SOURCES\n")[0]
|
||||
expect("Erzählmerkmale" not in style_part, "A current day dialogue is not appended as style signals")
|
||||
expect("Neutraler Journalstil" in style_part or "Core:" in style_part, "A empty profile uses the neutral journal voice")
|
||||
@@ -516,7 +514,7 @@ def main() -> None:
|
||||
if stage.get("purpose") == "journal_generate":
|
||||
intern_i = stage.get("intern") or ""
|
||||
intern_i = intern_i or ((gen_i.json().get("trace") or {}).get("intern") or "")
|
||||
expect("STYLE_EXAMPLES" in intern_i, "I style examples reach generate")
|
||||
expect("STYLE_EXAMPLES" not in intern_i, "I default voice does not send imported texts as style examples")
|
||||
expect("WRITING_PROFILE" in intern_i or "Neutraler Journalstil" in intern_i, "I writing profile reaches generate")
|
||||
expect("knapp" in imported.json()["compiled_brief"], "I stored brief still lists the import")
|
||||
profile = client.get("/api/journal/writing-profile", headers=headers).json()
|
||||
|
||||
@@ -15,10 +15,8 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-privacy-detect-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from identity_store import (
|
||||
@@ -115,6 +113,73 @@ def main() -> None:
|
||||
expect("[[PERSON:" in (person_sushi.trace.get("egress") or ""), "same word can be a person in another sentence")
|
||||
expect("Sushi" not in (person_sushi.trace.get("egress") or "").replace("[[PERSON:", ""), "person Sushi is masked")
|
||||
|
||||
mixed_homonym = "Ich aß Sushi. Meine Frau Sushi kam später."
|
||||
food_at = mixed_homonym.find("Sushi")
|
||||
person_at = mixed_homonym.find("Sushi", food_at + 1)
|
||||
dish = validate_detected_entity(
|
||||
{"start": food_at, "end": food_at + 5, "text": "Sushi", "entity_type": "FOOD"},
|
||||
mixed_homonym,
|
||||
0,
|
||||
)
|
||||
expect(dish is None, "FOOD on a dish mention is omitted, not a contract error")
|
||||
person_from_food = validate_detected_entity(
|
||||
{"start": person_at, "end": person_at + 5, "text": "Sushi", "entity_type": "FOOD"},
|
||||
mixed_homonym,
|
||||
0,
|
||||
)
|
||||
expect(
|
||||
person_from_food is not None and person_from_food.entity_type == "PERSON",
|
||||
"FOOD on a kinship mention stays PERSON",
|
||||
)
|
||||
arrived = "Sushi kam später."
|
||||
arrived_span = validate_detected_entity(
|
||||
{"start": 0, "end": 5, "text": "Sushi", "entity_type": "DISH"},
|
||||
arrived,
|
||||
0,
|
||||
)
|
||||
expect(
|
||||
arrived_span is not None and arrived_span.entity_type == "PERSON",
|
||||
"DISH on a person subject stays PERSON",
|
||||
)
|
||||
noted = validate_detected_entity(
|
||||
{
|
||||
"start": food_at,
|
||||
"end": food_at + 5,
|
||||
"text": "Sushi",
|
||||
"entity_type": "FOOD",
|
||||
"note": "Gericht",
|
||||
},
|
||||
mixed_homonym,
|
||||
0,
|
||||
)
|
||||
expect(noted is None, "extra fields on a FOOD dish do not fail the pass")
|
||||
install_test_spans(
|
||||
[
|
||||
{"start": food_at, "end": food_at + 5, "text": "Sushi", "entity_type": "FOOD"},
|
||||
{"start": person_at, "end": person_at + 5, "text": "Sushi", "entity_type": "FOOD"},
|
||||
]
|
||||
)
|
||||
try:
|
||||
mixed_run = _run(profile_id, mixed_homonym)
|
||||
mixed_egress = mixed_run.trace.get("egress") or ""
|
||||
expect(mixed_run.allowed, "FOOD homonym does not block generate")
|
||||
expect("aß Sushi" in mixed_egress, "reconstructed dish stays unmasked")
|
||||
expect("[[PERSON:" in mixed_egress, "person-shaped FOOD span is masked")
|
||||
expect(
|
||||
not mixed_run.diagnostics.get("contract_violation"),
|
||||
"food type is not a contract violation",
|
||||
)
|
||||
expect(
|
||||
not mixed_run.diagnostics.get("invalid_entity_type"),
|
||||
"food type is not recorded as invalid",
|
||||
)
|
||||
expect(
|
||||
"FOOD" in (mixed_run.diagnostics.get("omitted_non_identity_types") or []),
|
||||
"omitted food type is recorded without span text",
|
||||
)
|
||||
finally:
|
||||
reset_detect_test_hooks()
|
||||
|
||||
mixed = _run(
|
||||
profile_id,
|
||||
"Ich traf Anna. Ich arbeitete am privaten Projekt Aurora. "
|
||||
@@ -134,12 +199,15 @@ def main() -> None:
|
||||
0,
|
||||
)
|
||||
expect(span.text == "Anna" and span.start == start, "valid span matches the local substring")
|
||||
relocated = validate_detected_entity(
|
||||
expect(
|
||||
validate_detected_entity(
|
||||
{"start": 0, "end": 4, "text": "Anna", "entity_type": "PERSON"},
|
||||
sample,
|
||||
0,
|
||||
).start
|
||||
== start,
|
||||
"wrong offsets are grounded to the local word",
|
||||
)
|
||||
expect(relocated is not None and relocated.start == start and relocated.text == "Anna", "wrong offsets are grounded to the local word")
|
||||
expect(
|
||||
validate_detected_entity(
|
||||
{"start": -1, "end": 4, "text": "Anna", "entity_type": "PERSON"},
|
||||
@@ -149,15 +217,20 @@ def main() -> None:
|
||||
== start,
|
||||
"negative offsets still ground when the word exists",
|
||||
)
|
||||
expect(
|
||||
try:
|
||||
validate_detected_entity(
|
||||
{"start": 0, "end": 4, "text": "Nein", "entity_type": "PERSON"},
|
||||
sample,
|
||||
0,
|
||||
)
|
||||
is None,
|
||||
"a word that is not in the chunk is skipped",
|
||||
missing_word = False
|
||||
except DetectError as exc:
|
||||
missing_word = exc.code == "detect_invalid_output"
|
||||
expect(
|
||||
(exc.diagnostics or {}).get("contract_violation") == "unusable_offsets",
|
||||
"a word that is not in the chunk is a contract violation",
|
||||
)
|
||||
expect(missing_word, "a word that is not in the chunk fails closed")
|
||||
expect(
|
||||
validate_detected_entity(
|
||||
{"start": "x", "end": 4, "text": "Anna", "entity_type": "PERSON"},
|
||||
@@ -464,7 +537,7 @@ def main() -> None:
|
||||
"SELECT seed_revision, template, default_template FROM ai_prompts WHERE slug = ?",
|
||||
("mvp.entity_detect",),
|
||||
).fetchone()
|
||||
expect(row["seed_revision"] == "2026-08-27-detect-ground-v1", "detect prompt revision is stored")
|
||||
expect(row["seed_revision"] == "2026-09-08-detect-homonym-v1", "detect prompt revision is stored")
|
||||
expect("{{known_labels}}" not in (row["template"] or ""), "new detect prompt has no known_labels skip list")
|
||||
expect("Zwiebeln" not in (row["template"] or ""), "detect prompt has no food word list")
|
||||
|
||||
@@ -482,7 +555,7 @@ def main() -> None:
|
||||
("mvp.entity_detect",),
|
||||
).fetchone()
|
||||
expect(custom["template"] == "CUSTOM DETECT {{source_text}}", "user-edited detect prompt is not overwritten")
|
||||
expect(custom["seed_revision"] == "2026-08-27-detect-ground-v1", "revision still updates the default")
|
||||
expect(custom["seed_revision"] == "2026-09-08-detect-homonym-v1", "revision still updates the default")
|
||||
|
||||
remote = ProviderConfig(
|
||||
role="detect",
|
||||
@@ -497,7 +570,13 @@ def main() -> None:
|
||||
)
|
||||
expect(uses_llm_detect(remote), "development allows remote detect")
|
||||
os.environ["KANSHO_ENV"] = "production"
|
||||
os.environ.pop("KANSHO_ALLOW_REMOTE_DETECT", None)
|
||||
expect(not uses_llm_detect(remote), "production blocks remote detect")
|
||||
os.environ["KANSHO_ALLOW_REMOTE_DETECT"] = "1"
|
||||
expect(uses_llm_detect(remote), "operator override allows remote detect in production")
|
||||
os.environ["KANSHO_ALLOW_REMOTE_DETECT"] = "0"
|
||||
expect(not uses_llm_detect(remote), "false override does not allow remote detect")
|
||||
os.environ.pop("KANSHO_ALLOW_REMOTE_DETECT", None)
|
||||
local = ProviderConfig(
|
||||
role="detect",
|
||||
name="ollama",
|
||||
@@ -511,6 +590,7 @@ def main() -> None:
|
||||
)
|
||||
expect(uses_llm_detect(local), "production still allows local detect")
|
||||
os.environ.pop("KANSHO_ENV", None)
|
||||
os.environ.pop("KANSHO_ALLOW_REMOTE_DETECT", None)
|
||||
|
||||
mapped = [{"local_label": "Anna", "token": "PERSON:01"}]
|
||||
anna_manifest = mask_prompt("Anna war am Markt.", mapped, "journal_generate")
|
||||
|
||||
@@ -13,10 +13,8 @@ from unittest.mock import patch
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-privacy-manifest-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from entity_detect import install_test_spans, reset_detect_test_hooks
|
||||
|
||||
@@ -11,10 +11,8 @@ ROOT = Path(__file__).resolve().parents[1]
|
||||
REPO = ROOT.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-privacy-response-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from identity_store import list_mappings, remember_mapping
|
||||
|
||||
@@ -9,10 +9,8 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-profile-governance-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
|
||||
@@ -9,10 +9,8 @@ from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-profile-review-test.sqlite")
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from main import app
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Profile-review failures expose reason and whether the provider was billed.
|
||||
|
||||
Run from backend/: python tests/test_profile_review_errors.py
|
||||
No live provider calls.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import httpx
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ["KANSHO_FAKE_PROVIDER"] = "1"
|
||||
os.environ["KANSHO_FAKE_DETECT"] = "1"
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from engine import EngineError
|
||||
from main import app
|
||||
from privacy_gateway import public_cost_report
|
||||
from providers import ProviderConfig, complete_chat, provider_error_diagnostics
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
def header(token: str) -> dict:
|
||||
return {"X-Auth-Token": token}
|
||||
|
||||
|
||||
def _openrouter() -> ProviderConfig:
|
||||
return ProviderConfig(
|
||||
role="generate",
|
||||
name="openrouter",
|
||||
mode="http",
|
||||
url="https://openrouter.ai/api/v1/chat/completions",
|
||||
model="openai/gpt-4o",
|
||||
key="sk-test",
|
||||
local=False,
|
||||
zdr=True,
|
||||
no_train=True,
|
||||
)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
none = public_cost_report({})
|
||||
expect(none["billed"] == "no", "empty diagnostics are unbilled")
|
||||
expect("keine Kosten entstanden" in none["note"], "empty diagnostics say no provider call")
|
||||
|
||||
detect_only = public_cost_report(
|
||||
{"detect_calls": 2, "detect_cost": 0.0012, "generate_called": False, "generate_requested": False}
|
||||
)
|
||||
expect(detect_only["billed"] == "yes", "detect cost counts as billed")
|
||||
expect("Detect" in detect_only["note"] and "Generate nicht" in detect_only["note"], "detect-only note names both stages")
|
||||
|
||||
sent = public_cost_report(
|
||||
{"detect_calls": 1, "detect_cost": 0.0004, "generate_requested": True, "generate_called": False}
|
||||
)
|
||||
expect(sent["billed"] == "yes", "known detect cost stays billed if generate is unknown")
|
||||
expect("Generate-Aufruf gesendet" in sent["note"], "unknown generate request is explicit")
|
||||
|
||||
unknown = public_cost_report({"generate_requested": True, "generate_called": False})
|
||||
expect(unknown["billed"] == "unknown", "generate request without any usage is unknown")
|
||||
|
||||
known = public_cost_report(
|
||||
{"detect_calls": 1, "detect_cost": 0.0004, "generate_called": True, "cost": 0.021}
|
||||
)
|
||||
expect(known["billed"] == "yes", "generate usage is billed")
|
||||
expect(abs((known["total_cost"] or 0) - 0.0214) < 1e-9, "total adds detect and generate")
|
||||
|
||||
parsed = provider_error_diagnostics(
|
||||
402,
|
||||
'{"error":{"message":"Insufficient credits","code":402},"usage":{"cost":0.0}}',
|
||||
)
|
||||
expect(parsed["http_status"] == 402, "provider diagnostics keep HTTP status")
|
||||
expect(parsed["provider_message"] == "Insufficient credits", "provider message is copied")
|
||||
expect(parsed.get("cost") == 0.0, "error usage cost is kept")
|
||||
|
||||
class Reject:
|
||||
status_code = 402
|
||||
text = '{"error":{"message":"Insufficient credits","code":402}}'
|
||||
|
||||
def json(self):
|
||||
return {"error": {"message": "Insufficient credits", "code": 402}}
|
||||
|
||||
try:
|
||||
with patch("providers.httpx.post", lambda *args, **kwargs: Reject()):
|
||||
complete_chat(_openrouter(), [{"role": "user", "content": "x"}], timeout=5)
|
||||
raise SystemExit("FAIL: rejected complete_chat should raise")
|
||||
except Exception as exc:
|
||||
expect(getattr(exc, "code", "") == "provider_rejected", "credit reject is provider_rejected")
|
||||
expect("HTTP 402" in str(exc), "reject message includes HTTP status")
|
||||
expect("Insufficient credits" in str(exc), "reject message includes provider reason")
|
||||
expect(exc.diagnostics.get("generate_requested") is True, "reject marks generate as requested")
|
||||
|
||||
def boom(*args, **kwargs):
|
||||
raise httpx.TimeoutException("timed out")
|
||||
|
||||
try:
|
||||
with patch("providers.httpx.post", boom):
|
||||
complete_chat(_openrouter(), [{"role": "user", "content": "x"}], timeout=12)
|
||||
raise SystemExit("FAIL: timeout should raise")
|
||||
except Exception as exc:
|
||||
expect(getattr(exc, "code", "") == "provider_timeout", "timeout is distinct from unreachable")
|
||||
expect("12 Sekunden" in str(exc), "timeout names the limit")
|
||||
|
||||
with TestClient(app) as client:
|
||||
setup = client.post(
|
||||
"/api/auth/setup",
|
||||
json={"email": "lars@example.test", "name": "Lars", "password": "test-pass"},
|
||||
)
|
||||
expect(setup.status_code == 200, f"setup {setup.text}")
|
||||
token = setup.json()["token"]
|
||||
headers = header(token)
|
||||
imported = client.post(
|
||||
"/api/journal/writing-profile/import",
|
||||
headers=headers,
|
||||
json={"body": "Heute Kirschen am Markt, später der Hafen, und abends nur zwei knappe Zeilen."},
|
||||
)
|
||||
expect(imported.status_code == 200, f"import {imported.text}")
|
||||
|
||||
rejected = EngineError(
|
||||
"provider_rejected",
|
||||
"generate-Provider hat die Anfrage abgelehnt (HTTP 402): Insufficient credits",
|
||||
502,
|
||||
diagnostics={
|
||||
"http_status": 402,
|
||||
"provider_message": "Insufficient credits",
|
||||
"generate_requested": True,
|
||||
"generate_called": False,
|
||||
"detect_calls": 1,
|
||||
"detect_cost": 0.0015,
|
||||
},
|
||||
)
|
||||
with patch("engine.execute_prompt", side_effect=rejected):
|
||||
response = client.post("/api/journal/writing-profile/initial-build/api", headers=headers)
|
||||
expect(response.status_code == 502, f"rejected review status {response.text}")
|
||||
detail = response.json()["detail"]
|
||||
expect(detail["code"] == "provider_rejected", "API keeps provider code")
|
||||
expect("Insufficient credits" in detail["message"], "API message keeps provider reason")
|
||||
expect(detail["cost_report"]["billed"] == "yes", "detect cost is reported as billed")
|
||||
expect("Detect" in detail["cost_report"]["note"], "cost note mentions detect")
|
||||
expect(detail["cost_report"]["generate_requested"] is True, "generate was requested")
|
||||
expect(detail["cost_report"]["generate_called"] is False, "generate did not complete")
|
||||
|
||||
invalid = {
|
||||
"content": "kein json",
|
||||
"diagnostics": {
|
||||
"generate_called": True,
|
||||
"generate_requested": True,
|
||||
"cost": 0.033,
|
||||
"detect_calls": 1,
|
||||
"detect_cost": 0.002,
|
||||
},
|
||||
"trace": {"generate_called": True, "purpose": "profile_review"},
|
||||
}
|
||||
with patch("engine.execute_prompt", return_value=invalid):
|
||||
response = client.post("/api/journal/writing-profile/review/api", headers=headers)
|
||||
expect(response.status_code == 400, f"invalid result status {response.text}")
|
||||
detail = response.json()["detail"]
|
||||
expect(detail["code"] == "invalid_review_result", "parse failure keeps store code")
|
||||
expect("JSON" in detail["message"] or "json" in detail["message"].lower(), "parse failure explains JSON")
|
||||
expect(detail["cost_report"]["billed"] == "yes", "successful generate before parse failure is billed")
|
||||
expect(detail["cost_report"]["generate_called"] is True, "parse failure still records generate")
|
||||
expect(abs((detail["cost_report"]["cost"] or 0) - 0.033) < 1e-9, "generate cost survives parse failure")
|
||||
|
||||
print("ALL TESTS PASSED")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,20 +1,13 @@
|
||||
"""Intent-neutral provenance verification. Run from backend/: python tests/test_provenance.py"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
os.environ.setdefault(
|
||||
"KANSHO_DB_PATH",
|
||||
str(Path(tempfile.gettempdir()) / "kansho-provenance-test.sqlite"),
|
||||
)
|
||||
|
||||
from provenance import (
|
||||
COVERAGE_ALL_SELECTED_SOURCES,
|
||||
COVERAGE_SELECTED_EVIDENCE,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""SQL dialect adapter for the SQLite/Postgres dual backend."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from sql_compat import adapt_sql, split_sql, sqlite_schema_to_postgres, use_postgres
|
||||
|
||||
|
||||
def expect(ok: bool, message: str) -> None:
|
||||
if not ok:
|
||||
raise SystemExit(f"FAIL: {message}")
|
||||
print(f"OK {message}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
os.environ.pop("KANSHO_DB_BACKEND", None)
|
||||
os.environ.pop("KANSHO_DB_PATH", None)
|
||||
os.environ.pop("DB_HOST", None)
|
||||
os.environ.pop("DATABASE_URL", None)
|
||||
expect(use_postgres() is False, "default engine is sqlite")
|
||||
|
||||
os.environ["KANSHO_DB_PATH"] = "/tmp/isolated.sqlite"
|
||||
os.environ["DB_HOST"] = "postgres"
|
||||
expect(use_postgres() is False, "KANSHO_DB_PATH without backend keeps Windows local on sqlite")
|
||||
os.environ["KANSHO_DB_BACKEND"] = "postgres"
|
||||
expect(use_postgres() is True, "explicit postgres backend wins")
|
||||
os.environ["KANSHO_DB_BACKEND"] = "sqlite"
|
||||
expect(use_postgres() is False, "explicit sqlite backend wins")
|
||||
os.environ.pop("KANSHO_DB_BACKEND", None)
|
||||
os.environ.pop("KANSHO_DB_PATH", None)
|
||||
expect(use_postgres() is True, "DB_HOST alone selects postgres")
|
||||
os.environ.pop("DB_HOST", None)
|
||||
|
||||
translated = sqlite_schema_to_postgres("created TEXT NOT NULL DEFAULT (datetime('now'))")
|
||||
expect("CURRENT_TIMESTAMP::text" in translated, "schema datetime default")
|
||||
expect("datetime('now')" not in translated, "no sqlite datetime left in schema")
|
||||
|
||||
ignore = adapt_sql("INSERT OR IGNORE INTO tiers (id) VALUES (?)")
|
||||
expect("INSERT INTO tiers" in ignore, "insert or ignore becomes insert")
|
||||
expect("ON CONFLICT DO NOTHING" in ignore, "conflict do nothing appended")
|
||||
expect("%s" in ignore and "?" not in ignore, "placeholders converted")
|
||||
|
||||
upsert = adapt_sql(
|
||||
"INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
|
||||
)
|
||||
expect("ON CONFLICT (key)" in upsert, "on conflict parenthesis spacing")
|
||||
expect(upsert.count("ON CONFLICT") == 1, "existing on conflict not duplicated")
|
||||
expect("%s" in upsert, "upsert placeholders")
|
||||
|
||||
quoted = adapt_sql("SELECT '?' AS q, name FROM profiles WHERE id = ?")
|
||||
expect("'?'" in quoted, "question mark inside quotes kept")
|
||||
expect(quoted.endswith("%s") or quoted.rstrip().endswith("%s"), "trailing placeholder converted")
|
||||
|
||||
case_sql = adapt_sql("UPDATE t SET x = CASE WHEN ? = 1 THEN ? ELSE x END")
|
||||
expect("CASE WHEN %s = 1 THEN %s ELSE x END" in case_sql, "boolean-safe case placeholder")
|
||||
|
||||
rowid_sql = adapt_sql("SELECT e.* FROM journal_entries e ORDER BY e.created, e.rowid")
|
||||
expect("e.rowid" not in rowid_sql, "sqlite rowid removed for postgres")
|
||||
expect("ORDER BY e.created, e.id" in rowid_sql, "rowid becomes primary id")
|
||||
|
||||
parts = split_sql("CREATE TABLE a (id TEXT); CREATE TABLE b (id TEXT);")
|
||||
expect(parts == ["CREATE TABLE a (id TEXT)", "CREATE TABLE b (id TEXT)"], "split two statements")
|
||||
schema = (ROOT / "schema.sql").read_text(encoding="utf-8")
|
||||
pg_schema = sqlite_schema_to_postgres(schema)
|
||||
expect("datetime('now')" not in pg_schema, "translated schema has no sqlite datetime")
|
||||
expect("CURRENT_TIMESTAMP::text" in pg_schema, "translated schema uses timestamp text default")
|
||||
expect(len(split_sql(pg_schema)) > 40, "schema splits into many statements")
|
||||
from sqlite_to_postgres import TABLES
|
||||
|
||||
tables = re.findall(r"CREATE TABLE IF NOT EXISTS (\w+)", schema)
|
||||
expect(tables == list(TABLES), "import table order matches schema.sql")
|
||||
print("sql compat: OK")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1186,23 +1186,34 @@ def _assemble_brief(profile_id: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
def compile_task_brief(profile_id: str, task: str = "journal_generate") -> str:
|
||||
def compile_task_brief(
|
||||
profile_id: str,
|
||||
task: str = "journal_generate",
|
||||
*,
|
||||
include_core: bool = True,
|
||||
include_facet: bool = True,
|
||||
include_traits: bool = True,
|
||||
) -> str:
|
||||
"""Compact confirmed style brief. Historical texts are selected separately.
|
||||
|
||||
Unconfirmed profiles do not become a style authority. Journal adapters attach
|
||||
final entries as STYLE_EXAMPLES, not as extra rules in this brief.
|
||||
final entries as STYLE_EXAMPLES, not as extra rules in this brief. Callers may
|
||||
omit core, facet or traits; omitted parts are not rendered as empty headings.
|
||||
"""
|
||||
profile = get_profile(profile_id)
|
||||
if task != "journal_generate":
|
||||
core = (profile.get("core") or {}).get("value") or ""
|
||||
return _clip_field(core, TASK_BRIEF_MAX_CHARS)
|
||||
|
||||
if not include_core and not include_facet and not include_traits:
|
||||
return ""
|
||||
|
||||
if not has_confirmed_profile(profile_id):
|
||||
return NEUTRAL_JOURNAL_STYLE
|
||||
|
||||
parts: list[str] = []
|
||||
core_text = ((profile.get("core") or {}).get("value") or "").strip()
|
||||
if core_text:
|
||||
core_text = ((profile.get("core") or {}).get("value") or "").strip() if include_core else ""
|
||||
if include_core and core_text:
|
||||
clipped = _clip_field(core_text, TASK_BRIEF_CORE_CHARS)
|
||||
if clipped:
|
||||
parts.append("Core: " + clipped)
|
||||
@@ -1214,13 +1225,14 @@ def compile_task_brief(profile_id: str, task: str = "journal_generate") -> str:
|
||||
),
|
||||
None,
|
||||
)
|
||||
facet_text = ((facet or {}).get("value") or "").strip()
|
||||
if facet_text and _norm_overlap(facet_text, core_text) < 0.8:
|
||||
facet_text = ((facet or {}).get("value") or "").strip() if include_facet else ""
|
||||
if include_facet and facet_text and _norm_overlap(facet_text, core_text) < 0.8:
|
||||
clipped = _clip_field(facet_text, TASK_BRIEF_FACET_CHARS)
|
||||
if clipped:
|
||||
parts.append("Autobiografisches Journaling (Facet-Delta): " + clipped)
|
||||
selected = _select_task_traits(profile.get("traits") or [])
|
||||
selected = _select_task_traits(profile.get("traits") or []) if include_traits else []
|
||||
used_statements = [core_text, facet_text]
|
||||
trait_lines: list[str] = []
|
||||
for item in selected:
|
||||
statement = (item.get("statement") or "").strip()
|
||||
if any(_norm_overlap(statement, previous) >= 0.85 for previous in used_statements if previous):
|
||||
@@ -1228,8 +1240,9 @@ def compile_task_brief(profile_id: str, task: str = "journal_generate") -> str:
|
||||
clipped = _clip_field(statement, TASK_BRIEF_TRAIT_CHARS)
|
||||
if not clipped:
|
||||
continue
|
||||
parts.append(f"- {item.get('label') or item.get('slug')}: {clipped}")
|
||||
trait_lines.append(f"- {item.get('label') or item.get('slug')}: {clipped}")
|
||||
used_statements.append(statement)
|
||||
parts.extend(trait_lines)
|
||||
brief = "\n".join(part for part in parts if part).strip()
|
||||
while len(brief) > TASK_BRIEF_MAX_CHARS and parts:
|
||||
last = parts.pop()
|
||||
@@ -1240,7 +1253,9 @@ def compile_task_brief(profile_id: str, task: str = "journal_generate") -> str:
|
||||
brief = "\n".join(parts).strip()
|
||||
break
|
||||
brief = "\n".join(parts).strip()
|
||||
if include_core and include_facet and include_traits:
|
||||
return brief or NEUTRAL_JOURNAL_STYLE
|
||||
return brief
|
||||
|
||||
|
||||
def has_facets(profile_id: str) -> bool:
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
# Server development stack: /home/lars/docker/kansho-dev
|
||||
# No fixed container_name — Compose prefixes with the project name.
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_DB: "${DB_NAME:-kansho_dev}"
|
||||
POSTGRES_USER: "${DB_USER:-kansho_dev}"
|
||||
POSTGRES_PASSWORD: "${DB_PASSWORD:-dev_password_change_me}"
|
||||
volumes:
|
||||
- dev-kansho-db-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-kansho_dev} -d ${DB_NAME:-kansho_dev}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- dev-kansho-network
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
KANSHO_DB_BACKEND: postgres
|
||||
KANSHO_ENV: "${KANSHO_ENV:-development}"
|
||||
KANSHO_DATA_DIR: /app/data
|
||||
KANSHO_MEDIA_ROOT: /app/data/media
|
||||
DB_HOST: postgres
|
||||
DB_PORT: "5432"
|
||||
DB_NAME: "${DB_NAME:-kansho_dev}"
|
||||
DB_USER: "${DB_USER:-kansho_dev}"
|
||||
DB_PASSWORD: "${DB_PASSWORD:-dev_password_change_me}"
|
||||
APP_URL: "${APP_URL:-https://dev.kansho.jinkendo.de}"
|
||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://dev.kansho.jinkendo.de,http://192.168.2.49:3096,http://localhost:3096}"
|
||||
KANSHO_PROVIDER_KEY: "${KANSHO_PROVIDER_KEY:-}"
|
||||
KANSHO_DETECT_PROVIDER_KEY: "${KANSHO_DETECT_PROVIDER_KEY:-}"
|
||||
KANSHO_ALLOW_REMOTE_DETECT: "${KANSHO_ALLOW_REMOTE_DETECT:-}"
|
||||
SMTP_HOST: "${SMTP_HOST:-}"
|
||||
SMTP_PORT: "${SMTP_PORT:-587}"
|
||||
SMTP_USER: "${SMTP_USER:-}"
|
||||
SMTP_PASSWORD: "${SMTP_PASSWORD:-}"
|
||||
SMTP_FROM: "${SMTP_FROM:-}"
|
||||
volumes:
|
||||
- dev-kansho-media:/app/data/media
|
||||
ports:
|
||||
- "${KANSHO_BACKEND_PORT:-8096}:8000"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD",
|
||||
"python",
|
||||
"-c",
|
||||
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/health')",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 18
|
||||
start_period: 90s
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- dev-kansho-network
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
VITE_API_URL: ""
|
||||
ports:
|
||||
- "${KANSHO_FRONTEND_PORT:-3096}:80"
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- dev-kansho-network
|
||||
|
||||
volumes:
|
||||
dev-kansho-db-data:
|
||||
dev-kansho-media:
|
||||
|
||||
networks:
|
||||
dev-kansho-network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,93 @@
|
||||
# Production stack on the Raspberry Pi: /home/lars/docker/kansho
|
||||
# Secrets live in the host .env next to this file, never in Git.
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: kansho-db-prod
|
||||
environment:
|
||||
POSTGRES_DB: "${DB_NAME:-kansho}"
|
||||
POSTGRES_USER: "${DB_USER:-kansho}"
|
||||
POSTGRES_PASSWORD: "${DB_PASSWORD:?set DB_PASSWORD in .env}"
|
||||
volumes:
|
||||
- kansho-db-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USER:-kansho} -d ${DB_NAME:-kansho}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- kansho-network
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: kansho-api
|
||||
environment:
|
||||
KANSHO_DB_BACKEND: postgres
|
||||
KANSHO_ENV: "${KANSHO_ENV:-production}"
|
||||
KANSHO_DATA_DIR: /app/data
|
||||
KANSHO_MEDIA_ROOT: /app/data/media
|
||||
DB_HOST: postgres
|
||||
DB_PORT: "5432"
|
||||
DB_NAME: "${DB_NAME:-kansho}"
|
||||
DB_USER: "${DB_USER:-kansho}"
|
||||
DB_PASSWORD: "${DB_PASSWORD:?set DB_PASSWORD in .env}"
|
||||
APP_URL: "${APP_URL:-https://kansho.jinkendo.de}"
|
||||
ALLOWED_ORIGINS: "${ALLOWED_ORIGINS:-https://kansho.jinkendo.de}"
|
||||
KANSHO_PROVIDER_KEY: "${KANSHO_PROVIDER_KEY:-}"
|
||||
KANSHO_DETECT_PROVIDER_KEY: "${KANSHO_DETECT_PROVIDER_KEY:-}"
|
||||
KANSHO_ALLOW_REMOTE_DETECT: "${KANSHO_ALLOW_REMOTE_DETECT:-}"
|
||||
SMTP_HOST: "${SMTP_HOST:-}"
|
||||
SMTP_PORT: "${SMTP_PORT:-587}"
|
||||
SMTP_USER: "${SMTP_USER:-}"
|
||||
SMTP_PASSWORD: "${SMTP_PASSWORD:-}"
|
||||
SMTP_FROM: "${SMTP_FROM:-}"
|
||||
volumes:
|
||||
- kansho-media:/app/data/media
|
||||
ports:
|
||||
- "${KANSHO_BACKEND_PORT:-8005}:8000"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD",
|
||||
"python",
|
||||
"-c",
|
||||
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/health')",
|
||||
]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 12
|
||||
start_period: 40s
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- kansho-network
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
VITE_API_URL: ""
|
||||
container_name: kansho-ui
|
||||
ports:
|
||||
- "${KANSHO_FRONTEND_PORT:-3006}:80"
|
||||
depends_on:
|
||||
backend:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- kansho-network
|
||||
|
||||
volumes:
|
||||
kansho-db-data:
|
||||
kansho-media:
|
||||
|
||||
networks:
|
||||
kansho-network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,137 @@
|
||||
# Deployment – Kanshō
|
||||
|
||||
**Stand:** 2026-09-07
|
||||
**Server:** Raspberry Pi 5 (`192.168.2.49`) — gleicher Host wie Mitai/Shinkan/Kairo, **eigene** Compose-Projekte
|
||||
**Runner:** Gitea Actions (`/home/lars/gitea-runner/`)
|
||||
**Repo:** `http://192.168.2.144:3000/Lars/Kansho.git`
|
||||
|
||||
Kanonische Runtime-Entscheidungen: `docs/architecture/technical/runtime_and_deploy.md`.
|
||||
Datenübernahme SQLite → Postgres: `backend/sqlite_to_postgres.py` (Probe auf Kopie, `--confirm`).
|
||||
|
||||
---
|
||||
|
||||
## Port- und Pfad-Übersicht
|
||||
|
||||
| | Production | Development |
|
||||
|---|------------|-------------|
|
||||
| **Git-Branch** | `main` | `develop` |
|
||||
| **Server-Verzeichnis** | `/home/lars/docker/kansho` | `/home/lars/docker/kansho-dev` |
|
||||
| **Frontend-Port** | 3006 | 3096 |
|
||||
| **Backend-Port** | 8005 | 8096 |
|
||||
| **PostgreSQL** | nur Compose-Netz, DB `kansho` | nur Compose-Netz, DB `kansho_dev` |
|
||||
| **Domain** | kansho.jinkendo.de | dev.kansho.jinkendo.de |
|
||||
| **Öffentliche URL** | https://kansho.jinkendo.de | https://dev.kansho.jinkendo.de |
|
||||
| **Compose** | `docker-compose.yml` | `docker-compose.dev-env.yml` |
|
||||
|
||||
Prod-Frontend ist **3006**, nicht 3005: auf dem Pi lauscht Bookstack bereits auf `0.0.0.0:3005`. Dev 3096/8096 und Prod-API 8005 waren frei.
|
||||
|
||||
Lokal ohne Docker bleibt Windows: Frontend **5188**, Backend **8018**, SQLite unter `backend/data/`.
|
||||
|
||||
---
|
||||
|
||||
## Einmalige Server-Einrichtung
|
||||
|
||||
```bash
|
||||
mkdir -p /home/lars/docker/kansho /home/lars/docker/kansho-dev
|
||||
|
||||
cd /home/lars/docker/kansho-dev
|
||||
git clone http://192.168.2.144:3000/Lars/Kansho.git .
|
||||
git checkout develop
|
||||
cp .env.example .env
|
||||
# DB_PASSWORD und Provider-Keys setzen
|
||||
|
||||
cd /home/lars/docker/kansho
|
||||
git clone http://192.168.2.144:3000/Lars/Kansho.git .
|
||||
git checkout main
|
||||
cp .env.example .env
|
||||
# Prod-DB_PASSWORD und Provider-Keys setzen
|
||||
```
|
||||
|
||||
Host-nginx: `nginx/kansho.conf` und `nginx/kansho-dev.conf` nach `/etc/nginx/sites-available/`, dann `nginx/certbot-setup.sh`. DNS A/AAAA für `dev.kansho.jinkendo.de` und `kansho.jinkendo.de` auf den Reverse-Proxy. Bis TLS steht, bleibt der LAN-Zugriff über die Publish-Ports.
|
||||
|
||||
**Additiv 2026-09-08:** Live-TLS endet auf dem Synology-NAS `192.168.2.63` (DSM Reverse Proxy, nicht auf dem Kanshō-Pi). Pro Kanshō-Regel unter Erweitert Proxy-Lese- und -Sende-Timeout auf 600s. DSM-Default 60s liefert HTTP 504, während Detect/Generate auf dem Pi weiterlaufen. LAN `http://192.168.2.49:3096` umgeht diesen Hop (Frontend-Container bereits 600s). AdGuard-Rewrites bleiben auf `192.168.2.63`.
|
||||
|
||||
Gitea: Actions aktivieren. Derselbe Pi-Runner wie die Schwesterprodukte (`ubuntu-latest`).
|
||||
|
||||
Watchtower bleibt aus.
|
||||
|
||||
---
|
||||
|
||||
## Gitea Actions
|
||||
|
||||
| Workflow | Trigger | Zweck |
|
||||
|----------|---------|--------|
|
||||
| `deploy-dev.yml` | Push `develop` | Deploy nach `/home/lars/docker/kansho-dev`, Health `localhost:8096` |
|
||||
| `deploy-prod.yml` | Push `main` | Deploy nach `/home/lars/docker/kansho`, Health `localhost:8005` |
|
||||
| `test.yml` | nach erfolgreichem `Deploy Development` | pytest auf `kansho_test`, nicht-schreibender Smoke gegen die laufende Dev-API, Frontend-Build. Keine Live-Provider-Keys. |
|
||||
|
||||
Prod nur über Merge-Commit `develop` → `main` (`git merge --no-ff develop` auf `main`), danach Push von `main`. Kein Fast-Forward, kein direkter Commit auf `main`, kein manuelles `git pull` auf dem Prod-Checkout. Gitea (`deploy-prod.yml`) ist der einzige Prod-Schreibpfad für Code.
|
||||
|
||||
---
|
||||
|
||||
## Datenübernahme (persönlich, Klasse A/B)
|
||||
|
||||
1. Phase-A-SQLite auf dem Heimrechner ist führend, bis der Dev-Import grün ist.
|
||||
2. Schema auf der Zielinstanz durch normalen Container-Start anlegen (leeres Postgres).
|
||||
3. Import auf **Dev zuerst**:
|
||||
|
||||
```bash
|
||||
# Zip oder laufende SQLite + Medien in den Dev-Container legen, dann:
|
||||
docker compose -f docker-compose.dev-env.yml exec -T backend \
|
||||
python sqlite_to_postgres.py --confirm \
|
||||
--sqlite /tmp/kansho.sqlite \
|
||||
--media-src /tmp/media \
|
||||
--media-dest /app/data/media
|
||||
```
|
||||
|
||||
Windows-Vorbereitung (Kopie, nicht das einzige Backup):
|
||||
|
||||
```powershell
|
||||
.\scripts\backup-local.ps1 create
|
||||
# Archiv prüfen, dann SQLite+Medien auf den Pi kopieren — nicht nach Gitea.
|
||||
```
|
||||
|
||||
4. Abnahme Dev: Profilanzahl, Journal-Days/Entries, Messages, ein Medien-GET, Gateway fail-closed. Production ohne `KANSHO_ALLOW_REMOTE_DETECT` blockiert Klartext-Detect; der Operator-Übergang bis Ollama ist explizit und dokumentiert (`guardrails.md` §22.3).
|
||||
5. Erst dann derselbe Import nach Prod (`--confirm`, leeres Volume). `--replace` nur auf einer bewussten Kopie.
|
||||
|
||||
`debug.persist_traces` nach dem Import prüfen.
|
||||
|
||||
---
|
||||
|
||||
## Postgres-Backup (Server)
|
||||
|
||||
Kein Ersatz durch `backup-local.ps1` (das bleibt der SQLite-Weg).
|
||||
|
||||
```bash
|
||||
# Dump
|
||||
cd /home/lars/docker/kansho
|
||||
docker compose exec -T postgres pg_dump -U kansho kansho > "/home/lars/backups/kansho-$(date -u +%Y%m%d).sql"
|
||||
|
||||
# Medienvolume
|
||||
docker run --rm -v kansho_kansho-media:/src -v /home/lars/backups:/dst alpine \
|
||||
tar -C /src -czf /dst/kansho-media-$(date -u +%Y%m%d).tgz .
|
||||
```
|
||||
|
||||
Restore-Übung vor dem ersten Prod-Dialogbestand nach dem Cutover wiederholen. Dump und Medien nicht an Provider und nicht in öffentliche Remotes.
|
||||
|
||||
---
|
||||
|
||||
## Manuelles Deploy
|
||||
|
||||
```bash
|
||||
# Development
|
||||
cd /home/lars/docker/kansho-dev
|
||||
git fetch origin develop && git reset --hard origin/develop
|
||||
docker compose -f docker-compose.dev-env.yml build --no-cache backend frontend
|
||||
docker compose -f docker-compose.dev-env.yml up -d --wait
|
||||
curl -sf http://localhost:8096/api/health
|
||||
|
||||
# Production
|
||||
cd /home/lars/docker/kansho
|
||||
git fetch origin main && git reset --hard origin/main
|
||||
docker compose build --no-cache backend frontend
|
||||
docker compose up -d --wait
|
||||
curl -sf http://localhost:8005/api/health
|
||||
```
|
||||
|
||||
Laptop-Checkout nach erfolgreichem Heim-Restore und Dev-Import nur noch Archiv. Keine parallelen Schreibzugriffe auf denselben persönlichen Bestand.
|
||||
@@ -0,0 +1,430 @@
|
||||
Du arbeitest im Kanshō-Repository als **fachlicher Konzept-Worker**.
|
||||
|
||||
Deine Aufgabe ist ausdrücklich **nicht**, Slice 2 zu implementieren oder technische Detailarchitektur vorwegzunehmen. Du sollst auf Basis der bestehenden kanonischen Fachkonzepte einen **fachlich belastbaren Vorschlag und Anforderungsschnitt für den zweiten vertikalen Produktslice** erarbeiten, der anschließend als Grundlage für einen Coding Agent dienen kann.
|
||||
|
||||
## Ausgangslage
|
||||
|
||||
Der erste MVP-Slice ist abgeschlossen.
|
||||
|
||||
Er realisiert einen journalzentrierten Anwendungsfall innerhalb eines Reflection Space:
|
||||
|
||||
- Beispiel Reflection Space: `Veli Lošinj 2026`
|
||||
- pro Tag kann es einen Journal Day geben
|
||||
- pro Tag können mehrere Conversations/Chats geführt werden
|
||||
- der Nutzer kann entscheiden, welcher Dialog bzw. welche Dialoge als Inputquelle für die Journalgenerierung verwendet werden
|
||||
- der ausgewählte Dialog wird **nicht direkt als Tagebucheintrag übernommen**
|
||||
- aus dem Dialog wird mehrstufig mit Hilfe der KI und des persönlichen Writing Profile ein persönlicher Journal Draft generiert
|
||||
- dieser Draft kann anschließend redigiert und als Journal Entry übernommen werden
|
||||
- das Ergebnis soll insbesondere bei Reise-/Urlaubstagebüchern eine zusammenhängende, menschenlesbare autobiografische Erinnerung ergeben
|
||||
|
||||
Diese Fähigkeit ist wertvoll und darf durch Slice 2 **nicht verschlechtert oder fachlich entwertet** werden.
|
||||
|
||||
Gleichzeitig bildet dieser MVP nur eine Teilmenge des Kanshō-Zielbilds ab.
|
||||
|
||||
Kanshō soll langfristig ein **Personal Reflection Companion** sein und nicht auf Tagesjournal bzw. Tagebuch beschränkt bleiben.
|
||||
|
||||
## Bestehendes fachliches Zielbild
|
||||
|
||||
Die vorhandenen Fachkonzepte unterscheiden insbesondere:
|
||||
|
||||
### Reflection Space
|
||||
|
||||
Der Reflection Space beschreibt den Bedeutungs-, Lebens- oder Erfahrungskontext.
|
||||
|
||||
Beispiele:
|
||||
|
||||
- `Urlaub → Veli Lošinj 2026`
|
||||
- persönliche Entwicklung
|
||||
- Beruf
|
||||
- Familie
|
||||
- ein konkretes längerfristiges persönliches Thema
|
||||
|
||||
Ein Reflection Space ist kein bloßer Ordner und kein Intent. Er bildet für den Nutzer einen verständlichen Denk- und Erfahrungsraum und soll ein wesentliches menschliches Ordnungsprinzip bleiben.
|
||||
|
||||
### Nutzungssituation / Reflection Intent
|
||||
|
||||
Die bestehende Fachkonzeption beschreibt elf vorläufig vollständige Nutzungssituationen:
|
||||
|
||||
1. Erleben festhalten
|
||||
2. Tagesreflexion
|
||||
3. Spontaner Gedanke / Moment
|
||||
4. Früheren Faden fortsetzen
|
||||
5. Tiefe Reflexion / biografische Frage
|
||||
6. Entscheidung / Orientierung
|
||||
7. Inspiration / Vision / Kreativität
|
||||
8. Achtsamkeit / Meditation / Check-in
|
||||
9. Rückblick und persönliche Entwicklung
|
||||
10. Geplante Reflexionszeit / Ritual
|
||||
11. Wiederfinden und Revue passieren
|
||||
|
||||
Diese Nutzungssituationen sind **keine elf Reflection Spaces und keine Verpflichtung zu elf technischen Intent Engines**.
|
||||
|
||||
Sie beschreiben, was der Nutzer in einer konkreten Interaktion gerade erreichen möchte.
|
||||
|
||||
Der Reflection Intent kann:
|
||||
|
||||
- explizit durch den Nutzer gesetzt werden,
|
||||
- von Kanshō aus Einstieg und Kontext erkannt werden,
|
||||
- sich im Verlauf derselben Conversation verändern.
|
||||
|
||||
Ein Intent-Wechsel soll einen natürlichen Dialog nicht automatisch in mehrere Chats zerlegen.
|
||||
|
||||
### Threads
|
||||
|
||||
Eine Conversation kann mehrere Reflexionsfäden enthalten.
|
||||
|
||||
Threads dienen langfristiger inhaltlicher Kontinuität und können über Conversations, Tage und ggf. Reflection Spaces hinweg weiterlaufen.
|
||||
|
||||
Nicht jedes Seitenthema soll automatisch einen sichtbaren oder langlebigen Thread erzeugen.
|
||||
|
||||
### Memory und Context
|
||||
|
||||
Die bestehende Baseline lautet insbesondere:
|
||||
|
||||
- aktueller Dialog zuerst
|
||||
- Primary Reflection Space vor globalem Langzeitgedächtnis
|
||||
- Long-Term Memory nur bei tatsächlichem Bedarf
|
||||
- Minimum sufficient context
|
||||
- Retrieval findet Kandidaten; Context-Auswahl entscheidet Relevanz
|
||||
- semantische Ähnlichkeit allein ist kein Relevanznachweis
|
||||
- Source bleibt kanonisch
|
||||
- Derived ersetzt Source nicht
|
||||
- Current Validity und History bleiben getrennt
|
||||
- Nutzerkorrekturen haben Vorrang
|
||||
- langfristige Dialogkontinuität muss unter Kontrolle von Kanshō bleiben
|
||||
|
||||
Die bestehende fachliche Eskalation ist sinngemäß:
|
||||
|
||||
`Current Session → Primary Reflection Space → aktive Threads / offene Fragen → relevanter Reflection Context → relevantes Kanshō Long-Term Memory → mindnet → Original Sources / Re-Grounding`
|
||||
|
||||
### Reflection Outputs
|
||||
|
||||
Ein Dialog kann mehrere unterschiedliche Ergebnisse erzeugen.
|
||||
|
||||
Beispielsweise:
|
||||
|
||||
- Journal Entry
|
||||
- Reflection Memory
|
||||
- Knowledge Delta
|
||||
- Action Candidate
|
||||
- interne Kontinuitätsstrukturen wie Thread Memory oder offene Fragen
|
||||
|
||||
Nicht jede Conversation muss ein sichtbares Output-Artefakt erzeugen.
|
||||
|
||||
## Zentrale Fragestellung für Slice 2
|
||||
|
||||
Der nächste Slice soll das heute journalzentrierte System zu einem allgemeineren dialogischen Reflexionsbegleiter weiterentwickeln.
|
||||
|
||||
Dabei muss insbesondere geprüft werden:
|
||||
|
||||
> Wie kann ein Reflection Space unterschiedliche Reflection Intents und natürlich gemischte Conversations tragen, ohne dass dadurch die heute bereits gut funktionierende Fähigkeit verloren geht, aus einem oder mehreren ausgewählten Dialogen einen kohärenten persönlichen Tages- bzw. Reisetagebucheintrag zu generieren?
|
||||
|
||||
Beispiel:
|
||||
|
||||
Im Reflection Space `Veli Lošinj 2026` beginnt eine Conversation mit der Beschreibung des Urlaubstags.
|
||||
|
||||
Während des Gesprächs sagt der Nutzer beispielsweise:
|
||||
|
||||
> „Mir fällt auf, dass ich hier im Urlaub viel bewusster lebe als zu Hause.“
|
||||
|
||||
Daraus kann sich eine längere tiefere Reflexion entwickeln.
|
||||
|
||||
Danach erzählt der Nutzer möglicherweise wieder weiter vom Tagesgeschehen.
|
||||
|
||||
Die Conversation enthält damit mindestens:
|
||||
|
||||
- autobiografisches Tageserleben
|
||||
- persönliche Reflexion
|
||||
- möglicherweise einen längerfristig relevanten Reflexionsfaden
|
||||
|
||||
Trotzdem soll aus diesem Dialog weiterhin ein **guter zusammenhängender Journal Entry über den Urlaubstag** generiert werden können.
|
||||
|
||||
Dabei darf weder gelten:
|
||||
|
||||
- „der vollständige Dialog muss ungefiltert in den Journalentwurf einfließen“
|
||||
|
||||
noch:
|
||||
|
||||
- „alles, was während eines anderen Reflection Intents gesagt wurde, darf grundsätzlich nicht in das Journal“
|
||||
|
||||
Denn eine persönliche Reflexion kann sehr wohl ein wichtiger Teil der autobiografischen Erinnerung dieses Tages sein.
|
||||
|
||||
## Deine Aufgabe
|
||||
|
||||
Erarbeite daraus einen **fachlichen Vorschlag für Slice 2**.
|
||||
|
||||
Prüfe dabei insbesondere folgende Punkte.
|
||||
|
||||
### 1. Produktthese des Slices
|
||||
|
||||
Formuliere präzise:
|
||||
|
||||
- welche neue Nutzerfähigkeit Slice 2 beweisen soll,
|
||||
- warum diese nach dem Journal-MVP der sinnvollste nächste vertikale Schritt ist,
|
||||
- welche Teile des Kanshō-Zielbilds dadurch erstmals real validiert werden.
|
||||
|
||||
Vermeide einen rein technischen „Memory-Ausbau“ als Produktthese.
|
||||
|
||||
### 2. Reflection Space als Ordnungsrahmen
|
||||
|
||||
Prüfe und konkretisiere:
|
||||
|
||||
- welche Rolle Reflection Spaces im Slice spielen,
|
||||
- wie sie für den Nutzer als nachvollziehbares Ordnungsprinzip erhalten bleiben,
|
||||
- wie Conversations mit unterschiedlichen Intents innerhalb desselben Space organisiert werden,
|
||||
- wie verhindert wird, dass Threads, Memories, Intents und Derived Objects zu einer unübersichtlichen sichtbaren Struktur führen.
|
||||
|
||||
Beachte dabei die bestehende Leitlinie:
|
||||
|
||||
> interne Reichhaltigkeit darf deutlich größer sein als die sichtbare Nutzerstruktur.
|
||||
|
||||
### 3. Multi-Intent Conversation
|
||||
|
||||
Definiere fachlich:
|
||||
|
||||
- wie der initiale Reflection Intent entsteht,
|
||||
- wie expliziter Nutzer-Intent und automatische Erkennung zusammenspielen,
|
||||
- wie sich Intent innerhalb derselben Conversation verändern darf,
|
||||
- welche Auswirkungen Intent auf Dialogtiefe, Richtung, Initiative und Kontextnutzung besitzt,
|
||||
- welche Zustände tatsächlich langlebig gespeichert werden müssen und welche nur operative Dialogsteuerung sein können.
|
||||
|
||||
Lege **nicht vorschnell eine neue reduzierte Intent-Taxonomie** fest.
|
||||
|
||||
Wenn mehrere fachliche Intents dieselbe technische Dialog-/Context-Policy verwenden könnten, darfst du dies als spätere technische Verdichtung benennen. Die elf fachlichen Nutzungssituationen sollen dadurch jedoch nicht stillschweigend ersetzt werden.
|
||||
|
||||
### 4. Erhalt des Journal-Workflows
|
||||
|
||||
Dies ist ein **zentrales Acceptance-Thema des Slices**.
|
||||
|
||||
Beschreibe fachlich, wie der bestehende Workflow erhalten bleiben kann:
|
||||
|
||||
`Reflection Space → Journal Day → ein oder mehrere Dialoge als Input auswählen → mehrstufige KI-Generierung mit Writing Profile → Journal Draft → Nutzerredaktion → Journal Entry`
|
||||
|
||||
Berücksichtige dabei insbesondere gemischte Conversations.
|
||||
|
||||
Klärungsbedarf:
|
||||
|
||||
- Wie entscheidet sich fachlich, welche Inhalte eines gemischten Dialogs für einen konkreten Journal Draft relevant sind?
|
||||
- Welche Rolle spielen Reflection Intent, Tagesbezug, Ereignisbezug, Nutzerwahl und andere Signale?
|
||||
- Kann ein und derselbe Gesprächsabschnitt für mehrere fachliche Ergebnisse relevant sein?
|
||||
- Wie bleibt der Originaldialog die Quelle?
|
||||
- Welche fachliche Provenance zwischen Quelle und Output wird benötigt?
|
||||
- Muss dafür ein eigenes langlebiges Segmentobjekt entstehen oder reicht fachlich zunächst die Fähigkeit, Outputs auf relevante Message-/Source-Bereiche zurückzuführen?
|
||||
- Welche dieser Fragen muss Slice 2 tatsächlich lösen und welche darf offen bleiben?
|
||||
|
||||
Wichtig:
|
||||
|
||||
Der Nutzer soll weiterhin auf grober Ebene entscheiden können, welche Conversation(s) eines Tages als Inputquelle für den Journal Draft dienen.
|
||||
|
||||
Kanshō darf innerhalb dieser Quellen eine feinere inhaltliche Relevanzbewertung übernehmen, ohne daraus eine komplexe Segmentverwaltungsoberfläche für den Nutzer zu machen.
|
||||
|
||||
### 5. Threads und Kontinuität
|
||||
|
||||
Bestimme den minimal notwendigen Umfang für Slice 2.
|
||||
|
||||
Prüfe:
|
||||
|
||||
- wann ein Nebenfaden lediglich temporärer Gesprächskontext bleibt,
|
||||
- wann daraus ein Thread Candidate entstehen kann,
|
||||
- wann ein langlebiger Thread erforderlich ist,
|
||||
- wie ein bereits bestehender Thread später fortgesetzt werden kann,
|
||||
- welches minimale Thread Memory dafür benötigt wird.
|
||||
|
||||
Vermeide eine vollständige Thread-Ontologie oder umfangreiche automatische Thread-Verwaltung, wenn sie für diesen Slice nicht erforderlich ist.
|
||||
|
||||
### 6. Memory und Context Builder
|
||||
|
||||
Beschreibe den minimal notwendigen fachlichen Memory-Ausbau.
|
||||
|
||||
Insbesondere:
|
||||
|
||||
- welche Memory-/Context-Schichten Slice 2 tatsächlich benötigt,
|
||||
- wie der Reflection Intent die Context-Auswahl beeinflusst,
|
||||
- welche früheren Informationen bei unterschiedlichen Intents eher relevant sind,
|
||||
- wie `Reflection Space first, Long-Term Memory on demand` erhalten bleibt,
|
||||
- wie verhindert wird, dass globale autobiografische Suche zum Normalfall jedes Turns wird.
|
||||
|
||||
Prüfe ausdrücklich, welche Fähigkeiten **noch nicht** notwendig sind.
|
||||
|
||||
### 7. Persistenz und Outputs
|
||||
|
||||
Klär fachlich, welche langlebigen Ergebnisse Slice 2 benötigt.
|
||||
|
||||
Beispielsweise:
|
||||
|
||||
- Journal Entry
|
||||
- Thread Memory
|
||||
- Open Question
|
||||
- Reflection Memory / Insight
|
||||
- ggf. andere Derived Objects
|
||||
|
||||
Nicht jedes mögliche Target-Objekt soll automatisch Bestandteil des Slices werden.
|
||||
|
||||
Für jedes vorgeschlagene langlebige Objekt beantworte:
|
||||
|
||||
- Warum benötigt der aktuelle Slice dieses Objekt jetzt?
|
||||
- Würde ein späteres Nachrüsten sonst eine grundlegende Refaktierung erzwingen?
|
||||
- Ist es sichtbares Nutzerartefakt oder primär interne Kontinuitätsstruktur?
|
||||
|
||||
Beachte die Implementation Foundation:
|
||||
|
||||
> Neue Abstraktionen benötigen aktuellen Nutzen.
|
||||
|
||||
### 8. Current Validity, Correction und Provenance
|
||||
|
||||
Sobald Derived Memory produktiv für spätere Dialoge verwendet wird, müssen mindestens die bestehenden Foundation-Regeln eingehalten werden:
|
||||
|
||||
- Source bleibt kanonisch
|
||||
- Derived ersetzt Source nicht
|
||||
- Zeit und Provenance
|
||||
- Current Validity vs. History
|
||||
- User Correction > Model Inference
|
||||
|
||||
Prüfe, welcher **minimale fachliche Korrektur- und Re-Grounding-Umfang** für Slice 2 wirklich notwendig ist.
|
||||
|
||||
Baue daraus nicht automatisch eine umfangreiche Provenance- oder Memory-Administration als Produktfeature.
|
||||
|
||||
### 9. Auswahl der Nutzungssituationen für Slice 2
|
||||
|
||||
Mappe alle elf bestehenden Nutzungssituationen auf:
|
||||
|
||||
- bereits durch MVP abgedeckt / Regression Case
|
||||
- Bestandteil Slice 2
|
||||
- bewusst später
|
||||
|
||||
Begründe die Auswahl.
|
||||
|
||||
Prüfe insbesondere, ob für Slice 2 zusätzlich zum bestehenden Journalpfad folgende Situationen geeignet sind:
|
||||
|
||||
- Spontaner Gedanke / Moment
|
||||
- Früheren Faden fortsetzen
|
||||
- Tiefe Reflexion / biografische Frage
|
||||
- Entscheidung / Orientierung
|
||||
|
||||
Übernimm diese Auswahl aber nicht ungeprüft. Wenn du einen engeren oder besseren vertikalen Schnitt begründen kannst, schlage ihn vor.
|
||||
|
||||
### 10. Acceptance Scenarios
|
||||
|
||||
Definiere wenige, aber harte End-to-End-Szenarien.
|
||||
|
||||
Mindestens zu prüfen:
|
||||
|
||||
#### A. Bestehendes Reisetagebuch als Regression
|
||||
|
||||
Space `Veli Lošinj 2026`.
|
||||
|
||||
Der Nutzer führt einen überwiegend autobiografischen Tagesdialog.
|
||||
|
||||
Der bestehende Journalworkflow funktioniert weiterhin mindestens so gut wie im MVP.
|
||||
|
||||
#### B. Gemischter Urlaubsdialog
|
||||
|
||||
Ein Dialog beginnt mit Tageserleben, geht in tiefere persönliche Reflexion über und kehrt anschließend zum Tageserleben zurück.
|
||||
|
||||
Aus dem Dialog kann weiterhin ein kohärenter persönlicher Journal Draft entstehen.
|
||||
|
||||
Die tiefere Reflexion darf dabei weder ungeprüft vollständig in das Journal übernommen noch pauschal ausgeschlossen werden.
|
||||
|
||||
#### C. Freie Nicht-Journal-Reflexion
|
||||
|
||||
Der Nutzer beginnt innerhalb eines Reflection Space mit einer persönlichen Frage.
|
||||
|
||||
Kein Journal Day ist zwingend erforderlich.
|
||||
|
||||
Kanshō führt intentgerecht einen tieferen Reflexionsdialog.
|
||||
|
||||
#### D. Früheren Faden fortsetzen
|
||||
|
||||
Nach mehreren Tagen wird ein bestehender relevanter Reflexionsfaden fortgesetzt.
|
||||
|
||||
Der Nutzer muss den bisherigen Denkstand nicht erneut vollständig erklären.
|
||||
|
||||
#### E. Intent-Wechsel
|
||||
|
||||
Der Intent verändert sich innerhalb derselben Conversation, ohne dass der Nutzer einen neuen Chat starten muss.
|
||||
|
||||
#### F. Kein relevantes Memory
|
||||
|
||||
Kanshō führt einen natürlichen Dialog, ohne künstlich frühere Erinnerungen oder Zusammenhänge anzudeuten.
|
||||
|
||||
### 11. Explizite Non-Goals
|
||||
|
||||
Grenze den Slice klar gegen das spätere Zielmodell ab.
|
||||
|
||||
Prüfe insbesondere als Non-Goals:
|
||||
|
||||
- vollständiges Self Model
|
||||
- langfristige automatische Pattern-Erkennung
|
||||
- globales semantisches Retrieval über die gesamte Biografie
|
||||
- vollständiger Reflection Graph
|
||||
- komplexes Resurfacing
|
||||
- umfassende Thread-Ontologie
|
||||
- automatische Promotion jedes Gedankens
|
||||
- mindnet-/Kairo-/Obsidian-Vollintegration
|
||||
- Meditation/Achtsamkeit als eigener großer Interaction Slice
|
||||
- vollständiger Entwicklungsrückblick
|
||||
- Revue-/Recall-System
|
||||
- elf technische Intent Engines
|
||||
|
||||
### 12. Auswirkungen auf bestehende Fachkonzepte
|
||||
|
||||
Prüfe zum Abschluss:
|
||||
|
||||
- welche bestehenden Fachentscheidungen der Slice lediglich konkretisiert,
|
||||
- wo tatsächlich eine neue fachliche Entscheidung erforderlich ist,
|
||||
- welche Dokumente später additiv aktualisiert werden müssten,
|
||||
- ob irgendwo bestehende Konzepte widersprüchlich oder für den Slice noch unzureichend sind.
|
||||
|
||||
Ändere keine kanonischen Dateien in diesem Arbeitsschritt.
|
||||
|
||||
## Zu lesende kanonische Grundlage
|
||||
|
||||
Lade mindestens:
|
||||
|
||||
- `docs/architecture/functional/produktvision_und_produktidentitaet.md`
|
||||
- `docs/architecture/functional/usage_situations.md`
|
||||
- `docs/architecture/functional/reflection_spaces.md`
|
||||
- `docs/architecture/functional/dialogue_model.md`
|
||||
- `docs/architecture/functional/memory_and_context.md`
|
||||
- `docs/architecture/functional/reflection_outputs.md`
|
||||
- `docs/architecture/functional/implementation_foundation.md`
|
||||
|
||||
Zusätzlich gezielt, soweit für konkrete Entscheidungen erforderlich:
|
||||
|
||||
- `resurfacing_and_saturation.md`
|
||||
- `context_fidelity_and_regrounding.md`
|
||||
- `writing_profile_and_journaling.md`
|
||||
- `mvp.md`
|
||||
- aktuelle technische MVP-Dokumentation beziehungsweise Code nur zur Prüfung von Ist-Stand und Migrationsrisiko
|
||||
|
||||
Verwende `mvp_stand_und_abgleich.md` nur mit Vorsicht als historischen Snapshot, falls der aktuelle Repo-Stand inzwischen weiterentwickelt wurde.
|
||||
|
||||
## Erwartetes Ergebnis
|
||||
|
||||
Liefere einen strukturierten fachlichen Slice-Vorschlag mit:
|
||||
|
||||
1. Executive Summary
|
||||
2. Produktthese
|
||||
3. fachlichem Zielbild des Slices
|
||||
4. Fit-Gap zum abgeschlossenen Journal-MVP
|
||||
5. Mapping der elf Nutzungssituationen
|
||||
6. Rollen von Space, Conversation, Intent, Thread, Memory und Output
|
||||
7. Journal-Regressionsmodell einschließlich gemischter Conversations
|
||||
8. minimalem Memory-/Continuity-Umfang
|
||||
9. notwendigen fachlichen Objekten und Beziehungen
|
||||
10. Acceptance Scenarios und Acceptance Criteria
|
||||
11. expliziten Non-Goals
|
||||
12. offenen Produktentscheidungen
|
||||
13. empfohlenen Dokumentationsänderungen
|
||||
14. klarer Empfehlung, ob dieser Slice der optimale nächste vertikale Schritt ist oder ob ein kleinerer/besserer Schnitt vorzuziehen ist
|
||||
|
||||
Wichtig:
|
||||
|
||||
- Keine Implementierung beginnen.
|
||||
- Keine Dateien verändern.
|
||||
- Keine Target Capabilities allein deshalb vorbauen, weil sie im Gesamtmodell existieren.
|
||||
- Fachliche Anforderungen und technische mögliche Umsetzung klar trennen.
|
||||
- Bestehende Entscheidungen nicht stillschweigend ersetzen.
|
||||
- Bei Widersprüchen zwischen Dokumenten diese explizit benennen.
|
||||
- Den bestehenden Reisetagebuch-Workflow als harte Regression behandeln.
|
||||
- Ziel ist ein **umsetzbarer vertikaler Slice**, nicht eine neue vollständige Kanshō-Gesamtarchitektur.
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
title: "Kanshō – Dokumentationsindex und Context Bundles"
|
||||
status: "Arbeitsstand"
|
||||
date: "2026-08-18"
|
||||
date: "2026-09-07"
|
||||
product_family: "Jinkendo"
|
||||
document_role: "Documentation Index / Context Loading Guide"
|
||||
parent_document: "fachliche_zielarchitektur.md"
|
||||
@@ -13,7 +13,7 @@ Dieses Dokument dient dazu, für weitere Konzeptarbeit nur die tatsächlich ben
|
||||
|
||||
## 1. Root-Dokumente
|
||||
|
||||
- `handover.md` – Session-Bootstrap für die **Konzept-/Interviewarbeit**; nicht der Code-Stand. Implementierungsstand und Fit-Gap: `mvp_stand_und_abgleich.md`.
|
||||
- `handover.md` – Session-Bootstrap für die **Konzept-/Interviewarbeit**; nicht der Code-Stand. Implementierungsstand und Fit-Gap: `mvp_stand_und_abgleich.md`. Umgebungswechsel Laptop → Heim/Server: `../technical/environment_handover.md`.
|
||||
- `fachliche_zielarchitektur.md` – Governance, Dokumentationsprinzipien, Querschnittsinvarianten, Dateistruktur.
|
||||
- `produktvision_und_produktidentitaet.md` – Vision, Identität, Scope, Produktprinzipien und Nicht-Ziele.
|
||||
- `interview_plan.md` – Kapitelplan, Interviewmethode, Fortschritt und nächster Interviewblock.
|
||||
@@ -94,6 +94,7 @@ Kanonisches Home der Fit-Gap-Analyse ist `mvp_stand_und_abgleich.md`. Es ersetzt
|
||||
3. `self_model_and_lived_experience.md`
|
||||
4. `memory_and_context.md`
|
||||
5. das konkret betroffene Technik- oder Integrationskapitel
|
||||
6. bei Detect-Selbstlernen (Konzept, nicht Code-Stand): `docs/work_orders/detect_self_learning_pipeline.md`
|
||||
|
||||
## 4. Technische Architektur
|
||||
|
||||
@@ -103,6 +104,8 @@ Sie übernimmt den Produktrahmen **weitgehend von Mitai**. Datenschutz, Privacy
|
||||
|
||||
Technische Umsetzung des gebauten Journal-Slices: `../technical/mvp_implementation.md`. Fit-Gap bleibt fachlich: `mvp_stand_und_abgleich.md`.
|
||||
|
||||
Arbeitsaufträge (kein Ersatz kanonischer Kapitel): `docs/work_orders/` – Laptop-Abschluss, Heim-Setup, Debug-Export, Dialog/Memory-Slice, Selbstlern-Detect-Pipeline (`detect_self_learning_pipeline.md`, Konzept 2026-09-11). Slice-2-Konzeptbrief derzeit `Idea_seconmd_sclide.md`.
|
||||
|
||||
## 5. Ladeprinzip
|
||||
|
||||
> **Nicht alle Kanshō-Dokumente gleichzeitig laden.** Root-Dokumente plus die 2–4 fachlich betroffenen Dateien bilden den Standardkontext.
|
||||
|
||||
@@ -693,6 +693,44 @@ Additiv. Keine Wortlisten und keine textbezogenen Ausnahmen.
|
||||
|
||||
**Additiv 2026-08-28 (Prüffassung vs. Ausgabe):** Die interne Klartext-zu-Token-Normalisierung der Modellantwort bleibt die Prüffassung. Die sichtbare und gespeicherte Fassung rehydriert nur tatsächlich ausgegebene Platzhalter; modellseitiger Klartext behält seine Oberflächenform.
|
||||
|
||||
## 22.3 Übergang: externes Klartext-Detect in Production (2026-09-08)
|
||||
|
||||
Additiv. Ändert nicht das Ziel. Technische Abbildung: `../technical/privacy_gateway.md` §9.6.
|
||||
|
||||
**Entschieden (Endbetrieb):** Semantische Detection vor jedem persönlichen Generate bleibt Pflicht. Produktivziel ist ein lokales Detect-Modell. Das Privacy Gateway bleibt nicht abschaltbar. Generate sieht nur maskierten Kontext. Keys bleiben in der Umgebung, nicht in der Datenbank.
|
||||
|
||||
**Entschieden (Übergang, explizite Operatoranforderung):** Bis ein lokales Detect (Ollama) angebunden ist, darf Production externes Klartext-Detect nutzen, wenn der Operator `KANSHO_ALLOW_REMOTE_DETECT` setzt. Development/Test erlauben remote Detect weiter ohne dieses Flag. Ohne Flag bleibt Production fail-closed, sobald Detect nicht lokal ist.
|
||||
|
||||
Das ist kein Admin-Feature-Flag und kein Umdeuten von `KANSHO_ENV=production` nach Development. Default bleibt blockiert. Die Detect-Stufe sendet in diesem Übergang Klartext an den konfigurierten Detect-Endpunkt; das ist das bekannte Restrisiko der Testphase, nicht der Zielpfad.
|
||||
|
||||
**Entschieden (Modellwahl):** Maskierung und Sprachmodell bleiben zwei getrennte Stufen. URL und Modell sind je Stufe in Admin → Schnittstellen wählbar. Das größere Modell gehört an Generate, nicht zwingend an Detect.
|
||||
|
||||
**Additiv 2026-09-08 (LLM-Profile / LAN-Ollama):** Benannte Profile speichern Endpunkt und Modell ohne Keys. Ein Wechsel lädt das gespeicherte Profil. RFC1918-Ollama (`192.168.2.144:11434`) liegt in der lokalen Trusted Zone; Detect dorthin ist kein externes Klartext-Detect.
|
||||
|
||||
**Später prüfen:** Flag entfernen, sobald lokales Detect auf Prod läuft. Dann wieder Production ohne Klartext-Detect.
|
||||
|
||||
## 22.4 Übergang: Detect-Lernmodus (2026-09-08)
|
||||
|
||||
Additiv. Technische Abbildung: `../technical/privacy_gateway.md` §9.7.
|
||||
|
||||
**Entschieden (Übergang):** Doppeldeutigkeiten werden nicht als eigene Wortliste gepflegt. Sinne entstehen aus Bestätigungen im Dialog (Identität / nicht schützenswert). Beides bei derselben Schreibweise markiert sie als mehrdeutig.
|
||||
|
||||
**Entschieden (Übergang):** Im Admin konfigurierbarer Detector-Modus `semantic` (Default) oder `learning`. Lernmodus öffnet vor Generate ein Bestätigungs-Popup für Detect-Treffer im aktuellen Nutzersatz. Das ist mehr Arbeit am Anfang und kein Ersatz für semantische Detection.
|
||||
|
||||
**Entschieden (Übergang):** Eine Mini-Passage an ein internes Modell geht nur bei bereits mehrdeutiger Schreibweise und nur an ein lokales Detect. OpenRouter sieht diese Passage nicht. Fehlt das lokale Modell, bleibt das Popup.
|
||||
|
||||
**Additiv 2026-09-10:** Eine bestätigte Nennung wird nicht erneut gefragt, wenn derselbe lokale Kontext wiederkehrt. Enge Verwandtschaftsbindung in der Nominalphrase (auch Apposition: `Sushi, meine Frau`) ist ein Hinweis, nicht die ganze Wahrheit. Der gespeicherte Ausschnitt ist der Kontext für eine lokale Vorentscheidung.
|
||||
|
||||
**Additiv 2026-09-11 (GLiNER-Vorstufe):** Im Lernmodus darf die LAN-Instanz `http://192.168.2.144:8090` den aktuellen Nutzersatz sehen (`POST /v1/extract`). Gelernte Sinne/Cues bleiben führend. Unsichere Nennungen gehen als Mini-Passage an ein im Admin gewähltes LLM-Profil (Ollama oder OpenRouter), nicht an die Detect-Stufe. OpenRouter-Maskierung bleibt vollständig konfigurierbar und ist in diesem Slice weiter der Egress-Detect. GLiNER ist kein alleiniges Detect und keine Wortliste. Fail-soft, wenn der Dienst fehlt.
|
||||
|
||||
**Additiv 2026-09-11 (Selbstlern-Pipeline, Konzept):** Zielbild mit Schülerpfad vor GLiNER/Lehrer und zwei Lernstufen: `../../work_orders/detect_self_learning_pipeline.md`. Das ersetzt den laufenden Lernmodus-Code nicht. Offene Punkte dort §6 vor der Umsetzung klären.
|
||||
|
||||
**Additiv 2026-09-11 (Selbstlern-Pipeline, §6 geschlossen):** Start ist Lernmodus Stufe 1: Schüler (Cues, Verwandtschaft, Homonym-Mini-LLM nur bei beiden Sinnen, GLiNER) parallel zum Lehrer auf dem unveränderten Nutzersatz. Admin: Zielpfad, Lernen Stufe 1/2/manuell, Bypass (alter Voll-Detect, mittelfristig weg). Default nach Umbau: Stufe 1. Neuer Cue bei nur Identity-Hits bleibt sichtbar (Sushi-Tag-21). Cue gilt pro Vorkommen. Lehrer-Miss eines bestätigten Cues ohne Meldung verlernt nicht. FOOD gegen PERSON ist immer Diff. Diagnose nur Zähler ohne Klartext. Gilt für alle persönlichen Detect-Aufrufe einschließlich Journalentwurf. GLiNER bleibt fail-soft im Lernmodus (dann manuelle Review); außerhalb Lernmodus Bestätigung vor öffentlichem Klartext-Egress. Gateway nicht abschaltbar.
|
||||
|
||||
**Additiv 2026-10-12:** FOOD gegen PERSON bleibt ein Typkonflikt im Zähler. Ein **bereits bestätigter** Cue wird dabei nicht erneut gefragt und nicht still geändert — derselbe lokale Kontext wie am 2026-09-10. Unbestätigte Nennungen mit abweichendem Schutz bleiben im Popup.
|
||||
|
||||
**Nicht:** Gateway abschalten, Detect-Treffer auto-speichern, `Sushi_`/`Sushi+` im Nutzertext, Pattern-Wortliste als Wahrheit.
|
||||
|
||||
---
|
||||
|
||||
# 23. Externe Referenzquellen
|
||||
|
||||
@@ -15,7 +15,9 @@ canonical_docs_path: "docs/architecture/functional/"
|
||||
|
||||
Dieses Dokument ist der **vollständige fachliche Aufsatzpunkt für eine neue Kanshō-Konzept-Session**.
|
||||
|
||||
**Implementierungsstand (Code)** steht nicht hier, sondern in `mvp_stand_und_abgleich.md` (2026-08-25): Slice gegen Foundation, MVP-Text und Gesamtziel. Dieses Handover bleibt der Konzept-/Interview-Bootstrap.
|
||||
**Implementierungsstand (Code)** steht nicht hier, sondern in `mvp_stand_und_abgleich.md` (2026-08-25, Opening-Additiv 2026-09-03/07): Slice gegen Foundation, MVP-Text und Gesamtziel. Dieses Handover bleibt der Konzept-/Interview-Bootstrap.
|
||||
|
||||
**Umgebungswechsel Laptop → Heim/Server (2026-09-07):** nicht hier, sondern `docs/architecture/technical/environment_handover.md` plus `docs/architecture/technical/runtime_and_deploy.md` §7.2. Opening-Invariante (kein Folgetag aus Entry-Prefix): `mvp.md` §6.1.
|
||||
|
||||
Es soll ermöglichen, die Arbeit ohne Rückgriff auf den langen bisherigen Chat fortzusetzen und dabei insbesondere verhindern, dass:
|
||||
|
||||
|
||||
@@ -388,7 +388,11 @@ Der erste Gesprächsimpuls unterliegt derselben Dialog-Policy wie spätere Folge
|
||||
|
||||
**Status: Code vorhanden, journalspezifisch, keine universelle Continuation-Engine.**
|
||||
|
||||
Ein neu gestarteter Journal-Dialog erhält einen ersten Kanshō-Impuls. Belegte Vorhaben und offene user-Punkte desselben Journal Day dürfen den Einstieg stützen. Recency allein ist kein Muster. Assistententext ist Kontext, kein Nutzerfakt. Ohne relevanten Kontext: kurzer neutraler lokaler Einstieg. Fehlgeschlagener Modelloutput speichert keine beschädigte Nachricht.
|
||||
Ein neu gestarteter Journal-Dialog erhält einen ersten Kanshō-Impuls. Belegte Vorhaben dürfen den Einstieg stützen, wenn sie aus dem **user-Dialog des unmittelbar vorigen Kalendertags** stammen. Offene user-Punkte gelten nur für denselben Journal Day. Recency allein ist kein Muster. Ein gespeicherter Journal-Eintrag ist abgeschlossene Erzählung, kein offenes Vorhaben; ein 400-Zeichen-Entry-Ausschnitt darf keinen Folgetag als offenen Faden führen. Assistententext ist Kontext, kein Nutzerfakt. Ohne relevanten Kontext: kurzer neutraler lokaler Einstieg. Fehlgeschlagener Modelloutput speichert keine beschädigte Nachricht.
|
||||
|
||||
**Additiv 2026-09-03:** Der Opening-Pfad lädt Space-Recency nicht in den Modellkontext. Gestern angekündigte Vorhaben bleiben ein Folgetag lang zulässig; ältere oder nur im Entry vorkommende Formulierungen („auf den nächsten Tag“) erzeugen den neutralen Einstieg.
|
||||
|
||||
**Additiv 2026-09-07 (Fehlerbild, ohne Thread-Engine):** Ein nachgetragener Morgenanker (späte user-Zeile mit früher Uhrzeit) kann im Journal am Textanfang landen. Ein festes Prefix (400 Zeichen) liest dann Überlegung ohne späteren Vollzug und erzeugt tagelang denselben Einstieg. Das ist kein Primär-Thread, sondern Recency plus Plan-Regex. **Bewusst offen:** dieselben 400-Zeichen-Ausschnitte bleiben im *laufenden* Dialogzug (`dialogue_turn`) als Hinweis geladen; sie sind kein Opening-Mandat mehr. Entfernen oder Relevanz statt Prefix ist Slice-2-/Memory-Thema, nicht Opening-Regression.
|
||||
|
||||
---
|
||||
|
||||
@@ -439,6 +443,8 @@ Im MVP ist der Space-Kontext im Dialogzug die letzten gespeicherten Journal Entr
|
||||
|
||||
Fachliche Inhaltsquelle der Journalgenerierung sind die ausdrücklich ausgewählten Conversations des Journal Day. Stufe 2 erhält ausschließlich das lokal erzeugte Verified Artifact. Frühere Space Entries sind keine zusätzliche Faktenquelle in Generate. Das Writing Profile darf nur die Form beeinflussen. Space-Kontext kann die Dialogführung stützen, wird aber nicht still zur Journalquelle.
|
||||
|
||||
**Additiv 2026-08-29:** Ob Core, Facet, Traits und Style Examples überhaupt in den Prompt gelangen, bestimmt die gewählte Stilanwendungsausprägung (`writing_profile_and_journaling.md`). `Ohne persönliches Profil` ist eine profilfreie Kontrollgruppe. Der aktuelle Tagesdialog bleibt Inhaltsquelle, nicht Stilvorlage.
|
||||
|
||||
---
|
||||
|
||||
## 8.3 Generierungsprinzip
|
||||
@@ -557,6 +563,8 @@ Der Current Brief wird lokal zusammengesetzt, ohne zusätzlichen Modell-Call:
|
||||
|
||||
Finale Nutzerfassungen haben höheres Gewicht (mehr und längere Exzerpte, Stimme vor Dialog). Ohne Import ist der erste Generate-Tag nicht stil-leer (Formhinweise), aber nicht eine zweite Kopie desselben Dialogs.
|
||||
|
||||
**Additiv 2026-08-29:** Die Stilanwendungsausprägung filtert, welche dieser lokal zusammengesetzten Stilquellen den Provider überhaupt erreichen. Ohne Freigabe entfallen Core, Facet, Traits und Beispiele vollständig, einschließlich Formhinweisen aus dem Tagesdialog. Das ändert die Quellenpriorität nicht; es begrenzt den Egress.
|
||||
|
||||
---
|
||||
|
||||
# 10. Journal Editor
|
||||
|
||||
@@ -43,7 +43,7 @@ Nicht durch Fake-Provider bewiesen:
|
||||
|
||||
Kein Codefehler des Freeze Candidate, sondern Betriebsreife:
|
||||
|
||||
- PostgreSQL, Docker/Compose, TLS, Reverse Proxy
|
||||
- PostgreSQL, Docker/Compose, TLS, Reverse Proxy — **nach** SQLite-Restore der Urlaubsdaten (`../technical/environment_handover.md`, `../technical/runtime_and_deploy.md` §7.2)
|
||||
- Gitea-Pipelines / CI
|
||||
- Ollama bzw. lokales Detect-Modell
|
||||
- Verschlüsselung at rest, DSFA, persistentes Audit ohne Prompts
|
||||
|
||||
@@ -137,6 +137,8 @@ Additiv zu Abschnitt 2. Kein horizontaler Slice, kein Target-Model-Vorbau. Korri
|
||||
|
||||
Tests: `backend/tests/test_architecture_correction.py` plus Anpassungen in `test_mvp_journal.py` und `test_privacy_detect.py`.
|
||||
|
||||
**Additiv 2026-09-08:** Die Detect-Zeile in der Tabelle oben ist der Ist-Stand von 2026-08-25. Pattern-Fallback ist überholt. Production bleibt ohne lokales Detect default fail-closed; der Operator-Übergang `KANSHO_ALLOW_REMOTE_DETECT` ist in `guardrails.md` §22.3 festgehalten.
|
||||
|
||||
---
|
||||
|
||||
# 2.2 Profile Governance (2026-08-25)
|
||||
@@ -389,7 +391,7 @@ Er ist **noch nicht Kanshō im Sinne der Vision**. Die gefährlichen Drifts sind
|
||||
| Automatische Space-Erkennung | nein | **Bewusst offen** |
|
||||
| Semantisches Retrieval | nein | **Bewusst offen** |
|
||||
| Session Summary | nein | **Bewusst offen** |
|
||||
| Zusätzliche Enrichment-Calls | Detect in Development/Test optional remote | **Abweichung** gegenüber Produktivziel „Detect lokal“; Produktivmodus lässt externes Klartext-Detect nicht als normalen Pfad zu |
|
||||
| Zusätzliche Enrichment-Calls | Detect in Development/Test optional remote | **Abweichung** gegenüber Produktivziel „Detect lokal“; Produktivmodus lässt externes Klartext-Detect nicht als normalen Pfad zu. **Additiv 2026-09-08:** expliziter Operator-Übergang `KANSHO_ALLOW_REMOTE_DETECT`, Ziel bleibt lokal. |
|
||||
|
||||
## 4.4 Foundation Non-Goals
|
||||
|
||||
@@ -439,10 +441,10 @@ Foundation-Verletzungen, die ein Refactor erzwingen würden, sind **nicht** gefu
|
||||
| Kein Fragebogen; Reflexionspartner | **Teilweise** | Prompt und Stimme zielen darauf. Qualität ist modellabhängig. Lokale Wächter gegen Recap, erfundenen Vollzug, erfundene Empfindung, Systemfloskeln, Schluss-Wiederöffnung. `local_hold` bittet um Fortsetzung statt Floskel. |
|
||||
| Sechs Operationen, keine Intent-Engines | **Erfüllt** | Ein Call, JSON `{operation, impulse}`; sichtbar ist `impulse` |
|
||||
| Register lokal, kein zweites Modell | **Erfüllt** | `infer_register` |
|
||||
| Bekannter Tagesplan (Cres-Beispiel) | **Teilweise / Ungenauigkeit** | Plan kann aus begrenzten Recency-Ausschnitten **gespeicherter Entries** oder **jüngerer Original-Conversations** desselben Space kommen. Kein Plan-Objekt, keine zeitliche Vor/Nach-Logik, kein semantisches Retrieval. |
|
||||
| Bekannter Tagesplan (Cres-Beispiel) | **Teilweise / Ungenauigkeit** | **Opening (seit 2026-09-03):** nur user-Dialog des vorigen Kalendertags, nicht gespeicherte Entries. **Laufender Dialogzug:** Recency-Ausschnitte (Entries und jüngere Original-Conversations) bleiben Hinweis. Kein Plan-Objekt, keine Vor/Nach-Logik über den Folgetag hinaus, kein semantisches Retrieval. |
|
||||
| Wiederkehrende Aktivität (Japanisch-Beispiel) | **Gap** | Keine Zählung über Morgenbeschreibungen. Recency kann den Treffer zufällig enthalten oder nicht. |
|
||||
| Keine triviale Gefühlsfrage nach selbst benannter Emotion | **Teilweise** | Prompt + `is_unearned_stance`. Kein Dialogzustand „bereits beantwortet“. |
|
||||
| Kontextsensitiver Einstieg statt „Erzähl von deinem Tag“ | **Erfüllt** als begrenzte Keimzelle | Erster Impuls aus belegtem Plan oder offenem Tagesfaden; sonst neutral. Keine Pattern-Engine. |
|
||||
| Kontextsensitiver Einstieg statt „Erzähl von deinem Tag“ | **Erfüllt** als begrenzte Keimzelle | Erster Impuls aus belegtem *gestrigem* user-Plan oder offenem Tagesfaden; sonst neutral. Entries und Prefix-Recency sind kein Einstieg. Keine Pattern-Engine. |
|
||||
| Unterbrechen und Fortsetzen am selben Day | **Erfüllt** | Transcript bleibt. **Teilweise:** keine lokale Karte „welche Tagesabschnitte schon da sind“. |
|
||||
| Folgetag-Fortsetzung dem ursprünglichen Day zuordnen | **Erfüllt** | Nutzer öffnet den Day; Message-Zeit ist unabhängig. |
|
||||
|
||||
@@ -472,6 +474,10 @@ Foundation-Verletzungen, die ein Refactor erzwingen würden, sind **nicht** gefu
|
||||
| Lernsignale §9.3 vollständig | **Teilweise** | Satzlänge, Chronologie vs. Thema, Uhrzeiten, Reflexionsanteil, Humor. **Gap:** Umgang mit Namen, typische Übergänge, Wortwahl als eigene Signale. |
|
||||
| Dialogzug ohne Stil-Exzerpte des offenen Turns | **Erfüllt** | |
|
||||
|
||||
**Additiv 2026-08-29:** Die Stilanwendung filtert Writing-Profile-Core, Facet, Traits und Style Examples je benannter Voice-Ausprägung. `Ohne persönliches Profil` ist eine profilfreie Kontrollgruppe. Space-Kontext und faktisches Langzeitgedächtnis bleiben keine Stilquellen.
|
||||
|
||||
**Additiv 2026-08-29:** Vergleichsausprägungen `Legacy – vor Stilkontextsteuerung` rekonstruiert die frühere volle Stilkontextsemantik unter neuen IDs. Vorhandene Voice-IDs bleiben unverändert.
|
||||
|
||||
## 5.7 Editor, Versionen, Nachschlagen, Screens
|
||||
|
||||
| Anforderung | Stand | Befund |
|
||||
@@ -514,7 +520,7 @@ Foundation-Verletzungen, die ein Refactor erzwingen würden, sind **nicht** gefu
|
||||
1. **`mvp.md` §1 und §5.1** versprechen „relevante frühere Aussagen“ und „wiederkehrende Aktivitäten“. Der Code liefert Recency-Ausschnitte finaler Entries plus begrenzte Original-Ausschnitte jüngerer Space-Conversations. Der klarstellende Absatz in §5.1 und §8.2 ist der gültige Implementierungsstand; die Beispiele §5.4–5.5 und Case C bleiben **schärfer als der Code** (kein Plan-Objekt, keine Wiederholungszählung).
|
||||
2. **`mvp.md` §17** sprach vom „nächsten Schritt: technischen Plan ableiten“. Der Slice ist gebaut. Dieses Dokument ist der Abgleich; die Formulierung in §17 bleibt historisch.
|
||||
3. **`mvp.md` §4.1 Konsolidierung** beschreibt narrative Kriterien. Der Slice nutzt lokale Signale derselben Dimensionen, keine LLM-Typklassifikation.
|
||||
4. **`mvp.md` §6 Einstieg** verlangt einen kontextsensitiven ersten Impuls. Seit 2026-08-25: journalspezifischer Opening-Adapter; ohne belegten Plan oder offenen Tagesfaden lokal neutral.
|
||||
4. **`mvp.md` §6 Einstieg** verlangt einen kontextsensitiven ersten Impuls. Seit 2026-08-25: journalspezifischer Opening-Adapter; ohne belegten Plan oder offenen Tagesfaden lokal neutral. **Additiv 2026-09-03/07:** Plan nur noch aus dem user-Dialog des unmittelbar vorigen Kalendertags, nicht aus Journal-Entries oder älterer Recency. Opening-Call ohne Space-Recency. Ein 400-Zeichen-Entry-Prefix (typisch: nachgetragener Morgenanker ohne späteren Vollzug) ist kein Opening-Mandat. Der laufende Dialogzug lädt Recency-Ausschnitte weiterhin; das ist kein Slice-Gap des Openings, sondern bewusst offene Heuristik bis zu Relevanz/Memory.
|
||||
5. **`mvp.md` §8.2 Punkt 2** Space-Kontext bei der Generierung: Generate sieht Prior-Entries nicht. Für diesen Freeze bewusst so begrenzt (`mvp.md` §8.2.1).
|
||||
6. **`mvp.md` §9.3** listet Lernsignale, von denen nur ein Teil heuristisch existiert.
|
||||
7. **`mvp.md` §11.3 / §13.1–13.2** Papierkorb-UI und Entry-Liste sind vorhanden. Dialog-Medien bleiben bewusst aus (`mvp.md` §10.2).
|
||||
@@ -545,6 +551,7 @@ Zielmodell und Non-Goals, nicht „vergessen im MVP“:
|
||||
- Contextual Continuation als Ziel-IA (der Freeze hat nur eine journalspezifische Startkeimzelle)
|
||||
- Browser-Zurück als harter Unsaved-Blocker (Data-Router)
|
||||
- Dialogmedien als direkte Dialogquelle
|
||||
- Prefix-Recency (400 Zeichen) als Hinweis im *laufenden* Dialogzug; Relevanz statt Prefix bleibt Zielmodell (`resurfacing_and_saturation.md`)
|
||||
|
||||
---
|
||||
|
||||
@@ -554,7 +561,7 @@ Keine neue Horizontal-Konzeption. Getrennt halten, sonst baut ein Agent das Targ
|
||||
|
||||
## 8.1 Distanz zum **freigegebenen MVP-Text** (`mvp.md`)
|
||||
|
||||
1. **Case C Wiederholung** – wiederkehrende Aktivität bleibt Recency, keine Zählung. Der erste Impuls greift nur belegte Pläne oder offene Tagesfäden auf.
|
||||
1. **Case C Wiederholung** – wiederkehrende Aktivität bleibt Recency, keine Zählung. Der erste Impuls greift nur belegte Pläne aus dem user-Dialog von gestern oder offene Tagesfäden desselben Journal Day auf; Journal-Entries nicht.
|
||||
2. **Generate und Space-Ausschnitte** – für diesen Freeze entschieden: Day-Conversations plus Verified Artifact, keine Prior-Entries als Generate-Fakten (`mvp.md` §8.2.1).
|
||||
3. **Dialog-Medien** – bewusst gestrichen für den Slice (`mvp.md` §10.2); Editor-Medien bleiben.
|
||||
4. **Lokales Detect-Modell** – Klartext an externe Detect-Provider ist in Production blockiert; Ollama als Ablösung der Dev/Test-Phase bleibt offen.
|
||||
@@ -593,6 +600,7 @@ Ein Agent, der 8.2 in diesem Slice „schließt“, verletzt Foundation-Regeln 2
|
||||
|---|---|
|
||||
| `backend/privacy_gateway.py`, `entity_detect.py`, `pronoun_bind.py`, `identity_store.py` | Egress, Maskierung, Dialog-Pronomen |
|
||||
| `backend/context_builder.py`, `retrieval.py`, `conversation_signals.py` | Interner Kontext, Selection-Specs, lokale Dialogsignale |
|
||||
| `backend/journal_opening.py` | Erster Journal-Impuls; Plan nur gestriger user-Dialog; Opening ohne Space-Recency |
|
||||
| `backend/dialogue_turn.py` | Ein Call, Operation/Impuls, lokale Wächter; kein Writing-Profile-Kernel |
|
||||
| `backend/journal_generate.py`, `journal_shape.py`, `journal_body.py` | Entwurf, Shape, Titel/Markdown |
|
||||
| `backend/journal_store.py`, `journal_policy.py` | Entries, Versionen, Scratch, explizites Generate |
|
||||
@@ -614,6 +622,7 @@ Ein Agent, der 8.2 in diesem Slice „schließt“, verletzt Foundation-Regeln 2
|
||||
| `backend/tests/test_journal_shape.py` | Keine Pronomenersetzung nach Demask; akzeptierter Wortlaut bleibt | Modellqualität, Stil |
|
||||
| `backend/tests/test_writing_profile.py` | Quellenpriorität | „klingt wie die Person“ |
|
||||
| `backend/tests/test_frame.py` | Auth, Prompts, Rahmen | Journal-IA |
|
||||
| `backend/tests/test_journal_opening.py` | Neutral, Folgetag-Plan, abgeschlossener Entry kein Mandat, Plan älter als gestern entfällt | Opening-Qualität des Modells |
|
||||
| `frontend/src/journal/document.test.js` | Markdown-Runde | Editor-UX, Dirty-Flag |
|
||||
|
||||
Laufzeit lokal: Frontend Port **5188**, Backend **8018**, SQLite `backend/data/kansho.sqlite`. Prompt-Templates in der DB werden bei unangetasteten Seeds durch `init_db` aktualisiert; nach Prompt-Änderungen Backend neu starten.
|
||||
|
||||
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user