Files
ai-agent/backend/test_skill_injection.py
gabrielvidalandClaude Opus 5.5 e94deb8174 feat(parse): neutral tool names in the readers, the fold and the buckets (parser v45)
The readers put the neutral name in a tool_call's `tool` and the record's
own in `native` (readers/toolnames.py): Bash → shell, Read → read,
Agent/Task → agent, the five task tools → todo, CronCreate →
claude:CronCreate; a converter-written legacy file namespaces its own
tools under its entrypoint (agy:manage_task, opencode:execute), an
unstamped one's lowercase names are pi's. MCP names are untouched.

The fold, the cost buckets (bash → shell, task → todo; TaskOutput /
TaskStop now count as shell, TaskGet / TaskList as todo), taskevents, the
resource miner, the lifecycle / deploy / worktree detection, tree.py's
agent cards, spawned children, the scaffold and the bgtasks route key on
the neutral names only. The `todo` calls are told apart by their input
(tools.todo_op). A tool card carries `native` when it differs.

PARSER_VERSION 45 (a full re-index). docs/transcript-format.md gets the
"Tool names" table with the agy column filled from sidecar/agy_tools.py;
the v1 fixtures use the neutral names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 18:14:14 +01:00

227 lines
9.4 KiB
Python

"""A skill's injected prompt (conversations/parse/readers/claude.py `_skill_injection`) folds
into its Skill card — never a "You" bubble — whether Claude invoked it or the
user typed `/name`, and whether or not it is a skill on disk; and the newest
prompt per skill reaches the catalog (`skill_prompts`, `/api/skills/{name}/prompt`).
Records are trimmed copies of real Claude Code transcript lines."""
import json
import pathlib
import types
import conversations as c
from db import Store
from indexer import Indexer
CODE_REVIEW = ("`high effort → 8 inline angles → dedup (no verify) → ≤10 findings`\n\n"
"You are reviewing for **recall** at high effort.")
INIT = "Please analyze this codebase and create a CLAUDE.md file."
def _user(content, ts, **rec):
return {"type": "user", "timestamp": ts, "sessionId": "s1",
"message": {"role": "user", "content": content}, **rec}
def _assistant(content, ts, mid):
return {"type": "assistant", "timestamp": ts, "sessionId": "s1",
"message": {"id": mid, "role": "assistant", "model": "claude-opus-5-5",
"content": content}}
def _skill_call(tid, skill, ts, args=None):
inp = {"skill": skill, **({"args": args} if args else {})}
return [
_assistant([{"type": "tool_use", "id": tid, "name": "Skill", "input": inp}],
ts, f"m-{tid}"),
_user([{"type": "tool_result", "tool_use_id": tid,
"content": f"Launching skill: {skill}"}], ts,
toolUseResult={"success": True, "commandName": skill}),
]
def _injected(text, ts, src=None, as_list=True):
content = [{"type": "text", "text": text}] if as_list else text
return _user(content, ts, isMeta=True,
**({"sourceToolUseID": src} if src else {}))
def _typed(name, ts, args=""):
text = f"<command-message>{name}</command-message>\n<command-name>/{name}</command-name>"
if args:
text += f"\n<command-args>{args}</command-args>"
return _user(text, ts)
def _write(tmp_path, recs, name="s1.jsonl"):
p = tmp_path / name
p.write_text("".join(json.dumps(r) + "\n" for r in recs))
return p
def _parse(p, full=True):
st = c.ParserState(p, full=full)
for line in p.read_text().splitlines():
st.feed(json.loads(line))
return st
def _bubbles(st):
return [it["text"] for it in st.thread if it["role"] == "user" and it["kind"] == "text"]
def _cards(st):
return [it for it in st.thread if it["kind"] == "tool_use" and it["name"] == "skill"]
def test_a_builtin_skill_prompt_folds_into_its_card(tmp_path):
p = _write(tmp_path, [
_user("review my diff", "2026-07-13T16:23:00Z"),
*_skill_call("tu1", "code-review", "2026-07-13T16:23:36Z", args="medium"),
_injected(CODE_REVIEW, "2026-07-13T16:23:36.6Z", src="tu1"),
_assistant([{"type": "text", "text": "Reviewing."}], "2026-07-13T16:24:00Z", "m2"),
])
st = _parse(p)
assert _bubbles(st) == ["review my diff"]
assert st.user_turns == 1
[card] = _cards(st)
assert card["skillBody"] == CODE_REVIEW and "skillPath" not in card
assert st.skills["code-review"]["count"] == 1
def test_a_disk_skill_keeps_its_editor_link(tmp_path):
p = _write(tmp_path, [
{"type": "user", "timestamp": "2026-09-14T10:00:00Z", "sessionId": "s1",
"cwd": "/home/gabrielvidal/homelab",
"message": {"role": "user", "content": "ping me"}},
*_skill_call("tu1", "notify-done", "2026-09-14T10:00:05Z"),
_injected("Base directory for this skill: /home/gabrielvidal/homelab/.claude/"
"skills/notify-done\n\n# Notify when done\n", "2026-09-14T10:00:06Z",
src="tu1"),
])
st = _parse(p)
[card] = _cards(st)
assert card["skillBody"] == "# Notify when done\n"
assert card["skillPath"] == ".claude/skills/notify-done/SKILL.md"
assert _bubbles(st) == ["ping me"]
def test_a_repeat_call_note_is_neither_a_bubble_nor_the_prompt(tmp_path):
body = "# Commit homelab\n"
p = _write(tmp_path, [
*_skill_call("tu1", "commit-homelab", "2026-08-14T08:06:18Z"),
_injected("(Re-invocation of /commit-homelab — the skill instructions were "
"previously loaded; the arguments or dynamic output below are new.)",
"2026-08-14T08:06:18.8Z", src="tu1", as_list=False),
_injected("Base directory for this skill: /h/.claude/skills/commit-homelab\n\n"
+ body, "2026-08-14T08:06:18.9Z", src="tu1"),
*_skill_call("tu2", "commit-homelab", "2026-08-14T09:00:00Z"),
_injected("Skill /commit-homelab is already loaded above; instructions unchanged.",
"2026-08-14T09:00:00.5Z", src="tu2", as_list=False),
_injected("<system-reminder>\nDirectory-scoped variants of the skill exist.\n"
"</system-reminder>", "2026-08-14T09:00:00.6Z", src="tu2"),
])
st = _parse(p)
assert _bubbles(st) == []
first, second = _cards(st)
assert first["skillBody"] == body
assert "skillBody" not in second
assert st.skill_prompts["commit-homelab"]["text"] == body
def test_a_typed_builtin_command_becomes_a_skill_card(tmp_path):
p = _write(tmp_path, [
_typed("init", "2026-06-08T21:04:36Z"),
_injected(INIT, "2026-06-08T21:04:36.3Z"),
_assistant([{"type": "text", "text": "I'll analyze the codebase."}],
"2026-06-08T21:04:40Z", "m1"),
])
st = _parse(p)
assert _bubbles(st) == []
assert st.user_turns == 0
[card] = _cards(st)
assert card["role"] == "user"
assert card["input"] == {"skill": "init"}
assert card["skillBody"] == INIT
assert st.skills["init"]["count"] == 1
def test_a_typed_disk_skill_carries_its_args(tmp_path):
p = _write(tmp_path, [
_typed("babysit-pr", "2026-09-28T13:59:00Z", args='{"pr_number":13258}'),
_injected("Base directory for this skill: /Users/g/orus/.claude/skills/babysit-pr"
"\n\n# Babysit Pull Request CI\n", "2026-09-28T13:59:00.8Z"),
])
st = _parse(p)
[card] = _cards(st)
assert card["input"] == {"skill": "babysit-pr", "args": '{"pr_number":13258}'}
assert card["skillBody"] == "# Babysit Pull Request CI\n"
assert st.skill_prompts["babysit-pr"]["baseDir"] == "/Users/g/orus/.claude/skills/babysit-pr"
def test_a_local_command_leaves_the_next_message_alone(tmp_path):
# `/model` injects no prompt: its stdout ends the wait, so the user's next
# message — even an `isMeta` one — is not mistaken for a skill prompt.
p = _write(tmp_path, [
_typed("model", "2026-10-01T10:00:00Z"),
_user("<local-command-stdout>Set model to Fable</local-command-stdout>",
"2026-10-01T10:00:00.1Z"),
_injected("Continue from where you left off.", "2026-10-01T10:00:01Z"),
_user("fix the build", "2026-10-01T10:00:05Z"),
])
st = _parse(p)
assert _cards(st) == []
assert "fix the build" in _bubbles(st)
assert st.skills == {}
def test_the_summary_carries_each_skills_latest_prompt(tmp_path):
p = _write(tmp_path, [
*_skill_call("tu1", "loop", "2026-10-05T09:00:00Z"),
_injected("# /loop v1", "2026-10-05T09:00:01Z", src="tu1"),
*_skill_call("tu2", "loop", "2026-10-05T10:00:00Z"),
_injected("# /loop v2", "2026-10-05T10:00:01Z", src="tu2"),
])
summary = _parse(p, full=False).summary()
assert summary["skillPrompts"]["loop"]["text"] == "# /loop v2"
assert summary["skillPrompts"]["loop"]["at"] == "2026-10-05T10:00:01Z"
assert "skillPrompts" not in _parse(p).summary() # the detail payload
def test_the_store_keeps_only_the_newest_prompt(tmp_path):
s = Store(str(tmp_path / "x.db"))
s.keep_skill_prompts("/t/a.jsonl", {"loop": {"text": "new", "at": "2026-10-05"}})
s.keep_skill_prompts("/t/b.jsonl", {"loop": {"text": "old", "at": "2026-09-01"}})
assert s.get_skill_prompt("loop")["prompt"] == "new"
assert s.skill_prompt_index() == {"loop": {"seenAt": "2026-10-05", "path": "/t/a.jsonl"}}
s.keep_skill_prompts("/t/c.jsonl", {"loop": {"text": "newer", "at": "2026-10-06",
"baseDir": None}})
assert s.get_skill_prompt("loop")["path"] == "/t/c.jsonl"
def test_indexing_a_transcript_fills_the_prompt_table(tmp_path):
arch = tmp_path / "arch" / "-home-g-proj"
arch.mkdir(parents=True)
_write(arch, [*_skill_call("tu1", "code-review", "2026-07-13T16:23:36Z"),
_injected(CODE_REVIEW, "2026-07-13T16:23:36.6Z", src="tu1")])
store = Store(str(tmp_path / "x.db"))
Indexer(store, tmp_path, None, tmp_path / "arch", lambda: [],
lambda p: "").scan_transcripts()
row = store.get_skill_prompt("code-review")
assert row["prompt"] == CODE_REVIEW and row["path"].endswith("s1.jsonl")
# …and kept out of the stored summary.
[(_, summary)] = store.all_summaries()
assert "skillPrompts" not in summary
def test_the_prompt_route_names_its_conversation(tmp_path):
from dashboards import routes
store = Store(str(tmp_path / "x.db"))
store.keep_skill_prompts(str(tmp_path / "s1.jsonl"),
{"loop": {"text": "# /loop", "at": "2026-10-05"}})
deps = types.SimpleNamespace(store=store)
out = routes.skill_prompt(deps, "loop")
assert out["prompt"] == "# /loop" and out["seenAt"] == "2026-10-05"
from conversations import ids
assert ids.rel_for(out["conversationId"]) == "s1.jsonl" # its uid, not the path