Files
ai-agent/backend/test_worker_meta.py
gabrielvidalandClaude Opus 5.5 1a0b8187e1 feat(projects): fill worker projects' cards from their transcripts
A project on a worker (a guest's computer, the Macs) had an empty card:
no description, stack, version, site or README — the hub can't see that
disk. projects/worker_meta.py reads them off the project's conversations:
the last whole copy of package.json / README.md / CLAUDE.md / index.html a
session read, wrote, edited or cat-ed; the packages the files it touched
import, the file kinds and marker files; the deployed site among the URLs
it mentioned (every word of the name in the host, a domain of its own over
a SaaS tenant, production over Vercel previews). A background thread
follows every worker transcript by byte offset; requests only read the
scans. The detail page dates the README / CLAUDE.md copy (seenAt).

Transcripts only, every worker, no AI summary — Gabriel's form
project-metadata-on-guests-computers_2l6bxi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:51:31 +01:00

256 lines
13 KiB
Python

"""A worker project's card read off its transcripts (projects/worker_meta.py)
— the shapes Claude Code writes, seen on Akira's computer and the Orus
MacBook, 2026-11-06. ``python3 -m unittest test_worker_meta``"""
import json
import os
import tempfile
import unittest
from collections import Counter
from projects.worker_meta import (
Scan, Scanner, cat_target, imports_in, project_meta, scan_lines, site_url)
AK = "/home/ak/PROJETS"
PET = f"{AK}/pet-pet"
def line(d: dict) -> str:
return json.dumps(d) + "\n"
def read(path, content, ts="2026-11-04T01:00:00Z", start=1, num=None, total=None):
n = content.count("\n") + 1
return line({"type": "user", "timestamp": ts, "toolUseResult": {"type": "text", "file": {
"filePath": path, "content": content, "startLine": start,
"numLines": n if num is None else num, "totalLines": n if total is None else total}}})
def write(path, content, ts="2026-11-04T02:00:00Z"):
return line({"type": "user", "timestamp": ts, "toolUseResult": {
"type": "create", "filePath": path, "content": content, "structuredPatch": []}})
def edit(path, old, new, orig=None, ts="2026-11-04T03:00:00Z", replace_all=False):
r = {"filePath": path, "oldString": old, "newString": new, "replaceAll": replace_all,
"structuredPatch": [], "userModified": False}
if orig is not None:
r["originalFile"] = orig
return line({"type": "user", "timestamp": ts, "toolUseResult": r})
def bash_call(tid, cmd, cwd=PET):
return line({"type": "assistant", "cwd": cwd, "message": {"content": [
{"type": "tool_use", "id": tid, "name": "Bash", "input": {"command": cmd}}]}})
def bash_out(tid, stdout, ts="2026-11-04T04:00:00Z"):
return line({"type": "user", "timestamp": ts,
"message": {"content": [{"type": "tool_result", "tool_use_id": tid}]},
"toolUseResult": {"stdout": stdout, "stderr": "", "interrupted": False}})
PKG = json.dumps({"name": "pet-pet", "version": "0.3.0", "description": "A tiny hamster.",
"scripts": {"dev": "vite", "build": "vite build"},
"dependencies": {"react": "^19"}, "devDependencies": {"vite": "^7"}},
indent=2)
class Scanning(unittest.TestCase):
def test_read_write_edit(self):
s = scan_lines([
read(f"{PET}/package.json", PKG),
read(f"{PET}/README.md", "# x\n\npartial", start=10), # a slice: ignored
write(f"{PET}/README.md", "# pet-pet\n\nA hamster on your page.\n"),
edit(f"{PET}/README.md", "A hamster", "A tiny hamster"), # no originalFile
edit(f"{PET}/CLAUDE.md", "old", "new", orig="# C\n\nold rules\n"),
])
self.assertEqual(json.loads(s.files[f"{PET}/package.json"][1])["version"], "0.3.0")
self.assertEqual(s.files[f"{PET}/README.md"][1], "# pet-pet\n\nA tiny hamster on your page.\n")
self.assertEqual(s.files[f"{PET}/CLAUDE.md"][1], "# C\n\nnew rules\n")
def test_multiedit_and_unappliable_edit(self):
s = scan_lines([
line({"type": "user", "timestamp": "t", "toolUseResult": {
"filePath": f"{PET}/README.md", "originalFile": "a b c",
"edits": [{"old_string": "a", "new_string": "A"},
{"old_string": "c", "new_string": "C"}]}}),
edit(f"{PET}/index.html", "nope", "x", orig="<html></html>"),
])
self.assertEqual(s.files[f"{PET}/README.md"][1], "A b C")
self.assertNotIn(f"{PET}/index.html", s.files)
self.assertEqual(s.dirs[PET][".html"], 1) # still touched
def test_cat_package_json(self):
out = "total 8\ndrwxr-xr-x .\n" + PKG + "\nsrc\n"
s = scan_lines([
bash_call("t1", 'cd "/home/ak/PROJETS/thuth-or-truth" && ls src; cat package.json; wc -l x'),
bash_out("t1", out),
bash_call("t2", "cat a/package.json b/package.json"), # two: ambiguous
bash_out("t2", PKG),
])
self.assertIn(f"{AK}/thuth-or-truth/package.json", s.files)
self.assertEqual(len(s.files), 1)
def test_cat_target(self):
self.assertEqual(cat_target("cat package.json", PET), f"{PET}/package.json")
self.assertEqual(cat_target("cd ~/PROJETS/x; cat package.json", PET),
f"{AK}/x/package.json")
self.assertEqual(cat_target("cat /srv/app/package.json | jq .", PET), "/srv/app/package.json")
self.assertEqual(cat_target("cd web && cat ../package.json", PET), f"{PET}/package.json")
self.assertIsNone(cat_target("cat package.json.bak", PET))
self.assertIsNone(cat_target("npm i", PET))
def test_imports(self):
src = ('import React from "react";\nimport { Canvas } from \'@react-three/fiber/dist\';\n'
'import x from "./x";\nimport "@/styles.css";\nconst fs = require("node:fs");\n'
'const g = await import("gsap");\nimport type { T } from "vue";\n')
self.assertEqual(imports_in(src), {"react", "@react-three/fiber", "gsap", "vue"})
s = scan_lines([write(f"{PET}/src/App.tsx", src)])
self.assertIn("react", s.imports[f"{PET}/src"])
def test_urls(self):
s = scan_lines([line({"text": "see https://www.orus.eu/fr and "
"https://akkibi.github.io/pet-pet/assets/x.js and "
"http://localhost:5173/"})])
self.assertEqual(set(s.urls), {"https://orus.eu", "https://akkibi.github.io/pet-pet"})
class SiteUrl(unittest.TestCase):
def test_production_beats_preview(self):
urls = Counter({"https://music-generator-oofabqftc-akkibi11.vercel.app": 14,
"https://music-generator-eta.vercel.app": 3,
"https://music-generator-git-master-akkibi11.vercel.app": 4,
"https://portfolio-pipeline-five.vercel.app": 9})
self.assertEqual(site_url(urls, ["music-generator"]), "https://music-generator-eta.vercel.app")
self.assertIsNone(site_url(urls, ["portfolio-three"])) # every word, not one
def test_own_domain_beats_a_tenant(self):
urls = Counter({"https://orus.sentry.io": 900, "https://orus-insurance.slack.com": 3000,
"https://orus.eu": 129, "https://app.orus.eu": 2000,
"https://orus.lysta.fr": 11})
self.assertEqual(site_url(urls, ["orus"]), "https://orus.eu")
self.assertIsNone(site_url(Counter({"https://orus.sentry.io": 9}), ["orus"]))
def test_repo_pages_and_single_mentions(self):
urls = Counter({"https://akkibi.github.io/pet-pet": 5, "https://pet-pet.vercel.app": 1})
self.assertEqual(site_url(urls, ["pet-pet"]), "https://akkibi.github.io/pet-pet")
self.assertIsNone(site_url(Counter({"https://pet-pet.vercel.app": 1}), ["pet-pet"]))
class ProjectMeta(unittest.TestCase):
def test_card(self):
wt = f"{PET}/.claude/worktrees/feat"
older = scan_lines([read(f"{PET}/package.json", PKG, ts="2026-11-01T00:00:00Z")])
newer = scan_lines([
write(f"{wt}/README.md", "# pet-pet\n\nA hamster that roams your page.\n"),
write(f"{wt}/package.json", PKG.replace("0.3.0", "0.4.0"), ts="2026-11-05T00:00:00Z"),
write(f"{PET}/src/a.ts", "import * as THREE from 'three'"),
write(f"{PET}/src/b.ts", ""), write(f"{PET}/src/c.ts", ""),
read(f"{PET}/tsconfig.json", "{}"),
read(f"{AK}/other/package.json", PKG), # another project
line({"text": "https://akkibi.github.io/pet-pet/ https://akkibi.github.io/pet-pet"}),
])
fold = lambda p: p.replace("/.claude/worktrees/feat", "") # noqa: E731
m = project_meta(PET, "pet-pet", [newer, older], fold)
self.assertEqual(m["version"], "0.4.0") # the latest copy
self.assertEqual(m["description"], "A tiny hamster.") # package.json first
self.assertEqual(m["stack"], ["React", "Three.js", "Vite", "TypeScript"])
self.assertEqual(m["url"], "https://akkibi.github.io/pet-pet")
self.assertEqual(m["scripts"], ["dev", "build"])
self.assertTrue(m["readme"].startswith("# pet-pet"))
self.assertEqual(set(m["seenAt"]), {"package.json", "README.md"})
self.assertTrue(m["hasPackageJson"])
def test_fallbacks(self):
root = f"{AK}/wall-e game/far-waste"
html = ('<html><head><title>Far-Waste</title><meta name="description" '
'content="A robot automation game."><meta property="og:url" '
'content="https://farwaste.akkibi.art"><meta property="og:image" '
'content="/og-image.jpg"></head></html>')
s = scan_lines([
write(f"{root}/landing/index.html", html),
write(f"{root}/CLAUDE.md", "# CLAUDE.md\n\nThis file provides guidance to Claude Code.\n\n"
"Far-Waste is a Vue + three.js game.\n"),
*(write(f"{root}/src/c{i}.vue", "") for i in range(3)),
write(f"{root}/vite.config.ts", "export default {}"),
])
m = project_meta(root, "far-waste", [s])
self.assertEqual(m["description"], "Far-Waste is a Vue + three.js game.")
self.assertEqual(m["url"], "https://farwaste.akkibi.art") # og:url
self.assertEqual(m["ogImage"], {"kind": "url", "src": "https://farwaste.akkibi.art/og-image.jpg"})
self.assertEqual(m["stack"], ["Vue", "Vite"])
self.assertFalse(m["hasPackageJson"])
self.assertEqual(m["indexMeta"]["title"], "Far-Waste")
def test_empty(self):
m = project_meta(PET, "pet-pet", [Scan()])
self.assertEqual((m["description"], m["url"], m["stack"], m["seenAt"]), ("", None, [], None))
class Following(unittest.TestCase):
def test_incremental_and_shrink(self):
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "s.jsonl")
with open(path, "w") as f:
f.write(read(f"{PET}/package.json", PKG))
f.write(write(f"{PET}/README.md", "# r\n\nx\n").rstrip("\n")) # half a line
sc = Scanner()
self.assertEqual(sc.refresh([path]), 1)
first = sc.get(path)
self.assertNotIn(f"{PET}/README.md", first.files)
with open(path, "a") as f:
f.write("\n")
sc.refresh([path])
self.assertIn(f"{PET}/README.md", sc.get(path).files)
self.assertNotIn(f"{PET}/README.md", first.files) # published scans stay put
self.assertEqual(sc.refresh([path]), 0) # unchanged
with open(path, "w") as f: # rewritten shorter
f.write(write(f"{PET}/CLAUDE.md", "# c\n"))
sc.refresh([path])
self.assertEqual(set(sc.get(path).files), {f"{PET}/CLAUDE.md"})
class HubSide(unittest.TestCase):
"""``list_for`` / ``detail`` fill a worker project's card from its
transcript (fake hub state, a real transcript file)."""
def test_card_and_detail(self):
from types import SimpleNamespace
from projects import worker_meta, worker_projects as wp
with tempfile.TemporaryDirectory() as d:
os.environ["PROJECT_MERGES_PATH"] = os.path.join(d, "merges.json")
path = os.path.join(d, "s1.jsonl")
with open(path, "w") as f:
f.write(read(f"{PET}/package.json", PKG))
f.write(write(f"{PET}/README.md", "# pet-pet\n\nA hamster.\n"))
summary = {"sessionId": "s1", "cwd": PET, "gitBranch": "main",
"writtenDirsAuto": [PET], "startedAt": "2026-11-04T00:00:00Z"}
store = SimpleNamespace(summaries_version=1,
all_summaries=lambda: [(path, summary)])
deps = SimpleNamespace(
store=store,
meta_store=SimpleNamespace(version=1, peek=lambda sid: {"worker": "g1"}),
worker_store=SimpleNamespace(
version=1, get=lambda wid: {"id": "g1", "name": "fedora", "owner": "ak"}))
owner = SimpleNamespace(is_owner=True, id="owner")
wp._cache = None
# Not scanned yet: an empty card, never a transcript read in a request.
self.assertEqual(wp.list_for(deps, owner)[0]["description"], "")
worker_meta.SCANNER.refresh([path]) # the thread's pass, inline
card = wp.list_for(deps, owner)[0]
self.assertEqual((card["dir"], card["description"], card["version"], card["stack"]),
("pet-pet@g1", "A tiny hamster.", "0.3.0", ["React", "Vite"]))
det = wp.detail(deps, "pet-pet@g1")
self.assertEqual(det["readme"], "# pet-pet\n\nA hamster.\n")
self.assertEqual(det["scripts"], ["dev", "build"])
self.assertEqual(set(det["seenAt"]), {"package.json", "README.md"})
self.assertEqual(det["keyFiles"], [])
wp._cache = None
if __name__ == "__main__":
unittest.main()