goalui.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. """The goalui 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. def run(ctx):
  5. """Plan 14 workstream B + plan 15 C1: the goal supervision surface.
  6. B1 — goal-run control parity (Retry supervision / Requeue-to-resume
  7. on the status head, the /tasks/<goal-run-id> redirect, no
  8. notify-me toggle), B2 — the plan-review remarks queue, B4 —
  9. sessions.resume_notice on the task page's session rows + the
  10. plan-17 event log page, B5 —
  11. page order, effective rules and per-task capability badges, B6 —
  12. narrative footnote weights. C1 — the single-row block world: the
  13. goal's blocks ARE the run task's rows (answered from every
  14. surface through one path; no dual rows, no stragglers, at most
  15. one review-kind block per verdict path). C4 — the goal page
  16. batch: one muted head activity line, plan between attention and
  17. tasks, answered blocks behind an expander, footnote comments.
  18. C5 — the dashboard deep-link closure: goal pile cards link the
  19. goal page, every surface settles the single row, and no
  20. goal-side store exists to hold stragglers.
  21. """
  22. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  23. def run_task_of(goal_id):
  24. conn = db()
  25. try:
  26. return int(conn.execute(
  27. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  28. (goal_id,)).fetchone()[0])
  29. finally:
  30. conn.close()
  31. def wait_run(status, timeout=60, what="run status"):
  32. return wait_for(lambda: task_state(auth, run_task_of(goal))["status"] == status
  33. or False, timeout=timeout, what=what)
  34. def pile_questions():
  35. return [b.get("question") for b in
  36. slot_public(auth, "/", "dashboard")["pinned"]
  37. if b.get("item_type") == "goal"]
  38. def plant_live_worker(goal_id, title="Goalui live worker"):
  39. """Goal 27 refinements — the parking guard: the goal agent parks
  40. only while its goal owns a task that could still fire a
  41. terminal transition. The scenes that script it to park plant a
  42. BLOCKED live worker first (wakeable, never dispatched)."""
  43. conn = db()
  44. conn.execute("insert into tasks (project_id, goal_id, kind, title,"
  45. " status, priority, mode, creator, created_at)"
  46. " values (1, ?, 'task', ?, 'blocked', 5, 'implement',"
  47. " 'goal', strftime('%s','now'))", (goal_id, title))
  48. conn.commit()
  49. conn.close()
  50. def open_session(task_id):
  51. """The task's newest session row (plan 16 D4: a parked round's
  52. row is closed 'parked' — still the record the CLI callbacks,
  53. the telemetry pushes and the page surfaces key on)."""
  54. conn = db()
  55. try:
  56. row = conn.execute(
  57. "select max(id) from sessions where task_id = ?",
  58. (task_id,)).fetchone()
  59. return int(row[0]) if row and row[0] else None
  60. finally:
  61. conn.close()
  62. print("== B1: the goal-run task page redirects to the goal ==")
  63. fake.goal_script = [("plan", "# Remarks plan\n\n## Steps\n\n1. First move")]
  64. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  65. "project_id": "1", "title": "Goalui goal",
  66. "brief": "Drive the plan-14 goal surface end to end.",
  67. "branch_name": "goal/goalui"})
  68. conn = db()
  69. goal = conn.execute("select id from goals where title = 'Goalui goal'"
  70. ).fetchone()[0]
  71. conn.close()
  72. act(auth, goal_state(goal)["start"], {})
  73. wait_run("blocked", what="goalui goal agent parks on its plan") # plan review parks blocked
  74. run_task = run_task_of(goal)
  75. frames = directives("/tasks/%d" % run_task, auth)
  76. navigations = [d for d in frames if d.get("type") == "navigate"]
  77. check(any(d.get("uri") == "/goals/%d" % goal for d in navigations),
  78. "the goal-run task page redirects to /goals/<id> (navigate directive)")
  79. check(slot_public(auth, "/tasks/%d" % run_task, "task")["id"] == run_task,
  80. "the redirect still hydrates the task slot (sealed refresh + API readers)")
  81. status, page = http("GET", "/tasks/%d" % run_task, headers={
  82. "X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}, timeout=15)
  83. check(status == 200, "the compiled goal-run page serves")
  84. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  85. "project_id": "1", "title": "Goalui worker", "priority": "4",
  86. "description": "A plain worker under no goal."})
  87. conn = db()
  88. worker = conn.execute("select id from tasks where title = 'Goalui worker'"
  89. ).fetchone()[0]
  90. conn.close()
  91. check(not [d for d in directives("/tasks/%d" % worker, auth)
  92. if d.get("type") == "navigate"],
  93. "worker task pages render normally (no redirect)")
  94. state = goal_state(goal)
  95. check("toggle_notify" not in state and state.get("notify") is None,
  96. "no notify-me toggle on the goal (goals notify unconditionally)")
  97. goal_page = http_get_page(auth, "/goals/%d" % goal)
  98. check("Notify me" not in goal_page and "toggle-notify" not in goal_page,
  99. "the goal page template ships no notify control")
  100. check(state["branch_name"] == "goal/goalui" and state["base_branch"] == "main"
  101. and isinstance(state["push_branches"], list)
  102. and state["priority"] == 3
  103. and len(state["started_display"]) > 0
  104. and len(state["agent_saddle"]) > 0,
  105. "the status head carries the full field set (branch pair, chips list,"
  106. " priority, timestamps, agent saddle)")
  107. check("Retry supervision" in goal_page and "Requeue to resume" in goal_page,
  108. "the status head ships the run-control parity buttons")
  109. check("status-corner" not in goal_page and "goal complete" not in goal_page
  110. and "badge-yeehaw" not in goal_page,
  111. "no yeehaw badge remains anywhere (the feature died with the entry stream)")
  112. check(goal_state(goal)["current_activity"] == "parked awaiting the plan review",
  113. "the head line reads 'parked awaiting the plan review' while one is open")
  114. goal_page = http_get_page(auth, "/goals/%d" % goal)
  115. # Goal 41 T6 ("actions surface"): a pending plan review LEADS the
  116. # acting column as its own card — before the status head, the
  117. # blocks and the (history-only) plan card.
  118. check(goal_page.index("Plan review") < goal_page.index('class="card goal-head')
  119. < goal_page.index("Goal agent blocks") < goal_page.index("<h3>Plan</h3>"),
  120. "a pending plan review leads the acting column (status, blocks, history after)")
  121. check("data-plan-review" in goal_page and "Approved plan &amp; revisions" in goal_page,
  122. "an open review renders expanded beside the collapsed approved-plan expander")
  123. print("== B2: the plan-review remarks queue ==")
  124. check(goal_state(goal)["status"] == "plan_review"
  125. and goal_state(goal)["plan_pending_block"] is not None,
  126. "the goal sits in plan review with a pending block")
  127. goal_page = http_get_page(auth, "/goals/%d" % goal)
  128. review_at = goal_page.index("data-plan-review")
  129. check(review_at > 0, "the plan review region is marked for the remarks queue")
  130. check(goal_page.index('data-block-id="goal.plan_pending_block.id"') > 0,
  131. "the queue keys on the pending goal block id")
  132. body_at = goal_page.index('data-plan-body')
  133. remarks_at = goal_page.index("data-plan-remarks")
  134. check(body_at < remarks_at,
  135. "the remarks queue renders at the bottom of the plan body")
  136. for marker in ("data-plan-accept", "data-plan-toggle", "data-plan-submit"):
  137. check(marker in goal_page, "the remarks queue ships %s" % marker)
  138. # The queue ENGINE moved out of the inline page script into the
  139. # shared app.js (main.html's <script pstm-res-src="app.js">, the
  140. # theming commits): the page keeps the review markup and the
  141. # wiring, the engine keeps the machinery. The engine is asserted
  142. # on the SERVED bundle the page loads (the pages.py statum.js
  143. # pattern); main.html ships it ahead of the page's own script,
  144. # so the wiring below cannot run before the engine exists.
  145. status, app_js = http("GET", "/_statum/resource/app.js", timeout=15)
  146. check(status == 200 and "window.initPlanReviews" in app_js,
  147. "the served app.js ships the shared initPlanReviews engine")
  148. check("window.initPlanReviews" in goal_page,
  149. "the goal page references the shared engine (its review rides it)")
  150. for marker in ("data-plan-remove", "plan-popover", "remarksByBlock"):
  151. check(marker in app_js, "the remarks queue ships %s" % marker)
  152. check("(index + 1) + '. '" in app_js,
  153. "the rejection payload numbers every queued remark")
  154. check("rejectOpenByBlock" in app_js and "statum.afterEvaluate(syncPlanRemarks)" in app_js,
  155. "the queue survives pulse refreshes (maps outside statum re-renders)")
  156. # The rejection payload exactly as the client composes it: the
  157. # stable verdict wording, then each remark NUMBERED in queue order
  158. # with its quote prefixed like a comment.
  159. payload = ("Plan feedback received:\n\n"
  160. "> ## Steps\n\n1. First move\n\n"
  161. "1. Add a rollback step\n\n"
  162. "2. Name the owner of the migration")
  163. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  164. {"answer": payload})
  165. state = goal_state(goal)
  166. check(state["status"] == "planning",
  167. "the remarks rejection returns the agent to planning")
  168. rejected = [r for r in state["plan_revisions"] if r.get("answered")]
  169. check(any(r["answer"] == payload for r in rejected),
  170. "the rejection carries the remarks verbatim, in order")
  171. check(payload.index("1. Add a rollback step") < payload.index("2. Name the owner"),
  172. "the numbering is queue-ordered")
  173. print("== B4: resume_notice lands on the resumed session row ==")
  174. fake.goal_script = [("question", "Which datastore?", ["SQLite", "Redis"])]
  175. check(wait_for(lambda: goal_state(goal)["status"] == "planning" or False,
  176. timeout=30, what="rejection observed") is not None,
  177. "the agent revises")
  178. # The parked plan agent resumes with the verdict; the next round
  179. # raises the scripted question.
  180. check(wait_for(lambda: any(b["question"] == "Which datastore?"
  181. and not b.get("answered")
  182. for b in goal_state(goal)["blocks"]) or False,
  183. timeout=60, what="question raised") is not None,
  184. "the resumed agent raises its question")
  185. conn = db()
  186. notices = dict(conn.execute(
  187. "select id, resume_notice from sessions where task_id = ?", (run_task,)
  188. ).fetchall())
  189. conn.close()
  190. resumed_ids = [i for i, text in notices.items() if text]
  191. fresh_ids = [i for i, text in notices.items() if not text]
  192. check(len(resumed_ids) >= 1 and any("Plan feedback received" in notices[i]
  193. for i in resumed_ids),
  194. "the resumed session stores the notice it was allocated")
  195. check(min(notices) in fresh_ids,
  196. "session 1 (the fresh opening round) carries no resume notice")
  197. print("== C1: the single run-task row IS the goal's block ==")
  198. check("Which datastore?" in pile_questions(),
  199. "the open goal question pins onto the dashboard pile")
  200. goal_rows = [b for b in goal_state(goal)["blocks"]
  201. if b["question"] == "Which datastore?"]
  202. run_rows = [b for b in task_state(auth, run_task)["blocks"]
  203. if b["question"] == "Which datastore?"]
  204. check(len(run_rows) == 1 and len(goal_rows) == 1
  205. and int(run_rows[0]["id"]) == int(goal_rows[0]["id"]),
  206. "the goal page and the run task read the SAME single row")
  207. pile_card = [b for b in slot_public(auth, "/", "dashboard")["pinned"]
  208. if b.get("question") == "Which datastore?"][0]
  209. check(pile_card.get("item_type") == "goal"
  210. and int(pile_card.get("goal_id") or 0) == goal
  211. and int(pile_card.get("id") or 0) == int(run_rows[0]["id"])
  212. and pile_card.get("goal_title") == "Goalui goal",
  213. "the pile card is the run-task row styled as a goal item")
  214. act(auth, [b for b in goal_state(goal)["blocks"]
  215. if b["question"] == "Which datastore?" and not b.get("answered")]
  216. [0]["answer_action"], {"option": "SQLite"})
  217. conn = db()
  218. unanswered = conn.execute(
  219. "select count(*) from task_blocks where question = 'Which datastore?'"
  220. " and answer is null").fetchone()[0]
  221. conn.close()
  222. check(unanswered == 0, "answering from the goal page closes the single row")
  223. check("Which datastore?" not in pile_questions(),
  224. "the answered row no longer pins the dashboard pile")
  225. # The task-page deep link (the AnswerBlockAction API surface)
  226. # answers the SAME row through the one goal path — there is no
  227. # second row to sweep and no stale copy can survive.
  228. conn = db()
  229. conn.execute("insert into task_blocks (task_id, type, question, created_at)"
  230. " values (?, 'question', 'Deep link probe?',"
  231. " strftime('%s','now'))", (run_task,))
  232. conn.commit()
  233. conn.close()
  234. check("Deep link probe?" in pile_questions(),
  235. "the fixture row pins like any goal question")
  236. deep_block = [b for b in task_state(auth, run_task)["blocks"]
  237. if b["question"] == "Deep link probe?" and not b.get("answered")][0]
  238. act(auth, deep_block["answer_action"], {"answer": "Answered via the deep link"})
  239. conn = db()
  240. answered_row = conn.execute(
  241. "select answer from task_blocks where question = 'Deep link probe?'"
  242. ).fetchone()[0]
  243. tables = {r[0] for r in conn.execute(
  244. "select name from sqlite_master where type = 'table'").fetchall()}
  245. conn.close()
  246. check(answered_row == "Answered via the deep link",
  247. "the task-page deep link answers the same single row (the API path)")
  248. check("Deep link probe?" not in pile_questions(),
  249. "the deep-link answer closes the pile card too")
  250. check("goal_blocks" not in tables,
  251. "the goal_blocks table is gone (run-task blocks are canonical)")
  252. print("== C5: deep-link closure on the single-row world ==")
  253. # The pile card's goal item deep-links the goal page (the answer
  254. # surface); answering from either surface settled THE row above.
  255. home_markup = http_get_page(auth, "/")
  256. check("'/goals/' + blockview.goal_id" in home_markup,
  257. "the pile card deep-links the goal page for goal items")
  258. conn = db()
  259. dupes = conn.execute(
  260. "select count(*) from (select question from task_blocks where task_id = ?"
  261. " group by question having count(*) > 1)", (run_task,)).fetchone()[0]
  262. stragglers = conn.execute(
  263. "select count(*) from task_blocks where task_id = ? and answer is null",
  264. (run_task,)).fetchone()[0]
  265. goal_side_tables = [r[0] for r in conn.execute(
  266. "select name from sqlite_master where type = 'table'"
  267. " and name in ('goal_blocks','goal_comments','goal_events')").fetchall()]
  268. conn.close()
  269. check(dupes == 0 and stragglers == 0,
  270. "one row per question on the run task, none left unanswered")
  271. check(not goal_side_tables,
  272. "no goal-side store exists — historical stragglers are impossible")
  273. print("== B4: resume notices on the session rows + the event log page ==")
  274. plant_live_worker(goal)
  275. fake.goal_script = [("suspend",)]
  276. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  277. or False, timeout=60, what="agent parks suspended") is not None,
  278. "the agent parks suspended for the requeue scenario")
  279. sessions = task_state(auth, run_task)["sessions"]
  280. ids = [int(s["id"]) for s in sessions]
  281. check(ids == sorted(ids, reverse=True),
  282. "the task page's session history lists newest-first")
  283. # Recompute at the check point: the C1 answers above each
  284. # resumed the agent too, so the earlier snapshot would go stale.
  285. conn = db()
  286. resumed_ids = [int(i) for (i, text) in conn.execute(
  287. "select id, resume_notice from sessions where task_id = ?",
  288. (run_task,)).fetchall() if text]
  289. conn.close()
  290. notices_by_id = {int(s["id"]): s.get("notice") or "" for s in sessions}
  291. check(set(i for i in ids if notices_by_id[i]) == set(resumed_ids),
  292. "the session rows' notice column rides exactly the notice-carrying sessions")
  293. check(any("Plan feedback received" in notices_by_id[i] for i in resumed_ids),
  294. "a resumed session's row shows the stored resume notice")
  295. log_state = slot_public(auth, "/tasks/%d/log" % run_task, "task_log")
  296. check(log_state.get("exists") is True and int(log_state["task_id"]) == run_task
  297. and log_state["task_url"] == "/tasks/%d" % run_task,
  298. "the event log page hydrates the run-task header")
  299. log_page = http_get_page(auth, "/tasks/%d/log" % run_task)
  300. # The SSE client ships as the compiled task_log.js resource (plan 17
  301. # b3+): the page references it and the resource carries the code.
  302. status, log_js = http("GET", "/_statum/resource/task_log.js", timeout=15)
  303. check(status == 200 and "task_log.js" in log_page
  304. and "EventSource" in log_js and "events/stream" in log_js
  305. and "data-log-feed" in log_page,
  306. "the log page subscribes to the ledger's SSE stream")
  307. check(goal_state(goal)["runs"][0]["terminal_url"] == "/tasks/%d/log" % run_task,
  308. "the goal runs table links the event log")
  309. print("== B1: requeue-to-resume from the goal head ==")
  310. conn = db()
  311. conn.execute("update saddles set status = 'offline' where id = ?", (fake_id,))
  312. conn.commit()
  313. conn.close()
  314. def requeue_offered():
  315. # Act on the SAME state that satisfied the wait: a second read
  316. # once raced the scripted daemon's ask reviving the saddle row,
  317. # and the conditionally-authored action vanished between the
  318. # two reads (KeyError on act).
  319. offered = goal_state(goal)
  320. return offered if offered.get("requeue_run") is not None else False
  321. state = wait_for(requeue_offered, timeout=30, what="requeue offered")
  322. check(state is not None,
  323. "a parked run on a dead saddle offers Requeue-to-resume")
  324. check(state.get("retry_run") is None,
  325. "an active goal offers no Retry supervision")
  326. conn = db()
  327. before_requeue = conn.execute(
  328. "select id, outcome from sessions where task_id = ?"
  329. " order by id desc limit 1", (run_task,)).fetchone()
  330. conn.close()
  331. check(tuple(before_requeue) == (open_session(run_task), "parked"),
  332. "the parked round's newest session row closed 'parked' (D4)")
  333. def parked_session_ended():
  334. # D4: the parked row is ALREADY closed at its park — the pin
  335. # keeps guarding the restore-on-dispatch successor shape (the
  336. # requeue may not resurrect the OLD row; a fresh round opens
  337. # its own).
  338. conn = db()
  339. try:
  340. return conn.execute(
  341. "select ended_at is not null from sessions where id = ?",
  342. (before_requeue[0],)).fetchone()[0] == 1
  343. finally:
  344. conn.close()
  345. act(auth, state["requeue_run"], {})
  346. check(task_state(auth, run_task)["status"] == "queued",
  347. "the requeue returns the run to the queue")
  348. # The parked round's own row must stay closed (the
  349. # restore-on-dispatch successor opens a FRESH session row — the
  350. # check keys the old row, never the task's transient open window).
  351. check(wait_for(parked_session_ended, timeout=60,
  352. what="parked session closed") is not None,
  353. "the requeue leaves the parked session row closed (fresh round, fresh row)")
  354. conn = db()
  355. conn.execute("update saddles set status = 'idle' where id = ?", (fake_id,))
  356. conn.commit()
  357. conn.close()
  358. fake.goal_script = [("suspend",)]
  359. plant_live_worker(goal, "Goalui live worker two")
  360. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  361. or False, timeout=60, what="requeued run re-dispatches") is not None,
  362. "the requeued run re-dispatches and re-parks")
  363. fresh_session = open_session(run_task)
  364. conn = db()
  365. fresh_notice = conn.execute(
  366. "select resume_notice from sessions where id = ?", (fresh_session,)
  367. ).fetchone()[0]
  368. conn.close()
  369. check(fresh_notice is None,
  370. "a requeue's fresh session carries no resume notice (empty panel state)")
  371. print("== B1: Retry supervision revives a failed goal ==")
  372. fake.push_results("failed", summary="the supervision collapsed (scripted)")
  373. check(wait_for(lambda: goal_state(goal)["status"] == "failed" or False,
  374. timeout=30, what="goal fails") is not None,
  375. "the run's failure fails the goal")
  376. check(wait_for(lambda: goal_state(goal).get("retry_run") is not None
  377. or False, timeout=30, what="retry offered") is not None,
  378. "a failed goal offers Retry supervision")
  379. fake.goal_script = [("suspend",)]
  380. plant_live_worker(goal, "Goalui live worker three")
  381. act(auth, goal_state(goal)["retry_run"], {})
  382. state = goal_state(goal)
  383. check(state["status"] == "active",
  384. "the retry revives supervision (goal back to active)")
  385. check(task_state(auth, run_task)["status"] in ("queued", "assigned", "working",
  386. "suspended", "blocked"),
  387. "the retry re-offered the run task")
  388. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  389. or False, timeout=60, what="retried supervision parks") is not None,
  390. "the retried supervision dispatches and parks again")
  391. state = goal_state(goal)
  392. check(any(e["kind"] == "system" and "Supervision retried" in e["text"]
  393. for e in state["events"]),
  394. "the narrative records the supervision retry (a system row)")
  395. print("== B5 + C4 + goal 41 T6: act|consult layout, rules, badges ==")
  396. goal_page = http_get_page(auth, "/goals/%d" % goal)
  397. # Goal 41 T6 (ux-notes §5): the state strip leads, then the anchor
  398. # sub-nav, then the Act|Consult two-column layout — the acting
  399. # surfaces (status, attention, plan review, comments) in one
  400. # column, the consulting ones (tasks, brief, projects, rules,
  401. # narrative, runs) in the other, stacking act-first on narrow
  402. # screens (DOM order IS the stack order).
  403. check(goal_page.index('class="goal-state-strip"')
  404. < goal_page.index('class="goal-subnav"')
  405. < goal_page.index("data-goal-act")
  406. < goal_page.index("data-goal-consult"),
  407. "the goal page reads strip → sub-nav → act column → consult column")
  408. # mkpstm inlines pstm-fragment bodies at compile time, so the
  409. # include directive itself never serves; the adopted breadcrumb
  410. # (its ol/li markup) and the retired back anchor are the truth.
  411. check('class="breadcrumb"' in goal_page
  412. and 'aria-label="Breadcrumb"' in goal_page
  413. and "&larr; Goals" not in goal_page,
  414. "the shared breadcrumb replaces the hand-drawn back anchor")
  415. check(goal_state(goal)["crumbs"] == [
  416. {"href": "/", "label": "Dashboard"},
  417. {"href": "/goals", "label": "Goals"},
  418. {"href": None, "label": "#%d" % goal}],
  419. "the entrypoint publishes the Dashboard → Goals → #id crumb trail")
  420. act_markers = [
  421. ('id="goal-sec-plan-review"', "plan review (when pending)"),
  422. ('id="goal-sec-completion-review"', "completion review (when pending)"),
  423. ('class="card goal-head goal-section"', "status head"),
  424. ("Agent progress", "progress"),
  425. ("Goal agent blocks", "attention blocks"),
  426. ("<h3>Plan</h3>", "plan"),
  427. ("<h3>Comments</h3>", "comments"),
  428. ]
  429. consult_markers = [
  430. ("<h3>Tasks</h3>", "tasks"),
  431. ("Initial brief", "brief"),
  432. ("Involved projects", "projects"),
  433. ("<h3>Rules</h3>", "rules"),
  434. ("Supervision narrative", "narrative"),
  435. ("Goal agent runs", "runs"),
  436. ]
  437. for markers, column in ((act_markers, "act"), (consult_markers, "consult")):
  438. positions = []
  439. for marker, _ in markers:
  440. check(marker in goal_page, "the goal page ships the %s section" % _)
  441. positions.append(goal_page.index(marker))
  442. check(positions == sorted(positions),
  443. "the %s column reads %s (in order)" % (column,
  444. " → ".join(_ for _, __ in ((m, l) for m, l in markers))))
  445. act_at = goal_page.index("data-goal-act")
  446. consult_at = goal_page.index("data-goal-consult")
  447. check(all(act_at < goal_page.index(m) < consult_at
  448. for m, _ in act_markers),
  449. "every acting surface sits inside the act column")
  450. check(goal_page.index("data-goal-consult")
  451. < min(goal_page.index(m) for m, _ in consult_markers),
  452. "every consulting surface sits inside the consult column")
  453. # The strip: one glance — status badge, the open-item verdict, the
  454. # primary lifecycle button; the Status card keeps the detail.
  455. strip_at = goal_page.index("data-goal-state-strip")
  456. check(goal_page.index("'badge badge-' + goal.status", strip_at) > strip_at,
  457. "the strip leads with the status badge")
  458. for marker in ("goal.plan_pending_block", "goal.completion_pending",
  459. "goal.open_blocks.length"):
  460. check(marker in goal_page[strip_at:strip_at + 2500],
  461. "the strip's verdict is computed from %s" % marker)
  462. check(goal_page.count("stm-action=\"goal.start\"") >= 2,
  463. "the primary lifecycle button rides the strip (and the status ladder)")
  464. check("goalHighlightSubnav" in goal_page
  465. and "statum.afterEvaluate(goalHighlightSubnav)" in goal_page,
  466. "the anchor sub-nav rebinds its highlight across statum re-renders")
  467. check("goal.current_activity" in goal_page and "Current activity" not in goal_page,
  468. "the activity lives as ONE muted head line (the card is gone)")
  469. check(".goal-page .card" in open(os.path.join(REPO, "src/pages/app.css")).read(),
  470. "the stylesheet restores the goal page's card rhythm (padding regression)")
  471. rules_state = slot_public(auth, "/rules", "rules")
  472. act(auth, rules_state["create"], {"name": "goalui-primary", "body": "Primary rule"})
  473. act(auth, rules_state["create"], {"name": "goalui-codev", "body": "Co-dev rule"})
  474. act(auth, rules_state["create"], {"name": "goalui-ref", "body": "Reference rule"})
  475. conn = db()
  476. rule_ids = {name: int(conn.execute("select id from rules where name = ?",
  477. (name,)).fetchone()[0])
  478. for name in ("goalui-primary", "goalui-codev", "goalui-ref")}
  479. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  480. " values (?, 1, strftime('%s','now'))", (rule_ids["goalui-primary"],))
  481. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  482. " values ('goalui-codev-project', 'https://example.com/g.git',"
  483. " 'main', strftime('%s','now'))")
  484. codev_project = conn.execute(
  485. "select id from projects where name = 'goalui-codev-project'").fetchone()[0]
  486. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  487. " values ('goalui-ref-project', 'https://example.com/r.git',"
  488. " 'main', strftime('%s','now'))")
  489. ref_project = conn.execute(
  490. "select id from projects where name = 'goalui-ref-project'").fetchone()[0]
  491. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  492. " values (?, ?, strftime('%s','now'))",
  493. (rule_ids["goalui-codev"], codev_project))
  494. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  495. " values (?, ?, strftime('%s','now'))",
  496. (rule_ids["goalui-ref"], ref_project))
  497. conn.commit()
  498. conn.close()
  499. act(auth, goal_state(goal)["add_link"], {"linked_project_id": str(codev_project),
  500. "relationship": "co-developed"})
  501. act(auth, goal_state(goal)["add_link"], {"linked_project_id": str(ref_project),
  502. "relationship": "reference"})
  503. rule_names = [r["name"] for r in goal_state(goal)["rules"]]
  504. check(rule_names == ["goalui-primary", "goalui-codev"],
  505. "the Rules section lists the goal's effective set (primary then"
  506. " co-developed; reference contributes nothing)")
  507. act(auth, slot_public(auth, "/saddles", "saddles")["create_capability"],
  508. {"name": "goalui-capability"})
  509. conn = db()
  510. capability = conn.execute(
  511. "select id from capabilities where name = 'goalui-capability'"
  512. ).fetchone()[0]
  513. # The early redirect-fixture worker joins the goal (a fanned
  514. # worker's shape) so its row carries the badge too.
  515. conn.execute("update tasks set goal_id = ? where id = ?", (goal, worker))
  516. conn.execute("insert into task_capabilities (task_id, capability_id)"
  517. " values (?, ?)", (worker, capability))
  518. conn.commit()
  519. conn.close()
  520. goal_worker = {"id": worker, "caps": None}
  521. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  522. "project_id": "1", "title": "Goalui fanned worker", "priority": "4",
  523. "description": "A worker the agent fanned out."})
  524. conn = db()
  525. fanned = conn.execute(
  526. "select id from tasks where title = 'Goalui fanned worker'").fetchone()[0]
  527. conn.execute("update tasks set goal_id = ? where id = ?", (goal, fanned))
  528. conn.execute("insert into task_capabilities (task_id, capability_id)"
  529. " values (?, ?)", (fanned, capability))
  530. conn.commit()
  531. conn.close()
  532. rows = {int(t["id"]): t for t in goal_state(goal)["goal_tasks"]}
  533. check(rows[fanned].get("capabilities") == ["goalui-capability"]
  534. and rows[worker].get("capabilities") == ["goalui-capability"],
  535. "task rows carry their required capability tags")
  536. goal_page = http_get_page(auth, "/goals/%d" % goal)
  537. check('stm-for-capability-in="goal_task.capabilities"' in goal_page
  538. and "badge-capability" in goal_page,
  539. "the task rows render capability badges")
  540. print("== B6: narrative weights — events full, comments footnote ==")
  541. # An AGENT remark rides the ledger as a comment event (human
  542. # comments only thread) — pushed through the events channel while
  543. # parked, so the suspended state stays put.
  544. fake.push_events([{"kind": "comment", "actor": "model",
  545. "payload": {"author": "agent",
  546. "body": "An agent aside."}}])
  547. check(wait_for(lambda: any(e["kind"] == "comment"
  548. for e in goal_state(goal)["events"]) or False,
  549. timeout=15, what="comment event lands") is not None,
  550. "an agent comment lands as a narrative event")
  551. goal_page = http_get_page(auth, "/goals/%d" % goal)
  552. check("stm-attribute.class=\"'goal-event' + (event.kind == 'comment'"
  553. " ? ' footnote' : '')\"" in goal_page.replace("\n", " ").replace(" ", " ")
  554. or "'goal-event' + (event.kind == 'comment' ? ' footnote' : '')" in goal_page,
  555. "the WHOLE comment event row carries .footnote (badge included)")
  556. check("'badge badge-goal-' + event.kind" in goal_page,
  557. "non-comment events keep their full-weight kind badges")
  558. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  559. check(".goal-event.footnote" in css and ".footnote {" in css,
  560. "the stylesheet ships the footnote row weight beside the utility")
  561. print("== C2: system rows render distinctly on the ONE thread ==")
  562. run_comments = task_state(auth, run_task)["comments"]
  563. system_rows = [c for c in run_comments if c.get("is_system")]
  564. check(system_rows and all(c["author"] == "system" for c in system_rows)
  565. and not any(c.get("from_agent") for c in system_rows),
  566. "the harness bookkeeping rows are authored 'system' (never agent)")
  567. goal_thread = goal_state(goal)["comments"]
  568. check(any(c.get("is_system") for c in goal_thread),
  569. "the goal page reads the same thread (the system rows included)")
  570. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  571. check(".comment.system" in css and ".system-label" in css,
  572. "the stylesheet ships the distinct system-event styling")
  573. page = http_get_page(auth, "/goals/%d" % goal)
  574. check("comment.is_system" in page and "system-label" in page,
  575. "the goal page renders system rows with the labelled muted style")
  576. task_page = http_get_page(auth, "/tasks/%d" % worker)
  577. check("comment.is_system" in task_page and "system-label" in task_page,
  578. "the task page renders system rows with the same style")
  579. print("== S5 U2: mechanical rows filtered from user-facing timelines ==")
  580. # The daemon's mechanical system remarks (the park notice, the
  581. # restore footnote) ride the ledger as harness comment events: the
  582. # event row STORES, but no comment row, narrative event or
  583. # dashboard timeline row renders for them.
  584. open_run = open_session(run_task)
  585. mechanical = [
  586. {"seq": 9501, "kind": "comment", "actor": "harness",
  587. "payload": {"author": "system",
  588. "body": "goal agent parked until an owned task"
  589. " completes or fails"}},
  590. {"seq": 9502, "kind": "comment", "actor": "harness",
  591. "payload": {"author": "system",
  592. "body": "[harness] session context restored — task resumed"}},
  593. ]
  594. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  595. {"session_id": open_run, "events": mechanical})
  596. check(status == 200 and int(body.get("stored") or 0) == 2,
  597. "the mechanical harness remarks store on the ledger")
  598. check(all("parked until" not in c["body"]
  599. and "session context restored" not in c["body"]
  600. for c in task_state(auth, run_task)["comments"]),
  601. "no mechanical comment row lands on the thread (U2)")
  602. check(all("parked until" not in e["text"]
  603. and "session context restored" not in e["text"]
  604. for e in goal_state(goal)["events"]),
  605. "no mechanical narrative event lands on the goal page (U2)")
  606. dash_events = slot_public(auth, "/", "dashboard")["activity"]
  607. check(all("parked until" not in e["text"]
  608. and "session context restored" not in e["text"]
  609. for e in dash_events),
  610. "no mechanical row lands on the dashboard timeline (U2)")
  611. print("== C4: head line, answered-blocks expander, footnote comments ==")
  612. state = goal_state(goal)
  613. # (Goal 27 refinements: the parking guard can hand the run a
  614. # refusal resume between rounds — the parked head line is the
  615. # settled state, not a transient working blip.)
  616. check(wait_for(lambda: goal_state(goal)["current_activity"]
  617. == "parked awaiting its tasks' terminal transitions"
  618. or False, timeout=60, what="run settles parked")
  619. is not None,
  620. "a suspended run folds into the one muted head line")
  621. check(len(state.get("answered_blocks") or []) >= 2
  622. and len(state.get("open_blocks") or []) == 0,
  623. "the historic answered blocks expose as their own vector (open ones empty)")
  624. goal_page = http_get_page(auth, "/goals/%d" % goal)
  625. check("Answered blocks (" in goal_page and "comment-meta" in goal_page,
  626. "the answered blocks and the footnote comment meta ship in the markup")
  627. check("timeless note for a future reader" in goal_page,
  628. "the composer hint states the timeless-comment rule")
  629. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  630. check(".goal-page .card { margin-bottom" in css and ".comment-meta" in css,
  631. "the stylesheet ships the card rhythm and the comment footnote meta")
  632. print("== C1: one review block per verdict path (F6) ==")
  633. # The daemon's honest round pushes the ENTRY and the STATE
  634. # together — the done pair must raise exactly ONE completion
  635. # block, and a redelivered pair nothing more.
  636. fake.goal_script = [("done", "# Completion\n\nOne block only.")]
  637. conn = db()
  638. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  639. " priority, completed_at, created_at) values (1, ?, 'task',"
  640. " 'Warmup', 'done', 5,"
  641. " strftime('%s','now'),"
  642. " strftime('%s','now','-30 seconds'))", (goal,))
  643. conn.commit()
  644. conn.close()
  645. check(wait_for(lambda: goal_state(goal)["status"] == "completion_review" or False,
  646. timeout=60, what="goalui completion review opens") is not None,
  647. "the scripted done round enters completion review")
  648. def completion_block_count():
  649. conn = db()
  650. try:
  651. return conn.execute(
  652. "select count(*) from task_blocks where task_id = ?"
  653. " and type = 'completion'", (run_task,)).fetchone()[0]
  654. finally:
  655. conn.close()
  656. check(completion_block_count() == 1,
  657. "the done state raises exactly ONE completion block")
  658. # Plan 16 S5 (U1): the verdict-shaped block renders the rich review
  659. # form — explicit accept/reject affordances with the free-text
  660. # feedback path, never a free-text-only verdict.
  661. goal_page = http_get_page(auth, "/goals/%d" % goal)
  662. check("Accept goal" in goal_page and "Reject with feedback" in goal_page
  663. and 'name="feedback"' in goal_page,
  664. "the completion review presents explicit accept/reject + free-text feedback (U1)")
  665. # The burst shape: the done STATE redelivered under the run's
  666. # newest session (the entries channel is gone — the report rides
  667. # the summary) — the pending-report idempotency leaves the one
  668. # row alone.
  669. conn = db()
  670. burst_session = conn.execute(
  671. "select max(id) from sessions where task_id = ?",
  672. (run_task,)).fetchone()[0]
  673. conn.close()
  674. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  675. {"session_id": burst_session, "state": "done",
  676. "summary": "# Completion\n\nOne block only."})
  677. check(status == 200 and completion_block_count() == 1,
  678. "a redelivered done push raises nothing more (one block, ever)")
  679. state = goal_state(goal)
  680. act(auth, state["completion_pending_block"]["answer_action"],
  681. {"verdict": "accept"})
  682. check(wait_for(lambda: goal_state(goal)["status"] == "complete" or False,
  683. timeout=30, what="goalui goal completes") is not None,
  684. "accepting the completion completes the goal")
  685. check(completion_block_count() == 1,
  686. "the accept path leaves exactly one review-kind block behind")
  687. conn = db()
  688. stragglers = conn.execute(
  689. "select count(*) from task_blocks where task_id = ? and answer is null",
  690. (run_task,)).fetchone()[0]
  691. conn.close()
  692. check(stragglers == 0,
  693. "no unanswered straggler rows survive the completion")
  694. print("== S2: server-owned verdicts + the container-resolved reject ==")
  695. # A fresh goal drives the verdict paths the goal page's forms now
  696. # use: verdict markers for accept, raw `feedback` for reject, and
  697. # the block resolution living in the review CONTAINER (not
  698. # goal.plan_pending_block — the diagnosed completion-review bug).
  699. fake.goal_script = [("plan", "# S2 plan\n\nOne step")]
  700. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  701. "project_id": "1", "title": "S2 verdict goal",
  702. "brief": "Covers the plan-16 S2 verdict paths.",
  703. "branch_name": "goal/s2-verdicts"})
  704. conn = db()
  705. s2_goal = int(conn.execute(
  706. "select id from goals where title = 'S2 verdict goal'").fetchone()[0])
  707. conn.close()
  708. act(auth, goal_state(s2_goal)["start"], {})
  709. check(wait_for(lambda: goal_state(s2_goal)["status"] == "plan_review" or False,
  710. timeout=90, what="S2 goal enters plan review") is not None,
  711. "the S2 goal enters plan review")
  712. s2_state = goal_state(s2_goal)
  713. s2_pending = s2_state["plan_pending_block"]
  714. # (1) A remark-less, text-less rejection is refused: the action
  715. # errors and the block keeps waiting.
  716. refusal = act(auth, s2_pending["answer_action"], {"feedback": " "})
  717. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  718. and "answer is required" in (d.get("message") or "").lower()
  719. for d in refusal),
  720. "a remark-less, text-less rejection is refused with an error")
  721. conn = db()
  722. s2_still_open = conn.execute(
  723. "select answer from task_blocks where id = ?",
  724. (s2_pending["id"],)).fetchone()[0]
  725. conn.close()
  726. check(s2_still_open is None,
  727. "the refused rejection leaves the block unanswered")
  728. # (3) The goal page template ships no verdict constants and its
  729. # script resolves the review block from ANY [data-plan-review]
  730. # container via the open-blocks list (the completion-review fix);
  731. # the reject flow itself lives in the shared app.js engine
  732. # (app_js fetched in B2 above).
  733. # Fetched while the review is open so the accept form renders.
  734. s2_page = http_get_page(auth, "/goals/%d" % s2_goal)
  735. check("Plan approved. Proceed with implementation." not in s2_page
  736. and "Review approved. Continue with the task." not in s2_page,
  737. "the goal page ships no verdict constants (server-owned wording)")
  738. check('name="verdict" value="accept"' in s2_page,
  739. "the goal page's accept forms post the verdict marker")
  740. check("resolveReviewBlock" in s2_page and "goal.open_blocks" in s2_page,
  741. "the reject flow resolves its block from the open-blocks list (container-keyed)")
  742. check("statum.act(block.answer_action, { feedback: feedback })" in app_js,
  743. "the reject flow posts raw feedback (the server wraps the prefix)")
  744. check("extraText.length === 0" in app_js,
  745. "a remark-less rejection with textarea content is allowed (S2)")
  746. # (2) The goal page's reject rides `feedback` (the client composes
  747. # the numbered-remarks body) and the SERVER wraps it with the plan
  748. # prefix — byte-identical to the historical client-built answer.
  749. act(auth, s2_pending["answer_action"],
  750. {"feedback": "> ## One step\n\n1. Tighten it\n\n2. Name the owner"})
  751. conn = db()
  752. s2_wrapped = conn.execute(
  753. "select answer from task_blocks where id = ?",
  754. (s2_pending["id"],)).fetchone()[0]
  755. conn.close()
  756. check(s2_wrapped
  757. == "Plan feedback received:\n\n"
  758. "> ## One step\n\n1. Tighten it\n\n2. Name the owner",
  759. "the plan rejection wraps the client-shaped body with the stable prefix (%r)"
  760. % s2_wrapped)
  761. check(goal_state(s2_goal)["status"] == "planning",
  762. "the feedback rejection returns the agent to planning")
  763. # =====================================================================
  764. # Task 12 (goal half): the draft brief-card editor.
  765. # =====================================================================
  766. print("== task 12: the draft goal brief editor ==")
  767. # A fresh DRAFT goal (the fixtures above are all started): the
  768. # brief card carries the in-place editor with title/brief/priority
  769. # prefilled from state, goal.update saves through the sealed
  770. # action, and START removes the editor (the brief locks).
  771. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  772. "project_id": "1", "title": "Editable draft goal",
  773. "brief": "The original brief.",
  774. "branch_name": "goal/editable-draft"})
  775. conn = db()
  776. edit_goal = conn.execute(
  777. "select id from goals where title = 'Editable draft goal'"
  778. ).fetchone()[0]
  779. conn.close()
  780. draft = goal_state(edit_goal)
  781. check("update" in draft,
  782. "a draft goal's state carries the update action (the editor's save)")
  783. goal_page = http_get_page(auth, "/goals/%d" % edit_goal)
  784. check('stm-if="goal.update != null"' in goal_page
  785. and 'data-lf-toggle>Edit</button>' in goal_page,
  786. "the brief card renders the draft-only Edit button")
  787. check('data-lf-src="goal.brief"' in goal_page
  788. and 'data-lf-src="goal.title"' in goal_page
  789. and 'data-lf-src="goal.priority"' in goal_page,
  790. "the editor prefills title, brief and priority from state"
  791. " (stm-attribute.value cannot carry a textarea)")
  792. act(auth, draft["update"], {"title": "Editable draft goal (edited)",
  793. "brief": "The edited brief.",
  794. "priority": "7"})
  795. saved = goal_state(edit_goal)
  796. check(saved["title"] == "Editable draft goal (edited)"
  797. and saved["brief"] == "The edited brief."
  798. and saved["priority"] == 7,
  799. "the draft edit round-trips title, brief and priority"
  800. " (draft priority is finally changeable)")
  801. # The draft-only guard is server-side: start the goal, then the
  802. # update action is gone from state (the editor with it).
  803. act(auth, saved["start"], {})
  804. check(wait_for(lambda: goal_state(edit_goal)["status"] != "draft"
  805. or False, what="editable draft goal starts"),
  806. "the edited draft goal starts")
  807. check("update" not in goal_state(edit_goal),
  808. "a started goal's state carries no update action (the brief locked)")
  809. # The server-side guard: replaying the (still-valid) sealed
  810. # update action against the now-started goal must refuse — the
  811. # editor's disappearance is UI, the refusal is enforcement.
  812. replay = act(auth, draft["update"], {"brief": "Sneaked brief."})
  813. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  814. for d in replay),
  815. "the draft-only guard refuses an edit replay against a started goal")
  816. check(goal_state(edit_goal)["brief"] == "The edited brief.",
  817. "the refused replay left the brief unchanged")
  818. print("== goal 4 t1: force-wake action stays unoffered unless parked ==")
  819. # The page template ships the gated button markup statically (the
  820. # stm-if hides it client-side), so absence is asserted on the SLOT
  821. # STATE: the action is not AUTHORED. The offered pair (parked run)
  822. # is covered by the goals bundle, which owns a parked run.
  823. check(goal_state(edit_goal).get("force_wake") is None,
  824. "a non-parked (planning) goal state offers no force-wake action")
  825. conn = db()
  826. any_goal = conn.execute(
  827. "select id from goals where status = 'draft' order by id limit 1").fetchone()
  828. plain = conn.execute(
  829. "select id from tasks where status != 'suspended'"
  830. " and kind = 'task' order by id limit 1").fetchone()
  831. conn.close()
  832. if any_goal:
  833. check(goal_state(int(any_goal[0])).get("force_wake") is None,
  834. "a draft goal state offers no force-wake action")
  835. if plain:
  836. check(task_state(auth, int(plain[0])).get("force_wake") is None,
  837. "a non-suspended task state offers no force-wake action")