Files
ai-agent/cli/test_conv_ref.py
gabrielvidalandClaude Opus 5.5 e425f10358 feat(workers): the ai-agent CLI back on workers, through the outbox — any harness
On 2026-11-28 an agy run on the EVOX2 (2ca176fc) had no way to start a
conversation: since 2026-11-18 a worker's CLI kept only `past`, and the
hub's MCP — its stand-in — existed in Claude Code only. It shelled out to
three `claude -p --model haiku` relays to call start_conversation, which
named the worker EVOX2 (refused), had no parent to report to and polled
wait_for_conversation for 10+ minutes. Another agy run (25c32ca5) gave up
delegating. Gabriel's call: the CLI back on workers, the MCP stays.

The 2026-11-16 path, on today's code:
- cli/ai_agent.py: on a worker (AI_AGENT_OUTBOX_URL) the WORKER_COMMANDS
  go into the outbox as a `cli` item {argv, sessionId}; what the hub's run
  printed comes back (≈ 2–4 s, a `wait` when the run ends). The hub's run
  sends X-AIA-As-Worker + X-AIA-As-Worker-Mode.
- backend/workers/cli.py: CliJobs runs the same CLI in a clean env (host
  token, AIA_AS_WORKER, its switch as the mode, CLAUDE_SESSION_ID = the
  sending session → the parent of what it starts: children nest and report
  back). The narrowing is workers/bound.py worker_caller — the same caller
  as a worker-bound MCP connection, worker.read / worker.run scopes.
