rename(547): the server is grimoire — package, image, DB defaults, backups
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 12s
CI & Build / TypeScript typecheck (push) Successful in 56s
CI & Build / integration (push) Successful in 1m4s
CI & Build / Python tests (push) Successful in 1m55s
CI & Build / Build & push image (push) Successful in 44s

Step 2 of the Scribe -> Grimoire rename.

- src/scribe -> src/grimoire, and every import, patch target, module path,
  hypercorn entry point and `python -m grimoire.restore` with it; pyproject,
  uv.lock and the frontend package are named grimoire.
- Image git.fabledsword.com/bvandeusen/fabledgrimoire; CI's Postgres service
  runs as grimoire / grimoire_test.
- Compose files default the DB user, database and (prod) volume to grimoire,
  each overridable from .env, so an install created as Scribe keeps its data
  by setting POSTGRES_USER, POSTGRES_DB and PGDATA_VOLUME.
- Backups are written as grimoire-<ts>.tar with format grimoire-backup-tar.
  Archives named scribe-* with the scribe-backup-tar manifest still restore
  and are still counted at the destination (folder and S3), with tests.
- Exports, the MCP auth realm, the ASGI scope key and the persistent logger
  carry the new name.

Kept on purpose: the secret-sealing key label stays "scribe.secrets.v1",
because every stored secret was derived under it.

