Files
FabledScribe/src/scribe/mcp/tools/systems.py
T
bvandeusenandClaude Fable 5 56b1952de5
CI & Build / Python lint (push) Successful in 3s
CI & Build / Plugin hooks (push) Successful in 7s
CI & Build / TypeScript typecheck (push) Successful in 11s
CI & Build / integration (push) Successful in 16s
CI & Build / Python tests (push) Failing after 29s
CI & Build / Build & push image (push) Skipped
fix(systems): sweeps are the discovery moment — zero-Systems hint, create_system dedup gate, prose inverted
First real-world test of the #2562 fixes (Scribe issue #2569): a Forge
session ran a whole-codebase audit and created zero Systems — endorsed
by the shipped guidance, whose "no particular area takes none" clause
read as an exemption for exactly the record type that enumerates the
subsystem vocabulary. And the systems_hint was silent for a zero-Systems
project, the one state nothing else nudges out of.

- systems_hint gains a zero-Systems branch: prompt the FIRST
  create_system instead of going quiet.
- create_system is duplicate-gated like the other creates (normalized
  name, archived included, fail-open) — liberal creation becomes safe by
  construction, so the guidance can stop preaching restraint.
- Prose inverted on every surface (hint text, create_system docstring,
  floor bullet, using-scribe step 7): audits/sweeps take several tags
  and mint the Systems they name; the gate is the guardrail against
  sprawl, not holding back; only a record genuinely about no particular
  area goes untagged.
- Plugin 0.1.26 -> 0.1.27.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 15:35:59 -04:00

229 lines
9.0 KiB
Python

