feat(scribe): snippet management UI + REST routes; embed snippets on create
CI & Build / Python lint (push) Successful in 3s
CI & Build / integration (push) Successful in 23s
CI & Build / TypeScript typecheck (push) Successful in 33s
CI & Build / Python tests (push) Successful in 48s
CI & Build / Build & push image (push) Successful in 1m4s

Step 6 of the Drafter recall milestone (#227): a human-facing surface for
the reusable-code snippets that agents record via MCP, plus the REST API
behind it. Backend embeds snippets inline on create/update so they're
recallable immediately, not only after a restart.

Backend:
- routes/snippets.py: GET/POST /api/snippets, GET/PATCH/DELETE
  /api/snippets/<id>. Share-aware per rule #78 (get_note_for_user +
  can_write_note), writes performed as the owner; list owner-scoped —
  mirrors routes/notes.py. Registered in app.py.
- services/snippets.py: embed on create/update via a _embed_snippet
  fire-and-forget helper, covering BOTH the MCP tool and the REST route
  by construction. A snippet's value is immediate recall, so it can't wait
  for the startup-only backfill (see issue: MCP create path doesn't embed
  inline for notes/tasks generally).
- tests/test_routes_snippets.py: structural registration + handler/service
  contract + PATCH-field ↔ update_snippet-kwarg parity (rule #33).

Frontend (Vue 3 + TS):
- api/snippets.ts: typed client, modeled on api/systems.ts.
- views: SnippetListView (search, skeleton/empty/error states),
  SnippetDetailView (read + copy-to-clipboard, ConfirmDialog delete),
  SnippetEditorView (create/edit all fields, Ctrl/Cmd+S, Esc, autofocus,
  validation). v1 quality per rules #24/#27.
- router: /snippets, /snippets/new, /snippets/:id, /snippets/:id/edit.
- NoteType union widened to include 'snippet'; Snippets nav link added to
  AppHeader (desktop pill bar + mobile menu).
- Design system: Moss --color-action-primary for action buttons, accent
  --color-primary reserved for tags/brand (Hybrid rule); focus rings;
  JetBrains Mono for code/name/signature/location.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Pa2EsuB54BuWQ8GfJq9c7t
This commit is contained in:
2026-07-25 14:16:02 -04:00
parent 0ea3bff797
commit d257c0fd67
11 changed files with 1355 additions and 4 deletions
+137
View File
@@ -0,0 +1,137 @@
"""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 (rule #78): 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 scribe.auth import get_current_user_id, login_required
from scribe.routes.utils import not_found, parse_pagination
from scribe.services import snippets as snippets_svc
from scribe.services.access import can_write_note
from scribe.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")
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", "")
limit, offset = parse_pagination()
items, total = await snippets_svc.list_snippets(
uid, q=q, tag=tag, limit=limit, offset=offset,
)
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
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", ""),
tags=data.get("tags"),
project_id=project_id,
)
return jsonify(snippets_svc.snippet_to_dict(note)), 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)
data["permission"] = permission
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 "tags" in data:
kwargs["tags"] = data["tags"]
if "project_id" in data:
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")
return jsonify(snippets_svc.snippet_to_dict(updated))
@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
from scribe.services.trash import delete as trash_delete
batch = await trash_delete(note.user_id, "note", snippet_id)
if batch is None:
return not_found("Snippet")
return "", 204