Files
FabledScribe/src/fabledassistant/services/trash.py
T
bvandeusen 43a860c3ac
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 49s
CI & Build / Build & push image (push) Successful in 1m7s
feat(rules): project-scoped rules (S3)
Rules can now belong to either a rulebook topic OR a single project,
enforced by a CHECK constraint (exactly-one of topic_id/project_id).
Adds the create_project_rule MCP tool + REST endpoint, surfaces
project-scoped rules in get_project/get_task/start_planning under a
new project_rules field, and adds a project Rules tab section with an
inline create form so the operator can author project rules from the
UI without rulebook ceremony.

- migration 0059: rules.project_id (FK projects ON DELETE CASCADE),
  topic_id now nullable, CHECK ck_rule_topic_xor_project, index on
  project_id
- model: Rule gains project_id; to_dict exposes it
- service: create_project_rule with project-ownership guard; list_rules
  with project_id filter UNIONs subscription-derived + project-scoped;
  get_applicable_rules adds a project_rules field; get_rule / update_rule
  / delete_rule fetch via a shared _fetch_owned_rule that handles both
  rulebook and project ownership paths
- trash: project delete cascades to project-scoped rules
- MCP: create_project_rule tool registered; _INSTRUCTIONS mentions both
  create_rule and create_project_rule paths
- REST: POST /api/projects/<id>/rules (statement required, title derived
  if omitted)
- frontend: Rule type gains nullable topic_id + project_id; createProjectRule
  client; ProjectRulesTab.vue gains a "Project rules" section with inline
  create form and per-rule expand/delete
- tests: register count → 18; create_project_rule unit tests (required
  fields, title derivation, explicit-title pass-through); applicable_rules
  shape tests now include project_rules; trash cascade test updated to
  expect 5 executions

S1+S2 (always_on flag + Scribe-first prompt) shipped in 658348f.
S4 (enter_project handshake) follows.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-01 01:10:18 -04:00

192 lines
7.6 KiB
Python

