Files
ai-agent/backend/test_worker_projects.py
gabrielvidalandClaude Opus 5.5 51517b2474 feat(projects): deduce a worker conversation's project from where it wrote
On a worker (the Orus MacBook, a guest's computer) a conversation was only
filed under a project when it edited ~/projects/<slug> — everything else
landed on the homelab root or the Work fallback. The hub can't see a
worker's disk, so read the project off the transcripts, per worker:

- parser: writtenDirsAuto, gitRootsAuto (+ the hook's new `main`),
  worktreeAddsAuto (`git worktree add`) — PARSER_VERSION 42
- projects/worker_projects.py: git roots exact, worktrees folded into their
  repo (.claude/worktrees, worktree add, hook main, <repo>-<x> siblings),
  else the folder above the first src/docs/apps… segment, else the cwd;
  containers (~/PROJETS, ~/WORK/ORUS) and ~/Downloads, ~/Desktop, temp dirs
  never count; a conversation that wrote nothing → its cwd's project
- slug <folder>@<worker id>; owner workers map onto same-named lab projects,
  guests' computers never do; one attribution rule for cards and costs
- projects/merges.py: fold a lab project into a worker one
  (orus-monorepo → orus on the Orus MacBook), GET/PUT /api/project-merges
- /api/projects + /api/project serve them (worker, path, mergedFrom);
  a guest sees their own computers'
- sidecar bash_diff: a linked worktree's record names its main checkout

On the real transcripts: fedora 13/13 → 7 projects, Orus Mac → orus (316),
gh-pr-board, gh-pr-kanban, gh-qol.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 17:52:39 +01:00

205 lines
10 KiB
Python

"""Projects on a worker, deduced from where its conversations wrote
(projects/worker_projects.py) — the layouts seen on the Orus MacBook and on
Akira's computer, 2026-11-06. ``python3 -m unittest test_worker_projects``"""
import json
import os
import pathlib
import tempfile
import unittest
from conversations.parse import parse_conversation
from conversations.written import worktree_adds
from projects import merges
from projects.worker_projects import (
WorkerIndex, build, ignored, parse_slug, slug_of, source_root)
ORUS = "/Users/g/WORK/ORUS/orus"
AK = "/home/ak/PROJETS"
def conv(dirs=(), roots=None, adds=(), cwd=None, branch="HEAD"):
return {"dirs": list(dirs), "roots": dict(roots or {}), "adds": list(adds),
"cwd": cwd, "branch": branch}
class PathRules(unittest.TestCase):
def test_ignored(self):
for p in ["/tmp/x", "/private/tmp/claude-501/a/scratchpad/b",
"/private/var/folders/c9/T/cp-test", "/Users/g", "/Users/g/.claude/skills",
"/Users/g/Downloads/1.1.19_0", "/Users/g/Desktop/x",
"/Users/g/Library/Application Support/Code", "/home/ak/x/node_modules/y",
"/", "/Users"]:
self.assertTrue(ignored(p), p)
for p in [ORUS, f"{AK}/music-generator/src", "/srv/app/src"]:
self.assertFalse(ignored(p), p)
def test_source_root(self):
self.assertEqual(source_root(f"{AK}/wall-e game/far-waste/src/landing"),
f"{AK}/wall-e game/far-waste")
self.assertEqual(source_root(f"{AK}/pet-pet/apps/demo/src/pages"), f"{AK}/pet-pet")
self.assertEqual(source_root(f"{ORUS}/packages/apps/backend/src"), ORUS)
self.assertIsNone(source_root("/Users/g/src/x")) # no folder above
self.assertIsNone(source_root(f"{AK}/thust/status")) # no source segment
def test_slugs(self):
self.assertEqual(slug_of("portfolio react three", "w1"), "portfolio-react-three@w1")
self.assertEqual(parse_slug("far-waste@g77"), ("far-waste", "g77"))
self.assertIsNone(parse_slug("gabvdl"))
class WorktreeAdds(unittest.TestCase):
def test_commands(self):
self.assertEqual(worktree_adds("git worktree add -q ../orus-ins-2308 b && cd x", ORUS),
[{"path": "/Users/g/WORK/ORUS/orus-ins-2308", "repo": ORUS}])
self.assertEqual(worktree_adds("git worktree add -q -b ins-1 ../orus-ins-1 origin/main",
ORUS)[0]["path"], "/Users/g/WORK/ORUS/orus-ins-1")
self.assertEqual(worktree_adds(f"git -C {ORUS} worktree add /x/orus-z main", "/tmp"),
[{"path": "/x/orus-z", "repo": ORUS}])
self.assertEqual(worktree_adds("git worktree add -q $W main", ORUS), [])
self.assertEqual(worktree_adds("git worktree list", ORUS), [])
class GuestComputer(unittest.TestCase):
"""Akira: cwd is the folder that holds every project, nested at any depth."""
def setUp(self):
self.convs = [
conv([f"{AK}/music-generator/src/lib", f"{AK}/music-generator/src/hooks"],
roots={f"{AK}/music-generator": None}, cwd=AK),
conv([f"{AK}/wall-e game/far-waste/src/landing", f"{AK}/wall-e game/far-waste/docs",
"/tmp/claude-1000/-home-ak-PROJETS/x/scratchpad/p26/src"], cwd=AK),
conv([f"{AK}/portfolio projects/portfolio react three/portfolio-three/context",
f"{AK}/portfolio projects/portfolio react three/portfolio-three/src/utils",
"/home/ak/.claude"], cwd=AK),
conv([f"{AK}/thust-express-v2/status", f"{AK}/thust-express-v2/src/components"],
cwd=AK),
conv([f"{AK}/notes"], cwd=AK), # a file in the container: no project
conv([], cwd=AK),
conv([], cwd=f"{AK}/music-generator"),
]
self.idx = WorkerIndex(self.convs)
def test_roots(self):
self.assertEqual(sorted(self.idx.roots), sorted([
f"{AK}/music-generator", f"{AK}/wall-e game/far-waste",
f"{AK}/portfolio projects/portfolio react three/portfolio-three",
f"{AK}/thust-express-v2"]))
def test_resolve(self):
r = [self.idx.resolve(c) for c in self.convs]
self.assertEqual(r[1], [f"{AK}/wall-e game/far-waste"])
self.assertEqual(r[3], [f"{AK}/thust-express-v2"])
self.assertEqual(r[4], [])
self.assertEqual(r[5], []) # wrote nothing, cwd = container
self.assertEqual(r[6], [f"{AK}/music-generator"]) # wrote nothing: its cwd's
class OrusMac(unittest.TestCase):
"""The repo, its worktrees inside and beside it, and two other repos."""
def test_worktrees_fold_into_the_repo(self):
convs = [
conv([f"{ORUS}/packages/apps/backend/src"], roots={ORUS: None}, cwd=ORUS,
branch="ins-1"),
conv([f"{ORUS}/.claude/worktrees/ins-2312/packages/libs/x"],
roots={f"{ORUS}/.claude/worktrees/ins-2312": None},
cwd=f"{ORUS}/.claude/worktrees/ins-2312", branch="ins-2312"),
conv([f"{ORUS}-ins-2308/packages/apps"], roots={f"{ORUS}-ins-2308": None},
cwd=ORUS, branch="ins-2"),
conv([f"{ORUS}-pr-13259/infra/k8s"],
adds=[{"path": f"{ORUS}-pr-13259", "repo": f"{ORUS}-pr-13258"}],
cwd=f"{ORUS}-pr-13258", branch="ins-3"),
conv([f"{ORUS}-ins-2222/packages/x"], cwd=ORUS, branch="ins-4"), # only written
conv(["/Users/g/WORK/ORUS/gh-qol/src/content"], cwd="/Users/g/WORK/ORUS/gh-qol",
branch="main"),
conv([], cwd="/Users/g/WORK/ORUS/gh-pr-board", branch="main"),
conv(["/Users/g/WORK/ORUS/scripts"], cwd=ORUS, branch="main"), # the container
]
idx = WorkerIndex(convs)
self.assertEqual(sorted(idx.roots), sorted([
ORUS, "/Users/g/WORK/ORUS/gh-qol", "/Users/g/WORK/ORUS/gh-pr-board"]))
for c in convs[:5]:
self.assertEqual(idx.resolve(c), [ORUS], c)
self.assertEqual(idx.resolve(convs[6]), ["/Users/g/WORK/ORUS/gh-pr-board"])
self.assertEqual(idx.resolve(convs[7]), [ORUS]) # wrote only in the container
def test_sibling_on_main_is_its_own_repo(self):
convs = [conv([f"{ORUS}/src"], roots={ORUS: None}, cwd=ORUS, branch="feat"),
conv([f"{ORUS}-api/src"], roots={f"{ORUS}-api": None}, cwd=f"{ORUS}-api",
branch="main")]
self.assertEqual(sorted(WorkerIndex(convs).roots), sorted([ORUS, f"{ORUS}-api"]))
def test_hook_main_field(self):
convs = [conv(["/Users/g/wt/feature-x/src"],
roots={"/Users/g/wt/feature-x": "/Users/g/code/repo"}, cwd="/Users/g")]
self.assertEqual(WorkerIndex(convs).resolve(convs[0]), ["/Users/g/code/repo"])
class Registry(unittest.TestCase):
def test_build(self):
def s(sid, dirs, cwd, side=False):
return {"sessionId": sid, "writtenDirsAuto": dirs, "cwd": cwd, "gitBranch": "HEAD",
"isSidechain": side, "endedAt": "2026-11-05T10:00:00Z"}
guest = {"id": "g77", "owner": "akira"}
mine = {"id": "mac"}
reg = build([
(s("a", [f"{AK}/pet-pet/src"], AK), "g77", guest),
(s("a", [f"{AK}/far-waste/src"], AK, side=True), "g77", guest), # its subagent
(s("b", ["/Users/g/projects/bffr/scripts"], "/Users"), "mac", mine),
(s("c", ["/Users/g/code/pet-pet/src"], "/Users/g"), "mac", mine),
], lab={"bffr", "pet-pet"})
self.assertEqual(reg.by_sid["a"], ["pet-pet@g77", "far-waste@g77"]) # guest: never lab
self.assertEqual(reg.by_sid["b"], ["bffr"]) # owner: the lab's
self.assertEqual(reg.by_sid["c"], ["pet-pet"])
self.assertEqual(reg.projects["pet-pet@g77"]["path"], f"{AK}/pet-pet")
self.assertNotIn("bffr", reg.projects)
class Merges(unittest.TestCase):
def test_apply(self):
with tempfile.TemporaryDirectory() as d:
os.environ["PROJECT_MERGES_PATH"] = f"{d}/m.json"
try:
self.assertEqual(merges.apply(["orus-monorepo"]), ["orus-monorepo"])
merges.save({"orus-monorepo": "orus@mac"})
self.assertEqual(merges.apply(["orus-monorepo", "orus@mac", "x"]),
["orus@mac", "x"])
self.assertEqual(merges.merged_from("orus@mac"), ["orus-monorepo"])
finally:
del os.environ["PROJECT_MERGES_PATH"]
class ParserFields(unittest.TestCase):
def test_written_dirs_roots_and_adds(self):
sid = "11111111-2222-3333-4444-555555555555"
def rec(content, **kw):
return {"sessionId": sid, "cwd": ORUS, "gitBranch": "ins-1",
"timestamp": "2026-11-06T10:00:00.000Z", "type": "assistant",
"message": {"role": "assistant", "model": "claude-opus-5-5",
"content": content}, **kw}
hook = {"bashDiff": {"v": 1, "repos": [
{"root": f"{ORUS}-ins-9", "main": ORUS,
"files": [{"path": "packages/a.ts", "status": "modified"}]}]}}
recs = [
rec([{"type": "tool_use", "id": "t1", "name": "Edit",
"input": {"file_path": f"{ORUS}/src/x.ts", "old_string": "a",
"new_string": "b"}}]),
rec([{"type": "tool_use", "id": "t2", "name": "Bash",
"input": {"command": "git worktree add -q ../orus-ins-9 -b ins-9 origin/main"}}]),
{"sessionId": sid, "type": "attachment", "timestamp": "2026-11-06T10:00:01.000Z",
"attachment": {"type": "hook_success", "hookName": "PostToolUse:Bash",
"toolUseID": "t2", "stdout": json.dumps(hook)}},
]
p = pathlib.Path(tempfile.mkdtemp()) / f"{sid}.jsonl"
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
s = parse_conversation(p)
self.assertEqual(s["writtenDirsAuto"], [f"{ORUS}-ins-9/packages", f"{ORUS}/src"])
self.assertEqual(s["gitRootsAuto"], [{"root": f"{ORUS}-ins-9", "main": ORUS}])
self.assertEqual(s["worktreeAddsAuto"], [{"path": f"{ORUS}-ins-9", "repo": ORUS}])
if __name__ == "__main__":
unittest.main()