Python
Project identity: binding > git > path; named memories and boards
Rohit C Prasad34aa6b8dd654
diff --git a/coworker/agent.py b/coworker/agent.pyindex 5ac82af2..5ce35ba0 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -188,6 +188,10 @@ def build_engine(max_iterations: Optional[int] = None,model_settings: Optional[dict[str, Any]] = None,memory_store: Optional[MemoryStore] = None,+ # Twentieth pass: the project key memory loads/saves under. Defaults to the+ # workspace path; the manager passes the resolved key (binding > git > path)+ # so all worktrees of a repo share one memory and named bindings work.+ memory_workspace: Optional[str] = None,# MEMORY-SPEC §5.1: called with the MemoryItem right after `remember` persists it —# the manager uses this to push the memory_saved event that powers the save toast.on_memory_saved: Optional[Any] = None,@@ -375,10 +379,11 @@ def build_engine(# Always the full toolset: the registry is fixed at build, so a session born# while saving was off must still be able to save the moment it's turned on.# Enforcement is the tools' own live check, not their absence.+ mem_ws = memory_workspace or (str(ws) if ws else None)registry.register_all(memory_tools(memory_store,- workspace=str(ws) if ws else None,+ workspace=mem_ws,on_saved=on_memory_saved,saving_enabled=_saving_enabled,)@@ -390,8 +395,8 @@ def build_engine(# so the facts are processed once instead of re-sent every turn. Deletions reach# NEW conversations; the UI says so rather than pretending otherwise.remembered = memory_store.list(scope=Scope.GLOBAL)- if ws is not None:- remembered += memory_store.list(scope=Scope.WORKSPACE, workspace=str(ws))+ if mem_ws is not None:+ remembered += memory_store.list(scope=Scope.WORKSPACE, workspace=mem_ws)block = render_memory_block(remembered)if block:instructions = f"{instructions}\n\n{block}"diff --git a/coworker/conversations.py b/coworker/conversations.pyindex d77fdb8a..1e6c5edb 100644--- a/coworker/conversations.py+++ b/coworker/conversations.py@@ -97,6 +97,7 @@ class ConversationStore:"ALTER TABLE sessions ADD COLUMN grants TEXT","ALTER TABLE sessions ADD COLUMN compaction TEXT","ALTER TABLE sessions ADD COLUMN team TEXT",+ "ALTER TABLE sessions ADD COLUMN bindings TEXT",):try:self._conn.execute(ddl)@@ -193,8 +194,8 @@ class ConversationStore:title = record.title or title_from(record.messages)self._conn.execute("""- INSERT INTO sessions (session_id, workspace, model, mode, title, agent, n_msgs, messages, extra_roots, grants, compaction, team, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, CURRENT_TIMESTAMP)+ INSERT INTO sessions (session_id, workspace, model, mode, title, agent, n_msgs, messages, extra_roots, grants, compaction, team, bindings, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)ON CONFLICT(session_id) DO UPDATE SETworkspace = excluded.workspace, model = excluded.model, mode = excluded.mode,title = COALESCE(sessions.title, excluded.title), agent = excluded.agent,@@ -214,6 +215,7 @@ class ConversationStore:json.dumps(record.grants or {}),json.dumps(record.compaction or {}),json.dumps(record.team or {}),+ json.dumps(record.bindings or {}),),)self._conn.commit()@@ -255,6 +257,9 @@ class ConversationStore:origin=row["origin"],origin_label=row["origin_label"],team=_load_grants(row["team"] if "team" in row.keys() else None),+ bindings=_load_grants(+ row["bindings"] if "bindings" in row.keys() else None+ ),)def set_team(self, session_id: str, team: dict) -> None:@@ -269,6 +274,25 @@ class ConversationStore:)self._conn.commit()+ def names(self):+ """The project-names alias table, riding this store's connection."""+ from .projects import ProjectNames++ if not hasattr(self, "_names"):+ self._names = ProjectNames(self._conn, self._lock)+ return self._names++ def set_bindings(self, session_id: str, bindings: dict) -> None:+ """Persist the session's project bindings independent of the turn-save path+ (same shape as `team`: the per-turn upsert never touches this column, so a+ rebuild can't silently unbind a session)."""+ with self._lock:+ self._conn.execute(+ "UPDATE sessions SET bindings = ? WHERE session_id = ?",+ (json.dumps(bindings or {}), session_id),+ )+ self._conn.commit()+def set_extra_roots(self, session_id: str, extra_roots: list[dict]) -> None:"""Persist just the session's added folders, independent of its message log — used whenthe user adds/removes a folder (which may happen with no active engine)."""diff --git a/coworker/memory/sqlite_store.py b/coworker/memory/sqlite_store.pyindex 8d57f902..4829081e 100644--- a/coworker/memory/sqlite_store.py+++ b/coworker/memory/sqlite_store.py@@ -128,6 +128,21 @@ class SQLiteMemoryStore(MemoryStore):self._conn.commit()return cursor.rowcount+ def rekey_workspace(self, old: str, new: str) -> int:+ """Re-key workspace-scoped memories from one project key to another — the+ twentieth-pass one-time path→git migration. Rows are independent, so a+ collision with existing rows under `new` is just a union. Returns the+ number of rows moved."""+ if old == new:+ return 0+ with self._lock:+ cursor = self._conn.execute(+ "UPDATE memories SET workspace = ? WHERE workspace = ? AND scope = ?",+ (new, old, Scope.WORKSPACE.value),+ )+ self._conn.commit()+ return cursor.rowcount+def close(self) -> None:self._conn.close()diff --git a/coworker/projects.py b/coworker/projects.pynew file mode 100644index 00000000..b64cd0be--- /dev/null+++ b/coworker/projects.py@@ -0,0 +1,231 @@+"""Project identity — the key under boards and workspace memory, plus user names.++Twentieth-pass ladder (agent-teams-design.md): an explicit per-session binding+beats derivation; derivation prefers the git repo (all worktrees of one repo+collapse to one project); a plain folder falls back to its resolved path — the+status-quo key. Resolution happens at discrete moments (engine build, root+grant); nothing watches the filesystem.+"""++from __future__ import annotations++import sqlite3+import subprocess+import threading+from pathlib import Path+from typing import Any, Optional++NAME_KINDS = ("memory", "board")+MAX_NAME_CHARS = 60+++def _git_common_dir(workspace: Path) -> Optional[Path]:+ try:+ out = subprocess.run(+ ["git", "-C", str(workspace), "rev-parse", "--git-common-dir"],+ capture_output=True, text=True, timeout=5,+ )+ except (OSError, subprocess.TimeoutExpired):+ return None+ if out.returncode != 0:+ return None+ raw = out.stdout.strip()+ if not raw:+ return None+ p = Path(raw)+ if not p.is_absolute():+ p = workspace / p+ try:+ return p.resolve()+ except OSError:+ return None+++def project_key(workspace: str | Path) -> str:+ """Derive the project key for a directory. Git repo → the repo directory+ (common-dir's parent — shared by every worktree); otherwise the resolved+ path. Never raises; a missing directory just resolves as a path."""+ ws = Path(workspace).expanduser()+ try:+ ws = ws.resolve()+ except OSError:+ ws = Path(str(workspace))+ if ws.is_dir():+ common = _git_common_dir(ws)+ if common is not None:+ # Normal layout: <repo>/.git → key is <repo>. Bare/odd layouts keep+ # the common dir itself — still one stable key per repo.+ return str(common.parent if common.name == ".git" else common)+ return str(ws)+++def project_label(key: str, *, home: Optional[str] = None) -> dict[str, Any]:+ """Display info for a derived key. kind 'git' when the key currently looks+ like a repo (has a .git); label rules per UX-044: git = repo folder name,+ folder = ~-collapsed path (the GUI trims to the last 3 segments)."""+ p = Path(key)+ is_git = (p / ".git").exists()+ full = key+ h = home or str(Path.home())+ shown = key+ if shown == h:+ shown = "~"+ elif shown.startswith(h + "/"):+ shown = "~" + shown[len(h):]+ return {+ "kind": "git" if is_git else "folder",+ "label": p.name if is_git else shown,+ "full": full,+ }+++class ProjectNames:+ """User-given names for memories and boards — aliases over project keys.+ One table in the session DB; a name never moves data, it only points."""++ def __init__(self, conn: sqlite3.Connection, lock: threading.RLock) -> None:+ self._conn = conn+ self._lock = lock+ with self._lock:+ self._conn.execute(+ """CREATE TABLE IF NOT EXISTS project_names (+ kind TEXT NOT NULL, name TEXT NOT NULL, key TEXT NOT NULL,+ last_used_at TEXT NOT NULL DEFAULT (datetime('now')),+ PRIMARY KEY (kind, name)+ )"""+ )+ self._conn.commit()++ def name_current(self, kind: str, name: str, key: str) -> dict[str, Any]:+ name = (name or "").strip()[:MAX_NAME_CHARS]+ if kind not in NAME_KINDS:+ raise ValueError(f"unknown kind {kind!r}")+ if not name:+ raise ValueError("empty name")+ with self._lock:+ self._conn.execute(+ "INSERT INTO project_names (kind, name, key) VALUES (?, ?, ?) "+ "ON CONFLICT (kind, name) DO UPDATE SET key = excluded.key, "+ "last_used_at = datetime('now')",+ (kind, name, key),+ )+ self._conn.commit()+ return {"kind": kind, "name": name, "key": key}++ def resolve(self, kind: str, name: str) -> Optional[str]:+ with self._lock:+ row = self._conn.execute(+ "SELECT key FROM project_names WHERE kind = ? AND name = ?",+ (kind, name),+ ).fetchone()+ return row[0] if row else None++ def touch(self, kind: str, name: str) -> None:+ """Bump MRU when a binding is used."""+ with self._lock:+ self._conn.execute(+ "UPDATE project_names SET last_used_at = datetime('now') "+ "WHERE kind = ? AND name = ?",+ (kind, name),+ )+ self._conn.commit()++ def list(self, kind: str, *, limit: Optional[int] = None) -> list[dict[str, Any]]:+ q = (+ "SELECT name, key, last_used_at FROM project_names "+ "WHERE kind = ? ORDER BY last_used_at DESC, name"+ )+ args: list[Any] = [kind]+ if limit:+ q += " LIMIT ?"+ args.append(limit)+ with self._lock:+ rows = self._conn.execute(q, args).fetchall()+ return [{"name": r[0], "key": r[1], "last_used_at": r[2]} for r in rows]++ def forget(self, kind: str, name: str) -> bool:+ with self._lock:+ cur = self._conn.execute(+ "DELETE FROM project_names WHERE kind = ? AND name = ?", (kind, name)+ )+ self._conn.commit()+ return cur.rowcount > 0+++def resolve_memory_key(+ workspace: Optional[str],+ *,+ binding: Optional[str] = None,+ names: Optional["ProjectNames"] = None,+ memory_store: Any = None,+) -> Optional[str]:+ """The identity ladder for memory: explicit binding > git > path. Applies the+ one-time path→git re-key as a read-path side effect (idempotent: once moved,+ the path key has no rows left to move)."""+ if binding and names is not None:+ key = names.resolve("memory", binding)+ if key:+ names.touch("memory", binding)+ return key+ if not workspace:+ return None+ derived = project_key(workspace)+ path_key = str(Path(workspace).expanduser().resolve()) if Path(+ workspace+ ).expanduser().exists() else str(Path(workspace).expanduser())+ if memory_store is not None and derived != path_key:+ try:+ memory_store.rekey_workspace(path_key, derived)+ except Exception:+ pass+ return derived+++def resolve_board_space(+ workspace: Optional[str],+ *,+ binding: Optional[str] = None,+ names: Optional["ProjectNames"] = None,+ team_store: Any = None,+) -> Optional[str]:+ """The identity ladder for the board space — same ladder, board collision+ rule: when both a path-keyed and a git-keyed space have events, the git key+ wins and the path space stays dormant (rekey_space refuses; nothing merges)."""+ if binding and names is not None:+ key = names.resolve("board", binding)+ if key:+ names.touch("board", binding)+ return key+ if not workspace:+ return None+ derived = project_key(workspace)+ path_key = str(Path(workspace).expanduser().resolve()) if Path(+ workspace+ ).expanduser().exists() else str(Path(workspace).expanduser())+ if team_store is not None and derived != path_key:+ try:+ team_store.rekey_space(path_key, derived)+ except Exception:+ pass+ return derived+++def project_presence(+ key: str, *, memory_store: Any = None, team_store: Any = None+) -> dict[str, int]:+ """What already exists under a project key — feeds the grant-time notice.+ Counts only; the notice is a pointer, never content."""+ memories = 0+ items = 0+ if memory_store is not None:+ try:+ memories = len(memory_store.list(workspace=key))+ except Exception:+ pass+ if team_store is not None:+ try:+ # A cheap existence probe that needs no actor: any event under the key.+ items = team_store.event_count(key)+ except Exception:+ pass+ return {"memories": memories, "board_items": items}diff --git a/coworker/server/app.py b/coworker/server/app.pyindex 04ab0f19..d61dee8d 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -1143,6 +1143,27 @@ def create_app(manager: SessionManager) -> FastAPI:def memory_delete_all() -> dict[str, Any]:return manager.delete_all_memory()+ # -- project bindings (pass 20 / UX-044) --------------------------------------++ @app.get("/v1/sessions/{session_id}/project-menu")+ def project_menu(session_id: str, kind: str = "memory") -> dict[str, Any]:+ return manager.project_menu(session_id, kind)++ @app.put("/v1/sessions/{session_id}/bindings")+ def put_binding(session_id: str, body: dict) -> dict[str, Any]:+ body = body or {}+ name = body.get("name")+ return manager.set_binding(+ session_id, str(body.get("kind", "")), str(name) if name else None+ )++ @app.post("/v1/sessions/{session_id}/project-name")+ def name_project(session_id: str, body: dict) -> dict[str, Any]:+ body = body or {}+ return manager.name_current_project(+ session_id, str(body.get("kind", "")), str(body.get("name", ""))+ )+@app.post("/v1/chat/completions")def chat_completions(body: dict) -> dict[str, Any]:model = body.get("model", manager.model)diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex a040f428..07ae30c3 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -87,7 +87,13 @@ from ..sessions import SessionRecordfrom ..teams import Actor as TeamActorfrom ..teams import BoardError as TeamsBoardErrorfrom ..teams import JournalStore, Role as TeamRole, TeamStore, board_tools, journal_tools-from ..teams.model import space_for_workspace+from ..projects import (+ project_key,+ project_label,+ project_presence,+ resolve_board_space,+ resolve_memory_key,+)from ..teams.chat import ChatStorefrom ..teams.registry import TeamRegistry, TeamWorkerfrom ..teams.attachments import AttachmentStore@@ -644,6 +650,7 @@ class SessionManager:# and stay usable, only the write tools go. Read at build time; running# sessions finish under the mode they started with.memory_store=self.memory_store,+ memory_workspace=self._memory_key_for(record, ws),memory_off=not self.memory_settings.enabled,# LIVE, not a snapshot: turning saving off mid-conversation must take# effect at once (owner-hit 2026-07-28 — a running session kept saving).@@ -1645,10 +1652,32 @@ class SessionManager:# ------------------------------------------------------------- agent teams (OPE-96)+ # ------------------------------------------------- project identity (pass 20)++ def _memory_key_for(self, record, ws: Optional[str]) -> Optional[str]:+ """Binding > git > path, with the one-time path→git re-key on the way."""+ binding = ((record.bindings if record else {}) or {}).get("memory")+ return resolve_memory_key(+ ws,+ binding=binding,+ names=self.session_store.names(),+ memory_store=self.memory_store,+ )++ def _space_for(self, record, ws: Optional[str]) -> Optional[str]:+ """Board-space twin of _memory_key_for — same ladder, board collision rule."""+ binding = ((record.bindings if record else {}) or {}).get("board")+ return resolve_board_space(+ ws,+ binding=binding,+ names=self.session_store.names(),+ team_store=self.team_store,+ )+def _board_space(self, session_id: str) -> Optional[str]:record = self.session_store.load(session_id)workspace = (record.workspace if record else None) or self.default_workspace- return space_for_workspace(workspace) if workspace else None+ return self._space_for(record, workspace) if workspace else Nonedef _user_actor(self) -> TeamActor:return TeamActor(id="user", role=TeamRole.USER)@@ -1758,7 +1787,7 @@ class SessionManager:record = self.session_store.load(session_id)if record is None or not record.workspace:return {"approved": False, "error": "the session has no workspace"}- space = space_for_workspace(record.workspace)+ space = self._space_for(record, record.workspace)actor = TeamActor(id=f"{record.agent}:{session_id[:8]}",role=TeamRole.LEAD,@@ -1839,7 +1868,7 @@ class SessionManager:role = "lead"if role is None or not ws:return []- space = space_for_workspace(ws)+ space = self._space_for(record, ws)if role == "worker":info = (record.team if record is not None else {}) or {}actor = TeamActor(@@ -2034,7 +2063,7 @@ class SessionManager:return {"approved": False, "error": "the lead session has no workspace"}if self.teams.for_lead_session(session_id) is not None:return {"approved": False, "error": "this session already leads a team"}- space = space_for_workspace(record.workspace)+ space = self._space_for(record, record.workspace)workers: list[TeamWorker] = []used: set[str] = {"lead", "user", "board"} # reserved handlesfor member in members:@@ -4276,6 +4305,7 @@ class SessionManager:approver=self._scheduled_approver(task, session_id),provider=self.provider,memory_store=self.memory_store,+ memory_workspace=self._memory_key_for(None, task.workspace),memory_off=not self.memory_settings.enabled,memory_saving_enabled=lambda: self.memory_settings.enabled,# Callable, not a snapshot: editing your instructions in Settings applies@@ -5290,7 +5320,32 @@ class SessionManager:],)self.session_store.touch_workspace(str(resolved))- return {"ok": True, "roots": self.get_roots(session_id)}+ # Grant-time notice (pass 20): if this directory's project already has+ # memory or a board, say so — one line, pointer only, to agent + user.+ notice = self._project_notice(str(resolved))+ engine = self._engines.get(session_id)+ if notice and engine is not None:+ engine._append_notice("project_presence", notice)+ return {"ok": True, "roots": self.get_roots(session_id), "notice": notice}++ def _project_notice(self, path: str) -> Optional[str]:+ """One-line presence pointer for a newly granted directory, or None."""+ try:+ key = project_key(path)+ pres = project_presence(+ key, memory_store=self.memory_store, team_store=self.team_store+ )+ except Exception:+ return None+ parts = []+ if pres["memories"]:+ parts.append(f"project memory ({pres['memories']} entries)")+ if pres["board_items"]:+ parts.append("a board")+ if not parts:+ return None+ label = project_label(key)["label"]+ return f"“{label}” already has {' and '.join(parts)} — bind it by name or start a session there to use it."def remove_root(self, session_id: str, path: str) -> dict[str, Any]:"""Revoke a previously-added folder. The primary scratch cannot be removed."""@@ -5779,6 +5834,71 @@ class SessionManager:return notify+ # -- project bindings (pass 20 / UX-044) -------------------------------------++ def project_menu(self, session_id: str, kind: str) -> dict[str, Any]:+ """The submenu payload: the session's derived project (pinned, labeled per+ the UX-044 rules) + named entries MRU-ordered. The GUI shows 5 and grows a+ filter at 6+; the full named list ships so the filter reaches everything."""+ record = self.session_store.load(session_id)+ ws = (record.workspace if record else None) or self.default_workspace+ derived_key = project_key(ws) if ws else None+ names = self.session_store.names()+ bound = ((record.bindings if record else {}) or {}).get(kind)+ named = names.list(kind)+ return {+ "kind": kind,+ "bound": bound,+ "derived": (+ {**project_label(derived_key), "key": derived_key}+ if derived_key+ else None+ ),+ "named": [{"name": n["name"], "key": n["key"]} for n in named],+ }++ def set_binding(+ self, session_id: str, kind: str, name: Optional[str]+ ) -> dict[str, Any]:+ """Bind (or unbind, name=None) a named project for this session. Takes+ effect at the next engine build — the running engine keeps the knowledge+ it started with (same doctrine as memory deletions)."""+ if kind not in ("memory", "board"):+ return {"ok": False, "error": f"unknown kind {kind!r}"}+ if self.is_running(session_id):+ return {"ok": False, "error": "wait for the current task to finish first"}+ if name and self.session_store.names().resolve(kind, name) is None:+ return {"ok": False, "error": f"no {kind} named {name!r}"}+ record = self.session_store.load(session_id)+ bindings = dict((record.bindings if record else {}) or {})+ if name:+ bindings[kind] = name+ else:+ bindings.pop(kind, None)+ if record is None:+ return {"ok": False, "error": "unknown session"}+ self.session_store.set_bindings(session_id, bindings)+ # Rebind applies from the next engine build; drop the cached engine so the+ # next turn rebuilds with the new key (messages persist via the record).+ self._engines.pop(session_id, None)+ return {"ok": True, "bindings": bindings}++ def name_current_project(+ self, session_id: str, kind: str, name: str+ ) -> dict[str, Any]:+ """Give the session's derived project a user name (UX-044 'Name current…')."""+ record = self.session_store.load(session_id)+ ws = (record.workspace if record else None) or self.default_workspace+ if not ws:+ return {"ok": False, "error": "session has no workspace"}+ try:+ entry = self.session_store.names().name_current(+ kind, name, project_key(ws)+ )+ except ValueError as e:+ return {"ok": False, "error": str(e)}+ return {"ok": True, **entry}+def list_memory(self) -> list[dict[str, Any]]:return [{diff --git a/coworker/sessions.py b/coworker/sessions.pyindex 33f176d5..0e18cf27 100644--- a/coworker/sessions.py+++ b/coworker/sessions.py@@ -37,6 +37,9 @@ class SessionRecord:# Auto-compaction state (OPE-27): CompactionState.as_dict(), {} when never compacted.# Persisted so a reloaded session keeps its compacted outbound view.compaction: dict[str, Any] = field(default_factory=dict)+ # Twentieth pass: explicit per-session project bindings, {} = derive from the+ # workspace. Keys "memory" / "board", values = names in project_names.+ bindings: dict[str, Any] = field(default_factory=dict)# Agent teams: {} for plain sessions. Workers: {team_id, role: "worker", actor,# lead_session, space}. Leads gain their entry when the staffing gate creates the# team. Drives tool binding (board actor identity) + the sidebar's expandable entry.diff --git a/coworker/teams/store.py b/coworker/teams/store.pyindex df52e529..876347bf 100644--- a/coworker/teams/store.py+++ b/coworker/teams/store.py@@ -943,6 +943,93 @@ class TeamStore:).fetchone()return int(row["top"] or 0) + 1+ def event_count(self, space: str) -> int:+ """How many records a space holds — presence probe for the grant-time+ notice and the migration collision check. No actor: counts, not content."""+ with self._lock:+ row = self._conn.execute(+ "SELECT COUNT(*) FROM team_events WHERE space = ?", (space,)+ ).fetchone()+ return int(row[0]) if row else 0++ def rekey_space(self, old: str, new: str) -> bool:+ """Move one space's records under a new key — the twentieth-pass one-time+ path→git migration. `space` participates in the hash chain, so the chain+ is honestly RECOMPUTED in seq order (a wholesale re-key, not tampering).+ Refuses (returns False) when the target space already has events — the+ dumb collision rule: git key wins, the old space stays dormant."""+ if old == new:+ return True+ with self._lock:+ has_new = self._conn.execute(+ "SELECT 1 FROM team_events WHERE space = ? LIMIT 1", (new,)+ ).fetchone()+ if has_new:+ return False+ rows = self._conn.execute(+ "SELECT * FROM team_events WHERE space = ? ORDER BY seq", (old,)+ ).fetchall()+ try:+ prev = GENESIS+ for row in rows:+ record = {+ "ts": row["ts"],+ "space": new,+ "kind": row["kind"],+ "actor": row["actor"],+ "actor_role": row["actor_role"],+ "item_id": row["item_id"],+ "case_id": row["case_id"],+ "recipient": row["recipient"],+ "payload": row["payload"],+ "taint": row["taint"],+ "prev_hash": prev,+ }+ record["hash"] = _hash(record)+ self._conn.execute(+ "UPDATE team_events SET space = ?, prev_hash = ?, hash = ? "+ "WHERE seq = ?",+ (new, prev, record["hash"], row["seq"]),+ )+ prev = record["hash"]+ for table in ("team_items", "team_links", "team_settings"):+ self._conn.execute(+ f"UPDATE {table} SET space = ? WHERE space = ?", (new, old)+ )+ # Cursor keys embed the space as a suffix ("feed:<actor>:<space>",+ # "sub:<sub>:<space>") — rewrite the suffix, keep consumed positions.+ cur_rows = self._conn.execute(+ "SELECT cursor_key FROM team_cursors WHERE cursor_key LIKE ?",+ ("%:" + old,),+ ).fetchall()+ for crow in cur_rows:+ new_key = crow["cursor_key"][: -len(old)] + new+ self._conn.execute(+ "UPDATE OR REPLACE team_cursors SET cursor_key = ? "+ "WHERE cursor_key = ?",+ (new_key, crow["cursor_key"]),+ )+ meta = self._conn.execute(+ "SELECT watermark FROM team_meta WHERE space = ?", (old,)+ ).fetchone()+ if meta is not None and rows:+ self._conn.execute(+ "DELETE FROM team_meta WHERE space = ?", (old,)+ )+ self._conn.execute(+ "INSERT INTO team_meta (space, head_hash, watermark) "+ "VALUES (?, ?, ?) ON CONFLICT(space) DO UPDATE SET "+ "head_hash = excluded.head_hash, watermark = excluded.watermark",+ (new, prev, meta["watermark"]),+ )+ elif meta is not None:+ self._conn.execute("DELETE FROM team_meta WHERE space = ?", (old,))+ except Exception:+ self._conn.rollback()+ raise+ self._conn.commit()+ return True+def _head_hash(self, space: str) -> str:row = self._conn.execute("SELECT head_hash FROM team_meta WHERE space = ?", (space,)diff --git a/tests/test_project_bindings.py b/tests/test_project_bindings.pynew file mode 100644index 00000000..51c7a27e--- /dev/null+++ b/tests/test_project_bindings.py@@ -0,0 +1,178 @@+"""Pass 20 — project bindings over the manager/API surface (UX-044 backend)."""++from __future__ import annotations++import subprocess+from pathlib import Path++from fastapi.testclient import TestClient++from coworker.memory.base import Scope+from coworker.providers import ModelCapabilities, ProviderClient+from coworker.server import SessionManager, create_app+from coworker.sessions import SessionRecord+++class _StubProvider(ProviderClient):+ def complete(self, **kwargs): # pragma: no cover+ raise NotImplementedError++ def capabilities(self, model):+ return ModelCapabilities()+++def _fixture(tmp_path):+ manager = SessionManager(workspace=tmp_path, provider=_StubProvider())+ return TestClient(create_app(manager)), manager+++def _seed_session(manager, sid: str, workspace: Path) -> None:+ manager.session_store.save(+ SessionRecord(+ session_id=sid,+ workspace=str(workspace),+ model="m",+ mode="auto",+ messages=[{"role": "user", "content": "hi"}],+ )+ )+++def test_project_menu_derived_and_named(tmp_path):+ client, manager = _fixture(tmp_path)+ ws = tmp_path / "proj"+ ws.mkdir()+ _seed_session(manager, "s1", ws)++ menu = client.get("/v1/sessions/s1/project-menu", params={"kind": "memory"}).json()+ assert menu["bound"] is None+ assert menu["derived"]["key"] == str(ws.resolve())+ assert menu["derived"]["kind"] == "folder"+ assert menu["named"] == []++ named = client.post(+ "/v1/sessions/s1/project-name", json={"kind": "memory", "name": "myproj"}+ ).json()+ assert named["ok"] and named["key"] == str(ws.resolve())+ menu = client.get("/v1/sessions/s1/project-menu", params={"kind": "memory"}).json()+ assert [n["name"] for n in menu["named"]] == ["myproj"]+++def test_binding_swaps_memory_key(tmp_path):+ client, manager = _fixture(tmp_path)+ ws = tmp_path / "scratch"+ ws.mkdir()+ other = tmp_path / "real"+ other.mkdir()+ _seed_session(manager, "s1", ws)++ manager.session_store.names().name_current(+ "memory", "openworker", str(other.resolve())+ )+ manager.memory_store.add(+ "the real fact", scope=Scope.WORKSPACE, workspace=str(other.resolve())+ )++ put = client.put(+ "/v1/sessions/s1/bindings", json={"kind": "memory", "name": "openworker"}+ ).json()+ assert put["ok"] and put["bindings"] == {"memory": "openworker"}++ record = manager.session_store.load("s1")+ key = manager._memory_key_for(record, record.workspace)+ assert key == str(other.resolve())++ # unbind → back to derivation+ put = client.put("/v1/sessions/s1/bindings", json={"kind": "memory"}).json()+ assert put["ok"] and put["bindings"] == {}+ record = manager.session_store.load("s1")+ assert manager._memory_key_for(record, record.workspace) == str(ws.resolve())+++def test_binding_rejects_unknown_name_and_kind(tmp_path):+ client, manager = _fixture(tmp_path)+ _seed_session(manager, "s1", tmp_path)+ assert not client.put(+ "/v1/sessions/s1/bindings", json={"kind": "memory", "name": "ghost"}+ ).json()["ok"]+ assert not client.put(+ "/v1/sessions/s1/bindings", json={"kind": "nope", "name": "x"}+ ).json()["ok"]+++def test_bindings_survive_turn_save(tmp_path):+ """The per-turn upsert must not clobber bindings (same doctrine as team)."""+ client, manager = _fixture(tmp_path)+ ws = tmp_path / "p"+ ws.mkdir()+ _seed_session(manager, "s1", ws)+ manager.session_store.names().name_current("board", "b1", "/somewhere")+ assert client.put(+ "/v1/sessions/s1/bindings", json={"kind": "board", "name": "b1"}+ ).json()["ok"]++ # simulate a turn-save rebuilding the record WITHOUT bindings+ rec = manager.session_store.load("s1")+ manager.session_store.save(+ SessionRecord(+ session_id="s1",+ workspace=rec.workspace,+ model=rec.model,+ mode=rec.mode,+ messages=rec.messages,+ )+ )+ assert manager.session_store.load("s1").bindings == {"board": "b1"}+++def test_board_space_follows_binding(tmp_path):+ client, manager = _fixture(tmp_path)+ ws = tmp_path / "p"+ ws.mkdir()+ _seed_session(manager, "s1", ws)+ manager.session_store.names().name_current("board", "shared", "/the/shared/space")+ client.put("/v1/sessions/s1/bindings", json={"kind": "board", "name": "shared"})+ assert manager._board_space("s1") == "/the/shared/space"+++def test_worktree_sessions_share_memory_key(tmp_path):+ _, manager = _fixture(tmp_path)+ repo = tmp_path / "repo"+ repo.mkdir()+ for args in (["init", "-q"],):+ subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)+ (repo / "f").write_text("x")+ subprocess.run(+ ["git", "-c", "user.name=t", "-c", "user.email=t@t", "add", "f"],+ cwd=repo, check=True, capture_output=True,+ )+ subprocess.run(+ ["git", "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "i"],+ cwd=repo, check=True, capture_output=True,+ )+ wt = tmp_path / "wt"+ subprocess.run(+ ["git", "worktree", "add", "-q", str(wt)],+ cwd=repo, check=True, capture_output=True,+ )+ _seed_session(manager, "a", repo)+ _seed_session(manager, "b", wt)+ ra, rb = manager.session_store.load("a"), manager.session_store.load("b")+ ka = manager._memory_key_for(ra, ra.workspace)+ kb = manager._memory_key_for(rb, rb.workspace)+ assert ka == kb == str(repo.resolve())+++def test_grant_notice_fires_on_existing_memory(tmp_path):+ _, manager = _fixture(tmp_path)+ granted = tmp_path / "known"+ granted.mkdir()+ manager.memory_store.add(+ "fact", scope=Scope.WORKSPACE, workspace=str(granted.resolve())+ )+ notice = manager._project_notice(str(granted))+ assert notice is not None and "project memory (1 entries)" in notice++ empty = tmp_path / "fresh"+ empty.mkdir()+ assert manager._project_notice(str(empty)) is Nonediff --git a/tests/test_projects.py b/tests/test_projects.pynew file mode 100644index 00000000..dc2b0e72--- /dev/null+++ b/tests/test_projects.py@@ -0,0 +1,171 @@+"""Project identity (twentieth pass): key derivation, naming, one-time migration."""++import sqlite3+import subprocess+import threading+from pathlib import Path++import pytest++from coworker.memory.base import Scope+from coworker.memory.sqlite_store import SQLiteMemoryStore+from coworker.projects import (+ ProjectNames,+ project_key,+ project_label,+ project_presence,+ resolve_board_space,+ resolve_memory_key,+)+from coworker.teams.store import GENESIS, TeamStore+from coworker.teams.model import Actor, Role+++def _git(cwd: Path, *args: str) -> None:+ subprocess.run(+ ["git", "-c", "user.name=t", "-c", "user.email=t@t", *args],+ cwd=cwd, check=True, capture_output=True,+ )+++def repo(tmp_path: Path) -> Path:+ r = tmp_path / "repo"+ r.mkdir()+ _git(r, "init", "-q")+ (r / "a.txt").write_text("x")+ _git(r, "add", "a.txt")+ _git(r, "commit", "-qm", "init")+ return r+++class TestProjectKey:+ def test_plain_dir_is_resolved_path(self, tmp_path):+ d = tmp_path / "plain"+ d.mkdir()+ assert project_key(d) == str(d.resolve())++ def test_missing_dir_falls_back_to_path(self, tmp_path):+ d = tmp_path / "nope"+ assert project_key(d) == str(d.resolve())++ def test_repo_root_keys_to_repo(self, repo):+ assert project_key(repo) == str(repo.resolve())++ def test_subdir_keys_to_repo(self, repo):+ sub = repo / "src" / "deep"+ sub.mkdir(parents=True)+ assert project_key(sub) == str(repo.resolve())++ def test_worktrees_share_one_key(self, repo, tmp_path):+ wt = tmp_path / "wt"+ _git(repo, "worktree", "add", "-q", str(wt))+ assert project_key(wt) == project_key(repo) == str(repo.resolve())++ def test_labels(self, repo, tmp_path):+ lab = project_label(str(repo.resolve()))+ assert lab["kind"] == "git" and lab["label"] == "repo"+ plain = tmp_path / "plain"+ plain.mkdir()+ lab2 = project_label(str(plain.resolve()))+ assert lab2["kind"] == "folder"++ def test_label_home_collapse(self, tmp_path):+ lab = project_label(str(tmp_path / "x" / "y"), home=str(tmp_path))+ assert lab["label"] == "~/x/y"+++class TestProjectNames:+ @pytest.fixture()+ def names(self, tmp_path):+ conn = sqlite3.connect(tmp_path / "t.db", check_same_thread=False)+ conn.row_factory = sqlite3.Row+ return ProjectNames(conn, threading.RLock())++ def test_name_resolve_roundtrip(self, names):+ names.name_current("memory", "openworker", "/k1")+ assert names.resolve("memory", "openworker") == "/k1"+ assert names.resolve("board", "openworker") is None # kinds are separate++ def test_rename_repoints(self, names):+ names.name_current("memory", "ops", "/k1")+ names.name_current("memory", "ops", "/k2")+ assert names.resolve("memory", "ops") == "/k2"++ def test_mru_order_and_limit(self, names):+ import time+ for i, n in enumerate(["a", "b", "c"]):+ names.name_current("memory", n, f"/k{i}")+ names._conn.execute(+ "UPDATE project_names SET last_used_at = datetime('now', '-1 hour') "+ "WHERE name != 'a'"+ )+ listed = names.list("memory", limit=2)+ assert [x["name"] for x in listed] == ["a", "b"]++ def test_rejects_bad_input(self, names):+ with pytest.raises(ValueError):+ names.name_current("memory", " ", "/k")+ with pytest.raises(ValueError):+ names.name_current("nope", "x", "/k")++ def test_forget(self, names):+ names.name_current("board", "x", "/k")+ assert names.forget("board", "x") is True+ assert names.resolve("board", "x") is None+++class TestMigration:+ def test_memory_rekey_unions(self, tmp_path):+ store = SQLiteMemoryStore(tmp_path / "m.db")+ store.add("old fact", scope=Scope.WORKSPACE, workspace="/old")+ store.add("git fact", scope=Scope.WORKSPACE, workspace="/new")+ moved = store.rekey_workspace("/old", "/new")+ assert moved == 1+ assert {m.content for m in store.list(workspace="/new")} == {"old fact", "git fact"}+ assert store.list(workspace="/old") == []++ def test_board_rekey_recomputes_chain(self, tmp_path):+ store = TeamStore(tmp_path / "b.db")+ lead = Actor(id="lead", role=Role.LEAD)+ store.create_item("/old", lead, title="one", criteria="c1")+ store.create_item("/old", lead, title="two", criteria="c2")+ assert store.rekey_space("/old", "/new") is True+ assert store.event_count("/old") == 0+ assert store.event_count("/new") == 2+ assert store.verify_chain("/new") == 2 # chain honestly recomputed++ def test_board_rekey_refuses_occupied_target(self, tmp_path):+ store = TeamStore(tmp_path / "b.db")+ lead = Actor(id="lead", role=Role.LEAD)+ store.create_item("/old", lead, title="old item", criteria="c")+ store.create_item("/new", lead, title="new item", criteria="c")+ assert store.rekey_space("/old", "/new") is False+ assert store.event_count("/old") == 1 # dormant, untouched+++class TestResolvers:+ def test_binding_beats_derivation(self, tmp_path):+ conn = sqlite3.connect(tmp_path / "t.db", check_same_thread=False)+ conn.row_factory = sqlite3.Row+ names = ProjectNames(conn, threading.RLock())+ names.name_current("memory", "openworker", "/the/real/project")+ key = resolve_memory_key(str(tmp_path), binding="openworker", names=names)+ assert key == "/the/real/project"++ def test_derivation_migrates_memory(self, repo, tmp_path):+ store = SQLiteMemoryStore(tmp_path / "m.db")+ sub = repo / "src"+ sub.mkdir()+ store.add("learned here", scope=Scope.WORKSPACE, workspace=str(sub.resolve()))+ key = resolve_memory_key(str(sub), memory_store=store)+ assert key == str(repo.resolve())+ assert [m.content for m in store.list(workspace=key)] == ["learned here"]++ def test_presence_counts(self, tmp_path):+ mstore = SQLiteMemoryStore(tmp_path / "m.db")+ tstore = TeamStore(tmp_path / "b.db")+ mstore.add("f", scope=Scope.WORKSPACE, workspace="/p")+ tstore.create_item("/p", Actor(id="l", role=Role.LEAD), title="t", criteria="c")+ pres = project_presence("/p", memory_store=mstore, team_store=tstore)+ assert pres == {"memories": 1, "board_items": 1}