Files
ai-agent/backend/projects/worker_projects.py

543 lines
22 KiB
Python

"""Projects on a worker — deduced from where its conversations wrote files.
A conversation on the lab is filed under a project when it edits
``~/projects/<slug>/…`` (``conversations/parse/tools.py:_projects_in``). A worker —
the Orus MacBook, a guest's own computer — has no such layout: Akira keeps
their games in ``~/PROJETS/wall-e game/far-waste``, the Orus repo is
``~/WORK/ORUS/orus`` with worktrees beside it (``orus-ins-2308``) and inside
it (``.claude/worktrees/…``). The hub can't look at that disk, so a worker
project is read off the transcripts, per worker, over all its conversations:
1. **Git roots** the ai-agent Bash hook recorded around commands
(``gitRootsAuto``) — exact. A linked worktree folds into its main checkout:
``<repo>/.claude/worktrees/<n>``, a ``git worktree add`` the transcripts ran
(``worktreeAddsAuto``), the hook's ``main`` field, and a sibling
``<parent>/<repo>-<suffix>`` of a known root (unless sessions there sat on
``main``/``master`` — a worktree can't, so that one is a repo of its own).
2. **Where files were written** (``writtenDirsAuto``): inside a known root →
that root; else the folder above the shallowest source-like segment
(``src``, ``docs``, ``apps``, ``packages``…) — ``…/far-waste/src/landing``
→ ``…/far-waste``; else the session's cwd when it's a repo of its own.
3. A candidate that holds other projects is a **container**, not a project
(``~/PROJETS``, ``~/WORK/ORUS``); the home folder, ``~/Downloads``,
``~/Desktop``, ``~/Library``, dot-folders and temp/scratch dirs never are.
A conversation that wrote nothing in a project is filed under the project its
cwd is in. A project is named after its folder; its slug is
``<folder>@<worker id>`` — distinct from every lab slug, and what the
frontend recognises (``lib/workerProjects.ts``). An owner worker's root named
like a lab project (``~/projects/bffr`` on the Mac) is that lab project; a
guest's computer never maps onto the owner's projects. ``merges.py`` folds a
lab project into a worker one (orus-monorepo → orus on the Orus MacBook).
Measured on 2026-11-06: fedora (Akira) 13/13 conversations → music-generator,
far-waste, trashtopia, pet-pet, thust-express-v2, thuth-or-truth,
portfolio-three; Orus MacBook → orus (+ gh-qol, gh-pr-kanban, gh-pr-board).
"""
from __future__ import annotations
import posixpath as pp
import re
import threading
import accounts as accounts_mod
from projects import catalog as catalog_mod
from projects import merges as merges_mod
from projects import worker_meta as worker_meta_mod
SEP = "@"
def _owner(w: dict | None) -> str | None:
"""The guest a worker belongs to (None: the owner's) — workers/guests.py's
rule, inlined to keep this module free of the web stack."""
return (w or {}).get("owner") or None
_HOME_RE = re.compile(r"^(/Users/[^/]+|/home/[^/]+|/root)(?=/|$)")
_NOISE_RE = re.compile(
r"^(?:/tmp|/private/tmp|/private/var|/var/folders|/var/tmp|/dev|/proc|/sys)(?:/|$)"
r"|/(?:scratchpad|node_modules)(?:/|$)")
# Folders right under home that hold downloads and app state, not projects.
_HOME_SKIP = {"Downloads", "Desktop", "Library", "Applications", "Pictures",
"Movies", "Music", "Public", "snap"}
_WT_RE = re.compile(r"^(.*?)/(?:\.claude/worktrees|\.worktrees)/[^/]+(?=/|$)")
# A project's own sub-folders: the project root is the folder above the
# shallowest of these in a written path.
_SOURCE = {
"src", "lib", "libs", "app", "apps", "packages", "docs", "doc", "public",
"assets", "test", "tests", "__tests__", "spec", "e2e", "scripts",
"components", "pages", "styles", "static", "dist", "build", "bin", "cmd",
"internal", "pkg", "server", "client", "config", "examples", "modules",
"include", "resources", "migrations", "infra", "data", ".github",
".vscode", ".claude", ".buildkite", ".config",
}
_MAIN_BRANCHES = {"main", "master"}
_SLUG_RE = re.compile(r"[^a-z0-9._-]+")
# ── slugs ────────────────────────────────────────────────────────────────────
def slug_of(name: str, worker_id: str) -> str:
base = _SLUG_RE.sub("-", name.lower()).strip("-.") or "project"
return f"{base}{SEP}{worker_id}"
def parse_slug(slug: str | None) -> tuple[str, str] | None:
"""``(name part, worker id)`` of a worker project slug, else None."""
if not slug or SEP not in slug:
return None
name, wid = slug.rsplit(SEP, 1)
return (name, wid) if name and wid else None
def is_worker_slug(slug: str | None) -> bool:
return parse_slug(slug) is not None
# ── path rules (pure) ────────────────────────────────────────────────────────
def home_of(p: str) -> str | None:
m = _HOME_RE.match(p or "")
return m.group(1) if m else None
def _under(p: str, root: str) -> bool:
return p == root or p.startswith(root.rstrip("/") + "/")
def ignored(p: str | None) -> bool:
"""Never a project, nor inside one: temp/scratch, home itself, its
dot-folders and download/app-state folders, the filesystem root."""
if not p or not p.startswith("/") or p == "/":
return True
if _NOISE_RE.search(p):
return True
h = home_of(p)
if h:
rest = p[len(h):].strip("/")
if not rest:
return True
first = rest.split("/", 1)[0]
if first.startswith(".") or first in _HOME_SKIP:
return True
elif p.count("/") < 2: # /Users, /home, /srv …
return True
return False
def fold(p: str) -> str:
"""``<repo>/.claude/worktrees/<n>/x`` → ``<repo>/x``."""
m = _WT_RE.match(p)
return (m.group(1) + p[m.end():]) if m else p
def source_root(d: str) -> str | None:
"""The folder above the shallowest source-like segment of directory
``d`` (at least one folder below home), else None."""
h = home_of(d) or ""
rest = d[len(h):].strip("/").split("/") if d.startswith(h) else []
for i, seg in enumerate(rest):
if seg in _SOURCE:
return (h + "/" + "/".join(rest[:i])) if i > 0 else None
return None
# ── one worker's index ───────────────────────────────────────────────────────
class WorkerIndex:
"""The project roots of one worker, from all its conversations.
``convs``: one dict per conversation (subagent transcripts merged in):
``{"dirs": [...], "roots": {root: main|None}, "adds": [{path, repo}],
"cwd": str|None, "branch": str|None}``."""
def __init__(self, convs: list[dict]):
self.aliases: dict[str, str] = {}
hook_roots: set[str] = set()
for c in convs:
for r, main in (c.get("roots") or {}).items():
if main and not ignored(main):
self.aliases[fold(r)] = fold(main)
hook_roots.add(r)
for a in c.get("adds") or []:
if not ignored(a.get("repo")):
self.aliases.setdefault(fold(a["path"]), fold(a["repo"]))
known = {self._alias(fold(r)) for r in hook_roots if not ignored(r)}
# The repo a worktree was added from may be a folder inside it.
self.aliases = {k: next((r for r in _longest(known) if _under(v, r)), v)
for k, v in self.aliases.items()}
self.known = {self._alias(r) for r in known}
# Sibling worktrees `<parent>/<repo>-<x>` of a known root — not when
# sessions there sat on main/master (a repo of its own).
on_main: set[str] = {fold(c["cwd"]) for c in convs
if c.get("cwd") and (c.get("branch") or "") in _MAIN_BRANCHES}
sib = set(hook_roots) | {fold(c["cwd"]) for c in convs if c.get("cwd")}
for s in sib:
s = fold(s)
base = self._sibling_of(s)
if base and s not in on_main and s not in self.aliases:
self.aliases[s] = base
self.known = {self._alias(r) for r in self.known if not ignored(self._alias(r))}
cands: set[str] = set()
for c in convs:
cwd = self.rewrite(c["cwd"]) if c.get("cwd") else None
for d in c.get("dirs") or []:
d = self.rewrite(d)
if ignored(d) or self._known_root(d):
continue
r = source_root(d)
if r and not ignored(r):
cands.add(r)
elif cwd and _under(d, cwd) and not ignored(cwd):
cands.add(source_root(cwd + "/_") or cwd)
branch = c.get("branch") or ""
if cwd and branch and branch != "HEAD" and not ignored(cwd):
cands.add(source_root(cwd + "/_") or cwd)
# A folder only ever written in can still be a sibling worktree.
for x in list(cands):
base = None if x in on_main or self._known_root(x) else self._sibling_of(x)
if base:
self.aliases[x] = base
self.__dict__.pop("_rw_memo", None)
cands = {self._known_root(self._alias(x)) or self._alias(x) for x in cands}
others = cands | self.known
free = {x for x in cands - self.known
if not ignored(x)
and not any(o != x and _under(o, x) for o in others)}
self.roots = _longest(self.known | free)
self._root_set = set(self.roots)
self._roots_memo: dict[str, str | None] = {}
def _alias(self, p: str) -> str:
"""Follow worktree → repo aliases to the end (a worktree added from
a worktree lands on the main checkout)."""
for _ in range(8):
for a in _ancestors(p):
dst = self.aliases.get(a)
if dst is not None and dst != a:
p = dst + p[len(a):]
break
else:
return p
return p
def _sibling_of(self, p: str) -> str | None:
par, base = pp.split(p)
for k in _longest(getattr(self, "known", set())):
kp, kb = pp.split(k)
if kp == par and base != kb and base.startswith(kb + "-"):
return k
return None
def _known_root(self, p: str) -> str | None:
return next((a for a in _ancestors(p) if a in self.known), None)
def rewrite(self, p: str) -> str:
"""A path with its worktree folded into the main checkout."""
memo = self.__dict__.setdefault("_rw_memo", {})
hit = memo.get(p)
if hit is None:
hit = memo[p] = self._alias(fold(p))
return hit
def root_of(self, p: str | None) -> str | None:
if not p:
return None
hit = self._roots_memo.get(p, False)
if hit is not False:
return hit
q = self.rewrite(p)
r = None if ignored(q) else next((a for a in _ancestors(q) if a in self._root_set), None)
self._roots_memo[p] = r
return r
def resolve(self, conv: dict) -> list[str]:
"""The roots a conversation worked in; none written ⇒ its cwd's."""
out: list[str] = []
for d in conv.get("dirs") or []:
r = self.root_of(d)
if r and r not in out:
out.append(r)
if not out:
r = self.root_of(conv.get("cwd"))
if r:
out.append(r)
return out
def _longest(paths) -> list[str]:
return sorted(paths, key=len, reverse=True)
def _ancestors(p: str):
"""``p`` and each folder above it, deepest first (longest match first)."""
while p:
yield p
if p == "/":
return
p = p.rsplit("/", 1)[0] or "/"
# ── the registry (every worker, cached) ──────────────────────────────────────
class Registry:
def __init__(self):
self.by_sid: dict[str, list[str]] = {}
self.projects: dict[str, dict] = {}
self.indexes: dict[str, WorkerIndex] = {}
# sessionId → its transcript files (subagents' included) — what
# worker_meta.py reads a project's card from.
self.paths: dict[str, list[str]] = {}
_cache: tuple[tuple, Registry] | None = None
_lock = threading.Lock()
def _worker_of(meta: dict) -> str | None:
return meta.get("worker") or meta.get("workerSource") or None
def _conv_input(summary: dict) -> dict:
return {
"dirs": list(summary.get("writtenDirsAuto") or []),
"roots": {r["root"]: r.get("main") for r in summary.get("gitRootsAuto") or []
if isinstance(r, dict) and r.get("root")},
"adds": [a for a in summary.get("worktreeAddsAuto") or [] if isinstance(a, dict)],
"cwd": summary.get("cwd"),
"branch": summary.get("gitBranch"),
}
def _lab_slugs() -> set[str]:
return set(catalog_mod._worktree_slugs()) - {catalog_mod.ROOT_SLUG}
# One worker's index, kept while its inputs are the same: a live conversation
# on the lab (or on another worker) doesn't rebuild the Orus Mac's.
_index_cache: dict[str, tuple[int, WorkerIndex]] = {}
def _index_for(wid: str, convs: dict[str, dict]) -> WorkerIndex:
fp = hash(tuple(sorted(
(sid, tuple(c["dirs"]), tuple(sorted(c["roots"].items(), key=lambda kv: kv[0])),
tuple((a.get("path"), a.get("repo")) for a in c["adds"]), c["cwd"], c["branch"])
for sid, c in convs.items())))
hit = _index_cache.get(wid)
if hit and hit[0] == fp:
return hit[1]
idx = WorkerIndex(list(convs.values()))
_index_cache[wid] = (fp, idx)
return idx
def build(rows: list[tuple[dict, str, dict | None]], lab: set[str]) -> Registry:
"""``rows``: ``(summary, worker id, worker record)`` for every worker
transcript. Pure but for ``lab`` (the lab's project dirs)."""
by_worker: dict[str, dict[str, dict]] = {}
stamps: dict[str, dict[str, str | None]] = {}
wrec: dict[str, dict | None] = {}
for s, wid, w in rows:
sid = s.get("sessionId") or ""
if not sid:
continue
wrec[wid] = w
convs = by_worker.setdefault(wid, {})
c = _conv_input(s)
cur = convs.get(sid)
if cur is None:
convs[sid] = c
else: # a subagent transcript: same session, its writes count
cur["dirs"] += c["dirs"]
for r, m in c["roots"].items():
cur["roots"][r] = m or cur["roots"].get(r)
cur["adds"] += c["adds"]
if not s.get("isSidechain"):
cur["cwd"], cur["branch"] = c["cwd"] or cur["cwd"], c["branch"] or cur["branch"]
st = stamps.setdefault(sid, {"at": None})
at = s.get("endedAt") or s.get("startedAt")
if at and (st["at"] is None or at > st["at"]):
st["at"] = at
reg = Registry()
for wid, convs in by_worker.items():
idx = reg.indexes[wid] = _index_for(wid, convs)
guest = _owner(wrec.get(wid)) is not None
names: dict[str, str] = {}
for root in sorted(idx.roots):
base = pp.basename(root)
if not guest and base in lab:
names[root] = base
continue
slug = slug_of(base, wid)
n = 2
while slug in names.values():
slug = slug_of(f"{base}-{n}", wid)
n += 1
names[root] = slug
for sid, c in convs.items():
slugs = []
for root in idx.resolve(c):
slug = names.get(root)
if not slug or slug in slugs:
continue
slugs.append(slug)
if is_worker_slug(slug):
p = reg.projects.setdefault(slug, {
"slug": slug, "name": pp.basename(root), "path": root,
"worker": wid, "sessions": set(), "updatedAt": None})
p["sessions"].add(sid)
at = stamps.get(sid, {}).get("at")
if at and (p["updatedAt"] is None or at > p["updatedAt"]):
p["updatedAt"] = at
reg.by_sid[sid] = slugs
return reg
def registry(deps) -> Registry:
"""Every worker's projects, rebuilt when a transcript, a conversation's
metadata or the worker list changes."""
global _cache
key = (deps.store.summaries_version, deps.meta_store.version,
getattr(deps.worker_store, "version", 0))
with _lock:
if _cache and _cache[0] == key:
return _cache[1]
rows = []
paths: dict[str, list[str]] = {}
list_fn = getattr(deps.worker_store, "list", None)
workers_by_id = {w["id"]: w for w in list_fn()} if list_fn is not None else None
for path, s in deps.store.all_summaries():
sid = s.get("sessionId") or ""
wid = _worker_of(deps.meta_store.peek(sid))
if wid:
w = (workers_by_id.get(wid) if workers_by_id is not None
else deps.worker_store.get(wid))
rows.append((s, wid, w))
if sid and path:
paths.setdefault(sid, []).append(str(path))
reg = build(rows, _lab_slugs())
reg.paths = paths
with _lock:
_cache = (key, reg)
return reg
# ── attribution (cards + costs share it) ─────────────────────────────────────
def conversation_projects(deps, summary: dict, meta: dict | None = None,
profile: str | None = None, *,
merges: dict[str, str] | None = None,
lab_slugs: set[str] | None = None,
reg: Registry | None = None,
workers_by_id: dict[str, dict] | None = None) -> list[str]:
"""A conversation's projects — the one rule the cards, the cost rollups
and the project pages agree on.
Lab: the projects it edited (``projectsAuto``) plus any stamped ones,
else its profile's home project, else the root. Worker: the projects
deduced above (plus a lab project an owner worker edited under
``~/projects``), the stamped ones, else the profile's home project, else
none — a worker conversation is never the homelab's. Merges last."""
sid = summary.get("sessionId") or ""
m = meta if meta is not None else deps.meta_store.peek(sid)
wid = _worker_of(m)
auto = list(summary.get("projectsAuto") or [])
if wid:
w = (workers_by_id.get(wid) if workers_by_id is not None
else deps.worker_store.get(wid))
lab = _lab_slugs() if lab_slugs is None else lab_slugs
auto = [] if _owner(w) is not None else [p for p in auto if p in lab]
r = registry(deps) if reg is None else reg
for p in r.by_sid.get(sid, []):
if p not in auto:
auto.append(p)
for p in m.get("projects") or []:
if p and p not in auto:
auto.append(p)
if not auto:
if profile is None:
profile = deps.profile_store.of_meta(m, accounts_mod.resolve(summary, m))
home = deps.profile_store.home_project(profile)
if home:
auto = [home]
elif not wid:
auto = [catalog_mod.ROOT_SLUG]
return merges_mod.apply(auto, merges)
# ── the Projects page ────────────────────────────────────────────────────────
def account_for(deps, slug: str) -> str:
"""Whose spend a worker project is: the account of a lab project merged
into it, else its worker's ★ Claude login, else the default."""
for src in merges_mod.merged_from(slug):
a = deps.profile_store.account_for_project(src)
if a:
return a
a = deps.profile_store.account_for_project(slug)
if a:
return a
parsed = parse_slug(slug)
accts = deps.profile_store.effective_accounts(parsed[1]) if parsed else {}
return accts.get("anthropic") or accts.get("claude") or next(iter(accts.values()), None) or accounts_mod.DEFAULT
def visible_to(deps, caller, slug: str) -> bool:
if caller.is_owner:
return True
parsed = parse_slug(slug)
w = deps.worker_store.get(parsed[1]) if parsed else None
return bool(w) and _owner(w) == caller.id
def worker_info(deps, wid: str) -> dict:
w = deps.worker_store.get(wid) or {}
return {"id": wid, "name": w.get("name") or wid,
"owner": _owner(w), "platform": w.get("platform")}
def summary_of(deps, p: dict, meta: dict | None = None) -> dict:
"""A worker project as a ``ProjectSummary`` card — its description,
stack, version and site read off its transcripts (worker_meta.py)."""
meta = meta if meta is not None else worker_meta_mod.meta_for(deps, p)
return {
"dir": p["slug"], "name": p["name"],
**worker_meta_mod.summary_fields(meta),
"goal": None, "updatedAt": p.get("updatedAt"),
"path": p["path"], "worker": worker_info(deps, p["worker"]),
"mergedFrom": merges_mod.merged_from(p["slug"]) or None,
}
def list_for(deps, caller) -> list[dict]:
reg = registry(deps)
return [summary_of(deps, p) for slug, p in sorted(reg.projects.items())
if visible_to(deps, caller, slug)]
def detail(deps, slug: str) -> dict | None:
p = registry(deps).projects.get(slug)
if p is None:
return None
meta = worker_meta_mod.meta_for(deps, p)
return {**summary_of(deps, p, meta),
**{k: meta[k] for k in ("readme", "claudeMd", "indexMeta", "ogImage",
"scripts", "seenAt")},
"keyFiles": [], "commits": _commits(deps, p)}
def _commits(deps, p: dict, limit: int = 15) -> list[dict]:
"""The commits the project's conversations made in it (the Bash hook's
records and git's own commit lines, ``commitsAuto``), newest first."""
idx = registry(deps).indexes.get(p["worker"])
seen: dict[str, dict] = {}
for _path, s in deps.store.all_summaries():
if (s.get("sessionId") or "") not in p["sessions"]:
continue
for c in s.get("commitsAuto") or []:
sha = c.get("sha")
if not sha or sha in seen or c.get("merge"):
continue
root = c.get("root") or s.get("cwd")
if idx is None or idx.root_of(root) != p["path"]:
continue
seen[sha] = {"hash": c.get("short") or sha[:7], "date": c.get("date") or "",
"subject": c.get("subject") or ""}
return sorted(seen.values(), key=lambda c: c["date"], reverse=True)[:limit]