- The per-worker switch: workers.json `cli` off | read | run (unset = run,
  a guest's computer always off), PATCH /api/workers/{id} {cli}, Machines →
  the worker → Details → "ai-agent CLI".
- sidecar/outbox.py: the `cli` kind (results dropped 10 min after they end);
  outbox_mirror answers it; worker/install.sh writes the `ai-agent` terminal
  shim again.
- The conv-ref hook names the CLI on a worker; `past`'s lookup follows the
  switch. The bound MCP connection stays, optional.
- Docs: CLAUDE.md, docs/mcp.md, worker/README.md.

Tests: test_worker_cli.py (new), test_worker_bound.py, test_worker_routing.py,
sidecar test_outbox.py, cli test_ai_agent.py / test_conv_ref.py; the whole
backend per module matches main (test_typed_plugins' git-clone case fails on
both). A live local hub answered every worker command through the gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:57:34 +01:00

130 lines
6.4 KiB
Python

"""The conv-ref prompt hook (conv_ref.py): what counts as a conversation
reference (Gabriel's own prompts from the Nov 2026 analysis), the hub's tail
left out, the card it prints, and silence everywhere else.
``python -m unittest test_conv_ref`` from ``cli/``."""
import io
import json
import os
import tempfile
import unittest
from pathlib import Path
from unittest import mock
import conv_ref
A = "01a1e40a-9907-7a32-81d4-6bfc5a8f6240"
SA = "a2533c3a-d718-4823-80d0-70bf2939ba81"
CARD = {"id": A, "sessionId": SA, "title": "Linear metadata widget", "state": "finished",
"machine": "Orus Macbook", "account": "work", "projects": ["orus"],
"endedAt": "2026-11-16T13:54:30Z", "url": f"https://ai-agent.lab.gabvdl.xyz/conversation/{A}",
"firstPrompt": "build the\nwidget", "lastAnswer": "Done: PR #15039"}
OUTBOX_ENV = ("AI_AGENT_OUTBOX_URL", "AI_AGENT_OUTBOX_TOKEN")
def run(prompt, env=None, **kw):
out = io.StringIO()
data = json.dumps({"prompt": prompt, "session_id": "11111111-0000-4000-8000-000000000000", **kw})
with mock.patch.dict(os.environ, clear=False), \
mock.patch("sys.stdin", io.StringIO(data)), mock.patch("sys.stdout", out):
# A run on a worker has its outbox in the environment (EVOX2, the
# Macs): the hook would take the worker's path. The lab's, unless a
# test says otherwise.
for k in OUTBOX_ENV:
os.environ.pop(k, None)
os.environ.update(env or {})
conv_ref.main([])
text = out.getvalue()
return json.loads(text)["hookSpecificOutput"]["additionalContext"] if text else None
class Detect(unittest.TestCase):
def test_gabriels_phrasings_talk_about_past_conversations(self):
for p in ("I reauthorized tailscale for the vpn exit node, check past conv",
"what's left on this PR ? check previous convs https://github.com/o/r/pull/14871",
"search past conversation about the improvements of the CPMS page",
"dom requested to setup email sending in a previous conversation",
"check this PR and past conv, we decided to exclude contracts linked to partners",
"check the other PR and conv that fixed the CP",
"regarde la conv précédente sur raspy1"):
self.assertTrue(conv_ref.find_refs(p)[2], p)
def test_ordinary_prompts_dont(self):
for p in ("fix the conversation page padding when a run is stopped",
"add a conversation card to the home page",
"the convex hull is wrong"):
self.assertEqual(conv_ref.find_refs(p), ([], set(), False), p)
def test_ids_links_and_prefixes(self):
ids, named, _ = conv_ref.find_refs(
f"from this conv {A} and https://ai-agent.lab.gabvdl.xyz/conversation/01a1f4e8-795c-7f66-917a-a0012337347b"
" also conv a2533c3a, contract 01a1ffff-0000-7000-8000-000000000000")
self.assertEqual(ids, ["01a1f4e8-795c-7f66-917a-a0012337347b", A, "a2533c3a",
"01a1ffff-0000-7000-8000-000000000000"])
self.assertEqual(named, {"01a1f4e8-795c-7f66-917a-a0012337347b", A, "a2533c3a"})
def test_the_own_session_and_the_hubs_tail_are_left_out(self):
own = "22222222-0000-4000-8000-000000000000"
self.assertEqual(conv_ref.find_refs(f"conv {own}", own)[0], [])
p = ("fix the deploy\n\nUse the following in this task:\n- the `ai-agent` skill — … search "
"past ones, when a past conversation already holds the context")
self.assertFalse(conv_ref.find_refs(conv_ref.own_text(p))[2])
class Hook(unittest.TestCase):
def test_silent_on_an_ordinary_prompt_and_in_a_guest_run(self):
self.assertIsNone(run("rename the button"))
self.assertIsNone(run("check past conv", env={"AIA_GUEST": "dom"}))
def test_a_phrase_gets_the_hint_with_the_lab_commands(self):
with mock.patch.object(conv_ref, "lookup_hub") as hub:
ctx = run("check past conv about the edge split")
hub.assert_not_called() # nothing to resolve
self.assertIn("ai-agent search", ctx)
self.assertIn("not a file under ~/.claude/projects", ctx)
def test_an_id_gets_its_card(self):
with mock.patch.object(conv_ref, "lookup_hub",
return_value={"cards": [CARD], "unknown": [], "ambiguous": []}) as hub:
ctx = run(f"do i have the skill locally? from this conv {A}")
self.assertEqual(hub.call_args.args[0], [A])
self.assertIn(f"• {A} “Linear metadata widget” — finished · ended", ctx)
self.assertIn("Orus Macbook · work · orus", ctx)
self.assertIn("asked: build the widget", ctx)
self.assertIn("last answer: Done: PR #15039", ctx)
def test_on_a_worker_it_asks_the_outbox_and_names_the_cli(self):
with mock.patch.object(conv_ref, "lookup_outbox",
return_value={"cards": [], "unknown": [A], "ambiguous": []}) as ob:
ctx = run(f"I did the dry run on this conv {A}",
env={"AI_AGENT_OUTBOX_URL": "http://100.1.2.3:8790", "AI_AGENT_OUTBOX_TOKEN": "t"})
self.assertEqual(ob.call_args.args[2:], ("http://100.1.2.3:8790", "t"))
self.assertIn("ai-agent show ID", ctx)
self.assertIn("through this machine's outbox", ctx)
self.assertIn(f"• {A}: no conversation the hub shows here", ctx)
def test_a_bare_uuid_that_is_no_conversation_says_nothing(self):
with mock.patch.object(conv_ref, "lookup_hub",
return_value={"cards": [], "unknown": [A], "ambiguous": []}):
self.assertIsNone(run(f"contract {A} has the wrong start date"))
def test_a_hub_error_never_blocks(self):
with mock.patch.object(conv_ref, "lookup_hub", side_effect=RuntimeError("hub unreachable")):
ctx = run(f"follow this conv {A}")
self.assertIn("didn't resolve", ctx)
def test_the_transcript_on_this_machine(self):
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "projects" / "-Users-x-orus"
p.mkdir(parents=True)
(p / f"{SA}.jsonl").write_text("{}")
with mock.patch.dict(os.environ, {"CLAUDE_CONFIG_DIR": d}):
self.assertEqual(conv_ref.local_transcript(SA), str(p / f"{SA}.jsonl"))
self.assertIsNone(conv_ref.local_transcript("../etc"))
if __name__ == "__main__":
unittest.main()