Update .gitignore to exclude Python-related files and directories. Enhance AGENTS.md and README.md with clarifications on documentation structure and product identity. Add technical architecture references and local setup instructions. Revise privacy guardrails and product identity documents for consistency. Remove obsolete memory and context documentation. Expand reflection spaces documentation to define context boundaries and lifecycle. Ensure all changes align with the ongoing development of the Kanshō project.

This commit is contained in:
Lars committed 2026-08-21 15:48:43 +02:00
1 parent 3a367b7bcc
commit d62673e48b
89 files changed
+13463 -241

No files matched your search

+71
View File
@@ -0,0 +1,71 @@
"""Session auth. Identity always comes from the session, never from a client profile header."""
from __future__ import annotations
import secrets
from datetime import datetime, timedelta
from typing import Optional
import bcrypt
from fastapi import Header, HTTPException
from db import get_db, row_to_dict
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
def verify_password(password: str, stored_hash: str) -> bool:
if not stored_hash:
return False
try:
return bcrypt.checkpw(password.encode(), stored_hash.encode())
except Exception:
return False
def make_token() -> str:
return secrets.token_urlsafe(32)
def get_session(token: str) -> dict | None:
if not token:
return None
with get_db() as conn:
row = conn.execute(
"""
SELECT s.token, s.profile_id, s.expires_at, p.role, p.name, p.email
FROM sessions s
JOIN profiles p ON p.id = s.profile_id
WHERE s.token = ? AND s.expires_at > datetime('now')
""",
(token,),
).fetchone()
return row_to_dict(row)
def require_auth(x_auth_token: Optional[str] = Header(default=None, alias="X-Auth-Token")):
session = get_session(x_auth_token)
if not session:
raise HTTPException(401, "Nicht eingeloggt")
return session
def require_admin_dep(x_auth_token: Optional[str] = Header(default=None, alias="X-Auth-Token")):
session = get_session(x_auth_token)
if not session:
raise HTTPException(401, "Nicht eingeloggt")
if session.get("role") != "admin":
raise HTTPException(403, "Keine Berechtigung")
return session
def create_session(profile_id: str, session_days: int = 30) -> tuple[str, datetime]:
token = make_token()
expires = datetime.utcnow() + timedelta(days=session_days)
with get_db() as conn:
conn.execute(
"INSERT INTO sessions (token, profile_id, expires_at) VALUES (?, ?, ?)",
(token, profile_id, expires.isoformat(sep=" ")),
)
return token, expires
+20
View File
@@ -0,0 +1,20 @@
{
"kinds": [
{
"id": "working_context_snapshot",
"description": "Kurzlebiger Arbeitsstand einer Conversation. Keine bestätigte Erkenntnis."
},
{
"id": "thread_memory",
"description": "Quellengebundene Verdichtung eines Fadens. Ersetzt das Original nicht."
},
{
"id": "thread_candidate",
"description": "Intern markierter möglicher Faden. Nicht automatisch sichtbar oder bestätigt."
},
{
"id": "hypothesis",
"description": "Vorläufige Deutung. Nicht stillschweigend ins Self Model schreiben."
}
]
}
+24
View File
@@ -0,0 +1,24 @@
{
"tiers": [
{
"id": "local",
"name": "Lokal",
"description": "Entwicklungs- und Self-Host-Instanz. Keine Zahlungsanbindung.",
"sort_order": 0
}
],
"features": [
{
"id": "ai_calls",
"name": "KI-Aufrufe",
"description": "Ausführung der Prompt-Engine. Jeder Call läuft über das Privacy Gateway.",
"category": "platform",
"limit_type": "count",
"default_limit": null,
"reset_period": "day"
}
],
"tier_limits": [
{ "tier_id": "local", "feature_id": "ai_calls", "limit_value": null }
]
}
+1
View File
@@ -0,0 +1 @@
[]
+14
View File
@@ -0,0 +1,14 @@
"""Internal context for later Gateway use. Never sends originals to a provider."""
from __future__ import annotations
from data_layer import read
def build_internal_context(profile_id: str, conversation_id: str) -> dict:
messages = read("conversation_messages", profile_id=profile_id, context={"conversation_id": conversation_id})
return {
"conversation_id": conversation_id,
"messages": messages,
"egress": False,
"note": "Volltext bleibt lokal. Minimierung und Egress nur über das Privacy Gateway.",
}
+49
View File
@@ -0,0 +1,49 @@
"""Continuity checkpoint. No LLM. Session end must not mutate threads."""
from __future__ import annotations
from db import get_db, row_to_dict
from dialogue_store import StoreError, end_usage_session, list_messages, thread_snapshot
def checkpoint_usage_session(profile_id: str, usage_session_id: str) -> dict:
"""Ensure originals are stored. Does not insert summaries or change thread status."""
threads_before = thread_snapshot(profile_id)
with get_db() as conn:
session = row_to_dict(
conn.execute(
"SELECT * FROM usage_sessions WHERE id = ? AND profile_id = ?",
(usage_session_id, profile_id),
).fetchone()
)
if not session:
raise StoreError("not_found", "Nutzungssitzung nicht gefunden", 404)
conv_rows = conn.execute(
"SELECT id FROM conversations WHERE profile_id = ? AND usage_session_id = ?",
(profile_id, usage_session_id),
).fetchall()
conversations = []
message_count = 0
for row in conv_rows:
messages = list_messages(profile_id, row["id"])
message_count += len(messages)
conversations.append({"id": row["id"], "message_count": len(messages)})
if thread_snapshot(profile_id) != threads_before:
raise StoreError("thread_mutated", "Checkpoint darf Thread-Felder nicht ändern", 500)
return {
"usage_session_id": usage_session_id,
"ended_at": session.get("ended_at"),
"conversations": conversations,
"message_count": message_count,
"threads_unchanged": True,
"llm": False,
}
def close_usage_session(profile_id: str, usage_session_id: str) -> dict:
threads_before = thread_snapshot(profile_id)
ended = end_usage_session(profile_id, usage_session_id)
checkpoint = checkpoint_usage_session(profile_id, usage_session_id)
if thread_snapshot(profile_id) != threads_before:
raise StoreError("thread_mutated", "Session-Ende darf Thread-Status nicht ändern", 500)
checkpoint["usage_session"] = ended
return checkpoint
+20
View File
@@ -0,0 +1,20 @@
"""Layer 1 surface. Domain derivations register here later. No prompt text, no React payloads."""
from __future__ import annotations
from typing import Any, Callable
_READERS: dict[str, Callable[..., Any]] = {}
def register_reader(key: str, reader: Callable[..., Any]) -> None:
_READERS[key] = reader
def read(key: str, *, profile_id: str, context: dict[str, Any] | None = None) -> Any:
if key not in _READERS:
raise KeyError(key)
return _READERS[key](profile_id=profile_id, context=context or {})
def list_readers() -> list[str]:
return sorted(_READERS)
+25
View File
@@ -0,0 +1,25 @@
"""Layer-1 readers over dialogue originals and derived records. No formulas."""
from __future__ import annotations
from data_layer import register_reader
from dialogue_store import latest_derived, list_messages
def _conversation_messages(*, profile_id: str, context: dict):
conversation_id = context.get("conversation_id")
if not conversation_id:
raise KeyError("conversation_id")
return list_messages(profile_id, conversation_id)
def _latest_derived(*, profile_id: str, context: dict):
return latest_derived(
profile_id,
context.get("subject_type") or "",
context.get("subject_id") or "",
context.get("kind") or "",
)
register_reader("conversation_messages", _conversation_messages)
register_reader("latest_derived", _latest_derived)
+153
View File
@@ -0,0 +1,153 @@
"""SQLite persistence for the local frame. PostgreSQL remains the later target."""
from __future__ import annotations
import json
import os
import sqlite3
from contextlib import contextmanager
from pathlib import Path
DATA_DIR = 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"
_PROFILE_COLUMNS = {
"status": "TEXT NOT NULL DEFAULT 'active'",
"tier_id": "TEXT NOT NULL DEFAULT 'local'",
}
_PROMPT_COLUMNS = {
"description": "TEXT NOT NULL DEFAULT ''",
"category": "TEXT NOT NULL DEFAULT 'uncategorized'",
"stages_json": "TEXT",
"graph_json": "TEXT",
"output_format": "TEXT NOT NULL DEFAULT 'text'",
"output_schema_json": "TEXT",
"required_feature": "TEXT NOT NULL DEFAULT 'ai_calls'",
"default_template": "TEXT NOT NULL DEFAULT ''",
"sort_order": "INTEGER NOT NULL DEFAULT 0",
"updated": "TEXT NOT NULL DEFAULT (datetime('now'))",
}
def _connect() -> sqlite3.Connection:
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(DB_PATH, timeout=30)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
return conn
@contextmanager
def get_db():
conn = _connect()
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
def row_to_dict(row: sqlite3.Row | None) -> dict | None:
if row is None:
return None
return dict(row)
def _column_names(conn: sqlite3.Connection, 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:
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:
conn.execute(
"INSERT OR IGNORE INTO schema_migrations (id) VALUES (?)",
(migration_id,),
)
def _seed_platform(conn: sqlite3.Connection) -> None:
seed = json.loads(SEED_PATH.read_text(encoding="utf-8"))
for tier in seed.get("tiers", []):
conn.execute(
"""
INSERT OR IGNORE INTO tiers (id, name, description, sort_order)
VALUES (?, ?, ?, ?)
""",
(tier["id"], tier["name"], tier.get("description") or "", tier.get("sort_order") or 0),
)
for feature in seed.get("features", []):
conn.execute(
"""
INSERT OR IGNORE INTO features
(id, name, description, category, limit_type, default_limit, reset_period)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
feature["id"],
feature["name"],
feature.get("description") or "",
feature.get("category") or "platform",
feature["limit_type"],
feature.get("default_limit"),
feature.get("reset_period") or "none",
),
)
for limit in seed.get("tier_limits", []):
conn.execute(
"""
INSERT OR IGNORE INTO tier_limits (tier_id, feature_id, limit_value)
VALUES (?, ?, ?)
""",
(limit["tier_id"], limit["feature_id"], limit.get("limit_value")),
)
def _seed_prompts(conn: sqlite3.Connection) -> None:
"""Prompts come from JSON/DB, never from Python string literals."""
items = json.loads(PROMPTS_SEED_PATH.read_text(encoding="utf-8"))
for item in items:
conn.execute(
"""
INSERT OR IGNORE INTO ai_prompts
(id, slug, name, description, category, prompt_type, template,
required_feature, is_system_default, default_template)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?)
""",
(
item["id"],
item["slug"],
item["name"],
item.get("description") or "",
item.get("category") or "uncategorized",
item.get("prompt_type") or "base",
item.get("template") or "",
item.get("required_feature") or "ai_calls",
item.get("template") or "",
),
)
def init_db() -> None:
schema = SCHEMA_PATH.read_text(encoding="utf-8")
with get_db() as conn:
conn.executescript(schema)
_seed_platform(conn)
_seed_prompts(conn)
_ensure_columns(conn, "profiles", _PROFILE_COLUMNS)
_ensure_columns(conn, "ai_prompts", _PROMPT_COLUMNS)
_mark(conn, "001_frame")
_mark(conn, "002_platform")
_mark(conn, "003_dialogue_memory")
+27
View File
@@ -0,0 +1,27 @@
"""Registered derived-record kinds. No prompt templates, no domain heuristics."""
from __future__ import annotations
import json
from pathlib import Path
KINDS_PATH = Path(__file__).resolve().parent / "config" / "derived_kinds.json"
def load_kinds() -> dict[str, dict]:
payload = json.loads(KINDS_PATH.read_text(encoding="utf-8"))
return {item["id"]: item for item in payload.get("kinds", [])}
def known_kind_ids() -> set[str]:
return set(load_kinds())
def require_kind(kind: str) -> dict:
kinds = load_kinds()
if kind not in kinds:
raise ValueError(kind)
return kinds[kind]
def catalog() -> list[dict]:
return sorted(load_kinds().values(), key=lambda item: item["id"])
+364
View File
@@ -0,0 +1,364 @@
"""Layer-0 dialogue store. Profile-scoped. Auth sessions table is untouched."""
from __future__ import annotations
import json
import uuid
from datetime import datetime, timezone
from db import get_db, row_to_dict
from derived_kinds import require_kind
SUBJECT_TYPES = {"conversation", "thread", "space", "usage_session"}
VISIBILITIES = {"internal", "user"}
MESSAGE_ROLES = {"user", "assistant", "system"}
HANDOFF_TARGETS = {"journal", "memory", "knowledge", "action", "mindnet", "obsidian"}
class StoreError(Exception):
def __init__(self, code: str, message: str, status_code: int = 400):
super().__init__(message)
self.code = code
self.message = message
self.status_code = status_code
def _now() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
def _parse_ids(raw: str | None) -> list[str]:
if not raw:
return []
data = json.loads(raw)
if not isinstance(data, list):
return []
return [str(item) for item in data]
def _owned(conn, table: str, record_id: str, profile_id: str) -> dict | None:
return row_to_dict(
conn.execute(
f"SELECT * FROM {table} WHERE id = ? AND profile_id = ?",
(record_id, profile_id),
).fetchone()
)
def start_usage_session(profile_id: str, intent: str = "") -> dict:
session_id = str(uuid.uuid4())
with get_db() as conn:
conn.execute(
"INSERT INTO usage_sessions (id, profile_id, intent) VALUES (?, ?, ?)",
(session_id, profile_id, intent or ""),
)
return row_to_dict(conn.execute("SELECT * FROM usage_sessions WHERE id = ?", (session_id,)).fetchone())
def end_usage_session(profile_id: str, usage_session_id: str) -> dict:
with get_db() as conn:
current = _owned(conn, "usage_sessions", usage_session_id, profile_id)
if not current:
raise StoreError("not_found", "Nutzungssitzung nicht gefunden", 404)
if not current.get("ended_at"):
conn.execute(
"UPDATE usage_sessions SET ended_at = ? WHERE id = ? AND profile_id = ?",
(_now(), usage_session_id, profile_id),
)
return row_to_dict(
conn.execute(
"SELECT * FROM usage_sessions WHERE id = ? AND profile_id = ?",
(usage_session_id, profile_id),
).fetchone()
)
def thread_snapshot(profile_id: str) -> list[dict]:
with get_db() as conn:
rows = conn.execute(
"SELECT id, status, visibility, resurfacing_at FROM threads WHERE profile_id = ? ORDER BY created",
(profile_id,),
).fetchall()
return [row_to_dict(row) for row in rows]
def create_conversation(profile_id: str, usage_session_id: str | None = None, title: str = "") -> dict:
conversation_id = str(uuid.uuid4())
with get_db() as conn:
if usage_session_id:
session = _owned(conn, "usage_sessions", usage_session_id, profile_id)
if not session:
raise StoreError("not_found", "Nutzungssitzung nicht gefunden", 404)
conn.execute(
"""
INSERT INTO conversations (id, profile_id, usage_session_id, title)
VALUES (?, ?, ?, ?)
""",
(conversation_id, profile_id, usage_session_id, title or ""),
)
return row_to_dict(conn.execute("SELECT * FROM conversations WHERE id = ?", (conversation_id,)).fetchone())
def get_conversation(profile_id: str, conversation_id: str) -> dict:
with get_db() as conn:
conv = _owned(conn, "conversations", conversation_id, profile_id)
if not conv:
raise StoreError("not_found", "Conversation nicht gefunden", 404)
return conv
def list_conversations(profile_id: str) -> list[dict]:
with get_db() as conn:
rows = conn.execute(
"""
SELECT c.*,
(SELECT COUNT(*) FROM messages m WHERE m.conversation_id = c.id) AS message_count,
(SELECT COUNT(*) FROM derived_records d
WHERE d.profile_id = c.profile_id AND d.subject_type = 'conversation' AND d.subject_id = c.id
) AS derived_count
FROM conversations c
WHERE c.profile_id = ?
ORDER BY c.created DESC
""",
(profile_id,),
).fetchall()
return [row_to_dict(row) for row in rows]
def append_message(
profile_id: str,
conversation_id: str,
body: str,
role: str = "user",
message_id: str | None = None,
) -> dict:
if role not in MESSAGE_ROLES:
raise StoreError("invalid_role", "Nachrichtenrolle muss user, assistant oder system sein")
if not (body or "").strip():
raise StoreError("empty_body", "Nachricht darf nicht leer sein")
requested_id = message_id or str(uuid.uuid4())
with get_db() as conn:
conv = _owned(conn, "conversations", conversation_id, profile_id)
if not conv:
raise StoreError("not_found", "Conversation nicht gefunden", 404)
existing = row_to_dict(conn.execute("SELECT * FROM messages WHERE id = ?", (requested_id,)).fetchone())
if existing:
if existing["profile_id"] != profile_id or existing["conversation_id"] != conversation_id:
raise StoreError("id_conflict", "Message-ID gehört zu einer anderen Conversation", 409)
return existing
seq_row = conn.execute(
"SELECT COALESCE(MAX(seq), 0) AS n FROM messages WHERE conversation_id = ?",
(conversation_id,),
).fetchone()
seq = int(seq_row["n"]) + 1
conn.execute(
"""
INSERT INTO messages (id, profile_id, conversation_id, seq, role, body)
VALUES (?, ?, ?, ?, ?, ?)
""",
(requested_id, profile_id, conversation_id, seq, role, body.strip()),
)
conn.execute(
"UPDATE conversations SET updated = datetime('now') WHERE id = ?",
(conversation_id,),
)
return row_to_dict(conn.execute("SELECT * FROM messages WHERE id = ?", (requested_id,)).fetchone())
def list_messages(profile_id: str, conversation_id: str) -> list[dict]:
with get_db() as conn:
conv = _owned(conn, "conversations", conversation_id, profile_id)
if not conv:
raise StoreError("not_found", "Conversation nicht gefunden", 404)
rows = conn.execute(
"""
SELECT * FROM messages
WHERE conversation_id = ? AND profile_id = ?
ORDER BY seq
""",
(conversation_id, profile_id),
).fetchall()
return [row_to_dict(row) for row in rows]
def create_thread(profile_id: str, title: str = "", status: str = "open", visibility: str = "internal") -> dict:
if visibility not in VISIBILITIES:
raise StoreError("invalid_visibility", "visibility muss internal oder user sein")
thread_id = str(uuid.uuid4())
with get_db() as conn:
conn.execute(
"""
INSERT INTO threads (id, profile_id, title, status, visibility)
VALUES (?, ?, ?, ?, ?)
""",
(thread_id, profile_id, title or "", status or "open", visibility),
)
return row_to_dict(conn.execute("SELECT * FROM threads WHERE id = ?", (thread_id,)).fetchone())
def link_conversation_thread(profile_id: str, conversation_id: str, thread_id: str) -> dict:
with get_db() as conn:
if not _owned(conn, "conversations", conversation_id, profile_id):
raise StoreError("not_found", "Conversation nicht gefunden", 404)
if not _owned(conn, "threads", thread_id, profile_id):
raise StoreError("not_found", "Thread nicht gefunden", 404)
conn.execute(
"""
INSERT OR IGNORE INTO conversation_threads (conversation_id, thread_id, profile_id)
VALUES (?, ?, ?)
""",
(conversation_id, thread_id, profile_id),
)
return {"conversation_id": conversation_id, "thread_id": thread_id}
def create_space(profile_id: str, title: str = "", visibility: str = "internal") -> dict:
if visibility not in VISIBILITIES:
raise StoreError("invalid_visibility", "visibility muss internal oder user sein")
space_id = str(uuid.uuid4())
with get_db() as conn:
conn.execute(
"INSERT INTO spaces (id, profile_id, title, visibility) VALUES (?, ?, ?, ?)",
(space_id, profile_id, title or "", visibility),
)
return row_to_dict(conn.execute("SELECT * FROM spaces WHERE id = ?", (space_id,)).fetchone())
def link_thread_space(profile_id: str, thread_id: str, space_id: str, confidence: float | None = None) -> dict:
with get_db() as conn:
if not _owned(conn, "threads", thread_id, profile_id):
raise StoreError("not_found", "Thread nicht gefunden", 404)
if not _owned(conn, "spaces", space_id, profile_id):
raise StoreError("not_found", "Space nicht gefunden", 404)
conn.execute(
"""
INSERT OR IGNORE INTO thread_spaces (thread_id, space_id, profile_id, confidence)
VALUES (?, ?, ?, ?)
""",
(thread_id, space_id, profile_id, confidence),
)
return {"thread_id": thread_id, "space_id": space_id, "confidence": confidence}
def insert_derived(
profile_id: str,
kind: str,
subject_type: str,
subject_id: str,
source_message_ids: list[str],
body: str = "",
visibility: str = "internal",
confidence: float | None = None,
) -> dict:
try:
require_kind(kind)
except ValueError as exc:
raise StoreError("unknown_kind", f"Derived-Kind ist nicht registriert: {kind}") from exc
if subject_type not in SUBJECT_TYPES:
raise StoreError("invalid_subject", "Ungültiger subject_type")
if visibility not in VISIBILITIES:
raise StoreError("invalid_visibility", "visibility muss internal oder user sein")
ids = [item for item in source_message_ids if item]
if not ids:
raise StoreError("provenance_required", "Derived records brauchen source_message_ids")
record_id = str(uuid.uuid4())
as_of = _now()
with get_db() as conn:
for message_id in ids:
msg = _owned(conn, "messages", message_id, profile_id)
if not msg:
raise StoreError("not_found", f"Quellnachricht nicht gefunden: {message_id}", 404)
conn.execute(
"""
INSERT INTO derived_records
(id, profile_id, kind, subject_type, subject_id, source_message_ids,
as_of, confidence, visibility, body)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
record_id,
profile_id,
kind,
subject_type,
subject_id,
json.dumps(ids),
as_of,
confidence,
visibility,
body or "",
),
)
row = row_to_dict(conn.execute("SELECT * FROM derived_records WHERE id = ?", (record_id,)).fetchone())
row["source_message_ids"] = ids
return row
def latest_derived(profile_id: str, subject_type: str, subject_id: str, kind: str) -> dict | None:
with get_db() as conn:
row = row_to_dict(
conn.execute(
"""
SELECT * FROM derived_records
WHERE profile_id = ? AND subject_type = ? AND subject_id = ? AND kind = ?
ORDER BY created DESC
LIMIT 1
""",
(profile_id, subject_type, subject_id, kind),
).fetchone()
)
if not row:
return None
row["source_message_ids"] = _parse_ids(row.get("source_message_ids"))
return row
def list_derived_for_conversation(profile_id: str, conversation_id: str) -> list[dict]:
with get_db() as conn:
rows = conn.execute(
"""
SELECT * FROM derived_records
WHERE profile_id = ? AND subject_type = 'conversation' AND subject_id = ?
ORDER BY created
""",
(profile_id, conversation_id),
).fetchall()
result = []
for row in rows:
item = row_to_dict(row)
item["source_message_ids"] = _parse_ids(item.get("source_message_ids"))
result.append(item)
return result
def create_handoff(profile_id: str, target: str, source_conversation_id: str | None = None, payload: dict | None = None) -> dict:
if target not in HANDOFF_TARGETS:
raise StoreError("invalid_target", "Ungültiges Handoff-Ziel")
handoff_id = str(uuid.uuid4())
with get_db() as conn:
if source_conversation_id and not _owned(conn, "conversations", source_conversation_id, profile_id):
raise StoreError("not_found", "Conversation nicht gefunden", 404)
conn.execute(
"""
INSERT INTO handoffs (id, profile_id, target, source_conversation_id, payload_json)
VALUES (?, ?, ?, ?, ?)
""",
(handoff_id, profile_id, target, source_conversation_id, json.dumps(payload or {})),
)
return row_to_dict(conn.execute("SELECT * FROM handoffs WHERE id = ?", (handoff_id,)).fetchone())
def inventory(profile_id: str | None = None) -> dict:
params = (profile_id,) if profile_id else ()
with get_db() as conn:
def count(table: str) -> int:
if profile_id:
return conn.execute(f"SELECT COUNT(*) AS n FROM {table} WHERE profile_id = ?", params).fetchone()["n"]
return conn.execute(f"SELECT COUNT(*) AS n FROM {table}").fetchone()["n"]
return {
"usage_sessions": count("usage_sessions"),
"conversations": count("conversations"),
"messages": count("messages"),
"threads": count("threads"),
"spaces": count("spaces"),
"derived_records": count("derived_records"),
"handoffs": count("handoffs"),
}
+57
View File
@@ -0,0 +1,57 @@
"""Single prompt execution entry. Templates live in the DB; LLM egress only via Privacy Gateway."""
from __future__ import annotations
from typing import Any
import placeholder_system # noqa: F401 registers system keys
import privacy_placeholders
from entitlements import EntitlementError, check_feature_access
from placeholders import PlaceholderError, resolve_template
from privacy_gateway import GatewayRequest, PrivacyGatewayError, complete
class EngineError(Exception):
def __init__(self, code: str, message: str, status_code: int = 400):
super().__init__(message)
self.code = code
self.message = message
self.status_code = status_code
def preview_prompt(prompt: dict, context: dict[str, Any] | None = None) -> dict:
template = prompt.get("template") or ""
if prompt.get("prompt_type") != "base":
raise EngineError("prompt_type_not_ready", "Pipeline- und Workflow-Typen sind vorbereitet, aber noch ohne Executor-Stufen.")
try:
rendered = resolve_template(template, context or {})
privacy_tokens = privacy_placeholders.validate_tokens(template)
except PlaceholderError as exc:
raise EngineError(exc.code, exc.message) from exc
return {
"prompt_id": prompt["id"],
"slug": prompt["slug"],
"rendered": rendered,
"privacy_tokens": privacy_tokens,
"llm": False,
}
def execute_prompt(prompt: dict, profile_id: str, purpose: str, data_class: str, context: dict[str, Any] | None = None) -> dict:
preview = preview_prompt(prompt, context)
feature_id = prompt.get("required_feature") or "ai_calls"
try:
check_feature_access(profile_id, feature_id)
except EntitlementError as exc:
raise EngineError(exc.code, exc.message, exc.status_code) from exc
try:
complete(
GatewayRequest(
prompt_id=prompt["id"],
purpose=purpose,
data_class=data_class,
payload={"template_chars": len(preview["rendered"]), "privacy_tokens": preview["privacy_tokens"]},
)
)
except PrivacyGatewayError as exc:
raise EngineError(exc.code, exc.message, exc.status_code) from exc
raise EngineError("provider_missing", "Gateway erlaubte einen Aufruf ohne konfigurierten Provider", 500)
+129
View File
@@ -0,0 +1,129 @@
"""Feature access. Identity is Auth; this only answers 'may this profile use feature X?'."""
from __future__ import annotations
from datetime import datetime, timezone
from db import get_db, row_to_dict
class EntitlementError(Exception):
def __init__(self, code: str, message: str, status_code: int = 403):
super().__init__(message)
self.code = code
self.message = message
self.status_code = status_code
def _period_key(reset_period: str) -> str:
now = datetime.now(timezone.utc)
if reset_period == "day":
return now.strftime("%Y-%m-%d")
if reset_period == "month":
return now.strftime("%Y-%m")
return "all"
def _effective_limit(profile_id: str, feature_id: str) -> tuple[dict, int | None]:
with get_db() as conn:
feature = row_to_dict(
conn.execute("SELECT * FROM features WHERE id = ? AND active = 1", (feature_id,)).fetchone()
)
if not feature:
raise EntitlementError("unknown_feature", f"Feature ist nicht registriert: {feature_id}")
override = row_to_dict(
conn.execute(
"SELECT limit_value FROM user_feature_restrictions WHERE profile_id = ? AND feature_id = ?",
(profile_id, feature_id),
).fetchone()
)
if override is not None:
return feature, override["limit_value"]
profile = row_to_dict(
conn.execute("SELECT tier_id FROM profiles WHERE id = ?", (profile_id,)).fetchone()
)
tier_id = (profile or {}).get("tier_id") or "local"
tier_limit = row_to_dict(
conn.execute(
"SELECT limit_value FROM tier_limits WHERE tier_id = ? AND feature_id = ?",
(tier_id, feature_id),
).fetchone()
)
if tier_limit is not None:
return feature, tier_limit["limit_value"]
return feature, feature["default_limit"]
def check_feature_access(profile_id: str, feature_id: str) -> dict:
feature, limit = _effective_limit(profile_id, feature_id)
period = _period_key(feature["reset_period"])
with get_db() as conn:
usage = row_to_dict(
conn.execute(
"""
SELECT used FROM user_feature_usage
WHERE profile_id = ? AND feature_id = ? AND period_key = ?
""",
(profile_id, feature_id, period),
).fetchone()
)
used = int((usage or {}).get("used") or 0)
if feature["limit_type"] == "boolean":
allowed = limit is None or int(limit) >= 1
else:
allowed = limit is None or used < int(limit)
if not allowed:
raise EntitlementError("feature_limit", f"Kontingent erschöpft: {feature_id}")
return {
"feature_id": feature_id,
"allowed": True,
"limit": limit,
"used": used,
"period_key": period,
}
def increment_feature_usage(profile_id: str, feature_id: str) -> None:
feature, _limit = _effective_limit(profile_id, feature_id)
period = _period_key(feature["reset_period"])
with get_db() as conn:
conn.execute(
"""
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
""",
(profile_id, feature_id, period),
)
def subscription_for(profile_id: str) -> dict:
with get_db() as conn:
profile = row_to_dict(
conn.execute(
"""
SELECT p.id, p.tier_id, t.name AS tier_name, t.description AS tier_description
FROM profiles p
JOIN tiers t ON t.id = p.tier_id
WHERE p.id = ?
""",
(profile_id,),
).fetchone()
)
features = [row_to_dict(row) for row in conn.execute("SELECT * FROM features WHERE active = 1 ORDER BY id")]
entitlements = []
for feature in features:
try:
entitlements.append(check_feature_access(profile_id, feature["id"]))
except EntitlementError as exc:
entitlements.append({"feature_id": feature["id"], "allowed": False, "code": exc.code})
return {
"profile_id": profile_id,
"tier": {
"id": (profile or {}).get("tier_id"),
"name": (profile or {}).get("tier_name"),
"description": (profile or {}).get("tier_description"),
},
"features": entitlements,
"billing": None,
}
+35
View File
@@ -0,0 +1,35 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from db import init_db
import data_layer_dialogue # noqa: F401
from routers import admin, auth, dialogue, placeholders, prompts, subscription, users
from version import APP_VERSION
app = FastAPI(title="Kanshō", version=APP_VERSION)
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:5188", "http://127.0.0.1:5188"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(auth.router)
app.include_router(users.router)
app.include_router(dialogue.router)
app.include_router(prompts.router)
app.include_router(placeholders.router)
app.include_router(subscription.router)
app.include_router(admin.router)
@app.on_event("startup")
def on_startup():
init_db()
@app.get("/api/health")
def health():
return {"status": "ok", "service": "kansho", "version": APP_VERSION}
+15
View File
@@ -0,0 +1,15 @@
"""System context keys only. Domain keys are registered later, never hardcoded into prompts."""
from __future__ import annotations
from datetime import datetime, timezone
from placeholders import Placeholder, register
register(
Placeholder(
key="now",
description="UTC-Zeitstempel der Auflösung. Kein Personenbezug.",
data_class="C",
resolver=lambda _ctx: datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
)
)
+71
View File
@@ -0,0 +1,71 @@
"""Context placeholders {{key}}. Implementations register here; templates never define ad-hoc keys."""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any, Callable
CONTEXT_PATTERN = re.compile(r"\{\{([a-z][a-z0-9_]*)\}\}")
class PlaceholderError(Exception):
def __init__(self, code: str, message: str):
super().__init__(message)
self.code = code
self.message = message
@dataclass(frozen=True)
class Placeholder:
key: str
description: str
data_class: str
resolver: Callable[[dict[str, Any]], Any]
_REGISTRY: dict[str, Placeholder] = {}
def register(placeholder: Placeholder) -> None:
if placeholder.data_class == "A":
raise PlaceholderError(
"class_a_context_key_forbidden",
"Klasse-A-Werte gehören nicht in {{key}}-Kontext. Identität läuft über [[…]].",
)
_REGISTRY[placeholder.key] = placeholder
def get(key: str) -> Placeholder | None:
return _REGISTRY.get(key)
def list_placeholders() -> list[dict]:
return [
{
"key": item.key,
"description": item.description,
"data_class": item.data_class,
"syntax": f"{{{{{item.key}}}}}",
}
for item in sorted(_REGISTRY.values(), key=lambda item: item.key)
]
def extract_keys(template: str) -> list[str]:
return CONTEXT_PATTERN.findall(template or "")
def resolve_template(template: str, context: dict[str, Any]) -> str:
keys = extract_keys(template)
unknown = sorted({key for key in keys if key not in _REGISTRY})
if unknown:
raise PlaceholderError(
"unknown_placeholder",
"Unbekannte Kontext-Platzhalter: " + ", ".join(f"{{{{{key}}}}}" for key in unknown),
)
rendered = template
for key in keys:
spec = _REGISTRY[key]
value = spec.resolver(context)
rendered = rendered.replace("{{" + key + "}}", "" if value is None else str(value))
return rendered
+65
View File
@@ -0,0 +1,65 @@
"""Local privacy gateway stub. Personal LLM egress is not allowed to skip this layer."""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any
class PrivacyGatewayError(Exception):
def __init__(self, code: str, message: str, status_code: int = 503):
super().__init__(message)
self.code = code
self.message = message
self.status_code = status_code
@dataclass
class GatewayRequest:
prompt_id: str | None
purpose: str
data_class: str
payload: dict[str, Any] = field(default_factory=dict)
@dataclass
class GatewayResult:
allowed: bool
reason: str
provider: str | None = None
content: str | None = None
checked_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
ALLOWED_CLASSES = {"A", "B", "C"}
LOCAL_ONLY_CLASS = "A"
def inspect(request: GatewayRequest) -> GatewayResult:
"""Fail closed. No provider is configured in the local frame."""
data_class = (request.data_class or "").upper()
if data_class not in ALLOWED_CLASSES:
return GatewayResult(
allowed=False,
reason="unknown_data_class",
)
if data_class == LOCAL_ONLY_CLASS:
return GatewayResult(
allowed=False,
reason="class_a_never_leaves_local_zone",
)
return GatewayResult(
allowed=False,
reason="no_egress_provider_configured",
)
def complete(request: GatewayRequest) -> GatewayResult:
result = inspect(request)
if not result.allowed:
raise PrivacyGatewayError(
result.reason,
"Persönlicher KI-Aufruf wurde vom Privacy Gateway blockiert. "
"Es ist kein Egress-Provider konfiguriert.",
)
return result
+54
View File
@@ -0,0 +1,54 @@
"""Privacy tokens [[TOKEN]] in templates. Distinct from context {{key}}."""
from __future__ import annotations
import re
from placeholders import PlaceholderError
PRIVACY_PATTERN = re.compile(r"\[\[([A-Z][A-Z0-9_]*(?::[A-Z0-9_]+)?)\]\]")
KNOWN_EXACT = {"SELF"}
KNOWN_PREFIXES = ("PERSON:", "PLACE:")
def catalog() -> list[dict]:
return [
{
"token": "[[SELF]]",
"kind": "exact",
"data_class": "B",
"description": "Die reflektierende Person. Mapping bleibt lokal.",
},
{
"token": "[[PERSON:ROLE]]",
"kind": "prefix",
"data_class": "B",
"description": "Andere Person als nicht sprechende Rolle, nicht als Klarname.",
},
{
"token": "[[PLACE:KIND]]",
"kind": "prefix",
"data_class": "B",
"description": "Ort als Kategorie, nicht als Adresse oder Stadtname.",
},
]
def extract_tokens(template: str) -> list[str]:
return PRIVACY_PATTERN.findall(template or "")
def validate_tokens(template: str) -> list[str]:
tokens = extract_tokens(template)
invalid = []
for token in tokens:
if token in KNOWN_EXACT:
continue
if any(token.startswith(prefix) for prefix in KNOWN_PREFIXES):
continue
invalid.append(f"[[{token}]]")
if invalid:
raise PlaceholderError(
"unknown_privacy_placeholder",
"Unbekannte Privacy-Platzhalter: " + ", ".join(sorted(set(invalid))),
)
return [f"[[{token}]]" for token in tokens]
+4
View File
@@ -0,0 +1,4 @@
fastapi==0.115.6
uvicorn[standard]==0.34.0
bcrypt==4.2.1
httpx==0.28.1
+1
View File
@@ -0,0 +1 @@
# Kanshō API routers
+56
View File
@@ -0,0 +1,56 @@
from fastapi import APIRouter, Depends, HTTPException
from auth import require_admin_dep
from db import get_db
from dialogue_store import StoreError, get_conversation, inventory, list_conversations, list_derived_for_conversation, list_messages
from version import APP_VERSION, BUILD_DATE, MODULE_VERSIONS
router = APIRouter(prefix="/api/admin", tags=["admin"])
@router.get("/health")
def admin_health(session: dict = Depends(require_admin_dep)):
with get_db() as conn:
users = conn.execute("SELECT COUNT(*) AS n FROM profiles").fetchone()["n"]
prompts = conn.execute("SELECT COUNT(*) AS n FROM ai_prompts").fetchone()["n"]
features = conn.execute("SELECT COUNT(*) AS n FROM features").fetchone()["n"]
dialogue = inventory()
return {
"ok": True,
"service": "kansho",
"version": APP_VERSION,
"build_date": BUILD_DATE,
"modules": MODULE_VERSIONS,
"inventory": {
"users": users,
"prompts": prompts,
"features": features,
"dialogue": dialogue,
},
"session": {
"profile_id": session["profile_id"],
"role": session["role"],
},
}
@router.get("/dialogue")
def admin_dialogue(session: dict = Depends(require_admin_dep)):
return {
"instance": inventory(),
"own_conversations": list_conversations(session["profile_id"]),
"note": "Fremde Lived Experience ist kein Alltagspfad. Detailansicht nur für das eigene Profil.",
}
@router.get("/dialogue/conversations/{conversation_id}")
def admin_conversation(conversation_id: str, session: dict = Depends(require_admin_dep)):
try:
conv = get_conversation(session["profile_id"], conversation_id)
return {
"conversation": conv,
"original_messages": list_messages(session["profile_id"], conversation_id),
"derived_records": list_derived_for_conversation(session["profile_id"], conversation_id),
}
except StoreError as exc:
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
+103
View File
@@ -0,0 +1,103 @@
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from auth import create_session, hash_password, require_auth, verify_password
from db import get_db, row_to_dict
from version import APP_VERSION
router = APIRouter(prefix="/api/auth", tags=["auth"])
class LoginRequest(BaseModel):
email: str
password: str = Field(min_length=4)
class SetupRequest(BaseModel):
email: str
name: str = Field(min_length=1)
password: str = Field(min_length=4)
def _profile_count() -> int:
with get_db() as conn:
row = conn.execute("SELECT COUNT(*) AS n FROM profiles").fetchone()
return int(row["n"])
@router.get("/status")
def auth_status():
return {
"status": "ok",
"service": "kansho",
"version": APP_VERSION,
"needs_setup": _profile_count() == 0,
}
@router.post("/setup")
def setup(req: SetupRequest):
if _profile_count() > 0:
raise HTTPException(409, "Setup ist bereits abgeschlossen")
profile_id = str(uuid.uuid4())
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)),
)
token, expires = create_session(profile_id)
return {
"token": token,
"profile_id": profile_id,
"name": req.name.strip(),
"role": "admin",
"expires_at": expires.isoformat(),
}
@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()
)
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":
raise HTTPException(401, "Ungültige Zugangsdaten")
token, expires = create_session(prof["id"], prof.get("session_days") or 30)
return {
"token": token,
"profile_id": prof["id"],
"name": prof["name"],
"role": prof["role"],
"expires_at": expires.isoformat(),
}
@router.post("/logout")
def logout(session: dict = Depends(require_auth)):
with get_db() as conn:
conn.execute("DELETE FROM sessions WHERE token = ?", (session["token"],))
return {"ok": True}
@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()
)
if not prof:
raise HTTPException(401, "Profil nicht gefunden")
return prof
+215
View File
@@ -0,0 +1,215 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
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_store import (
StoreError,
append_message,
create_conversation,
create_handoff,
create_space,
create_thread,
get_conversation,
insert_derived,
link_conversation_thread,
link_thread_space,
list_conversations,
list_derived_for_conversation,
list_messages,
start_usage_session,
)
router = APIRouter(prefix="/api/dialogue", tags=["dialogue"])
def _http(exc: StoreError):
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
class SessionWrite(BaseModel):
intent: str = ""
class ConversationWrite(BaseModel):
usage_session_id: str | None = None
title: str = ""
class MessageWrite(BaseModel):
body: str = Field(min_length=1)
role: str = "user"
id: str | None = None
class ThreadWrite(BaseModel):
title: str = ""
status: str = "open"
visibility: str = "internal"
class SpaceWrite(BaseModel):
title: str = ""
visibility: str = "internal"
class DerivedWrite(BaseModel):
kind: str
subject_type: str
subject_id: str
source_message_ids: list[str]
body: str = ""
visibility: str = "internal"
confidence: float | None = None
class HandoffWrite(BaseModel):
target: str
source_conversation_id: str | None = None
payload: dict = Field(default_factory=dict)
@router.get("/kinds")
def list_kinds(session: dict = Depends(require_auth)):
return catalog()
@router.post("/sessions")
def create_session(req: SessionWrite, session: dict = Depends(require_auth)):
return start_usage_session(session["profile_id"], req.intent)
@router.post("/sessions/{usage_session_id}/end")
def end_session(usage_session_id: str, session: dict = Depends(require_auth)):
try:
return close_usage_session(session["profile_id"], usage_session_id)
except StoreError as exc:
_http(exc)
@router.post("/sessions/{usage_session_id}/checkpoint")
def checkpoint_session(usage_session_id: str, session: dict = Depends(require_auth)):
try:
return checkpoint_usage_session(session["profile_id"], usage_session_id)
except StoreError as exc:
_http(exc)
@router.post("/conversations")
def post_conversation(req: ConversationWrite, session: dict = Depends(require_auth)):
try:
return create_conversation(session["profile_id"], req.usage_session_id, req.title)
except StoreError as exc:
_http(exc)
@router.get("/conversations")
def get_conversations(session: dict = Depends(require_auth)):
return list_conversations(session["profile_id"])
@router.get("/conversations/{conversation_id}")
def get_one_conversation(conversation_id: str, session: dict = Depends(require_auth)):
try:
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)
return conv
except StoreError as exc:
_http(exc)
@router.get("/conversations/{conversation_id}/context")
def get_internal_context(conversation_id: str, session: dict = Depends(require_auth)):
try:
return build_internal_context(session["profile_id"], conversation_id)
except StoreError as exc:
_http(exc)
@router.post("/conversations/{conversation_id}/messages")
def post_message(conversation_id: str, req: MessageWrite, session: dict = Depends(require_auth)):
try:
return append_message(session["profile_id"], conversation_id, req.body, req.role, req.id)
except StoreError as exc:
_http(exc)
@router.get("/conversations/{conversation_id}/messages")
def get_messages(conversation_id: str, session: dict = Depends(require_auth)):
try:
return list_messages(session["profile_id"], conversation_id)
except StoreError as exc:
_http(exc)
@router.post("/threads")
def post_thread(req: ThreadWrite, session: dict = Depends(require_auth)):
try:
return create_thread(session["profile_id"], req.title, req.status, req.visibility)
except StoreError as exc:
_http(exc)
@router.post("/conversations/{conversation_id}/threads/{thread_id}")
def post_conversation_thread(conversation_id: str, thread_id: str, session: dict = Depends(require_auth)):
try:
return link_conversation_thread(session["profile_id"], conversation_id, thread_id)
except StoreError as exc:
_http(exc)
@router.post("/spaces")
def post_space(req: SpaceWrite, session: dict = Depends(require_auth)):
try:
return create_space(session["profile_id"], req.title, req.visibility)
except StoreError as exc:
_http(exc)
@router.post("/threads/{thread_id}/spaces/{space_id}")
def post_thread_space(thread_id: str, space_id: str, confidence: float | None = None, session: dict = Depends(require_auth)):
try:
return link_thread_space(session["profile_id"], thread_id, space_id, confidence)
except StoreError as exc:
_http(exc)
@router.post("/derived")
def post_derived(req: DerivedWrite, session: dict = Depends(require_auth)):
try:
return insert_derived(
session["profile_id"],
req.kind,
req.subject_type,
req.subject_id,
req.source_message_ids,
req.body,
req.visibility,
req.confidence,
)
except StoreError as exc:
_http(exc)
@router.get("/derived/latest")
def get_latest(subject_type: str, subject_id: str, kind: str, session: dict = Depends(require_auth)):
from data_layer import read
return read(
"latest_derived",
profile_id=session["profile_id"],
context={"subject_type": subject_type, "subject_id": subject_id, "kind": kind},
)
@router.post("/handoffs")
def post_handoff(req: HandoffWrite, session: dict = Depends(require_auth)):
try:
return create_handoff(session["profile_id"], req.target, req.source_conversation_id, req.payload)
except StoreError as exc:
_http(exc)
+19
View File
@@ -0,0 +1,19 @@
from __future__ import annotations
from fastapi import APIRouter, Depends
from auth import require_auth
import placeholder_system # noqa: F401
from placeholders import list_placeholders
from privacy_placeholders import catalog as privacy_catalog
router = APIRouter(prefix="/api/placeholders", tags=["placeholders"])
@router.get("")
def list_all_placeholders(session: dict = Depends(require_auth)):
return {
"context": list_placeholders(),
"privacy": privacy_catalog(),
"note": "Templates dürfen nur registrierte {{key}} und [[TOKEN]] enthalten. Fachliche Keys kommen später als Registry-Einträge, nicht als Freitext.",
}
+182
View File
@@ -0,0 +1,182 @@
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from auth import require_admin_dep, require_auth
from db import get_db, row_to_dict
from engine import EngineError, execute_prompt, preview_prompt
router = APIRouter(prefix="/api/prompts", tags=["prompts"])
LIST_FIELDS = """
id, slug, name, description, category, prompt_type, template, required_feature,
active, is_system_default, sort_order, created, updated
"""
class PromptWrite(BaseModel):
slug: str = Field(min_length=1, max_length=80)
name: str = Field(min_length=1)
description: str = ""
category: str = "uncategorized"
prompt_type: str = "base"
template: str = ""
required_feature: str = "ai_calls"
active: bool = True
class PreviewRequest(BaseModel):
slug: str | None = None
prompt_id: str | None = None
class ExecuteRequest(BaseModel):
slug: str | None = None
prompt_id: str | None = None
purpose: str = "reflection"
data_class: str = Field(default="B")
def _http(exc: EngineError):
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
def _load(conn, prompt_id: str | None, slug: str | None) -> dict:
if prompt_id:
row = conn.execute("SELECT * FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone()
elif slug:
row = conn.execute("SELECT * FROM ai_prompts WHERE slug = ?", (slug,)).fetchone()
else:
raise HTTPException(400, "prompt_id oder slug ist erforderlich")
prompt = row_to_dict(row)
if not prompt:
raise HTTPException(404, "Prompt nicht gefunden")
return prompt
@router.get("")
def list_prompts(session: dict = Depends(require_admin_dep)):
with get_db() as conn:
rows = conn.execute(f"SELECT {LIST_FIELDS} FROM ai_prompts ORDER BY sort_order, name").fetchall()
return [row_to_dict(row) for row in rows]
@router.post("")
def create_prompt(req: PromptWrite, session: dict = Depends(require_admin_dep)):
if req.prompt_type not in {"base", "pipeline", "workflow"}:
raise HTTPException(400, "Ungültiger Prompt-Typ")
prompt_id = str(uuid.uuid4())
if req.prompt_type == "base" and req.template:
try:
preview_prompt(
{
"id": prompt_id,
"slug": req.slug.strip(),
"prompt_type": req.prompt_type,
"template": req.template,
},
{},
)
except EngineError as exc:
_http(exc)
try:
with get_db() as conn:
conn.execute(
"""
INSERT INTO ai_prompts
(id, slug, name, description, category, prompt_type, template,
required_feature, active, default_template)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
prompt_id,
req.slug.strip(),
req.name.strip(),
req.description,
req.category.strip() or "uncategorized",
req.prompt_type,
req.template,
req.required_feature,
1 if req.active else 0,
req.template,
),
)
return row_to_dict(conn.execute(f"SELECT {LIST_FIELDS} FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
except Exception as exc:
if "UNIQUE" in str(exc).upper():
raise HTTPException(409, "Slug ist bereits vergeben") from exc
raise
@router.put("/{prompt_id}")
def update_prompt(prompt_id: str, req: PromptWrite, session: dict = Depends(require_admin_dep)):
with get_db() as conn:
current = row_to_dict(conn.execute("SELECT id FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
if not current:
raise HTTPException(404, "Prompt nicht gefunden")
conn.execute(
"""
UPDATE ai_prompts
SET slug = ?, name = ?, description = ?, category = ?, prompt_type = ?,
template = ?, required_feature = ?, active = ?, updated = datetime('now')
WHERE id = ?
""",
(
req.slug.strip(),
req.name.strip(),
req.description,
req.category.strip() or "uncategorized",
req.prompt_type,
req.template,
req.required_feature,
1 if req.active else 0,
prompt_id,
),
)
return row_to_dict(conn.execute(f"SELECT {LIST_FIELDS} FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
@router.post("/{prompt_id}/reset")
def reset_prompt(prompt_id: str, session: dict = Depends(require_admin_dep)):
with get_db() as conn:
prompt = row_to_dict(conn.execute("SELECT * FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
if not prompt:
raise HTTPException(404, "Prompt nicht gefunden")
if not prompt["is_system_default"]:
raise HTTPException(400, "Nur System-Defaults können zurückgesetzt werden")
conn.execute(
"UPDATE ai_prompts SET template = default_template, updated = datetime('now') WHERE id = ?",
(prompt_id,),
)
return row_to_dict(conn.execute(f"SELECT {LIST_FIELDS} FROM ai_prompts WHERE id = ?", (prompt_id,)).fetchone())
@router.post("/preview")
def preview(req: PreviewRequest, session: dict = Depends(require_admin_dep)):
with get_db() as conn:
prompt = _load(conn, req.prompt_id, req.slug)
try:
return preview_prompt(prompt, {"profile_id": session["profile_id"]})
except EngineError as exc:
_http(exc)
@router.post("/execute")
def execute(req: ExecuteRequest, session: dict = Depends(require_auth)):
with get_db() as conn:
prompt = _load(conn, req.prompt_id, req.slug)
if not prompt["active"] and session.get("role") != "admin":
raise HTTPException(404, "Prompt nicht gefunden")
try:
return execute_prompt(
prompt,
profile_id=session["profile_id"],
purpose=req.purpose,
data_class=req.data_class,
context={"profile_id": session["profile_id"]},
)
except EngineError as exc:
_http(exc)
+29
View File
@@ -0,0 +1,29 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from auth import require_admin_dep, require_auth
from db import get_db, row_to_dict
from entitlements import EntitlementError, check_feature_access, subscription_for
router = APIRouter(prefix="/api", tags=["subscription"])
@router.get("/subscription")
def get_subscription(session: dict = Depends(require_auth)):
return subscription_for(session["profile_id"])
@router.get("/features")
def list_features(session: dict = Depends(require_admin_dep)):
with get_db() as conn:
rows = conn.execute("SELECT * FROM features ORDER BY id").fetchall()
return [row_to_dict(row) for row in rows]
@router.get("/features/{feature_id}/access")
def feature_access(feature_id: str, session: dict = Depends(require_auth)):
try:
return check_feature_access(session["profile_id"], feature_id)
except EntitlementError as exc:
raise HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": exc.message}) from exc
+122
View File
@@ -0,0 +1,122 @@
from __future__ import annotations
import uuid
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field
from auth import hash_password, require_admin_dep, require_auth
from db import get_db, row_to_dict
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"
class PatchUserRequest(BaseModel):
name: str | None = None
role: str | None = None
status: str | None = None
password: str | None = None
def _active_admin_count(conn, exclude_id: str | None = None) -> int:
if exclude_id:
row = conn.execute(
"SELECT COUNT(*) AS n FROM profiles WHERE role = 'admin' AND status = 'active' AND id != ?",
(exclude_id,),
).fetchone()
else:
row = conn.execute(
"SELECT COUNT(*) AS n FROM profiles WHERE role = 'admin' AND status = 'active'"
).fetchone()
return int(row["n"])
@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]
@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")
profile_id = str(uuid.uuid4())
try:
with get_db() as conn:
conn.execute(
"""
INSERT INTO profiles (id, email, name, password_hash, role, status, tier_id)
VALUES (?, ?, ?, ?, ?, 'active', 'local')
""",
(
profile_id,
req.email.lower().strip(),
req.name.strip(),
hash_password(req.password),
req.role,
),
)
prof = row_to_dict(conn.execute(f"SELECT {PUBLIC_FIELDS} FROM profiles WHERE id = ?", (profile_id,)).fetchone())
except Exception as exc:
if "UNIQUE" in str(exc).upper():
raise HTTPException(409, "E-Mail ist bereits vergeben") from exc
raise
return prof
@router.patch("/{profile_id}")
def patch_user(profile_id: str, req: PatchUserRequest, session: dict = Depends(require_admin_dep)):
with get_db() as conn:
current = row_to_dict(conn.execute("SELECT * FROM profiles WHERE id = ?", (profile_id,)).fetchone())
if not current:
raise HTTPException(404, "Nutzer nicht gefunden")
name = req.name.strip() if req.name is not None else current["name"]
role = req.role if req.role is not None else current["role"]
status = req.status if req.status is not None else current["status"]
if role not in {"user", "admin"}:
raise HTTPException(400, "Rolle muss user oder admin sein")
if status not in {"active", "disabled"}:
raise HTTPException(400, "Status muss active oder disabled sein")
becomes_non_admin = current["role"] == "admin" and (role != "admin" or status == "disabled")
if becomes_non_admin and _active_admin_count(conn, exclude_id=profile_id) < 1:
raise HTTPException(400, "Der letzte aktive Admin kann nicht entfernt werden")
password_hash = current["password_hash"]
if req.password:
if len(req.password) < 4:
raise HTTPException(400, "Passwort muss mind. 4 Zeichen haben")
password_hash = hash_password(req.password)
conn.execute(
"""
UPDATE profiles SET name = ?, role = ?, status = ?, password_hash = ?
WHERE id = ?
""",
(name, role, status, password_hash, profile_id),
)
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())
@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()
)
if not prof:
raise HTTPException(401, "Profil nicht gefunden")
return prof
+204
View File
@@ -0,0 +1,204 @@
CREATE TABLE IF NOT EXISTS schema_migrations (
id TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS tiers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
active INTEGER NOT NULL DEFAULT 1,
sort_order INTEGER NOT NULL DEFAULT 0,
created TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS features (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
category TEXT NOT NULL DEFAULT 'platform',
limit_type TEXT NOT NULL CHECK (limit_type IN ('boolean', 'count')),
default_limit INTEGER,
reset_period TEXT NOT NULL DEFAULT 'none' CHECK (reset_period IN ('none', 'day', 'month')),
active INTEGER NOT NULL DEFAULT 1,
created TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS tier_limits (
tier_id TEXT NOT NULL REFERENCES tiers(id) ON DELETE CASCADE,
feature_id TEXT NOT NULL REFERENCES features(id) ON DELETE CASCADE,
limit_value INTEGER,
PRIMARY KEY (tier_id, feature_id)
);
CREATE TABLE IF NOT EXISTS profiles (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL CHECK (role IN ('user', 'admin')),
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,
created TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
expires_at TEXT NOT NULL,
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,
limit_value INTEGER,
PRIMARY KEY (profile_id, feature_id)
);
CREATE TABLE IF NOT EXISTS user_feature_usage (
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
feature_id TEXT NOT NULL REFERENCES features(id) ON DELETE CASCADE,
period_key TEXT NOT NULL,
used INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (profile_id, feature_id, period_key)
);
CREATE TABLE IF NOT EXISTS ai_prompts (
id TEXT PRIMARY KEY,
slug TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
category TEXT NOT NULL DEFAULT 'uncategorized',
prompt_type TEXT NOT NULL DEFAULT 'base' CHECK (prompt_type IN ('base', 'pipeline', 'workflow')),
template TEXT NOT NULL DEFAULT '',
stages_json TEXT,
graph_json TEXT,
output_format TEXT NOT NULL DEFAULT 'text',
output_schema_json TEXT,
required_feature TEXT NOT NULL DEFAULT 'ai_calls',
active INTEGER NOT NULL DEFAULT 1,
is_system_default INTEGER NOT NULL DEFAULT 0,
default_template TEXT NOT NULL DEFAULT '',
sort_order INTEGER NOT NULL DEFAULT 0,
created TEXT NOT NULL DEFAULT (datetime('now')),
updated TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS usage_sessions (
id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
intent TEXT NOT NULL DEFAULT '',
started_at TEXT NOT NULL DEFAULT (datetime('now')),
ended_at TEXT,
created TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS conversations (
id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
usage_session_id TEXT REFERENCES usage_sessions(id),
title TEXT NOT NULL DEFAULT '',
created TEXT NOT NULL DEFAULT (datetime('now')),
updated TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS messages (
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,
seq INTEGER NOT NULL,
role TEXT NOT NULL,
body TEXT NOT NULL,
created TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE (conversation_id, seq)
);
CREATE TABLE IF NOT EXISTS threads (
id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
title TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'open',
visibility TEXT NOT NULL DEFAULT 'internal' CHECK (visibility IN ('internal', 'user')),
resurfacing_at TEXT,
created TEXT NOT NULL DEFAULT (datetime('now')),
updated TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS conversation_threads (
conversation_id TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
thread_id TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
PRIMARY KEY (conversation_id, thread_id)
);
CREATE TABLE IF NOT EXISTS spaces (
id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
title TEXT NOT NULL DEFAULT '',
visibility TEXT NOT NULL DEFAULT 'internal' CHECK (visibility IN ('internal', 'user')),
created TEXT NOT NULL DEFAULT (datetime('now')),
updated TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS thread_spaces (
thread_id TEXT NOT NULL REFERENCES threads(id) ON DELETE CASCADE,
space_id TEXT NOT NULL REFERENCES spaces(id) ON DELETE CASCADE,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
confidence REAL,
PRIMARY KEY (thread_id, space_id)
);
CREATE TABLE IF NOT EXISTS derived_records (
id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
kind TEXT NOT NULL,
subject_type TEXT NOT NULL,
subject_id TEXT NOT NULL,
source_message_ids TEXT NOT NULL,
as_of TEXT NOT NULL,
confidence REAL,
visibility TEXT NOT NULL DEFAULT 'internal' CHECK (visibility IN ('internal', 'user')),
body TEXT NOT NULL DEFAULT '',
created TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS handoffs (
id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
target TEXT NOT NULL CHECK (target IN ('journal', 'memory', 'knowledge', 'action', 'mindnet', 'obsidian')),
status TEXT NOT NULL DEFAULT 'draft',
source_conversation_id TEXT REFERENCES conversations(id),
payload_json TEXT NOT NULL DEFAULT '{}',
created TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS external_refs (
id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
target TEXT NOT NULL CHECK (target IN ('mindnet', 'obsidian')),
external_id TEXT NOT NULL DEFAULT '',
kansho_type TEXT NOT NULL,
kansho_id TEXT NOT NULL,
created TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS re_grounding_events (
id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
subject_type TEXT NOT NULL,
subject_id TEXT NOT NULL,
reason TEXT NOT NULL DEFAULT '',
source_message_ids TEXT NOT NULL DEFAULT '[]',
created TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS identity_mappings (
id TEXT PRIMARY KEY,
profile_id TEXT NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
token TEXT NOT NULL,
local_label TEXT NOT NULL DEFAULT '',
created TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE (profile_id, token)
);
+1
View File
@@ -0,0 +1 @@
# Kanshō local frame. Not a domain test package.
+157
View File
@@ -0,0 +1,157 @@
"""Dialogue memory contracts. Run from backend/: python tests/test_dialogue_memory.py"""
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["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
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 main() -> None:
with TestClient(app) as client:
setup = client.post(
"/api/auth/setup",
json={"email": "lars@example.test", "name": "Lars", "password": "test-pass"},
)
token = setup.json()["token"]
headers = header(token)
usage = client.post("/api/dialogue/sessions", headers=headers, json={"intent": "festhalten"})
expect(usage.status_code == 200, f"start usage session {usage.text}")
usage_id = usage.json()["id"]
conv = client.post(
"/api/dialogue/conversations",
headers=headers,
json={"usage_session_id": usage_id, "title": "Testgespräch"},
)
expect(conv.status_code == 200, f"create conversation {conv.text}")
cid = conv.json()["id"]
msg = client.post(
"/api/dialogue/conversations/{}/messages".format(cid),
headers=headers,
json={"body": "Heute war der Tag anstrengend.", "id": "msg-fixed-1"},
)
expect(msg.status_code == 200 and msg.json()["seq"] == 1, f"append message {msg.text}")
mid = msg.json()["id"]
again = client.post(
"/api/dialogue/conversations/{}/messages".format(cid),
headers=headers,
json={"body": "Heute war der Tag anstrengend.", "id": "msg-fixed-1"},
)
expect(again.status_code == 200 and again.json()["id"] == mid, "idempotent message id")
thread = client.post("/api/dialogue/threads", headers=headers, json={"title": "Offener Faden", "status": "open"})
expect(thread.status_code == 200, "create thread")
tid = thread.json()["id"]
thread_status = thread.json()["status"]
client.post(f"/api/dialogue/conversations/{cid}/threads/{tid}", headers=headers)
derived_bad = client.post(
"/api/dialogue/derived",
headers=headers,
json={
"kind": "thread_memory",
"subject_type": "conversation",
"subject_id": cid,
"source_message_ids": [],
"body": "ohne quelle",
},
)
expect(derived_bad.status_code == 400, "derived without provenance rejected")
expect(derived_bad.json()["detail"]["code"] == "provenance_required", "provenance code")
unknown = client.post(
"/api/dialogue/derived",
headers=headers,
json={
"kind": "journal_summary",
"subject_type": "conversation",
"subject_id": cid,
"source_message_ids": [mid],
"body": "nein",
},
)
expect(unknown.status_code == 400, "unregistered kind rejected")
derived = client.post(
"/api/dialogue/derived",
headers=headers,
json={
"kind": "working_context_snapshot",
"subject_type": "conversation",
"subject_id": cid,
"source_message_ids": [mid],
"body": "Arbeitsstand, nicht Erkenntnis",
},
)
expect(derived.status_code == 200, f"derived with provenance {derived.text}")
ended = client.post(f"/api/dialogue/sessions/{usage_id}/end", headers=headers)
expect(ended.status_code == 200, f"end usage session {ended.text}")
expect(ended.json()["threads_unchanged"] is True, "checkpoint reports threads unchanged")
expect(ended.json()["llm"] is False, "no llm on checkpoint")
messages = client.get(f"/api/dialogue/conversations/{cid}/messages", headers=headers)
expect(len(messages.json()) == 1, "original survives session end")
expect(messages.json()[0]["body"].startswith("Heute"), "original body intact")
from db import get_db, row_to_dict
with get_db() as conn:
row = row_to_dict(conn.execute("SELECT status FROM threads WHERE id = ?", (tid,)).fetchone())
expect(row["status"] == thread_status, "session end did not change thread status")
other = client.post(
"/api/users",
headers=headers,
json={"email": "ute@example.test", "name": "Ute", "password": "user-pass", "role": "user"},
)
login = client.post("/api/auth/login", json={"email": "ute@example.test", "password": "user-pass"})
other_headers = header(login.json()["token"])
stolen = client.get(f"/api/dialogue/conversations/{cid}", headers=other_headers)
expect(stolen.status_code == 404, "other profile cannot read conversation")
ctx = client.get(f"/api/dialogue/conversations/{cid}/context", headers=headers)
expect(ctx.status_code == 200 and ctx.json()["egress"] is False, "internal context does not egress")
admin = client.get("/api/admin/dialogue", headers=headers)
expect(admin.status_code == 200, "admin dialogue inventory")
expect(admin.json()["instance"]["messages"] >= 1, "admin sees message count")
detail = client.get(f"/api/admin/dialogue/conversations/{cid}", headers=headers)
expect(len(detail.json()["original_messages"]) == 1, "admin original vs derived split")
expect(len(detail.json()["derived_records"]) == 1, "derived listed separately")
spoof = client.get(
f"/api/dialogue/conversations/{cid}",
headers={**headers, "X-Profile-Id": other.json()["id"]},
)
expect(spoof.status_code == 200, "identity from session not profile header")
print("All dialogue memory tests passed.")
if __name__ == "__main__":
main()
+197
View File
@@ -0,0 +1,197 @@
"""Smoke test for the local product frame. Run from backend/: python tests/test_frame.py"""
from __future__ import annotations
import json
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_DB_PATH"] = str(Path(tempfile.gettempdir()) / "kansho-frame-test.sqlite")
Path(os.environ["KANSHO_DB_PATH"]).unlink(missing_ok=True)
from fastapi.testclient import TestClient
from main import app
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 main() -> None:
seed_prompts = json.loads((ROOT / "config" / "prompts.seed.json").read_text(encoding="utf-8"))
expect(seed_prompts == [], "prompt seed is empty — no domain prompts in git")
with TestClient(app) as client:
health = client.get("/api/health")
expect(health.status_code == 200 and health.json()["service"] == "kansho", "health")
status = client.get("/api/auth/status")
expect(status.json()["needs_setup"] is True, "needs setup before first profile")
denied = client.get("/api/auth/me")
expect(denied.status_code == 401, "me without session is 401")
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)
expect(setup.json()["role"] == "admin", "first profile is admin")
again = client.post(
"/api/auth/setup",
json={"email": "other@example.test", "name": "Other", "password": "test-pass"},
)
expect(again.status_code == 409, "second setup is blocked")
me = client.get("/api/auth/me", headers=headers)
expect(me.status_code == 200 and me.json()["email"] == "lars@example.test", "me with session")
spoof = client.get(
"/api/auth/me",
headers={**headers, "X-Profile-Id": "someone-else"},
)
expect(spoof.json()["id"] == me.json()["id"], "identity comes from session, not profile header")
login = client.post(
"/api/auth/login",
json={"email": "lars@example.test", "password": "test-pass"},
)
expect(login.status_code == 200, "login")
token = login.json()["token"]
headers = auth_header(token)
admin = client.get("/api/admin/health", headers=headers)
expect(admin.status_code == 200, "admin health")
expect(admin.json()["inventory"]["prompts"] == 0, "no seeded prompts")
missing = client.post(
"/api/prompts/execute",
headers=headers,
json={"prompt_id": "demo", "data_class": "B"},
)
expect(missing.status_code == 404, "execute requires a stored prompt")
created = client.post(
"/api/prompts",
headers=headers,
json={
"slug": "frame-echo",
"name": "Frame Echo",
"template": "Zeit {{now}} für [[SELF]] am [[PLACE:HOME]].",
},
)
expect(created.status_code == 200, f"create prompt {created.text}")
prompt_id = created.json()["id"]
bad_key = client.post(
"/api/prompts",
headers=headers,
json={"slug": "bad", "name": "Bad", "template": "Hallo {{journal_summary}}"},
)
expect(bad_key.status_code == 400, "unknown context key rejected")
expect(bad_key.json()["detail"]["code"] == "unknown_placeholder", "unknown key code")
bad_privacy = client.post(
"/api/prompts",
headers=headers,
json={"slug": "bad-privacy", "name": "Bad privacy", "template": "[[INDIAN_WIFE]]"},
)
expect(bad_privacy.status_code == 400, "speaking privacy token rejected")
preview = client.post("/api/prompts/preview", headers=headers, json={"prompt_id": prompt_id})
expect(preview.status_code == 200, f"preview {preview.text}")
expect("{{now}}" not in preview.json()["rendered"], "context key resolved")
expect("[[SELF]]" in preview.json()["rendered"], "privacy token left for gateway")
expect(preview.json()["llm"] is False, "preview does not call LLM")
blocked = client.post(
"/api/prompts/execute",
headers=headers,
json={"prompt_id": prompt_id, "data_class": "B"},
)
expect(blocked.status_code == 503, f"gateway fail-closed {blocked.text}")
expect(blocked.json()["detail"]["code"] == "no_egress_provider_configured", "gateway reason")
class_a = client.post(
"/api/prompts/execute",
headers=headers,
json={"prompt_id": prompt_id, "data_class": "A"},
)
expect(class_a.status_code == 503, "class A never leaves")
expect(class_a.json()["detail"]["code"] == "class_a_never_leaves_local_zone", "class A reason")
created_user = client.post(
"/api/users",
headers=headers,
json={"email": "user@example.test", "name": "Ute", "password": "user-pass", "role": "user"},
)
expect(created_user.status_code == 200, f"admin creates user {created_user.text}")
expect(created_user.json()["role"] == "user", "created role is user")
users = client.get("/api/users", headers=headers)
expect(len(users.json()) == 2, "two profiles")
user_login = client.post(
"/api/auth/login",
json={"email": "user@example.test", "password": "user-pass"},
)
expect(user_login.status_code == 200, "user login")
user_headers = auth_header(user_login.json()["token"])
forbidden_users = client.get("/api/users", headers=user_headers)
expect(forbidden_users.status_code == 403, "user cannot list users")
sub = client.get("/api/subscription", headers=user_headers)
expect(sub.status_code == 200, "subscription payload")
expect(sub.json()["tier"]["id"] == "local", "local tier")
expect(sub.json()["billing"] is None, "no billing provider")
expect(any(item["feature_id"] == "ai_calls" and item["allowed"] for item in sub.json()["features"]), "ai_calls allowed")
placeholders = client.get("/api/placeholders", headers=user_headers)
expect(placeholders.status_code == 200, "placeholder catalog")
keys = {item["key"] for item in placeholders.json()["context"]}
expect(keys == {"now"}, "only system context key now")
last_admin = client.patch(
f"/api/users/{me.json()['id']}",
headers=headers,
json={"role": "user"},
)
expect(last_admin.status_code == 400, "last admin cannot be demoted")
disabled = client.patch(
f"/api/users/{created_user.json()['id']}",
headers=headers,
json={"status": "disabled"},
)
expect(disabled.status_code == 200, "disable user")
disabled_login = client.post(
"/api/auth/login",
json={"email": "user@example.test", "password": "user-pass"},
)
expect(disabled_login.status_code == 401, "disabled user cannot login")
bad_login = client.post(
"/api/auth/login",
json={"email": "lars@example.test", "password": "wrong"},
)
expect(bad_login.status_code == 401, "bad password")
print("All frame tests passed.")
if __name__ == "__main__":
main()
+13
View File
@@ -0,0 +1,13 @@
APP_VERSION = "0.1.0-frame"
BUILD_DATE = "2026-08-19"
MODULE_VERSIONS = {
"auth": "0.1.0",
"users": "0.1.0",
"entitlements": "0.1.0",
"privacy_gateway": "0.1.0",
"placeholders": "0.1.0",
"prompts": "0.1.0",
"data_layer": "0.1.0",
"dialogue": "0.1.0",
"continuity": "0.1.0",
}