"""Soft-delete / trash service — single source of truth for recoverable deletes.
A delete stamps `deleted_at` + a shared `deleted_batch_id` on the target row and
its descendants (cascade). Restore clears the batch; purge hard-deletes it; the
retention cron purges rows older than the configured window. Live reads exclude
trashed rows via `alive()`.
"""
from __future__ import annotations
import uuid
from datetime import datetime, timezone
from sqlalchemy import select, update
from fabledassistant.models import async_session
from fabledassistant.models.note import Note
from fabledassistant.models.event import Event
from fabledassistant.models.project import Project
from fabledassistant.models.milestone import Milestone
from fabledassistant.models.rulebook import Rulebook, RulebookTopic, Rule
# entity_type -> (Model, owner_column_name or None). Used by the existence check.
_OWNER = {
"note": (Note, "user_id"),
"task": (Note, "user_id"),
"event": (Event, "user_id"),
"project": (Project, "user_id"),
"milestone": (Milestone, "user_id"),
"rulebook": (Rulebook, "owner_user_id"),
"topic": (RulebookTopic, None),
"rule": (Rule, None),
}
async def _set(session, model, where, batch, now) -> None:
"""Stamp deleted_at + batch on live rows matching `where`."""
await session.execute(
update(model)
.where(*where, model.deleted_at.is_(None))
.values(deleted_at=now, deleted_batch_id=batch)
)
async def _exists_alive(session, user_id: int, etype: str, eid: int) -> bool:
model, owner = _OWNER[etype]
where = [model.id == eid, model.deleted_at.is_(None)]
if owner:
where.append(getattr(model, owner) == user_id)
return (await session.execute(select(model.id).where(*where))).first() is not None
async def _cascade(session, user_id: int, etype: str, eid: int, batch: str, now) -> None:
if etype == "project":
await _set(session, Note, [Note.user_id == user_id, Note.project_id == eid], batch, now)
await _set(session, Milestone, [Milestone.user_id == user_id, Milestone.project_id == eid], batch, now)
# Project-scoped rules cascade with the project they're attached to.
await _set(session, Rule, [Rule.project_id == eid], batch, now)
await _set(session, Project, [Project.user_id == user_id, Project.id == eid], batch, now)
elif etype == "milestone":
await _set(session, Note, [Note.user_id == user_id, Note.milestone_id == eid], batch, now)
await _set(session, Milestone, [Milestone.user_id == user_id, Milestone.id == eid], batch, now)
elif etype in ("note", "task"):
await _set(session, Note, [Note.user_id == user_id, Note.parent_id == eid], batch, now) # sub-tasks
await _set(session, Note, [Note.user_id == user_id, Note.id == eid], batch, now)
elif etype == "event":
await _set(session, Event, [Event.user_id == user_id, Event.id == eid], batch, now)
elif etype == "rulebook":
topic_ids = (await session.execute(
select(RulebookTopic.id)
.join(Rulebook, RulebookTopic.rulebook_id == Rulebook.id)
.where(Rulebook.id == eid, Rulebook.owner_user_id == user_id)
)).scalars().all()
if topic_ids:
await _set(session, Rule, [Rule.topic_id.in_(topic_ids)], batch, now)
await _set(session, RulebookTopic, [RulebookTopic.rulebook_id == eid], batch, now)
await _set(session, Rulebook, [Rulebook.id == eid, Rulebook.owner_user_id == user_id], batch, now)
elif etype == "topic":
await _set(session, Rule, [Rule.topic_id == eid], batch, now)
await _set(session, RulebookTopic, [RulebookTopic.id == eid], batch, now)
elif etype == "rule":
await _set(session, Rule, [Rule.id == eid], batch, now)
else:
raise ValueError(f"unknown entity_type: {etype!r}")
async def delete(user_id: int, entity_type: str, entity_id: int) -> str | None:
"""Soft-delete an entity + its descendants under one batch_id.
Returns the batch_id, or None if the entity wasn't found / not owned.
"""
batch = str(uuid.uuid4())
now = datetime.now(timezone.utc)
async with async_session() as session:
if not await _exists_alive(session, user_id, entity_type, entity_id):
return None
await _cascade(session, user_id, entity_type, entity_id, batch, now)
await session.commit()
return batch
# All soft-deletable models, and their trash-listing type label.
_ALL = [Note, Event, Project, Milestone, Rulebook, RulebookTopic, Rule]
_TYPE = {
Note: "note", Event: "event", Project: "project", Milestone: "milestone",
Rulebook: "rulebook", RulebookTopic: "topic", Rule: "rule",
}
def alive(stmt, model):
"""Append a 'not trashed' filter to a select. Use in every live read."""
return stmt.where(model.deleted_at.is_(None))
async def restore(user_id: int, batch_id: str) -> int:
"""Clear deleted_at for every row in the batch. Returns rows restored."""
n = 0
async with async_session() as session:
for model in _ALL:
res = await session.execute(
update(model)
.where(model.deleted_batch_id == batch_id)
.values(deleted_at=None, deleted_batch_id=None)
)
n += res.rowcount or 0
await session.commit()
return n
async def purge(user_id: int, batch_id: str) -> int:
"""Hard-delete every row in the batch. Irreversible."""
from sqlalchemy import delete as sql_delete
n = 0
async with async_session() as session:
for model in _ALL:
res = await session.execute(
sql_delete(model).where(model.deleted_batch_id == batch_id)
)
n += res.rowcount or 0
await session.commit()
return n
async def list_trash(user_id: int) -> list[dict]:
"""Trashed rows across all soft-deletable tables, grouped by batch_id."""
batches: dict[str, dict] = {}
async with async_session() as session:
for model in _ALL:
rows = (await session.execute(
select(model).where(model.deleted_at.isnot(None))
)).scalars().all()
for r in rows:
grp = batches.setdefault(
r.deleted_batch_id,
{"batch_id": r.deleted_batch_id,
"deleted_at": r.deleted_at.isoformat() if r.deleted_at else None,
"items": []},
)
grp["items"].append({
"type": _TYPE[model], "id": r.id,
"title": getattr(r, "title", "") or "",
})
out = list(batches.values())
for g in out:
lead = g["items"][0]
g["summary"] = lead["title"] or f"{lead['type']} {lead['id']}"
g["count"] = len(g["items"])
out.sort(key=lambda g: g["deleted_at"] or "", reverse=True)
return out
async def purge_expired(retention_days: int) -> int:
"""Cron entry: hard-delete rows trashed more than retention_days ago.
retention_days <= 0 disables auto-purge (returns 0 without touching anything).
"""
from datetime import timedelta
from sqlalchemy import delete as sql_delete
if retention_days <= 0:
return 0
cutoff = datetime.now(timezone.utc) - timedelta(days=retention_days)
n = 0
async with async_session() as session:
for model in _ALL:
res = await session.execute(
sql_delete(model).where(
model.deleted_at.isnot(None), model.deleted_at < cutoff
)
)
n += res.rowcount or 0
await session.commit()
return n