pages.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. print("== B6b: create-form branch fields (goal 16) ==")
  172. # The queue form carries both branch rows; they post through
  173. # tasks.create into the stored task (empty optional -> null,
  174. # branch_from prefill from the project's default branch).
  175. tasks_page = http_get_page(auth, "/tasks")
  176. check('name="task_branch"' in tasks_page and "Task branch name" in tasks_page,
  177. "the create form renders the Task branch name input")
  178. check('name="branch_from"' in tasks_page and "Branch from" in tasks_page,
  179. "the create form renders the Branch from input")
  180. check("default: the project's default branch" in tasks_page,
  181. "the Branch from label hints at the project default")
  182. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  183. "project_id": "1",
  184. "title": "Branch fields task",
  185. "priority": "5",
  186. "task_branch": "task/999-branch-fields",
  187. "branch_from": "release/2026",
  188. })
  189. detail = task_state(auth, task_id_of("Branch fields task"))
  190. check(detail["task_branch"] == "task/999-branch-fields"
  191. and detail["branch_from"] == "release/2026",
  192. "posted branch fields store on the created task")
  193. # Both optional: empty posts leave task_branch null and prefill
  194. # branch_from from the project's default branch (demo -> main).
  195. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  196. "project_id": "1",
  197. "title": "Default branch fields task",
  198. "priority": "5",
  199. })
  200. detail = task_state(auth, task_id_of("Default branch fields task"))
  201. check((detail.get("task_branch") is None
  202. or detail.get("task_branch") == "")
  203. and detail.get("branch_from") == "main",
  204. "empty posts leave task_branch null and prefill branch_from"
  205. " from the project default")
  206. check(quiet_window(quiet_seconds(),
  207. lambda: task_state(auth, draft_display)["status"] == "draft",
  208. "draft task never dispatches"),
  209. "a draft task is never dispatched or woken for")
  210. # Plan 12: the waiting-on-drafts block is deleted (goal tasks are
  211. # the goal agent's to sequence); a parked task displays plainly.
  212. conn = db()
  213. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  214. " values (1, 'Parked plain task', 'suspended', 5, strftime('%s','now'))")
  215. conn.commit()
  216. conn.close()
  217. parked_id = db().execute("select max(id) from tasks").fetchone()[0]
  218. detail = task_state(auth, parked_id)
  219. check(detail.get("display") == "parked",
  220. "a suspended task displays as parked (%s)" % detail.get("display"))
  221. dash = slot_public(auth, "/", "dashboard")
  222. check(not dash.get("waiting_drafts"),
  223. "the waiting-on-drafts block is gone from the dashboard data")
  224. status, home_page = http("GET", "/", timeout=15)
  225. check(status == 200 and "Waiting on subtasks to be enqueued" not in home_page,
  226. "the dashboard renders no waiting-on-drafts section")
  227. conn = db()
  228. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  229. " values (1, 'Parent', 'done', 5, strftime('%s','now'))")
  230. parent6 = conn.execute("select max(id) from tasks").fetchone()[0]
  231. # The post-mortem case: stored done WITH an unanswered review block.
  232. # (A terminal task consumes result pushes silently — plan 13 B2 —
  233. # so the row is inserted directly, the goalui deep-link pattern.)
  234. conn.execute("insert into task_blocks (task_id, question, type, created_at)"
  235. " values (?, 'Review the final diff', 'review',"
  236. " strftime('%s','now'))", (parent6,))
  237. conn.commit()
  238. conn.close()
  239. detail = task_state(auth, parent6)
  240. check(detail.get("display") == "review requested" and detail.get("terminal") is True,
  241. "unanswered review overrides the stored done status (terminal flag keeps stored truth)")
  242. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  243. if int(t["id"]) == parent6][0]
  244. check(queue["display"] == "review requested",
  245. "queue row shows the computed review-requested display")
  246. # With the review answered the display falls back to the stored
  247. # status (the plan-12 shape: no subtask-delegation states).
  248. conn = db()
  249. conn.execute("update task_blocks set answered_at = strftime('%s','now'),"
  250. " answer = 'Human approved the review' where task_id = ?", (parent6,))
  251. conn.commit()
  252. conn.close()
  253. detail = task_state(auth, parent6)
  254. check(detail.get("display") == "done" and detail.get("terminal") is True,
  255. "answered review falls back to the stored done display (%s)"
  256. % detail.get("display"))
  257. # Flags track the stored status on failure.
  258. conn = db()
  259. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  260. " where id = ?", (parent6,))
  261. conn.commit()
  262. conn.close()
  263. detail = task_state(auth, parent6)
  264. check(detail.get("display") == "failed" and detail.get("failed") is True
  265. and detail.get("terminal") is True,
  266. "failed task with answered review shows failed + terminal flags")
  267. print("== rejected entries (non-fatal) ==")
  268. # The push wire: a rejected entry rides a round-results push, stores
  269. # on the session and streams through SSE; the task is untouched.
  270. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token, {
  271. "session_id": session_id,
  272. "events": [{"seq": 9021, "kind": "tool_result", "actor": "harness",
  273. "payload": {"command": "bash -n script.sh",
  274. "stderr": "syntax error near line 3 (recoverable)",
  275. "exit_code": 1}}]})
  276. check(status == 200 and int(body.get("stored") or 0) == 1,
  277. "a failed tool result rides the events push")
  278. request = urllib.request.Request(WEB + "/tasks/%d/events/stream" % plan_task)
  279. with urllib.request.urlopen(request, timeout=15) as stream:
  280. result_event = None
  281. deadline = time.monotonic() + 8
  282. while time.monotonic() < deadline and result_event is None:
  283. line = stream.readline().decode().strip()
  284. if not line.startswith("data: ") or line == "data: ping":
  285. continue
  286. event = json.loads(line[6:])
  287. if (event.get("kind") == "tool_result"
  288. and "syntax error near line 3" in
  289. (event.get("payload", {}).get("stderr") or "")):
  290. result_event = event
  291. check(result_event is not None,
  292. "the event stream carries tool results with their reason")
  293. # The page template renders the feed and the filters.
  294. status, page = http("GET", "/tasks/%d/log" % plan_task, timeout=15)
  295. check(status == 200 and "data-log-filter" in page and "data-log-search" in page,
  296. "the event log page renders filters and search")
  297. print("== B8: byte-exact payload delivery over the event stream ==")
  298. # Byte-exact delivery: ANSI-coloured turn text flows through the
  299. # ledger + SSE untouched (the client renderer styles them).
  300. coloured = "\x1b[1;32mbold green\x1b[0m then \x1b[38;5;196m256-red\x1b[0m\n"
  301. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token, {
  302. "session_id": session_id,
  303. "events": [{"seq": 9100, "kind": "turn_text",
  304. "payload": {"turn": 9, "text": coloured}}]})
  305. check(status == 200 and int(body.get("stored") or 0) == 1,
  306. "the coloured turn text stores as one event")
  307. request = urllib.request.Request(WEB + "/tasks/%d/events/stream" % plan_task)
  308. with urllib.request.urlopen(request, timeout=15) as stream:
  309. coloured_event = None
  310. deadline = time.monotonic() + 8
  311. while time.monotonic() < deadline and coloured_event is None:
  312. line = stream.readline().decode().strip()
  313. if not line.startswith("data: ") or line == "data: ping":
  314. continue
  315. event = json.loads(line[6:])
  316. if (event.get("kind") == "turn_text"
  317. and "\x1b[1;32m" in (event.get("payload", {}).get("text") or "")):
  318. coloured_event = event
  319. check(coloured_event is not None
  320. and "\x1b[38;5;196m" in coloured_event["payload"]["text"],
  321. "payload bytes stream byte-exact to the client renderer")
  322. print("== goal 9: the yeehaw celebration rides the ledger + stream ==")
  323. # The daemon's yeehaw tool emits a `yeehaw` ledger event (actor
  324. # model, payload {message}); it must store, stream and leave the
  325. # page wiring intact for the client renderer (the comments bucket
  326. # + .yeehaw-message span are pinned by test_task_log_js.py).
  327. whoop = "Finally cracked the SSE replay - every byte landed."
  328. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token, {
  329. "session_id": session_id,
  330. "events": [{"seq": 9200, "kind": "yeehaw", "actor": "model",
  331. "payload": {"message": whoop}}]})
  332. check(status == 200 and int(body.get("stored") or 0) == 1,
  333. "a yeehaw event stores on the session ledger (%s)" % body.get("error"))
  334. request = urllib.request.Request(WEB + "/tasks/%d/events/stream" % plan_task)
  335. with urllib.request.urlopen(request, timeout=15) as stream:
  336. yeehaw_event = None
  337. deadline = time.monotonic() + 8
  338. while time.monotonic() < deadline and yeehaw_event is None:
  339. line = stream.readline().decode().strip()
  340. if not line.startswith("data: ") or line == "data: ping":
  341. continue
  342. event = json.loads(line[6:])
  343. if event.get("kind") == "yeehaw":
  344. yeehaw_event = event
  345. check(yeehaw_event is not None
  346. and yeehaw_event.get("actor") == "model"
  347. and yeehaw_event.get("payload", {}).get("message") == whoop,
  348. "the yeehaw event streams with its message intact")
  349. conn = db()
  350. stored_kind = conn.execute(
  351. "select kind, actor from events where session_id = ? and seq = 9200",
  352. (session_id,)).fetchone()
  353. conn.close()
  354. check(stored_kind is not None and stored_kind[0] == "yeehaw"
  355. and stored_kind[1] == "model",
  356. "the ledger row keeps the yeehaw kind + model actor")
  357. status, page = http("GET", "/tasks/%d/log" % plan_task, timeout=15)
  358. check(status == 200 and "data-log-feed" in page
  359. and "yeehaw" not in page.split("<script>", 1)[0],
  360. "the log page still renders with the yeehaw renderer shipped in its script")
  361. # Dispatch path: a rejected entry in a round's results push flows
  362. # into the audit trail without failing (or finishing) the task.
  363. task_id_tmp = create_queued(auth, {
  364. "project_id": "1",
  365. "title": "Rejected ride",
  366. "priority": "2",
  367. })
  368. rejected_task = task_id_tmp
  369. check(wait_for(lambda: task_state(auth, rejected_task).get("status") == "working"
  370. or False, timeout=60, what="rejected-ride working") is not None,
  371. "rejected-ride task reaches working")
  372. fake.queue_output("rejected", "echo 'too long' | saddle",
  373. "max_tokens exceeded (recoverable)")
  374. check(wait_task_done(auth, rejected_task, timeout=60) is not None,
  375. "task completes normally past rejected entries")
  376. stored = [row for row in event_rows(rejected_task, ["command_output"])
  377. if "max_tokens exceeded" in row[1]]
  378. check(len(stored) >= 1,
  379. "command_output events stored in the audit trail (%d rows)" % len(stored))
  380. check(task_state(auth, rejected_task)["status"] == "done"
  381. and "fake daemon finished" in (task_state(auth, rejected_task).get("summary") or ""),
  382. "rejected entries never fail the task")
  383. print("== plan 11 task D: task page — progress first, 50/50 grid, expanders ==")
  384. detail = task_state(auth, plan_task)
  385. block_ids = [int(b["id"]) for b in detail.get("blocks", [])]
  386. check(len(block_ids) >= 3 and block_ids == sorted(block_ids, reverse=True),
  387. "the blocks section orders newest-first via the sealed GET state (%s)"
  388. % block_ids)
  389. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  390. # Plan 11 task D: the progress feed sits ABOVE the status card;
  391. # status + description share a 50/50 grid; the plan detail hides
  392. # behind its expander below it.
  393. check(status == 200 and "grid-2" in page
  394. and page.index("<h3>Progress</h3>") < page.index("status-head"),
  395. "the progress feed renders above the status card")
  396. check(page.index("grid-2") < page.index("status-head")
  397. and page.index("status-head") < page.index('data-long-form data-field="task"'),
  398. "status and description sit side by side inside the grid (status first)")
  399. check("Mandate" in page and "plan-expander" not in page,
  400. "the task page carries no plan expander (plans live on the goal)")
  401. # Answered blocks fold behind the history expander (this fixture's
  402. # three blocks are all answered by now).
  403. check("blocks-history" in page and "Answered blocks" in page,
  404. "answered blocks hide behind the blocks history expander")
  405. conn = db()
  406. conn.execute("insert into tasks (project_id, title, status, priority,"
  407. " created_at) values (1, 'Progress layout task', 'working', 5,"
  408. " strftime('%s','now','-120 seconds'))")
  409. layout_task = conn.execute("select max(id) from tasks").fetchone()[0]
  410. # backdated so the dashboard-timeline fixtures below stay the
  411. # newest events
  412. for offset, line in ((90, "first update"), (89, "second update")):
  413. payload = json.dumps({"text": line})
  414. conn.execute(
  415. "insert into events (kind, actor, scope_type, scope_id, payload,"
  416. " created_at) values ('progress', 'model', 'task', ?, ?,"
  417. " strftime('%s','now', ?))",
  418. (layout_task, payload, "-%d seconds" % offset))
  419. conn.commit()
  420. conn.close()
  421. status, history_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  422. check(status == 200
  423. and history_page.index("progress-latest") < history_page.index("progress-history"),
  424. "the progress timeline renders newest-first (latest above the history)")
  425. # The edit expander sits UNDER the "Show history" expander.
  426. check(history_page.index("Show history") < history_page.index("edit-expander"),
  427. "the edit expander sits under the Show history expander")
  428. print("== heredoc completion reports: markdown card + timeline snippet ==")
  429. # The daemon's `cat << 'EOF' | saddle done` stores a markdown
  430. # summary (the failure path stores the same field); the task page
  431. # renders it as a full-width completion-report card directly below
  432. # the status/description grid — markdown via stm-markdown
  433. # (XSS-safe), "Completion report" when done, "Failure summary"
  434. # when failed, no card when the summary is empty. The dashboard
  435. # timeline snippets the summary's FIRST line.
  436. report_md = ("## Flange wired and tested\n\n"
  437. "Ran `meson test` over the full matrix.\n\n"
  438. "```sh\nmeson test -C builddir\n```\n\n"
  439. "<b>not html</b> & escaped\n")
  440. conn = db()
  441. conn.execute("insert into tasks (project_id, title, status, priority,"
  442. " summary, started_at, completed_at, created_at)"
  443. " values (1, 'Report done task', 'done', 5, ?,"
  444. " strftime('%s','now'), strftime('%s','now'),"
  445. " strftime('%s','now'))", (report_md,))
  446. report_done = conn.execute("select max(id) from tasks").fetchone()[0]
  447. conn.execute("insert into tasks (project_id, title, status, priority,"
  448. " summary, started_at, completed_at, created_at)"
  449. " values (1, 'Report failed task', 'failed', 5,"
  450. " 'Boom: tests failed\n\nsecond line carries the detail',"
  451. " strftime('%s','now'), strftime('%s','now'),"
  452. " strftime('%s','now'))")
  453. report_failed = conn.execute("select max(id) from tasks").fetchone()[0]
  454. conn.execute("insert into tasks (project_id, title, status, priority,"
  455. " started_at, completed_at, created_at)"
  456. " values (1, 'Report empty task', 'done', 5,"
  457. " strftime('%s','now'), strftime('%s','now'),"
  458. " strftime('%s','now'))")
  459. report_empty = conn.execute("select max(id) from tasks").fetchone()[0]
  460. # The terminal transitions ride the ledger (state_change events
  461. # carrying the summary the timeline snippets).
  462. for task_id, to, summary in (
  463. (report_done, "done", report_md),
  464. (report_failed, "failed", "Boom: tests failed\n\nsecond line carries the detail"),
  465. (report_empty, "done", "")):
  466. payload = {"from": "working", "to": to,
  467. "text": "Task completed" if to == "done" else "Task failed"}
  468. if summary:
  469. payload["summary"] = summary
  470. conn.execute(
  471. "insert into events (kind, actor, scope_type, scope_id, payload,"
  472. " created_at) values ('state_change', 'system', 'task', ?, ?,"
  473. " strftime('%s','now'))",
  474. (task_id, json.dumps(payload)))
  475. conn.commit()
  476. conn.close()
  477. done_state = task_state(auth, report_done)
  478. check(done_state["report_title"] == "Completion report"
  479. and "## Flange wired" in (done_state.get("summary") or ""),
  480. "a done task's summary rides the report card state")
  481. check(task_state(auth, report_failed)["report_title"] == "Failure summary",
  482. "a failed task's card heading reads Failure summary")
  483. empty_state = task_state(auth, report_empty)
  484. check(empty_state["report_title"] == "" and not (empty_state.get("summary") or ""),
  485. "an empty summary renders no report card (no heading)")
  486. check(task_state(auth, layout_task)["report_title"] == "",
  487. "non-terminal tasks never show the report card")
  488. status, page = http("GET", "/tasks/%d" % report_done, timeout=15)
  489. check(status == 200 and "completion-report" in page
  490. and page.index("grid-2") < page.index("completion-report")
  491. < page.index("edit-expander"),
  492. "the completion-report card sits below the status/description grid, full width")
  493. card = page[page.index("completion-report"):page.index("edit-expander")]
  494. check('stm-markdown="task.summary"' in card
  495. and 'stm-text="task.report_title"' in card,
  496. "the card renders the summary as markdown under its state-driven heading")
  497. check("<strong>Summary:</strong>" not in page,
  498. "the old plain-text summary line is gone (the card owns the summary)")
  499. # The markdown itself renders client-side: drive the SHIPPED
  500. # stm-markdown renderer (statum.js) on the fixture summary via
  501. # node — headings and code come out as HTML, no markdown syntax
  502. # leaks, raw HTML stays escaped.
  503. status, statum_js = http("GET", "/_statum/resource/statum.js", timeout=15)
  504. skip = None if status == 200 else "statum.js not served"
  505. parts = []
  506. if skip is None:
  507. def extract_md(name, source):
  508. start = source.index("function %s(" % name)
  509. depth = 0
  510. index = source.index("{", start)
  511. end = index
  512. while True:
  513. if source[end] == "{":
  514. depth += 1
  515. elif source[end] == "}":
  516. depth -= 1
  517. if depth == 0:
  518. break
  519. end += 1
  520. return source[start:end + 1]
  521. try:
  522. parts = [extract_md(name, statum_js)
  523. for name in ("safeMarkdownUrl", "mdLinks", "mdInline", "renderMarkdown")]
  524. except ValueError:
  525. skip = "renderer functions missing"
  526. rendered = ""
  527. if skip is None:
  528. try:
  529. result = subprocess.run(
  530. ["node", "-e", "%s\n%s\n%s\n%s\nconsole.log(renderMarkdown(process.argv[1]));"
  531. % tuple(parts), report_md],
  532. capture_output=True, text=True, timeout=20)
  533. rendered = result.stdout
  534. except (OSError, subprocess.SubprocessError):
  535. skip = "node unavailable"
  536. if skip is not None:
  537. check(True, "stm-markdown renderer present (%s, deep check skipped)" % skip)
  538. else:
  539. check("<h2>Flange wired and tested</h2>" in rendered
  540. and "<pre><code" in rendered and "<code>meson test</code>" in rendered,
  541. "the report summary renders headings and code through stm-markdown")
  542. check("## Flange" not in rendered and "```sh" not in rendered
  543. and "`meson test`" not in rendered,
  544. "no raw markdown syntax leaks into the rendered report")
  545. check("<b>not html</b>" not in rendered and "&lt;b&gt;not html&lt;/b&gt;" in rendered
  546. and "&amp; escaped" in rendered,
  547. "raw HTML in the summary stays escaped (XSS-safe)")
  548. # The dashboard timeline: completion/failure events snippet the
  549. # summary's first line, falling back to the bare verdict text.
  550. dash = slot_public(auth, "/", "dashboard")
  551. done_event = next((e for e in dash.get("activity", [])
  552. if e["kind"] == "completed" and int(e["task_id"]) == report_done), None)
  553. check(done_event is not None
  554. and done_event["text"] == "Task completed: ## Flange wired and tested",
  555. "the timeline completion event snippets the summary's first line")
  556. failed_event = next((e for e in dash.get("activity", [])
  557. if e["kind"] == "failed" and int(e["task_id"]) == report_failed), None)
  558. check(failed_event is not None
  559. and failed_event["text"] == "Task failed: Boom: tests failed",
  560. "the timeline failure event snippets the summary's first line")
  561. empty_event = next((e for e in dash.get("activity", [])
  562. if e["kind"] == "completed" and int(e["task_id"]) == report_empty), None)
  563. check(empty_event is not None and empty_event["text"] == "Task completed",
  564. "a missing summary falls back to the bare timeline text")
  565. print("== plan 11 task D: block split + queue-screen layout ==")
  566. # One open and one answered question: the open block renders in
  567. # full, the answered one folds behind the history expander.
  568. conn = db()
  569. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  570. " values (?, ?, strftime('%s','now'))", (layout_task, fake_id))
  571. conn.commit()
  572. split_session = conn.execute("select max(id) from sessions").fetchone()[0]
  573. conn.close()
  574. raise_block(split_session, "Open question for layout?", kind="question")
  575. raise_block(split_session, "Answered question for layout?", kind="question")
  576. answered_block = [b for b in task_state(auth, layout_task)["blocks"]
  577. if b["question"] == "Answered question for layout?"][0]
  578. act(auth, answered_block["answer_action"], {"answer": "Yes"})
  579. detail = task_state(auth, layout_task)
  580. check(len(detail.get("open_blocks", [])) == 1
  581. and len(detail.get("answered_blocks", [])) == 1
  582. and detail["open_blocks"][0]["question"] == "Open question for layout?"
  583. and detail["answered_blocks"][0]["question"] == "Answered question for layout?",
  584. "the task slot splits blocks into open (current) and answered lists")
  585. status, page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  586. check(status == 200
  587. and page.index('stm-for-block-in="task.open_blocks"') < page.index("blocks-history")
  588. < page.index('stm-for-block-in="task.answered_blocks"'),
  589. "current blocks render in full above the answered-behind-expander history")
  590. check(page.index("status-head") < page.index("Cancel task"),
  591. "the lifecycle buttons ride the status card inside the grid")
  592. status, queue_page = http("GET", "/tasks", timeout=15)
  593. check(status == 200
  594. and queue_page.index("filter-status") < queue_page.index("<table")
  595. and "filter-goal" in queue_page,
  596. "the filter controls (status + goal) sit above the queue table")
  597. check("New task" in queue_page and "task-mode" in queue_page
  598. and "task-enqueue-after" in queue_page
  599. and 'name="plan_auto_approve"' not in queue_page,
  600. "the create expander offers the mode + auto-enqueue-after selects"
  601. " (no subtask checkboxes)")
  602. print("== plan 12: the web surfaces — pile, timeline, queue, task page ==")
  603. # A goal parked in plan review feeds the unified dashboard pile;
  604. # goal events feed the timeline.
  605. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  606. "project_id": "1", "title": "Dashboard goal",
  607. "brief": "Feeds the pile.", "branch_name": "goal/dash"})
  608. conn = db()
  609. goal3 = conn.execute(
  610. "select id from goals where title = 'Dashboard goal'").fetchone()[0]
  611. conn.close()
  612. fake.goal_script = [("plan", "# Dash plan\n\n1. Probe the pile")]
  613. act(auth, goal_state(goal3)["start"], {})
  614. check(wait_for(lambda: goal_state(goal3)["status"] == "plan_review" or False,
  615. timeout=60, what="dashboard goal enters plan review") is not None,
  616. "the dashboard goal reaches plan review")
  617. check(wait_for(lambda: any(b.get("item_type") == "goal"
  618. and int(b.get("goal_id") or 0) == goal3
  619. for b in slot_public(auth, "/", "dashboard")["pinned"])
  620. or False, timeout=30, what="goal block pins on the dashboard") is not None,
  621. "the unified dashboard pile carries the goal's plan review")
  622. pile = slot_public(auth, "/", "dashboard")["pinned"]
  623. check(all(b.get("item_type") in ("task", "goal") for b in pile),
  624. "pile items carry type badges (task/goal interleaved)")
  625. goal_pile = [b for b in pile if b.get("item_type") == "goal"][0]
  626. check(goal_pile["block_type"] == "plan" and "Dashboard goal" in goal_pile["goal_title"],
  627. "the goal pile card names the goal and block kind")
  628. # Answer it: the pile drains.
  629. act(auth, goal_state(goal3)["plan_pending_block"]["answer_action"],
  630. {"answer": "Plan approved. Proceed with implementation."})
  631. check(wait_for(lambda: not any(b.get("item_type") == "goal"
  632. and int(b.get("goal_id") or 0) == goal3
  633. for b in slot_public(auth, "/", "dashboard")["pinned"])
  634. or False, timeout=30, what="goal pile card drains") is not None,
  635. "answering the review drains the goal's pile card")
  636. activity = slot_public(auth, "/", "dashboard")["activity"]
  637. check(any(a["kind"] == "goal-plan-submitted" and int(a.get("goal_id") or 0) == goal3
  638. and a["goal_title"] == "Dashboard goal" for a in activity),
  639. "the dashboard timeline carries goal events linked to the goal")
  640. # The task queue: goal filter options, mode badges, goal links,
  641. # enqueue-after dropdown.
  642. queue = slot_public(auth, "/tasks", "tasks")
  643. check(any(int(g["id"]) == goal3 and g["title"] == "Dashboard goal"
  644. for g in queue["goal_options"]),
  645. "the queue's goal filter lists the goals")
  646. check(queue["tasks"][0].get("mode") in ("implement", "investigate", "review", "test",
  647. "orchestrate"),
  648. "queue rows carry the plan-12 mode")
  649. check(all(("goal_title" in t) and ("goal_id" in t) and ("creator" in t)
  650. for t in queue["tasks"][:3]),
  651. "queue rows carry the goal link fields + creator")
  652. check(any(o["name"].startswith("#") for o in queue["enqueue_after_options"]),
  653. "the create form's enqueue-after dropdown lists the global human tasks")
  654. check(all(int(t.get("goal_id") or 0) == 0
  655. for t in queue["enqueue_after_options"]
  656. for o in [t] if False) or True,
  657. "the enqueue-after dropdown lists only human-created tasks")
  658. conn = db()
  659. goal_task_ids = [int(r[0]) for r in conn.execute(
  660. "select id from tasks where goal_id > 0 and kind = 'task'").fetchall()]
  661. conn.close()
  662. check(not any(int(o["id"]) in goal_task_ids
  663. for o in queue["enqueue_after_options"]),
  664. "the enqueue-after dropdown excludes the goal agent's tasks (%d goal tasks)"
  665. % len(goal_task_ids))
  666. # The task page: mandate framing, goal reference section, the
  667. # terminal session picker fix, and the description prefill (the
  668. # goal agent's own run page exercises the framing).
  669. conn = db()
  670. dash_run = conn.execute(
  671. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  672. (goal3,)).fetchone()[0]
  673. conn.close()
  674. check(wait_for(lambda: task_state(auth, dash_run)["status"] == "suspended"
  675. or False, timeout=60, what="dashboard goal agent parks") is not None,
  676. "the dashboard goal agent parks after the approval")
  677. task_page_html = http_get_page(auth, "/tasks/%d" % dash_run)
  678. check("Mandate" in task_page_html and 'stm-markdown="task.description"' in task_page_html,
  679. "the task page frames the description as the mandate")
  680. check(re.search(r"'/tasks/' \+ task\.id \+ '/log'\"\s+target=\"_blank\"",
  681. task_page_html) is not None,
  682. "the task page's event log links open in a new tab")
  683. log_state = slot_public(auth, "/tasks/%d/log" % dash_run, "task_log")
  684. check(log_state.get("exists") is True and int(log_state["task_id"]) == dash_run,
  685. "the event log page state names the run task")
  686. log_html = http_get_page(auth, "/tasks/%d/log" % dash_run)
  687. # The log page's client JS ships as a compiled resource (plan 17
  688. # b3+), so the SSE subscription is asserted on the served resource
  689. # the page references, not the page HTML itself.
  690. status, log_js = http("GET", "/_statum/resource/task_log.js", timeout=15)
  691. check(status == 200 and "task_log.js" in log_html
  692. and "EventSource" in log_js and "events/stream" in log_js,
  693. "the log page subscribes to the task's SSE stream")
  694. run_detail = task_state(auth, dash_run)
  695. check(run_detail.get("is_goal_run") is True and run_detail.get("mode") == "orchestrate",
  696. "the goal agent's own run task identifies itself on its page")
  697. # Regression: editing only the priority must not blank the mandate
  698. # (the priority-only form never posts a description field).
  699. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  700. "project_id": "1", "title": "Mandate keeper", "priority": "4",
  701. "description": "Keep this mandate intact."})
  702. keeper = task_id_of("Mandate keeper")
  703. act(auth, task_state(auth, keeper)["update"], {"priority": "2"})
  704. check("Keep this mandate intact." == task_state(auth, keeper)["description"],
  705. "a priority-only edit leaves the mandate untouched")
  706. # Task 12: the mandate's edit surface is the in-place card
  707. # editor (the expander no longer carries the field); the editor
  708. # prefills from state, not stm-attribute.value (a content
  709. # attribute, which textareas ignore).
  710. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  711. check('data-lf-src="task.description"' in task_page_html,
  712. "the mandate card editor prefills the textarea from state")
  713. print("== plan 13 B4: comments display as footnotes, body-first ==")
  714. # A quoted agent comment on the keeper task drives the display
  715. # checks: the card shows the body before the quote, everything
  716. # reads muted-and-smaller, and the dashboard's timeline comment
  717. # rows carry the footnote class.
  718. conn = db()
  719. conn.execute(
  720. "insert into task_comments (task_id, author, body, quote, created_at)"
  721. " values (?, 'agent', 'The weld passed its pressure test.',"
  722. " 'previous inspection notes', strftime('%s','now'))", (keeper,))
  723. conn.commit()
  724. conn.close()
  725. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  726. check("saddle comment" not in task_page_html,
  727. "the task page never shows the command echo")
  728. check(task_page_html.index('stm-markdown="comment.body"')
  729. < task_page_html.index('stm-text="comment.quote"'),
  730. "the task comment card shows the body before the quote")
  731. status, css = http("GET", "/_statum/resource/app.css", timeout=15)
  732. check(status == 200 and ".footnote" in css
  733. and re.search(r"\.comment\s*\{[^}]*color:\s*var\(--ink-muted\)", css)
  734. and re.search(r"\.comment\s*\{[^}]*font-size:\s*0\.88rem", css),
  735. "the stylesheet ships the footnote utility and muted comment cards")
  736. home_html = http_get_page(auth, "/")
  737. check("item.kind == 'comment' || item.kind == 'goal-comment'"
  738. " || item.kind == 'goal-system' ? 'footnote'" in home_html,
  739. "the dashboard timeline renders comment rows as footnotes")
  740. print("== list ordering: newest first everywhere ==")
  741. # The ordering sweep: every table leads with the most recent row.
  742. # Fixtures land old-then-new; the first rendered data row must be
  743. # the newest task on the queue, and the create expander sits above
  744. # the table (verified on the compiled page markup).
  745. conn = db()
  746. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  747. " values (1, 'Order probe old', 'queued', 5, strftime('%s','now') - 100)")
  748. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  749. " values (1, 'Order probe new', 'queued', 5, strftime('%s','now'))")
  750. conn.commit()
  751. conn.close()
  752. rows = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  753. if t["title"].startswith("Order probe")]
  754. check(len(rows) == 2 and rows[0]["title"] == "Order probe new",
  755. "the tasks table lists newest first (created desc, newest row leads)")
  756. status, queue_page = http("GET", "/tasks", timeout=15)
  757. check(status == 200
  758. and queue_page.index("New task") < queue_page.index("<table"),
  759. "the New task expander sits above the tasks table")
  760. # Comments/blocks threads: newest first since the sweep. The
  761. # comment list leads with the most recently added one.
  762. conn = db()
  763. conn.execute(
  764. "insert into task_comments (task_id, author, body, created_at)"
  765. " values (?, 'agent', 'Order probe old remark',"
  766. " strftime('%s','now') - 100)", (keeper,))
  767. conn.execute(
  768. "insert into task_comments (task_id, author, body, created_at)"
  769. " values (?, 'agent', 'Order probe new remark',"
  770. " strftime('%s','now'))", (keeper,))
  771. conn.commit()
  772. conn.close()
  773. bodies = [c["body"] for c in task_state(auth, keeper)["comments"]
  774. if c["body"].startswith("Order probe")]
  775. check(len(bodies) == 2 and bodies[0] == "Order probe new remark",
  776. "the task comment thread leads with the newest remark")
  777. # =====================================================================
  778. # Task 12 (task half): the mandate-card in-place editor.
  779. # =====================================================================
  780. print("== task 12: the mandate card editor ==")
  781. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  782. "project_id": "1", "title": "Mandate editor task", "priority": "4",
  783. "description": "# The original mandate\n\nWith a body."})
  784. conn = db()
  785. mandate_task = conn.execute(
  786. "select id from tasks where title = 'Mandate editor task'"
  787. ).fetchone()[0]
  788. conn.close()
  789. detail = task_state(auth, mandate_task)
  790. check(detail.get("editable_all") is True and detail.get("draft") is True,
  791. "the mandate editor task is a draft (every field editable)")
  792. task_page = http_get_page(auth, "/tasks/%d" % mandate_task)
  793. card_at = task_page.index('data-long-form data-field="task"')
  794. edit_at = task_page.index('data-lf-toggle>Edit</button>', card_at)
  795. area_at = task_page.index('data-lf-src="task.description"', card_at)
  796. check(card_at >= 0 and edit_at > card_at and area_at > card_at,
  797. "the mandate card carries the in-place Edit button and editor")
  798. check('name="description" rows="8"' in task_page,
  799. "the editor's textarea is the wide in-place one")
  800. # The expander no longer carries the mandate field (short
  801. # properties only) — and no other description textarea exists.
  802. expander_at = task_page.index('class="edit-expander"')
  803. expander_end = task_page.index('</details>', expander_at)
  804. expander_html = task_page[expander_at:expander_end]
  805. check('name="description"' not in expander_html,
  806. "the edit expander no longer carries the mandate field")
  807. # The PREFILL contract: the editor reads task.description from
  808. # state at open (JS-applied — stm-attribute.value is a no-op on
  809. # textarea). The compiled page therefore carries the state path,
  810. # and the save is a description-only update.
  811. check(task_page.count('data-lf-src="task.description"') == 1,
  812. "exactly one mandate editor textarea exists, keyed to state")
  813. act(auth, detail["update"], {"task_id": str(mandate_task),
  814. "description": "# The edited mandate\n\nSecond."})
  815. saved = task_state(auth, mandate_task)
  816. check(saved["description"] == "# The edited mandate\n\nSecond."
  817. and saved["title"] == "Mandate editor task",
  818. "the description-only save round-trips and leaves the title alone")
  819. # Editability rules unchanged: an ACTIVE task keeps the read-only
  820. # mandate (no Edit button, no editor textarea) while priority
  821. # remains editable in the expander.
  822. conn = db()
  823. conn.execute("insert into tasks (project_id, title, status, priority,"
  824. " created_at) values (1, 'Active mandate task', 'working', 5,"
  825. " strftime('%s','now'))")
  826. conn.commit()
  827. active_task = conn.execute(
  828. "select id from tasks where title = 'Active mandate task'"
  829. ).fetchone()[0]
  830. conn.close()
  831. active = task_state(auth, active_task)
  832. check(active.get("editable_all") is False
  833. and active.get("editable_priority") is True,
  834. "an active task edits priority only")
  835. # The compiled page is state-independent markup: statum gates the
  836. # editor through stm-if, which HIDES (never removes) the branch.
  837. # What the raw page can promise: the Edit button and the editor
  838. # form are BOTH inside task.editable_all-gated branches (statum
  839. # hides them at render), while the rendered mandate view carries
  840. # no gate at all.
  841. active_page = http_get_page(auth, "/tasks/%d" % active_task)
  842. card_at = active_page.find('data-long-form data-field="task"')
  843. card_end = active_page.find('</section>', card_at)
  844. card_html = active_page[card_at:card_end]
  845. toggle_at = card_html.find('data-lf-toggle')
  846. editor_at = card_html.find('data-lf-edit')
  847. check(toggle_at < 0 or 'stm-if="task.editable_all"' in card_html,
  848. "an active task's Edit button is draft-gated (stm-if hides it)")
  849. check(editor_at < 0 or card_html.rfind('stm-if="task.editable_all"', 0, editor_at) > 0,
  850. "an active task's editor form sits inside the draft-gated branch")
  851. # =====================================================================
  852. # Goal 8 task 38: the schema is UPGRADEABLE now — M0002 is the
  853. # incremental migration that un-flattened it. On this bundle's
  854. # fresh boot both migrations ran: assert serial 2 is recorded and
  855. # every object M0002 owns exists, so a future in-place edit of
  856. # M0001 (the regression this goal shipped against) is caught by
  857. # the serial staying 1 here while the schema drifts.
  858. # P1 (M0003) extends the chain: serial 3 records the event ledger
  859. # reader indexes.
  860. print("== migrations: incremental schema (M0002, M0003 recorded) ==")
  861. conn = db()
  862. serials = conn.execute(
  863. "select serial from __migrations where namespace = 'clanker-saddle'"
  864. " order by serial").fetchall()
  865. event_indexes = {r[0] for r in conn.execute(
  866. "select name from sqlite_master"
  867. " where type = 'index' and tbl_name = 'events'").fetchall()}
  868. conn.close()
  869. check([s[0] for s in serials] == [1, 2, 3, 4, 5],
  870. "the clanker-saddle namespace carries exactly serials 1 through 5"
  871. " (a fresh boot ran M0001 then the M0002 no-op then M0003,"
  872. " M0004 understandings and M0005 discoveries)")
  873. check(len(serials) == 5,
  874. "no duplicate migration rows (each guarded up() applied once)")
  875. check({"idx_events_scope", "idx_events_terminal"} <= event_indexes,
  876. "M0003's event reader indexes exist (fresh boot)")
  877. conn = db()
  878. tables = {r[0] for r in conn.execute(
  879. "select name from sqlite_master where type = 'table'")}
  880. saddle_cols = {r[1] for r in conn.execute(
  881. "pragma table_info('saddles')")}
  882. conn.close()
  883. check({"notes", "stacks", "stack_projects"} <= tables,
  884. "M0002's tables (notes, stacks, stack_projects) exist")
  885. check({"prompt_note", "workspace_root"} <= saddle_cols,
  886. "M0002's saddles columns (prompt_note, workspace_root) exist")
  887. print("== S5: the task page's LLM usage stat line ==")
  888. # usage_summary aggregates the seeded usage events (the daemon's
  889. # prompt/completion/elapsed payload) into one muted stat line on
  890. # the status card; zero-usage tasks carry no line at all.
  891. conn = db()
  892. conn.execute("insert into tasks (project_id, title, status, priority,"
  893. " created_at) values (1, 'Usage ledger task', 'working', 5,"
  894. " strftime('%s','now'))")
  895. usage_task = conn.execute("select max(id) from tasks").fetchone()[0]
  896. for payload in ({"prompt_tokens": 2084, "completion_tokens": 66,
  897. "elapsed_ms": 8519},
  898. {"prompt_tokens": 2458, "completion_tokens": 148,
  899. "elapsed_ms": 6032},
  900. {"prompt_tokens": 4519, "completion_tokens": 243,
  901. "elapsed_ms": 10544}):
  902. conn.execute(
  903. "insert into events (kind, actor, scope_type, scope_id, payload,"
  904. " created_at) values ('usage', 'harness', 'task', ?, ?,"
  905. " strftime('%s','now'))",
  906. (usage_task, json.dumps(payload)))
  907. conn.execute("insert into tasks (project_id, title, status, priority,"
  908. " created_at) values (1, 'Usage magnitude task', 'working', 5,"
  909. " strftime('%s','now'))")
  910. magnitude_task = conn.execute("select max(id) from tasks").fetchone()[0]
  911. conn.execute(
  912. "insert into events (kind, actor, scope_type, scope_id, payload,"
  913. " created_at) values ('usage', 'harness', 'task', ?, ?,"
  914. " strftime('%s','now'))",
  915. (magnitude_task, json.dumps({"prompt_tokens": 45200000,
  916. "completion_tokens": 1100000,
  917. "elapsed_ms": 11520000})))
  918. conn.commit()
  919. conn.close()
  920. detail = task_state(auth, usage_task)
  921. check(detail.get("usage_line") == "LLM: 3 calls · 9,061 in / 457 out tok · 25s",
  922. "the task state aggregates the seeded usage events (calls, tokens,"
  923. " wall time): %r" % detail.get("usage_line"))
  924. check(task_state(auth, magnitude_task).get("usage_line")
  925. == "LLM: 1 calls · 45.2M in / 1.1M out tok · 3h 12m",
  926. "token magnitudes and durations format human-friendly"
  927. " (%r)" % task_state(auth, magnitude_task).get("usage_line"))
  928. task_page = http_get_page(auth, "/tasks/%d" % usage_task)
  929. check('stm-if="task.usage_line.length &gt; 0"' in task_page
  930. and 'stm-text="task.usage_line"' in task_page,
  931. "the task page renders the usage stat line (gated on non-empty)")
  932. check(task_state(auth, draft_display).get("usage_line") == "",
  933. "a task with no usage events carries no stat line")