398 lines
20 KiB
Python
398 lines
20 KiB
Python
"""Tests for the Plans live plugin: parsing, every action, and the hub calls
|
|
(ask-form create/get, conversations with metrics) against a fake hub."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
import urllib.parse
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
ROOT = pathlib.Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "actions"))
|
|
import _common as C # noqa: E402
|
|
|
|
PLAN = """---
|
|
title: Ship the widget
|
|
created: 2026-11-20
|
|
status: proposed
|
|
sessionId: sess-plan
|
|
conversationIds: sess-impl, sess-missing
|
|
estCost: 4.50
|
|
estTimeMinutes: 30
|
|
estTokens: 120000
|
|
---
|
|
|
|
# Ship the widget
|
|
|
|
## Summary
|
|
Touches projects/widget and services/traefik.
|
|
|
|
## Files changed
|
|
| file | change |
|
|
| ---- | ------ |
|
|
| `projects/widget/a.ts` | add the thing |
|
|
| services/traefik/x.yml | route it |
|
|
|
|
## Steps
|
|
1. **Build it** — write the code
|
|
and the tests
|
|
2. **Ship it** — deploy
|
|
|
|
```
|
|
## Steps
|
|
1. not a real step
|
|
```
|
|
|
|
## Questions
|
|
|
|
```json
|
|
{
|
|
"title": "Open questions",
|
|
"description": "Two calls to make",
|
|
"fields": [
|
|
{"key": "store", "label": "Where do answers live?", "type": "radio",
|
|
"options": ["localStorage", {"value": "db", "label": "A DB row"}]},
|
|
{"type": "markdown", "text": "context"},
|
|
{"key": "notify", "label": "Push when done?", "type": "checkbox"}
|
|
]
|
|
}
|
|
```
|
|
|
|
## Risks / notes
|
|
- none
|
|
"""
|
|
|
|
|
|
class FakeHub:
|
|
"""A tiny HTTP server standing in for ``$AIA_TOOLS_URL``."""
|
|
|
|
def __init__(self):
|
|
self.calls: list[tuple[str, str, dict]] = []
|
|
self.forms: dict[str, dict] = {}
|
|
hub = self
|
|
|
|
class H(BaseHTTPRequestHandler):
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def _send(self, code, obj):
|
|
raw = json.dumps(obj).encode()
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(raw)))
|
|
self.end_headers()
|
|
self.wfile.write(raw)
|
|
|
|
def do_GET(self):
|
|
u = urllib.parse.urlparse(self.path)
|
|
q = dict(urllib.parse.parse_qsl(u.query))
|
|
hub.calls.append(("GET", u.path, q))
|
|
if u.path == "/proxy/tools/plugins/plans/hub/conversations":
|
|
rows = [
|
|
{"id": "c-plan", "sessionId": "sess-plan", "title": "Planning",
|
|
"startedAt": "2026-11-20T10:00:00Z", "endedAt": "2026-11-20T10:10:00Z",
|
|
"tokens": 1000, "costUsd": 0.5, "durationMs": 0},
|
|
{"id": "c-impl", "sessionId": "sess-impl", "title": "Impl",
|
|
"startedAt": "2026-11-21T10:00:00Z", "endedAt": "2026-11-21T10:20:00Z",
|
|
"tokens": 99000, "costUsd": 5.25, "durationMs": 1_200_000},
|
|
]
|
|
want = set(q.get("sids", "").split(","))
|
|
return self._send(200, {"conversations": [r for r in rows if r["sessionId"] in want]})
|
|
return self._send(404, {"error": {"message": "nope"}})
|
|
|
|
def do_POST(self):
|
|
u = urllib.parse.urlparse(self.path)
|
|
n = int(self.headers.get("Content-Length") or 0)
|
|
body = json.loads(self.rfile.read(n) or b"{}")
|
|
hub.calls.append(("POST", u.path, {"body": body, "depth": self.headers.get("X-Plugin-Call-Depth")}))
|
|
if u.path == "/proxy/tools/plugins/ask-form/actions/create":
|
|
fid = f"f{len(hub.forms) + 1}"
|
|
hub.forms[fid] = {"id": fid, "status": "pending", "url": f"https://forms/{fid}", **body}
|
|
return self._send(200, hub.forms[fid])
|
|
if u.path == "/proxy/tools/plugins/ask-form/actions/get":
|
|
f = hub.forms.get(body.get("id"))
|
|
if not f:
|
|
return self._send(404, {"error": {"message": "form not found", "kind": "not_found"}})
|
|
return self._send(200, f)
|
|
return self._send(404, {"error": {"message": "nope"}})
|
|
|
|
self.server = ThreadingHTTPServer(("127.0.0.1", 0), H)
|
|
self.url = f"http://127.0.0.1:{self.server.server_address[1]}/proxy/tools"
|
|
threading.Thread(target=self.server.serve_forever, daemon=True).start()
|
|
|
|
def close(self):
|
|
self.server.shutdown()
|
|
self.server.server_close()
|
|
|
|
|
|
class PlansPluginTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.hub = FakeHub()
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.hub.close()
|
|
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.dir = pathlib.Path(self.tmp.name)
|
|
(self.dir / "2026-11-20-widget.md").write_text(PLAN, encoding="utf-8")
|
|
(self.dir / "2026-11-21-other.md").write_text(
|
|
"---\ntitle: Other\nstatus: done\nsessionId: sess-x\n---\n\n# Other\n", encoding="utf-8")
|
|
self.hub.calls.clear()
|
|
self.hub.forms.clear()
|
|
|
|
def tearDown(self):
|
|
self.tmp.cleanup()
|
|
|
|
def run_action(self, name: str, payload: dict, *, plans_dir: bool = True) -> dict:
|
|
env = {k: v for k, v in os.environ.items() if not k.startswith("AIA_")}
|
|
env.update({"AIA_TOOLS_URL": self.hub.url, "AIA_TOOLS_TOKEN": "t", "AIA_PLUGIN_ID": "plans",
|
|
"AIA_PLUGIN_CALL_DEPTH": "0"})
|
|
if plans_dir:
|
|
env["AIA_PLANS_DIR"] = str(self.dir)
|
|
p = subprocess.run([sys.executable, str(ROOT / "actions" / f"{name}.py")],
|
|
input=json.dumps(payload), text=True, capture_output=True, env=env, timeout=30)
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
return json.loads(p.stdout)
|
|
|
|
# ── manifest ─────────────────────────────────────────────────────────
|
|
def test_manifest_and_assets(self):
|
|
mf = json.loads((ROOT / "plugin.json").read_text(encoding="utf-8"))
|
|
self.assertEqual(mf["id"], "plans")
|
|
self.assertNotIn("managed", mf)
|
|
self.assertEqual(mf["requires"], ["ask-form"])
|
|
self.assertEqual(set(mf["capabilities"]), {"plans.read", "plans.write", "conversations.read"})
|
|
self.assertEqual(mf["provides"], {"plans.index": "index"})
|
|
self.assertEqual(mf["events"][0]["on"], ["plugin:ask-form:form.submitted"])
|
|
self.assertEqual(mf["events"][0]["action"], "on_form_submitted")
|
|
self.assertEqual(mf["events"][1], {"id": "implement-link", "on": ["conversation.started"],
|
|
"action": "on_conversation_started"})
|
|
self.assertEqual({k for k, a in mf["actions"].items() if a.get("readOnly")},
|
|
{"list", "index", "get", "for_session"})
|
|
# `ai-agent plugin plans ls|show` + the MCP tools: reads only, by GET
|
|
self.assertEqual({n: c["action"] for n, c in mf["commands"].items()},
|
|
{"ls": "index", "show": "get"})
|
|
self.assertTrue(all(mf["actions"][c["action"]].get("readOnly") and c["mcp"]
|
|
for c in mf["commands"].values()))
|
|
for f in ("skill/scripts/plan-info.sh", "skill/scripts/plan-cost.sh"):
|
|
self.assertTrue(os.access(ROOT / f, os.X_OK), f)
|
|
for act in mf["actions"].values():
|
|
self.assertTrue((ROOT / act["script"]).is_file(), act["script"])
|
|
for kind in ("pages", "toolCards", "slots"):
|
|
for item in mf["ui"][kind]:
|
|
self.assertTrue((ROOT / item["html"]).is_file(), item["html"])
|
|
self.assertTrue(mf["ui"]["pages"][0]["subpath"])
|
|
self.assertEqual(mf["ui"]["slots"][0]["where"], "conversation.details")
|
|
tc = mf["ui"]["toolCards"][0]
|
|
self.assertTrue(tc["replace"])
|
|
import re
|
|
rx = re.compile(tc["match"]["filePathRegex"])
|
|
self.assertTrue(rx.search("/home/x/homelab/data/plans/2026-11-20-a.md"))
|
|
self.assertTrue(rx.search("data/plans/a.md"))
|
|
self.assertFalse(rx.search("/home/x/homelab/data/plans/sub/a.md"))
|
|
self.assertFalse(rx.search("/home/x/mydata/plans/a.md"))
|
|
for f in ("icon.svg", "illustration.webp", "README.md", "skill/SKILL.md"):
|
|
self.assertTrue((ROOT / f).is_file(), f)
|
|
svg = (ROOT / "icon.svg").read_text()
|
|
self.assertNotIn("<script", svg)
|
|
self.assertNotIn("href", svg)
|
|
self.assertIn("askFormId", (ROOT / "skill/SKILL.md").read_text())
|
|
|
|
# ── parsing ──────────────────────────────────────────────────────────
|
|
def test_record_parsing(self):
|
|
rec = C.record(self.dir / "2026-11-20-widget.md", with_body=True)
|
|
self.assertEqual(rec["title"], "Ship the widget")
|
|
self.assertEqual(rec["status"], "proposed")
|
|
self.assertEqual(rec["estCost"], 4.5)
|
|
self.assertEqual(rec["estTimeMinutes"], 30)
|
|
self.assertEqual(rec["conversationIds"], ["sess-impl", "sess-missing"])
|
|
self.assertEqual(rec["fileList"][0], {"file": "projects/widget/a.ts", "change": "add the thing"})
|
|
self.assertEqual(rec["files"], 2)
|
|
self.assertEqual([s["title"] for s in rec["stepList"]], ["Build it", "Ship it"])
|
|
self.assertEqual(rec["stepList"][0]["detail"], "write the code and the tests")
|
|
self.assertEqual(rec["questions"], 2)
|
|
q = rec["questionForm"]
|
|
self.assertEqual(q["fields"][0]["options"][0], {"value": "localStorage", "label": "localStorage"})
|
|
self.assertEqual(rec["projects"], ["widget"])
|
|
self.assertEqual(rec["services"], ["traefik"])
|
|
self.assertIsNone(rec["answers"])
|
|
self.assertEqual(rec["url"], "/plugins/plans/plans/2026-11-20-widget")
|
|
|
|
def test_bad_questions_ignored(self):
|
|
body = "## Questions\n\n```json\n{\"fields\": [{\"key\": \"a\", \"type\": \"radio\", \"label\": \"x\", \"options\": [\"one\"]}]}\n```\n"
|
|
self.assertIsNone(C.parse_questions(body))
|
|
self.assertIsNone(C.parse_questions("## Questions\n\n```json\n{nope\n```\n"))
|
|
|
|
def test_frontmatter_and_answers_helpers(self):
|
|
t = C.set_frontmatter("---\ntitle: A\nstatus: proposed\n---\n\nbody\n", "status", "done")
|
|
self.assertIn("status: done", t)
|
|
self.assertNotIn("proposed", t)
|
|
t = C.set_frontmatter(t, "askFormId", "f9")
|
|
self.assertTrue(t.startswith("---\ntitle: A\nstatus: done\naskFormId: f9\n---"))
|
|
self.assertTrue(C.set_frontmatter("no fm", "status", "done").startswith("---\nstatus: done\n---"))
|
|
t2 = C.write_answers("# X\n\n## Answers\n\nold\n\n## Risks\n- r\n", ["- **a** — b"], "now")
|
|
self.assertIn("- **a** — b", t2)
|
|
self.assertNotIn("old", t2)
|
|
self.assertIn("## Risks", t2)
|
|
self.assertEqual(t2.count("## Answers"), 1)
|
|
|
|
def test_safe_slug(self):
|
|
self.assertEqual(C.safe_slug("../../etc/passwd"), "passwd")
|
|
self.assertEqual(C.safe_slug("a.md"), "a")
|
|
self.assertEqual(C.safe_slug(""), "")
|
|
self.assertIsNone(C.plan_path(self.dir, "../nope"))
|
|
|
|
# ── actions ──────────────────────────────────────────────────────────
|
|
def test_list_joins_actuals(self):
|
|
out = self.run_action("list", {})
|
|
self.assertTrue(out["available"])
|
|
self.assertEqual(len(out["plans"]), 2)
|
|
w = next(p for p in out["plans"] if p["slug"] == "2026-11-20-widget")
|
|
self.assertEqual(w["actual"]["cost"], 5.75)
|
|
self.assertEqual(w["actual"]["tokens"], 100000)
|
|
# 10 min derived from startedAt/endedAt + the 20 min reported.
|
|
self.assertEqual(w["actual"]["durationMs"], 30 * 60_000)
|
|
self.assertEqual([c["sessionId"] for c in w["conversations"]], ["sess-plan", "sess-impl"])
|
|
gets = [c for c in self.hub.calls if c[0] == "GET"]
|
|
self.assertEqual(len(gets), 1)
|
|
self.assertEqual(gets[0][2]["metrics"], "1")
|
|
self.assertEqual(self.run_action("list", {"status": "done"})["plans"][0]["slug"], "2026-11-21-other")
|
|
self.assertEqual(len(self.run_action("list", {"q": "widget", "actuals": False})["plans"]), 1)
|
|
|
|
def test_list_and_index_without_dir(self):
|
|
self.assertEqual(self.run_action("list", {}, plans_dir=False), {"plans": [], "available": False})
|
|
self.assertEqual(self.run_action("index", {}, plans_dir=False), {"plans": []})
|
|
|
|
def test_index_no_network(self):
|
|
out = self.run_action("index", {})
|
|
self.assertEqual(len(out["plans"]), 2)
|
|
self.assertNotIn("actual", out["plans"][0])
|
|
self.assertEqual(self.hub.calls, [])
|
|
|
|
def test_get_and_not_found(self):
|
|
out = self.run_action("get", {"slug": "2026-11-20-widget"})
|
|
self.assertIn("## Summary", out["content"])
|
|
self.assertEqual(out["actual"]["cost"], 5.75)
|
|
self.assertIsNone(out["askForm"])
|
|
err = self.run_action("get", {"slug": "nope"})
|
|
self.assertEqual(err["_error"]["status"], 404)
|
|
err = self.run_action("get", {"slug": "2026-11-20-widget"}, plans_dir=False)
|
|
self.assertEqual(err["_error"]["status"], 403)
|
|
|
|
def test_set_status(self):
|
|
out = self.run_action("set_status", {"slug": "2026-11-20-widget", "status": "in-progress"})
|
|
self.assertEqual(out["plan"]["status"], "in-progress")
|
|
text = (self.dir / "2026-11-20-widget.md").read_text()
|
|
self.assertIn("status: in-progress\n", text)
|
|
self.assertIn("title: Ship the widget\n", text)
|
|
self.assertEqual(self.run_action("set_status", {"slug": "2026-11-20-widget", "status": "bogus"})["_error"]["status"], 400)
|
|
self.assertEqual(self.run_action("set_status", {"slug": "missing", "status": "done"})["_error"]["status"], 404)
|
|
self.assertEqual(list(self.dir.glob(".*.tmp")), [])
|
|
|
|
def test_for_session(self):
|
|
self.assertEqual([p["slug"] for p in self.run_action("for_session", {"sessionId": "sess-impl"})["plans"]],
|
|
["2026-11-20-widget"])
|
|
self.assertEqual(self.run_action("for_session", {"sessionId": "zzz"})["plans"], [])
|
|
self.assertEqual(self.run_action("for_session", {})["plans"], [])
|
|
|
|
def test_open_questions_creates_then_reuses(self):
|
|
out = self.run_action("open_questions", {"slug": "2026-11-20-widget"})
|
|
self.assertTrue(out["created"])
|
|
self.assertEqual(out["formId"], "f1")
|
|
create = [c for c in self.hub.calls if c[1].endswith("/ask-form/actions/create")][0]
|
|
body = create[2]["body"]
|
|
self.assertEqual(create[2]["depth"], "0")
|
|
self.assertEqual(body["title"], "Ship the widget")
|
|
self.assertEqual(body["sessionId"], "sess-plan")
|
|
self.assertEqual(body["meta"], {"plugin": "plans", "planSlug": "2026-11-20-widget"})
|
|
self.assertEqual(body["fields"][-1]["key"], "anything_else")
|
|
self.assertIn("askFormId: f1\n", (self.dir / "2026-11-20-widget.md").read_text())
|
|
|
|
again = self.run_action("open_questions", {"slug": "2026-11-20-widget"})
|
|
self.assertFalse(again["created"])
|
|
self.assertEqual(again["formId"], "f1")
|
|
self.assertEqual(again["status"], "pending")
|
|
|
|
got = self.run_action("get", {"slug": "2026-11-20-widget"})
|
|
self.assertEqual(got["askForm"]["status"], "pending")
|
|
|
|
# The stamped form vanished (or reopen asked): a new one is made.
|
|
self.hub.forms.clear()
|
|
fresh = self.run_action("open_questions", {"slug": "2026-11-20-widget"})
|
|
self.assertTrue(fresh["created"])
|
|
self.assertIn(f"askFormId: {fresh['formId']}\n", (self.dir / "2026-11-20-widget.md").read_text())
|
|
reopened = self.run_action("open_questions", {"slug": "2026-11-20-widget", "reopen": True})
|
|
self.assertTrue(reopened["created"])
|
|
self.assertNotEqual(reopened["formId"], fresh["formId"])
|
|
|
|
def test_open_questions_without_spec(self):
|
|
err = self.run_action("open_questions", {"slug": "2026-11-21-other"})
|
|
self.assertEqual(err["_error"]["status"], 400)
|
|
|
|
def test_on_form_submitted_writes_answers(self):
|
|
ev = {"event": "plugin:ask-form:form.submitted", "source": "ask-form", "data": {
|
|
"id": "f7", "formId": "f7", "status": "submitted", "closedAt": "2026-11-22T09:30:00Z",
|
|
"meta": {"plugin": "plans", "planSlug": "2026-11-20-widget"},
|
|
"answers": {"store": "db", "notify": True, "anything_else": "ship it\nsoon"}}}
|
|
out = self.run_action("on_form_submitted", ev)
|
|
self.assertEqual(out, {"ok": True, "slug": "2026-11-20-widget", "answers": 3})
|
|
text = (self.dir / "2026-11-20-widget.md").read_text()
|
|
self.assertIn("## Answers\n\n_Answered 2026-11-22 09:30 UTC_\n", text)
|
|
self.assertIn("- **Where do answers live?** — A DB row", text)
|
|
self.assertIn("- **Push when done?** — yes", text)
|
|
self.assertIn("- **Anything else** — ship it\n soon", text)
|
|
self.assertIn("askFormId: f7\n", text)
|
|
# A re-submit replaces the section.
|
|
ev["data"]["answers"] = {"store": "localStorage", "notify": False}
|
|
self.run_action("on_form_submitted", ev)
|
|
text = (self.dir / "2026-11-20-widget.md").read_text()
|
|
self.assertEqual(text.count("## Answers"), 1)
|
|
self.assertIn("— localStorage", text)
|
|
self.assertNotIn("— A DB row", text)
|
|
rec = C.record(self.dir / "2026-11-20-widget.md", with_body=True)
|
|
self.assertTrue(rec["answered"])
|
|
self.assertEqual(len(rec["answers"]["lines"]), 2)
|
|
# Still parses the rest of the plan.
|
|
self.assertEqual(rec["steps"], 2)
|
|
self.assertEqual(rec["questions"], 2)
|
|
|
|
def test_on_conversation_started_links_the_implementing_run(self):
|
|
ev = {"event": "conversation.started", "data": {
|
|
"sessionId": "sess-new", "worker": "local", "origin": "app",
|
|
"prompt": "Implement the plan `data/plans/2026-11-20-widget.md` — Ship the widget.\n\n"
|
|
"Also see data/plans/nope.md"}}
|
|
self.assertEqual(self.run_action("on_conversation_started", ev),
|
|
{"ok": True, "linked": ["2026-11-20-widget"]})
|
|
fm, _ = C.parse_frontmatter((self.dir / "2026-11-20-widget.md").read_text())
|
|
self.assertEqual(C.list_field(fm, "conversationIds"), ["sess-impl", "sess-missing", "sess-new"])
|
|
# once only; the planning session and prompts naming no plan link nothing
|
|
self.assertEqual(self.run_action("on_conversation_started", ev)["linked"], [])
|
|
ev["data"]["sessionId"] = "sess-plan"
|
|
self.assertEqual(self.run_action("on_conversation_started", ev)["linked"], [])
|
|
self.assertEqual(self.run_action("on_conversation_started", {"event": "conversation.started", "data": {
|
|
"sessionId": "sess-x", "prompt": "just chatting"}})["linked"], [])
|
|
self.assertEqual(self.run_action("on_conversation_started", {"event": "conversation.started", "data": {
|
|
"sessionId": "../bad id", "prompt": "data/plans/2026-11-20-widget.md"}})["linked"], [])
|
|
self.assertEqual(self.run_action("on_conversation_started", ev, plans_dir=False)["linked"], [])
|
|
|
|
def test_on_form_submitted_ignores_other_forms(self):
|
|
before = (self.dir / "2026-11-20-widget.md").read_text()
|
|
out = self.run_action("on_form_submitted", {"data": {"meta": {"plugin": "new-project"}, "answers": {"a": 1}}})
|
|
self.assertIn("skipped", out)
|
|
out = self.run_action("on_form_submitted", {"data": {"meta": {"plugin": "plans", "planSlug": "nope"}}})
|
|
self.assertIn("skipped", out)
|
|
self.assertEqual((self.dir / "2026-11-20-widget.md").read_text(), before)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|