Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ Gecko Suite, through the two functions every job already calls, `build_provider`
and search falls back to keywords; jobs fail with a sentence and retry.
- **The assistant exists only in `suite` mode, and never writes.** Its tools look
(`search_assets`, `get_asset`, `read_transcript`, `list_clips`, `list_tags`,
`list_playlists`) or record a proposal (`propose_changes`, `propose_enrichment`,
`propose_clip`, `propose_cut`, `propose_playlist`, `propose_note`);
`find_similar_tags`, `list_playlists`) or record a proposal (`propose_changes`,
`propose_enrichment`, `propose_clip`, `propose_cut`, `propose_playlist`, `propose_note`,
`propose_tag_groups`, `propose_tag_rename`, `propose_tag_delete`);
`assistant/apply.py` is the only place a proposal reaches the library, and only when a
person presses Apply. A new tool that writes would break that, so make it a proposal
kind instead. Every tool re-checks that the asset is the caller's: the model chooses
Expand All @@ -52,6 +53,11 @@ Gecko Suite, through the two functions every job already calls, `build_provider`
`SUITE_BASE_URL`, and the old `NOTES_BASE_URL` is not read) with the caller's
own token, which only the Apply request has; their `/a/<id>` links are made absolute
there. Notes failing is a skipped item with a sentence, never a failed Apply.
A proposal's `tag_ops` (each with its own `op_ref`) change the vocabulary, not one asset:
groups are `TagCategory` rows (there is no tag-under-tag), and a rename onto a name that
exists is recorded as a merge. Apply runs them in dependency order (`TAG_OP_ORDER`) through
`services/tags`, resolves categories proposed in the same turn by ref, skips a stale op
with a sentence, and re-indexes the touched assets once at the end.
`web_search` is one of the looking tools: the suite runs the search (its own backend, else
DuckDuckGo) and credits it to the conversation, and what comes back is for the model to
read and cite, never a write. A **persona** is the suite's, chosen per turn and kept on the
Expand Down
194 changes: 192 additions & 2 deletions backend/app/assistant/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@
Playlists (`proposal["playlists"]`) go through services/playlists, the same as a person
building one. Each item is checked again; one whose asset has gone or whose range no
longer fits is left out and reported, and the rest of the playlist is still made.

Tag changes (`proposal["tag_ops"]`) are to the vocabulary rather than to one asset: new
categories, categories moved, tags filed, renamed, merged and deleted. They run in the
order one depends on another (a category is made before tags are filed into it, and tags
are filed before they are merged away), each checked against the library as it is now, and
one that no longer makes sense is skipped with a sentence while the rest still apply.
"""

from __future__ import annotations
Expand All @@ -40,6 +46,7 @@
from app.jobs.runner import ACTIVE_STATUSES
from app.models.asset import Asset
from app.models.job import KIND_AUTOTAG, KIND_DESCRIBE, KIND_EXTRACT_SUBVIDEO, KIND_SUMMARIZE, EnrichmentJob
from app.models.tag import Tag, TagCategory
from app.providers import build_provider
from app.providers.base import ProviderError
from app import notes_client
Expand All @@ -57,7 +64,8 @@ def apply(session: Session, user_id: str, proposal: dict,
only: Optional[Iterable[str]] = None,
only_clips: Optional[Iterable[str]] = None,
only_playlists: Optional[Iterable[str]] = None,
only_notes: Optional[Iterable[str]] = None, *,
only_notes: Optional[Iterable[str]] = None,
only_tag_ops: Optional[Iterable[str]] = None, *,
token: Optional[str] = None, origin: str = "") -> list[dict]:
"""Apply the proposal's items, clips, playlists and notes, one result per entry.

Expand All @@ -69,7 +77,8 @@ def apply(session: Session, user_id: str, proposal: dict,
or playlists, and must not get them as a side effect).
"""
everything = (only is None and only_clips is None and only_playlists is None
and only_notes is None)
and only_notes is None and only_tag_ops is None)
wanted_ops = set(only_tag_ops) if only_tag_ops is not None else set()
wanted_notes = set(only_notes) if only_notes is not None else set()
wanted = set(only) if only is not None else set()
wanted_clips = set(only_clips) if only_clips is not None else set()
Expand All @@ -87,9 +96,190 @@ def apply(session: Session, user_id: str, proposal: dict,
for entry in proposal.get("notes", []):
if everything or entry["note_ref"] in wanted_notes:
results.append(_apply_note(entry, token, origin))
ops = [op for op in proposal.get("tag_ops", []) if everything or op["op_ref"] in wanted_ops]
if ops:
results.extend(_apply_tag_ops(session, user_id, ops))
return results


# The order tag changes are applied in, whatever order they were proposed in: a category
# exists before anything is filed under it, and a tag is filed before a merge carries its
# category over to the target.
TAG_OP_ORDER = ("create_category", "move_category", "file_tags", "rename_tag", "merge_tags",
"delete_tag")


def _apply_tag_ops(session: Session, user_id: str, ops: list[dict]) -> list[dict]:
"""Apply the chosen tag changes, one result each, in the proposal's order.

