pages.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. """The pages bundle (moved verbatim from the pre-split web_stack_test.py;
  2. see test/harness.py for the shared machinery and the runner)."""
  3. from harness import * # noqa: F401,F403 — the shared wire helpers
  4. # =============================================================================
  5. # Bundle: pages — block presentation, diff URLs, computed display state,
  6. # terminal rendering (rejected entries, ANSI SGR) and task-page layout.
  7. # Fixture-driven: tasks and sessions are inserted as rows; blocks are
  8. # raised through the push-era wire (POST /api/saddle/results with a
  9. # blocked state) or inserted directly for terminal-task fixtures; only
  10. # the rejected-ride scenario dispatches.
  11. # =============================================================================
  12. def run(ctx):
  13. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  14. app = ctx.app
  15. def raise_block(session_id, question, kind="question", options=None, body=None):
  16. """The push-era block raise: a blocked round-results push
  17. carrying the block payload (the poll-era /update channel is
  18. gone — 404 below pins that)."""
  19. block = {"question": question, "type": kind}
  20. if options is not None:
  21. block["options"] = options
  22. if body is not None:
  23. block["body"] = body
  24. return saddle_api("POST", "/api/saddle/results", fake_token,
  25. {"session_id": session_id, "state": "blocked",
  26. "block": block})
  27. check(True, "login yields an auth slot")
  28. print("== the poll-era wire is gone (arch 19) ==")
  29. # The daemon never called update/poll (verified against saddle/src);
  30. # the routes 404 for any caller, authenticated or not.
  31. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  32. {"type": "status", "session_id": 1,
  33. "data": {"state": "working"}})
  34. check(status == 404, "POST /api/saddle/{id}/update is gone (404)")
  35. status, _ = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  36. check(status == 404, "GET /api/saddle/{id}/poll is gone (404)")
  37. print("== blocks: push-era raises + body presentation ==")
  38. conn = db()
  39. conn.execute("insert into tasks (project_id, title, status, priority,"
  40. " created_at)"
  41. " values (1, 'Block display task', 'working', 5,"
  42. " strftime('%s','now'))")
  43. plan_task = conn.execute("select max(id) from tasks").fetchone()[0]
  44. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  45. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  46. (plan_task, fake_id))
  47. conn.commit()
  48. session_id = conn.execute("select max(id) from sessions").fetchone()[0]
  49. conn.close()
  50. status, _ = raise_block(session_id, "Which database?", kind="question",
  51. options=["SQLite", "Postgres"], body="# Storage choice")
  52. check(status == 200, "question block raised through the results push")
  53. print("== B1: highlight-to-comment quote dialog ==")
  54. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  55. check(status == 200 and "quote-comment-dialog" in page and "quote-text" in page,
  56. "task page carries the quote-comment dialog the popover opens")
  57. check('name="quote"' in page and 'name="return_to"' in page,
  58. "quote dialog posts the quote and return-to fields")
  59. status, page = http("GET", "/tasks/%d/log" % plan_task, timeout=15)
  60. check(status == 200 and "data-log-feed" in page and "data-log-more" in page,
  61. "the event log page renders the feed and the load-more control")
  62. print("== B3: review section hides the duplicate body ==")
  63. status, _ = raise_block(session_id, "Review the diff", kind="review",
  64. body="# The change\n\nReworks the flange module.")
  65. check(status == 200, "review block raised through the results push")
  66. detail = task_state(auth, plan_task)
  67. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  68. check(detail.get("review_pending") is True,
  69. "review section shows while the review is unanswered")
  70. check(review_block.get("show_body") is False,
  71. "pending review block hides its duplicate body preview")
  72. check(review_block.get("body", "").startswith("# The change"),
  73. "review body itself still arrives in state (B2 counterpart)")
  74. act(auth, review_block["answer_action"], {"verdict": "accept"})
  75. detail = task_state(auth, plan_task)
  76. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  77. check(review_block.get("show_body") is True,
  78. "answered review shows the body again (banner gone)")
  79. check(review_block.get("answer") == "Review approved. Continue with the task.",
  80. "the review accept form's verdict marker resolves to the stable wording")
  81. # Plan 16 S2/R4: no verdict constant ships in any template — the
  82. # accept forms carry only the verdict marker.
  83. task_page_html = http_get_page(auth, "/tasks/%d" % plan_task)
  84. check("Plan approved. Proceed with implementation." not in task_page_html
  85. and "Review approved. Continue with the task." not in task_page_html,
  86. "the task page ships no verdict constants (server-owned wording)")
  87. check('name="verdict" value="accept"' in task_page_html,
  88. "the accept forms post the verdict marker")
  89. # Plan 16 S5 (U1): verdict-shaped blocks keep their explicit
  90. # buttons + free-text path; a question with NULL options renders
  91. # the question form (radio "other" + free reply), never a
  92. # free-text-only verdict.
  93. check("Request changes" in task_page_html and 'name="feedback"' in task_page_html,
  94. "the review verdict keeps Request changes with free-text feedback (U1)")
  95. check('value="__other__"' in task_page_html and 'name="other"' in task_page_html,
  96. "question blocks render the option/other question form (U1)")
  97. status, _ = raise_block(session_id, "Free-text thought?", kind="question")
  98. check(status == 200, "a NULL-options question block raises")
  99. bare_question = [b for b in task_state(auth, plan_task)["blocks"]
  100. if b["question"] == "Free-text thought?"][0]
  101. check(bare_question.get("options") == []
  102. and bare_question.get("block_type") == "question",
  103. "a NULL-options question stays a question (no options, not a verdict)")
  104. print("== B2: question block body above options ==")
  105. # Contract side (A2 will restore bodies end-to-end): a question
  106. # block raised with a heredoc body carries it; the body preview
  107. # rides above the options (template order) and survives answering
  108. # alongside the selected answer. (Blocks list newest-first; the
  109. # U1 fixture above raised a second, options-less question.)
  110. detail = task_state(auth, plan_task)
  111. question = [b for b in detail["blocks"]
  112. if b["block_type"] == "question"
  113. and b["body"] == "# Storage choice"][0]
  114. check(question.get("body") == "# Storage choice"
  115. and question.get("show_body") is True,
  116. "question block keeps its body markdown with the preview on")
  117. act(auth, question["answer_action"], {"option": "SQLite"})
  118. detail = task_state(auth, plan_task)
  119. question = [b for b in detail["blocks"]
  120. if b["block_type"] == "question"
  121. and b["body"] == "# Storage choice"][0]
  122. check(question.get("answered") is True and question.get("answer") == "SQLite"
  123. and question.get("body") == "# Storage choice"
  124. and question.get("show_body") is True,
  125. "answered question shows body + selected answer")
  126. print("== B5: compare-changes SSH -> HTTPS ==")
  127. def diff_url_for_project(git_url, suffix):
  128. state = slot_public(auth, "/projects", "projects")
  129. act(auth, state["create"], {"name": "diff-%s" % suffix, "git_url": git_url})
  130. project_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  131. if p["name"] == "diff-%s" % suffix][0])
  132. conn = db()
  133. conn.execute("insert into tasks (project_id, title, status, task_branch,"
  134. " branch_from, created_at) values (?, ?, 'working', 'feature/x',"
  135. " 'main', strftime('%s','now'))", (project_id, "Diff %s" % suffix))
  136. conn.commit()
  137. task_id = conn.execute("select max(id) from tasks").fetchone()[0]
  138. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at,"
  139. " outcome) values (?, ?, strftime('%s','now'), strftime('%s','now'),"
  140. " 'done')", (task_id, fake_id))
  141. conn.commit()
  142. session = conn.execute("select max(id) from sessions").fetchone()[0]
  143. conn.close()
  144. status, _ = raise_block(session, "Review the diff", kind="review")
  145. return task_state(auth, task_id).get("review_diff_url") or ""
  146. check(diff_url_for_project("ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git",
  147. "fabrica")
  148. == "https://fabrica.unitatem.net/clanker/clanker-saddle/compare/main...feature/x",
  149. "ssh://git@host:port/owner/repo.git translates (port dropped)")
  150. check(diff_url_for_project("git@github.com:acme/widgets.git", "scp")
  151. == "https://github.com/acme/widgets/compare/main...feature/x",
  152. "git@host:owner/repo.git translates to the browse host")
  153. check(diff_url_for_project("https://example.com/plain/repo", "plain")
  154. == "https://example.com/plain/repo/compare/main...feature/x",
  155. "HTTPS URLs pass through unchanged")
  156. print("== B6: computed display state ==")
  157. # Draft tasks display as draft (plan 11) and never dispatch.
  158. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  159. "project_id": "1",
  160. "title": "Draft display task",
  161. "priority": "5",
  162. })
  163. draft_display = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  164. if t["title"] == "Draft display task"][0])
  165. detail = task_state(auth, draft_display)
  166. check(detail["status"] == "draft" and detail.get("display") == "draft",
  167. "new tasks default to draft and display it")
  168. check(detail.get("draft") is True and detail.get("enqueue") is not None
  169. and detail.get("delete") is not None,
  170. "draft tasks expose the enqueue + delete actions")
  171. check(quiet_window(quiet_seconds(),
  172. lambda: task_state(auth, draft_display)["status"] == "draft",
  173. "draft task never dispatches"),
  174. "a draft task is never dispatched or woken for")
  175. # Plan 12: the waiting-on-drafts block is deleted (goal tasks are
  176. # the goal agent's to sequence); a parked task displays plainly.
  177. conn = db()
  178. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  179. " values (1, 'Parked plain task', 'suspended', 5, strftime('%s','now'))")
  180. conn.commit()
  181. conn.close()
  182. parked_id = db().execute("select max(id) from tasks").fetchone()[0]
  183. detail = task_state(auth, parked_id)
  184. check(detail.get("display") == "parked",
  185. "a suspended task displays as parked (%s)" % detail.get("display"))
  186. dash = slot_public(auth, "/", "dashboard")
  187. check(not dash.get("waiting_drafts"),
  188. "the waiting-on-drafts block is gone from the dashboard data")
  189. status, home_page = http("GET", "/", timeout=15)
  190. check(status == 200 and "Waiting on subtasks to be enqueued" not in home_page,
  191. "the dashboard renders no waiting-on-drafts section")
  192. conn = db()
  193. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  194. " values (1, 'Parent', 'done', 5, strftime('%s','now'))")
  195. parent6 = conn.execute("select max(id) from tasks").fetchone()[0]
  196. # The post-mortem case: stored done WITH an unanswered review block.
  197. # (A terminal task consumes result pushes silently — plan 13 B2 —
  198. # so the row is inserted directly, the goalui deep-link pattern.)
  199. conn.execute("insert into task_blocks (task_id, question, type, created_at)"
  200. " values (?, 'Review the final diff', 'review',"
  201. " strftime('%s','now'))", (parent6,))
  202. conn.commit()
  203. conn.close()
  204. detail = task_state(auth, parent6)
  205. check(detail.get("display") == "review requested" and detail.get("terminal") is True,
  206. "unanswered review overrides the stored done status (terminal flag keeps stored truth)")
  207. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  208. if int(t["id"]) == parent6][0]
  209. check(queue["display"] == "review requested",
  210. "queue row shows the computed review-requested display")
  211. # With the review answered the display falls back to the stored
  212. # status (the plan-12 shape: no subtask-delegation states).
  213. conn = db()
  214. conn.execute("update task_blocks set answered_at = strftime('%s','now'),"
  215. " answer = 'Human approved the review' where task_id = ?", (parent6,))
  216. conn.commit()
  217. conn.close()
  218. detail = task_state(auth, parent6)
  219. check(detail.get("display") == "done" and detail.get("terminal") is True,
  220. "answered review falls back to the stored done display (%s)"
  221. % detail.get("display"))
  222. # Flags track the stored status on failure.
  223. conn = db()
  224. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  225. " where id = ?", (parent6,))
  226. conn.commit()
  227. conn.close()
  228. detail = task_state(auth, parent6)
  229. check(detail.get("display") == "failed" and detail.get("failed") is True
  230. and detail.get("terminal") is True,
  231. "failed task with answered review shows failed + terminal flags")
  232. print("== rejected entries (non-fatal) ==")
  233. # The push wire: a rejected entry rides a round-results push, stores
  234. # on the session and streams through SSE; the task is untouched.
  235. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token, {
  236. "session_id": session_id,
  237. "events": [{"seq": 9021, "kind": "tool_result", "actor": "harness",
  238. "payload": {"command": "bash -n script.sh",
  239. "stderr": "syntax error near line 3 (recoverable)",
  240. "exit_code": 1}}]})
  241. check(status == 200 and int(body.get("stored") or 0) == 1,
  242. "a failed tool result rides the events push")
  243. request = urllib.request.Request(WEB + "/tasks/%d/events/stream" % plan_task)
  244. with urllib.request.urlopen(request, timeout=15) as stream:
  245. result_event = None
  246. deadline = time.monotonic() + 8
  247. while time.monotonic() < deadline and result_event is None:
  248. line = stream.readline().decode().strip()
  249. if not line.startswith("data: ") or line == "data: ping":
  250. continue
  251. event = json.loads(line[6:])
  252. if (event.get("kind") == "tool_result"
  253. and "syntax error near line 3" in
  254. (event.get("payload", {}).get("stderr") or "")):
  255. result_event = event
  256. check(result_event is not None,
  257. "the event stream carries tool results with their reason")
  258. # The page template renders the feed and the filters.
  259. status, page = http("GET", "/tasks/%d/log" % plan_task, timeout=15)
  260. check(status == 200 and "data-log-filter" in page and "data-log-search" in page,
  261. "the event log page renders filters and search")
  262. print("== B8: byte-exact payload delivery over the event stream ==")
  263. # Byte-exact delivery: ANSI-coloured turn text flows through the
  264. # ledger + SSE untouched (the client renderer styles them).
  265. coloured = "\x1b[1;32mbold green\x1b[0m then \x1b[38;5;196m256-red\x1b[0m\n"
  266. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token, {
  267. "session_id": session_id,
  268. "events": [{"seq": 9100, "kind": "turn_text",
  269. "payload": {"turn": 9, "text": coloured}}]})
  270. check(status == 200 and int(body.get("stored") or 0) == 1,
  271. "the coloured turn text stores as one event")
  272. request = urllib.request.Request(WEB + "/tasks/%d/events/stream" % plan_task)
  273. with urllib.request.urlopen(request, timeout=15) as stream:
  274. coloured_event = None
  275. deadline = time.monotonic() + 8
  276. while time.monotonic() < deadline and coloured_event is None:
  277. line = stream.readline().decode().strip()
  278. if not line.startswith("data: ") or line == "data: ping":
  279. continue
  280. event = json.loads(line[6:])
  281. if (event.get("kind") == "turn_text"
  282. and "\x1b[1;32m" in (event.get("payload", {}).get("text") or "")):
  283. coloured_event = event
  284. check(coloured_event is not None
  285. and "\x1b[38;5;196m" in coloured_event["payload"]["text"],
  286. "payload bytes stream byte-exact to the client renderer")
  287. # Dispatch path: a rejected entry in a round's results push flows
  288. # into the audit trail without failing (or finishing) the task.
  289. task_id_tmp = create_queued(auth, {
  290. "project_id": "1",
  291. "title": "Rejected ride",
  292. "priority": "2",
  293. })
  294. rejected_task = task_id_tmp
  295. check(wait_for(lambda: task_state(auth, rejected_task).get("status") == "working"
  296. or False, timeout=60, what="rejected-ride working") is not None,
  297. "rejected-ride task reaches working")
  298. fake.queue_output("rejected", "echo 'too long' | saddle",
  299. "max_tokens exceeded (recoverable)")
  300. check(wait_task_done(auth, rejected_task, timeout=60) is not None,
  301. "task completes normally past rejected entries")
  302. stored = [row for row in event_rows(rejected_task, ["command_output"])
  303. if "max_tokens exceeded" in row[1]]
  304. check(len(stored) >= 1,
  305. "command_output events stored in the audit trail (%d rows)" % len(stored))
  306. check(task_state(auth, rejected_task)["status"] == "done"
  307. and "fake daemon finished" in (task_state(auth, rejected_task).get("summary") or ""),
  308. "rejected entries never fail the task")
  309. print("== plan 11 task D: task page — progress first, 50/50 grid, expanders ==")
  310. detail = task_state(auth, plan_task)
  311. block_ids = [int(b["id"]) for b in detail.get("blocks", [])]
  312. check(len(block_ids) >= 3 and block_ids == sorted(block_ids, reverse=True),
  313. "the blocks section orders newest-first via the sealed GET state (%s)"
  314. % block_ids)
  315. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  316. # Plan 11 task D: the progress feed sits ABOVE the status card;
  317. # status + description share a 50/50 grid; the plan detail hides
  318. # behind its expander below it.
  319. check(status == 200 and "grid-2" in page
  320. and page.index("<h3>Progress</h3>") < page.index("status-head"),
  321. "the progress feed renders above the status card")
  322. check(page.index("grid-2") < page.index("status-head")
  323. and page.index("status-head") < page.index('data-long-form data-field="task"'),
  324. "status and description sit side by side inside the grid (status first)")
  325. check("Mandate" in page and "plan-expander" not in page,
  326. "the task page carries no plan expander (plans live on the goal)")
  327. # Answered blocks fold behind the history expander (this fixture's
  328. # three blocks are all answered by now).
  329. check("blocks-history" in page and "Answered blocks" in page,
  330. "answered blocks hide behind the blocks history expander")
  331. conn = db()
  332. conn.execute("insert into tasks (project_id, title, status, priority,"
  333. " created_at) values (1, 'Progress layout task', 'working', 5,"
  334. " strftime('%s','now','-120 seconds'))")
  335. layout_task = conn.execute("select max(id) from tasks").fetchone()[0]
  336. # backdated so the dashboard-timeline fixtures below stay the
  337. # newest events
  338. for offset, line in ((90, "first update"), (89, "second update")):
  339. payload = json.dumps({"text": line})
  340. conn.execute(
  341. "insert into events (kind, actor, scope_type, scope_id, payload,"
  342. " created_at) values ('progress', 'model', 'task', ?, ?,"
  343. " strftime('%s','now', ?))",
  344. (layout_task, payload, "-%d seconds" % offset))
  345. conn.commit()
  346. conn.close()
  347. status, history_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  348. check(status == 200
  349. and history_page.index("progress-latest") < history_page.index("progress-history"),
  350. "the progress timeline renders newest-first (latest above the history)")
  351. # The edit expander sits UNDER the "Show history" expander.
  352. check(history_page.index("Show history") < history_page.index("edit-expander"),
  353. "the edit expander sits under the Show history expander")
  354. print("== heredoc completion reports: markdown card + timeline snippet ==")
  355. # The daemon's `cat << 'EOF' | saddle done` stores a markdown
  356. # summary (the failure path stores the same field); the task page
  357. # renders it as a full-width completion-report card directly below
  358. # the status/description grid — markdown via stm-markdown
  359. # (XSS-safe), "Completion report" when done, "Failure summary"
  360. # when failed, no card when the summary is empty. The dashboard
  361. # timeline snippets the summary's FIRST line.
  362. report_md = ("## Flange wired and tested\n\n"
  363. "Ran `meson test` over the full matrix.\n\n"
  364. "```sh\nmeson test -C builddir\n```\n\n"
  365. "<b>not html</b> & escaped\n")
  366. conn = db()
  367. conn.execute("insert into tasks (project_id, title, status, priority,"
  368. " summary, started_at, completed_at, created_at)"
  369. " values (1, 'Report done task', 'done', 5, ?,"
  370. " strftime('%s','now'), strftime('%s','now'),"
  371. " strftime('%s','now'))", (report_md,))
  372. report_done = conn.execute("select max(id) from tasks").fetchone()[0]
  373. conn.execute("insert into tasks (project_id, title, status, priority,"
  374. " summary, started_at, completed_at, created_at)"
  375. " values (1, 'Report failed task', 'failed', 5,"
  376. " 'Boom: tests failed\n\nsecond line carries the detail',"
  377. " strftime('%s','now'), strftime('%s','now'),"
  378. " strftime('%s','now'))")
  379. report_failed = conn.execute("select max(id) from tasks").fetchone()[0]
  380. conn.execute("insert into tasks (project_id, title, status, priority,"
  381. " started_at, completed_at, created_at)"
  382. " values (1, 'Report empty task', 'done', 5,"
  383. " strftime('%s','now'), strftime('%s','now'),"
  384. " strftime('%s','now'))")
  385. report_empty = conn.execute("select max(id) from tasks").fetchone()[0]
  386. # The terminal transitions ride the ledger (state_change events
  387. # carrying the summary the timeline snippets).
  388. for task_id, to, summary in (
  389. (report_done, "done", report_md),
  390. (report_failed, "failed", "Boom: tests failed\n\nsecond line carries the detail"),
  391. (report_empty, "done", "")):
  392. payload = {"from": "working", "to": to,
  393. "text": "Task completed" if to == "done" else "Task failed"}
  394. if summary:
  395. payload["summary"] = summary
  396. conn.execute(
  397. "insert into events (kind, actor, scope_type, scope_id, payload,"
  398. " created_at) values ('state_change', 'system', 'task', ?, ?,"
  399. " strftime('%s','now'))",
  400. (task_id, json.dumps(payload)))
  401. conn.commit()
  402. conn.close()
  403. done_state = task_state(auth, report_done)
  404. check(done_state["report_title"] == "Completion report"
  405. and "## Flange wired" in (done_state.get("summary") or ""),
  406. "a done task's summary rides the report card state")
  407. check(task_state(auth, report_failed)["report_title"] == "Failure summary",
  408. "a failed task's card heading reads Failure summary")
  409. empty_state = task_state(auth, report_empty)
  410. check(empty_state["report_title"] == "" and not (empty_state.get("summary") or ""),
  411. "an empty summary renders no report card (no heading)")
  412. check(task_state(auth, layout_task)["report_title"] == "",
  413. "non-terminal tasks never show the report card")
  414. status, page = http("GET", "/tasks/%d" % report_done, timeout=15)
  415. check(status == 200 and "completion-report" in page
  416. and page.index("grid-2") < page.index("completion-report")
  417. < page.index("edit-expander"),
  418. "the completion-report card sits below the status/description grid, full width")
  419. card = page[page.index("completion-report"):page.index("edit-expander")]
  420. check('stm-markdown="task.summary"' in card
  421. and 'stm-text="task.report_title"' in card,
  422. "the card renders the summary as markdown under its state-driven heading")
  423. check("<strong>Summary:</strong>" not in page,
  424. "the old plain-text summary line is gone (the card owns the summary)")
  425. # The markdown itself renders client-side: drive the SHIPPED
  426. # stm-markdown renderer (statum.js) on the fixture summary via
  427. # node — headings and code come out as HTML, no markdown syntax
  428. # leaks, raw HTML stays escaped.
  429. status, statum_js = http("GET", "/_statum/resource/statum.js", timeout=15)
  430. skip = None if status == 200 else "statum.js not served"
  431. parts = []
  432. if skip is None:
  433. def extract_md(name, source):
  434. start = source.index("function %s(" % name)
  435. depth = 0
  436. index = source.index("{", start)
  437. end = index
  438. while True:
  439. if source[end] == "{":
  440. depth += 1
  441. elif source[end] == "}":
  442. depth -= 1
  443. if depth == 0:
  444. break
  445. end += 1
  446. return source[start:end + 1]
  447. try:
  448. parts = [extract_md(name, statum_js)
  449. for name in ("safeMarkdownUrl", "mdLinks", "mdInline", "renderMarkdown")]
  450. except ValueError:
  451. skip = "renderer functions missing"
  452. rendered = ""
  453. if skip is None:
  454. try:
  455. result = subprocess.run(
  456. ["node", "-e", "%s\n%s\n%s\n%s\nconsole.log(renderMarkdown(process.argv[1]));"
  457. % tuple(parts), report_md],
  458. capture_output=True, text=True, timeout=20)
  459. rendered = result.stdout
  460. except (OSError, subprocess.SubprocessError):
  461. skip = "node unavailable"
  462. if skip is not None:
  463. check(True, "stm-markdown renderer present (%s, deep check skipped)" % skip)
  464. else:
  465. check("<h2>Flange wired and tested</h2>" in rendered
  466. and "<pre><code" in rendered and "<code>meson test</code>" in rendered,
  467. "the report summary renders headings and code through stm-markdown")
  468. check("## Flange" not in rendered and "```sh" not in rendered
  469. and "`meson test`" not in rendered,
  470. "no raw markdown syntax leaks into the rendered report")
  471. check("<b>not html</b>" not in rendered and "&lt;b&gt;not html&lt;/b&gt;" in rendered
  472. and "&amp; escaped" in rendered,
  473. "raw HTML in the summary stays escaped (XSS-safe)")
  474. # The dashboard timeline: completion/failure events snippet the
  475. # summary's first line, falling back to the bare verdict text.
  476. dash = slot_public(auth, "/", "dashboard")
  477. done_event = next((e for e in dash.get("activity", [])
  478. if e["kind"] == "completed" and int(e["task_id"]) == report_done), None)
  479. check(done_event is not None
  480. and done_event["text"] == "Task completed: ## Flange wired and tested",
  481. "the timeline completion event snippets the summary's first line")
  482. failed_event = next((e for e in dash.get("activity", [])
  483. if e["kind"] == "failed" and int(e["task_id"]) == report_failed), None)
  484. check(failed_event is not None
  485. and failed_event["text"] == "Task failed: Boom: tests failed",
  486. "the timeline failure event snippets the summary's first line")
  487. empty_event = next((e for e in dash.get("activity", [])
  488. if e["kind"] == "completed" and int(e["task_id"]) == report_empty), None)
  489. check(empty_event is not None and empty_event["text"] == "Task completed",
  490. "a missing summary falls back to the bare timeline text")
  491. print("== plan 11 task D: block split + queue-screen layout ==")
  492. # One open and one answered question: the open block renders in
  493. # full, the answered one folds behind the history expander.
  494. conn = db()
  495. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  496. " values (?, ?, strftime('%s','now'))", (layout_task, fake_id))
  497. conn.commit()
  498. split_session = conn.execute("select max(id) from sessions").fetchone()[0]
  499. conn.close()
  500. raise_block(split_session, "Open question for layout?", kind="question")
  501. raise_block(split_session, "Answered question for layout?", kind="question")
  502. answered_block = [b for b in task_state(auth, layout_task)["blocks"]
  503. if b["question"] == "Answered question for layout?"][0]
  504. act(auth, answered_block["answer_action"], {"answer": "Yes"})
  505. detail = task_state(auth, layout_task)
  506. check(len(detail.get("open_blocks", [])) == 1
  507. and len(detail.get("answered_blocks", [])) == 1
  508. and detail["open_blocks"][0]["question"] == "Open question for layout?"
  509. and detail["answered_blocks"][0]["question"] == "Answered question for layout?",
  510. "the task slot splits blocks into open (current) and answered lists")
  511. status, page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  512. check(status == 200
  513. and page.index('stm-for-block-in="task.open_blocks"') < page.index("blocks-history")
  514. < page.index('stm-for-block-in="task.answered_blocks"'),
  515. "current blocks render in full above the answered-behind-expander history")
  516. check(page.index("status-head") < page.index("Cancel task"),
  517. "the lifecycle buttons ride the status card inside the grid")
  518. status, queue_page = http("GET", "/tasks", timeout=15)
  519. check(status == 200
  520. and queue_page.index("filter-status") < queue_page.index("<table")
  521. and "filter-goal" in queue_page,
  522. "the filter controls (status + goal) sit above the queue table")
  523. check("New task" in queue_page and "task-mode" in queue_page
  524. and "task-enqueue-after" in queue_page
  525. and 'name="plan_auto_approve"' not in queue_page,
  526. "the create expander offers the mode + auto-enqueue-after selects"
  527. " (no subtask checkboxes)")
  528. print("== plan 12: the web surfaces — pile, timeline, queue, task page ==")
  529. # A goal parked in plan review feeds the unified dashboard pile;
  530. # goal events feed the timeline.
  531. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  532. "project_id": "1", "title": "Dashboard goal",
  533. "brief": "Feeds the pile.", "branch_name": "goal/dash"})
  534. conn = db()
  535. goal3 = conn.execute(
  536. "select id from goals where title = 'Dashboard goal'").fetchone()[0]
  537. conn.close()
  538. fake.goal_script = [("plan", "# Dash plan\n\n1. Probe the pile")]
  539. act(auth, goal_state(goal3)["start"], {})
  540. check(wait_for(lambda: goal_state(goal3)["status"] == "plan_review" or False,
  541. timeout=60, what="dashboard goal enters plan review") is not None,
  542. "the dashboard goal reaches plan review")
  543. check(wait_for(lambda: any(b.get("item_type") == "goal"
  544. and int(b.get("goal_id") or 0) == goal3
  545. for b in slot_public(auth, "/", "dashboard")["pinned"])
  546. or False, timeout=30, what="goal block pins on the dashboard") is not None,
  547. "the unified dashboard pile carries the goal's plan review")
  548. pile = slot_public(auth, "/", "dashboard")["pinned"]
  549. check(all(b.get("item_type") in ("task", "goal") for b in pile),
  550. "pile items carry type badges (task/goal interleaved)")
  551. goal_pile = [b for b in pile if b.get("item_type") == "goal"][0]
  552. check(goal_pile["block_type"] == "plan" and "Dashboard goal" in goal_pile["goal_title"],
  553. "the goal pile card names the goal and block kind")
  554. # Answer it: the pile drains.
  555. act(auth, goal_state(goal3)["plan_pending_block"]["answer_action"],
  556. {"answer": "Plan approved. Proceed with implementation."})
  557. check(wait_for(lambda: not any(b.get("item_type") == "goal"
  558. and int(b.get("goal_id") or 0) == goal3
  559. for b in slot_public(auth, "/", "dashboard")["pinned"])
  560. or False, timeout=30, what="goal pile card drains") is not None,
  561. "answering the review drains the goal's pile card")
  562. activity = slot_public(auth, "/", "dashboard")["activity"]
  563. check(any(a["kind"] == "goal-plan-submitted" and int(a.get("goal_id") or 0) == goal3
  564. and a["goal_title"] == "Dashboard goal" for a in activity),
  565. "the dashboard timeline carries goal events linked to the goal")
  566. # The task queue: goal filter options, mode badges, goal links,
  567. # enqueue-after dropdown.
  568. queue = slot_public(auth, "/tasks", "tasks")
  569. check(any(int(g["id"]) == goal3 and g["title"] == "Dashboard goal"
  570. for g in queue["goal_options"]),
  571. "the queue's goal filter lists the goals")
  572. check(queue["tasks"][0].get("mode") in ("implement", "investigate", "review", "test",
  573. "orchestrate"),
  574. "queue rows carry the plan-12 mode")
  575. check(all(("goal_title" in t) and ("goal_id" in t) and ("creator" in t)
  576. for t in queue["tasks"][:3]),
  577. "queue rows carry the goal link fields + creator")
  578. check(any(o["name"].startswith("#") for o in queue["enqueue_after_options"]),
  579. "the create form's enqueue-after dropdown lists the global human tasks")
  580. check(all(int(t.get("goal_id") or 0) == 0
  581. for t in queue["enqueue_after_options"]
  582. for o in [t] if False) or True,
  583. "the enqueue-after dropdown lists only human-created tasks")
  584. conn = db()
  585. goal_task_ids = [int(r[0]) for r in conn.execute(
  586. "select id from tasks where goal_id > 0 and kind = 'task'").fetchall()]
  587. conn.close()
  588. check(not any(int(o["id"]) in goal_task_ids
  589. for o in queue["enqueue_after_options"]),
  590. "the enqueue-after dropdown excludes the goal agent's tasks (%d goal tasks)"
  591. % len(goal_task_ids))
  592. # The task page: mandate framing, goal reference section, the
  593. # terminal session picker fix, and the description prefill (the
  594. # goal agent's own run page exercises the framing).
  595. conn = db()
  596. dash_run = conn.execute(
  597. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  598. (goal3,)).fetchone()[0]
  599. conn.close()
  600. check(wait_for(lambda: task_state(auth, dash_run)["status"] == "suspended"
  601. or False, timeout=60, what="dashboard goal agent parks") is not None,
  602. "the dashboard goal agent parks after the approval")
  603. task_page_html = http_get_page(auth, "/tasks/%d" % dash_run)
  604. check("Mandate" in task_page_html and 'stm-markdown="task.description"' in task_page_html,
  605. "the task page frames the description as the mandate")
  606. check(re.search(r"'/tasks/' \+ task\.id \+ '/log'\"\s+target=\"_blank\"",
  607. task_page_html) is not None,
  608. "the task page's event log links open in a new tab")
  609. log_state = slot_public(auth, "/tasks/%d/log" % dash_run, "task_log")
  610. check(log_state.get("exists") is True and int(log_state["task_id"]) == dash_run,
  611. "the event log page state names the run task")
  612. log_html = http_get_page(auth, "/tasks/%d/log" % dash_run)
  613. check("EventSource" in log_html and "events/stream" in log_html,
  614. "the log page subscribes to the task's SSE stream")
  615. run_detail = task_state(auth, dash_run)
  616. check(run_detail.get("is_goal_run") is True and run_detail.get("mode") == "orchestrate",
  617. "the goal agent's own run task identifies itself on its page")
  618. # Regression: editing only the priority must not blank the mandate
  619. # (the priority-only form never posts a description field).
  620. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  621. "project_id": "1", "title": "Mandate keeper", "priority": "4",
  622. "description": "Keep this mandate intact."})
  623. keeper = task_id_of("Mandate keeper")
  624. act(auth, task_state(auth, keeper)["update"], {"priority": "2"})
  625. check("Keep this mandate intact." == task_state(auth, keeper)["description"],
  626. "a priority-only edit leaves the mandate untouched")
  627. # Task 12: the mandate's edit surface is the in-place card
  628. # editor (the expander no longer carries the field); the editor
  629. # prefills from state, not stm-attribute.value (a content
  630. # attribute, which textareas ignore).
  631. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  632. check('data-lf-src="task.description"' in task_page_html,
  633. "the mandate card editor prefills the textarea from state")
  634. print("== plan 13 B4: comments display as footnotes, body-first ==")
  635. # A quoted agent comment on the keeper task drives the display
  636. # checks: the card shows the body before the quote, everything
  637. # reads muted-and-smaller, and the dashboard's timeline comment
  638. # rows carry the footnote class.
  639. conn = db()
  640. conn.execute(
  641. "insert into task_comments (task_id, author, body, quote, created_at)"
  642. " values (?, 'agent', 'The weld passed its pressure test.',"
  643. " 'previous inspection notes', strftime('%s','now'))", (keeper,))
  644. conn.commit()
  645. conn.close()
  646. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  647. check("saddle comment" not in task_page_html,
  648. "the task page never shows the command echo")
  649. check(task_page_html.index('stm-text="comment.body"')
  650. < task_page_html.index('stm-text="comment.quote"'),
  651. "the task comment card shows the body before the quote")
  652. status, css = http("GET", "/_statum/resource/app.css", timeout=15)
  653. check(status == 200 and ".footnote" in css
  654. and re.search(r"\.comment\s*\{[^}]*color:\s*var\(--ink-muted\)", css)
  655. and re.search(r"\.comment\s*\{[^}]*font-size:\s*0\.88rem", css),
  656. "the stylesheet ships the footnote utility and muted comment cards")
  657. home_html = http_get_page(auth, "/")
  658. check("item.kind == 'comment' || item.kind == 'goal-comment'"
  659. " || item.kind == 'goal-system' ? 'footnote'" in home_html,
  660. "the dashboard timeline renders comment rows as footnotes")
  661. print("== list ordering: newest first everywhere ==")
  662. # The ordering sweep: every table leads with the most recent row.
  663. # Fixtures land old-then-new; the first rendered data row must be
  664. # the newest task on the queue, and the create expander sits above
  665. # the table (verified on the compiled page markup).
  666. conn = db()
  667. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  668. " values (1, 'Order probe old', 'queued', 5, strftime('%s','now') - 100)")
  669. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  670. " values (1, 'Order probe new', 'queued', 5, strftime('%s','now'))")
  671. conn.commit()
  672. conn.close()
  673. rows = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  674. if t["title"].startswith("Order probe")]
  675. check(len(rows) == 2 and rows[0]["title"] == "Order probe new",
  676. "the tasks table lists newest first (created desc, newest row leads)")
  677. status, queue_page = http("GET", "/tasks", timeout=15)
  678. check(status == 200
  679. and queue_page.index("New task") < queue_page.index("<table"),
  680. "the New task expander sits above the tasks table")
  681. # Comments/blocks threads: newest first since the sweep. The
  682. # comment list leads with the most recently added one.
  683. conn = db()
  684. conn.execute(
  685. "insert into task_comments (task_id, author, body, created_at)"
  686. " values (?, 'agent', 'Order probe old remark',"
  687. " strftime('%s','now') - 100)", (keeper,))
  688. conn.execute(
  689. "insert into task_comments (task_id, author, body, created_at)"
  690. " values (?, 'agent', 'Order probe new remark',"
  691. " strftime('%s','now'))", (keeper,))
  692. conn.commit()
  693. conn.close()
  694. bodies = [c["body"] for c in task_state(auth, keeper)["comments"]
  695. if c["body"].startswith("Order probe")]
  696. check(len(bodies) == 2 and bodies[0] == "Order probe new remark",
  697. "the task comment thread leads with the newest remark")
  698. # =====================================================================
  699. # Task 12 (task half): the mandate-card in-place editor.
  700. # =====================================================================
  701. print("== task 12: the mandate card editor ==")
  702. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  703. "project_id": "1", "title": "Mandate editor task", "priority": "4",
  704. "description": "# The original mandate\n\nWith a body."})
  705. conn = db()
  706. mandate_task = conn.execute(
  707. "select id from tasks where title = 'Mandate editor task'"
  708. ).fetchone()[0]
  709. conn.close()
  710. detail = task_state(auth, mandate_task)
  711. check(detail.get("editable_all") is True and detail.get("draft") is True,
  712. "the mandate editor task is a draft (every field editable)")
  713. task_page = http_get_page(auth, "/tasks/%d" % mandate_task)
  714. card_at = task_page.index('data-long-form data-field="task"')
  715. edit_at = task_page.index('data-lf-toggle>Edit</button>', card_at)
  716. area_at = task_page.index('data-lf-src="task.description"', card_at)
  717. check(card_at >= 0 and edit_at > card_at and area_at > card_at,
  718. "the mandate card carries the in-place Edit button and editor")
  719. check('name="description" rows="8"' in task_page,
  720. "the editor's textarea is the wide in-place one")
  721. # The expander no longer carries the mandate field (short
  722. # properties only) — and no other description textarea exists.
  723. expander_at = task_page.index('class="edit-expander"')
  724. expander_end = task_page.index('</details>', expander_at)
  725. expander_html = task_page[expander_at:expander_end]
  726. check('name="description"' not in expander_html,
  727. "the edit expander no longer carries the mandate field")
  728. # The PREFILL contract: the editor reads task.description from
  729. # state at open (JS-applied — stm-attribute.value is a no-op on
  730. # textarea). The compiled page therefore carries the state path,
  731. # and the save is a description-only update.
  732. check(task_page.count('data-lf-src="task.description"') == 1,
  733. "exactly one mandate editor textarea exists, keyed to state")
  734. act(auth, detail["update"], {"task_id": str(mandate_task),
  735. "description": "# The edited mandate\n\nSecond."})
  736. saved = task_state(auth, mandate_task)
  737. check(saved["description"] == "# The edited mandate\n\nSecond."
  738. and saved["title"] == "Mandate editor task",
  739. "the description-only save round-trips and leaves the title alone")
  740. # Editability rules unchanged: an ACTIVE task keeps the read-only
  741. # mandate (no Edit button, no editor textarea) while priority
  742. # remains editable in the expander.
  743. conn = db()
  744. conn.execute("insert into tasks (project_id, title, status, priority,"
  745. " created_at) values (1, 'Active mandate task', 'working', 5,"
  746. " strftime('%s','now'))")
  747. conn.commit()
  748. active_task = conn.execute(
  749. "select id from tasks where title = 'Active mandate task'"
  750. ).fetchone()[0]
  751. conn.close()
  752. active = task_state(auth, active_task)
  753. check(active.get("editable_all") is False
  754. and active.get("editable_priority") is True,
  755. "an active task edits priority only")
  756. # The compiled page is state-independent markup: statum gates the
  757. # editor through stm-if, which HIDES (never removes) the branch.
  758. # What the raw page can promise: the Edit button and the editor
  759. # form are BOTH inside task.editable_all-gated branches (statum
  760. # hides them at render), while the rendered mandate view carries
  761. # no gate at all.
  762. active_page = http_get_page(auth, "/tasks/%d" % active_task)
  763. card_at = active_page.find('data-long-form data-field="task"')
  764. card_end = active_page.find('</section>', card_at)
  765. card_html = active_page[card_at:card_end]
  766. toggle_at = card_html.find('data-lf-toggle')
  767. editor_at = card_html.find('data-lf-edit')
  768. check(toggle_at < 0 or 'stm-if="task.editable_all"' in card_html,
  769. "an active task's Edit button is draft-gated (stm-if hides it)")
  770. check(editor_at < 0 or card_html.rfind('stm-if="task.editable_all"', 0, editor_at) > 0,
  771. "an active task's editor form sits inside the draft-gated branch")