goalui.py 41 KB

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