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
+2
View File
@@ -29,6 +29,7 @@ from scribe.routes.plugin import plugin_bp
from scribe.routes.trash import trash_bp
from scribe.routes.dashboard import dashboard_bp
from scribe.routes.systems import systems_bp
from scribe.routes.snippets import snippets_bp
from scribe.mcp import mount_mcp
STATIC_DIR = Path(__file__).parent / "static"
@@ -91,6 +92,7 @@ def create_app() -> Quart:
app.register_blueprint(trash_bp)
app.register_blueprint(dashboard_bp)
app.register_blueprint(systems_bp)
app.register_blueprint(snippets_bp)
@app.before_request
async def before_request():
+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
+30 -3
View File
@@ -23,6 +23,7 @@ changing any caller (MCP tool, REST route, UI).
"""
from __future__ import annotations
import asyncio
import re
from scribe.services import knowledge as knowledge_svc
@@ -32,6 +33,25 @@ SNIPPET_NOTE_TYPE = "snippet"
SNIPPET_TAG = "snippet"
def _embed_snippet(note) -> None:
"""Fire-and-forget embedding refresh for a snippet.
A snippet's whole value is *immediate* recall — it must join the semantic /
auto-inject pool the moment it's recorded, not wait for the startup backfill.
Unlike a plain note (embedded at the REST-route boundary only, so its MCP
create path defers to restart-backfill), a snippet is recorded primarily via
MCP, so we embed here in the service — covering BOTH the MCP tool and the
REST route by construction. Mirrors the route pattern: fire-and-forget,
text = title + body. Import lazily so the pure serialize/parse helpers can be
imported without pulling in the embedding model.
"""
text = f"{note.title}\n{note.body}".strip() if note.body else (note.title or "")
if not text:
return
from scribe.services.embeddings import upsert_note_embedding
asyncio.create_task(upsert_note_embedding(note.id, note.user_id, text))
# --- serialize: structured fields -> note (title/body/tags) ------------------
def compose_title(name: str, when_to_use: str = "") -> str:
@@ -164,8 +184,9 @@ async def create_snippet(
tags: list[str] | None = None,
project_id: int | None = None,
):
"""Create a snippet note. Returns the created Note."""
return await notes_svc.create_note(
"""Create a snippet note (embedded on create for immediate recall). Returns
the created Note."""
note = await notes_svc.create_note(
user_id,
title=compose_title(name, when_to_use),
body=compose_body(
@@ -176,6 +197,8 @@ async def create_snippet(
tags=compose_tags(language, tags),
project_id=project_id,
)
_embed_snippet(note)
return note
async def get_snippet(user_id: int, snippet_id: int):
@@ -254,4 +277,8 @@ async def update_snippet(
if project_id is not None:
fields["project_id"] = project_id
return await notes_svc.update_note(user_id, snippet_id, **fields)
updated = await notes_svc.update_note(user_id, snippet_id, **fields)
if updated is not None:
# Title/body changed → refresh the embedding so recall reflects the edit.
_embed_snippet(updated)
return updated