`made` maps a proposed category's op_ref to the category it became, so an op naming a
new parent or home finds it; one whose category was not chosen or could not be made is
skipped. Every asset whose tag names changed is re-indexed once, at the end, rather than
once per op that touched it.
"""
results: dict[str, dict] = {}
made: dict[str, str] = {}
reindex: set[str] = set()
for op in sorted(ops, key=lambda o: TAG_OP_ORDER.index(o["kind"])
if o["kind"] in TAG_OP_ORDER else len(TAG_OP_ORDER)):
result = {"asset_id": None, "asset_name": _tag_op_label(op), "applied": [],
"skipped": [], "op_ref": op["op_ref"]}
results[op["op_ref"]] = result
try:
reindex.update(_apply_tag_op(session, user_id, op, made, result))
except Exception as exc: # noqa: BLE001 - one bad op must not sink the others
logger.exception("Applying tag change %s failed", op.get("kind"))
session.rollback()
result["skipped"].append(f"It could not be applied: {exc}")
if reindex:
asset_service.reindex_ids(session, reindex)
return [results[op["op_ref"]] for op in ops]


def _tag_op_label(op: dict) -> str:
kind = op["kind"]
if kind == "create_category":
return op["name"]
if kind == "move_category":
return op["name"]
if kind == "file_tags":
return op.get("category_label") or "No category"
if kind == "rename_tag":
return op["from"]
if kind == "merge_tags":
return op["target_name"]
return op.get("name") or ""


def _parent_id(session: Session, user_id: str, op: dict, made: dict[str, str],
ref_key: str, id_key: str) -> tuple[bool, Optional[str]]:
"""The category an op points at, as (found, id). None with found means "no category"."""
if op.get(ref_key):
made_id = made.get(op[ref_key])
return (made_id is not None, made_id)
if op.get(id_key):
row = session.get(TagCategory, op[id_key])
if row is None or row.user_id != user_id:
return False, None
return True, row.id
return True, None


def _apply_tag_op(session: Session, user_id: str, op: dict, made: dict[str, str],
result: dict) -> list[str]:
"""Apply one tag change; return the assets to re-index."""
kind = op["kind"]
if kind == "create_category":
found, parent_id = _parent_id(session, user_id, op, made, "parent_ref", "parent_category_id")
if not found:
result["skipped"].append("Its parent category was not made, or no longer exists.")
return []
twin = session.exec(select(TagCategory).where(
TagCategory.user_id == user_id, TagCategory.parent_category_id == parent_id)).all()
match = next((c for c in twin if c.name.lower() == op["name"].lower()), None)
if match is not None:
made[op["op_ref"]] = match.id
result["applied"].append("it existed already")
return []
category = TagCategory(user_id=user_id, name=op["name"], parent_category_id=parent_id)
session.add(category)
session.commit()
made[op["op_ref"]] = category.id
result["applied"].append("category made")
return []

if kind == "move_category":
category = session.get(TagCategory, op["category_id"])
if category is None or category.user_id != user_id:
result["skipped"].append("The category no longer exists.")
return []
if op.get("move"):
found, parent_id = _parent_id(session, user_id, op, made, "parent_ref",
"parent_category_id")
if not found:
result["skipped"].append("Its new parent was not made, or no longer exists.")
return []
if tag_service.would_create_cycle(session, user_id, category.id, parent_id):
result["skipped"].append("A category cannot be moved inside itself.")
return []
category.parent_category_id = parent_id
result["applied"].append("moved")
if op.get("new_name"):
category.name = op["new_name"]
result["applied"].append("renamed")
session.add(category)
session.commit()
return []

if kind == "file_tags":
found, category_id = _parent_id(session, user_id, op, made, "category_ref", "category_id")
if not found:
result["skipped"].append("The category was not made, or no longer exists.")
return []
filed = gone = 0
for entry in op["tags"]:
tag = session.get(Tag, entry["id"])
if tag is None or tag.user_id != user_id:
gone += 1
continue
tag.category_id = category_id
session.add(tag)
filed += 1
session.commit()
if filed:
result["applied"].append(f"{filed} tag(s) filed")
if gone:
result["skipped"].append(f"{gone} tag(s) no longer exist.")
return []

if kind == "rename_tag":
tag = session.get(Tag, op["tag_id"])
if tag is None or tag.user_id != user_id:
result["skipped"].append("The tag no longer exists.")
return []
try:
changed = tag_service.rename_tag(session, tag, op["to"])
except ValueError as exc:
session.rollback()
result["skipped"].append(f"{exc}; merge them instead.")
return []
session.commit()
result["applied"].append("renamed")
return tag_service.asset_ids_for_tag(session, tag.id) if changed else []

if kind == "merge_tags":
sources = [t for t in (session.get(Tag, s["id"]) for s in op["sources"])
if t is not None and t.user_id == user_id]
if op.get("target_id"):
target = session.get(Tag, op["target_id"])
if target is None or target.user_id != user_id:
result["skipped"].append("The tag to merge into no longer exists.")
return []
else:
target = tag_service.get_or_create(session, user_id, op["target_name"])
sources = [t for t in sources if t.id != target.id]
if not sources:
result["skipped"].append("The tags to merge no longer exist.")
return []
affected = tag_service.merge_tags(session, sources, target)
result["applied"].append(f"{len(sources)} tag(s) merged into {target.name}")
if len(sources) < len(op["sources"]):
result["skipped"].append(f"{len(op['sources']) - len(sources)} tag(s) no longer exist.")
return affected

if kind == "delete_tag":
tag = session.get(Tag, op["tag_id"])
if tag is None or tag.user_id != user_id:
result["skipped"].append("The tag no longer exists.")
return []
affected = tag_service.delete_tag(session, tag)
result["applied"].append("deleted")
return affected

result["skipped"].append(f"{kind}: not something the library can do.")
return []


def _apply_note(entry: dict, token: Optional[str], origin: str) -> dict:
result = {"asset_id": None, "asset_name": entry.get("title") or "", "applied": [],
"skipped": [], "note_ref": entry["note_ref"], "note_url": None}
Expand Down
19 changes: 18 additions & 1 deletion backend/app/assistant/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
- Search before you answer. Use search_assets for anything about what is in the library, and \
read_transcript when what was said matters. Never describe an asset you have not looked at.
- You cannot change the library. propose_changes, propose_enrichment, propose_clip, \
propose_cut, propose_playlist and propose_note record a proposal; the person reads it \
propose_cut, propose_playlist, propose_note, propose_tag_groups, propose_tag_rename and \
propose_tag_delete record a proposal; the person reads it \
and applies it or throws it away. Say plainly what you are proposing and why. Never say \
a change "has been made" or that a clip "exists".
- Clips and cuts. To find a moment: search_assets gives where a search matched; \
Expand Down Expand Up @@ -52,6 +53,22 @@
- The web is for what the library cannot say. Use web_search sparingly, and say where a fact
came from. Never present something from the web as if it were in the asset itself.
- Prefer the tags the person already uses (list_tags). Invent a new one only when none fits.
- Organising tags. Groups of tags are categories, which nest (People > Scientists); a tag \
is filed under one category at most, and filtering by a category finds everything below it. \
Read list_tags first: it gives every tag's id, how often it is used and where it is filed, \
and on its first page the categories. To sort the whole vocabulary into groups, page through \
list_tags (offset) or ask for uncategorised_only, reuse the categories that exist before \
making new ones, keep the groups few and broad, and nest only where a group is large or \
mixed. Use web_search for a name you do not recognise rather than guessing. File each tag \
once: for one that could go in two groups, choose and say why. Then propose_tag_groups, with \
as many categories and filings in one call as you can.
- Tidying tags. find_similar_tags finds spellings of one tag (case, plurals, typos); read \
each group, since similar is not always the same, and merge into the most used spelling with \
propose_tag_rename. A rename or merge applies to every asset carrying the tag. \
propose_tag_delete is for unused tags and junk (list_tags with max_uses 0 finds the unused \
ones); a tag still in use is better merged, and if asked to delete one anyway, say how many \
assets lose it. These change the vocabulary, not one asset, so use propose_changes only for \
the tags of particular assets.
- Change as little as you must. Leave a good name, description or summary alone. Propose \
changes to the assets the request is about, not to everything you happened to see.
- Names are short and plain. A description says what the asset shows or contains. A summary is \
Expand Down
Loading
Loading