"""System CRUD + record-association MCP tools — wrappers over services/systems.py.
A System is a per-project, reusable, self-describing subsystem/area that any
record (note, task, or issue) can be associated with — so research, build-work,
and corrective work line up under the same area and recurring problem-spots are
visible. The service enforces the multi-user ACL (project permission); these
tools are thin wrappers.
Sentinels (match the milestone/task tool conventions):
- name="" / description="" / color="" / status="" → "leave unchanged" on update
- order_index=-1 → "leave unchanged" on update (0 is a valid order_index)
"""
from __future__ import annotations
from scribe.mcp._context import current_user_id
from scribe.services import systems as systems_svc
async def untagged_systems_hint(user_id: int, project_id: int) -> str | None:
"""Nudge text for a record created untagged in a project that has Systems.
Not a tool. create_task / create_note / create_snippet attach this to
their responses so the tagging question arrives in-band at the exact write
it applies to — instruction prose alone demonstrably doesn't fire at write
time, while in-band behavior (the duplicate gate) does (#2562).
"""
# Fail-open like the dedup gate: a hint must never break a create.
try:
systems = await systems_svc.list_systems(user_id, project_id)
except Exception:
return None
if not systems:
# Zero Systems is the one state nothing else nudges out of: the hint
# below needs a vocabulary to name, so without this branch the FIRST
# create_system depends entirely on prose that demonstrably doesn't
# fire at write time (#2562).
return (
"Created untagged — this project has no Systems yet. If this "
"record is about a code subsystem/area, create_system it (name + "
"a one-paragraph charter) and tag the record. An audit or sweep "
"that names areas is exactly the moment to mint them; the "
"duplicate gate is what guards against sprawl, not holding back."
)
names = ", ".join(f"#{s.id} {s.name}" for s in systems)
return (
f"Created untagged. This project's Systems: {names}. If this record is "
"about one or more of those areas, tag it (update it with "
"system_ids=[...]) — cross-cutting records like audits take several; "
"if an area it names is missing, create_system it and tag; only leave "
"it untagged if it is about no particular area."
)
async def create_system(
project_id: int,
name: str,
description: str = "",
color: str = "",
) -> dict:
"""Create a System (a reusable, self-describing subsystem/area) in a project.
Associate records with it via the `system_ids` arg on create/update_task and
create/update_note.
Create one the moment two records would share an area that has no System
yet — the same two-or-more test snippets use. Don't wait to be asked to
name an area that plainly exists in the code; an unmodelled area means
every record about it stays untaggable. An audit or sweep that walks the
codebase is a DISCOVERY moment: mint the Systems it names as it names
them — the duplicate gate below, plus reviewing the existing list, is what
guards against sprawl, not holding back. Give each one a one-paragraph
charter, not just a label: the description is what tells a later session
whether a record belongs here.
Args:
project_id: The project this system belongs to (required).
name: Short label (required).
description: What the system is and how it's used — a name is rarely enough.
color: Optional UI accent (hex), or empty.
Duplicate-gated like the other creates: if a System with the same
normalized name already exists in this project (archived included), the
call returns {"duplicate": true, "existing_id": ...} instead of creating —
tag records to that one, or update_system it if its charter needs work.
"""
uid = current_user_id()
norm = " ".join(name.split()).lower()
if norm:
try:
existing = await systems_svc.list_systems(
uid, project_id, include_archived=True
)
except Exception:
existing = []
for s in existing:
if " ".join(s.name.split()).lower() == norm:
return {
"duplicate": True,
"existing_id": s.id,
"message": (
f"System '{s.name}' (#{s.id}) already covers this area "
"in this project. Tag records to it with system_ids, "
"or update_system it if the charter needs revising — "
"a second System with the same name would split the "
"area's records across two piles."
),
}
system = await systems_svc.create_system(
uid, project_id=project_id, name=name,
description=description or None, color=color or None,
)
if system is None:
raise ValueError(f"cannot create system in project {project_id} (no write access)")
return system.to_dict()
async def list_systems(project_id: int, include_archived: bool = False) -> dict:
"""List a project's systems (active by default), ordered by order_index.
Pass include_archived=True to include archived systems.
"""
uid = current_user_id()
rows = await systems_svc.list_systems(uid, project_id, include_archived=include_archived)
return {"systems": [s.to_dict() for s in rows]}
async def get_system(system_id: int) -> dict:
"""Fetch a System plus the records associated with it.
Returns the system, plus its associated records split into `issues`,
`tasks` (work/plan), and `notes`.
"""
uid = current_user_id()
system = await systems_svc.get_system(uid, system_id)
if system is None:
raise ValueError(f"system {system_id} not found")
records = await systems_svc.list_records_for_system(uid, system_id)
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)
data = system.to_dict()
data["issues"] = issues
data["tasks"] = tasks
data["notes"] = notes
return data
async def update_system(
system_id: int,
name: str = "",
description: str = "",
color: str = "",
status: str = "",
order_index: int = -1,
) -> dict:
"""Update a System. Only explicitly provided fields change.
Args:
status: 'active' or 'archived'. Archive a system to retire it without
losing history; archived systems hide from default lists.
order_index: display position (0-based); -1 = leave unchanged.
"""
uid = current_user_id()
fields: dict = {}
if name:
fields["name"] = name
if description:
fields["description"] = description
if color:
fields["color"] = color
if status:
fields["status"] = status
if order_index >= 0:
fields["order_index"] = order_index
system = await systems_svc.update_system(uid, system_id, **fields)
if system is None:
raise ValueError(f"system {system_id} not found or no write access")
return system.to_dict()
async def list_system_records(
system_id: int, kind: str = "", open_only: bool = False
) -> dict:
"""Everything filed under one System — the way to READ a subsystem.
Reach for this when investigating a specific area: it returns the notes,
tasks, issues and snippets someone deliberately tagged to it — the
subsystem's accumulated record, unranked. Start with its reference note if
one exists (titled "«System» — reference"); that is the living state, and
the rest is history and open work around it. For a ranked cut of the same
slice, search(system_id=...) filters semantic search to this association.
Args:
kind: filter by task_kind — 'issue', 'work', or 'plan'. Omit for all.
open_only: limit to tasks not done/cancelled (e.g. open issues only).
"""
uid = current_user_id()
rows = await systems_svc.list_records_for_system(
uid, system_id, kind=kind or None, open_only=open_only,
)
return {"records": [r.to_dict() for r in rows]}
async def delete_system(system_id: int) -> dict:
"""Soft-delete a System (recoverable). Its record associations are removed."""
uid = current_user_id()
ok = await systems_svc.delete_system(uid, system_id)
if not ok:
raise ValueError(f"system {system_id} not found or no write access")
return {"message": f"System {system_id} deleted."}
def register(mcp) -> None:
for fn in (
create_system,
list_systems,
get_system,
update_system,
list_system_records,
delete_system,
):
mcp.tool(name=fn.__name__)(fn)