Plugin identity (plugin name, hooks, env vars, .scribe marker, skills) is
step 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 10:50:45 -04:00
co-authored by Claude Opus 5.5
parent e99f1169f7
commit 0f5ef0be63
447 changed files with 3611 additions and 3558 deletions
View File
+503
View File
@@ -0,0 +1,503 @@
import asyncio
import json
from quart import Blueprint, Response, g, jsonify, request
from grimoire.auth import admin_required, login_required, get_current_user_id
from grimoire.services.auth import (
create_invitation,
delete_user,
is_registration_open,
list_pending_invitations,
list_users,
revoke_invitation,
set_registration_open,
)
from grimoire.services.backup import (
export_full_backup,
export_user_backup,
restore_full_backup,
)
from grimoire.services.email import SMTP_SETTING_KEYS, get_base_url, get_smtp_config, is_smtp_configured, send_test_email
from grimoire.services.logging import get_logs, get_log_stats, log_audit
from grimoire.services.notifications import send_invitation_email
from grimoire.services.settings import (
SECRET_MASK,
get_admin_setting,
set_admin_setting,
set_setting,
set_settings_batch,
)
admin_bp = Blueprint("admin", __name__, url_prefix="/api/admin")
@admin_bp.route("/backup", methods=["GET"])
@login_required
async def backup():
uid = get_current_user_id()
scope = request.args.get("scope", "user")
if scope == "full":
# Full backup requires admin
if g.user.role != "admin":
return jsonify({"error": "Admin access required for full backup"}), 403
data = await export_full_backup()
else:
data = await export_user_backup(uid)
await log_audit("backup", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"scope": scope})
return Response(
json.dumps(data, indent=2, default=str),
content_type="application/json",
headers={
"Content-Disposition": f'attachment; filename="fabled-backup-{scope}.json"',
},
)
@admin_bp.route("/restore", methods=["POST"])
@admin_required
async def restore():
"""Restore from an uploaded backup: the JSON download (application/json)
or the scheduled backup's tar (sent as the raw body). The upload is held
to the app's request-size limit; `python -m grimoire.restore` has none, and
is the way in for a bigger file or a fresh instance."""
if request.mimetype == "application/json":
data = await request.get_json()
else:
import io
from grimoire.services.backup_file import ArchiveError, read_archive
try:
data = read_archive(io.BytesIO(await request.get_data()))
except ArchiveError as exc:
return jsonify({"error": f"That file isn't a Grimoire backup: {exc}"}), 400
if not data:
return jsonify({"error": "No backup data provided"}), 400
stats = await restore_full_backup(data)
uid = get_current_user_id()
await log_audit("restore", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"stats": stats})
return jsonify({"status": "ok", "stats": stats})
@admin_bp.route("/users", methods=["GET"])
@admin_required
async def get_users():
users = await list_users()
return jsonify({"users": [u.to_dict() for u in users]})
@admin_bp.route("/users/<int:user_id>", methods=["DELETE"])
@admin_required
async def remove_user(user_id: int):
current_uid = get_current_user_id()
if user_id == current_uid:
return jsonify({"error": "Cannot delete your own account"}), 400
deleted = await delete_user(user_id)
if not deleted:
return jsonify({"error": "User not found"}), 404
await log_audit("user_delete", user_id=current_uid, username=g.user.username, ip_address=request.remote_addr, details={"deleted_user_id": user_id})
return jsonify({"status": "ok"})
@admin_bp.route("/registration", methods=["GET"])
@admin_required
async def get_registration():
open_status = await is_registration_open()
return jsonify({"open": open_status})
@admin_bp.route("/registration", methods=["PUT"])
@admin_required
async def toggle_registration():
data = await request.get_json()
open_val = data.get("open")
if open_val is None:
return jsonify({"error": "Missing 'open' field"}), 400
uid = get_current_user_id()
await set_registration_open(uid, bool(open_val))
await log_audit("registration_toggle", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"open": bool(open_val)})
return jsonify({"status": "ok", "open": bool(open_val)})
@admin_bp.route("/smtp", methods=["GET"])
@admin_required
async def get_smtp():
config = await get_smtp_config()
# Mask password
if config.get("smtp_password"):
config["smtp_password"] = SECRET_MASK
return jsonify(config)
@admin_bp.route("/smtp", methods=["PUT"])
@admin_required
async def update_smtp():
data = await request.get_json()
uid = get_current_user_id()
settings_to_save = {}
for key in SMTP_SETTING_KEYS:
if key in data:
# Skip password if it's the mask placeholder
if key == "smtp_password" and data[key] == SECRET_MASK:
continue
settings_to_save[key] = str(data[key])
if settings_to_save:
await set_settings_batch(uid, settings_to_save)
await log_audit("smtp_config", user_id=uid, username=g.user.username, ip_address=request.remote_addr)
return jsonify({"status": "ok"})
@admin_bp.route("/smtp/test", methods=["POST"])
@admin_required
async def test_smtp():
data = await request.get_json()
recipient = (data.get("recipient") or "").strip()
if not recipient:
return jsonify({"error": "Recipient email is required"}), 400
uid = get_current_user_id()
try:
await send_test_email(recipient)
await log_audit("smtp_test", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"recipient": recipient})
return jsonify({"status": "ok"})
except Exception as e:
return jsonify({"error": str(e)}), 500
# The forge CONFIG is per-user keyring rows (Settings → Git forges); what
# stays admin is the webhook secret, because the push endpoint
# is one URL per instance and authenticates deliveries, not users.
@admin_bp.route("/forge-webhook", methods=["GET"])
@admin_required
async def get_forge_webhook_settings():
from grimoire.config import Config
from grimoire.routes.webhooks import FORGE_WEBHOOK_SECRET_KEY
webhook_secret = (
await get_admin_setting(FORGE_WEBHOOK_SECRET_KEY, "")
or Config.FORGE_WEBHOOK_SECRET
)
return jsonify({
# Secrets never leave the server — the smtp_password convention:
# masked when set, empty when not.
"webhook_secret": SECRET_MASK if webhook_secret else "",
})
@admin_bp.route("/forge-webhook", methods=["PUT"])
@admin_required
async def update_forge_webhook_settings():
from grimoire.routes.webhooks import FORGE_WEBHOOK_SECRET_KEY
data = await request.get_json() or {}
uid = get_current_user_id()
webhook_secret = data.get("webhook_secret")
# The mask coming back means "unchanged" — the form round-trips what GET
# showed it, and storing the mask would silently break the integration.
if webhook_secret is not None and webhook_secret != SECRET_MASK:
await set_admin_setting(FORGE_WEBHOOK_SECRET_KEY, str(webhook_secret))
# The secret is deliberately absent from the audit detail.
await log_audit(
"forge_webhook_config", user_id=uid, username=g.user.username,
ip_address=request.remote_addr, details={},
)
return jsonify({"status": "ok"})
@admin_bp.route("/logs", methods=["GET"])
@admin_required
async def list_logs():
category = request.args.get("category")
user_id = request.args.get("user_id", type=int)
search = request.args.get("search")
date_from = request.args.get("date_from")
date_to = request.args.get("date_to")
limit = request.args.get("limit", 50, type=int)
offset = request.args.get("offset", 0, type=int)
logs, total = await get_logs(
category=category,
user_id=user_id,
search=search,
date_from=date_from,
date_to=date_to,
limit=min(limit, 200),
offset=offset,
)
return jsonify({"logs": logs, "total": total})
@admin_bp.route("/logs/stats", methods=["GET"])
@admin_required
async def log_stats():
stats = await get_log_stats()
return jsonify(stats)
@admin_bp.route("/base-url", methods=["GET"])
@admin_required
async def get_base_url_setting():
base_url = await get_base_url()
return jsonify({"base_url": base_url})
@admin_bp.route("/base-url", methods=["PUT"])
@admin_required
async def update_base_url():
data = await request.get_json()
url = (data.get("base_url") or "").strip().rstrip("/")
if url:
scheme = url.split("://")[0].lower() if "://" in url else ""
if scheme not in ("http", "https"):
return jsonify({"error": "Base URL must use http or https"}), 400
uid = get_current_user_id()
await set_setting(uid, "base_url", url)
await log_audit("base_url_config", user_id=uid, username=g.user.username, ip_address=request.remote_addr, details={"base_url": url})
return jsonify({"status": "ok"})
@admin_bp.route("/db-maintenance", methods=["GET"])
@admin_required
async def get_db_maintenance():
"""Current DB-maintenance config + the last run's summary."""
from grimoire.services.db_maintenance import get_last_run
from grimoire.services.db_maintenance_scheduler import (
get_maintenance_hour,
is_maintenance_enabled,
)
return jsonify({
"enabled": await is_maintenance_enabled(),
"hour": await get_maintenance_hour(),
"last_run": await get_last_run(),
})
@admin_bp.route("/db-maintenance/health", methods=["GET"])
@admin_required
async def get_db_maintenance_health():
"""Read-only per-table bloat/health stats from Postgres + total DB size."""
from grimoire.services.db_maintenance import get_table_health
return jsonify(await get_table_health())
@admin_bp.route("/db-maintenance", methods=["PUT"])
@admin_required
async def update_db_maintenance():
"""Set whether scheduled maintenance runs and at what UTC hour."""
from grimoire.services.db_maintenance_scheduler import reschedule_db_maintenance
data = await request.get_json() or {}
enabled = bool(data.get("enabled", True))
try:
hour = int(data.get("hour", 4))
except (TypeError, ValueError):
return jsonify({"error": "hour must be an integer 0–23"}), 400
if not 0 <= hour <= 23:
return jsonify({"error": "hour must be between 0 and 23"}), 400
await set_admin_setting("db_maintenance_enabled", "true" if enabled else "false")
await set_admin_setting("db_maintenance_hour", str(hour))
reschedule_db_maintenance(hour)
uid = get_current_user_id()
await log_audit(
"db_maintenance_config", user_id=uid, username=g.user.username,
ip_address=request.remote_addr, details={"enabled": enabled, "hour": hour},
)
return jsonify({"status": "ok", "enabled": enabled, "hour": hour})
@admin_bp.route("/db-maintenance/run", methods=["POST"])
@admin_required
async def run_db_maintenance_now():
"""Run a VACUUM (ANALYZE) sweep immediately and return its summary."""
from grimoire.services.db_maintenance import run_maintenance
uid = get_current_user_id()
await log_audit(
"db_maintenance_run", user_id=uid, username=g.user.username,
ip_address=request.remote_addr,
)
summary = await run_maintenance()
return jsonify(summary)
# ── Scheduled backups ────────────────────────────────────────────────────────
# One dated, uncompressed tar per run to a folder or an S3 bucket — see
# services/backup_file.py for why it is shaped that way, backup_destination.py
# for where it goes, backup_job.py for when.
# How long "Test" waits on the destination. A folder on a hung NFS mount has
# no timeout of its own, and the request must come back either way.
_BACKUP_CHECK_TIMEOUT = 45.0
async def _backups_payload() -> dict:
from datetime import datetime, timezone
from grimoire.services import backup_destination as dest
from grimoire.services import backup_job as job
config = await dest.load_config()
secret, stored = await dest.load_secret()
runs = await job.list_runs()
return {
"config": config.to_dict(),
# Never the secret itself: whether one is kept, and whether this
# instance can still open it (it can't after a restore onto another
# SECRET_KEY, and then it has to be entered again).
"secret": {"set": stored, "readable": secret is not None},
"problems": config.problems(has_secret=secret is not None),
"running": job.is_running(),
"runs": runs,
**job.summarise(runs, enabled=config.enabled, now=datetime.now(timezone.utc)),
}
@admin_bp.route("/backups", methods=["GET"])
@admin_required
async def get_backups():
"""The backup destination, its schedule, and the recent runs."""
return jsonify(await _backups_payload())
@admin_bp.route("/backups", methods=["PUT"])
@admin_required
async def update_backups():
"""Change the destination or schedule. `s3_secret` replaces the stored
secret when it is sent and isn't the mask; `clear_s3_secret` removes it."""
from grimoire.services import backup_destination as dest
data = await request.get_json() or {}
try:
config = dest.apply_changes(await dest.load_config(), data)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
await dest.save_config(config)
secret = data.get("s3_secret")
if data.get("clear_s3_secret"):
await dest.save_secret("")
elif isinstance(secret, str) and secret and secret != SECRET_MASK:
await dest.save_secret(secret)
uid = get_current_user_id()
await log_audit(
"backup_config", user_id=uid, username=g.user.username,
ip_address=request.remote_addr,
details={**config.to_dict(), "secret_changed": bool(
data.get("clear_s3_secret") or (isinstance(secret, str) and secret and secret != SECRET_MASK)
)},
)
return jsonify(await _backups_payload())
@admin_bp.route("/backups/check", methods=["POST"])
@admin_required
async def check_backups_destination():
"""Ask the destination whether it would take a backup, without sending
one. The body may carry unsaved form values, so a destination can be
tested before it is saved; the stored secret is used unless one is sent."""
from grimoire.services import backup_destination as dest
data = await request.get_json() or {}
try:
config = dest.apply_changes(await dest.load_config(), data)
except ValueError as exc:
return jsonify({"ok": False, "message": str(exc)})
secret = data.get("s3_secret")
if not (isinstance(secret, str) and secret and secret != SECRET_MASK):
secret, _ = await dest.load_secret()
try:
message = await asyncio.wait_for(
dest.check_destination(config, secret), _BACKUP_CHECK_TIMEOUT,
)
except dest.DestinationError as exc:
return jsonify({"ok": False, "message": str(exc)})
except (TimeoutError, asyncio.TimeoutError):
return jsonify({"ok": False, "message": (
f"The destination didn't answer within {int(_BACKUP_CHECK_TIMEOUT)} seconds."
)})
return jsonify({"ok": True, "message": message})
@admin_bp.route("/backups/run", methods=["POST"])
@admin_required
async def run_backup_now():
"""Start a backup now. It runs in the background; the page follows it
through GET /backups (`running`, then the newest run)."""
from grimoire.services import backup_job as job
try:
job.start_backup_now()
except job.BackupBusy:
return jsonify({"error": "A backup is already running."}), 409
uid = get_current_user_id()
await log_audit("backup_run", user_id=uid, username=g.user.username,
ip_address=request.remote_addr, details={})
return jsonify({"status": "started"}), 202
@admin_bp.route("/invitations", methods=["POST"])
@admin_required
async def create_invite():
data = await request.get_json()
email = (data.get("email") or "").strip().lower()
if not email:
return jsonify({"error": "Email is required"}), 400
if not await is_smtp_configured():
return jsonify({"error": "SMTP is not configured. Configure email settings first."}), 400
uid = get_current_user_id()
raw_token = await create_invitation(email, uid)
base_url = await get_base_url()
invite_url = f"{base_url}/register-invite?token={raw_token}"
asyncio.create_task(send_invitation_email(email, invite_url, g.user.username))
await log_audit(
"invitation_created",
user_id=uid,
username=g.user.username,
ip_address=request.remote_addr,
details={"invited_email": email},
)
return jsonify({"status": "ok"}), 201
@admin_bp.route("/invitations", methods=["GET"])
@admin_required
async def get_invitations():
invitations = await list_pending_invitations()
return jsonify({
"invitations": [
{
"id": inv.id,
"email": inv.email,
"created_at": inv.created_at.isoformat(),
"expires_at": inv.expires_at.isoformat(),
}
for inv in invitations
]
})
@admin_bp.route("/invitations/<int:invitation_id>", methods=["DELETE"])
@admin_required
async def delete_invitation(invitation_id: int):
uid = get_current_user_id()
revoked = await revoke_invitation(invitation_id)
if not revoked:
return jsonify({"error": "Invitation not found or already used"}), 404
await log_audit(
"invitation_revoked",
user_id=uid,
username=g.user.username,
ip_address=request.remote_addr,
details={"invitation_id": invitation_id},
)
return jsonify({"status": "ok"})
+67
View File
@@ -0,0 +1,67 @@
import os
from quart import Blueprint, jsonify
api = Blueprint("api", __name__, url_prefix="/api")
@api.route("/health")
async def health():
return jsonify({"status": "ok"})
def build_version_payload() -> dict:
"""What build is this, separated into the values that answer different
questions.
A channel name ("dev", "main") is not a build identifier: with a deploy
misbehaving, the one endpoint whose job is to say which commit is serving
must not answer with the name of a branch.
The three values, and why they are three:
- `version` — the NAME, `YYYY.MM.DD.HHMM` from COMMIT time. Answers "is
this the same code?", so two channels carrying one commit report the
same string.
- `build` — the ORDERING KEY, minutes since 2020-01-01 from BUILD time.
Answers "may this be installed over that?". The ONLY value anything may
compare; it is monotonic by construction, which neither a commit count
(branches diverge) nor a commit time (rebuilds go backwards) is.
- `channel` — its own field, never folded into the name.
Plus `commit`, so the artifact's claim about itself can be checked against
the `:<sha>` it was published under.
ABSENT RATHER THAN EMPTY when unknown. A local build has no ordering key
and no channel, and saying so is honest; emitting `""` or a placeholder
would let it claim a position in an update order it is not part of. A
reader must treat a missing `build` as "cannot be ordered", not as zero.
"""
payload: dict = {"version": os.environ.get("APP_VERSION", "dev")}
# Reported verbatim, never validated against an enum — a build claiming
# something unexpected is better shown than dropped.
for key, env in (("channel", "APP_CHANNEL"), ("commit", "APP_COMMIT")):
value = (os.environ.get(env) or "").strip()
if value:
payload[key] = value
raw_key = (os.environ.get("APP_BUILD_KEY") or "").strip()
if raw_key:
try:
# An INTEGER, not a string. A string ordering key is how a
# comparison silently becomes lexicographic — "9" > "10" — which
# is the same class of fault as folding the channel in: it reads
# fine and orders wrong.
payload["build"] = int(raw_key)
except ValueError:
# A malformed key is omitted rather than passed through: a reader
# that cannot order is correct, one that orders on garbage is not.
pass
return payload
@api.route("/version")
async def version():
return jsonify(build_version_payload())
+42
View File
@@ -0,0 +1,42 @@
from quart import Blueprint, jsonify, request
from grimoire.auth import login_required, get_current_user_id
from grimoire.services.api_keys import create_api_key, list_api_keys, revoke_api_key
api_keys_bp = Blueprint("api_keys", __name__, url_prefix="/api/api-keys")
@api_keys_bp.route("", methods=["GET"])
@login_required
async def list_keys_route():
uid = get_current_user_id()
keys = await list_api_keys(uid)
return jsonify({"api_keys": keys})
@api_keys_bp.route("", methods=["POST"])
@login_required
async def create_key_route():
uid = get_current_user_id()
data = await request.get_json(force=True, silent=True) or {}
name = (data.get("name") or "").strip()
scope = (data.get("scope") or "").strip()
if not name:
return jsonify({"error": "name is required"}), 400
if scope not in ("read", "write"):
return jsonify({"error": "scope must be 'read' or 'write'"}), 400
full_key, key_dict = await create_api_key(uid, name=name, scope=scope)
# Return the full key ONCE — it is never retrievable again
return jsonify({"key": full_key, "api_key": key_dict}), 201
@api_keys_bp.route("/<int:key_id>", methods=["DELETE"])
@login_required
async def revoke_key_route(key_id: int):
uid = get_current_user_id()
deleted = await revoke_api_key(uid, key_id)
if not deleted:
return jsonify({"error": "API key not found"}), 404
return "", 204
+375
View File
@@ -0,0 +1,375 @@
import asyncio
import base64
import hashlib
import os
import secrets
from quart import Blueprint, g, jsonify, redirect, request, session
from grimoire.auth import login_required, get_current_user_id
from grimoire.config import Config
from grimoire.rate_limit import is_rate_limited
from grimoire.services.auth import (
authenticate,
change_password,
create_password_reset_token,
create_user,
get_user_by_email,
get_user_by_id,
get_user_by_username,
get_user_count,
invalidate_other_sessions,
is_registration_open,
register_with_invitation,
reset_password_with_token,
update_user_email,
validate_invitation_token,
verify_password,
)
from grimoire.services.logging import log_audit
from grimoire.services.notifications import (
notify_security_event,
send_password_reset_email,
send_password_reset_success_email,
)
from grimoire.services.email import get_base_url, is_smtp_configured
from grimoire.services.oauth import (
build_auth_url,
exchange_code,
get_userinfo,
find_or_create_oauth_user,
)
auth_bp = Blueprint("auth", __name__, url_prefix="/api/auth")
def _client_ip() -> str:
if Config.TRUST_PROXY_HEADERS:
for header in ("X-Forwarded-For", "X-Real-IP"):
val = request.headers.get(header, "").split(",")[0].strip()
if val:
return val
return request.remote_addr or ""
@auth_bp.route("/register", methods=["POST"])
async def register():
if not Config.LOCAL_AUTH_ENABLED:
return jsonify({"error": "Local authentication is disabled. Please use SSO."}), 403
if await is_rate_limited(f"register:{_client_ip()}", max_requests=5, window_seconds=300):
return jsonify({"error": "Too many registration attempts. Try again later."}), 429
if not await is_registration_open():
return jsonify({"error": "Registration is closed"}), 403
data = await request.get_json()
username = (data.get("username") or "").strip()
password = data.get("password") or ""
email = (data.get("email") or "").strip() or None
if not username:
return jsonify({"error": "Username is required"}), 400
if len(password) < 8:
return jsonify({"error": "Password must be at least 8 characters"}), 400
try:
user = await create_user(username, password, email)
except Exception:
return jsonify({"error": "Username already taken"}), 409
session["user_id"] = user.id
session["session_version"] = user.session_version
await log_audit("register", user_id=user.id, username=user.username, ip_address=_client_ip())
return jsonify(user.to_dict()), 201
@auth_bp.route("/login", methods=["POST"])
async def login():
if not Config.LOCAL_AUTH_ENABLED:
return jsonify({"error": "Local authentication is disabled. Please use SSO."}), 403
if await is_rate_limited(f"login:{_client_ip()}", max_requests=10, window_seconds=60):
return jsonify({"error": "Too many login attempts. Try again later."}), 429
data = await request.get_json()
username = (data.get("username") or "").strip()
password = data.get("password") or ""
if not username or not password:
return jsonify({"error": "Username and password are required"}), 400
user = await authenticate(username, password)
if not user:
await log_audit("login_failed", username=username, ip_address=_client_ip())
# Try to notify the actual user about the failed attempt
target_user = await get_user_by_username(username)
if target_user:
asyncio.create_task(notify_security_event(
target_user.id, "login_failed",
{"ip_address": _client_ip(), "username": username},
))
return jsonify({"error": "Invalid username or password"}), 401
session["user_id"] = user.id
session["session_version"] = user.session_version
await log_audit("login", user_id=user.id, username=user.username, ip_address=_client_ip())
asyncio.create_task(notify_security_event(
user.id, "login",
{"ip_address": _client_ip()},
))
return jsonify(user.to_dict())
@auth_bp.route("/logout", methods=["POST"])
async def logout():
uid = session.get("user_id")
if uid:
user = await get_user_by_id(uid)
await log_audit("logout", user_id=uid, username=user.username if user else None, ip_address=_client_ip())
asyncio.create_task(notify_security_event(
uid, "logout",
{"ip_address": _client_ip()},
))
session.clear()
return jsonify({"status": "ok"})
@auth_bp.route("/me", methods=["GET"])
@login_required
async def me():
user = await get_user_by_id(get_current_user_id())
if not user:
return jsonify({"error": "User not found"}), 404
return jsonify(user.to_dict())
@auth_bp.route("/password", methods=["PUT"])
@login_required
async def update_password():
data = await request.get_json()
current = data.get("current_password") or ""
new_pw = data.get("new_password") or ""
if not current:
return jsonify({"error": "Current password is required"}), 400
if len(new_pw) < 8:
return jsonify({"error": "New password must be at least 8 characters"}), 400
uid = get_current_user_id()
new_version = await change_password(uid, current, new_pw)
if new_version is None:
return jsonify({"error": "Current password is incorrect"}), 403
# Keep the current session alive with the new version (other sessions are now invalidated)
session["session_version"] = new_version
await log_audit("password_change", user_id=uid, username=g.user.username, ip_address=_client_ip())
asyncio.create_task(notify_security_event(
uid, "password_change",
{"ip_address": _client_ip()},
))
return jsonify({"status": "ok"})
@auth_bp.route("/invalidate-sessions", methods=["POST"])
@login_required
async def invalidate_sessions_route():
"""Invalidate all other active sessions by bumping the session version.
The current session is kept alive. Useful after an SSO/OAuth password change
where the app has no visibility into credential rotation.
"""
uid = get_current_user_id()
new_version = await invalidate_other_sessions(uid)
session["session_version"] = new_version
await log_audit("sessions_invalidated", user_id=uid, username=g.user.username, ip_address=_client_ip())
return jsonify({"status": "ok"})
@auth_bp.route("/email", methods=["PUT"])
@login_required
async def update_email():
data = await request.get_json()
new_email = (data.get("email") or "").strip().lower() or None
password = data.get("password") or ""
uid = get_current_user_id()
user = await get_user_by_id(uid)
if not user:
return jsonify({"error": "User not found"}), 404
# Require password confirmation only for local-auth users
if user.password_hash is not None:
if not password:
return jsonify({"error": "Password is required to change your email"}), 400
if not verify_password(password, user.password_hash):
return jsonify({"error": "Incorrect password"}), 403
# Check the new email isn't taken by a different account
if new_email:
existing = await get_user_by_email(new_email)
if existing and existing.id != uid:
return jsonify({"error": "Email already in use by another account"}), 409
await update_user_email(uid, new_email)
await log_audit("email_change", user_id=uid, username=user.username, ip_address=_client_ip())
updated = await get_user_by_id(uid)
return jsonify(updated.to_dict())
@auth_bp.route("/forgot-password", methods=["POST"])
async def forgot_password():
if await is_rate_limited(f"forgot:{_client_ip()}", max_requests=5, window_seconds=300):
return jsonify({"status": "ok"})
data = await request.get_json()
email = (data.get("email") or "").strip().lower()
if not email:
return jsonify({"error": "Email is required"}), 400
# Always return success to prevent email enumeration
user = await get_user_by_email(email)
if user and await is_smtp_configured():
raw_token = await create_password_reset_token(user.id)
base_url = await get_base_url()
reset_url = f"{base_url}/reset-password?token={raw_token}"
asyncio.create_task(send_password_reset_email(user.email, reset_url))
await log_audit(
"password_reset_requested",
user_id=user.id,
username=user.username,
ip_address=_client_ip(),
)
return jsonify({"status": "ok"})
@auth_bp.route("/reset-password", methods=["POST"])
async def reset_password():
if await is_rate_limited(f"reset:{_client_ip()}", max_requests=10, window_seconds=60):
return jsonify({"error": "Too many attempts. Try again later."}), 429
data = await request.get_json()
token = (data.get("token") or "").strip()
new_password = data.get("new_password") or ""
if not token:
return jsonify({"error": "Reset token is required"}), 400
if len(new_password) < 8:
return jsonify({"error": "Password must be at least 8 characters"}), 400
user_id = await reset_password_with_token(token, new_password)
if user_id is None:
return jsonify({"error": "Invalid or expired reset link"}), 400
user = await get_user_by_id(user_id)
if user:
await log_audit(
"password_reset_completed",
user_id=user.id, username=user.username, ip_address=_client_ip(),
)
if user.email:
asyncio.create_task(send_password_reset_success_email(user.email))
return jsonify({"status": "ok"})
@auth_bp.route("/invitation/<token>", methods=["GET"])
async def check_invitation(token: str):
invitation = await validate_invitation_token(token)
if not invitation:
return jsonify({"valid": False})
return jsonify({"valid": True, "email": invitation.email})
@auth_bp.route("/register-with-invite", methods=["POST"])
async def register_with_invite():
data = await request.get_json()
raw_token = (data.get("token") or "").strip()
username = (data.get("username") or "").strip()
password = data.get("password") or ""
if not raw_token:
return jsonify({"error": "Invitation token is required"}), 400
if not username:
return jsonify({"error": "Username is required"}), 400
if len(password) < 8:
return jsonify({"error": "Password must be at least 8 characters"}), 400
try:
user = await register_with_invitation(raw_token, username, password)
except Exception:
return jsonify({"error": "Username already taken"}), 409
if not user:
return jsonify({"error": "Invalid or expired invitation"}), 400
session["user_id"] = user.id
session["session_version"] = user.session_version
await log_audit(
"register_with_invite",
user_id=user.id,
username=user.username,
ip_address=_client_ip(),
)
return jsonify(user.to_dict()), 201
@auth_bp.route("/status", methods=["GET"])
async def status():
count = await get_user_count()
reg_open = await is_registration_open()
return jsonify({
"has_users": count > 0,
"registration_open": reg_open,
"oauth_enabled": Config.oidc_enabled(),
"local_auth_enabled": Config.LOCAL_AUTH_ENABLED,
})
@auth_bp.route("/oauth/login", methods=["GET"])
async def oauth_login():
if not Config.oidc_enabled():
return jsonify({"error": "SSO is not configured"}), 404
state = secrets.token_hex(32)
code_verifier = secrets.token_urlsafe(64)
digest = hashlib.sha256(code_verifier.encode()).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
session["oauth_state"] = state
session["oauth_code_verifier"] = code_verifier
url = await build_auth_url(state, code_challenge)
return redirect(url)
@auth_bp.route("/oauth/callback", methods=["GET"])
async def oauth_callback():
error = request.args.get("error")
code = request.args.get("code")
state = request.args.get("state")
stored_state = session.pop("oauth_state", None)
code_verifier = session.pop("oauth_code_verifier", None)
if error or not code or state != stored_state:
return redirect("/login?error=oauth")
redirect_uri = Config.BASE_URL.rstrip("/") + "/api/auth/oauth/callback"
try:
token_response = await exchange_code(code, redirect_uri, code_verifier)
claims = await get_userinfo(token_response["access_token"])
except Exception:
return redirect("/login?error=oauth")
sub = claims.get("sub", "")
# Only trust the email claim for account linking if the provider has verified it.
# An unverified email could be used to hijack an existing local account.
email_verified = claims.get("email_verified", False)
email = claims.get("email", "") if email_verified else ""
preferred_username = claims.get("preferred_username", "")
if not sub:
return redirect("/login?error=oauth")
user = await find_or_create_oauth_user(sub, email, preferred_username)
session["user_id"] = user.id
session["session_version"] = user.session_version
await log_audit("oauth_login", user_id=user.id, username=user.username, ip_address=_client_ip())
return redirect("/")
+93
View File
@@ -0,0 +1,93 @@
"""Canonical-system routes — the GLOBAL area vocabulary, and the mapping of a
project's Systems onto it.
Two shapes live here because they are two halves of one idea:
- `/api/canonical-systems` — the catalog itself. Readable by any signed-in
user (it is shared vocabulary, not user data); writable only by an admin,
since a global list anyone can extend stops being a shared list.
- the mapping endpoints — authorised by the PROJECT, because mapping writes a
project's own System row. The service enforces both; these are thin wrappers.
"""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import admin_required, get_current_user_id, login_required
from grimoire.routes.utils import not_found
from grimoire.services import canonical_systems as canonical_svc
from grimoire.services.projects import get_project_for_user
logger = logging.getLogger(__name__)
canonical_systems_bp = Blueprint("canonical_systems", __name__, url_prefix="/api")
@canonical_systems_bp.route("/canonical-systems", methods=["GET"])
@login_required
async def list_canonical_systems_route():
entries = await canonical_svc.list_canonical_systems()
return jsonify({"canonical_systems": [e.to_dict() for e in entries]})
@canonical_systems_bp.route("/canonical-systems", methods=["POST"])
@admin_required
async def create_canonical_system_route():
uid = get_current_user_id()
data = await request.get_json() or {}
if not (data.get("name") or "").strip():
return jsonify({"error": "name is required"}), 400
entry = await canonical_svc.create_canonical_system(
uid, data["name"], description=data.get("description"),
)
if entry is None:
return jsonify({"error": "Permission denied"}), 403
# The slug duplicate gate answers with the entry that already covers the
# area rather than minting a second spelling of it — 409, not a silent
# second row (the whole point of the table).
if isinstance(entry, dict):
return jsonify(entry), 409
return jsonify(entry.to_dict()), 201
@canonical_systems_bp.route("/canonical-systems/<int:canonical_id>", methods=["PATCH"])
@admin_required
async def update_canonical_system_route(canonical_id: int):
uid = get_current_user_id()
data = await request.get_json() or {}
fields = {k: v for k, v in data.items() if k in ("name", "description", "order_index")}
entry = await canonical_svc.update_canonical_system(uid, canonical_id, **fields)
if entry is None:
return not_found("Canonical system")
return jsonify(entry.to_dict())
@canonical_systems_bp.route(
"/projects/<int:project_id>/canonical-proposals", methods=["GET"]
)
@login_required
async def propose_canonical_mappings_route(project_id: int):
"""Proposals only — this endpoint writes nothing. The PUT below applies one."""
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
return jsonify({"proposals": await canonical_svc.propose_mappings(uid, project_id)})
@canonical_systems_bp.route("/systems/<int:system_id>/canonical", methods=["PUT"])
@login_required
async def map_system_to_canonical_route(system_id: int):
"""Map or unmap one System. Body: {"canonical_id": <id>|null}.
Sets that column and nothing else — no rename, no change to which records
are tagged to the System.
"""
uid = get_current_user_id()
data = await request.get_json() or {}
canonical_id = data.get("canonical_id")
if canonical_id is not None and not isinstance(canonical_id, int):
return jsonify({"error": "canonical_id must be an integer or null"}), 400
system = await canonical_svc.set_system_canonical(uid, system_id, canonical_id)
if system is None:
return not_found("System or canonical system")
return jsonify(system.to_dict())
+13
View File
@@ -0,0 +1,13 @@
"""Dashboard REST endpoint — the aggregated landing payload."""
from quart import Blueprint, g, jsonify
from grimoire.auth import login_required
from grimoire.services.dashboard import build_dashboard
dashboard_bp = Blueprint("dashboard", __name__, url_prefix="/api/dashboard")
@dashboard_bp.get("")
@login_required
async def get_dashboard():
return jsonify(await build_dashboard(g.user.id))
+250
View File
@@ -0,0 +1,250 @@
"""Design system + token REST endpoints.
Wraps `services/design_systems.py`, which owns the ACL and the cycle guard.
Design systems are owner-scoped top-level records rather than project-scoped
ones, so these do NOT nest under `/api/projects/` — `routes/rulebooks.py` is the
closer shape.
Two failures this layer has to keep apart, which is why the service raises for
one and returns None for the other:
- `DesignSystemCycle` -> 400 with its message. "That parent already inherits
from this system" is a correctable mistake and the caller needs to be told
which one they made.
- None -> 404, covering both "no such system" and "not yours". Conflating
those two IS the intent: distinguishing them would confirm the existence of
records the caller may not see.
"""
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.routes.utils import not_found
from grimoire.services import design_systems as ds_svc
from grimoire.services.design_starter_roles import (
DEFAULT_TOKEN_PREFIX,
describe_groups,
)
from grimoire.services.design_systems import DesignSystemCycle
design_systems_bp = Blueprint("design_systems", __name__, url_prefix="/api")
# ── Design systems ──────────────────────────────────────────────────────
@design_systems_bp.get("/design-systems")
@login_required
async def list_design_systems():
"""The caller's design systems. An empty list is the ordinary state for an
install that has never made one, not an error."""
rows = await ds_svc.list_design_systems(get_current_user_id())
return jsonify({"design_systems": [s.to_dict() for s in rows]})
@design_systems_bp.post("/design-systems")
@login_required
async def create_design_system():
data = await request.get_json() or {}
title = (data.get("title") or "").strip()
if not title:
return jsonify({"error": "title is required"}), 400
system = await ds_svc.create_design_system(
user_id=get_current_user_id(),
title=title,
description=data.get("description") or None,
guidance=data.get("guidance") or None,
parent_id=data.get("parent_id"),
starter_role_groups=data.get("starter_role_groups"),
token_prefix=data.get("token_prefix") or DEFAULT_TOKEN_PREFIX,
)
if system is None:
return jsonify({"error": "parent design system not found"}), 404
return jsonify(system.to_dict()), 201
@design_systems_bp.get("/design-systems/starter-roles")
@login_required
async def list_starter_role_groups():
"""The starter role catalogue, for the creation form's checklist.
Roles and purposes only — no values, ever. See services/design_starter_roles.
"""
return jsonify({
"groups": describe_groups(),
"default_prefix": DEFAULT_TOKEN_PREFIX,
})
@design_systems_bp.get("/design-systems/<int:design_system_id>")
@login_required
async def get_design_system(design_system_id: int):
system = await ds_svc.get_design_system(get_current_user_id(), design_system_id)
if system is None:
return not_found("Design system")
return jsonify(system.to_dict())
@design_systems_bp.patch("/design-systems/<int:design_system_id>")
@login_required
async def update_design_system(design_system_id: int):
data = await request.get_json() or {}
fields = {
k: v for k, v in data.items() if k in ("title", "description", "guidance")
}
# Presence, not truthiness: `{"parent_id": null}` means "make this a root",
# which a `if data.get("parent_id")` filter would silently drop.
if "parent_id" in data:
fields["parent_id"] = data["parent_id"]
try:
system = await ds_svc.update_design_system(get_current_user_id(), design_system_id, **fields)
except DesignSystemCycle as exc:
return jsonify({"error": str(exc)}), 400
if system is None:
return not_found("Design system")
return jsonify(system.to_dict())
@design_systems_bp.delete("/design-systems/<int:design_system_id>")
@login_required
async def delete_design_system(design_system_id: int):
if not await ds_svc.delete_design_system(get_current_user_id(), design_system_id):
return not_found("Design system")
return "", 204
@design_systems_bp.get("/design-systems/<int:design_system_id>/resolved")
@login_required
async def resolve_design_system(design_system_id: int):
"""The EFFECTIVE token set — everything inherited, with this system's on top.
Distinct from `/tokens` on purpose: that returns what this system CHANGES,
this returns what it ends up being. Both are real questions and answering
only one would make the other a client-side computation.
"""
resolved = await ds_svc.resolve_design_system(get_current_user_id(), design_system_id)
if resolved is None:
return not_found("Design system")
return jsonify({
"design_system_id": design_system_id,
"tokens": [t.to_dict() for t in resolved],
})
@design_systems_bp.get("/design-systems/<int:design_system_id>/stylesheet")
@login_required
async def get_design_system_stylesheet(design_system_id: int):
"""The master CSS sheet this design system generates.
JSON by default (the UI wants the reuse report alongside the CSS); add
`?format=css` for the raw stylesheet as `text/css`, which is what a build
step or a `curl` wants.
`?root=` overrides the base selector — a container-scoped preview cannot use
`:root`, so the generator takes it as a parameter.
"""
root = (request.args.get("root") or ":root").strip() or ":root"
result = await ds_svc.stylesheet_for_system(get_current_user_id(), design_system_id, root)
if result is None:
return not_found("Design system")
if request.args.get("format") == "css":
return result["css"], 200, {"Content-Type": "text/css; charset=utf-8"}
return jsonify(result)
@design_systems_bp.get("/design-systems/<int:design_system_id>/snippet-check")
@login_required
async def check_snippets_against_system(design_system_id: int):
"""Which recorded snippets disagree with this system's sheet.
`?project_id=` narrows to one project; omit it to check every project, which
is usually right — a component recorded elsewhere still has to use the same
tags.
"""
project_id = request.args.get("project_id", type=int) or 0
result = await ds_svc.check_snippets_against_system(
get_current_user_id(), design_system_id, project_id
)
if result is None:
return not_found("Design system")
return jsonify(result)
# ── Tokens ──────────────────────────────────────────────────────────────
@design_systems_bp.get("/design-systems/<int:design_system_id>/tokens")
@login_required
async def list_design_tokens(design_system_id: int):
"""This system's OWN tokens — its override set, not its effective set."""
if await ds_svc.get_design_system(get_current_user_id(), design_system_id) is None:
return not_found("Design system")
rows = await ds_svc.list_tokens(get_current_user_id(), design_system_id)
return jsonify({"tokens": [t.to_dict() for t in rows]})
@design_systems_bp.post("/design-systems/<int:design_system_id>/tokens")
@login_required
async def create_design_token(design_system_id: int):
data = await request.get_json() or {}
name = (data.get("name") or "").strip()
if not name:
return jsonify({"error": "name is required"}), 400
token = await ds_svc.create_token(
user_id=get_current_user_id(),
design_system_id=design_system_id,
name=name,
value_by_mode=data.get("value_by_mode"),
group_name=data.get("group_name") or None,
purpose=data.get("purpose") or None,
rationale=data.get("rationale") or None,
supersedes=data.get("supersedes"),
order_index=data.get("order_index") or 0,
)
if token is None:
return not_found("Design system")
return jsonify(token.to_dict()), 201
@design_systems_bp.patch("/design-tokens/<int:token_id>")
@login_required
async def update_design_token(token_id: int):
data = await request.get_json() or {}
fields = {
k: v for k, v in data.items()
if k in (
"name", "value_by_mode", "group_name", "purpose", "rationale",
"supersedes", "order_index",
)
}
token = await ds_svc.update_token(get_current_user_id(), token_id, **fields)
if token is None:
return not_found("Design token")
return jsonify(token.to_dict())
@design_systems_bp.delete("/design-tokens/<int:token_id>")
@login_required
async def delete_design_token(token_id: int):
if not await ds_svc.delete_token(get_current_user_id(), token_id):
return not_found("Design token")
return "", 204
# ── The project pointer ─────────────────────────────────────────────────
@design_systems_bp.put("/projects/<int:project_id>/design-system")
@login_required
async def set_project_design_system(project_id: int):
"""Point a project at a design system. `{"design_system_id": null}` clears it.
PUT rather than PATCH: this sets one field to exactly what is sent, and
clearing it is a first-class outcome rather than an omission.
"""
data = await request.get_json() or {}
ok = await ds_svc.set_project_design_system(
get_current_user_id(), project_id, data.get("design_system_id")
)
if not ok:
return not_found("Project or design system")
return jsonify({"project_id": project_id,
"design_system_id": data.get("design_system_id")})
+117
View File
@@ -0,0 +1,117 @@
import io
import json
import re
import zipfile
from datetime import datetime, timezone
from quart import Blueprint, Response, request
from grimoire.auth import login_required, get_current_user_id
from grimoire.models import async_session
from grimoire.models.note import Note
from sqlalchemy import select
export_bp = Blueprint("export", __name__)
def _safe_filename(title: str) -> str:
name = re.sub(r"[^\w\s-]", "", title or "untitled").strip()
name = re.sub(r"[\s]+", "_", name) or "untitled"
return name[:80]
def _note_frontmatter(note: Note) -> str:
lines = ["---"]
lines.append(f"title: {json.dumps(note.title or '')}")
lines.append(f"type: {'task' if note.is_task else 'note'}")
if note.tags:
lines.append(f"tags: [{', '.join(note.tags)}]")
if note.is_task:
lines.append(f"status: {note.status or 'todo'}")
lines.append(f"priority: {note.priority or 'none'}")
if note.due_date:
lines.append(f"due_date: {note.due_date}")
if note.project_id:
lines.append(f"project_id: {note.project_id}")
lines.append(f"created_at: {note.created_at.isoformat() if note.created_at else ''}")
lines.append(f"updated_at: {note.updated_at.isoformat() if note.updated_at else ''}")
lines.append("---")
return "\n".join(lines) + "\n\n"
async def _fetch_notes(uid: int):
async with async_session() as db:
result = await db.execute(
select(Note)
.where(Note.user_id == uid)
.order_by(Note.updated_at.desc())
)
return result.scalars().all()
@export_bp.get("/api/export")
@login_required
async def export_data():
uid = get_current_user_id()
fmt = request.args.get("format", "markdown")
notes = await _fetch_notes(uid)
if fmt == "json":
payload = [
{
"id": n.id,
"title": n.title,
"body": n.body,
"is_task": n.is_task,
"status": n.status,
"priority": n.priority,
"tags": n.tags or [],
"due_date": str(n.due_date) if n.due_date else None,
"project_id": n.project_id,
"milestone_id": n.milestone_id,
"parent_id": n.parent_id,
"created_at": n.created_at.isoformat() if n.created_at else None,
"updated_at": n.updated_at.isoformat() if n.updated_at else None,
}
for n in notes
]
data = json.dumps(payload, indent=2, ensure_ascii=False).encode("utf-8")
stamp = datetime.now(timezone.utc).strftime("%Y%m%d")
return Response(
data,
status=200,
headers={
"Content-Type": "application/json; charset=utf-8",
"Content-Disposition": f'attachment; filename="grimoire-{stamp}.json"',
},
)
# Markdown ZIP
buf = io.BytesIO()
used_names: dict[str, int] = {}
with zipfile.ZipFile(buf, mode="w", compression=zipfile.ZIP_DEFLATED) as zf:
index_rows = []
for note in notes:
base = _safe_filename(note.title)
count = used_names.get(base, 0)
used_names[base] = count + 1
fname = f"{base}_{count}.md" if count else f"{base}.md"
content = _note_frontmatter(note) + (note.body or "")
zf.writestr(fname, content.encode("utf-8"))
index_rows.append({"file": fname, "title": note.title, "id": note.id})
zf.writestr("index.json", json.dumps(index_rows, indent=2, ensure_ascii=False))
buf.seek(0)
stamp = datetime.now(timezone.utc).strftime("%Y%m%d")
return Response(
buf.read(),
status=200,
headers={
"Content-Type": "application/zip",
"Content-Disposition": f'attachment; filename="grimoire-{stamp}.zip"',
},
)
+146
View File
@@ -0,0 +1,146 @@
"""Family canon routes — the web door to the promotion engine.
The agent decides promotions and each project's answers through the MCP
tools; this door exists so a person can READ every decision and its reasons
— the ideas, the adoption matrix, the log — and retire an idea or undo a
decision when they disagree. The promote and propose endpoints are here for
parity with the agent's door, and are recorded as the operator's.
Every write is gated on the idea's note in the service.
"""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.routes.utils import not_found
from grimoire.services import family as family_svc
from grimoire.services import family_adoption as adoption_svc
logger = logging.getLogger(__name__)
family_bp = Blueprint("family", __name__, url_prefix="/api/family")
def _page() -> tuple[int, int]:
try:
limit = max(1, min(int(request.args.get("limit", 50)), 200))
offset = max(0, int(request.args.get("offset", 0)))
except ValueError:
limit, offset = 50, 0
return limit, offset
@family_bp.route("/ideas", methods=["GET"])
@login_required
async def list_ideas_route():
limit, offset = _page()
ideas = await family_svc.list_ideas(
get_current_user_id(),
status=request.args.get("status") or None,
platform=request.args.get("platform") or None,
limit=limit, offset=offset,
)
return jsonify({
"ideas": ideas, "criteria": list(family_svc.CRITERIA),
"conflict_order": list(adoption_svc.CONFLICT_ORDER),
})
@family_bp.route("/ideas/<int:note_id>", methods=["GET"])
@login_required
async def get_idea_route(note_id: int):
uid = get_current_user_id()
idea = await family_svc.get_idea(uid, note_id)
if idea is None:
return not_found("Family idea")
idea["precedents"] = await family_svc.precedents(uid, note_id)
return jsonify(idea)
@family_bp.route("/ideas/<int:note_id>/propose", methods=["POST"])
@login_required
async def propose_route(note_id: int):
data = await request.get_json() or {}
try:
idea, created = await family_svc.propose(
get_current_user_id(), note_id, reason=data.get("reason") or "",
applies_when=data.get("applies_when") or None, decided_via="operator",
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
return jsonify({"idea": idea, "created": created}), (201 if created else 200)
@family_bp.route("/ideas/<int:note_id>/promote", methods=["POST"])
@login_required
async def promote_route(note_id: int):
data = await request.get_json() or {}
try:
result = await family_svc.promote(
get_current_user_id(), note_id,
applies_when=data.get("applies_when") or "",
platforms=data.get("platforms") or [],
criteria=data.get("criteria") or {},
evidence=data.get("evidence") or [],
reason=data.get("reason") or "",
precedent_ids=data.get("precedent_ids") or [],
decided_via="operator",
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
return jsonify(result)
@family_bp.route("/ideas/<int:note_id>/retire", methods=["POST"])
@login_required
async def retire_route(note_id: int):
data = await request.get_json() or {}
try:
result = await family_svc.retire(
get_current_user_id(), note_id, reason=data.get("reason") or "",
decided_via="operator",
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
return jsonify(result)
@family_bp.route("/matrix", methods=["GET"])
@login_required
async def matrix_route():
"""Projects × canon ideas — the adoption matrix. Read-only: the agent
answers through assess_family_adoption; a person reads the answers here
and undoes one from the decision log if they disagree."""
matrix = await adoption_svc.adoption_matrix(
get_current_user_id(),
platform=request.args.get("platform") or None,
project_id=request.args.get("project_id", type=int) or None,
)
return jsonify(matrix)
@family_bp.route("/decisions", methods=["GET"])
@login_required
async def list_decisions_route():
limit, offset = _page()
idea_id = request.args.get("idea_id", type=int)
project_id = request.args.get("project_id", type=int)
rows = await family_svc.list_decisions(
get_current_user_id(), idea_id=idea_id or None, project_id=project_id or None,
limit=limit, offset=offset,
)
return jsonify({"decisions": rows, "limit": limit, "offset": offset})
@family_bp.route("/decisions/<int:decision_id>/undo", methods=["POST"])
@login_required
async def undo_route(decision_id: int):
data = await request.get_json() or {}
try:
result = await family_svc.undo(
get_current_user_id(), decision_id, reason=data.get("reason") or "",
decided_via="operator",
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
return jsonify(result)
+112
View File
@@ -0,0 +1,112 @@
import asyncio
from quart import Blueprint, g, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.services import groups as group_svc
from grimoire.services.notifications import notify_group_added
groups_bp = Blueprint("groups", __name__, url_prefix="/api/groups")
@groups_bp.route("", methods=["GET"])
@login_required
async def list_groups():
uid = get_current_user_id()
return jsonify({"groups": await group_svc.list_groups(uid)})
@groups_bp.route("", methods=["POST"])
@login_required
async def create_group():
uid = get_current_user_id()
data = await request.get_json()
name = (data.get("name") or "").strip()
if not name:
return jsonify({"error": "Name is required"}), 400
try:
group = await group_svc.create_group(uid, name, data.get("description"))
except Exception:
return jsonify({"error": "Group name already taken"}), 409
return jsonify(group.to_dict()), 201
@groups_bp.route("/<int:group_id>", methods=["GET"])
@login_required
async def get_group(group_id: int):
group = await group_svc.get_group(group_id)
if not group:
return jsonify({"error": "Not found"}), 404
members = await group_svc.list_members(group_id)
return jsonify({**group.to_dict(), "members": members})
@groups_bp.route("/<int:group_id>", methods=["PATCH"])
@login_required
async def update_group(group_id: int):
uid = get_current_user_id()
data = await request.get_json()
updates = {k: v for k, v in data.items() if k in ("name", "description")}
group = await group_svc.update_group(uid, group_id, g.user.role == "admin", **updates)
if not group:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify(group.to_dict())
@groups_bp.route("/<int:group_id>", methods=["DELETE"])
@login_required
async def delete_group(group_id: int):
uid = get_current_user_id()
deleted = await group_svc.delete_group(uid, group_id, g.user.role == "admin")
if not deleted:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify({"status": "ok"})
@groups_bp.route("/<int:group_id>/members", methods=["GET"])
@login_required
async def list_members(group_id: int):
members = await group_svc.list_members(group_id)
return jsonify({"members": members})
@groups_bp.route("/<int:group_id>/members", methods=["POST"])
@login_required
async def add_member(group_id: int):
uid = get_current_user_id()
data = await request.get_json()
target_uid = data.get("user_id")
role = data.get("role", "member")
if not target_uid:
return jsonify({"error": "user_id required"}), 400
if role not in ("owner", "member"):
return jsonify({"error": "role must be owner or member"}), 400
membership = await group_svc.add_member(uid, group_id, target_uid, role, g.user.role == "admin")
if not membership:
return jsonify({"error": "Forbidden, group not found, or user already a member"}), 403
asyncio.create_task(notify_group_added(group_id, role, uid, target_uid))
return jsonify(membership.to_dict()), 201
@groups_bp.route("/<int:group_id>/members/<int:target_uid>", methods=["PATCH"])
@login_required
async def update_member(group_id: int, target_uid: int):
uid = get_current_user_id()
data = await request.get_json()
role = data.get("role")
if role not in ("owner", "member"):
return jsonify({"error": "role must be owner or member"}), 400
m = await group_svc.update_member_role(uid, group_id, target_uid, role, g.user.role == "admin")
if not m:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify(m.to_dict())
@groups_bp.route("/<int:group_id>/members/<int:target_uid>", methods=["DELETE"])
@login_required
async def remove_member(group_id: int, target_uid: int):
uid = get_current_user_id()
removed = await group_svc.remove_member(uid, group_id, target_uid, g.user.role == "admin")
if not removed:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify({"status": "ok"})
@@ -0,0 +1,44 @@
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.services.notifications import (
list_in_app_notifications,
mark_all_notifications_read,
mark_notification_read,
unread_notification_count,
)
notifications_bp = Blueprint("notifications", __name__, url_prefix="/api/notifications")
@notifications_bp.route("", methods=["GET"])
@login_required
async def list_notifications():
uid = get_current_user_id()
all_flag = request.args.get("all", "false").lower() == "true"
items = await list_in_app_notifications(uid, unread_only=not all_flag)
return jsonify({"notifications": items})
@notifications_bp.route("/count", methods=["GET"])
@login_required
async def get_count():
uid = get_current_user_id()
return jsonify({"count": await unread_notification_count(uid)})
@notifications_bp.route("/<int:notif_id>/read", methods=["POST"])
@login_required
async def mark_read(notif_id: int):
uid = get_current_user_id()
if not await mark_notification_read(uid, notif_id):
return jsonify({"error": "Not found"}), 404
return jsonify({"status": "ok"})
@notifications_bp.route("/read-all", methods=["POST"])
@login_required
async def mark_all_read():
uid = get_current_user_id()
count = await mark_all_notifications_read(uid)
return jsonify({"status": "ok", "marked": count})
+167
View File
@@ -0,0 +1,167 @@
"""Unified Knowledge endpoint — every record kind in one queryable feed."""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.routes.utils import parse_pagination
from grimoire.services.access import label_shared_items
from grimoire.services.knowledge import FACET_TYPES
from grimoire.services.note_usage import attach_usage
logger = logging.getLogger(__name__)
knowledge_bp = Blueprint("knowledge", __name__, url_prefix="/api/knowledge")
# Derived from the service's facet table, never re-listed here. This set was a
# hand-kept copy drifts behind it — admitting retired kinds and rejecting new
# ones — until the browse surface cannot filter to the kinds it renders
# badges for.
_VALID_TYPES = FACET_TYPES
_VALID_SORTS = {"modified", "created", "alpha", "type"}
@knowledge_bp.route("", methods=["GET"])
@login_required
async def list_knowledge():
"""Return paginated knowledge objects with optional filtering.
Query params:
type — a facet from services.knowledge._FACETS: a record type
(note|process|snippet) or a task kind (task for any,
else work|issue|spike|plan). Omit for all.
tags — comma-separated tag filter (AND logic)
sort — modified|created|alpha|type (default: modified)
q — search query (semantic when provided, keyword fallback)
page — 1-based page number (default 1)
per_page — items per page (default 24, max 100)
"""
uid = get_current_user_id()
note_type = request.args.get("type", "").strip().lower() or None
tags_raw = request.args.get("tags", "").strip()
tags = [t.strip() for t in tags_raw.split(",") if t.strip()] if tags_raw else []
sort = request.args.get("sort", "modified").strip().lower()
q = request.args.get("q", "").strip() or None
if note_type and note_type not in _VALID_TYPES:
return jsonify({"error": f"Invalid type. Must be one of: {', '.join(sorted(_VALID_TYPES))}"}), 400
if sort not in _VALID_SORTS:
sort = "modified"
limit, offset = parse_pagination(default_limit=24, max_limit=100)
page = max(1, int(request.args.get("page", 1)))
from grimoire.services.knowledge import query_knowledge
items, total = await query_knowledge(
user_id=uid,
note_type=note_type,
tags=tags,
sort=sort,
q=q,
limit=limit,
offset=offset,
)
items = await label_shared_items(uid, items)
# The surfaced-vs-opened counts, on the list a person actually browses.
# This is the ONLY lesson and note list in the UI — `/knowledge` is how
# notes, lessons and processes are all browsed — so attaching here is what
# shows those kinds' counters at all.
#
# Mixed kinds is not a problem for this: usage keys on the note row, which
# every facet of this feed is.
await attach_usage(items)
return jsonify({
# Mark rows another user owns: this feed can be mixed-ownership, and an
# unmarked card reads as one the viewer wrote.
"items": items,
"total": total,
"page": page,
"per_page": limit,
"pages": max(1, (total + limit - 1) // limit),
})
@knowledge_bp.route("/ids", methods=["GET"])
@login_required
async def list_knowledge_ids():
"""Return note IDs only (cheap) for the two-tier pagination feed.
Same filter params as GET /api/knowledge.
Additional params: limit (default 100, max 200), offset (default 0).
Returns {ids, total, has_more}.
"""
uid = get_current_user_id()
note_type = request.args.get("type", "").strip().lower() or None
tags_raw = request.args.get("tags", "").strip()
tags = [t.strip() for t in tags_raw.split(",") if t.strip()] if tags_raw else []
sort = request.args.get("sort", "modified").strip().lower()
q = request.args.get("q", "").strip() or None
if sort not in _VALID_SORTS:
sort = "modified"
try:
limit = min(int(request.args.get("limit", 100)), 200)
offset = max(0, int(request.args.get("offset", 0)))
except ValueError:
return jsonify({"error": "Invalid limit or offset"}), 400
if note_type and note_type not in _VALID_TYPES:
return jsonify({"error": "Invalid type"}), 400
from grimoire.services.knowledge import query_knowledge_ids
ids, total = await query_knowledge_ids(
user_id=uid, note_type=note_type, tags=tags,
sort=sort, q=q, limit=limit, offset=offset,
)
return jsonify({"ids": ids, "total": total, "has_more": (offset + len(ids)) < total})
@knowledge_bp.route("/batch", methods=["GET"])
@login_required
async def get_knowledge_batch():
"""Fetch full items for a comma-separated list of IDs (max 100).
Returns {items: [...]} in the order of the requested IDs.
"""
uid = get_current_user_id()
ids_raw = request.args.get("ids", "").strip()
if not ids_raw:
return jsonify({"items": []})
try:
ids = [int(x) for x in ids_raw.split(",") if x.strip()]
except ValueError:
return jsonify({"error": "Invalid IDs"}), 400
if len(ids) > 100:
return jsonify({"error": "Too many IDs (max 100)"}), 400
from grimoire.services.knowledge import get_knowledge_by_ids
items = await get_knowledge_by_ids(uid, ids)
# The scrolling feed hydrates its cards here, not from the list route, so the
# ownership markers have to be applied on this path too.
return jsonify({"items": await label_shared_items(uid, items)})
@knowledge_bp.route("/tags", methods=["GET"])
@login_required
async def list_knowledge_tags():
"""Return all tags used across knowledge objects, narrowed to one facet."""
uid = get_current_user_id()
note_type = request.args.get("type", "").strip().lower() or None
from grimoire.services.knowledge import get_knowledge_tags
tags = await get_knowledge_tags(uid, note_type=note_type)
return jsonify({"tags": tags})
@knowledge_bp.route("/counts", methods=["GET"])
@login_required
async def get_knowledge_counts():
"""Return per-type counts — used by the sidebar to show item counts."""
uid = get_current_user_id()
tags_raw = request.args.get("tags", "").strip()
tags = [t.strip() for t in tags_raw.split(",") if t.strip()] if tags_raw else None
from grimoire.services.knowledge import get_knowledge_counts as _counts
counts = await _counts(uid, tags=tags)
return jsonify(counts)
+374
View File
@@ -0,0 +1,374 @@
"""REST routes for lessons — a transferable insight, retrievable by situation.
A lesson is a note with note_type='lesson' (see services/lessons.py). These
routes feed the web UI; the MCP tools (mcp/tools/lessons.py) are the
agent-facing surface. Both go through services/lessons.py, so the compose/parse
contract and the `data` mirror live in one place — the same division snippets
use, and for the same reason: two doors that each compose a lesson would
compose it two ways, and the document IS what ranks.
ACL: reads and writes of a single lesson resolve through the
share-aware `get_lesson` / `can_write_note`, and writes are performed as the
OWNER so a shared editor isn't rejected by the owner-scoped service —
mirroring routes/snippets.py and routes/notes.py.
WHY THE TRIGGER IS A NAMED FIELD HERE TOO. The web editor could have posted a
body and let the service parse it. It doesn't, because a trigger gets filled
when a door ASKS for it by name — a field the service composes from a named
parameter is filled every time, with no guard anywhere, and a single markdown
box is not.
"""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.routes.utils import not_found, parse_pagination
from grimoire.services import dedup as dedup_svc
from grimoire.services import knowledge as knowledge_svc
from grimoire.services import lesson_rules as lesson_rules_svc
from grimoire.services import lessons as lessons_svc
from grimoire.services import systems as systems_svc
from grimoire.services import trash as trash_svc
from grimoire.services.access import (
can_write_note,
describe_provenance,
label_shared_items,
)
from grimoire.services.note_usage import attach_usage, record_pulled
logger = logging.getLogger(__name__)
lessons_bp = Blueprint("lessons", __name__, url_prefix="/api/lessons")
@lessons_bp.route("", methods=["GET"])
@login_required
async def list_lessons_route():
"""The kind enumerated, rather than only what a query resembles.
Semantic search is how a lesson REACHES a session; this is how a person
sees what exists at all. Each row carries its trigger, because a list of
lessons without them is a list of claims with the half that says when each
one matters left off.
"""
uid = get_current_user_id()
q = request.args.get("q") or None
tag = request.args.get("tag", "")
try:
project_id = int(request.args.get("project_id", 0) or 0) or None
except (TypeError, ValueError):
project_id = None
limit, offset = parse_pagination(default_limit=24, max_limit=100)
# The lessons nobody has answered "which rule?" for. A listing,
# so it does not combine with a search — the MCP door says the same.
if request.args.get("unjudged") in ("1", "true"):
if q:
return jsonify({"error": "unjudged is a listing; drop q"}), 400
items, total = await lesson_rules_svc.list_unjudged(
uid, tag=tag, project_id=project_id, limit=limit, offset=offset,
)
else:
items, total = await knowledge_svc.query_knowledge(
user_id=uid,
note_type=lessons_svc.LESSON_NOTE_TYPE,
tags=[tag] if tag else [],
sort="modified",
q=q,
limit=limit,
offset=offset,
project_id=project_id,
)
items = await label_shared_items(uid, items)
# One aggregate for the whole page — a per-row lookup would be N+1 by
# construction. Every row gets the key, zero-filled, so the UI renders
# "never surfaced" rather than treating a missing field as a state.
#
# The counts matter more here than on a snippet: the promotion question a
# lesson eventually raises — does this bind? — is answered by repeatedly
# surfaced AND repeatedly opened, and the far commoner reading of the same
# row is that the trigger fires on the wrong situation, which `update_lesson`
# exists to fix.
await attach_usage(items)
return jsonify({"lessons": items, "total": total})
@lessons_bp.route("/taught-by/<int:record_id>", methods=["GET"])
@login_required
async def lessons_taught_by_route(record_id: int):
"""The lessons drawn FROM one record — the reverse of `learned_from`.
Registered ABOVE the `/<int:lesson_id>` routes on purpose: Quart matches
in registration order, and `taught-by` would otherwise never be reached
if the converter ever widened. The same ordering snippets' `/duplicates`
route documents.
This is the direction that gets forgotten. A reader opening an old issue
wants to know what was learned from it, and without this the relation is
only navigable from the lesson's side.
"""
uid = get_current_user_id()
notes = await lessons_svc.lessons_taught_by(uid, record_id)
return jsonify({
"lessons": [lessons_svc.lesson_to_dict(n) for n in notes],
"taught_by": record_id,
})
@lessons_bp.route("/rule-candidates", methods=["GET"])
@login_required
async def lesson_rule_candidates_route():
"""The rules a lesson being written resembles, BEFORE it is saved.
The create door offers the same list in its reply when neither answer was
given. A form needs it earlier, so the writer can name the rule in the
same save while the situation is still in mind. Query: `what`,
`when_to_apply`, optional `project_id`. Above the `/<int:lesson_id>`
routes for the reason `taught-by` is.
`candidates` is null when the search could not run. That means
"unavailable", which is different from "nothing resembles it" (an empty
list).
"""
uid = get_current_user_id()
what = (request.args.get("what") or "").strip()
when_to_apply = (request.args.get("when_to_apply") or "").strip()
if not what and not when_to_apply:
return jsonify({"error": "what or when_to_apply is required"}), 400
project_id = request.args.get("project_id", type=int) or None
candidates = await lesson_rules_svc.rule_candidates(
uid, what, when_to_apply, project_id,
)
return jsonify({"candidates": candidates})
@lessons_bp.route("", methods=["POST"])
@login_required
async def create_lesson_route():
uid = get_current_user_id()
data = await request.get_json() or {}
what = (data.get("what") or "").strip()
when_to_apply = (data.get("when_to_apply") or "").strip()
if not what:
return jsonify({"error": "what is required"}), 400
try:
lessons_svc.require_claim(what)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
# The trigger is not optional at this door even though the service will
# store a lesson without one. A lesson with no trigger saves, reads
# correctly in every listing, and never surfaces — there is nothing to
# notice afterwards, which is exactly why the form has to refuse it here
# rather than leave the writer a record that looks finished.
if not when_to_apply:
return jsonify({
"error": "when_to_apply is required",
"detail": (
"A lesson is found by the SITUATION it applies to. Without a "
"trigger it still saves and still reads correctly, and it "
"never reaches anyone — so it is refused here rather than "
"stored as a record that looks finished."
),
}), 400
project_id = data.get("project_id") or None
learned_from = data.get("learned_from") or []
# The rules this lesson is an instance of. Validated before
# anything is written, as the MCP door does, so a bad id saves nothing.
no_rule = (data.get("no_rule") or "").strip()
try:
linked = await lesson_rules_svc.require_rules(uid, data.get("rule_ids") or [])
lesson_rules_svc.require_one_answer(linked, no_rule)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
# The same near-duplicate gate the MCP create path applies. Two lessons
# under one trigger compete in a single ranked list for one reserved slot,
# so the duplicate does not merely clutter — it displaces.
if not data.get("force"):
title, body = lessons_svc.lesson_document(
what, when_to_apply, data.get("insight", ""), learned_from,
)
dup = await dedup_svc.find_duplicate_note(
uid, title, body,
project_id=project_id,
is_task=False,
note_type=lessons_svc.LESSON_NOTE_TYPE,
data=lessons_svc.compose_data(what, when_to_apply),
)
if dup is not None:
return jsonify(dedup_svc.duplicate_response(dup, "lesson")), 409
note = await lessons_svc.create_lesson(
uid,
what=what,
when_to_apply=when_to_apply,
insight=data.get("insight", ""),
learned_from=learned_from,
tags=data.get("tags"),
project_id=project_id,
)
if data.get("system_ids") is not None:
await systems_svc.set_record_systems(uid, note.id, data["system_ids"])
if linked:
await lesson_rules_svc.set_lesson_rules(uid, note.id, linked)
elif no_rule:
await lesson_rules_svc.set_no_rule(uid, note.id, no_rule)
out = lessons_svc.lesson_to_dict(note)
if no_rule:
group = await lesson_rules_svc.convergence_for(uid, note.id)
if group:
out["convergence"] = group
out["systems"] = [
s.to_dict() for s in await systems_svc.list_record_systems(uid, note.id)
]
await lesson_rules_svc.attach_lesson_rules(uid, [out])
# The same offer the MCP door makes, so the form can show the rules to
# judge against while the writer still has the situation in mind.
if not linked and not no_rule:
candidates = await lesson_rules_svc.rule_candidates(
uid, what, when_to_apply, project_id,
)
if candidates is not None:
out["rule_candidates"] = candidates
return jsonify(out), 201
@lessons_bp.route("/<int:lesson_id>", methods=["GET"])
@login_required
async def get_lesson_route(lesson_id: int):
uid = get_current_user_id()
note = await lessons_svc.get_lesson(uid, lesson_id)
if note is None:
return not_found("Lesson")
out = lessons_svc.lesson_to_dict(note)
# As the OWNER: a shared reader isn't scoped to the owner's project, so
# their own id would come back empty (the write-as-owner pattern this
# module already uses, read side).
out["systems"] = [
s.to_dict()
for s in await systems_svc.list_record_systems(note.user_id, lesson_id)
]
# Resolved, not bare ids: "#4181" on a page tells a reader nothing about
# whether it is worth opening, and the provenance is the point of a lesson.
out["learned_from_records"] = await lessons_svc.source_records(
uid, out["learned_from"]
)
out.update(await describe_provenance(uid, note))
await attach_usage([out])
await lesson_rules_svc.attach_lesson_rules(uid, [out])
# Opening the detail view IS a pull — the operator chose to look. Tagged
# apart from the MCP sources so "an agent was handed it" and "a human read
# it" stay distinguishable; they mean different things for pruning.
record_pulled(user_id=uid, note_id=lesson_id, source="rest_lesson")
return jsonify(out)
@lessons_bp.route("/<int:lesson_id>", methods=["PATCH"])
@login_required
async def update_lesson_route(lesson_id: int):
uid = get_current_user_id()
note = await lessons_svc.get_lesson(uid, lesson_id)
if note is None:
return not_found("Lesson")
if not await can_write_note(uid, lesson_id):
return jsonify({"error": "Permission denied"}), 403
owner_uid = note.user_id
data = await request.get_json() or {}
# Partial update: only keys present in the payload change, and the service
# re-composes title, body and mirror from the merged set — so a form that
# sends one field cannot leave the halves of the document disagreeing.
kwargs = {
k: data[k]
for k in ("what", "when_to_apply", "insight", "learned_from", "tags")
if k in data
}
# An empty trigger would save and silently stop the lesson surfacing, so
# clearing it is refused for the same reason creating without one is.
if "when_to_apply" in kwargs and not (kwargs["when_to_apply"] or "").strip():
return jsonify({
"error": "when_to_apply cannot be cleared",
"detail": (
"A lesson with no trigger never surfaces, and nothing about "
"the stored record would show it. Rewrite the trigger rather "
"than emptying it."
),
}), 400
linked = None
no_rule = (data.get("no_rule") or "").strip()
try:
if kwargs.get("what"):
lessons_svc.require_claim(kwargs["what"])
if data.get("rule_ids") is not None:
linked = await lesson_rules_svc.require_rules(uid, data["rule_ids"])
lesson_rules_svc.require_one_answer(linked, no_rule)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
updated = await lessons_svc.update_lesson(owner_uid, lesson_id, **kwargs)
if updated is None:
return not_found("Lesson")
if linked is not None:
# The CALLER, for the reason system_ids below uses it: the rules named
# must be ones the person making the edit can read.
await lesson_rules_svc.set_lesson_rules(uid, lesson_id, linked)
if no_rule:
await lesson_rules_svc.set_no_rule(uid, lesson_id, no_rule)
if data.get("system_ids") is not None:
# The CALLER, not owner_uid. `set_record_systems` runs its own
# `can_write_note` and links only Systems the acting user can read;
# handing it the owner makes that check trivially pass and filters by
# the owner's visibility instead. The caller's write permission is
# already established above, so this neither loosens nor tightens who
# may edit — it decides WHOSE reach the tagging uses (#47).
await systems_svc.set_record_systems(uid, lesson_id, data["system_ids"])
out = lessons_svc.lesson_to_dict(updated)
if no_rule:
# The same nudge the MCP door gives: this answer may complete
# a group of no-rule lessons in one situation.
group = await lesson_rules_svc.convergence_for(uid, lesson_id)
if group:
out["convergence"] = group
out["systems"] = [
s.to_dict()
for s in await systems_svc.list_record_systems(owner_uid, lesson_id)
]
await lesson_rules_svc.attach_lesson_rules(uid, [out])
return jsonify(out)
@lessons_bp.route("/<int:lesson_id>/rules/<int:rule_id>", methods=["PUT"])
@login_required
async def judge_lesson_link_route(lesson_id: int, rule_id: int):
"""Confirm or reject one lesson→rule link — the REST twin of the MCP
`judge_lesson_link`. Body: {"verdict": "confirm" | "reject", "note": "…"}."""
uid = get_current_user_id()
data = await request.get_json() or {}
try:
link = await lesson_rules_svc.judge_link(
uid, lesson_id, rule_id, data.get("verdict", ""), data.get("note", ""),
)
except PermissionError:
return jsonify({"error": "Permission denied"}), 403
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
return jsonify(link)
@lessons_bp.route("/<int:lesson_id>", methods=["DELETE"])
@login_required
async def delete_lesson_route(lesson_id: int):
"""Trash, not erase — recoverable from the trash like every other kind."""
uid = get_current_user_id()
note = await lessons_svc.get_lesson(uid, lesson_id)
if note is None:
return not_found("Lesson")
if not await can_write_note(uid, lesson_id):
return jsonify({"error": "Permission denied"}), 403
batch_id = await trash_svc.delete(note.user_id, "note", lesson_id)
if batch_id is None:
return not_found("Lesson")
return jsonify({"deleted": lesson_id, "deleted_batch_id": batch_id})
+143
View File
@@ -0,0 +1,143 @@
"""Milestone routes nested under /api/projects/<project_id>/milestones."""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import login_required, get_current_user_id
from grimoire.routes.utils import not_found, parse_pagination
from grimoire.services.access import can_write_project
from grimoire.services.milestones import (
create_milestone,
delete_milestone,
get_milestone_in_project,
get_milestone_progress,
list_milestones,
update_milestone,
)
from grimoire.services.notes import list_notes
from grimoire.services.projects import get_project_for_user
logger = logging.getLogger(__name__)
milestones_bp = Blueprint("milestones", __name__, url_prefix="/api/projects")
async def _milestone_dict(m) -> dict:
d = m.to_dict()
d.update(await get_milestone_progress(m.id))
return d
@milestones_bp.route("/<int:project_id>/milestones", methods=["GET"])
@login_required
async def list_milestones_route(project_id: int):
uid = get_current_user_id()
result = await get_project_for_user(uid, project_id)
if result is None:
return not_found("Project")
project, _ = result
# List milestones using the project owner's uid so ownership filter matches
owner_uid = project.user_id or uid
status = request.args.get("status")
milestones = await list_milestones(owner_uid, project_id, status=status)
return jsonify({"milestones": [await _milestone_dict(m) for m in milestones]})
@milestones_bp.route("/<int:project_id>/milestones", methods=["POST"])
@login_required
async def create_milestone_route(project_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
if not await can_write_project(uid, project_id):
return jsonify({"error": "Permission denied"}), 403
data = await request.get_json()
if not data.get("title"):
return jsonify({"error": "title is required"}), 400
status = data.get("status", "active")
if status not in ("active", "done"):
return jsonify({"error": "status must be 'active' or 'done'"}), 400
milestone = await create_milestone(
uid,
project_id,
title=data["title"],
description=data.get("description"),
body=data.get("body"),
order_index=data.get("order_index", 0),
status=status,
)
return jsonify(await _milestone_dict(milestone)), 201
@milestones_bp.route("/<int:project_id>/milestones/<int:milestone_id>", methods=["GET"])
@login_required
async def get_milestone_route(project_id: int, milestone_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
milestone = await get_milestone_in_project(project_id, milestone_id)
if milestone is None:
return not_found("Milestone")
return jsonify(await _milestone_dict(milestone))
@milestones_bp.route("/<int:project_id>/milestones/<int:milestone_id>", methods=["PATCH"])
@login_required
async def update_milestone_route(project_id: int, milestone_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
if not await can_write_project(uid, project_id):
return jsonify({"error": "Permission denied"}), 403
milestone = await get_milestone_in_project(project_id, milestone_id)
if milestone is None:
return not_found("Milestone")
data = await request.get_json()
allowed = {"title", "description", "body", "status", "order_index"}
fields = {k: v for k, v in data.items() if k in allowed}
if "status" in fields and fields["status"] not in ("active", "done"):
return jsonify({"error": "status must be 'active' or 'done'"}), 400
updated = await update_milestone(milestone.user_id, milestone_id, **fields)
if updated is None:
return not_found("Milestone")
return jsonify(await _milestone_dict(updated))
@milestones_bp.route("/<int:project_id>/milestones/<int:milestone_id>", methods=["DELETE"])
@login_required
async def delete_milestone_route(project_id: int, milestone_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
if not await can_write_project(uid, project_id):
return jsonify({"error": "Permission denied"}), 403
milestone = await get_milestone_in_project(project_id, milestone_id)
if milestone is None:
return not_found("Milestone")
from grimoire.services.trash import delete as trash_delete
batch = await trash_delete(milestone.user_id, "milestone", milestone_id)
if batch is None:
return not_found("Milestone")
return "", 204
@milestones_bp.route("/<int:project_id>/milestones/<int:milestone_id>/tasks", methods=["GET"])
@login_required
async def get_milestone_tasks_route(project_id: int, milestone_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
milestone = await get_milestone_in_project(project_id, milestone_id)
if milestone is None:
return not_found("Milestone")
status_filter = request.args.get("status")
limit, offset = parse_pagination(default_limit=100)
notes, total = await list_notes(
milestone.user_id,
is_task=True,
status=status_filter,
milestone_id=milestone_id,
limit=limit,
offset=offset,
)
return jsonify({"notes": [n.to_dict() for n in notes], "total": total})
+576
View File
@@ -0,0 +1,576 @@
import logging
import re
from quart import Blueprint, jsonify, request
from grimoire.auth import login_required, get_current_user_id
from grimoire.routes.utils import not_found, parse_iso_date, parse_pagination
from grimoire.services.access import can_write_note
from grimoire.services.notes import (
build_note_graph,
convert_note_to_task,
convert_task_to_note,
create_note,
get_all_tags,
get_backlinks,
get_note,
get_note_by_title,
get_note_for_user,
get_or_create_note_by_title,
list_notes,
mark_note_verified,
notes_due_for_verification,
update_note,
verification_row,
)
from grimoire.services.note_drafts import upsert_draft, get_draft, delete_draft
from grimoire.services import dedup as dedup_svc
from grimoire.services import supersession as supersession_svc
from grimoire.services import systems as systems_svc
from grimoire.services.note_usage import record_pulled
from grimoire.services.note_versions import list_versions, get_version
logger = logging.getLogger(__name__)
notes_bp = Blueprint("notes", __name__, url_prefix="/api/notes")
@notes_bp.route("", methods=["GET"])
@login_required
async def list_notes_route():
uid = get_current_user_id()
q = request.args.get("q")
tag = request.args.getlist("tag")
sort = request.args.get("sort", "updated_at")
order = request.args.get("order", "desc")
limit, offset = parse_pagination()
# Default to non-task notes only; ?is_task=true for tasks, ?all=true for everything
is_task: bool | None = False
if request.args.get("all", "").lower() == "true":
is_task = None
elif request.args.get("is_task", "").lower() == "true":
is_task = True
project_id = request.args.get("project_id", type=int)
milestone_id = request.args.get("milestone_id", type=int)
parent_id = request.args.get("parent_id", type=int)
no_project = request.args.get("no_project", "").lower() == "true"
# type= shorthand used by web frontend (?type=task or ?type=note)
type_param = request.args.get("type")
if type_param == "task":
is_task = True
elif type_param == "note":
is_task = False
status = request.args.getlist("status") or None
priority = request.args.getlist("priority") or None
notes, total = await list_notes(
uid, q=q, tags=tag or None, is_task=is_task, sort=sort, order=order,
limit=limit, offset=offset,
project_id=project_id, milestone_id=milestone_id, parent_id=parent_id,
no_project=no_project, status=status, priority=priority,
)
return jsonify({"notes": [n.to_dict() for n in notes], "total": total})
@notes_bp.route("", methods=["POST"])
@login_required
async def create_note_route():
uid = get_current_user_id()
data = await request.get_json()
body = data.get("body", "")
tags = data.get("tags", [])
# Optional task fields
status = data.get("status")
priority = data.get("priority")
due_date = parse_iso_date(data.get("due_date"), "due_date")
if isinstance(due_date, tuple):
return due_date
project_id = data.get("project_id")
if project_id is None and data.get("project"):
from grimoire.services.projects import get_project_by_title as _gpbt
proj = await _gpbt(uid, data["project"])
if proj:
project_id = proj.id
note_type = data.get("note_type", "note")
try:
note = await create_note(
uid,
title=data.get("title", ""),
body=body,
description=data.get("description"),
tags=tags,
parent_id=data.get("parent_id"),
project_id=project_id,
milestone_id=data.get("milestone_id"),
status=status,
priority=priority,
due_date=due_date,
note_type=note_type,
verify_with=data.get("verify_with"),
expires_when=data.get("expires_when"),
)
except ValueError as e:
return jsonify({"error": str(e)}), 400
# Same capability as the MCP create path (#33). Without it the web UI would
# be the surface on which a supersession claim silently cannot be made.
if data.get("supersedes"):
try:
await supersession_svc.set_supersedes(uid, note.id, data["supersedes"])
except PermissionError as exc:
# 403, not 400: the request is well-formed and the caller simply
# may not write the target. The note itself was created.
return jsonify({"error": str(exc), "note": note.to_dict()}), 403
# Both doors file a note to Systems: the door nobody exercises for a kind
# is the one that never grows the parameter.
if data.get("system_ids") is not None:
await systems_svc.set_record_systems(uid, note.id, data["system_ids"])
out = note.to_dict()
await supersession_svc.attach_relations(uid, note.id, out)
return jsonify(out), 201
@notes_bp.route("/tags", methods=["GET"])
@login_required
async def list_tags_route():
uid = get_current_user_id()
q = request.args.get("q")
tags = await get_all_tags(uid, q=q)
return jsonify({"tags": tags})
@notes_bp.route("/<int:note_id>/append-tag", methods=["POST"])
@login_required
async def append_tag_route(note_id: int):
uid = get_current_user_id()
data = await request.get_json()
tag = data.get("tag", "").strip().replace(" ", "-")
if not tag:
return jsonify({"error": "tag is required"}), 400
note = await get_note(uid, note_id)
if note is None:
return not_found("Note")
existing = list(note.tags or [])
if tag not in existing:
existing.append(tag)
updated = await update_note(uid, note_id, tags=existing)
return jsonify(updated.to_dict())
@notes_bp.route("/by-title", methods=["GET"])
@login_required
async def get_note_by_title_route():
uid = get_current_user_id()
title = request.args.get("title", "")
if not title:
return jsonify({"error": "title parameter is required"}), 400
note = await get_note_by_title(uid, title)
if note is None:
return not_found("Note")
return jsonify(note.to_dict())
@notes_bp.route("/resolve-title", methods=["POST"])
@login_required
async def resolve_title_route():
uid = get_current_user_id()
data = await request.get_json()
title = data.get("title", "").strip()
if not title:
return jsonify({"error": "title is required"}), 400
note = await get_or_create_note_by_title(uid, title)
return jsonify(note.to_dict())
@notes_bp.route("/duplicates", methods=["GET"])
@login_required
async def find_duplicate_records_route():
"""Near-duplicate notes or tasks, grouped, with the per-kind suggestion.
?kind=note|task, ?threshold= (0 = configured setting). Registered above the
`/<int:note_id>` routes on purpose — the literal path first, same reasoning
as /api/snippets/duplicates. Mirrors the MCP tool (#33): the web UI has no
dedup gate by design, so this report is the UI's only window onto what that
decision admits.
"""
uid = get_current_user_id()
kind = request.args.get("kind", "note")
if kind not in ("note", "task"):
return jsonify({"error": 'kind must be "note" or "task"'}), 400
try:
threshold = float(request.args.get("threshold", 0) or 0)
except (TypeError, ValueError):
threshold = 0.0
return jsonify(await dedup_svc.find_duplicate_records(
uid, kind=kind, threshold=threshold if threshold > 0 else None,
))
@notes_bp.route("/<int:note_id>", methods=["GET"])
@login_required
async def get_note_route(note_id: int):
uid = get_current_user_id()
result = await get_note_for_user(uid, note_id)
if result is None:
return not_found("Note")
note, permission = result
data = note.to_dict()
data["permission"] = permission
# Opening the detail view IS a pull — the operator chose to look. Tagged by
# SURFACE, not by the record's kind, matching rest_snippet: the kind is a
# join away, but which surface asked is not recoverable after the fact.
# Keeping rest_* apart from mcp_* is load-bearing, not tidiness — "was that
# injected line useful?" is answered by agent pulls alone, and a human
# clicking a link would inflate exactly the number pruning gates on.
record_pulled(user_id=uid, note_id=note_id, source="rest_note")
await supersession_svc.attach_relations(uid, note_id, data)
return jsonify(data)
@notes_bp.route("/<int:note_id>", methods=["PUT", "PATCH"])
@login_required
async def update_note_route(note_id: int):
"""Partial update — only the keys present in the payload change. PUT and
PATCH are the same handler on purpose: the form sends the field set it
edited, and two copies of this function would drift (one carrying the
supersedes contract, one not)."""
uid = get_current_user_id()
# Share-aware: resolve through the ACL and write as the OWNER, so a shared
# editor's save isn't rejected by the owner-scoped update service.
result = await get_note_for_user(uid, note_id)
if result is None:
return not_found("Note")
note_obj, _ = result
if not await can_write_note(uid, note_id):
return jsonify({"error": "Permission denied"}), 403
owner_uid = note_obj.user_id
data = await request.get_json()
fields = {}
for key in (
"title", "body", "description", "parent_id", "project_id",
"milestone_id", "status", "priority", "note_type",
# A cleared form input arrives as "" and the service reads that as
# NULL (NULLABLE_NOTE_TEXT), so this door expresses "remove the check"
# with its own idiom and needs no `clear` list.
"verify_with", "expires_when",
):
if key in data:
fields[key] = data[key]
if "due_date" in data:
if data["due_date"]:
result = parse_iso_date(data["due_date"], "due_date")
if isinstance(result, tuple):
return result
fields["due_date"] = result
else:
fields["due_date"] = None
if "tags" in data:
fields["tags"] = data["tags"]
try:
note = await update_note(owner_uid, note_id, **fields)
except ValueError as e:
return jsonify({"error": str(e)}), 400
if note is None:
return not_found("Note")
# Set-semantics, matching MCP and the PATCH route: present-and-empty
# clears, absent leaves alone. Scoped by the CALLER, not owner_uid — an
# editor-share holder may edit this note and must not thereby inherit the
# owner's write access to whatever they name as superseded (#47).
if "supersedes" in data:
try:
await supersession_svc.set_supersedes(uid, note_id, data["supersedes"] or [])
except PermissionError as exc:
return jsonify({"error": str(exc)}), 403
# Set-semantics like the above: present-and-empty clears, absent leaves
# alone. Scoped by the CALLER rather than owner_uid, for the same reason
# the supersedes call is — `set_record_systems` links only Systems the
# acting user can read, and an editor-share holder should tag from what
# they can see rather than inherit the owner's reach. Every door that
# tags a record (tasks, lessons, snippets) does the same.
if "system_ids" in data:
await systems_svc.set_record_systems(uid, note_id, data["system_ids"] or [])
out = note.to_dict()
await supersession_svc.attach_relations(uid, note_id, out)
return jsonify(out)
@notes_bp.route("/<int:note_id>", methods=["DELETE"])
@login_required
async def delete_note_route(note_id: int):
uid = get_current_user_id()
result = await get_note_for_user(uid, note_id)
if result is None:
return not_found("Note")
note_obj, _ = result
if not await can_write_note(uid, note_id):
return jsonify({"error": "Permission denied"}), 403
from grimoire.services.trash import delete as trash_delete
batch = await trash_delete(note_obj.user_id, "note", note_id)
if batch is None:
return not_found("Note")
return "", 204
@notes_bp.route("/<int:note_id>/convert-to-task", methods=["POST"])
@login_required
async def convert_note_to_task_route(note_id: int):
uid = get_current_user_id()
try:
note = await convert_note_to_task(uid, note_id)
return jsonify(note.to_dict()), 200
except ValueError as e:
return jsonify({"error": str(e)}), 404
@notes_bp.route("/<int:note_id>/convert-to-note", methods=["POST"])
@login_required
async def convert_task_to_note_route(note_id: int):
uid = get_current_user_id()
try:
note = await convert_task_to_note(uid, note_id)
return jsonify(note.to_dict()), 200
except ValueError as e:
return jsonify({"error": str(e)}), 404
@notes_bp.route("/<int:note_id>/backlinks", methods=["GET"])
@login_required
async def get_backlinks_route(note_id: int):
uid = get_current_user_id()
links = await get_backlinks(uid, note_id)
return jsonify({"backlinks": links})
# ── Link suggestions ─────────────────────────────────────────────────────────
_WIKILINK_RE = re.compile(r'\[\[[^\]]+\]\]')
def _find_unlinked_terms(body: str, note_titles: list[tuple[int, str]]) -> list[dict]:
"""Return project note titles that appear in body as plain text (not inside [[...]])."""
linked_ranges = [(m.start(), m.end()) for m in _WIKILINK_RE.finditer(body)]
def in_wikilink(start: int, end: int) -> bool:
return any(ls <= start and end <= le for ls, le in linked_ranges)
suggestions = []
for note_id, title in note_titles:
title = title.strip()
if len(title) < 3:
continue
pattern = re.compile(r'\b' + re.escape(title) + r'\b', re.IGNORECASE)
count = sum(1 for m in pattern.finditer(body) if not in_wikilink(m.start(), m.end()))
if count > 0:
suggestions.append({"note_id": note_id, "title": title, "count": count})
suggestions.sort(key=lambda x: x["count"], reverse=True)
return suggestions
@notes_bp.route("/link-suggestions", methods=["POST"])
@login_required
async def link_suggestions_route():
"""Find project note titles that appear unlinked in the given body text."""
uid = get_current_user_id()
data = await request.get_json()
body_text = data.get("body", "")
project_id = data.get("project_id")
exclude_note_id = data.get("exclude_note_id")
if not project_id or not body_text:
return jsonify({"suggestions": []})
try:
project_notes, _ = await list_notes(
uid, project_id=int(project_id), sort="title", order="asc", limit=200
)
titles = [
(n.id, n.title)
for n in project_notes
if n.id != exclude_note_id and n.title
]
suggestions = _find_unlinked_terms(body_text, titles)
except Exception:
logger.warning("Failed to compute link suggestions", exc_info=True)
suggestions = []
return jsonify({"suggestions": suggestions})
# ── Draft routes ─────────────────────────────────────────────────────────────
@notes_bp.route("/<int:note_id>/draft", methods=["GET"])
@login_required
async def get_draft_route(note_id: int):
uid = get_current_user_id()
draft = await get_draft(uid, note_id)
if draft is None:
return jsonify({"error": "No draft found"}), 404
return jsonify(draft.to_dict())
@notes_bp.route("/<int:note_id>/draft", methods=["PUT"])
@login_required
async def upsert_draft_route(note_id: int):
uid = get_current_user_id()
# Verify note ownership
note = await get_note(uid, note_id)
if note is None:
return not_found("Note")
data = await request.get_json()
draft = await upsert_draft(
user_id=uid,
note_id=note_id,
proposed_body=data.get("proposed_body", ""),
original_body=data.get("original_body", ""),
instruction=data.get("instruction", ""),
scope=data.get("scope", "document"),
)
return jsonify(draft.to_dict()), 200
@notes_bp.route("/<int:note_id>/draft", methods=["DELETE"])
@login_required
async def delete_draft_route(note_id: int):
uid = get_current_user_id()
await delete_draft(uid, note_id)
return "", 204
# ── Version routes ────────────────────────────────────────────────────────────
@notes_bp.route("/<int:note_id>/versions", methods=["GET"])
@login_required
async def list_versions_route(note_id: int):
uid = get_current_user_id()
versions = await list_versions(uid, note_id)
return jsonify({"versions": [v.to_dict(include_body=False) for v in versions]})
@notes_bp.route("/<int:note_id>/versions/<int:version_id>", methods=["GET"])
@login_required
async def get_version_route(note_id: int, version_id: int):
uid = get_current_user_id()
version = await get_version(uid, note_id, version_id)
if version is None:
return not_found("Version")
return jsonify(version.to_dict(include_body=True))
@notes_bp.route("/<int:note_id>/versions/<int:version_id>/pin", methods=["POST"])
@login_required
async def pin_version_route(note_id: int, version_id: int):
"""Mark a version as manually pinned. Body: {"label": str | null}."""
uid = get_current_user_id()
data = await request.get_json() or {}
label = data.get("label")
if label is not None and not isinstance(label, str):
return jsonify({"error": "label must be a string or null"}), 400
from grimoire.services.version_pinning import pin_version
try:
version = await pin_version(uid, note_id, version_id, label=label)
except ValueError as e:
return jsonify({"error": str(e)}), 400
if version is None:
return not_found("Version")
return jsonify(version.to_dict(include_body=False))
@notes_bp.route(
"/<int:note_id>/versions/<int:version_id>/pin", methods=["DELETE"],
)
@login_required
async def unpin_version_route(note_id: int, version_id: int):
"""Downgrade a manually-pinned version back to rolling."""
uid = get_current_user_id()
from grimoire.services.version_pinning import unpin_version
version = await unpin_version(uid, note_id, version_id)
if version is None:
return not_found("Version")
return jsonify(version.to_dict(include_body=False))
# ── Graph route ────────────────────────────────────────────────────────────────
@notes_bp.route("/graph", methods=["GET"])
@login_required
async def graph_route():
uid = get_current_user_id()
project_id = request.args.get("project_id", type=int)
shared_tags = request.args.get("shared_tags", "false").lower() == "true"
graph = await build_note_graph(uid, project_id=project_id, include_shared_tags=shared_tags)
return jsonify(graph)
# ── The staleness sweep ──────────────────────────────────────────────────────
# The web half of notes_due_for_verification / mark_note_verified. Same
# contract as the MCP door and the rules routes beside it — the service holds
# the behaviour, these two just parse and serialise.
@notes_bp.route("/due-for-verification", methods=["GET"])
@login_required
async def notes_due_route():
"""Notes that carry a check, oldest verification first, never-checked top.
Query params: older_than_days, project_id, never_only. A note with no
`verify_with` never appears — it is a decision, not a fact.
"""
uid = get_current_user_id()
args = request.args
try:
older = int(args.get("older_than_days", 0) or 0)
project = int(args.get("project_id", 0) or 0)
except ValueError:
return jsonify({"error": "older_than_days and project_id must be integers"}), 400
try:
notes = await notes_due_for_verification(
uid,
older_than_days=older,
project_id=project or None,
never_only=args.get("never_only", "").lower() in ("1", "true", "yes"),
)
except ValueError as exc:
# A 400, not a silently narrowed result: a filter that quietly answers
# a different question is the failure this whole surface exists to
# catch.
return jsonify({"error": str(exc)}), 400
return jsonify({
"notes": [verification_row(n) for n in notes],
"total": len(notes),
})
@notes_bp.route("/<int:note_id>/verify", methods=["POST"])
@login_required
async def mark_note_verified_route(note_id: int):
"""Record that the note's check was run. Body: {"still_true": bool}.
`still_true: false` writes nothing — a note whose check failed is wrong,
not in a recordable state — so it keeps its place at the top of the sweep.
"""
data = await request.get_json() or {}
uid = get_current_user_id()
still_true = bool(data.get("still_true", True))
note = await mark_note_verified(note_id, uid, still_true)
if note is None:
return jsonify({
"error": "note not found, not writable by you, or carries no verify_with"
}), 404
payload = verification_row(note)
payload["verified"] = still_true
return jsonify(payload)
+96
View File
@@ -0,0 +1,96 @@
"""Platform routes — the GLOBAL platform catalog, and which platforms a
project is.
Two shapes, as with the canonical areas:
- `/api/platforms` — the catalog. Readable by any signed-in user; writable
only by an admin, since a vocabulary anyone extends stops being shared.
- `/api/projects/<id>/platforms` — a project's answers, authorised by the
PROJECT (read to see them, write to change them). The service enforces
both; these are thin wrappers.
"""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import admin_required, get_current_user_id, login_required
from grimoire.routes.utils import not_found
from grimoire.services import platforms as platforms_svc
logger = logging.getLogger(__name__)
platforms_bp = Blueprint("platforms", __name__, url_prefix="/api")
_EDITABLE = ("name", "description", "order_index", "markers")
@platforms_bp.route("/platforms", methods=["GET"])
@login_required
async def list_platforms_route():
entries = await platforms_svc.list_platforms()
return jsonify({"platforms": [e.to_dict() for e in entries]})
@platforms_bp.route("/platforms", methods=["POST"])
@admin_required
async def create_platform_route():
uid = get_current_user_id()
data = await request.get_json() or {}
if not (data.get("name") or "").strip():
return jsonify({"error": "name is required"}), 400
try:
entry = await platforms_svc.create_platform(
uid, data["name"], description=data.get("description"),
markers=data.get("markers"),
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
if entry is None:
return jsonify({"error": "Permission denied"}), 403
# Duplicate-gated on the slug: the entry that already is this platform
# comes back as a 409 rather than a second spelling of it.
if isinstance(entry, dict):
return jsonify(entry), 409
return jsonify(entry.to_dict()), 201
@platforms_bp.route("/platforms/<int:platform_id>", methods=["PATCH"])
@admin_required
async def update_platform_route(platform_id: int):
uid = get_current_user_id()
data = await request.get_json() or {}
fields = {k: v for k, v in data.items() if k in _EDITABLE}
try:
entry = await platforms_svc.update_platform(uid, platform_id, **fields)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
if entry is None:
return not_found("Platform")
return jsonify(entry.to_dict())
@platforms_bp.route("/projects/<int:project_id>/platforms", methods=["GET"])
@login_required
async def project_platforms_route(project_id: int):
"""Every platform the project has an answer for — rejected included, so
a screen can show "no" as well as "yes"."""
rows = await platforms_svc.project_platforms(get_current_user_id(), project_id)
if rows is None:
return not_found("Project")
return jsonify({"project_platforms": rows})
@platforms_bp.route("/projects/<int:project_id>/platforms", methods=["PUT"])
@login_required
async def set_project_platforms_route(project_id: int):
"""Body: {"platforms": {<slug>: "declared" | "rejected" | null}}. Only
the slugs named change; null withdraws the answer. Applies whole or not
at all."""
data = await request.get_json() or {}
try:
rows = await platforms_svc.set_project_platforms(
get_current_user_id(), project_id, data.get("platforms"),
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
return jsonify({"project_platforms": rows})
+683
View File
@@ -0,0 +1,683 @@
"""Grimoire-plugin support endpoints.
Consumed by the Grimoire Claude Code plugin (not the web UI). `GET /api/plugin/
context` is curled by the plugin's SessionStart hook to push the operator's
always-on rules + active-project context into the session — Grimoire's own push
channel. Auth is the standard `@login_required` path, which accepts a `Bearer
fmcp_<key>` API key (a read-scoped key suffices for this GET).
"""
from __future__ import annotations
from quart import Blueprint, g, jsonify, request
from grimoire.auth import admin_required, get_current_user_id, login_required
from grimoire.config import Config
from grimoire.services import lesson_rules as lesson_rules_svc
from grimoire.services import moment_delivery as moment_delivery_svc
from grimoire.services import plugin_context as plugin_ctx_svc
from grimoire.services import reply_shapes as reply_shapes_svc
from grimoire.services import repo_bindings as repo_bindings_svc
from grimoire.services import report_check as report_check_svc
from grimoire.services import rule_moment_judgments as judgments_svc
from grimoire.services import shape_check as shape_check_svc
from grimoire.services import task_claims as task_claims_svc
from grimoire.services.embeddings import memoized_query_embeddings
from grimoire.services.settings import get_admin_setting, set_setting
plugin_bp = Blueprint("plugin", __name__, url_prefix="/api/plugin")
# Setting key for the git URL of the marketplace that serves this plugin (the
# Grimoire app's own repo). Instance-global (stored on an admin account) so every
# user's Settings page shows the real, copyable install command.
_MARKETPLACE_KEY = "plugin_marketplace_url"
def _int_list(raw: str | None) -> list[int]:
"""A comma-separated id list from the query string; non-ints dropped."""
return [int(p) for p in (raw or "").split(",") if p.strip().isdigit()]
async def _project_scope() -> tuple[int, str, str]:
"""(project_id, repo, unbound_repo) from the request's `project_id` /
`repo` query args — the one resolution every plugin endpoint shares.
An explicit project_id wins; otherwise the repo remote is resolved
through the caller's bindings, and a remote nobody bound comes back as
`unbound_repo` (normalised) so /context can say "bind this repo".
"""
try:
project_id = int(request.args.get("project_id", 0) or 0)
except (TypeError, ValueError):
project_id = 0
repo = (request.args.get("repo") or "").strip()
unbound_repo = ""
if repo and not project_id:
resolved = await repo_bindings_svc.resolve_project(g.user.id, repo)
if resolved:
project_id = resolved
else:
unbound_repo = repo_bindings_svc.normalize_repo_key(repo)
return project_id, repo, unbound_repo
@plugin_bp.get("/context")
@login_required
async def session_context():
"""Return SessionStart context (always-on rules + active project).
Query:
repo (optional str) — the working repo's git remote. The server
resolves it to the bound project (see services/repo_bindings); an
unbound repo yields a "bind this repo" hint instead. This is how the
active project is determined — the plugin never pins a project id.
project_id (optional int) — the project named directly, and the only
key a caller outside a git repo has: the plugin's hooks
send it when a `.scribe` marker file names a project. Takes
precedence over `repo`. Access-checked like any other read — an id
this account cannot read loads no project rather than failing.
source (optional str) — the host's SessionStart source (startup,
resume, compact, clear, fork); decides what the claim section says.
session_id (optional str) — the session's id, so a claim bound to it
reads as this session's own.
"""
project_id, _repo, unbound_repo = await _project_scope()
result = await plugin_ctx_svc.build_session_context(
g.user.id, project_id, unbound_repo=unbound_repo,
source=(request.args.get("source") or "").strip()[:20],
session_id=(request.args.get("session_id") or "").strip()[:200],
)
return jsonify(result)
@plugin_bp.get("/retrieve")
@login_required
@memoized_query_embeddings
async def autoinject_retrieve():
"""Title-first knowledge auto-inject for the plugin's UserPromptSubmit hook.
Given the user's prompt (`q`), returns a compact awareness hint — note
titles + scores only, never bodies — for the top hits that clear the
per-user gates (see services.plugin_context.build_autoinject_hint). Returns
empty context (most of the time) when disabled or nothing is relevant.
Query:
q (str) — the user's prompt to retrieve against.
repo (optional) — working repo remote; resolved to the bound project
to scope the search (mirrors /context). Unbound or
absent → searches all the user's notes.
project_id (opt) — explicit project scope override (ad-hoc/testing).
exclude_ids (opt) — comma-separated note ids already injected this
session; skipped so each note injects at most once.
ctx (opt) — the tail of the last assistant reply. The
notes AND rule arms append it to a short prompt,
so a follow-up like "yes do that" still names
what it is about — and a rule or lesson arrives
while the work is under way, before the operator
has to call it out.
exclude_rule_ids — comma-separated rule ids already surfaced this
(opt) session. SHARED with /prior-art and /tool-rules on
purpose: one session keeps ONE rule ledger, so a
rule named by any arm is not re-announced by
another. Ages out, so salience decays.
held_rule_ids — comma-separated rule ids the session actually
(opt) OPENED, observed from the `get_rule` call itself
rather than claimed. A rule on exclude_rule_ids
was NAMED; a rule here was READ, and the two say
different things about what the reader holds —
so they get different lines. Shares the
ledger directory and the same clear-on-compact.
shapes_seen (opt) — comma-separated reply-shape keys this session was
already shown in full. The core
goes out in full when `core` is absent, as its
one-line reminder when present; the hook's
ledger is swept on compaction, which is how the
full core comes back after one.
THE TURN'S REPLY SHAPE COMES FIRST. Every turn ends
in a reply and this is the last point before it is written, so the core
shape and whatever is mounted on `reply.report` lead the payload. Fresh
shape keys come back as `shape_keys` for the ledger.
TWO ARMS, TWO SETS OF GATES. Rules ride the same hook and the same query
but nothing else: the notes menu can be disabled, thresholded and top-k'd
by the operator without touching whether a rule reaches them. Composed
here rather than inside either builder so neither one's early return can
silently suppress the other.
Rules come FIRST in the payload. A rule or preference governing the answer
is more consequential than a menu of things that might be worth reading,
and a reader who stops after the first block should have stopped after
the right one.
"""
q = (request.args.get("q") or "").strip()
project_id, _repo, _unbound = await _project_scope()
exclude_ids = _int_list(request.args.get("exclude_ids"))
exclude_rule_ids = _int_list(request.args.get("exclude_rule_ids"))
held_rule_ids = _int_list(request.args.get("held_rule_ids"))
ctx = request.args.get("ctx") or ""
rules = await plugin_ctx_svc.build_prompt_rule_hint(
g.user.id, q, project_id=project_id, exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
context=ctx,
)
result = await plugin_ctx_svc.build_autoinject_hint(
g.user.id, q, project_id=project_id, exclude_ids=exclude_ids, context=ctx,
)
# The one place both arms' lines meet, so the one place a lesson and a
# rule arriving TOGETHER can be counted. Keyed on the operator's
# prompt — the situation — and fails open to "".
proposal = await lesson_rules_svc.co_surfaced(
g.user.id, result.get("lesson_ids") or [], rules.get("shown_rule_ids") or [],
arm="p", situation=q, project_id=project_id or None,
)
# The reply mounts go through the same rule ledger; a rule the prompt arm
# just named is not quoted a second time by the turn's delivery.
turn = await moment_delivery_svc.deliver_for_turn(
g.user.id, seen=reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
project_id=project_id,
exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]),
held=frozenset(held_rule_ids),
)
blocks = [b for b in (turn["context"], rules["context"], result["context"], proposal) if b]
result["context"] = "\n\n".join(blocks)
result["rule_ids"] = list(dict.fromkeys([*rules["rule_ids"], *turn["rule_ids"]]))
result["shape_keys"] = [k for k, form in turn["shape_forms"].items()
if form == reply_shapes_svc.FULL]
return jsonify(result)
@plugin_bp.get("/tool-rules")
@login_required
@memoized_query_embeddings
async def pre_tool_rules():
"""Standing rules for the plugin's PreToolUse hook on ACTIONS.
Answers "does a recorded rule speak to the command about to be run?" — the
sibling of /prior-art, which can only answer that question about a code
write. Rules about which tool to reach for (don't curl the forge, don't
stand up a stack, don't run the suite locally) have no other retrieval
surface: no code write ever happens for them to ride on.
Titles + trigger only, never the statement: the hint says a rule may apply
and hands over `get_rule(id)`. One rule at most (RULEHINT_LIMIT), and empty
most of the time.
Query:
tool (str) — the tool about to run, e.g. `Bash`. Used in
the hint's wording, not in the search: a
rule is about the action, not the harness.
command (str) — the command about to run; the semantic query.
Absent or blank → empty, no search.
repo (optional) — working repo remote, resolved to the bound
project exactly as /retrieve and /prior-art.
exclude_rule_ids (opt) — comma-separated rule ids already surfaced
this session. SHARED with /prior-art's
ledger on purpose: one session keeps one
list, so a rule named by either arm is not
re-offered by the other.
held_rule_ids (opt) — rule ids the session actually OPENED, as
against merely named. Named and read are
different claims about the reader's
context, so they get different lines.
root, cwd (opt) — the repo's absolute root and the command's
working directory. They turn the paths the
command names into repo-relative ones, for
the rulings arm.
seen_ruling_systems (opt) — comma-separated System ids whose rulings
were already shown this session, by either
arm; those get a one-line reference. SHARED
with /prior-art, like exclude_rule_ids.
Returns `context`, `rule_ids`, and `checkpoint`,
plus `ruling_system_ids` — the Systems whose rulings were shown in full on
this call — when there were any.
`checkpoint` IS THE ONE PART OF THIS RESPONSE THAT IS NOT A HINT. It is
empty on almost every call. When present it carries `rule_id`, `title`,
`trigger`, `score` and a rendered `reason`, and it means the hook should
DENY the call rather than annotate it — because every other line this
endpoint returns is delivered by Claude Code alongside the tool RESULT,
so it reaches the reader after the act is composed and reads as
commentary on a decision already made.
It is raised only for a rule (never a preference, which claims no such
force), only for the ranker's top hit, only above the checkpoint
threshold — well above this arm's own floor — and only when the session
has NOT opened that rule. The remedy is one `get_rule` call, and the act
may then be re-submitted unchanged; the hook caps stops at one per rule
and five per session so a mis-set floor degrades to noise rather than to
a session that cannot proceed.
"""
tool = (request.args.get("tool") or "tool").strip()
command = request.args.get("command") or ""
project_id, _repo, _unbound = await _project_scope()
exclude_rule_ids = _int_list(request.args.get("exclude_rule_ids"))
held_rule_ids = _int_list(request.args.get("held_rule_ids"))
result = await plugin_ctx_svc.build_tool_rule_hint(
g.user.id, tool, command,
project_id=project_id, exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
root=(request.args.get("root") or "").strip(),
cwd=(request.args.get("cwd") or "").strip(),
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
)
return jsonify(result)
@plugin_bp.get("/moment-tools")
@login_required
async def moment_tools():
"""The tools whose calls can deliver a mounted rule.
Read by the plugin's catch-all PreToolUse hook once per session window and
kept on disk, so a call that cannot reach a mounted rule costs no request.
`tools` are tool KEYS — bare, lowercased, no MCP server prefix — the same
keys the moment mappings are written in. Empty on an install that has
mounted nothing, which keeps that hook entirely off the wire.
"""
return jsonify({"tools": await moment_delivery_svc.reachable_tools(g.user.id)})
@plugin_bp.post("/moment")
@login_required
async def moment():
"""The rules mounted on the moments this tool call reaches.
Body: the PreToolUse event as Claude Code delivers it — `tool_name` and
`tool_input` are read, nothing else. Sent whole because which input field
a mapping matches on is the mapping's business, not the hook's.
Query: `repo` / `project_id` for the scope, and the shared session ledger —
`exclude_rule_ids` (named this session: a repeat is cited, not quoted) and
`held_rule_ids` (opened) — exactly as /tool-rules takes them.
Returns `context` (the lines, each naming the moment and the action that
reached it, so a misfire is visible and can be unmapped in-session),
`rule_ids` (the FRESH ones, for the hook to append to the ledger) and
`moments` (the names reached). A lookup, not a ranked search: no
retrieval_logs row; each fresh rule is recorded surfaced with its moment.
A moment that carries a default reply shape brings it too,
ahead of the rules: in full unless `shapes_seen` names it, then as its
reminder. `shape_keys` are the ones sent in full, for the hook's ledger.
"""
event = await request.get_json(silent=True) or {}
tool = str(event.get("tool_name") or "").strip()
tool_input = event.get("tool_input")
if not tool:
return jsonify({"context": "", "rule_ids": [], "moments": [], "shape_keys": []})
project_id, _repo, _unbound = await _project_scope()
reached, result = await moment_delivery_svc.deliver_for_act(
g.user.id, tool, tool_input if isinstance(tool_input, dict) else {},
project_id=project_id,
exclude=frozenset(_int_list(request.args.get("exclude_rule_ids"))),
held=frozenset(_int_list(request.args.get("held_rule_ids"))),
)
shapes, forms = moment_delivery_svc.shapes_for_act(
reached, reply_shapes_svc.parse_seen(request.args.get("shapes_seen")),
)
await reply_shapes_svc.record_delivery(g.user.id, forms, via="hook")
context = "\n\n".join(b for b in ("\n\n".join(shapes), "\n".join(result.lines)) if b)
return jsonify({
"context": context,
"rule_ids": result.rule_ids,
"moments": [hit["moment"] for hit in reached],
"shape_keys": [k for k, form in forms.items() if form == reply_shapes_svc.FULL],
})
@plugin_bp.post("/rule-opened")
@login_required
async def rule_opened():
"""A session opened a rule shortly after these acts.
Body: `{"rule_id", "session_id", "acts": [<PreToolUse event>, ...]}` —
the calls the plugin saw in the window before the `get_rule`. Each is
resolved to its moments, and the open is counted as evidence that the
rule belongs on them; once a pair has repeated across enough distinct
sessions, `context` carries the line asking the reader to offer the
mount. Nothing is mounted here. `repo` / `project_id` scope the evidence.
"""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict):
return jsonify({"moments": [], "context": ""})
try:
rule_id = int(data.get("rule_id") or 0)
except (TypeError, ValueError):
rule_id = 0
acts = data.get("acts")
if rule_id <= 0 or not isinstance(acts, list):
return jsonify({"moments": [], "context": ""})
project_id, _repo, _unbound = await _project_scope()
return jsonify(await judgments_svc.opened_after(
g.user.id, rule_id, acts, session_id=str(data.get("session_id") or ""),
project_id=project_id or None,
))
@plugin_bp.post("/reply-rules")
@login_required
@memoized_query_embeddings
async def reply_rules():
"""Whether the reply that ends a turn is held for one read.
Called by the plugin's Stop hook with the finished reply. Two halves: the
rules MOUNTED on the reply moments (`reply.report`, and `reply.ask` when
the reply asks something), and the reply text against every rule's
trigger — the backstop for whatever the earlier arms missed.
ONE END-OF-TURN REQUEST: a reply that closed tasks is also checked here
for the completion sections (services/report_check). Both holds fold
into one `reason`; `report_check` says what the section check recorded, so
the hook knows the rewrite is one to report.
Body: `{"reply": "<text>", "closed": 1, "closed_task_ids": [41],
"rewrite": false}` — the last three only when the turn closed a task.
`closed` is the count and decides whether the check runs (a task created
already done has no id to list); `rewrite` marks the reply written after a
section hold, which is recorded and never held.
Query: `repo` / `project_id` for the scope;
`held_rule_ids` (opened this session — exempt, as at the act checkpoint);
`exclude_rule_ids` (named this session — not re-counted as surfaced);
`stopped_rule_ids` (already held a reply or an act this session — a rule
holds once, and the per-session cap counts these).
Returns `reason` — the words the hook blocks with, empty when nothing
holds — plus `rule_ids` for the hook's ledger, `moments` reached and
`report_check` (the recorded outcome, or "" when nothing was checked).
"""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict):
data = {}
reply = str(data.get("reply") or "")
# `type(...) is int`, not isinstance: JSON `true` would otherwise read as 1.
closed = data.get("closed") if type(data.get("closed")) is int else 0
ids = data.get("closed_task_ids")
task_ids = [i for i in ids if type(i) is int and i > 0][:20] if isinstance(ids, list) else []
rewrite = data.get("rewrite") is True
project_id, _repo, _unbound = await _project_scope()
checked: dict = {}
if closed > 0:
checked = await report_check_svc.check_reply(
g.user.id, reply, task_ids=task_ids, rewrite=rewrite, project_id=project_id or None,
)
# The rewrite after a hold goes out as written: recorded above, held by nothing.
held: dict = {}
if not rewrite:
held = await moment_delivery_svc.reply_hold(
g.user.id, reply, project_id=project_id,
exclude=frozenset(_int_list(request.args.get("exclude_rule_ids"))),
held=frozenset(_int_list(request.args.get("held_rule_ids"))),
stopped=frozenset(_int_list(request.args.get("stopped_rule_ids"))),
)
reasons = [r for r in (checked.get("reason", ""), held.get("reason", "")) if r]
return jsonify({
"reason": "\n\n".join(reasons),
"rule_ids": held.get("rule_ids", []),
"moments": held.get("moments", []),
"report_check": checked.get("outcome", ""),
})
@plugin_bp.get("/prior-art")
@login_required
@memoized_query_embeddings
async def write_path_prior_art():
"""Prior-art hint for the plugin's PreToolUse hook on Write/Edit.
Answers "what is already recorded for the file about to be written?" — by
place (a snippet at this path or in its directory) and by meaning (snippets
resembling the code about to be written). Titles only, gated, and empty most
of the time. See services.plugin_context.build_write_path_hint.
Query:
path (str) — the target file, REPO-RELATIVE, matching the
convention snippet locations are recorded in. An
absolute path simply won't match anything.
code (optional) — the code about to be written; the semantic query.
Omit it and only the location arm runs.
repo (optional) — working repo remote; resolved to the bound project
to scope the search, exactly as /retrieve does. It
is NOT used as the location `repo` filter — see the
service docstring for why those two differ.
project_id (opt) — explicit project scope override (ad-hoc/testing).
exclude_ids (opt) — comma-separated REUSE-class ids already surfaced
this session.
exclude_sync_ids (opt) — comma-separated SYNC-class ids (snippets
recorded AT the edited file) already
surfaced. A separate channel on purpose: a reuse
hint shown early must not suppress the record-sync
nudge when the recorded file is edited later.
exclude_rule_ids (opt) — comma-separated RULE ids already surfaced
this session. Its own channel like the three
above, and for the same reason: a rule named
twenty turns ago should not be re-offered on
every subsequent write.
held_rule_ids (opt) — RULE ids the session actually OPENED, as
against merely named; drives the third
reference wording.
exclude_derive (opt) — comma-separated derive keys (a derive group id
or `canon:<snippet_id>`) already named this
session by the ledger arm; its own
channel, like the two above.
seen_ruling_systems (opt) — System ids whose rulings were already shown
this session; shared with
/tool-rules. The response's `ruling_system_ids`
are the ones shown in full on this call.
(Returns a `checkpoint` block on the same contract as /tool-rules —
see that endpoint. The write-path HOOK deliberately does not act on
it: scribe_prior_art.sh carries a tested property that it never
returns a permissionDecision, because a recall aid must not stand in
the way of a write. The block is computed and
returned so that decision can be revisited with evidence rather than
re-argued, and so a change of mind is a hook edit and not a feature.)
shapes (opt) — comma-separated `kind:name` definitions the hook
found in (or enclosing) the payload, kind being
css|sym. The shape ledger's write-path feed:
when the session recently PULLED a
snippet this payload references or resembles,
these carry it as a proposal — evidence for the
agent's own end-of-turn judgment, never a
verdict. Honoured only for a
caller allowed to write — a read-scoped key still
gets the hint, and never changes the ledger on a
GET.
"""
path = (request.args.get("path") or "").strip()
code = request.args.get("code") or ""
project_id, repo, _unbound = await _project_scope()
exclude_ids = _int_list(request.args.get("exclude_ids"))
exclude_sync_ids = _int_list(request.args.get("exclude_sync_ids"))
exclude_derive = [
p.strip() for p in (request.args.get("exclude_derive") or "").split(",") if p.strip()
]
exclude_rule_ids = _int_list(request.args.get("exclude_rule_ids"))
held_rule_ids = _int_list(request.args.get("held_rule_ids"))
shapes = _parse_shapes(request.args.get("shapes") or "")
api_key = getattr(g, "api_key", None)
may_stamp = api_key is None or getattr(api_key, "scope", "") == "write"
result = await plugin_ctx_svc.build_write_path_hint(
g.user.id, path, code=code, project_id=project_id,
exclude_ids=exclude_ids, exclude_sync_ids=exclude_sync_ids,
stamp_shapes=shapes if may_stamp else None,
repo_key=repo_bindings_svc.normalize_repo_key(repo) if repo else "",
exclude_derive=exclude_derive,
exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids,
seen_ruling_systems=_int_list(request.args.get("seen_ruling_systems")),
)
return jsonify(result)
# The hook names at most a dozen definitions per write; anything past that is
# a generated file, not a shape being instantiated.
_SHAPES_CAP = 12
def _parse_shapes(raw: str) -> list[tuple[str, str]]:
"""`css:btn-primary,sym:onTrash` → [("css", "btn-primary"), ("sym", "onTrash")].
Unknown kinds and empty names are dropped, duplicates collapse, and the
list is capped — the hook's own cap, re-applied so the contract holds
for any caller."""
out: list[tuple[str, str]] = []
for part in raw.split(","):
kind, _sep, name = part.strip().partition(":")
kind, name = kind.strip(), name.strip()
if kind in ("css", "sym") and name and (kind, name) not in out:
out.append((kind, name))
if len(out) >= _SHAPES_CAP:
break
return out
@plugin_bp.get("/shape-check")
@login_required
async def shape_check():
"""The end-of-turn question: what did this turn write that
nobody has judged?
The client's write hooks keep a ledger of the definitions each turn wrote;
its Stop hook sends them here. The server decides which carry no judgment
— against the ledger and the project's recorded snippets — records the
outcome, and for a block returns the `reason` the agent is sent back with.
A hook blocks only on a reason it received, so only on a block that was
recorded, and never on the stop that follows one (`phase=after`).
A GET like every plugin endpoint: a read-scoped key runs the plugin, and
this records telemetry the way /reply-rules records its section check. It changes no ledger
row — the agent's own classify_shapes call does that.
Query:
written (str) — newline-separated `path<TAB>kind<TAB>name` lines,
repo-relative, kind css|sym|file.
phase (str) — check | after. Anything else is a 400.
repo (opt) — working repo remote, resolved like the other arms.
project_id (opt) — explicit scope override.
"""
phase = (request.args.get("phase") or "check").strip()
if phase not in shape_check_svc.PHASES:
return jsonify({"error": f"phase must be one of {list(shape_check_svc.PHASES)}"}), 400
written = shape_check_svc.parse_written(request.args.get("written") or "")
project_id, repo, _unbound = await _project_scope()
body: dict = {"status": "ok", "unjudged": []}
if not project_id or not written:
return jsonify(body)
from grimoire.services import access
from grimoire.services import coverage as coverage_svc
from grimoire.services import shape_ledger as shape_ledger_svc
if not await access.can_read_project(g.user.id, project_id):
return jsonify(body)
repo_key = repo_bindings_svc.normalize_repo_key(repo) if repo else ""
unjudged = await shape_ledger_svc.unjudged_shapes(project_id, written, repo_key=repo_key)
# A snippet recorded AT a shape is the strongest verdict there is — the
# next refresh stamps that row canonical. Until then the ledger cannot
# know, so the recorded locations answer for it: an agent who just
# recorded what it built is not asked again.
if unjudged:
recorded = {
(path, symbol)
for _sid, path, symbol in await coverage_svc._recorded_locations(g.user.id, project_id)
}
unjudged = [u for u in unjudged if (u["path"], u["symbol"]) not in recorded
and not (u["kind"] == "file" and (u["path"], "") in recorded)]
outcome = shape_check_svc.outcome_for(phase, unjudged)
await shape_check_svc.record_shape_check(
g.user.id, outcome, written=len(written), unjudged=len(unjudged),
project_id=project_id,
)
body["outcome"] = outcome
body["unjudged"] = unjudged
if outcome == "blocked":
body["reason"] = shape_check_svc.block_reason(
unjudged, project_id=project_id, repo=repo_key or repo,
)
return jsonify(body)
@plugin_bp.get("/claim-session")
@login_required
async def claim_session():
"""Bind the harness's session id to the caller's live claim on a task.
Called by `scribe_claim_session.sh` after `update_task` / `add_task_log`.
The server has already stamped the claim on that write; this only says
WHICH session made it — an id the harness reported, not one the model
asserted. A GET for the reason every plugin endpoint is one: a read-scoped
key must be enough to run the plugin.
Query:
task_id (int) — the task the tool call named.
session_id (str) — the Claude Code session id from the hook event.
Returns the claim when one was bound, `{"claim": null}` when there was
nothing to bind to (no live claim of the caller's, or not writable).
"""
try:
task_id = int(request.args.get("task_id") or "")
except ValueError:
return jsonify({"error": "task_id must be an integer"}), 400
session_id = (request.args.get("session_id") or "").strip()
if not session_id:
return jsonify({"error": "session_id is required"}), 400
claim = await task_claims_svc.bind_session(g.user.id, task_id, session_id)
return jsonify({"claim": claim})
@plugin_bp.get("/release-session")
@login_required
async def release_session():
"""Release the claims a session held, as it ends.
Called by `scribe_session_end.sh`. Best-effort by design: SessionEnd does
not fire on a crash, so the claim's lease — not this call — is what makes a
dead session's claim read as dead. This only makes the common case tidy.
Query:
session_id (str) — the ending session's id, from the hook event.
"""
session_id = (request.args.get("session_id") or "").strip()
if not session_id:
return jsonify({"error": "session_id is required"}), 400
released = await task_claims_svc.release_session(g.user.id, session_id)
return jsonify({"released": released})
@plugin_bp.get("/processes")
@login_required
async def process_manifest():
"""Stored Processes as skill-stub specs for the plugin's sync script.
The plugin's `scribe_sync_processes.sh` (run at SessionStart and via the
`/scribe:sync` command) curls this and writes one auto-surfacing local skill
per Process into ~/.claude/skills/. See services/plugin_context.
build_process_manifest. A read-scoped API key suffices.
"""
result = await plugin_ctx_svc.build_process_manifest(g.user.id)
return jsonify(result)
@plugin_bp.get("/marketplace-url")
@login_required
async def get_marketplace_url():
"""The plugin marketplace git URL, readable by any logged-in user so their
Settings page can show a copyable install command. Falls back to the
config default (this deployment's own repo) when no admin override is set."""
url = await get_admin_setting(_MARKETPLACE_KEY, default=Config.PLUGIN_MARKETPLACE_URL)
return jsonify({"marketplace_url": url})
@plugin_bp.put("/marketplace-url")
@admin_required
async def set_marketplace_url():
"""Admin-set the marketplace git URL (e.g. this app's own repo)."""
data = await request.get_json() or {}
url = (data.get("marketplace_url") or "").strip()
if url:
scheme = url.split("://")[0].lower() if "://" in url else ""
if scheme not in ("http", "https"):
return jsonify({"error": "Marketplace URL must use http or https"}), 400
await set_setting(get_current_user_id(), _MARKETPLACE_KEY, url)
return jsonify({"status": "ok"})
+299
View File
@@ -0,0 +1,299 @@
"""Project management routes."""
import logging
from quart import Blueprint, g, jsonify, request
from grimoire.auth import login_required, get_current_user_id
from grimoire.routes.utils import not_found, parse_pagination
from grimoire.services import inception as inception_svc
from grimoire.services.milestones import list_milestones
from grimoire.services.notes import list_notes
from grimoire.services.projects import (
create_project,
delete_project,
get_project,
get_project_for_user,
get_project_summaries,
get_project_summary,
list_projects_for_user,
update_project,
)
logger = logging.getLogger(__name__)
projects_bp = Blueprint("projects", __name__, url_prefix="/api/projects")
@projects_bp.route("", methods=["GET"])
@login_required
async def list_projects_route():
uid = get_current_user_id()
status = request.args.get("status")
include_summary = request.args.get("include_summary", "").lower() in ("1", "true")
projects = await list_projects_for_user(uid, status=status)
if include_summary:
# Batched: four queries plus two, in two sessions, for ALL projects.
# An asyncio.gather over a per-project summary would open a session per
# project and one more per milestone — far more concurrent checkouts
# than the pool holds, all waiting out the checkout timeout and
# starving every other route on the instance.
#
# Grouped by OWNER because a shared project's counts belong to its
# owner's records, matching what the per-project path passed.
by_owner: dict[int, list[dict]] = {}
for p in projects:
by_owner.setdefault(p.get("user_id") or uid, []).append(p)
for owner_uid, owned in by_owner.items():
try:
summaries = await get_project_summaries(
owner_uid, [p["id"] for p in owned]
)
except Exception:
logger.warning("Project summaries failed", exc_info=True)
continue
for p in owned:
if p["id"] in summaries:
p["summary"] = summaries[p["id"]]
return jsonify({"projects": projects})
@projects_bp.route("", methods=["POST"])
@login_required
async def create_project_route():
uid = get_current_user_id()
data = await request.get_json()
if not data.get("title"):
return jsonify({"error": "title is required"}), 400
status = data.get("status", "active")
if status not in ("active", "paused", "completed", "archived"):
return jsonify({"error": "status must be 'active', 'paused', 'completed', or 'archived'"}), 400
# The inception decision rides the create: the UI's
# second step sends `inception: {choices}`; absent = undecided, and the
# project page shows the card until it is. Validated before the create
# so a bad decision never leaves a half-made project behind.
inception = data.get("inception")
if inception is not None:
error = inception_svc.validate_inception(inception)
if error:
return jsonify({"error": error}), 400
project = await create_project(
uid,
title=data["title"],
description=data.get("description", ""),
goal=data.get("goal", ""),
color=data.get("color"),
status=status,
)
out = project.to_dict()
if inception is not None:
try:
decided = await inception_svc.decide(uid, project.id, choices=inception, via="ui")
except ValueError as exc:
return jsonify({"error": str(exc), "project": out}), 400
out["inception"] = decided["inception"]
out["inception_effects"] = decided["effects"]
return jsonify(out), 201
@projects_bp.route("/<int:project_id>/inception", methods=["POST"])
@login_required
async def decide_inception_route(project_id: int):
"""Record (or re-record) what a project inherits.
Body: the choices object {design_system_id, seed_systems}; owner-only."""
uid = get_current_user_id()
data = await request.get_json() or {}
choices = data.get("choices", data)
try:
decided = await inception_svc.decide(uid, project_id, choices=choices, via="ui")
except ValueError as exc:
msg = str(exc)
status = 404 if "not found" in msg else 400
return jsonify({"error": msg}), status
return jsonify({"project_id": project_id, **decided})
@projects_bp.route("/<int:project_id>/inception/defaults", methods=["GET"])
@login_required
async def inception_defaults_route(project_id: int):
"""What the project inherits if nobody decides — the card's payload."""
uid = get_current_user_id()
try:
return jsonify(await inception_svc.current_defaults(uid, project_id))
except ValueError:
return not_found("Project")
@projects_bp.route("/<int:project_id>", methods=["GET"])
@login_required
async def get_project_route(project_id: int):
uid = get_current_user_id()
result = await get_project_for_user(uid, project_id)
if result is None:
return not_found("Project")
project, permission = result
# Summary uses the project owner's uid for stats when viewer is not the owner
owner_uid = project.user_id or uid
summary = await get_project_summary(owner_uid, project_id)
data = project.to_dict()
data["summary"] = summary
data["permission"] = permission
return jsonify(data)
@projects_bp.route("/<int:project_id>", methods=["PATCH"])
@login_required
async def update_project_route(project_id: int):
uid = get_current_user_id()
data = await request.get_json()
allowed = {"title", "description", "goal", "status", "color"}
fields = {k: (v if v is not None else "") for k, v in data.items() if k in allowed}
if "status" in fields and fields["status"] not in ("active", "paused", "completed", "archived"):
return jsonify({"error": "status must be 'active', 'paused', 'completed', or 'archived'"}), 400
project = await update_project(uid, project_id, **fields)
if project is None:
return not_found("Project")
return jsonify(project.to_dict())
@projects_bp.route("/<int:project_id>", methods=["DELETE"])
@login_required
async def delete_project_route(project_id: int):
uid = get_current_user_id()
from grimoire.services.trash import delete as trash_delete
batch = await trash_delete(uid, "project", project_id)
if batch is None:
return not_found("Project")
return "", 204
@projects_bp.route("/<int:project_id>/coverage", methods=["GET"])
@login_required
async def get_coverage_route(project_id: int):
"""The cached shape-accounting summary — never computes.
`configured` tells the card whether offering a Refresh button makes
sense; `coverage` is null until something has computed it (a webhook
push or an explicit refresh).
"""
from grimoire.services.coverage import cached_coverage
from grimoire.services.forge import get_forges
uid = get_current_user_id()
result = await get_project_for_user(uid, project_id)
if result is None:
return not_found("Project")
project, _ = result
owner_uid = project.user_id or uid
return jsonify({
# The OWNER's keyring — whether refresh could do anything,
# regardless of who is looking.
"configured": (await get_forges(owner_uid, project_id)).configured,
"coverage": await cached_coverage(owner_uid, project_id),
})
@projects_bp.route("/<int:project_id>/coverage/refresh", methods=["POST"])
@login_required
async def refresh_coverage_route(project_id: int):
"""Recompute coverage now (archive fetch — seconds, not milliseconds).
Synchronous on purpose: the caller is a person who just clicked Refresh
and wants the new number, and the forge timeout bounds the wait.
"""
from grimoire.services.coverage import refresh_coverage
from grimoire.services.forge import ForgeError, get_forges
uid = get_current_user_id()
result = await get_project_for_user(uid, project_id)
if result is None:
return not_found("Project")
project, _ = result
owner_uid = project.user_id or uid
selector = await get_forges(owner_uid, project_id)
if not selector.configured:
return jsonify({
"error": "The project owner has no forge connection "
"(Settings → Git forges)"
}), 400
try:
coverage = await refresh_coverage(owner_uid, project_id, selector=selector)
except ForgeError as exc:
return jsonify({"error": str(exc)}), 502
if coverage is None:
return jsonify({
"error": "No bound repo is served by the owner's forge connections — "
"bind the project's repo (bind_repo) on a remote a connection hosts"
}), 400
return jsonify({"coverage": coverage})
@projects_bp.route("/<int:project_id>/forge", methods=["PUT"])
@login_required
async def set_project_forge_route(project_id: int):
"""Pin the project to one forge connection, or clear the pin.
Body: {"connection_id": <id> | null}. Owner-or-admin may ask; either way
the pin can only reference a connection the project OWNER holds — the
service enforces that, so a collaborator's token can never end up serving
someone else's project.
"""
from grimoire.services.forge_connections import set_project_pin
uid = get_current_user_id()
result = await get_project_for_user(uid, project_id)
if result is None:
return not_found("Project")
project, permission = result
if permission != "owner" and g.user.role != "admin":
return jsonify({"error": "Only the project owner can change its forge"}), 403
data = await request.get_json() or {}
raw = data.get("connection_id")
if raw is not None and not isinstance(raw, int):
return jsonify({"error": "connection_id must be an integer or null"}), 400
owner_uid = project.user_id or uid
if not await set_project_pin(owner_uid, project_id, raw):
return jsonify({
"error": "That connection does not belong to the project owner"
}), 400
return jsonify({"forge_connection_id": raw})
@projects_bp.route("/<int:project_id>/notes", methods=["GET"])
@login_required
async def get_project_notes_route(project_id: int):
uid = get_current_user_id()
result = await get_project_for_user(uid, project_id)
if result is None:
return not_found("Project")
project, _ = result
# Use the project owner's uid so the ownership filter on notes/milestones
# matches for shared collaborators (who'd otherwise see an empty panel).
owner_uid = project.user_id or uid
# type filter: "note", "task", or None (both)
type_filter = request.args.get("type")
status_filter = request.args.get("status")
limit, offset = parse_pagination(default_limit=100)
is_task: bool | None = None
if type_filter == "task":
is_task = True
elif type_filter == "note":
is_task = False
ms_list = await list_milestones(owner_uid, project_id)
milestone_ids = [m.id for m in ms_list]
notes, total = await list_notes(
owner_uid,
is_task=is_task,
status=status_filter,
project_id=project_id,
milestone_ids=milestone_ids,
limit=limit,
offset=offset,
sort="updated_at",
order="desc",
)
return jsonify({"notes": [n.to_dict() for n in notes], "total": total})
+222
View File
@@ -0,0 +1,222 @@
"""The operator's view of retrieval tuning — what the dials are, and who moved them.
WHY THIS EXISTS SEPARATELY FROM /api/settings
The numbers themselves are ordinary settings rows and could be written through
the generic KV endpoint. They must not be, and that is the whole point of this
blueprint: a floor changed through `/api/settings` moves silently, leaving the
history saying nothing happened. Those dials are moved by the model on the
operator's behalf, so a trail with holes in it is worse than
no trail — it reads as complete.
So every change to a retrieval dial goes through `set_dial`, from the UI as
much as from the MCP tool, and the only difference is the `actor` recorded.
"""
import logging
from datetime import datetime, timedelta, timezone
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.services import moment_actions as moment_actions_svc
from grimoire.services import moments as moments_svc
from grimoire.services import reply_shapes as shapes_svc
from grimoire.services import rule_moment_judgments as judgments_svc
from grimoire.services import rulebooks as rulebooks_svc
from grimoire.services.retrieval_telemetry import moment_usage
from grimoire.services.retrieval_tuning import set_dial, current_settings, tuning_history
logger = logging.getLogger(__name__)
retrieval_bp = Blueprint("retrieval", __name__, url_prefix="/api/retrieval")
# What is recorded when the operator changes a dial in Settings and says
# nothing about why.
#
# The MCP tool REFUSES a blank reason, and this endpoint does not, which is a
# deliberate asymmetry rather than an oversight. The requirement exists to make
# the model look at the records before it moves a number on someone else's
# behalf. The operator IS that someone: they are the audience the trail is
# written for, they cannot be uninformed about their own decision, and a
# mandatory justification textarea on every control would be friction charged
# to the one participant who owes no explanation.
#
# The event is still written, because "the operator set this by hand" is the
# single most useful thing the history can tell a later session — it is the one
# entry the model must not quietly tune back.
_OPERATOR_DEFAULT_REASON = "Set directly in Settings by the operator."
@retrieval_bp.route("/surfaces", methods=["GET"])
@login_required
async def get_surfaces_route():
"""Every tunable surface: its live floor and budget, what it asks and over
what, and the reason each dial was last moved."""
uid = get_current_user_id()
surfaces = await current_settings(uid)
return jsonify({"surfaces": surfaces, "total": len(surfaces)})
@retrieval_bp.route("/surfaces/<surface>", methods=["PUT"])
@login_required
async def tune_surface_route(surface: str):
"""Move one dial, recorded as a human change.
`actor` is fixed here rather than taken from the payload: this endpoint is
reached with a session cookie from the Settings form, so the actor is known
and accepting a claim about it would let the one field a reviewer relies on
be set to anything.
"""
uid = get_current_user_id()
data = await request.get_json()
if not isinstance(data, dict):
return jsonify({"error": "Expected a JSON object"}), 400
if "dial" not in data or "value" not in data:
return jsonify({"error": "dial and value are required"}), 400
try:
value = float(data["value"])
except (TypeError, ValueError):
return jsonify({"error": f"value must be a number, got {data['value']!r}"}), 400
reason = str(data.get("reason") or "").strip() or _OPERATOR_DEFAULT_REASON
try:
result = await set_dial(
uid, surface, str(data["dial"]), value, reason=reason, actor="human",
)
except ValueError as e:
# Unknown surface, unknown dial — the service names the alternatives,
# so the message is worth passing through rather than flattening.
return jsonify({"error": str(e)}), 400
return jsonify(result)
@retrieval_bp.route("/tuning-history", methods=["GET"])
@login_required
async def tuning_history_route():
"""What has been changed about retrieval on this install, newest first.
The review surface. Unscoped by default because the operator's question
here is "what has been done on my behalf", not "why is this one arm set
like that" — the per-surface scoping is for the model.
"""
uid = get_current_user_id()
surface = request.args.get("surface") or None
try:
limit = int(request.args.get("limit", 50))
except ValueError:
return jsonify({"error": "limit must be a whole number"}), 400
try:
events = await tuning_history(uid, surface=surface, limit=limit)
except ValueError as e:
return jsonify({"error": str(e)}), 400
return jsonify({"events": events, "total": len(events)})
@retrieval_bp.route("/moments", methods=["GET"])
@login_required
async def moments_route():
"""The moments of work that rules mount on, with the
actions that reach each one on this install.
The same payload `list_moments` returns, from the same services, so the
session and the Settings view cannot name different moments — plus what
the view shows beside each one: `mounted`, how many rules each
carries, and `usage`, the deliveries and opens per moment over `days`
(the block `retrieval_telemetry` reports as `moment_usage`).
"""
uid = get_current_user_id()
try:
days = max(1, min(int(request.args.get("days", 30)), 365))
except ValueError:
return jsonify({"error": "days must be a whole number"}), 400
out = moments_svc.catalog()
out.update(await moment_actions_svc.actions_by_moment(uid))
# The catalog is the page; the counts beside it are not worth losing it
# over. A failed count is flagged rather than shown as "nothing mounted".
try:
out["mounted"] = await rulebooks_svc.mount_counts(uid)
except Exception:
logger.warning("mount counts unreadable", exc_info=True)
out["mounted"], out["mounted_failed"] = {}, True
out["usage"] = await moment_usage(uid, datetime.now(timezone.utc) - timedelta(days=days))
out["usage"]["days"] = days
return jsonify(out)
@retrieval_bp.route("/reply-shapes", methods=["GET"])
@login_required
async def reply_shapes_route():
"""The default reply shapes and the moment each rides.
`list_reply_shapes`' payload from the same service, so the Settings view
and the session cannot show different defaults — plus what only the
operator's view needs: per shape, the preferences mounted on its
moment and its deliveries over `days` (default 30, 1–90).
"""
try:
days = min(90, max(1, int(request.args.get("days") or shapes_svc.OVERVIEW_DAYS)))
except ValueError:
days = shapes_svc.OVERVIEW_DAYS
return jsonify(await shapes_svc.overview(get_current_user_id(), days=days))
async def _mapping_change(change):
"""map/unmap from the browser: the MCP tools' service, recorded as human.
The mapping comes as a JSON body, or — for DELETE, whose body many
clients will not send — as query parameters of the same names.
"""
data = await request.get_json(silent=True)
if data is None and request.args:
data = request.args.to_dict()
if not isinstance(data, dict):
return jsonify({"error": "Expected a JSON object"}), 400
if not data.get("tool") or not data.get("moment"):
return jsonify({"error": "tool and moment are required"}), 400
try:
result = await change(
get_current_user_id(), str(data["tool"]), str(data.get("match") or ""),
str(data["moment"]), reason=str(data.get("reason") or ""), actor="human",
)
except ValueError as e:
# Unknown moment, a match the tool cannot take, nothing to remove —
# the service says what would work, so pass it through.
return jsonify({"error": str(e)}), 400
return jsonify(result)
@retrieval_bp.route("/moments/mappings", methods=["POST"])
@login_required
async def map_action_route():
return await _mapping_change(moment_actions_svc.map_action)
@retrieval_bp.route("/moments/mappings", methods=["DELETE"])
@login_required
async def unmap_action_route():
return await _mapping_change(moment_actions_svc.unmap_action)
@retrieval_bp.route("/moments/proposals", methods=["GET"])
@login_required
async def moment_proposals_route():
"""The moment proposals waiting on a judgment —
`rule_moment_proposals`' payload, from the same service. `?rule_id=`
narrows to one rule, for the rule editor."""
try:
rule_id = int(request.args.get("rule_id") or 0)
except ValueError:
return jsonify({"error": "rule_id must be a whole number"}), 400
return jsonify(await judgments_svc.pending(get_current_user_id(), rule_id=rule_id or None))
@retrieval_bp.route("/moments/proposals/judge", methods=["POST"])
@login_required
async def judge_moment_proposals_route():
"""Confirm or reject proposals: `{"judgments": [{rule_id, moment, verdict,
note}]}` — `judge_rule_moments` from the browser. A confirm mounts."""
data = await request.get_json(silent=True)
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
return jsonify(await judgments_svc.judge(get_current_user_id(), data["judgments"]))
+503
View File
@@ -0,0 +1,503 @@
"""Rulebook / topic REST endpoints.
Wraps services/rulebooks.py. Standard Grimoire auth: get_current_user_id() is the
authenticated owner; the service enforces ownership scoping.
"""
from __future__ import annotations
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
import grimoire.services.moments as moments_svc
import grimoire.services.rulebooks as rulebooks_svc
from grimoire.services.trash import delete as trash_delete
from grimoire.services.rule_usage import (
empty_rule_usage, record_rule_pulled, usage_for_rules,
)
rulebooks_bp = Blueprint("rulebooks", __name__, url_prefix="/api")
def _moments_or_refusal(data: dict):
"""The request's `moments`, validated BEFORE any write — so an unknown
name is a 400 and not a rule created without the mounts it asked for.
Absent means "leave them alone" (None), as on the MCP door."""
try:
return moments_svc.require_moments(data.get("moments")), None
except ValueError as exc:
return None, (jsonify({"error": str(exc)}), 400)
# ── Rulebooks ───────────────────────────────────────────────────────────
@rulebooks_bp.get("/rulebooks")
@login_required
async def list_rulebooks():
rows = await rulebooks_svc.list_rulebooks(get_current_user_id())
return jsonify({"rulebooks": [rb.to_dict() for rb in rows]})
@rulebooks_bp.post("/rulebooks")
@login_required
async def create_rulebook():
data = await request.get_json() or {}
title = (data.get("title") or "").strip()
if not title:
return jsonify({"error": "title is required"}), 400
rb = await rulebooks_svc.create_rulebook(
user_id=get_current_user_id(),
title=title,
description=data.get("description", ""),
)
return jsonify(rb.to_dict()), 201
@rulebooks_bp.get("/rulebooks/<int:rulebook_id>")
@login_required
async def get_rulebook(rulebook_id: int):
rb = await rulebooks_svc.get_rulebook(rulebook_id, get_current_user_id())
if rb is None:
return jsonify({"error": "rulebook not found"}), 404
return jsonify(rb.to_dict())
@rulebooks_bp.patch("/rulebooks/<int:rulebook_id>")
@login_required
async def update_rulebook(rulebook_id: int):
data = await request.get_json() or {}
fields = {k: v for k, v in data.items() if k in ("title", "description")}
rb = await rulebooks_svc.update_rulebook(rulebook_id, get_current_user_id(), **fields)
if rb is None:
return jsonify({"error": "rulebook not found"}), 404
return jsonify(rb.to_dict())
@rulebooks_bp.delete("/rulebooks/<int:rulebook_id>")
@login_required
async def delete_rulebook(rulebook_id: int):
await trash_delete(get_current_user_id(), "rulebook", rulebook_id)
return "", 204
# ── Topics ──────────────────────────────────────────────────────────────
@rulebooks_bp.get("/rulebooks/<int:rulebook_id>/topics")
@login_required
async def list_topics(rulebook_id: int):
try:
rows = await rulebooks_svc.list_topics(rulebook_id, get_current_user_id())
except ValueError as exc:
return jsonify({"error": str(exc)}), 404
return jsonify({"topics": [t.to_dict() for t in rows]})
@rulebooks_bp.post("/rulebooks/<int:rulebook_id>/topics")
@login_required
async def create_topic(rulebook_id: int):
data = await request.get_json() or {}
title = (data.get("title") or "").strip()
if not title:
return jsonify({"error": "title is required"}), 400
try:
topic = await rulebooks_svc.create_topic(
rulebook_id=rulebook_id,
user_id=get_current_user_id(),
title=title,
description=data.get("description", ""),
order_index=data.get("order_index", 0),
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 404
return jsonify(topic.to_dict()), 201
@rulebooks_bp.patch("/rulebook-topics/<int:topic_id>")
@login_required
async def update_topic(topic_id: int):
data = await request.get_json() or {}
fields = {
k: v for k, v in data.items()
if k in ("title", "description", "order_index")
}
topic = await rulebooks_svc.update_topic(topic_id, get_current_user_id(), **fields)
if topic is None:
return jsonify({"error": "topic not found"}), 404
return jsonify(topic.to_dict())
@rulebooks_bp.delete("/rulebook-topics/<int:topic_id>")
@login_required
async def delete_topic(topic_id: int):
if await trash_delete(get_current_user_id(), "topic", topic_id) is None:
return jsonify({"error": "topic not found"}), 404
return "", 204
# ── Rules ───────────────────────────────────────────────────────────────
@rulebooks_bp.get("/rules")
@login_required
async def list_rules():
def _opt_int(name):
raw = request.args.get(name)
return int(raw) if raw else None
try:
rulebook_id = _opt_int("rulebook_id")
topic_id = _opt_int("topic_id")
project_id = _opt_int("project_id")
except ValueError:
return jsonify({"error": "rulebook_id, topic_id, project_id must be integers"}), 400
uid = get_current_user_id()
rows = await rulebooks_svc.list_rules(
user_id=uid,
rulebook_id=rulebook_id,
topic_id=topic_id,
project_id=project_id,
)
items = [r.to_dict() for r in rows]
# One aggregate for the whole page — a per-row lookup here would be N+1 by
# construction, the same reason the snippet list does it this way. Every
# row gets the key, zero-filled, so the UI renders "never surfaced" rather
# than having to treat a missing field as a state. That matters more here
# than for snippets: every rule on every install predates this table, so
# for a while the zero-filled shape IS the common case.
usage = await usage_for_rules([int(it["id"]) for it in items])
# Zero-filled like `usage`, for the same reason: the UI renders "mounted
# nowhere" from an empty list rather than treating a missing key as a state.
mounted = await rulebooks_svc.list_rule_moments([int(it["id"]) for it in items])
for it in items:
it["usage"] = usage.get(int(it["id"]), empty_rule_usage())
it["moments"] = mounted.get(int(it["id"]), [])
return jsonify({"rules": items})
@rulebooks_bp.post("/rulebook-topics/<int:topic_id>/rules")
@login_required
async def create_rule(topic_id: int):
data = await request.get_json() or {}
title = (data.get("title") or "").strip()
statement = (data.get("statement") or "").strip()
if not title or not statement:
return jsonify({"error": "title and statement are required"}), 400
moments, refused = _moments_or_refusal(data)
if refused:
return refused
try:
rule = await rulebooks_svc.create_rule(
topic_id=topic_id,
user_id=get_current_user_id(),
title=title,
statement=statement,
why=data.get("why", ""),
how_to_apply=data.get("how_to_apply", ""),
order_index=data.get("order_index", 0),
when_to_apply=data.get("when_to_apply", ""),
# The human door carries `kind` too, and without the MCP door's
# required provenance: an operator editing their own preference
# owes nobody an explanation. That requirement is about auditing
# what the AGENT changed, not what they did themselves.
kind=data.get("kind", "rule"),
arose_from_id=data.get("arose_from_id", 0) or 0,
verify_with=data.get("verify_with", ""),
expires_when=data.get("expires_when", ""),
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 404
return jsonify(await rulebooks_svc.rule_detail(
get_current_user_id(), rule, data.get("system_ids"), moments,
)), 201
@rulebooks_bp.get("/rules/<int:rule_id>")
@login_required
async def get_rule(rule_id: int):
uid = get_current_user_id()
rule = await rulebooks_svc.get_rule(rule_id, uid)
if rule is None:
return jsonify({"error": "rule not found"}), 404
# `rest_` rather than `mcp_`, and the prefix is load-bearing: "is this rule
# dead weight?" is served by any pull, but "did that injected hint land?"
# — the question this arm exists to answer — is served by AGENT pulls only.
# A person clicking through the rule list says nothing about the hint.
record_rule_pulled(user_id=uid, rule_id=int(rule.id), source="rest_rule")
return jsonify(await rulebooks_svc.rule_detail(uid, rule))
@rulebooks_bp.patch("/rules/<int:rule_id>")
@login_required
async def update_rule(rule_id: int):
data = await request.get_json() or {}
uid = get_current_user_id()
fields = {
k: v for k, v in data.items()
if k in ("title", "statement", "why", "how_to_apply", "order_index",
"when_to_apply", "kind", "arose_from_id",
"verify_with", "expires_when")
}
# No clear_fields here: a form sends "" for an emptied input, and the
# service normalises "" to NULL for every nullable text column. The MCP
# door needs the explicit list only because "" already means "unchanged"
# there — two idioms, one outcome.
moments, refused = _moments_or_refusal(data)
if refused:
return refused
rule = await rulebooks_svc.update_rule(rule_id, uid, **fields)
if rule is None:
return jsonify({"error": "rule not found"}), 404
return jsonify(await rulebooks_svc.rule_detail(
uid, rule, data.get("system_ids"), moments,
))
@rulebooks_bp.get("/rules/<int:rule_id>/versions")
@login_required
async def list_rule_versions(rule_id: int):
"""A rule's edit history, newest first.
Listing form only — a rule's `statement` and `why` run to thousands of
characters, so a history list carrying every field would be unreadable
and expensive to send. Open one for the text.
"""
uid = get_current_user_id()
versions = await rulebooks_svc.list_rule_versions(rule_id, uid)
if versions is None:
return jsonify({"error": "rule not found"}), 404
return jsonify({
"versions": [v.to_dict(include_text=False) for v in versions],
})
@rulebooks_bp.get("/rules/<int:rule_id>/versions/<int:version_id>")
@login_required
async def get_rule_version(rule_id: int, version_id: int):
"""One snapshot in full — what the rule said before that edit."""
uid = get_current_user_id()
version = await rulebooks_svc.get_rule_version(rule_id, version_id, uid)
if version is None:
return jsonify({"error": "version not found"}), 404
return jsonify(version.to_dict(include_text=True))
# NO restore route FOR A RULE, deliberately. A note version
# can be restored; a binding instruction should not be revertible in one
# click. Putting a rewrite back goes through update_rule, which takes its own
# snapshot and leaves the undo in the history like any other edit — a silent
# revert would erase the only record of why the rewrite happened.
#
# A PREFERENCE IS THE EXCEPTION, and the route below refuses anything else.
# The reasoning above turns on the rewrite being the operator's own decision.
# A preference's rewrite is not: the agent makes it mid-work without asking,
# which is what the kind is for. Reverting one is a veto over someone else's
# edit rather than an undo of your own, and making that veto expensive leaves
# drift supervised in name only. The safeguard survives intact, because the restore goes through
# update_rule too: the rewrite stays in the history with the revert recorded
# after it, so the history gains an entry rather than losing one.
@rulebooks_bp.get("/rules/drift")
@login_required
async def preference_drift():
"""Preferences that have been rewritten, most recently changed first.
One row per preference carrying its latest rewrite, what it said before,
and the record that taught the change. `?limit=` caps the list.
"""
uid = get_current_user_id()
try:
limit = int(request.args.get("limit", 20))
except (TypeError, ValueError):
limit = 20
rows = await rulebooks_svc.recent_preference_drift(uid, limit=limit)
return jsonify({"drift": rows})
@rulebooks_bp.post("/rules/<int:rule_id>/versions/<int:version_id>/restore")
@login_required
async def restore_rule_version(rule_id: int, version_id: int):
"""Put a preference back to what that version said. Preferences only.
409 rather than 400 on a rule: the request is well-formed and the caller
is not wrong to have asked — this rule is simply in a state where the
action does not apply, and the message says which state and why.
"""
uid = get_current_user_id()
try:
rule = await rulebooks_svc.restore_rule_version(rule_id, version_id, uid)
except ValueError as exc:
return jsonify({"error": str(exc)}), 409
if rule is None:
return jsonify({"error": "rule or version not found"}), 404
return jsonify(await rulebooks_svc.rule_detail(uid, rule))
@rulebooks_bp.post("/rules/<int:rule_id>/relations")
@login_required
async def relate_rules(rule_id: int):
"""Draw a typed edge FROM this rule to another.
Body: {"to_rule_id": N, "kind": "co_surfaces"|"overrides"|"elaborates",
"note": "..."}. Idempotent — re-drawing an edge returns the existing one.
"""
data = await request.get_json() or {}
to_rule_id = data.get("to_rule_id")
if not isinstance(to_rule_id, int):
return jsonify({"error": "to_rule_id is required"}), 400
try:
relation = await rulebooks_svc.add_rule_relation(
get_current_user_id(), rule_id, to_rule_id,
data.get("kind", ""), data.get("note", ""),
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
if relation is None:
return jsonify({"error": "rule not found"}), 404
return jsonify(relation.to_dict()), 201
@rulebooks_bp.delete("/rule-relations/<int:relation_id>")
@login_required
async def unrelate_rules(relation_id: int):
if not await rulebooks_svc.remove_rule_relation(get_current_user_id(), relation_id):
return jsonify({"error": "relation not found"}), 404
return "", 204
@rulebooks_bp.post("/rules/<int:rule_id>/move")
@login_required
async def move_rule(rule_id: int):
"""Give a rule a new home: {topic_id} makes it global, {project_id} makes
it that project's. The MCP twin is move_rule, under the same names."""
data = await request.get_json() or {}
uid = get_current_user_id()
try:
rule = await rulebooks_svc.move_rule(
rule_id, uid,
topic_id=int(data.get("topic_id") or 0),
project_id=int(data.get("project_id") or 0),
)
except (TypeError, ValueError) as exc:
msg = str(exc)
return jsonify({"error": msg}), 404 if "not found" in msg else 400
if rule is None:
return jsonify({"error": "rule not found"}), 404
return jsonify(await rulebooks_svc.rule_detail(uid, rule))
@rulebooks_bp.delete("/rules/<int:rule_id>")
@login_required
async def delete_rule(rule_id: int):
if await trash_delete(get_current_user_id(), "rule", rule_id) is None:
return jsonify({"error": "rule not found"}), 404
return "", 204
# ── A project's rule listing ───────────────────────────────────────────
@rulebooks_bp.get("/projects/<int:project_id>/rules")
@login_required
async def get_project_rules(project_id: int):
result = await rulebooks_svc.get_applicable_rules(
project_id=project_id, user_id=get_current_user_id(),
)
return jsonify(result)
@rulebooks_bp.post("/projects/<int:project_id>/rules")
@login_required
async def create_project_rule(project_id: int):
"""Create a rule scoped to a single project. Frontend fast path."""
data = await request.get_json() or {}
statement = (data.get("statement") or "").strip()
if not statement:
return jsonify({"error": "statement is required"}), 400
# Checked here as well as in the service, only for the STATUS CODE: the
# service raises ValueError, which this route maps to 404 for "project not
# found", and a missing trigger is a 400. The service stays the guard —
# this is the door telling the truth about whose mistake it was.
if not (data.get("when_to_apply") or "").strip():
return jsonify({
"error": "when_to_apply is required: a rule with no trigger never "
"surfaces at the moment it applies."
}), 400
title = (data.get("title") or "").strip() or statement.split(".")[0][:50]
moments, refused = _moments_or_refusal(data)
if refused:
return refused
try:
rule = await rulebooks_svc.create_project_rule(
project_id=project_id,
user_id=get_current_user_id(),
title=title,
statement=statement,
why=data.get("why", ""),
how_to_apply=data.get("how_to_apply", ""),
order_index=data.get("order_index", 0),
when_to_apply=data.get("when_to_apply", ""),
# The human door carries `kind` too, and without the MCP door's
# required provenance: an operator editing their own preference
# owes nobody an explanation. That requirement is about auditing
# what the AGENT changed, not what they did themselves.
kind=data.get("kind", "rule"),
arose_from_id=data.get("arose_from_id", 0) or 0,
verify_with=data.get("verify_with", ""),
expires_when=data.get("expires_when", ""),
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 404
return jsonify(await rulebooks_svc.rule_detail(
get_current_user_id(), rule, data.get("system_ids"), moments,
)), 201
# ── The staleness sweep ────────────────────────────────────────────────
@rulebooks_bp.get("/rules-due-for-verification")
@login_required
async def rules_due_for_verification():
"""Rules that carry a check, oldest verification first, never-checked top.
Query params: older_than_days, never_only. A rule with no
`verify_with` never appears — it is a decision, not a fact.
"""
uid = get_current_user_id()
args = request.args
try:
older = int(args.get("older_than_days", 0) or 0)
except ValueError:
return jsonify({"error": "older_than_days must be an integer"}), 400
try:
rules = await rulebooks_svc.rules_due_for_verification(
uid,
older_than_days=older,
never_only=args.get("never_only", "").lower() in ("1", "true", "yes"),
)
except ValueError as exc:
# An unrecognised tier is a 400, not a silently narrowed result set:
# a filter that quietly answers a different question is the failure
# this whole surface exists to catch.
return jsonify({"error": str(exc)}), 400
return jsonify({
"rules": [rulebooks_svc.verification_row(r) for r in rules],
"total": len(rules),
})
@rulebooks_bp.post("/rules/<int:rule_id>/verify")
@login_required
async def mark_rule_verified(rule_id: int):
"""Record that the rule's check was run. Body: {"still_true": bool}.
`still_true: false` writes nothing — a rule whose check failed is wrong,
not in a recordable state — so it stays at the top of the sweep.
"""
data = await request.get_json() or {}
uid = get_current_user_id()
still_true = data.get("still_true", True)
rule = await rulebooks_svc.mark_rule_verified(rule_id, uid, bool(still_true))
if rule is None:
return jsonify({"error": "rule not found, or carries no verify_with"}), 404
payload = await rulebooks_svc.rule_detail(uid, rule)
payload["verified"] = bool(still_true)
return jsonify(payload)
+84
View File
@@ -0,0 +1,84 @@
import time
from quart import Blueprint, jsonify, request
from grimoire.auth import login_required, get_current_user_id
from grimoire.services.access import owner_names_for
from grimoire.services.embeddings import (
INTERACTIVE_SEARCH_THRESHOLD as _REST_SEARCH_THRESHOLD,
)
from grimoire.services.embeddings import semantic_search_notes
from grimoire.services.knowledge import content_type_filters
from grimoire.services.retrieval_telemetry import record_retrieval
# The interactive floor lives in embeddings.py, shared with Browse search and
# the list views' semantic `q` — one number, one rationale.
search_bp = Blueprint("search", __name__, url_prefix="/api/search")
@search_bp.route("", methods=["GET"])
@login_required
async def search_route():
uid = get_current_user_id()
q = (request.args.get("q") or "").strip()
if not q:
return jsonify({"error": "q is required"}), 400
limit = min(request.args.get("limit", 10, type=int), 50)
# Every kind the facet table declares, derived rather than mapped here, so
# no kind can fall through to "no filter" and silently return the whole
# corpus. An unknown kind is a 400 naming the ones that exist: a
# result set is an answer, and it should not be able to answer a question
# nobody asked.
try:
filters = content_type_filters(request.args.get("content_type", "all"))
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
is_task = filters.get("is_task")
# Same association filters the MCP tool takes. Optional, default global:
# the web UI searches through /api/knowledge, so this route serves API
# callers,
# and an API caller states its scope explicitly.
system_id = request.args.get("system_id", type=int)
project_id = request.args.get("project_id", type=int)
t0 = time.perf_counter()
report: dict = {}
results = await semantic_search_notes(
uid, q, limit=limit, **filters, threshold=_REST_SEARCH_THRESHOLD,
project_id=project_id, system_id=system_id,
# The user typed this, so it reaches everything they may read.
scope="read",
report=report,
)
record_retrieval(
user_id=uid, source="rest_search", query=q,
threshold=_REST_SEARCH_THRESHOLD, limit=limit,
project_id=project_id, is_task=is_task, results=results,
duration_ms=(time.perf_counter() - t0) * 1000.0,
best_available=report.get("best_available_score"),
best_available_id=report.get("best_available_id"),
searched=bool(report.get("searched", True)),
)
owners = await owner_names_for(
{int(note.user_id) for _s, note in results if note.user_id != uid}
)
return jsonify({
"results": [
{
"id": note.id,
"title": note.title,
"body": note.body or "",
"is_task": note.is_task,
"tags": note.tags or [],
"similarity": score,
**(
{"shared": True, "owner": owners.get(int(note.user_id))}
if note.user_id != uid else {}
),
}
for score, note in results # semantic_search_notes returns list[tuple[float, Note]]
],
"total": len(results),
})
+220
View File
@@ -0,0 +1,220 @@
"""User settings + integrations (SearXNG status)."""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import login_required, get_current_user_id
from grimoire.config import Config
from grimoire.services.retrieval_surfaces import dial_for_key, get_surface
from grimoire.services.retrieval_tuning import set_dial
from grimoire.services.settings import (
SECRET_MASK, delete_setting, get_all_settings, get_setting, set_settings_batch,
)
logger = logging.getLogger(__name__)
settings_bp = Blueprint("settings", __name__, url_prefix="/api/settings")
# Keys whose values are credentials. The admin endpoints that own them mask on
# read and skip the mask on write; this generic KV surface has to apply the
# same treatment, or it silently un-masks what those endpoints masked — the
# rows live on the admin's own user_id, so the plain GET returned them raw.
# (No forge_token here: forge credentials are keyring rows, since migration 0078.)
_SECRET_KEYS = frozenset({"smtp_password", "forge_webhook_secret"})
# What the tuning history records for a dial changed through this form. The MCP
# tool refuses a blank reason; the operator is not asked for one, because the
# requirement exists to make the MODEL read the records before moving a number
# on someone else's behalf — and the operator is that someone. See
# routes/retrieval.py, which states the asymmetry in full.
_SETTINGS_FORM_REASON = "Changed in Settings by the operator."
def _masked(settings: dict) -> dict:
return {
k: (SECRET_MASK if k in _SECRET_KEYS and v else v)
for k, v in settings.items()
}
@settings_bp.route("", methods=["GET"])
@login_required
async def get_settings_route():
uid = get_current_user_id()
settings = await get_all_settings(uid)
return jsonify(_masked(settings))
@settings_bp.route("", methods=["PUT"])
@login_required
async def update_settings_route():
uid = get_current_user_id()
data = await request.get_json()
if not isinstance(data, dict):
return jsonify({"error": "Expected a JSON object"}), 400
to_save = {}
for k, v in data.items():
str_v = str(v)
# A retrieval dial is never written as a plain settings row, wherever
# the request came from. The value would land correctly and the tuning
# history would say nothing happened — and since those dials are moved
# by the model on the operator's behalf, a history with holes in it is
# worse than none: it reads as complete.
#
# Routed rather than refused on purpose. Refusing would work only for
# callers that had been updated; this way every caller that ever writes
# one of these keys — this form, a script, an old client — leaves the
# trail, and there is no version of "forgot to use the other endpoint".
dial = dial_for_key(k)
if dial:
surface, which = dial
s = get_surface(surface)
# A CLEARED control means "back to the shipped starting point", and
# that is a change like any other — it is the operator reverting
# something, which is the single most important move this history
# can record. So it is written as an explicit set to the default
# rather than deleted, which would leave the same value behind and
# no record of anyone having chosen it.
default = s.floor_default if which == "floor" else s.budget_default
try:
await set_dial(uid, surface, which, float(str_v or default),
reason=_SETTINGS_FORM_REASON, actor="human")
except (TypeError, ValueError) as e:
return jsonify({"error": f"{k}: {e}"}), 400
continue
# A masked secret round-tripping through a client is "unchanged", not
# a request to store the mask over the real credential.
if k in _SECRET_KEYS and str_v == SECRET_MASK:
continue
if not str_v:
await delete_setting(uid, k)
else:
to_save[k] = str_v
if to_save:
await set_settings_batch(uid, to_save)
settings = await get_all_settings(uid)
return jsonify(_masked(settings))
@settings_bp.route("/search", methods=["GET"])
@login_required
async def test_search():
"""Report SearXNG configuration status (used by the Integrations tab)."""
if not Config.searxng_enabled():
return jsonify({"configured": False, "results": [], "searxng_url": ""})
return jsonify({"configured": True, "results": [], "searxng_url": Config.SEARXNG_URL})
# --- forge connections ---------------------------------------------------------
# The user's keyring: read-only forge credentials, one per host, resolved by
# repo host for every server-side forge read on the user's projects. Strictly
# own-rows — a connection is a credential, and there is no admin view of
# another user's keyring. Tokens never leave the server: the model's to_dict
# omits them, and the routes never echo the submitted value back.
@settings_bp.route("/forge-connections", methods=["GET"])
@login_required
async def list_forge_connections_route():
from grimoire.services.forge import FORGE_KINDS
from grimoire.services.forge_connections import connection_token, list_connections
uid = get_current_user_id()
rows = await list_connections(uid)
# Never the token: only whether this instance can still open it, so the
# page can ask for it again after a SECRET_KEY change.
return jsonify({
"connections": [
{**r.to_dict(), "token_readable": connection_token(r) is not None}
for r in rows
],
"kinds": list(FORGE_KINDS),
})
@settings_bp.route("/forge-connections", methods=["POST"])
@login_required
async def create_forge_connection_route():
from grimoire.services.forge_connections import create_connection
uid = get_current_user_id()
data = await request.get_json() or {}
try:
row = await create_connection(
uid,
kind=str(data.get("kind", "")),
base_url=str(data.get("base_url", "")),
token=str(data.get("token", "")),
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
return jsonify(row.to_dict()), 201
@settings_bp.route("/forge-connections/<int:connection_id>", methods=["PUT"])
@login_required
async def update_forge_connection_route(connection_id: int):
from grimoire.services.forge_connections import update_connection
uid = get_current_user_id()
data = await request.get_json() or {}
token = str(data.get("token", ""))
# The mask coming back means "unchanged" — the form round-trips what the
# list showed, and storing the mask would silently break the connection.
if token == SECRET_MASK:
token = ""
try:
row = await update_connection(
uid, connection_id,
kind=str(data.get("kind", "")),
base_url=str(data.get("base_url", "")),
token=token,
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
if row is None:
return jsonify({"error": "Connection not found"}), 404
return jsonify(row.to_dict())
@settings_bp.route("/forge-connections/<int:connection_id>", methods=["DELETE"])
@login_required
async def delete_forge_connection_route(connection_id: int):
from grimoire.services.forge_connections import delete_connection
uid = get_current_user_id()
if not await delete_connection(uid, connection_id):
return jsonify({"error": "Connection not found"}), 404
return "", 204
@settings_bp.route("/forge-connections/<int:connection_id>/test", methods=["POST"])
@login_required
async def test_forge_connection_route(connection_id: int):
"""Probe the SAVED connection: reachability and token acceptance in one
press, so a misconfiguration is visible now rather than as silent
fallbacks later, per keyring row."""
from grimoire.services.forge import ForgeError, build_adapter
from grimoire.services.forge_connections import connection_token, get_connection
uid = get_current_user_id()
row = await get_connection(uid, connection_id)
if row is None:
return jsonify({"error": "Connection not found"}), 404
token = connection_token(row)
if token is None:
return jsonify({
"error": "This instance can't read the saved token: SECRET_KEY has changed "
"since it was saved. Enter the token again."
}), 400
adapter = build_adapter(row.kind, row.base_url, token)
if adapter is None:
return jsonify({"error": "Connection is not usable — check kind and base URL"}), 400
try:
return jsonify(await adapter.check())
except ForgeError as exc:
return jsonify({"error": str(exc)}), 502
+128
View File
@@ -0,0 +1,128 @@
import asyncio
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.services import sharing as share_svc
from grimoire.services.access import can_admin_project, can_write_note
from grimoire.services.notifications import notify_note_shared, notify_project_shared
from grimoire.services.sharing import list_shared_with_me
shares_bp = Blueprint("shares", __name__)
# ---------------------------------------------------------------------------
# Project shares
# ---------------------------------------------------------------------------
@shares_bp.route("/api/projects/<int:project_id>/shares", methods=["GET"])
@login_required
async def list_project_shares(project_id: int):
uid = get_current_user_id()
if not await can_admin_project(uid, project_id):
return jsonify({"error": "Forbidden"}), 403
return jsonify({"shares": await share_svc.list_project_shares(project_id)})
@shares_bp.route("/api/projects/<int:project_id>/shares", methods=["POST"])
@login_required
async def create_project_share(project_id: int):
uid = get_current_user_id()
data = await request.get_json()
share = await share_svc.share_project(
uid, project_id,
target_user_id=data.get("user_id"),
target_group_id=data.get("group_id"),
permission=data.get("permission", "viewer"),
)
if not share:
return jsonify({"error": "Forbidden or invalid permission"}), 403
asyncio.create_task(notify_project_shared(
project_id, share.permission, uid,
data.get("user_id"), data.get("group_id"),
))
return jsonify(share.to_dict()), 201
@shares_bp.route("/api/projects/<int:project_id>/shares/<int:share_id>", methods=["PATCH"])
@login_required
async def update_project_share(project_id: int, share_id: int):
uid = get_current_user_id()
data = await request.get_json()
share = await share_svc.update_project_share(uid, share_id, data.get("permission", ""))
if not share:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify(share.to_dict())
@shares_bp.route("/api/projects/<int:project_id>/shares/<int:share_id>", methods=["DELETE"])
@login_required
async def remove_project_share(project_id: int, share_id: int):
uid = get_current_user_id()
if not await share_svc.remove_project_share(uid, share_id):
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify({"status": "ok"})
# ---------------------------------------------------------------------------
# Note / task shares
# ---------------------------------------------------------------------------
@shares_bp.route("/api/notes/<int:note_id>/shares", methods=["GET"])
@login_required
async def list_note_shares(note_id: int):
uid = get_current_user_id()
if not await can_write_note(uid, note_id):
return jsonify({"error": "Forbidden"}), 403
return jsonify({"shares": await share_svc.list_note_shares(note_id)})
@shares_bp.route("/api/notes/<int:note_id>/shares", methods=["POST"])
@login_required
async def create_note_share(note_id: int):
uid = get_current_user_id()
data = await request.get_json()
share = await share_svc.share_note(
uid, note_id,
target_user_id=data.get("user_id"),
target_group_id=data.get("group_id"),
permission=data.get("permission", "viewer"),
)
if not share:
return jsonify({"error": "Forbidden or invalid permission"}), 403
asyncio.create_task(notify_note_shared(
note_id, share.permission, uid,
data.get("user_id"), data.get("group_id"),
))
return jsonify(share.to_dict()), 201
@shares_bp.route("/api/notes/<int:note_id>/shares/<int:share_id>", methods=["PATCH"])
@login_required
async def update_note_share(note_id: int, share_id: int):
uid = get_current_user_id()
data = await request.get_json()
share = await share_svc.update_note_share(uid, share_id, data.get("permission", ""))
if not share:
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify(share.to_dict())
@shares_bp.route("/api/notes/<int:note_id>/shares/<int:share_id>", methods=["DELETE"])
@login_required
async def remove_note_share(note_id: int, share_id: int):
uid = get_current_user_id()
if not await share_svc.remove_note_share(uid, share_id):
return jsonify({"error": "Not found or forbidden"}), 404
return jsonify({"status": "ok"})
# ---------------------------------------------------------------------------
# Shared-with-me
# ---------------------------------------------------------------------------
@shares_bp.route("/api/shared-with-me", methods=["GET"])
@login_required
async def shared_with_me():
uid = get_current_user_id()
return jsonify(await list_shared_with_me(uid))
+362
View File
@@ -0,0 +1,362 @@
"""REST routes for snippets — reusable functions/components recorded for recall.
A snippet is a note with note_type='snippet' (see services/snippets.py). These
routes feed the web management UI; the MCP tools (mcp/tools/snippets.py) are the
agent-facing surface. Both go through services/snippets.py, so the
serialize/parse contract and embedding-on-create live in one place (DRY).
ACL: reads/writes of a single snippet resolve through the share-aware
`get_note_for_user` + `can_write_note`, and writes are performed as the OWNER so
a shared editor isn't rejected by the owner-scoped service — mirroring
routes/notes.py. The list is owner-scoped, matching the note-browse surface.
"""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.routes.utils import not_found, parse_pagination
from grimoire.services import dedup as dedup_svc
from grimoire.services import snippets as snippets_svc
from grimoire.services import systems as systems_svc
from grimoire.services.note_usage import attach_usage, record_pulled
from grimoire.services.access import (
can_write_note,
describe_provenance,
label_shared_items,
)
from grimoire.services.notes import get_note_for_user
logger = logging.getLogger(__name__)
snippets_bp = Blueprint("snippets", __name__, url_prefix="/api/snippets")
# Fields the create/update payload may carry, mapped straight to the service.
_STR_FIELDS = (
"name", "code", "language", "signature", "when_to_use", "repo", "path", "symbol",
"notes",
)
async def _load_snippet(uid: int, snippet_id: int):
"""Share-aware resolve of a snippet by id → (note, permission) or None if it
isn't accessible or isn't a snippet."""
result = await get_note_for_user(uid, snippet_id)
if result is None:
return None
note, permission = result
if note.note_type != snippets_svc.SNIPPET_NOTE_TYPE:
return None
return note, permission
@snippets_bp.route("", methods=["GET"])
@login_required
async def list_snippets_route():
uid = get_current_user_id()
q = request.args.get("q") or None
tag = request.args.get("tag", "")
try:
project_id = int(request.args.get("project_id", 0) or 0) or None
except (TypeError, ValueError):
project_id = None
# Reverse lookup — "what already lives here?" Empty args are ignored, so the
# plain list is unchanged.
repo = request.args.get("repo", "")
path = request.args.get("path", "")
symbol = request.args.get("symbol", "")
# Drift check. "attention" is what the UI's filter chip sends.
verification = request.args.get("verification", "")
limit, offset = parse_pagination()
items, total = await snippets_svc.list_snippets(
uid, q=q, tag=tag, limit=limit, offset=offset, project_id=project_id,
repo=repo, path=path, symbol=symbol, verification=verification,
)
# Mark rows owned by someone else so the UI can show whose they are — an
# unmarked row in your own list reads as one you recorded and vetted.
items = await label_shared_items(uid, items)
# One aggregate for the whole page — a per-row lookup here would be N+1 by
# construction. Every row gets the key, zero-filled, so the UI renders
# "never pulled" rather than having to treat a missing field as a state.
await attach_usage(items)
return jsonify({"snippets": items, "total": total})
@snippets_bp.route("", methods=["POST"])
@login_required
async def create_snippet_route():
uid = get_current_user_id()
data = await request.get_json() or {}
name = (data.get("name") or "").strip()
code = (data.get("code") or "").strip()
if not name or not code:
return jsonify({"error": "name and code are required"}), 400
project_id = data.get("project_id") or None
# Same near-duplicate gate the MCP create path applies: recording the same
# reusable thing twice is what merge then has to undo, so catch it here too.
# `force` is the deliberate override once the operator has seen the warning.
if not data.get("force"):
dup = await dedup_svc.find_duplicate_note(
uid,
name.strip(),
snippets_svc.compose_body(
code=data.get("code", ""),
language=data.get("language", ""),
signature=data.get("signature", ""),
when_to_use=data.get("when_to_use", ""),
repo=data.get("repo", ""),
path=data.get("path", ""),
symbol=data.get("symbol", ""),
locations=data.get("locations"),
notes=data.get("notes", ""),
),
project_id=project_id,
is_task=False,
note_type=snippets_svc.SNIPPET_NOTE_TYPE,
# Matched on the artefact — location and code — before prose, the
# same way the MCP create path does. Both surfaces must
# apply the identical gate or the web UI becomes the way to record
# a duplicate the agent would have been stopped from writing.
code=data.get("code", ""),
locations=snippets_svc.resolve_locations(
data.get("repo", ""), data.get("path", ""), data.get("symbol", ""),
data.get("locations"),
),
data=snippets_svc.compose_data(
name=name, when_to_use=data.get("when_to_use", ""),
),
)
if dup is not None:
return jsonify(dedup_svc.duplicate_response(dup, "snippet")), 409
note = await snippets_svc.create_snippet(
uid,
name=name,
code=data.get("code", ""),
language=data.get("language", ""),
signature=data.get("signature", ""),
when_to_use=data.get("when_to_use", ""),
repo=data.get("repo", ""),
path=data.get("path", ""),
symbol=data.get("symbol", ""),
locations=data.get("locations"),
tags=data.get("tags"),
project_id=project_id,
notes=data.get("notes", ""),
)
if data.get("system_ids") is not None:
await systems_svc.set_record_systems(uid, note.id, data["system_ids"])
out = snippets_svc.snippet_to_dict(note)
out["systems"] = [
s.to_dict() for s in await systems_svc.list_record_systems(uid, note.id)
]
return jsonify(out), 201
@snippets_bp.route("/<int:snippet_id>", methods=["GET"])
@login_required
async def get_snippet_route(snippet_id: int):
uid = get_current_user_id()
loaded = await _load_snippet(uid, snippet_id)
if loaded is None:
return not_found("Snippet")
note, permission = loaded
data = snippets_svc.snippet_to_dict(note)
# Forge-checked freshness — same decoration the MCP pull gets.
await snippets_svc.attach_live_body(note, data)
data["permission"] = permission
# Read the association as the OWNER: a shared reader isn't scoped to the
# owner's project, so their own id would come back empty (mirrors the
# write-as-owner pattern this module already uses).
data["systems"] = [
s.to_dict()
for s in await systems_svc.list_record_systems(note.user_id, snippet_id)
]
data.update(await describe_provenance(uid, note))
await attach_usage([data])
# Opening the detail view IS a pull — the operator chose to look. Tagged
# apart from the MCP sources so "the agent reused it" and "a human read it"
# stay distinguishable; they mean different things for pruning.
record_pulled(user_id=uid, note_id=snippet_id, source="rest_snippet")
return jsonify(data)
@snippets_bp.route("/<int:snippet_id>", methods=["PATCH"])
@login_required
async def update_snippet_route(snippet_id: int):
uid = get_current_user_id()
loaded = await _load_snippet(uid, snippet_id)
if loaded is None:
return not_found("Snippet")
note, _ = loaded
if not await can_write_note(uid, snippet_id):
return jsonify({"error": "Permission denied"}), 403
owner_uid = note.user_id
data = await request.get_json() or {}
# Partial update: only keys present in the payload change (the service
# treats None as "leave unchanged"). Empty strings ARE applied — the form
# sends the full field set, so a cleared field is an intentional clear.
kwargs = {k: data[k] for k in _STR_FIELDS if k in data}
if "locations" in data:
kwargs["locations"] = data["locations"]
if "tags" in data:
kwargs["tags"] = data["tags"]
if "project_id" in data:
# A present-but-empty project_id is a deliberate detach, not "unchanged"
# — the service distinguishes the two via its UNSET sentinel.
kwargs["project_id"] = data["project_id"] or None
updated = await snippets_svc.update_snippet(owner_uid, snippet_id, **kwargs)
if updated is None:
return not_found("Snippet")
if data.get("system_ids") is not None:
# The CALLER, not owner_uid — see routes/lessons.py for the why.
await systems_svc.set_record_systems(uid, snippet_id, data["system_ids"])
out = snippets_svc.snippet_to_dict(updated)
out["systems"] = [
s.to_dict() for s in await systems_svc.list_record_systems(owner_uid, snippet_id)
]
return jsonify(out)
@snippets_bp.route("/<int:snippet_id>/unmerge", methods=["POST"])
@login_required
async def unmerge_snippet_route(snippet_id: int):
"""Pull one source back out of a merged survivor. Body: {"source_id": int}.
Also the repair for a half-undone merge: restoring a source from the trash by
hand leaves the survivor still claiming its call sites, and running this on an
already-restored source strips them."""
uid = get_current_user_id()
data = await request.get_json() or {}
source_id = data.get("source_id")
if not isinstance(source_id, int):
return jsonify({"error": "source_id (int) is required"}), 400
try:
result = await snippets_svc.unmerge_snippet(uid, snippet_id, source_id)
except PermissionError as exc:
return jsonify({"error": str(exc)}), 403
except snippets_svc.UnmergeError as exc:
# 409, not 400: the request is well-formed, the record's state is what
# makes it impossible — and the message says which.
return jsonify({"error": str(exc)}), 409
if result is None:
return not_found("Snippet")
survivor, restored = result
return jsonify({
"survivor": snippets_svc.snippet_to_dict(survivor),
"restored": snippets_svc.snippet_to_dict(restored) if restored else None,
})
@snippets_bp.route("/duplicates", methods=["GET"])
@login_required
async def duplicate_snippets_route():
"""Near-duplicate snippets already recorded, grouped into merge candidates.
Registered ABOVE the `/<int:snippet_id>` routes on purpose — Quart matches
an int converter before a static segment either way, but keeping the literal
path first makes the precedence obvious to the next person reading this."""
uid = get_current_user_id()
try:
threshold = float(request.args.get("threshold", 0) or 0)
except (TypeError, ValueError):
threshold = 0.0
return jsonify(await dedup_svc.find_duplicate_snippets(
uid, threshold=threshold if threshold > 0 else None
))
@snippets_bp.route("/<int:snippet_id>/verify", methods=["POST"])
@login_required
async def verify_snippet_route(snippet_id: int):
"""Record a drift-check verdict. Body: {"status": ..., "detail", "path"}.
The CHECK itself runs wherever the code is — an agent with the working tree
— because Grimoire has no checkout and shouldn't have one. This endpoint just
stores what was found. It's here for parity with the MCP tool and so the UI
can clear a stale marker after the operator fixes a record by hand."""
uid = get_current_user_id()
if await _load_snippet(uid, snippet_id) is None:
return not_found("Snippet")
# Distinguished from not-found deliberately: the service returns None for
# both, and telling a shared reader "no such snippet" about one they can
# plainly see is a confusing lie.
if not await can_write_note(uid, snippet_id):
return jsonify({"error": "Permission denied"}), 403
data = await request.get_json() or {}
status = (data.get("status") or "").strip()
if not status:
return jsonify({"error": "status is required"}), 400
try:
updated = await snippets_svc.record_verification(
uid, snippet_id,
status=status,
detail=data.get("detail") or "",
path=data.get("path") or "",
)
except ValueError as exc:
# An unknown status — reject it rather than storing a value the filter
# would then never match.
return jsonify({"error": str(exc)}), 400
if updated is None:
return not_found("Snippet")
return jsonify(snippets_svc.snippet_to_dict(updated))
@snippets_bp.route("/<int:snippet_id>/merge", methods=["POST"])
@login_required
async def merge_snippet_route(snippet_id: int):
"""Unify source snippets into this one (the canonical target). Body:
{"source_ids": [int, ...]}. Requires write on the target and every source,
and all must share the target's owner (cross-owner merge is out of scope)."""
uid = get_current_user_id()
loaded = await _load_snippet(uid, snippet_id)
if loaded is None:
return not_found("Snippet")
target, _ = loaded
if not await can_write_note(uid, snippet_id):
return jsonify({"error": "Permission denied"}), 403
data = await request.get_json() or {}
raw = data.get("source_ids") or []
source_ids = [s for s in raw if isinstance(s, int) and s != snippet_id]
if not source_ids:
return jsonify({"error": "source_ids (non-empty list of other snippet ids) is required"}), 400
owner_uid = target.user_id
for sid in source_ids:
sloaded = await _load_snippet(uid, sid)
if sloaded is None:
return not_found(f"Snippet {sid}")
snote, _ = sloaded
if snote.user_id != owner_uid:
return jsonify({"error": "can only merge snippets with the same owner"}), 400
if not await can_write_note(uid, sid):
return jsonify({"error": f"Permission denied for snippet {sid}"}), 403
result = await snippets_svc.merge_snippets(owner_uid, snippet_id, source_ids)
if result is None:
return not_found("Snippet")
note, merged_ids = result
out = snippets_svc.snippet_to_dict(note)
out["merged_ids"] = merged_ids
return jsonify(out)
@snippets_bp.route("/<int:snippet_id>", methods=["DELETE"])
@login_required
async def delete_snippet_route(snippet_id: int):
uid = get_current_user_id()
loaded = await _load_snippet(uid, snippet_id)
if loaded is None:
return not_found("Snippet")
note, _ = loaded
if not await can_write_note(uid, snippet_id):
return jsonify({"error": "Permission denied"}), 403
if not await snippets_svc.delete_snippet(note.user_id, snippet_id):
return not_found("Snippet")
return "", 204
+191
View File
@@ -0,0 +1,191 @@
"""System routes nested under /api/projects/<project_id>/systems, plus the
project's open-issues list. A System is a per-project, reusable subsystem/area
that records (notes/tasks/issues) associate with."""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import login_required, get_current_user_id
from grimoire.routes.utils import not_found
from grimoire.services import systems as systems_svc
from grimoire.services.access import can_write_project
from grimoire.services.projects import get_project_for_user
from grimoire.services import system_usage as system_usage_svc
logger = logging.getLogger(__name__)
systems_bp = Blueprint("systems", __name__, url_prefix="/api/projects")
def _truthy(v: str | None) -> bool:
return (v or "").lower() in ("1", "true", "yes")
def _split_records(records: list) -> tuple[list, list, list]:
issues, tasks, notes = [], [], []
for r in records:
d = r.to_dict()
if r.status is None:
notes.append(d)
elif r.task_kind == "issue":
issues.append(d)
else:
tasks.append(d)
return issues, tasks, notes
@systems_bp.route("/<int:project_id>/systems", methods=["GET"])
@login_required
async def list_systems_route(project_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
systems = await systems_svc.list_systems(
uid, project_id, include_archived=_truthy(request.args.get("include_archived")),
)
counts = await systems_svc.open_issue_counts_by_system(uid, project_id)
# How often each area's rulings reached a session — one GROUP BY
# for the page, and a zero shape for an area nothing has touched.
usage = await system_usage_svc.usage_for_systems([s.id for s in systems])
out = []
for s in systems:
d = s.to_dict()
d["open_issue_count"] = counts.get(s.id, 0)
d["usage"] = usage.get(s.id, system_usage_svc.empty_system_usage())
out.append(d)
return jsonify({"systems": out})
@systems_bp.route("/<int:project_id>/systems", methods=["POST"])
@login_required
async def create_system_route(project_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
if not await can_write_project(uid, project_id):
return jsonify({"error": "Permission denied"}), 403
data = await request.get_json() or {}
if not (data.get("name") or "").strip():
return jsonify({"error": "name is required"}), 400
# The same gate the MCP door enforces — one service call, one answer, so
# neither door ships without a gate the other has.
assessment = await systems_svc.assess_system_name(uid, project_id, data["name"])
duplicate = assessment["duplicate"]
if duplicate and not data.get("force"):
return jsonify({
"duplicate": True,
"existing_id": duplicate["id"],
"error": (
f"“{duplicate['name']}” already covers this area in this "
"project. Tag records to it, or rename it if its charter has "
"moved on — a second System with the same name splits the "
"area's records across two piles."
),
}), 409
canonical = assessment["canonical"]
# Exact is mechanical and applied; overlap is a judgment call and is only
# offered back for the form to present.
applied = canonical["id"] if canonical and canonical["basis"] == "exact" else None
try:
system = await systems_svc.create_system(
uid, project_id=project_id, name=data["name"],
description=data.get("description"), color=data.get("color"),
order_index=data.get("order_index", 0),
canonical_id=data.get("canonical_id") or applied,
path_patterns=data.get("path_patterns"),
)
except ValueError as e:
return jsonify({"error": str(e)}), 400
if system is None:
return jsonify({"error": "Permission denied"}), 403
out = system.to_dict()
if canonical and canonical["basis"] == "overlap" and not system.canonical_id:
out["canonical_suggestion"] = canonical
return jsonify(out), 201
@systems_bp.route("/<int:project_id>/systems/<int:system_id>", methods=["GET"])
@login_required
async def get_system_route(project_id: int, system_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
system = await systems_svc.get_system(uid, system_id)
if system is None or system.project_id != project_id:
return not_found("System")
issues, tasks, notes = _split_records(
await systems_svc.list_records_for_system(uid, system_id)
)
data = system.to_dict()
data["issues"], data["tasks"], data["notes"] = issues, tasks, notes
data["usage"] = (await system_usage_svc.usage_for_systems([system.id]))[system.id]
return jsonify(data)
@systems_bp.route("/<int:project_id>/systems/<int:system_id>", methods=["PATCH"])
@login_required
async def update_system_route(project_id: int, system_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
if not await can_write_project(uid, project_id):
return jsonify({"error": "Permission denied"}), 403
system = await systems_svc.get_system(uid, system_id)
if system is None or system.project_id != project_id:
return not_found("System")
data = await request.get_json() or {}
allowed = {"name", "description", "color", "status", "order_index", "path_patterns"}
fields = {k: v for k, v in data.items() if k in allowed}
if "status" in fields and fields["status"] not in ("active", "archived"):
return jsonify({"error": "status must be 'active' or 'archived'"}), 400
try:
updated = await systems_svc.update_system(uid, system_id, **fields)
except ValueError as e:
return jsonify({"error": str(e)}), 400
if updated is None:
return not_found("System")
return jsonify(updated.to_dict())
@systems_bp.route("/<int:project_id>/systems/<int:system_id>", methods=["DELETE"])
@login_required
async def delete_system_route(project_id: int, system_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
if not await can_write_project(uid, project_id):
return jsonify({"error": "Permission denied"}), 403
system = await systems_svc.get_system(uid, system_id)
if system is None or system.project_id != project_id:
return not_found("System")
await systems_svc.delete_system(uid, system_id)
return "", 204
@systems_bp.route("/<int:project_id>/systems/<int:system_id>/records", methods=["GET"])
@login_required
async def system_records_route(project_id: int, system_id: int):
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
system = await systems_svc.get_system(uid, system_id)
if system is None or system.project_id != project_id:
return not_found("System")
records = await systems_svc.list_records_for_system(
uid, system_id,
kind=request.args.get("kind") or None,
open_only=_truthy(request.args.get("open_only")),
)
return jsonify({"records": [r.to_dict() for r in records]})
@systems_bp.route("/<int:project_id>/issues", methods=["GET"])
@login_required
async def project_issues_route(project_id: int):
"""A project's issues (open by default — pass open_only=false for all)."""
uid = get_current_user_id()
if await get_project_for_user(uid, project_id) is None:
return not_found("Project")
open_only = request.args.get("open_only", "true").lower() in ("1", "true", "yes")
issues = await systems_svc.list_issues(uid, project_id, open_only=open_only)
return jsonify({"issues": [n.to_dict() for n in issues]})
+68
View File
@@ -0,0 +1,68 @@
"""Task work log routes — /api/tasks/<task_id>/logs."""
import logging
from quart import Blueprint, jsonify, request
from grimoire.auth import get_current_user_id, login_required
from grimoire.services.task_logs import create_log, delete_log, list_logs, update_log
logger = logging.getLogger(__name__)
task_logs_bp = Blueprint("task_logs", __name__, url_prefix="/api/tasks")
@task_logs_bp.route("/<int:task_id>/logs", methods=["GET"])
@login_required
async def list_logs_route(task_id: int):
uid = get_current_user_id()
logs = await list_logs(uid, task_id)
return jsonify({"logs": [log.to_dict() for log in logs]})
@task_logs_bp.route("/<int:task_id>/logs", methods=["POST"])
@login_required
async def create_log_route(task_id: int):
uid = get_current_user_id()
data = await request.get_json()
content = (data or {}).get("content", "").strip()
if not content:
return jsonify({"error": "content is required"}), 400
duration_minutes = (data or {}).get("duration_minutes")
if duration_minutes is not None:
try:
duration_minutes = int(duration_minutes)
except (TypeError, ValueError):
return jsonify({"error": "duration_minutes must be an integer"}), 400
try:
log = await create_log(uid, task_id, content, duration_minutes)
except ValueError as e:
return jsonify({"error": str(e)}), 404
return jsonify(log.to_dict()), 201
@task_logs_bp.route("/<int:task_id>/logs/<int:log_id>", methods=["PATCH"])
@login_required
async def update_log_route(task_id: int, log_id: int):
uid = get_current_user_id()
data = await request.get_json() or {}
content = data.get("content")
if content is not None:
content = content.strip() or None
from grimoire.services.task_logs import _UNSET
duration_minutes = data.get("duration_minutes", _UNSET)
log = await update_log(uid, log_id, content=content, duration_minutes=duration_minutes)
if log is None:
return jsonify({"error": "Log entry not found"}), 404
return jsonify(log.to_dict())
@task_logs_bp.route("/<int:task_id>/logs/<int:log_id>", methods=["DELETE"])
@login_required
async def delete_log_route(task_id: int, log_id: int):
uid = get_current_user_id()
deleted = await delete_log(uid, log_id)
if not deleted:
return jsonify({"error": "Log entry not found"}), 404
return "", 204
+338
View File
@@ -0,0 +1,338 @@
from datetime import date
from quart import Blueprint, jsonify, request
from grimoire.auth import login_required, get_current_user_id
from grimoire.models.note import TaskPriority, TaskStatus
from grimoire.routes.utils import not_found, parse_iso_date, parse_pagination
from grimoire.services.access import can_write_note
from grimoire.services import placement as placement_svc
from grimoire.services import systems as systems_svc
from grimoire.services.notes import (
create_note,
get_note_for_user,
list_notes,
update_note,
)
from grimoire.services.notes import minted_kind as notes_minted_kind
from grimoire.services.note_usage import record_pulled
from grimoire.services.planning import start_planning as svc_start_planning
from grimoire.services.recurrence import calculate_next_due, validate_recurrence_rule
tasks_bp = Blueprint("tasks", __name__, url_prefix="/api/tasks")
_UNSET = object()
def _parse_recurrence_rule(data: dict) -> tuple[object, tuple | None]:
"""Extract and validate recurrence_rule from request data.
Returns (rule_or_UNSET, error_response_or_None):
_UNSET → key not present, do nothing
None → key present and null, clear the rule
dict → key present and valid, set the rule
"""
if "recurrence_rule" not in data:
return _UNSET, None
rule = data["recurrence_rule"]
if rule is None:
return None, None
try:
validate_recurrence_rule(rule)
except ValueError as exc:
return _UNSET, (jsonify({"error": str(exc)}), 400)
return rule, None
@tasks_bp.route("", methods=["GET"])
@login_required
async def list_tasks_route():
uid = get_current_user_id()
q = request.args.get("q")
tag = request.args.getlist("tag")
status = request.args.getlist("status") or None
priority = request.args.getlist("priority") or None
sort = request.args.get("sort", "updated_at")
order = request.args.get("order", "desc")
limit, offset = parse_pagination()
project_id = request.args.get("project_id", type=int)
no_project = request.args.get("no_project", "").lower() == "true"
kind = request.args.get("kind") or None
due_before = parse_iso_date(request.args.get("due_before"), "due_before")
if isinstance(due_before, tuple):
return due_before
due_after = parse_iso_date(request.args.get("due_after"), "due_after")
if isinstance(due_after, tuple):
return due_after
tasks, total = await list_notes(
uid,
q=q,
tags=tag or None,
is_task=True,
status=status,
priority=priority,
due_before=due_before,
due_after=due_after,
project_id=project_id,
task_kind=kind,
no_project=no_project,
sort=sort,
order=order,
limit=limit,
offset=offset,
)
return jsonify({"tasks": [t.to_dict() for t in tasks], "total": total})
@tasks_bp.route("", methods=["POST"])
@login_required
async def create_task_route():
uid = get_current_user_id()
data = await request.get_json()
# Description (user-stated goal) and body (machine-maintained summary) are
# separate fields under the task-as-durable-record design. Don't fold one
# into the other.
body = data.get("body", "")
description = data.get("description")
tags = data.get("tags", [])
# kind=plan is retired — plans are milestones now (see start_planning).
# The 'plan' enum value stays valid for legacy tasks, but new ones can't
# be created with it through any path.
if data.get("kind") == "plan":
return jsonify({
"error": "kind=plan is retired — plans are milestones. "
"Use POST /api/tasks/planning to start a plan."
}), 400
due_date = parse_iso_date(data.get("due_date"), "due_date")
if isinstance(due_date, tuple):
return due_date
try:
status = TaskStatus(data["status"]).value if "status" in data else TaskStatus.todo.value
except ValueError:
return jsonify({"error": f"Invalid status: {data['status']}"}), 400
try:
priority = TaskPriority(data["priority"]).value if "priority" in data else TaskPriority.none.value
except ValueError:
return jsonify({"error": f"Invalid priority: {data['priority']}"}), 400
recurrence_rule, recurrence_err = _parse_recurrence_rule(data)
if recurrence_err:
return recurrence_err
project_id = data.get("project_id")
if project_id is None and data.get("project"):
from grimoire.services.projects import get_project_by_title as _gpbt
proj = await _gpbt(uid, data["project"])
if proj:
project_id = proj.id
task = await create_note(
uid,
title=data.get("title", ""),
body=body,
description=description,
status=status,
priority=priority,
due_date=due_date,
tags=tags,
project_id=project_id,
milestone_id=data.get("milestone_id"),
parent_id=data.get("parent_id"),
recurrence_rule=recurrence_rule if recurrence_rule is not _UNSET else None,
task_kind=data.get("kind", "work"),
arose_from_id=data.get("arose_from_id"),
)
if data.get("system_ids") is not None:
await systems_svc.set_record_systems(uid, task.id, data["system_ids"])
out = task.to_dict()
out["systems"] = [s.to_dict() for s in await systems_svc.list_record_systems(uid, task.id)]
await placement_svc.attach_placement(uid, out, task)
return jsonify(out), 201
@tasks_bp.route("/planning", methods=["POST"])
@login_required
async def start_planning_route():
uid = get_current_user_id()
data = await request.get_json() or {}
project_id = data.get("project_id")
title = (data.get("title") or "").strip()
if not project_id or not title:
return jsonify({"error": "project_id and title are required"}), 400
try:
result = await svc_start_planning(
user_id=uid, project_id=int(project_id), title=title,
)
except ValueError as exc:
return jsonify({"error": str(exc)}), 404
return jsonify(result), 201
@tasks_bp.route("/<int:task_id>", methods=["GET"])
@login_required
async def get_task_route(task_id: int):
uid = get_current_user_id()
result = await get_note_for_user(uid, task_id)
if result is None:
return not_found("Task")
task, permission = result
data = task.to_dict()
data["permission"] = permission
if task.parent_id:
# Share-aware like the task itself: a shared subtask whose parent is also
# shared would otherwise render as an orphan with no parent title.
parent = await get_note_for_user(uid, task.parent_id)
data["parent_title"] = parent[0].title if parent else None
data["systems"] = [s.to_dict() for s in await systems_svc.list_record_systems(uid, task_id)]
# Opening the detail view IS a pull — see the note beside rest_note in
# routes/notes.py for why the rest_* and mcp_* prefixes stay separable.
record_pulled(user_id=uid, note_id=task_id, source="rest_task")
return jsonify(data)
@tasks_bp.route("/<int:task_id>", methods=["PUT", "PATCH"])
@login_required
async def update_task_route(task_id: int):
uid = get_current_user_id()
result = await get_note_for_user(uid, task_id)
if result is None:
return not_found("Task")
task_note, _ = result
if not await can_write_note(uid, task_id):
return jsonify({"error": "Permission denied"}), 403
data = await request.get_json()
fields = {}
for key in ("title",):
if key in data:
fields[key] = data[key]
if "status" in data:
try:
fields["status"] = TaskStatus(data["status"]).value
except ValueError:
return jsonify({"error": f"Invalid status: {data['status']}"}), 400
if "priority" in data:
try:
fields["priority"] = TaskPriority(data["priority"]).value
except ValueError:
return jsonify({"error": f"Invalid priority: {data['priority']}"}), 400
# Body and description are distinct fields under the task-as-durable-record
# design. Don't alias one to the other.
if "body" in data:
fields["body"] = data["body"]
if "description" in data:
fields["description"] = data["description"]
if "due_date" in data:
if data["due_date"]:
result = parse_iso_date(data["due_date"], "due_date")
if isinstance(result, tuple):
return result
fields["due_date"] = result
else:
fields["due_date"] = None
if "tags" in data:
fields["tags"] = data["tags"]
# Re-filing a task's kind. The editor sends this field; dropping it would
# report "Task saved" and revert on the next load. Validated at the same layer as status and priority so
# an unrecognised value is a 400 rather than a database CHECK violation.
if "kind" in data:
try:
fields["task_kind"] = notes_minted_kind(data["kind"])
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
for key in ("project_id", "milestone_id", "parent_id", "arose_from_id"):
if key in data:
fields[key] = data[key]
recurrence_rule, recurrence_err = _parse_recurrence_rule(data)
if recurrence_err:
return recurrence_err
if recurrence_rule is not _UNSET:
fields["recurrence_rule"] = recurrence_rule
task = await update_note(task_note.user_id, task_id, **fields)
if task is None:
return not_found("Task")
if data.get("system_ids") is not None:
await systems_svc.set_record_systems(uid, task_id, data["system_ids"])
out = task.to_dict()
out["systems"] = [s.to_dict() for s in await systems_svc.list_record_systems(uid, task_id)]
await placement_svc.attach_placement(uid, out, task)
return jsonify(out)
@tasks_bp.route("/<int:task_id>/status", methods=["PATCH"])
@login_required
async def patch_task_status(task_id: int):
uid = get_current_user_id()
result = await get_note_for_user(uid, task_id)
if result is None:
return not_found("Task")
task_note, _ = result
if not await can_write_note(uid, task_id):
return jsonify({"error": "Permission denied"}), 403
data = await request.get_json()
status_val = data.get("status")
if not status_val:
return jsonify({"error": "status is required"}), 400
try:
TaskStatus(status_val)
except ValueError:
return jsonify({"error": f"Invalid status: {status_val}"}), 400
task = await update_note(task_note.user_id, task_id, status=status_val)
if task is None:
return not_found("Task")
return jsonify(task.to_dict())
@tasks_bp.route("/<int:task_id>/recurrence-preview", methods=["GET"])
@login_required
async def recurrence_preview_route(task_id: int):
uid = get_current_user_id()
result = await get_note_for_user(uid, task_id)
if result is None:
return not_found("Task")
task, _ = result
if not task.recurrence_rule:
return jsonify({"error": "Task has no recurrence rule"}), 400
count = min(request.args.get("count", 5, type=int), 10)
base = task.due_date or date.today()
dates = []
current = base
for _ in range(count):
current = calculate_next_due(task.recurrence_rule, current)
dates.append(current.isoformat())
return jsonify({"dates": dates})
@tasks_bp.route("/<int:task_id>", methods=["DELETE"])
@login_required
async def delete_task_route(task_id: int):
uid = get_current_user_id()
result = await get_note_for_user(uid, task_id)
if result is None:
return not_found("Task")
task_note, _ = result
if not await can_write_note(uid, task_id):
return jsonify({"error": "Permission denied"}), 403
from grimoire.services.trash import delete as trash_delete
batch = await trash_delete(task_note.user_id, "task", task_id)
if batch is None:
return not_found("Task")
return "", 204
+30
View File
@@ -0,0 +1,30 @@
"""Trash REST API — list / restore / purge soft-deleted content by batch."""
from __future__ import annotations
from quart import Blueprint, jsonify
from grimoire.auth import get_current_user_id, login_required
import grimoire.services.trash as trash_svc
trash_bp = Blueprint("trash", __name__, url_prefix="/api/trash")
@trash_bp.get("")
@login_required
async def list_trash():
return jsonify({"batches": await trash_svc.list_trash(get_current_user_id())})
@trash_bp.post("/<batch_id>/restore")
@login_required
async def restore_batch(batch_id: str):
n = await trash_svc.restore(get_current_user_id(), batch_id)
return jsonify({"restored": n})
@trash_bp.delete("/<batch_id>")
@login_required
async def purge_batch(batch_id: str):
n = await trash_svc.purge(get_current_user_id(), batch_id)
return jsonify({"purged": n})
+29
View File
@@ -0,0 +1,29 @@
from quart import Blueprint, jsonify, request
from sqlalchemy import or_, select
from grimoire.auth import get_current_user_id, login_required
from grimoire.models import async_session
from grimoire.models.user import User
users_bp = Blueprint("users", __name__, url_prefix="/api/users")
@users_bp.route("/search", methods=["GET"])
@login_required
async def search_users():
uid = get_current_user_id()
q = (request.args.get("q") or "").strip()
if len(q) < 2:
return jsonify({"users": []})
like = f"{q}%"
async with async_session() as session:
users = (await session.execute(
select(User).where(
User.id != uid,
or_(User.username.ilike(like), User.email.ilike(like)),
).limit(10)
)).scalars().all()
return jsonify({"users": [
{"id": u.id, "username": u.username}
for u in users
]})
+24
View File
@@ -0,0 +1,24 @@
from datetime import date
from quart import jsonify, request
def not_found(resource: str = "Item"):
return jsonify({"error": f"{resource} not found"}), 404
def parse_iso_date(value: str | None, field: str = "date"):
"""Parse an ISO date string. Returns a date, None, or a (response, 400) tuple."""
if not value:
return None
try:
return date.fromisoformat(value)
except ValueError:
return jsonify({"error": f"Invalid {field} format. Use YYYY-MM-DD."}), 400
def parse_pagination(default_limit: int = 50, max_limit: int = 500) -> tuple[int, int]:
"""Extract and clamp ``limit`` / ``offset`` from the current request's query string."""
limit = min(request.args.get("limit", default_limit, type=int), max_limit)
offset = request.args.get("offset", 0, type=int)
return limit, offset
+132
View File
@@ -0,0 +1,132 @@
"""Forge push webhook — drift flagging at the moment the repo moves.
The forge POSTs here on every push; changed paths are matched against recorded
snippet locations (through repo bindings) and matched verdicts get an
``invalidated_by`` marker that surfaces in the ``verification="attention"``
listing. This is what makes verification scale past tens of records: sessions
recheck what pushes flagged instead of sweeping everything.
Registering the webhook on the forge is per-instance setup (Settings → Config
→ Git Forge shows the endpoint and holds the secret) — the server never
self-registers on the forge.
Contract with the forge's delivery loop:
- No secret configured → 404: the endpoint doesn't exist until an operator
creates it. Bad signature → 401: that's a caller problem worth signaling.
- A PROCESSING failure returns 200 with ``{"ok": false}`` and drops a
WARNING + AppLog row (the telemetry canary pattern): repeated 5xx responses
make forges mark deliveries failed and operators disable the hook, which
would silently turn the feature off — the exact failure mode this
milestone exists to prevent.
"""
from __future__ import annotations
import hashlib
import hmac
import logging
import traceback
from quart import Blueprint, jsonify, request
from grimoire.config import Config
from grimoire.services.background import spawn
from grimoire.services.coverage import refresh_coverage
from grimoire.services.repo_bindings import bindings_for_key, normalize_repo_key
from grimoire.services.settings import get_admin_setting
from grimoire.services.snippets import invalidate_for_push
logger = logging.getLogger(__name__)
webhooks_bp = Blueprint("webhooks", __name__, url_prefix="/api/webhooks")
FORGE_WEBHOOK_SECRET_KEY = "forge_webhook_secret"
def signature_ok(secret: str, body: bytes, signature: str) -> bool:
"""Validate a push signature: the hex HMAC-SHA256 of the raw body under
the webhook secret (Gitea's X-Gitea-Signature verbatim; GitHub's
X-Hub-Signature-256 minus its "sha256=" prefix). Constant-time compare."""
if not secret or not signature:
return False
expected = hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, signature.strip().lower())
def delivered_signature(headers) -> str:
"""The HMAC hex a delivery carries, whichever forge sent it: Gitea's
X-Gitea-Signature verbatim, or GitHub's X-Hub-Signature-256 minus its
"sha256=" scheme prefix. Empty when neither header is present."""
return headers.get("X-Gitea-Signature", "") or headers.get(
"X-Hub-Signature-256", ""
).removeprefix("sha256=")
def push_facts(payload: dict) -> tuple[str, list[str], list[str], str]:
"""(repo identity, changed paths, removed paths, head commit) from a Gitea
push payload. Tolerant: absent fields read as empty, never raise."""
repo = payload.get("repository") or {}
raw_repo = repo.get("clone_url") or repo.get("html_url") or repo.get("full_name") or ""
changed: list[str] = []
removed: list[str] = []
for commit in payload.get("commits") or []:
changed.extend(commit.get("added") or [])
changed.extend(commit.get("modified") or [])
removed.extend(commit.get("removed") or [])
# De-dup while keeping order stable for logs.
changed = list(dict.fromkeys(changed))
removed = list(dict.fromkeys(removed))
return raw_repo, changed, removed, str(payload.get("after") or "")
@webhooks_bp.route("/forge", methods=["POST"])
async def forge_push():
secret = await get_admin_setting(FORGE_WEBHOOK_SECRET_KEY, "") or Config.FORGE_WEBHOOK_SECRET
if not secret:
# Not "forbidden" — the endpoint is not a thing on this instance.
return jsonify({"error": "Not found"}), 404
body = await request.get_data()
# The payload shape push_facts reads (repository.clone_url,
# commits[].added/modified/removed, after) is common to both forges, so
# the signature header is the whole GitHub mapping.
if not signature_ok(secret, body, delivered_signature(request.headers)):
return jsonify({"error": "Invalid signature"}), 401
try:
payload = await request.get_json(force=True) or {}
raw_repo, changed, removed, head = push_facts(payload)
repo_key = normalize_repo_key(raw_repo)
if not repo_key:
return jsonify({"ok": True, "flagged": 0, "reason": "no repository in payload"})
flagged = await invalidate_for_push(repo_key, changed, removed, head)
if flagged:
logger.info(
"forge push %s flagged %d snippet(s) for recheck", head[:12], flagged
)
# A push is exactly when the coverage number goes stale — recompute it
# off the delivery path. Fire-and-forget: the forge's delivery
# loop must not wait on an archive download, and a failure is a
# WARNING from spawn(), never a failed delivery. This also SEEDS the
# cache on a webhook-configured instance — no manual first refresh.
for binding in await bindings_for_key(repo_key):
spawn(
refresh_coverage(binding.user_id, binding.project_id),
site="webhooks.coverage_refresh",
)
return jsonify({"ok": True, "flagged": flagged})
except Exception:
logger.warning("forge webhook processing failed", exc_info=True)
try:
from grimoire.services.logging import log_error
await log_error(
endpoint="webhooks/forge",
error_type="forge_webhook_failed",
error_message="push received but drift flagging failed — "
"snippets touched by this push were not marked for recheck",
traceback=traceback.format_exc(),
)
except Exception:
logger.debug("forge webhook canary write failed", exc_info=True)
# 200 on purpose — see the module docstring's delivery contract.
return jsonify({"ok": False})