feat(plugin): resolve session project from git remote, not a pinned project_id
The SessionStart hook asked for a project_id via plugin userConfig, which pins one install to a single project — wrong for an operator working across many repos/projects. Resolve the active project server-side from the working repo's git remote instead (a stable identifier, not a dir-name guess). - repo_bindings table (migration 0064) + RepoBinding model: (user, repo_key) -> project, FKs CASCADE. - services/repo_bindings: normalize_repo_key collapses ssh/https/scp/creds/port/ .git to host/owner/repo; resolve/set/list/delete. - GET /api/plugin/context takes ?repo=<remote>; unbound repo -> a "bind this repo" hint with a ready bind_repo() call. project_id kept as manual override. - MCP tools: bind_repo / list_repo_bindings / unbind_repo. - Hook sends ?repo=$(git remote get-url origin) URL-encoded; all project_id handling removed. plugin.json drops the project_id userConfig (0.1.2 -> 0.1.3). - Tests: normalize equivalence classes + unbound-hint rendering. Refs task 755 (Scribe-as-plugin push channel). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -40,9 +40,19 @@ async def _topic_titles(topic_ids: set[int]) -> dict[int, str]:
|
||||
return {tid: title for tid, title in rows.all()}
|
||||
|
||||
|
||||
async def build_session_context(user_id: int, project_id: int = 0) -> dict:
|
||||
async def build_session_context(
|
||||
user_id: int, project_id: int = 0, unbound_repo: str = ""
|
||||
) -> dict:
|
||||
"""Render the SessionStart context for a user, optionally project-scoped.
|
||||
|
||||
Args:
|
||||
user_id: the operator.
|
||||
project_id: the resolved active project (0 = none). The endpoint
|
||||
resolves this from the working repo's remote, not from config.
|
||||
unbound_repo: when the hook sent a repo remote that maps to no project,
|
||||
its normalized key — triggers a one-line "bind this repo" hint so
|
||||
the binding is self-healing.
|
||||
|
||||
Returns {"context": str, "rule_count": int, "project": dict | None}.
|
||||
`context` is markdown ready to drop into `additionalContext`; it is capped
|
||||
at _MAX_CHARS with an explicit truncation note so the hook can pass it
|
||||
@@ -86,6 +96,16 @@ async def build_session_context(user_id: int, project_id: int = 0) -> dict:
|
||||
f"Goal: {goal[:200]}" if goal else "",
|
||||
f"Open todo tasks: {open_count}",
|
||||
]
|
||||
elif unbound_repo:
|
||||
lines += [
|
||||
"",
|
||||
"## Repository not yet bound",
|
||||
f"This repo (`{unbound_repo}`) isn't mapped to a Scribe project, so "
|
||||
"no project context was loaded. Bind it once with "
|
||||
f'`bind_repo(repo_url="{unbound_repo}", project_id=<id>)` '
|
||||
"(call `list_projects` to find the id) and future sessions here will "
|
||||
"auto-load that project's context.",
|
||||
]
|
||||
|
||||
lines += [
|
||||
"",
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Repo -> project binding resolution.
|
||||
|
||||
The SessionStart hook sends the working repo's git remote; this module
|
||||
normalizes it to a stable `repo_key` and resolves it to a project id. The key
|
||||
deliberately collapses ssh/https forms of the same remote so the operator binds
|
||||
a repo once regardless of how it's cloned.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from scribe.models import async_session
|
||||
from scribe.models.repo_binding import RepoBinding
|
||||
|
||||
|
||||
def normalize_repo_key(raw: str) -> str:
|
||||
"""Reduce a git remote URL to a stable, scheme-agnostic ``host/owner/repo``.
|
||||
|
||||
Collapses the equivalent clone URLs to one key, e.g.::
|
||||
|
||||
git@git.fabledsword.com:bvandeusen/FabledScribe.git
|
||||
https://git.fabledsword.com/bvandeusen/fabledscribe.git
|
||||
ssh://git@git.fabledsword.com:22/bvandeusen/fabledscribe
|
||||
|
||||
all normalize to ``git.fabledsword.com/bvandeusen/fabledscribe``.
|
||||
|
||||
Returns "" for empty/garbage input so callers can treat it as "no repo".
|
||||
"""
|
||||
s = (raw or "").strip()
|
||||
if not s:
|
||||
return ""
|
||||
|
||||
# scp-like syntax: git@host:owner/repo(.git) -> ssh://host/owner/repo
|
||||
scp = re.match(r"^[^/@]+@([^:/]+):(.+)$", s)
|
||||
if scp and "://" not in s:
|
||||
s = f"//{scp.group(1)}/{scp.group(2)}"
|
||||
else:
|
||||
# strip an explicit scheme (https://, http://, ssh://, git://, git+ssh://)
|
||||
s = re.sub(r"^[a-z][a-z0-9+.\-]*://", "//", s, flags=re.IGNORECASE)
|
||||
if not s.startswith("//"):
|
||||
s = "//" + s
|
||||
|
||||
body = s[2:] # drop leading //
|
||||
# strip userinfo (user@ or user:pass@) on the authority
|
||||
body = re.sub(r"^[^/]*@", "", body)
|
||||
# drop an explicit port on the host (host:22/...)
|
||||
body = re.sub(r"^([^/:]+):\d+", r"\1", body)
|
||||
# strip trailing .git and surrounding slashes
|
||||
body = body.strip("/")
|
||||
if body.endswith(".git"):
|
||||
body = body[:-4]
|
||||
return body.lower()
|
||||
|
||||
|
||||
async def resolve_project(user_id: int, raw_repo: str) -> int | None:
|
||||
"""Return the bound project id for a repo remote, or None if unbound."""
|
||||
key = normalize_repo_key(raw_repo)
|
||||
if not key:
|
||||
return None
|
||||
async with async_session() as session:
|
||||
row = await session.execute(
|
||||
select(RepoBinding.project_id).where(
|
||||
RepoBinding.user_id == user_id, RepoBinding.repo_key == key
|
||||
)
|
||||
)
|
||||
return row.scalar_one_or_none()
|
||||
|
||||
|
||||
async def set_binding(user_id: int, raw_repo: str, project_id: int) -> RepoBinding:
|
||||
"""Create or update the binding for a repo. Idempotent on (user, repo_key)."""
|
||||
key = normalize_repo_key(raw_repo)
|
||||
if not key:
|
||||
raise ValueError("repo remote is empty or unparseable")
|
||||
async with async_session() as session:
|
||||
existing = await session.execute(
|
||||
select(RepoBinding).where(
|
||||
RepoBinding.user_id == user_id, RepoBinding.repo_key == key
|
||||
)
|
||||
)
|
||||
binding = existing.scalar_one_or_none()
|
||||
if binding is None:
|
||||
binding = RepoBinding(user_id=user_id, repo_key=key, project_id=project_id)
|
||||
session.add(binding)
|
||||
else:
|
||||
binding.project_id = project_id
|
||||
await session.commit()
|
||||
await session.refresh(binding)
|
||||
return binding
|
||||
|
||||
|
||||
async def list_bindings(user_id: int) -> list[RepoBinding]:
|
||||
async with async_session() as session:
|
||||
rows = await session.execute(
|
||||
select(RepoBinding)
|
||||
.where(RepoBinding.user_id == user_id)
|
||||
.order_by(RepoBinding.repo_key)
|
||||
)
|
||||
return list(rows.scalars().all())
|
||||
|
||||
|
||||
async def delete_binding(user_id: int, raw_repo: str) -> bool:
|
||||
"""Remove a repo's binding. Returns True if a row was deleted."""
|
||||
key = normalize_repo_key(raw_repo)
|
||||
if not key:
|
||||
return False
|
||||
async with async_session() as session:
|
||||
row = await session.execute(
|
||||
select(RepoBinding).where(
|
||||
RepoBinding.user_id == user_id, RepoBinding.repo_key == key
|
||||
)
|
||||
)
|
||||
binding = row.scalar_one_or_none()
|
||||
if binding is None:
|
||||
return False
|
||||
await session.delete(binding)
|
||||
await session.commit()
|
||||
return True
|
||||
Reference in New Issue
Block a user