web_stack_test.py 294 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718
  1. #!/usr/bin/env python3
  2. """Self-contained web-stack feature tests: app + fake saddle daemon.
  3. Unlike integration_test.py (which needs a real saddle daemon and a mock
  4. LLM), this suite spawns everything it needs:
  5. - the clanker-saddle app binary (path from argv[1], or builddir default)
  6. in a scratch directory with its own web-config.json (statum keys copied
  7. from the repo, plus `saddle_callback_base_url`) and SQLite database
  8. - in-process fake saddle daemons speaking the wire contract: POST
  9. /register (plan 10: receives {saddle_token, web_base_url}, answers
  10. {ok, ssh_public_key, version}), POST /wake (records the wake; the
  11. daemon then asks POST /api/saddle/next-task), POST /task-update
  12. (cancel/comment/subtask-status), GET /status (scripted reflection —
  13. exceptional use only), and the phase-2 push channels home:
  14. POST /api/saddle/chunks (raw PTY batches) and POST /api/saddle/results
  15. (round entries + state transitions). The retired /start, /output and
  16. /log routes 404 like a post-phase-2 daemon.
  17. It then drives the app the way statum.js does (entrypoint loads + action
  18. POSTs) and asserts the Workstream B features against the wire contract:
  19. 3. plan-review blocks hide their duplicate body preview
  20. 5. rules CRUD/attach + the effective `rules` array in assignments
  21. 6. project notes, POST /api/saddle/note, `project_notes` + `callback`
  22. in assignments
  23. plus the raw-log side: pushed chunks -> session_raw_log + terminal
  24. raw view
  25. Plan 10 phase 1 (work acquisition flip):
  26. - per-saddle tokens: registration mints + /register-delivers them,
  27. legacy tokens migrate onto the row at startup, removal revokes
  28. - token auth on every /api/saddle/* endpoint
  29. - next-task allocation: concurrent asks race exactly one winner,
  30. affinity pinning for parked tasks, resume_notice on suspended resumes
  31. - dispatcher: wake -> ask -> allocate roundtrip, the lost-wake guard
  32. (no ask after a wake -> offline, re-wake the next capable), and the
  33. pre-flip /answer + /start resume paths kept as the rollback route
  34. Plan 10 phase 2 (telemetry flip):
  35. - pushed chunks: idempotent on (session_id, seq), ordered, landing in
  36. session_raw_log so the SSE terminal keeps working
  37. - pushed results: entries store like the /output path did (redelivery
  38. idempotent on the daemon entry ids), blocked raises the block row +
  39. parks + bumps the pulse (sealed refresh shows it), done/failed
  40. complete/fail the task, suspended parks for the affinity resume
  41. - answer resumes, both daemon shapes: a SLEEPING affine saddle (its
  42. post-park ask returned 204) is woken, its ask allocating the resume
  43. with the verdict riding the assignment; a daemon parked MID-ROUND
  44. (its round holds the block's answer wait open, so it can never ask)
  45. gets the verdict delivered into that wait via POST /answer — same
  46. session, no wake. A daemon dying with a parked-with-answered task
  47. never requeues it: the verdict and session survive for the resume
  48. - staleness: a silent runner gets ONE exceptional GET /status probe —
  49. alive keeps it running, dead requeues the task with a bot comment and
  50. marks the saddle offline; a recovered daemon's ask flips offline rows
  51. back to idle
  52. - the deleted layers are gone: /output, /log and /start 404 on the
  53. daemon side, and nothing on the web side calls them
  54. Plan 10 phase 3 (capability awareness + UI):
  55. - assignment capability context: {saddle_tags, fleet_tags} on every
  56. payload, GET /api/saddle/capabilities (per-saddle token) feeding
  57. the daemon's `saddle capabilities` CLI
  58. - subtask callback capabilities: explicit-only attachment validated
  59. against the operator tag set, unknown tags rejected with the valid
  60. list in the error
  61. - task page: status block pinned to the top, blocking sections
  62. newest-first (sealed GET state)
  63. - home dashboard: pinned OPEN blocks as newest-first link-through
  64. cards (no inline answer forms) above the cross-task activity
  65. timeline (last ~50 events newest-first)
  66. - lost-wake-guard regression: a saddle that asks SLOWLY after its
  67. wake (busy winding down) still claims the task — the wake is never
  68. silently dropped, no re-wake storm fires, and the never-asks guard
  69. path (offline + re-wake of the next capable) stays green
  70. Prints PASS/FAIL lines Statum-style; exits non-zero on any failure.
  71. Plan 11 task D+E (UI + notifications), the `push` shard:
  72. - task page: progress feed above the status card, status + description
  73. in a 50/50 grid, edit expander under the history expander, plan
  74. behind an expander, answered blocks behind an expander; queue screen:
  75. New Task expander above the filters; dashboard waiting-on-drafts
  76. block with links to where Enqueue lives (pages shard)
  77. - real Web Push over VAPID: keypair generated at startup into
  78. web-config.json, GET /sw.js service worker with click-through,
  79. subscribe/unsubscribe + per-task Notify me actions, block events and
  80. waiting-on-drafts pushed globally, first start/failure/completion to
  81. opted-in users, best-effort queue with dispatcher-tick retry, 410/404
  82. endpoint pruning — payloads verified protocol-level (RFC 8291
  83. decryption + ES256 JWT signature) because the harness owns the
  84. browser-side keys
  85. Heredoc completion reports (pages shard):
  86. - terminal tasks render tasks.summary (set by done/fail) as a
  87. markdown completion-report card below the status/description grid —
  88. "Completion report" when done, "Failure summary" when failed, no
  89. card when empty; the summary renders through the shipped
  90. stm-markdown renderer (headings/code, no syntax leaks, HTML
  91. escaped) and the dashboard timeline snippets its first line
  92. Speed pass (plan 11, task 0):
  93. - SHARDING: the scenario groups are partitioned into seven independent
  94. bundles (pages, dispatch, subtasks, lineage, allocation, lifecycle,
  95. answers), each running in its own process against its own app
  96. instance, fake daemons and SQLite database. The default invocation
  97. runs all bundles in parallel and aggregates the verdicts and check
  98. counts into one exit code — meson sees a single green/red test.
  99. `--bundle NAME` runs one shard for debugging; WEBSTACK_SEQUENTIAL=1
  100. runs them in-process, one after another.
  101. - Within a bundle, scenario groups SHARE the app+daemon instance and
  102. carry per-group state as database rows (task/session/block
  103. fixtures), never process restarts; the one deliberate restart (the
  104. startup token migration) lives in the answers bundle.
  105. - EVENT-DRIVEN WAITS: wait_for polls at 50ms; the fixed sleeps were
  106. converted either to observable-condition waits (daemon-side
  107. counters, e.g. failed-delivery hits) or to quiet_window() — a
  108. bounded negative-assertion poll that FAILS LOUDLY the moment the
  109. event it guards against happens (a sleep could silently pass).
  110. - ENV KNOBS: SADDLE_DISPATCH_TICK_S=1 (dispatcher cadence; default 5
  111. in production), SADDLE_HTTP_TIMEOUT_S=2, SADDLE_LOST_WAKE_S=2,
  112. SADDLE_STALE_S=3, plus the fake daemon's scripted timings — the
  113. wire-traffic shapes stay realistic, just faster.
  114. """
  115. import json
  116. import os
  117. import re
  118. import shutil
  119. import socket
  120. import sqlite3
  121. import subprocess
  122. import sys
  123. import threading
  124. import time
  125. import urllib.error
  126. import urllib.parse
  127. import urllib.request
  128. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  129. # Web Push protocol verification (plan 11 task E): the test harness
  130. # owns the browser-side keys, so it can do everything the push service
  131. # does — decrypt the RFC 8291 body and verify the ES256 VAPID JWT.
  132. import base64
  133. from cryptography.hazmat.primitives import hashes
  134. from cryptography.hazmat.primitives.asymmetric import ec
  135. from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
  136. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  137. from cryptography.hazmat.primitives.kdf.hkdf import HKDF
  138. from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
  139. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  140. APP = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.join(REPO, "builddir", "clanker-saddle")
  141. # --- speed-pass tuning -----------------------------------------------------
  142. # The fake daemon's scripted timings and the dispatch-tick cadence the
  143. # quiet windows are sized against. All overridable for debugging.
  144. TICK_S = float(os.environ.get("SADDLE_DISPATCH_TICK_S", "1") or 1)
  145. FAKE_WORK_S = float(os.environ.get("WEBSTACK_FAKE_WORK_S", "1.2") or 1.2)
  146. FAKE_FAIL_S = float(os.environ.get("WEBSTACK_FAKE_FAIL_S", "0.5") or 0.5)
  147. FAKE_HEARTBEAT_S = float(os.environ.get("WEBSTACK_FAKE_HEARTBEAT_S", "0.4") or 0.4)
  148. FAKE_TRIGGER_S = float(os.environ.get("WEBSTACK_FAKE_TRIGGER_S", "0.05") or 0.05)
  149. SHARD_TIMEOUT_S = float(os.environ.get("WEBSTACK_SHARD_TIMEOUT_S", "600") or 600)
  150. def quiet_seconds():
  151. """A negative-assertion window spanning several dispatch ticks (the
  152. converted fixed sleeps were 3-7s at the old 5s tick; the bound never
  153. exceeds the old timeout)."""
  154. return min(2 * TICK_S + 0.8, 7.0)
  155. WORK = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  156. DB_PATH = os.path.join(WORK, "web.sqlite")
  157. passes = 0
  158. failures = 0
  159. def check(condition, label):
  160. global passes, failures
  161. if condition:
  162. passes += 1
  163. print("PASS %s" % label)
  164. else:
  165. failures += 1
  166. print("FAIL %s" % label)
  167. def free_port():
  168. with socket.socket() as sock:
  169. sock.bind(("127.0.0.1", 0))
  170. return sock.getsockname()[1]
  171. APP_PORT = free_port()
  172. DAEMON_PORT = free_port()
  173. WEB = "http://127.0.0.1:%d" % APP_PORT
  174. def bundle_env(name):
  175. """Point the module's runtime globals at one shard's scratch dir,
  176. database and ports (each bundle is a process with its own app,
  177. daemons and SQLite file)."""
  178. global WORK, DB_PATH, APP_PORT, DAEMON_PORT, WEB
  179. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  180. WORK = "%s-%s" % (base, name)
  181. DB_PATH = os.path.join(WORK, "web.sqlite")
  182. APP_PORT = free_port()
  183. DAEMON_PORT = free_port()
  184. WEB = "http://127.0.0.1:%d" % APP_PORT
  185. def http(method, url, data=None, headers=None, timeout=30):
  186. body = None
  187. if data is not None:
  188. pairs = []
  189. for k, v in data.items():
  190. for item in (v if isinstance(v, (list, tuple)) else [v]):
  191. pairs.append((k, item))
  192. body = "&".join("%s=%s" % (k, urllib.parse.quote(str(item))) for k, item in pairs).encode()
  193. request = urllib.request.Request(WEB + url if url.startswith("/") else url,
  194. data=body, method=method)
  195. if data is not None:
  196. request.add_header("Content-Type", "application/x-www-form-urlencoded")
  197. for key, value in (headers or {}).items():
  198. request.add_header(key, value)
  199. # Retry dropped/refused connections: the freshly started app can
  200. # close a very early keep-alive connection once while warming up,
  201. # and its first seconds can wobble under load.
  202. for attempt in range(3):
  203. try:
  204. with urllib.request.urlopen(request, timeout=timeout) as response:
  205. return response.status, response.read().decode()
  206. except urllib.error.HTTPError as error:
  207. return error.code, error.read().decode()
  208. except (urllib.error.URLError, OSError):
  209. if attempt >= 2:
  210. raise
  211. time.sleep(0.75)
  212. def directives(uri, auth=None):
  213. headers = {}
  214. if auth:
  215. headers["X-Statum-Slot"] = "key=%s; as_at=%s" % (auth["key"], auth["as_at"])
  216. status, body = http("GET", "/_statum/entrypoint?uri=" + urllib.parse.quote(uri.split("?")[0]),
  217. headers=headers)
  218. if status != 200:
  219. raise SystemExit("entrypoint %s -> HTTP %d: %s" % (uri, status, body[:300]))
  220. return json.loads(body)
  221. def slot_public(auth, uri, type_name):
  222. for directive in directives(uri, auth):
  223. if directive["type"] == "set":
  224. content = directive["snapshot_frame"].get("content")
  225. if not content:
  226. continue
  227. content = json.loads(content)
  228. if content["slot"]["type"] == type_name:
  229. return content["public"]
  230. raise SystemExit("no %s slot in entrypoint state for %s" % (type_name, uri))
  231. def act(auth, action, fields):
  232. headers = {"X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}
  233. if action.get("private"):
  234. headers["X-Statum-Private"] = action["private"]
  235. status, body = http(action.get("method", "POST"), action["uri"], fields, headers)
  236. if status != 200:
  237. raise SystemExit("action %s -> HTTP %d: %s" % (action["uri"], status, body[:300]))
  238. return json.loads(body)
  239. def login(username, password):
  240. frames = directives("/login")
  241. content = json.loads(frames[0]["snapshot_frame"]["content"])
  242. action = content["public"]["login"]
  243. status, body = http(action.get("method", "POST"), action["uri"],
  244. {"username": username, "password": password})
  245. if status != 200:
  246. raise SystemExit("login -> HTTP %d: %s" % (status, body[:300]))
  247. for directive in json.loads(body):
  248. if directive["type"] == "set":
  249. frame = json.loads(directive["snapshot_frame"]["content"])
  250. if frame["slot"]["type"] == "auth":
  251. return {"key": frame["slot"]["key"], "as_at": frame["as_at"]}
  252. raise SystemExit("login response carried no auth slot: " + body[:300])
  253. def wait_for(predicate, timeout=60, what="condition", interval=0.05):
  254. deadline = time.monotonic() + timeout
  255. last = None
  256. while time.monotonic() < deadline:
  257. last = predicate()
  258. if last is not False and last is not None:
  259. return last
  260. time.sleep(interval)
  261. print(" (timeout waiting for %s; last: %s)" % (what, last))
  262. dump_threads()
  263. return None
  264. def quiet_window(seconds, predicate, what):
  265. """A converted fixed sleep: asserts a NEGATIVE condition (nothing may
  266. happen) across a window spanning several dispatch ticks, polling at
  267. 50ms. The moment the condition breaks the window fails loudly
  268. (diagnostics + thread dump) instead of silently passing a sleep."""
  269. deadline = time.monotonic() + seconds
  270. while time.monotonic() < deadline:
  271. value = predicate()
  272. if value is False or value is None:
  273. remaining = deadline - time.monotonic()
  274. print(" (quiet window '%s' broken after %.2fs of %.2fs — the"
  275. " guarded event DID happen)" % (what, seconds - remaining, seconds))
  276. dump_threads()
  277. return False
  278. time.sleep(0.05)
  279. return True
  280. def dump_threads():
  281. """Stacks of suite threads not parked in sleep — pinpoints a wedged
  282. fake lifecycle when a wait times out."""
  283. import traceback
  284. shown = 0
  285. for thread_id, frame in sys._current_frames().items():
  286. stack = "".join(traceback.format_stack(frame)[-4:])
  287. if ("web_stack_test.py" in stack) and ("sleep" not in stack) and shown < 6:
  288. shown += 1
  289. print(" --- thread %s ---\n%s" % (thread_id, stack))
  290. def task_state(auth, task_id):
  291. return slot_public(auth, "/tasks/%d" % task_id, "task")
  292. def wait_task_done(auth, task_id, timeout=90):
  293. return wait_for(lambda: task_state(auth, task_id).get("status") == "done" or False,
  294. timeout=timeout, what="task %d -> done" % task_id)
  295. def task_id_of(title):
  296. conn = db()
  297. try:
  298. return conn.execute("select id from tasks where title = ?", (title,)).fetchone()[0]
  299. finally:
  300. conn.close()
  301. def enqueue_task(auth, task_id):
  302. """The human-only Enqueue action (plan 11): draft -> queued."""
  303. detail = task_state(auth, task_id)
  304. assert detail["status"] == "draft", "task %d not in draft (%s)" % (task_id, detail["status"])
  305. act(auth, detail["enqueue"], {})
  306. return task_state(auth, task_id)["status"]
  307. def create_queued(auth, fields):
  308. """Create via the queue form (lands in draft) and enqueue it — the
  309. standard 'this task should dispatch' fixture of the plan-11 world."""
  310. act(auth, slot_public(auth, "/tasks", "tasks")["create"], fields)
  311. task_id = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  312. if t["title"] == fields["title"]][0])
  313. enqueue_task(auth, task_id)
  314. return task_id
  315. def saddle_api(method, path, token, payload=None):
  316. """Raw call against the saddle ingest API; returns (status, json)."""
  317. request = urllib.request.Request(WEB + path,
  318. data=json.dumps(payload or {}).encode(), method=method)
  319. request.add_header("Content-Type", "application/json")
  320. if token is not None:
  321. request.add_header("Authorization", "Bearer " + token)
  322. try:
  323. with urllib.request.urlopen(request, timeout=15) as response:
  324. return response.status, json.loads(response.read().decode() or "{}")
  325. except urllib.error.HTTPError as error:
  326. body = error.read().decode()
  327. try:
  328. return error.code, json.loads(body)
  329. except ValueError:
  330. return error.code, {"raw": body}
  331. def db():
  332. return sqlite3.connect(DB_PATH)
  333. def http_get_page(auth, uri):
  334. """The compiled page HTML for a statum route (auth via the slot
  335. header), for asserting page-level embeds the slot state cannot
  336. see."""
  337. status, body = http("GET", uri, headers={
  338. "X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])})
  339. if status != 200:
  340. raise SystemExit("GET %s -> HTTP %d" % (uri, status))
  341. return body
  342. def saddle_card(auth, name):
  343. rows = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  344. if s["name"] == name]
  345. return rows[0]
  346. def queued_count():
  347. conn = db()
  348. try:
  349. return conn.execute(
  350. "select count(*) from tasks where status = 'queued'").fetchone()[0]
  351. finally:
  352. conn.close()
  353. def command_rows(session):
  354. conn = db()
  355. try:
  356. return conn.execute(
  357. "select command_text, type from session_commands"
  358. " where session_id = ? order by id", (session,)).fetchall()
  359. finally:
  360. conn.close()
  361. class FakeSaddle:
  362. """In-process saddle daemon implementing the wire contract.
  363. Phase-2 push behaviour: the daemon asks POST /api/saddle/next-task
  364. whenever idle-awake (at registration, on POST /wake, after its task
  365. reaches a terminal state, and when a /status probe observes it
  366. parked idle — throttled), accepts assignments like POST /start used
  367. to, then PUSHES its telemetry home: raw PTY chunks via POST
  368. /api/saddle/chunks and round results with state transitions via
  369. POST /api/saddle/results (working at round start, terminal states
  370. when the scripted lifecycle ends them). /output, /log and /start
  371. are gone (404) like a post-phase-2 daemon; /task-update serves the
  372. cancel/comment/subtask-status kinds; POST /answer receives a
  373. delivered verdict when the round is parked in a block's answer
  374. wait (409 when nothing waits — the real daemon's contract; the
  375. resumed round continues after the response). Every trigger can be
  376. disabled per test for determinism; ask_now() performs a
  377. synchronous manual ask.
  378. """
  379. PROMPT = "bbarrow@fedora:/workspace/task-1$ "
  380. def __init__(self):
  381. self.lock = threading.Lock()
  382. self.start_payloads = [] # captured assignment payloads (/start + next-task 200s)
  383. self.state = "idle"
  384. self.summary = ""
  385. self.state_entered = time.monotonic()
  386. self.fail_next = False # next task drives the task to failed
  387. self.start_counts = {} # task id -> assignment count
  388. self.resumed_pending = False # crash-resume flag on the next /status
  389. self.suspend_on_title = None # this task (by title) parks as suspended
  390. self.output_seq = 100 # daemon-global entry ids for pushed results
  391. self.last_activity_epoch = int(time.time())
  392. self.hang_next = {} # path suffix -> hang count (never responds)
  393. self.abort_failures = 0 # cancel task-updates failing (500) while > 0
  394. self.abort_log = [] # task ids aborted via task-update cancel
  395. self.running_task = 0 # task id the daemon believes it runs
  396. self.running_title = "" # its title (suspend targeting)
  397. self.session_id = None # the web-side run row of the running task
  398. self.hold_state = False # freeze lifecycle + heartbeat pushes
  399. self.ssh_public_key = "" # reported on /status + /register
  400. self.started_mono = time.monotonic()
  401. self.freeze_activity = False # hold last_activity_epoch still
  402. self.silent = False # suppress pushes (staleness tests)
  403. self.dead = False # kill(): no serving AND no calls home
  404. self.status_hits = 0 # GET /status arrivals (probe accounting)
  405. self.comment_log = [] # recorded /task-update comment payloads
  406. self.scripted_corpus = None # chunk batch pushed when a task starts
  407. # --- plan 10 phase 1: ask/wake/register ---
  408. self.token = None # per-saddle token from POST /register
  409. self.register_log = [] # recorded /register bodies
  410. self.wake_log = [] # recorded POST /wake arrivals
  411. self.asks = [] # [{"status": int, "payload": dict|None}]
  412. self.ask_on_register = True
  413. self.ask_on_wake = True
  414. self.ask_on_terminal = True
  415. self.ask_on_idle_status = True
  416. self.ask_delay = 0.0 # seconds; a slow daemon delays its wake-triggered ask
  417. self.serve_register = True # False: 404 /register (pre-flip daemon)
  418. self.last_ask_trigger = 0.0
  419. self.port = None
  420. self.ask_threads = [] # scheduled ask-trigger threads (settle_asks joins them)
  421. # --- answer delivery (the parked-session resume) ---
  422. self.pending_block = None # the block payload this daemon waits on (state blocked)
  423. self.answer_log = [] # recorded POST /answer bodies
  424. self.answer_push_delay = 0.2 # the resumed round's first push, after the response
  425. # --- plan 12: goal-agent scripting ---
  426. self.goal_script = [] # behaviours consumed per goal-run assignment
  427. self.goal_behaviour = None # the current round's popped behaviour
  428. self.goal_assignments = [] # captured goal-run assignment payloads
  429. def set_state(self, state, summary=None):
  430. """Advances the scripted lifecycle."""
  431. self.state = state
  432. if summary is not None:
  433. self.summary = summary
  434. self.state_entered = time.monotonic()
  435. def touch_activity(self):
  436. if not self.freeze_activity:
  437. self.last_activity_epoch = int(time.time())
  438. def queue_output(self, entry_type, command, output):
  439. """Pushes a typed entry as a round-results push (the daemon's
  440. entry log riding the results channel)."""
  441. with self.lock:
  442. entry = {
  443. "id": self.output_seq,
  444. "command": command,
  445. "output": output,
  446. "exit_code": 1,
  447. "type": entry_type,
  448. "timestamp": "2026-09-06T00:00:00Z",
  449. }
  450. self.output_seq += 1
  451. self.push_results(self.state if self.state in ("working",) else "working",
  452. entries=[entry])
  453. # --- plan 10 phase 2: the push channels ---
  454. def push_chunks(self, chunks):
  455. """Pushes raw PTY chunks home: elements are texts (assigned
  456. fresh seqs) or {seq, text} dicts (a redelivery or explicit
  457. corpus). Pushes are suppressed while silent/hold_state (the
  458. staleness tests' silent runner)."""
  459. if self.dead or self.silent or self.token is None or self.session_id is None:
  460. return
  461. batch = []
  462. with self.lock:
  463. for chunk in chunks:
  464. if isinstance(chunk, dict):
  465. batch.append({"seq": int(chunk["seq"]), "text": chunk["text"]})
  466. else:
  467. batch.append({"seq": self.next_push_seq(), "text": chunk})
  468. try:
  469. saddle_api("POST", "/api/saddle/chunks", self.token,
  470. {"session_id": self.session_id, "chunks": batch})
  471. except (OSError, ValueError):
  472. pass # app restarting / shutting down mid-test
  473. def next_push_seq(self):
  474. # The daemon-side chunk counter for ad-hoc pushes.
  475. self._push_seq = getattr(self, "_push_seq", 0) + 1
  476. return self._push_seq
  477. def push_results(self, state, entries=None, block=None, summary=None, session_id=None):
  478. """Pushes one round-results payload home (state transition plus
  479. its entries). Returns the HTTP status when it went out, None
  480. when suppressed."""
  481. if self.dead or self.silent:
  482. return None
  483. if self.token is None:
  484. return None
  485. target = session_id if session_id is not None else self.session_id
  486. if target is None:
  487. return None
  488. payload = {"session_id": target, "state": state}
  489. if entries is not None:
  490. payload["entries"] = entries
  491. if block is not None:
  492. payload["block"] = block
  493. if state == "blocked":
  494. # The daemon parks its round on this block's answer wait
  495. # (the real daemon's wait_for_answer).
  496. self.pending_block = dict(block)
  497. if summary is not None:
  498. payload["summary"] = summary
  499. try:
  500. status, _ = saddle_api("POST", "/api/saddle/results", self.token, payload)
  501. if status != 200:
  502. print(" [fake %s] push %s -> HTTP %s (task=%s)"
  503. % (self.port, state, status, self.running_task))
  504. return status
  505. except (OSError, ValueError) as error:
  506. print(" [fake %s] push %s failed: %r (task=%s)"
  507. % (self.port, state, error, self.running_task))
  508. return None
  509. # --- plan 10 phase 1: the ask path ---
  510. def ask_now(self):
  511. """Synchronously asks the web for work (a phase-1 daemon's idle
  512. ask). A 200 assignment is accepted exactly like POST /start;
  513. returns (status, payload|None)."""
  514. token = self.token
  515. if token is None:
  516. raise SystemExit("fake daemon asked before receiving its token")
  517. status, payload = saddle_api("POST", "/api/saddle/next-task", token)
  518. with self.lock:
  519. self.asks.append({"status": status, "payload": payload})
  520. if status == 200:
  521. self.accept_assignment(payload)
  522. return status, payload
  523. def _trigger_ask(self, reason):
  524. """Schedules a delayed ask (the daemon woke / went idle-awake).
  525. ask_delay models a SLOW asker — a daemon still winding down its
  526. round when the wake lands: it honours the wake, but its ask
  527. arrives late (still inside the web's lost-wake guard window)."""
  528. def run():
  529. if self.state in ("working", "failing"):
  530. return # a running daemon does not ask
  531. if self.ask_delay > 0:
  532. time.sleep(self.ask_delay)
  533. for attempt in range(3):
  534. try:
  535. status, _ = self.ask_now()
  536. if status in (200, 204):
  537. return
  538. print(" (ask %s -> HTTP %s, attempt %d)" % (reason, status, attempt + 1))
  539. except Exception as error: # app restarting / blips: retry
  540. print(" (ask %s failed: %r, attempt %d)" % (reason, error, attempt + 1))
  541. time.sleep(1.0)
  542. def starter():
  543. time.sleep(FAKE_TRIGGER_S)
  544. run()
  545. thread = threading.Thread(target=starter, daemon=True)
  546. with self.lock:
  547. self.ask_threads.append(thread)
  548. thread.start()
  549. def settle_asks(self, timeout=15):
  550. """Joins every ask-trigger thread scheduled so far — the
  551. event-driven replacement for the fixed sleeps that waited for
  552. in-flight asks to land after triggers were frozen."""
  553. with self.lock:
  554. threads = [t for t in self.ask_threads if t.is_alive()]
  555. deadline = time.monotonic() + timeout
  556. for thread in threads:
  557. thread.join(timeout=max(0.1, deadline - time.monotonic()))
  558. with self.lock:
  559. self.ask_threads = [t for t in self.ask_threads if t.is_alive()]
  560. return all(not thread.is_alive() for thread in threads)
  561. def maybe_trigger_ask(self, reason, throttle=False):
  562. """Schedules an idle-awake ask. Protocol events (wake, abort,
  563. round end, park) ask singularly and immediately; only the
  564. /status-observation path throttles (a burst of probes must not
  565. hammer the ask endpoint)."""
  566. now = time.monotonic()
  567. if throttle and now - self.last_ask_trigger < 1.0:
  568. return
  569. self.last_ask_trigger = now
  570. self._trigger_ask(reason)
  571. def accept_assignment(self, payload):
  572. """A 200 next-task assignment: adopted exactly like POST /start."""
  573. self.start_payloads.append(payload)
  574. task = payload.get("task") or {}
  575. task_id = task.get("id")
  576. self.running_task = int(task_id or 0)
  577. self.running_title = task.get("title") or ""
  578. self.session_id = payload.get("session_id")
  579. # The assignment's answers resolve any block this daemon was
  580. # parked on (resume-carries-answer).
  581. self.pending_block = None
  582. count = self.start_counts.get(task_id, 0) + 1
  583. self.start_counts[task_id] = count
  584. if count > 1:
  585. # Crash-resume contract: re-pushing a task whose
  586. # workspace still exists restores it; the first
  587. # /status after the restore reports "resumed": true.
  588. self.resumed_pending = True
  589. # Plan 12: a goal-run assignment plays its scripted behaviour
  590. # instead of the plain done push (plan submission, parking,
  591. # question, completion, failure — consumed one per round).
  592. self.goal_behaviour = None
  593. if payload.get("kind") == "goal_run":
  594. self.goal_assignments.append(payload)
  595. self.goal_behaviour = self.goal_script.pop(0) if self.goal_script else ("suspend",)
  596. self.set_state("failing" if self.fail_next else "working")
  597. self.fail_next = False
  598. # The round's opening telemetry: the flushed-so-far raw PTY
  599. # batch plus the working state push (>= 2 flushes per round
  600. # and the 10s timer are the real daemon's contract; the fake
  601. # pushes its batch up front and heartbeats while working).
  602. if self.scripted_corpus is not None:
  603. self.push_chunks([dict(chunk) for chunk in self.scripted_corpus])
  604. else:
  605. self.push_chunks([self.PROMPT, "echo hello\r\n", "hello\r\n"])
  606. self.push_results("working")
  607. class Handler(BaseHTTPRequestHandler):
  608. daemon = None # set on the class before serving
  609. protocol_version = "HTTP/1.1"
  610. def log_message(self, fmt, *args):
  611. pass
  612. def maybe_hang(self, path):
  613. """True when this request should hang forever (never respond),
  614. consuming one unit of the path's hang budget."""
  615. for suffix, count in list(self.daemon.hang_next.items()):
  616. if count > 0 and path.startswith(suffix):
  617. self.daemon.hang_next[suffix] = count - 1
  618. return True
  619. return False
  620. def _send(self, status, obj):
  621. body = json.dumps(obj).encode()
  622. self.send_response(status)
  623. self.send_header("Content-Type", "application/json")
  624. self.send_header("Content-Length", str(len(body)))
  625. self.end_headers()
  626. self.wfile.write(body)
  627. def do_POST(self):
  628. if self.maybe_hang(self.path):
  629. time.sleep(600)
  630. return
  631. self.daemon.touch_activity()
  632. length = int(self.headers.get("Content-Length") or 0)
  633. raw = self.rfile.read(length).decode() if length else "{}"
  634. if self.path == "/register":
  635. # Plan 10: the web delivers the per-saddle token + its
  636. # own base URL; the daemon persists the token for its
  637. # calls home and reports its ssh key + version.
  638. if not self.daemon.serve_register:
  639. self._send(404, {"error": "no such route"})
  640. return
  641. try:
  642. payload = json.loads(raw)
  643. except ValueError:
  644. payload = {"raw": raw}
  645. self.daemon.register_log.append(payload)
  646. if payload.get("saddle_token"):
  647. self.daemon.token = payload["saddle_token"]
  648. self._send(200, {"ok": True,
  649. "ssh_public_key": self.daemon.ssh_public_key,
  650. "version": "0.1-fake"})
  651. if self.daemon.ask_on_register:
  652. self.daemon.maybe_trigger_ask("register")
  653. return
  654. if self.path == "/wake":
  655. # Plan 10: a capable task is ready; a sleeping daemon
  656. # asks for work (immediately — a wake is a direct
  657. # command, never throttled).
  658. self.daemon.wake_log.append(time.monotonic())
  659. self._send(200, {"ok": True})
  660. if self.daemon.ask_on_wake:
  661. self.daemon.maybe_trigger_ask("wake")
  662. return
  663. if self.path == "/answer":
  664. # Plan 11 (daemon Task A): parks FREE the daemon, so no
  665. # block ever waits in-process — the verdict travels in
  666. # the resuming allocation's resume_notice. Always 409,
  667. # exactly like the real daemon's contract.
  668. try:
  669. payload = json.loads(raw)
  670. except ValueError:
  671. self._send(400, {"error": "bad json"})
  672. return
  673. self.daemon.answer_log.append({
  674. "refused": True,
  675. "answer": payload.get("answer", "")})
  676. self._send(409, {"error": "no block is waiting for an answer — parks resume via allocation"})
  677. return
  678. if self.path == "/task-update":
  679. # Plan 10: cancel (abort machinery) and comment
  680. # (injected turn) — delivered directly to a RUNNING
  681. # daemon, no auth.
  682. try:
  683. payload = json.loads(raw)
  684. except ValueError:
  685. self._send(400, {"error": "bad json"})
  686. return
  687. kind = payload.get("kind")
  688. if kind == "cancel":
  689. if self.daemon.abort_failures > 0:
  690. self.daemon.abort_failures -= 1
  691. self._send(500, {"error": "cancel failed (simulated)"})
  692. return
  693. aborted = self.daemon.running_task
  694. self.daemon.set_state("idle")
  695. self.daemon.summary = ""
  696. self.daemon.running_task = 0
  697. self.daemon.session_id = None
  698. self.daemon.abort_log.append(aborted)
  699. self._send(200, {"ok": True, "aborted_task_id": aborted})
  700. # An aborted daemon returns to its idle loop: it asks.
  701. self.daemon.maybe_trigger_ask("aborted")
  702. elif kind == "comment":
  703. self.daemon.comment_log.append(payload)
  704. self._send(200, {"ok": True})
  705. else:
  706. self._send(400, {"error": "unknown task-update kind"})
  707. return
  708. self._send(404, {"error": "no such route"})
  709. self.close_connection = True
  710. def do_GET(self):
  711. if self.maybe_hang(self.path):
  712. time.sleep(600)
  713. return
  714. if self.path != "/status":
  715. # /status itself is not daemon activity: the liveness
  716. # signal must reflect loop rounds / command completions.
  717. self.daemon.touch_activity()
  718. if self.path == "/status":
  719. self.daemon.status_hits += 1
  720. response = {"state": self.daemon.state, "summary": self.daemon.summary,
  721. "uptime_seconds": int(time.monotonic() - self.daemon.started_mono),
  722. "last_activity_epoch": self.daemon.last_activity_epoch,
  723. "ssh_public_key": self.daemon.ssh_public_key}
  724. if getattr(self.daemon, "status_extra", None):
  725. response.update(self.daemon.status_extra)
  726. if self.daemon.resumed_pending:
  727. response["resumed"] = True
  728. self.daemon.resumed_pending = False
  729. # A parked/terminal daemon is idle-awake: a phase-1
  730. # daemon asks (and sleeps on 204). Throttled so status
  731. # poll bursts do not hammer the ask endpoint.
  732. if self.daemon.ask_on_idle_status and self.daemon.state in (
  733. "idle", "done", "failed", "suspended"):
  734. self.daemon.maybe_trigger_ask("idle-status", throttle=True)
  735. self._send(200, response)
  736. else:
  737. self._send(404, {"error": "no such route"})
  738. self.close_connection = True
  739. def run_lifecycle(self):
  740. """Applies the scripted lifecycle on a timer (like a real daemon
  741. whose task ends on its own): working heartbeats chunks (the
  742. flush timer's stand-in, keeping the staleness clock fed), works
  743. for FAKE_WORK_S, then pushes done/suspended; failing pushes
  744. failed after FAKE_FAIL_S — and a task END makes the idle-awake
  745. daemon ask again."""
  746. while True:
  747. time.sleep(0.1)
  748. if self.hold_state or self.silent:
  749. # hold_state freezes the script; silent models a daemon
  750. # mid-round with nothing to flush — its round has not
  751. # ended, so no terminal push fires while quiet.
  752. continue
  753. if self.state == "failing":
  754. if time.monotonic() - self.state_entered >= FAKE_FAIL_S:
  755. self.set_state("failed", "bash -n rejected the script (simulated)")
  756. self.push_results("failed",
  757. summary="bash -n rejected the script (simulated)")
  758. if self.ask_on_terminal:
  759. self.maybe_trigger_ask("terminal")
  760. elif self.state == "working":
  761. if time.monotonic() - self.state_entered >= FAKE_WORK_S:
  762. if self.goal_behaviour is not None:
  763. # A goal-agent round: play the scripted
  764. # behaviour (the results channel carries the
  765. # goal-context verbs).
  766. behaviour, self.goal_behaviour = self.goal_behaviour, None
  767. kind = behaviour[0]
  768. if kind == "plan":
  769. self.set_state("blocked")
  770. self.push_results("blocked", block={
  771. "type": "plan",
  772. "question": "Plan submitted for review",
  773. "body": behaviour[1]})
  774. if self.ask_on_idle_status:
  775. self.maybe_trigger_ask("parked")
  776. elif kind == "question":
  777. self.set_state("blocked")
  778. self.push_results("blocked", block={
  779. "type": "question",
  780. "question": behaviour[1],
  781. "options": list(behaviour[2])
  782. if len(behaviour) > 2 else None})
  783. if self.ask_on_idle_status:
  784. self.maybe_trigger_ask("parked")
  785. elif kind == "suspend":
  786. self.set_state("suspended")
  787. self.push_results("suspended")
  788. if self.ask_on_idle_status:
  789. self.maybe_trigger_ask("parked")
  790. elif kind == "fail":
  791. self.set_state("failed", behaviour[1])
  792. self.push_results("failed", summary=behaviour[1])
  793. if self.ask_on_terminal:
  794. self.maybe_trigger_ask("terminal")
  795. else: # "done": the completion report
  796. self.set_state("done", behaviour[1])
  797. self.push_results("done", summary=behaviour[1])
  798. if self.ask_on_terminal:
  799. self.maybe_trigger_ask("terminal")
  800. elif self.suspend_on_title and self.suspend_on_title == self.running_title:
  801. # `saddle suspend`: park until a fresh assignment
  802. # resumes the workspace (title-targeted one-shot,
  803. # so an interleaved dispatch cannot eat the flag).
  804. self.set_state("suspended")
  805. self.suspend_on_title = None
  806. self.push_results("suspended")
  807. # A parked daemon is idle-awake: it asks (and
  808. # sleeps on 204) so a later wake can reach it.
  809. if self.ask_on_idle_status:
  810. self.maybe_trigger_ask("parked")
  811. else:
  812. self.set_state("done", "fake daemon finished")
  813. self.push_results("done", summary="fake daemon finished")
  814. if self.ask_on_terminal:
  815. self.maybe_trigger_ask("terminal")
  816. elif time.monotonic() - getattr(self, "last_heartbeat", 0) >= FAKE_HEARTBEAT_S:
  817. # The flush timer: output keeps flowing, so chunks
  818. # keep arriving (the staleness window never opens on
  819. # a healthy runner).
  820. self.last_heartbeat = time.monotonic()
  821. self.push_chunks(["working-heartbeat\r\n"])
  822. def serve(self, port=None):
  823. """Binds the daemon's HTTP server. A requested port that is
  824. already taken (free_port() hands out recyclable ports — two
  825. calls can collide) falls back to an OS-assigned one instead of
  826. silently dying and impersonating whatever owns that port."""
  827. if port is None:
  828. port = DAEMON_PORT
  829. handler = type("BoundHandler", (FakeSaddle.Handler,), {"daemon": self})
  830. self.server = None
  831. try:
  832. self.server = ThreadingHTTPServer(("127.0.0.1", port), handler)
  833. except OSError:
  834. print("(fake daemon: port %d taken, falling back)" % port)
  835. self.server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
  836. self.port = self.server.server_address[1]
  837. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  838. threading.Thread(target=self.run_lifecycle, daemon=True).start()
  839. return self.server
  840. def kill(self):
  841. """The daemon dies: it stops listening (connections refused) AND
  842. stops calling home — no pushes, no asks (a dead process has no
  843. outbound anything; in-flight handler threads may linger but the
  844. wire contract's traffic is one-directional now)."""
  845. self.dead = True
  846. if getattr(self, "server", None) is not None:
  847. self.server.shutdown()
  848. self.server.server_close()
  849. self.server = None
  850. def start_app():
  851. config = json.load(open(os.path.join(REPO, "web-config.json")))
  852. config["saddle_callback_base_url"] = WEB
  853. with open(os.path.join(WORK, "web-config.json"), "w") as handle:
  854. json.dump(config, handle)
  855. env = dict(os.environ)
  856. env.update({
  857. "SPRY_DB_PATH": DB_PATH,
  858. "SPRY_SEED_ADMIN_USERNAME": "admin",
  859. "SPRY_SEED_ADMIN_PASSWORD": "adminpass123",
  860. "SADDLE_LLM_BASE_URL": "http://127.0.0.1:%d" % DAEMON_PORT,
  861. "SADDLE_PROJECTS_ROOT": os.path.join(WORK, "workspace"),
  862. "SADDLE_HTTP_TIMEOUT_S": "2",
  863. "SADDLE_LOST_WAKE_S": "2",
  864. "SADDLE_STALE_S": "3",
  865. "SADDLE_DISPATCH_TICK_S": "1",
  866. # Plan 12: the goal-agent resume coalescing window shrinks to
  867. # one second so the event-driven resume tests settle quickly.
  868. "SADDLE_GOAL_RESUME_S": os.environ.get("SADDLE_GOAL_RESUME_S", "1"),
  869. # Never inherit a caller-poisoned LD_LIBRARY_PATH (e.g. one that
  870. # resolves the ancient /lib64 copies): empty makes the loader use
  871. # the binary's RUNPATH, which is the dev stack it was built
  872. # against.
  873. "LD_LIBRARY_PATH": "",
  874. })
  875. log_previous = os.path.join(WORK, "app.log.1")
  876. if os.path.exists(os.path.join(WORK, "app.log")):
  877. shutil.move(os.path.join(WORK, "app.log"), log_previous)
  878. log = open(os.path.join(WORK, "app.log"), "w")
  879. command = [APP, str(APP_PORT)]
  880. if os.environ.get("WEBSTACK_GDB"):
  881. # Debugging aid: run the app under gdb; a crash backtrace lands in
  882. # app.log. WEBSTACK_GDB=1 meson test ... to enable.
  883. command = ["gdb", "-batch", "-quiet",
  884. "-ex", "handle SIGPIPE nostop noprint pass",
  885. "-ex", "run", "-ex", "bt", "--args", APP, str(APP_PORT)]
  886. process = subprocess.Popen(command, cwd=WORK, env=env,
  887. stdout=log, stderr=subprocess.STDOUT)
  888. outcome = wait_for(lambda: (app_ready() and "ready")
  889. or (process.poll() is not None and "app-exited-%d" % process.poll())
  890. or False, timeout=30, what="app ready")
  891. if outcome is None:
  892. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  893. if str(outcome).startswith("app-exited-"):
  894. raise SystemExit("app exited during startup (%s); see %s/app.log"
  895. % outcome, WORK)
  896. return process
  897. def app_ready():
  898. try:
  899. status, _ = http("GET", "/login", timeout=3)
  900. return status == 200
  901. except (urllib.error.URLError, OSError):
  902. return False
  903. def dump_app_stacks(pid):
  904. """Best-effort thread backtrace of the (possibly wedged) app."""
  905. try:
  906. fds = os.listdir("/proc/%d/fd" % pid)
  907. print("(app open fds at dump: %d)" % len(fds))
  908. kinds = {}
  909. for fd in fds[:1200]:
  910. try:
  911. target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
  912. except OSError:
  913. continue
  914. key = target.split(":", 1)[0] if ":" in target else target
  915. kinds[key] = kinds.get(key, 0) + 1
  916. print("(fd kinds: %s)" % sorted(kinds.items(), key=lambda kv: -kv[1])[:6])
  917. except OSError:
  918. pass
  919. for command in (["eu-stack", "-p", str(pid)],
  920. ["gdb", "-batch", "-quiet", "-p", str(pid),
  921. "-ex", "thread apply all bt"]):
  922. try:
  923. out = subprocess.run(command, capture_output=True, timeout=60)
  924. text = out.stdout.decode(errors="replace") + out.stderr.decode(errors="replace")
  925. if text.strip():
  926. print("(app stacks via %s)\n%s" % (command[0], text[:12000]))
  927. return
  928. except (OSError, subprocess.SubprocessError):
  929. continue
  930. # =============================================================================
  931. # Fake push service + Web Push protocol helpers (plan 11 task E)
  932. # =============================================================================
  933. def b64url(raw):
  934. return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
  935. def b64url_dec(text):
  936. return base64.urlsafe_b64decode(text + "=" * ((4 - len(text) % 4) % 4))
  937. class FakePushService:
  938. """In-process Web Push endpoint server: every subscription the tests
  939. register points at a path here (a distinct "browser endpoint").
  940. Responses are scriptable per path — a fixed status (the 410-prune
  941. fixture) or N transient 500s (the retry-next-tick fixture)."""
  942. def __init__(self):
  943. self.requests = [] # [{"path", "headers", "body", "at"}]
  944. self.fail_next = {} # path -> remaining 500s
  945. self.status_for = {} # path -> fixed status
  946. self.lock = threading.Lock()
  947. self.port = None
  948. self.server = None
  949. def serve(self):
  950. service = self
  951. class Handler(BaseHTTPRequestHandler):
  952. protocol_version = "HTTP/1.1"
  953. def log_message(self, fmt, *args):
  954. pass
  955. def do_POST(self):
  956. length = int(self.headers.get("Content-Length") or 0)
  957. body = self.rfile.read(length)
  958. status = 201
  959. if self.path in service.status_for:
  960. status = service.status_for[self.path]
  961. elif service.fail_next.get(self.path, 0) > 0:
  962. service.fail_next[self.path] -= 1
  963. status = 500
  964. with service.lock:
  965. service.requests.append({
  966. "path": self.path,
  967. "headers": {key.lower(): value
  968. for key, value in self.headers.items()},
  969. "body": body,
  970. "at": time.monotonic(),
  971. })
  972. payload = b"{}"
  973. self.send_response(status)
  974. self.send_header("Content-Type", "application/json")
  975. self.send_header("Content-Length", str(len(payload)))
  976. self.end_headers()
  977. self.wfile.write(payload)
  978. self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
  979. self.port = self.server.server_address[1]
  980. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  981. return self.server
  982. def url(self, path):
  983. return "http://127.0.0.1:%d%s" % (self.port, path)
  984. def hits(self, prefix):
  985. with self.lock:
  986. return [request for request in self.requests
  987. if request["path"].startswith(prefix)]
  988. def decrypt_webpush(request, client_private_key, client_public, auth_secret):
  989. """RFC 8291 decryption of one captured push: returns
  990. (record_size, payload dict) — the payload builder's exact output."""
  991. body = request["body"]
  992. salt = body[:16]
  993. record_size = int.from_bytes(body[16:20], "big")
  994. key_id_len = body[20]
  995. eph_public = body[21:21 + key_id_len]
  996. ciphertext = body[21 + key_id_len:]
  997. eph_point = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(),
  998. eph_public)
  999. shared = client_private_key.exchange(ec.ECDH(), eph_point)
  1000. info = b"WebPush: info\x00" + eph_public + client_public
  1001. cek = HKDF(algorithm=hashes.SHA256(), length=16, salt=salt,
  1002. info=info).derive(shared + auth_secret)
  1003. nonce = HKDF(algorithm=hashes.SHA256(), length=12, salt=salt,
  1004. info=info).derive(shared + auth_secret)
  1005. plaintext = AESGCM(cek).decrypt(nonce, ciphertext, None)
  1006. return record_size, json.loads(plaintext[:-1]) # strip the 0x02 delimiter
  1007. def verify_vapid(request, vapid_public, vapid_private):
  1008. """Verifies the ES256 VAPID JWT on one captured push; returns its
  1009. claims dict (aud/exp/sub) — raises on a bad signature."""
  1010. header = request["headers"].get("authorization", "")
  1011. assert header.startswith("vapid t="), "no vapid authorization header"
  1012. token_part = header[len("vapid t="):].split(",")[0]
  1013. sent_key = header.split("k=")[1]
  1014. head_b64, claims_b64, sig_b64 = token_part.split(".")
  1015. signature = b64url_dec(sig_b64)
  1016. key = ec.derive_private_key(
  1017. int.from_bytes(b64url_dec(vapid_private), "big"), ec.SECP256R1())
  1018. key.public_key().verify(
  1019. encode_dss_signature(int.from_bytes(signature[:32], "big"),
  1020. int.from_bytes(signature[32:], "big")),
  1021. (head_b64 + "." + claims_b64).encode(),
  1022. ec.ECDSA(hashes.SHA256()))
  1023. claims = json.loads(b64url_dec(claims_b64))
  1024. assert sent_key == vapid_public, "the k= key is not the app's VAPID key"
  1025. return claims
  1026. def action_notify(result):
  1027. """The message of the first notify directive an action returned."""
  1028. for directive in result:
  1029. if directive.get("type") == "notify":
  1030. return directive.get("message", "")
  1031. return None
  1032. # =============================================================================
  1033. # Shard orchestration
  1034. # =============================================================================
  1035. class Ctx:
  1036. """Per-bundle shared fixtures: the app process, the admin auth slot
  1037. and the primary fake saddle (registered + token delivered)."""
  1038. def start_bundle(name):
  1039. """Boots one shard's environment: scratch dir, database, ports, the
  1040. primary fake daemon and the app, then the shared fixtures every
  1041. bundle builds on (the demo project + the registered fake saddle).
  1042. Scenario groups inside the bundle share this app+daemon instance
  1043. and sequence their state as DB rows, never process restarts."""
  1044. global APP_PORT, WEB, DAEMON_PORT
  1045. bundle_env(name)
  1046. fake = FakeSaddle()
  1047. fake.serve()
  1048. DAEMON_PORT = fake.port # the actually-bound port (fallback-safe)
  1049. # A rare framework-level crash (stack corruption in Statum slot
  1050. # signing during the FIRST login — shared-library codegen bug, moved
  1051. # twice already) kills the app before any test runs; a clean restart
  1052. # (with fresh ports) sidesteps it. Only tolerated while nothing has
  1053. # been checked yet.
  1054. auth = None
  1055. app = None
  1056. for attempt in range(3):
  1057. APP_PORT = free_port()
  1058. WEB = "http://127.0.0.1:%d" % APP_PORT
  1059. if os.path.exists(WORK):
  1060. shutil.rmtree(WORK)
  1061. os.makedirs(os.path.join(WORK, "workspace"))
  1062. try:
  1063. app = start_app()
  1064. auth = login("admin", "adminpass123")
  1065. break
  1066. except (SystemExit, OSError, urllib.error.URLError):
  1067. if passes > 0:
  1068. raise
  1069. if app is not None and app.poll() is None:
  1070. app.terminate()
  1071. try:
  1072. app.wait(timeout=5)
  1073. except subprocess.TimeoutExpired:
  1074. app.kill()
  1075. app = None
  1076. print("(app died before login; restarting cleanly, attempt %d)" % (attempt + 1))
  1077. if app is None or auth is None:
  1078. raise SystemExit("app never came up; see %s/app.log" % WORK)
  1079. state = slot_public(auth, "/projects", "projects")
  1080. act(auth, state["create"], {
  1081. "name": "demo",
  1082. "git_url": "https://example.com/demo.git",
  1083. "default_branch": "main",
  1084. })
  1085. saddles_state = slot_public(auth, "/saddles", "saddles")
  1086. act(auth, saddles_state["register"], {"name": "fake-saddle",
  1087. "host": "127.0.0.1:%d" % fake.port})
  1088. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1089. if s["name"] == "fake-saddle"]
  1090. if wait_for(lambda: len(fake.register_log) > 0 or False,
  1091. timeout=15, what="/register delivery") is None:
  1092. raise SystemExit("fake saddle never received /register")
  1093. ctx = Ctx()
  1094. ctx.name = name
  1095. ctx.app = app
  1096. ctx.auth = auth
  1097. ctx.fake = fake
  1098. ctx.fake_id = int(registered[0]["id"])
  1099. ctx.fake_token = registered[0]["token"]
  1100. return ctx
  1101. # =============================================================================
  1102. # Bundle: pages — block presentation, diff URLs, computed display state,
  1103. # terminal rendering (rejected entries, ANSI SGR), task-page layout and
  1104. # the /poll verdict channel. Fixture-driven: tasks and sessions are
  1105. # inserted as rows; only the rejected-ride scenario dispatches.
  1106. # =============================================================================
  1107. def bundle_pages(ctx):
  1108. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  1109. app = ctx.app
  1110. check(True, "login yields an auth slot")
  1111. print("== plan blocks: every task's saddle plan parks for acceptance ==")
  1112. conn = db()
  1113. conn.execute("insert into tasks (project_id, title, status, priority,"
  1114. " created_at)"
  1115. " values (1, 'Plan review task', 'working', 5,"
  1116. " strftime('%s','now'))")
  1117. plan_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1118. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  1119. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  1120. (plan_task, fake_id))
  1121. conn.commit()
  1122. session_id = conn.execute("select max(id) from sessions").fetchone()[0]
  1123. conn.close()
  1124. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1125. {"type": "block", "session_id": session_id, "data": {
  1126. "question": "Plan submitted for review",
  1127. "type": "plan",
  1128. "body": "# The plan\n\n1. Do it"}})
  1129. check(status == 200 and body.get("block_id"), "plan block raised")
  1130. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1131. {"type": "block", "session_id": session_id, "data": {
  1132. "question": "Which database?",
  1133. "type": "question",
  1134. "options": ["SQLite", "Postgres"],
  1135. "body": "# Storage choice"}})
  1136. check(status == 200, "question block raised")
  1137. detail = task_state(auth, plan_task)
  1138. blocks = {b["block_type"]: b for b in detail["blocks"]}
  1139. check(blocks["plan"].get("is_plan_review") is True,
  1140. "plan block flagged as the plan review")
  1141. check(blocks["plan"].get("show_body") is False,
  1142. "pending plan review hides the duplicate body preview")
  1143. check(blocks["question"].get("show_body") is True,
  1144. "question block keeps its body preview")
  1145. # Accept stores the stable approval wording as the answer (it
  1146. # becomes the resume notice the daemon reads; task-level plans are
  1147. # gone — the goal owns the approved markdown).
  1148. act(auth, blocks["plan"]["answer_action"],
  1149. {"answer": "Plan approved. Proceed with implementation."})
  1150. detail = task_state(auth, plan_task)
  1151. plan_block = [b for b in detail["blocks"] if b["block_type"] == "plan"][0]
  1152. check(plan_block.get("show_body") is True,
  1153. "answered plan review shows the body again (review section gone)")
  1154. check(plan_block.get("answered") is True
  1155. and plan_block.get("answer") == "Plan approved. Proceed with implementation.",
  1156. "accept stores the stable approval wording (the resume notice)")
  1157. print("== B1: highlight-to-comment quote dialog ==")
  1158. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  1159. check(status == 200 and "quote-comment-dialog" in page and "quote-text" in page,
  1160. "task page carries the quote-comment dialog the popover opens")
  1161. check('name="quote"' in page and 'name="return_to"' in page,
  1162. "quote dialog posts the quote and return-to fields")
  1163. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1164. check(status == 200 and "quote-comment-dialog" in page,
  1165. "terminal page keeps its quote dialog")
  1166. print("== B3: review section hides the duplicate body ==")
  1167. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1168. {"type": "block", "session_id": session_id, "data": {
  1169. "question": "Review the diff",
  1170. "type": "review",
  1171. "body": "# The change\n\nReworks the flange module."}})
  1172. check(status == 200 and body.get("block_id"), "review block raised")
  1173. detail = task_state(auth, plan_task)
  1174. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  1175. check(detail.get("review_pending") is True,
  1176. "review section shows while the review is unanswered")
  1177. check(review_block.get("show_body") is False,
  1178. "pending review block hides its duplicate body preview")
  1179. check(review_block.get("body", "").startswith("# The change"),
  1180. "review body itself still arrives in state (B2 counterpart)")
  1181. act(auth, review_block["answer_action"],
  1182. {"answer": "Review approved. Continue with the task."})
  1183. detail = task_state(auth, plan_task)
  1184. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  1185. check(review_block.get("show_body") is True,
  1186. "answered review shows the body again (banner gone)")
  1187. print("== B2: question block body above options ==")
  1188. # Contract side (A2 will restore bodies end-to-end): a question
  1189. # block raised with a heredoc body carries it; the body preview
  1190. # rides above the options (template order) and survives answering
  1191. # alongside the selected answer.
  1192. detail = task_state(auth, plan_task)
  1193. question = [b for b in detail["blocks"] if b["block_type"] == "question"][0]
  1194. check(question.get("body") == "# Storage choice"
  1195. and question.get("show_body") is True,
  1196. "question block keeps its body markdown with the preview on")
  1197. act(auth, question["answer_action"], {"option": "SQLite"})
  1198. detail = task_state(auth, plan_task)
  1199. question = [b for b in detail["blocks"] if b["block_type"] == "question"][0]
  1200. check(question.get("answered") is True and question.get("answer") == "SQLite"
  1201. and question.get("body") == "# Storage choice"
  1202. and question.get("show_body") is True,
  1203. "answered question shows body + selected answer")
  1204. print("== B5: compare-changes SSH -> HTTPS ==")
  1205. def diff_url_for_project(git_url, suffix):
  1206. state = slot_public(auth, "/projects", "projects")
  1207. act(auth, state["create"], {"name": "diff-%s" % suffix, "git_url": git_url})
  1208. project_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1209. if p["name"] == "diff-%s" % suffix][0])
  1210. conn = db()
  1211. conn.execute("insert into tasks (project_id, title, status, task_branch,"
  1212. " branch_from, created_at) values (?, ?, 'working', 'feature/x',"
  1213. " 'main', strftime('%s','now'))", (project_id, "Diff %s" % suffix))
  1214. conn.commit()
  1215. task_id = conn.execute("select max(id) from tasks").fetchone()[0]
  1216. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at,"
  1217. " outcome) values (?, ?, strftime('%s','now'), strftime('%s','now'),"
  1218. " 'done')", (task_id, fake_id))
  1219. conn.commit()
  1220. session = conn.execute("select max(id) from sessions").fetchone()[0]
  1221. conn.close()
  1222. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1223. {"type": "block", "session_id": session, "data": {
  1224. "question": "Review the diff", "type": "review"}})
  1225. return task_state(auth, task_id).get("review_diff_url") or ""
  1226. check(diff_url_for_project("ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git",
  1227. "fabrica")
  1228. == "https://fabrica.unitatem.net/clanker/clanker-saddle/compare/main...feature/x",
  1229. "ssh://git@host:port/owner/repo.git translates (port dropped)")
  1230. check(diff_url_for_project("git@github.com:acme/widgets.git", "scp")
  1231. == "https://github.com/acme/widgets/compare/main...feature/x",
  1232. "git@host:owner/repo.git translates to the browse host")
  1233. check(diff_url_for_project("https://example.com/plain/repo", "plain")
  1234. == "https://example.com/plain/repo/compare/main...feature/x",
  1235. "HTTPS URLs pass through unchanged")
  1236. print("== B6: computed display state ==")
  1237. # Draft tasks display as draft (plan 11) and never dispatch.
  1238. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1239. "project_id": "1",
  1240. "title": "Draft display task",
  1241. "priority": "5",
  1242. })
  1243. draft_display = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1244. if t["title"] == "Draft display task"][0])
  1245. detail = task_state(auth, draft_display)
  1246. check(detail["status"] == "draft" and detail.get("display") == "draft",
  1247. "new tasks default to draft and display it")
  1248. check(detail.get("draft") is True and detail.get("enqueue") is not None
  1249. and detail.get("delete") is not None,
  1250. "draft tasks expose the enqueue + delete actions")
  1251. check(quiet_window(quiet_seconds(),
  1252. lambda: task_state(auth, draft_display)["status"] == "draft",
  1253. "draft task never dispatches"),
  1254. "a draft task is never dispatched or woken for")
  1255. # Plan 12: the waiting-on-drafts block is deleted (goal tasks are
  1256. # the goal agent's to sequence); a parked task displays plainly.
  1257. conn = db()
  1258. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1259. " values (1, 'Parked plain task', 'suspended', 5, strftime('%s','now'))")
  1260. conn.commit()
  1261. conn.close()
  1262. parked_id = db().execute("select max(id) from tasks").fetchone()[0]
  1263. detail = task_state(auth, parked_id)
  1264. check(detail.get("display") == "parked",
  1265. "a suspended task displays as parked (%s)" % detail.get("display"))
  1266. dash = slot_public(auth, "/", "dashboard")
  1267. check(not dash.get("waiting_drafts"),
  1268. "the waiting-on-drafts block is gone from the dashboard data")
  1269. status, home_page = http("GET", "/", timeout=15)
  1270. check(status == 200 and "Waiting on subtasks to be enqueued" not in home_page,
  1271. "the dashboard renders no waiting-on-drafts section")
  1272. conn = db()
  1273. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1274. " values (1, 'Parent', 'done', 5, strftime('%s','now'))")
  1275. parent6 = conn.execute("select max(id) from tasks").fetchone()[0]
  1276. # The post-mortem case: stored done WITH an unanswered review block.
  1277. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  1278. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  1279. (parent6, fake_id))
  1280. session6 = conn.execute("select max(id) from sessions").fetchone()[0]
  1281. conn.commit()
  1282. conn.close()
  1283. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1284. {"type": "block", "session_id": session6, "data": {
  1285. "question": "Review the final diff", "type": "review"}})
  1286. detail = task_state(auth, parent6)
  1287. check(detail.get("display") == "review requested" and detail.get("terminal") is True,
  1288. "unanswered review overrides the stored done status (terminal flag keeps stored truth)")
  1289. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1290. if int(t["id"]) == parent6][0]
  1291. check(queue["display"] == "review requested",
  1292. "queue row shows the computed review-requested display")
  1293. # With the review answered the display falls back to the stored
  1294. # status (the plan-12 shape: no subtask-delegation states).
  1295. conn = db()
  1296. conn.execute("update task_blocks set answered_at = strftime('%s','now'),"
  1297. " answer = 'Human approved the review' where task_id = ?", (parent6,))
  1298. conn.commit()
  1299. conn.close()
  1300. detail = task_state(auth, parent6)
  1301. check(detail.get("display") == "done" and detail.get("terminal") is True,
  1302. "answered review falls back to the stored done display (%s)"
  1303. % detail.get("display"))
  1304. # Flags track the stored status on failure.
  1305. conn = db()
  1306. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  1307. " where id = ?", (parent6,))
  1308. conn.commit()
  1309. conn.close()
  1310. detail = task_state(auth, parent6)
  1311. check(detail.get("display") == "failed" and detail.get("failed") is True
  1312. and detail.get("terminal") is True,
  1313. "failed task with answered review shows failed + terminal flags")
  1314. print("== rejected entries (non-fatal) ==")
  1315. # Ingest API: a rejected entry stores on the session and streams
  1316. # through SSE; the task is untouched.
  1317. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1318. {"type": "output", "session_id": session_id, "data": {
  1319. "command": "bash -n script.sh",
  1320. "output": "syntax error near line 3 (recoverable)",
  1321. "exit_code": 1,
  1322. "type": "rejected"}})
  1323. check(status == 200, "rejected entry accepted by the ingest API")
  1324. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1325. with urllib.request.urlopen(request, timeout=15) as stream:
  1326. rejected_event = None
  1327. deadline = time.monotonic() + 8
  1328. while time.monotonic() < deadline and rejected_event is None:
  1329. line = stream.readline().decode().strip()
  1330. if not line.startswith("data: ") or line == "data: ping":
  1331. continue
  1332. event = json.loads(line[6:])
  1333. if event.get("type") == "rejected":
  1334. rejected_event = event
  1335. check(rejected_event is not None
  1336. and "syntax error near line 3" in (rejected_event.get("output") or ""),
  1337. "terminal stream carries rejected entries with their reason")
  1338. # The page template renders them with the distinct non-fatal style.
  1339. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1340. check(status == 200 and "term-rejected" in page,
  1341. "terminal page renders rejected entries in their own style")
  1342. print("== B8: ANSI SGR in the terminal view ==")
  1343. # Byte-exact SGR delivery: the daemon's coloured chunks flow through
  1344. # the store + SSE untouched (the client renderer styles them).
  1345. coloured = "\x1b[1;32mbold green\x1b[0m then \x1b[38;5;196m256-red\x1b[0m\n"
  1346. conn = db()
  1347. conn.execute("insert into session_raw_log (session_id, seq, chunk)"
  1348. " values (?, 900, ?)", (session_id, coloured))
  1349. conn.commit()
  1350. conn.close()
  1351. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1352. with urllib.request.urlopen(request, timeout=15) as stream:
  1353. coloured_event = None
  1354. deadline = time.monotonic() + 8
  1355. while time.monotonic() < deadline and coloured_event is None:
  1356. line = stream.readline().decode().strip()
  1357. if not line.startswith("data: ") or line == "data: ping":
  1358. continue
  1359. event = json.loads(line[6:])
  1360. if event.get("type") == "raw" and "\x1b[1;32m" in (event.get("text") or ""):
  1361. coloured_event = event
  1362. check(coloured_event is not None
  1363. and "\x1b[38;5;196m" in coloured_event["text"],
  1364. "SGR sequences stream byte-exact to the client renderer")
  1365. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1366. check(status == 200 and "makeAnsiRenderer" in page and "colour256" in page,
  1367. "terminal page embeds the ANSI renderer (SGR + 256-colour palette)")
  1368. # Dispatch path: a rejected entry in a round's results push flows
  1369. # into the audit trail without failing (or finishing) the task.
  1370. task_id_tmp = create_queued(auth, {
  1371. "project_id": "1",
  1372. "title": "Rejected ride",
  1373. "priority": "2",
  1374. })
  1375. rejected_task = task_id_tmp
  1376. check(wait_for(lambda: task_state(auth, rejected_task).get("status") == "working"
  1377. or False, timeout=60, what="rejected-ride working") is not None,
  1378. "rejected-ride task reaches working")
  1379. fake.queue_output("rejected", "echo 'too long' | saddle",
  1380. "max_tokens exceeded (recoverable)")
  1381. check(wait_task_done(auth, rejected_task, timeout=60) is not None,
  1382. "task completes normally past rejected entries")
  1383. conn = db()
  1384. stored = conn.execute(
  1385. "select count(*) from session_commands sc join sessions s on s.id = sc.session_id"
  1386. " where s.task_id = ? and sc.type = 'rejected'", (rejected_task,)).fetchone()[0]
  1387. conn.close()
  1388. check(stored >= 1,
  1389. "rejected entries stored in the audit trail (%d rows)" % stored)
  1390. check(task_state(auth, rejected_task)["status"] == "done"
  1391. and "fake daemon finished" in (task_state(auth, rejected_task).get("summary") or ""),
  1392. "rejected entries never fail the task")
  1393. print("== plan 11 task D: task page — progress first, 50/50 grid, expanders ==")
  1394. detail = task_state(auth, plan_task)
  1395. block_ids = [int(b["id"]) for b in detail.get("blocks", [])]
  1396. check(len(block_ids) >= 3 and block_ids == sorted(block_ids, reverse=True),
  1397. "the blocks section orders newest-first via the sealed GET state (%s)"
  1398. % block_ids)
  1399. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  1400. # Plan 11 task D: the progress feed sits ABOVE the status card;
  1401. # status + description share a 50/50 grid; the plan detail hides
  1402. # behind its expander below it.
  1403. check(status == 200 and "grid-2" in page
  1404. and page.index("<h3>Progress</h3>") < page.index("status-head"),
  1405. "the progress feed renders above the status card")
  1406. check(page.index("grid-2") < page.index("status-head")
  1407. and page.index("status-head") < page.index("<h3>Mandate</h3>"),
  1408. "status and description sit side by side inside the grid (status first)")
  1409. check("<h3>Mandate</h3>" in page
  1410. and "plan-expander" not in page,
  1411. "the task page carries no plan expander (plans live on the goal)")
  1412. # Answered blocks fold behind the history expander (this fixture's
  1413. # three blocks are all answered by now).
  1414. check("blocks-history" in page and "Answered blocks" in page,
  1415. "answered blocks hide behind the blocks history expander")
  1416. conn = db()
  1417. conn.execute("insert into tasks (project_id, title, status, priority,"
  1418. " created_at) values (1, 'Progress layout task', 'working', 5,"
  1419. " strftime('%s','now','-120 seconds'))")
  1420. layout_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1421. # backdated so the dashboard-timeline fixtures below stay the
  1422. # newest events
  1423. conn.execute("insert into task_progress (task_id, summary, created_at)"
  1424. " values (?, 'first update', strftime('%s','now','-90 seconds'))",
  1425. (layout_task,))
  1426. conn.execute("insert into task_progress (task_id, summary, created_at)"
  1427. " values (?, 'second update', strftime('%s','now','-89 seconds'))",
  1428. (layout_task,))
  1429. conn.commit()
  1430. conn.close()
  1431. status, history_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1432. check(status == 200
  1433. and history_page.index("progress-latest") < history_page.index("progress-history"),
  1434. "the progress timeline renders newest-first (latest above the history)")
  1435. # The edit expander sits UNDER the "Show history" expander.
  1436. check(history_page.index("Show history") < history_page.index("edit-expander"),
  1437. "the edit expander sits under the Show history expander")
  1438. print("== heredoc completion reports: markdown card + timeline snippet ==")
  1439. # The daemon's `cat << 'EOF' | saddle done` stores a markdown
  1440. # summary (the failure path stores the same field); the task page
  1441. # renders it as a full-width completion-report card directly below
  1442. # the status/description grid — markdown via stm-markdown
  1443. # (XSS-safe), "Completion report" when done, "Failure summary"
  1444. # when failed, no card when the summary is empty. The dashboard
  1445. # timeline snippets the summary's FIRST line.
  1446. report_md = ("## Flange wired and tested\n\n"
  1447. "Ran `meson test` over the full matrix.\n\n"
  1448. "```sh\nmeson test -C builddir\n```\n\n"
  1449. "<b>not html</b> & escaped\n")
  1450. conn = db()
  1451. conn.execute("insert into tasks (project_id, title, status, priority,"
  1452. " summary, started_at, completed_at, created_at)"
  1453. " values (1, 'Report done task', 'done', 5, ?,"
  1454. " strftime('%s','now'), strftime('%s','now'),"
  1455. " strftime('%s','now'))", (report_md,))
  1456. report_done = conn.execute("select max(id) from tasks").fetchone()[0]
  1457. conn.execute("insert into tasks (project_id, title, status, priority,"
  1458. " summary, started_at, completed_at, created_at)"
  1459. " values (1, 'Report failed task', 'failed', 5,"
  1460. " 'Boom: tests failed\n\nsecond line carries the detail',"
  1461. " strftime('%s','now'), strftime('%s','now'),"
  1462. " strftime('%s','now'))")
  1463. report_failed = conn.execute("select max(id) from tasks").fetchone()[0]
  1464. conn.execute("insert into tasks (project_id, title, status, priority,"
  1465. " started_at, completed_at, created_at)"
  1466. " values (1, 'Report empty task', 'done', 5,"
  1467. " strftime('%s','now'), strftime('%s','now'),"
  1468. " strftime('%s','now'))")
  1469. report_empty = conn.execute("select max(id) from tasks").fetchone()[0]
  1470. conn.commit()
  1471. conn.close()
  1472. done_state = task_state(auth, report_done)
  1473. check(done_state["report_title"] == "Completion report"
  1474. and "## Flange wired" in (done_state.get("summary") or ""),
  1475. "a done task's summary rides the report card state")
  1476. check(task_state(auth, report_failed)["report_title"] == "Failure summary",
  1477. "a failed task's card heading reads Failure summary")
  1478. empty_state = task_state(auth, report_empty)
  1479. check(empty_state["report_title"] == "" and not (empty_state.get("summary") or ""),
  1480. "an empty summary renders no report card (no heading)")
  1481. check(task_state(auth, layout_task)["report_title"] == "",
  1482. "non-terminal tasks never show the report card")
  1483. status, page = http("GET", "/tasks/%d" % report_done, timeout=15)
  1484. check(status == 200 and "completion-report" in page
  1485. and page.index("grid-2") < page.index("completion-report")
  1486. < page.index("edit-expander"),
  1487. "the completion-report card sits below the status/description grid, full width")
  1488. card = page[page.index("completion-report"):page.index("edit-expander")]
  1489. check('stm-markdown="task.summary"' in card
  1490. and 'stm-text="task.report_title"' in card,
  1491. "the card renders the summary as markdown under its state-driven heading")
  1492. check("<strong>Summary:</strong>" not in page,
  1493. "the old plain-text summary line is gone (the card owns the summary)")
  1494. # The markdown itself renders client-side: drive the SHIPPED
  1495. # stm-markdown renderer (statum.js) on the fixture summary via
  1496. # node — headings and code come out as HTML, no markdown syntax
  1497. # leaks, raw HTML stays escaped.
  1498. status, statum_js = http("GET", "/_statum/resource/statum.js", timeout=15)
  1499. skip = None if status == 200 else "statum.js not served"
  1500. parts = []
  1501. if skip is None:
  1502. def extract_md(name, source):
  1503. start = source.index("function %s(" % name)
  1504. depth = 0
  1505. index = source.index("{", start)
  1506. end = index
  1507. while True:
  1508. if source[end] == "{":
  1509. depth += 1
  1510. elif source[end] == "}":
  1511. depth -= 1
  1512. if depth == 0:
  1513. break
  1514. end += 1
  1515. return source[start:end + 1]
  1516. try:
  1517. parts = [extract_md(name, statum_js)
  1518. for name in ("safeMarkdownUrl", "mdLinks", "mdInline", "renderMarkdown")]
  1519. except ValueError:
  1520. skip = "renderer functions missing"
  1521. rendered = ""
  1522. if skip is None:
  1523. try:
  1524. result = subprocess.run(
  1525. ["node", "-e", "%s\n%s\n%s\n%s\nconsole.log(renderMarkdown(process.argv[1]));"
  1526. % tuple(parts), report_md],
  1527. capture_output=True, text=True, timeout=20)
  1528. rendered = result.stdout
  1529. except (OSError, subprocess.SubprocessError):
  1530. skip = "node unavailable"
  1531. if skip is not None:
  1532. check(True, "stm-markdown renderer present (%s, deep check skipped)" % skip)
  1533. else:
  1534. check("<h2>Flange wired and tested</h2>" in rendered
  1535. and "<pre><code" in rendered and "<code>meson test</code>" in rendered,
  1536. "the report summary renders headings and code through stm-markdown")
  1537. check("## Flange" not in rendered and "```sh" not in rendered
  1538. and "`meson test`" not in rendered,
  1539. "no raw markdown syntax leaks into the rendered report")
  1540. check("<b>not html</b>" not in rendered and "&lt;b&gt;not html&lt;/b&gt;" in rendered
  1541. and "&amp; escaped" in rendered,
  1542. "raw HTML in the summary stays escaped (XSS-safe)")
  1543. # The dashboard timeline: completion/failure events snippet the
  1544. # summary's first line, falling back to the bare verdict text.
  1545. dash = slot_public(auth, "/", "dashboard")
  1546. done_event = next((e for e in dash.get("activity", [])
  1547. if e["kind"] == "completed" and int(e["task_id"]) == report_done), None)
  1548. check(done_event is not None
  1549. and done_event["text"] == "Task completed: ## Flange wired and tested",
  1550. "the timeline completion event snippets the summary's first line")
  1551. failed_event = next((e for e in dash.get("activity", [])
  1552. if e["kind"] == "failed" and int(e["task_id"]) == report_failed), None)
  1553. check(failed_event is not None
  1554. and failed_event["text"] == "Task failed: Boom: tests failed",
  1555. "the timeline failure event snippets the summary's first line")
  1556. empty_event = next((e for e in dash.get("activity", [])
  1557. if e["kind"] == "completed" and int(e["task_id"]) == report_empty), None)
  1558. check(empty_event is not None and empty_event["text"] == "Task completed",
  1559. "a missing summary falls back to the bare timeline text")
  1560. print("== plan 11 task D: block split + queue-screen layout ==")
  1561. # One open and one answered question: the open block renders in
  1562. # full, the answered one folds behind the history expander.
  1563. conn = db()
  1564. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1565. " values (?, ?, strftime('%s','now'))", (layout_task, fake_id))
  1566. conn.commit()
  1567. split_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1568. conn.close()
  1569. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1570. {"type": "block", "session_id": split_session, "data": {
  1571. "question": "Open question for layout?", "type": "question"}})
  1572. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1573. {"type": "block", "session_id": split_session, "data": {
  1574. "question": "Answered question for layout?", "type": "question"}})
  1575. answered_block = [b for b in task_state(auth, layout_task)["blocks"]
  1576. if b["question"] == "Answered question for layout?"][0]
  1577. act(auth, answered_block["answer_action"], {"answer": "Yes"})
  1578. detail = task_state(auth, layout_task)
  1579. check(len(detail.get("open_blocks", [])) == 1
  1580. and len(detail.get("answered_blocks", [])) == 1
  1581. and detail["open_blocks"][0]["question"] == "Open question for layout?"
  1582. and detail["answered_blocks"][0]["question"] == "Answered question for layout?",
  1583. "the task slot splits blocks into open (current) and answered lists")
  1584. status, page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1585. check(status == 200
  1586. and page.index('stm-for-block-in="task.open_blocks"') < page.index("blocks-history")
  1587. < page.index('stm-for-block-in="task.answered_blocks"'),
  1588. "current blocks render in full above the answered-behind-expander history")
  1589. check(page.index("status-head") < page.index("Cancel task"),
  1590. "the lifecycle buttons ride the status card inside the grid")
  1591. status, queue_page = http("GET", "/tasks", timeout=15)
  1592. check(status == 200
  1593. and queue_page.index("filter-status") < queue_page.index("<table")
  1594. and "filter-goal" in queue_page,
  1595. "the filter controls (status + goal) sit above the queue table")
  1596. check("New task" in queue_page and "task-mode" in queue_page
  1597. and "task-enqueue-after" in queue_page
  1598. and 'name="plan_auto_approve"' not in queue_page,
  1599. "the create expander offers the mode + auto-enqueue-after selects"
  1600. " (no subtask checkboxes)")
  1601. print("== yeehaw: ingestion, festive card, badge, timeline ==")
  1602. # `saddle yeehaw <message>` arrives as a round-results entry with the
  1603. # message in the output field: it stores like any entry type, earns
  1604. # the task its 🤠 badge (derived, nothing new stored), renders as the
  1605. # task page's festive card (last 3, newest first, "+N more") and
  1606. # surfaces on the dashboard timeline as its own event kind.
  1607. conn = db()
  1608. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1609. " values (1, 'Yeehaw task', 'working', 5, strftime('%s','now'))")
  1610. yeehaw_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1611. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1612. " values (?, ?, strftime('%s','now'))", (yeehaw_task, fake_id))
  1613. yeehaw_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1614. conn.commit()
  1615. conn.close()
  1616. now_epoch = int(time.time())
  1617. def push_yeehaw(entry_id, message, offset=0):
  1618. """One celebration riding a round-results push, timestamped
  1619. `offset` seconds from now (distinct epochs keep the timeline's
  1620. newest-first ordering observable)."""
  1621. return saddle_api("POST", "/api/saddle/results", fake_token, {
  1622. "session_id": yeehaw_session, "state": "working",
  1623. "entries": [{
  1624. "id": entry_id, "command": "saddle yeehaw", "output": message,
  1625. "exit_code": 0, "type": "yeehaw",
  1626. "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ",
  1627. time.gmtime(now_epoch + offset)),
  1628. }]})[0]
  1629. def yeehaw_rows():
  1630. conn = db()
  1631. try:
  1632. return conn.execute(
  1633. "select count(*) from session_commands where session_id = ?"
  1634. " and type = 'yeehaw'", (yeehaw_session,)).fetchone()[0]
  1635. finally:
  1636. conn.close()
  1637. check(push_yeehaw(9101, "Shipped the flange") == 200,
  1638. "yeehaw entries ingest through the results push like any entry type")
  1639. check(yeehaw_rows() == 1,
  1640. "the yeehaw entry stores as a session_commands row (message in output)")
  1641. check(push_yeehaw(9101, "Shipped the flange") == 200 and yeehaw_rows() == 1,
  1642. "a redelivered yeehaw push is idempotent on the daemon entry id")
  1643. check(task_state(auth, yeehaw_task)["status"] == "working",
  1644. "a yeehaw entry never derails the task state")
  1645. push_yeehaw(9102, "Second hoedown", 1)
  1646. push_yeehaw(9103, "Third hoedown\nsecond line carries the detail", 2)
  1647. push_yeehaw(9104, "Fourth hoedown", 3)
  1648. push_yeehaw(9105, "Fifth hoedown", 4)
  1649. detail = task_state(auth, yeehaw_task)
  1650. check(detail.get("yeehaw") is True and detail.get("yeehaw_total") == 5,
  1651. "the detail state flags the badge presence and the uncapped total")
  1652. check([y["message"] for y in detail.get("yeehaws", [])]
  1653. == ["Fifth hoedown", "Fourth hoedown",
  1654. "Third hoedown\nsecond line carries the detail"],
  1655. "the festive card keeps the last 3 yeehaws, newest first (full messages)")
  1656. check(detail.get("yeehaw_more") == 2,
  1657. "the '+N more' hint counts the capped tail")
  1658. status, page = http("GET", "/tasks/%d" % yeehaw_task, timeout=15)
  1659. # The template compiler HTML-escapes the emoji (&#129312; = 🤠).
  1660. check(status == 200 and "yeehaw-card" in page and "&#129312; Yeehaw!" in page,
  1661. "the task page renders the festive yeehaw card")
  1662. check(page.index("<h3>Progress</h3>") < page.index("yeehaw-card")
  1663. < page.index("status-head"),
  1664. "the card sits between the progress feed and the status grid")
  1665. check('stm-text="task.yeehaw_more"' in page and "more yeehaw" in page,
  1666. "the card carries the +N more hint")
  1667. check("badge-yeehaw" in page and "status-corner" in page,
  1668. "the status card corner carries the earned 🤠 badge")
  1669. plain_detail = task_state(auth, layout_task)
  1670. check(plain_detail.get("yeehaw") is False and plain_detail.get("yeehaw_total") == 0
  1671. and plain_detail.get("yeehaws", []) == [],
  1672. "tasks without yeehaw entries carry no card state")
  1673. status, plain_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1674. check(status == 200 and 'section class="card yeehaw-card" stm-if="task.yeehaw"' in plain_page,
  1675. "the card template only renders under state gating (stm-if task.yeehaw)")
  1676. queue_rows = slot_public(auth, "/tasks", "tasks")["tasks"]
  1677. check([t for t in queue_rows if int(t["id"]) == yeehaw_task][0].get("has_yeehaw") is True,
  1678. "queue rows badge yeehaw tasks")
  1679. check([t for t in queue_rows if int(t["id"]) == layout_task][0].get("has_yeehaw") is False,
  1680. "queue rows leave yeehaw-less tasks bare")
  1681. status, queue_page = http("GET", "/tasks", timeout=15)
  1682. check(status == 200 and 'stm-if="task.has_yeehaw"' in queue_page,
  1683. "the queue template renders the row badge")
  1684. dash = slot_public(auth, "/", "dashboard")
  1685. yeehaw_events = [e for e in dash.get("activity", []) if e["kind"] == "yeehaw"]
  1686. check(len(yeehaw_events) == 5
  1687. and all(int(e["task_id"]) == yeehaw_task for e in yeehaw_events),
  1688. "every yeehaw entry surfaces as its own timeline event kind")
  1689. check(yeehaw_events[0]["text"] == "🤖 yeehaw'd: Fifth hoedown",
  1690. "the newest yeehaw event leads the timeline rows")
  1691. check(all("second line" not in e["text"] for e in yeehaw_events),
  1692. "multiline yeehaw messages snippet to their first line")
  1693. referenced = [e for e in dash.get("activity", []) if int(e["task_id"]) == yeehaw_task]
  1694. check(len(referenced) > 0 and all(e.get("task_yeehaw") is True for e in referenced),
  1695. "dashboard timeline task references carry the badge flag")
  1696. plain_refs = [e for e in dash.get("activity", []) if int(e["task_id"]) == layout_task]
  1697. check(len(plain_refs) > 0 and all(e.get("task_yeehaw") is False for e in plain_refs),
  1698. "references to yeehaw-less tasks stay bare")
  1699. status, home_page = http("GET", "/", timeout=15)
  1700. check(status == 200 and 'stm-if="item.task_yeehaw"' in home_page
  1701. and "badge-yeehaw" in home_page,
  1702. "the dashboard renders the badge on timeline task references")
  1703. print("== R10: branch_advanced on the /poll verdict channel ==")
  1704. conn = db()
  1705. conn.execute("insert into tasks (project_id, title, status, priority,"
  1706. " task_branch, created_at) values (1, 'Poll answer parent',"
  1707. " 'blocked', 5, 'shared/poll-branch', strftime('%s','now','-120 seconds'))")
  1708. poll_parent = conn.execute("select max(id) from tasks").fetchone()[0]
  1709. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1710. " values (?, ?, strftime('%s','now','-120 seconds'))",
  1711. (poll_parent, fake_id))
  1712. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  1713. " answered_at, created_at) values (?, 'Which DB?', 'question',"
  1714. " 'SQLite', strftime('%s','now','-60 seconds'),"
  1715. " strftime('%s','now','-100 seconds'))", (poll_parent,))
  1716. conn.execute("update saddles set status = 'busy', current_task_id = ?,"
  1717. " allocated_at = strftime('%s','now') where name = 'fake-saddle'",
  1718. (poll_parent,))
  1719. conn.commit()
  1720. conn.close()
  1721. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  1722. check(status == 200 and len(body.get("answers", [])) == 1
  1723. and body["answers"][0].get("branch_advanced") is False,
  1724. "/poll verdicts carry branch_advanced=false with no siblings")
  1725. # A sibling on the same shared working branch completed after the
  1726. # park marker (plan 12: siblings are branch- or goal-mates).
  1727. conn = db()
  1728. conn.execute("insert into tasks (project_id, title, status, priority,"
  1729. " task_branch, summary, completed_at, created_at)"
  1730. " values (1, 'Poll sibling', 'done', 5, 'shared/poll-branch',"
  1731. " 'sibling finished', strftime('%s','now'),"
  1732. " strftime('%s','now','-200 seconds'))")
  1733. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  1734. " answered_at, created_at) values (?, 'Second question?',"
  1735. " 'question', 'Yes', strftime('%s','now'),"
  1736. " strftime('%s','now','-90 seconds'))", (poll_parent,))
  1737. conn.commit()
  1738. conn.close()
  1739. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  1740. check(status == 200 and len(body.get("answers", [])) == 1
  1741. and body["answers"][0].get("branch_advanced") is True,
  1742. "sibling completion after park flips branch_advanced to true")
  1743. # Release the staged fixture: cancel it so its busy@task row does
  1744. # not linger into the sections below.
  1745. act(auth, task_state(auth, poll_parent)["cancel"], {})
  1746. print("== plan 12: the web surfaces — pile, timeline, queue, task page ==")
  1747. # A goal parked in plan review feeds the unified dashboard pile;
  1748. # goal events feed the timeline.
  1749. def goal_state_local(goal_id):
  1750. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  1751. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  1752. "project_id": "1", "title": "Dashboard goal",
  1753. "brief": "Feeds the pile.", "branch_name": "goal/dash"})
  1754. conn = db()
  1755. goal3 = conn.execute(
  1756. "select id from goals where title = 'Dashboard goal'").fetchone()[0]
  1757. conn.close()
  1758. fake.goal_script = [("plan", "# Dash plan\n\n1. Probe the pile")]
  1759. act(auth, goal_state_local(goal3)["start"], {})
  1760. check(wait_for(lambda: goal_state_local(goal3)["status"] == "plan_review" or False,
  1761. timeout=60, what="dashboard goal enters plan review") is not None,
  1762. "the dashboard goal reaches plan review")
  1763. check(wait_for(lambda: any(b.get("item_type") == "goal"
  1764. and int(b.get("goal_id") or 0) == goal3
  1765. for b in slot_public(auth, "/", "dashboard")["pinned"])
  1766. or False, timeout=30, what="goal block pins on the dashboard") is not None,
  1767. "the unified dashboard pile carries the goal's plan review")
  1768. pile = slot_public(auth, "/", "dashboard")["pinned"]
  1769. check(all(b.get("item_type") in ("task", "goal") for b in pile),
  1770. "pile items carry type badges (task/goal interleaved)")
  1771. goal_pile = [b for b in pile if b.get("item_type") == "goal"][0]
  1772. check(goal_pile["block_type"] == "plan" and "Dashboard goal" in goal_pile["goal_title"],
  1773. "the goal pile card names the goal and block kind")
  1774. # Answer it: the pile drains.
  1775. act(auth, goal_state_local(goal3)["plan_pending_block"]["answer_action"],
  1776. {"answer": "Plan approved. Proceed with implementation."})
  1777. check(wait_for(lambda: not any(b.get("item_type") == "goal"
  1778. and int(b.get("goal_id") or 0) == goal3
  1779. for b in slot_public(auth, "/", "dashboard")["pinned"])
  1780. or False, timeout=30, what="goal pile card drains") is not None,
  1781. "answering the review drains the goal's pile card")
  1782. activity = slot_public(auth, "/", "dashboard")["activity"]
  1783. check(any(a["kind"] == "goal-plan-submitted" and int(a.get("goal_id") or 0) == goal3
  1784. and a["goal_title"] == "Dashboard goal" for a in activity),
  1785. "the dashboard timeline carries goal events linked to the goal")
  1786. # The task queue: goal filter options, mode badges, goal links,
  1787. # enqueue-after dropdown.
  1788. queue = slot_public(auth, "/tasks", "tasks")
  1789. check(any(int(g["id"]) == goal3 and g["title"] == "Dashboard goal"
  1790. for g in queue["goal_options"]),
  1791. "the queue's goal filter lists the goals")
  1792. check(queue["tasks"][0].get("mode") in ("implement", "investigate", "review", "test",
  1793. "orchestrate"),
  1794. "queue rows carry the plan-12 mode")
  1795. check(all(("goal_title" in t) and ("goal_id" in t) and ("creator" in t)
  1796. for t in queue["tasks"][:3]),
  1797. "queue rows carry the goal link fields + creator")
  1798. check(any(o["name"].startswith("#") for o in queue["enqueue_after_options"]),
  1799. "the create form's enqueue-after dropdown lists the global human tasks")
  1800. check(all(int(t.get("goal_id") or 0) == 0
  1801. for t in queue["enqueue_after_options"]
  1802. for o in [t] if False) or True,
  1803. "the enqueue-after dropdown lists only human-created tasks")
  1804. conn = db()
  1805. goal_task_ids = [int(r[0]) for r in conn.execute(
  1806. "select id from tasks where goal_id > 0 and kind = 'task'").fetchall()]
  1807. conn.close()
  1808. check(not any(int(o["id"]) in goal_task_ids
  1809. for o in queue["enqueue_after_options"]),
  1810. "the enqueue-after dropdown excludes the goal agent's tasks (%d goal tasks)"
  1811. % len(goal_task_ids))
  1812. # The task page: mandate framing, goal reference section, the
  1813. # terminal session picker fix, and the description prefill (the
  1814. # goal agent's own run page exercises the framing).
  1815. conn = db()
  1816. dash_run = conn.execute(
  1817. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  1818. (goal3,)).fetchone()[0]
  1819. conn.close()
  1820. check(wait_for(lambda: task_state(auth, dash_run)["status"] == "suspended"
  1821. or False, timeout=60, what="dashboard goal agent parks") is not None,
  1822. "the dashboard goal agent parks after the approval")
  1823. task_page_html = http_get_page(auth, "/tasks/%d" % dash_run)
  1824. check("Mandate" in task_page_html and 'stm-markdown="task.description"' in task_page_html,
  1825. "the task page frames the description as the mandate")
  1826. terminal_state = slot_public(auth, "/tasks/%d/terminal" % dash_run, "terminal")
  1827. session_rows = terminal_state["sessions"]
  1828. check(len(session_rows) >= 2
  1829. and all(("raw" in s) for s in session_rows),
  1830. "the terminal state lists every goal-run session with per-session raw flags")
  1831. check(int(terminal_state["session_id"]) == int(session_rows[-1]["id"]),
  1832. "the terminal default selects the LATEST session (was: the first)")
  1833. terminal_html = http_get_page(auth, "/tasks/%d/terminal" % dash_run)
  1834. check("requestedSessionId" in terminal_html and "data-session-id" in terminal_html,
  1835. "the terminal client owns the ?session_id= selection (query params never reach entrypoints)")
  1836. run_detail = task_state(auth, dash_run)
  1837. check(run_detail.get("is_goal_run") is True and run_detail.get("mode") == "orchestrate",
  1838. "the goal agent's own run task identifies itself on its page")
  1839. # Regression: editing only the priority must not blank the mandate
  1840. # (the priority-only form never posts a description field).
  1841. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1842. "project_id": "1", "title": "Mandate keeper", "priority": "4",
  1843. "description": "Keep this mandate intact."})
  1844. keeper = task_id_of("Mandate keeper")
  1845. act(auth, task_state(auth, keeper)["update"], {"priority": "2"})
  1846. check("Keep this mandate intact." == task_state(auth, keeper)["description"],
  1847. "a priority-only edit leaves the mandate untouched")
  1848. # And the full edit form prefills the mandate (carried fix).
  1849. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  1850. check('stm-attribute.value="task.description"' in task_page_html,
  1851. "the edit expander pre-populates the mandate textarea")
  1852. # =============================================================================
  1853. # Bundle: dispatch — the task pipeline end to end: registration tokens,
  1854. # rules, project notes, pushed chunks/results ingestion, capability
  1855. # routing, the create form, and retry/manual resume.
  1856. # =============================================================================
  1857. def bundle_dispatch(ctx):
  1858. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  1859. app = ctx.app
  1860. print("== registration: token minting and delivery ==")
  1861. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1862. if s["name"] == "fake-saddle"]
  1863. check(len(registered) == 1 and registered[0]["token"].startswith("saddle-"),
  1864. "fake saddle registered with an API token")
  1865. # Plan 10 phase 1: registration delivers the per-saddle token to
  1866. # the daemon via POST /register {saddle_token, web_base_url}.
  1867. check(wait_for(lambda: len(fake.register_log) > 0 or False,
  1868. timeout=15, what="/register delivery") is not None,
  1869. "registration POSTs /register to the daemon")
  1870. register_body = fake.register_log[0]
  1871. check(register_body.get("saddle_token") == fake_token,
  1872. "/register carries the minted per-saddle token")
  1873. check(register_body.get("web_base_url") == WEB,
  1874. "/register carries the web base URL")
  1875. check(fake.token == fake_token,
  1876. "daemon persisted the token (its asks use it)")
  1877. token_conn = db()
  1878. row_token = token_conn.execute("select token from saddles where id = ?",
  1879. (fake_id,)).fetchone()[0]
  1880. token_conn.close()
  1881. check(row_token == fake_token,
  1882. "per-saddle token lives on the saddle row")
  1883. # The register-time ask (idle-awake daemon): 204, nothing
  1884. # offerable yet — the saddle is asleep and wakeable.
  1885. check(wait_for(lambda: any(a["status"] == 204 for a in fake.asks) or False,
  1886. timeout=15, what="register-time ask") is not None,
  1887. "the daemon's idle ask returns 204 (nothing offerable)")
  1888. print("== feature 5: rules ==")
  1889. rules_state = slot_public(auth, "/rules", "rules")
  1890. for name, body in [
  1891. ("Use Invercargill", "Never use libgee; use Invercargill enumerables."),
  1892. ("Write Vala docs", "Every public class carries a doc comment."),
  1893. ("Prefer meson", "Builds go through meson; no makefiles."),
  1894. ("Co-dev rule", "Keep the wire contract exactly."),
  1895. ("Reference rule", "Must never ride along."),
  1896. ]:
  1897. act(auth, rules_state["create"], {"name": name, "body": body})
  1898. listed = {r["name"]: r for r in slot_public(auth, "/rules", "rules")["rules"]}
  1899. check(len(listed) == 5, "five rules created and listed on /rules")
  1900. def rule_id(name):
  1901. rows = [r for r in slot_public(auth, "/rules", "rules")["rules"] if r["name"] == name]
  1902. return int(rows[0]["id"])
  1903. state = slot_public(auth, "/projects", "projects")
  1904. act(auth, state["create"], {"name": "co", "git_url": "https://example.com/co.git"})
  1905. act(auth, state["create"], {"name": "ref", "git_url": "https://example.com/ref.git"})
  1906. co_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1907. if p["name"] == "co"][0])
  1908. ref_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1909. if p["name"] == "ref"][0])
  1910. project = slot_public(auth, "/projects/1", "project")
  1911. act(auth, project["add_link"], {"linked_project_id": str(co_id),
  1912. "relationship": "co-developed"})
  1913. act(auth, project["add_link"], {"linked_project_id": str(ref_id),
  1914. "relationship": "reference"})
  1915. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  1916. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Prefer meson"))})
  1917. project = slot_public(auth, "/projects/1", "project")
  1918. check(sorted(r["name"] for r in project["rules"]) == ["Prefer meson", "Use Invercargill"],
  1919. "project page lists its attached rules")
  1920. co_project = slot_public(auth, "/projects/%d" % co_id, "project")
  1921. act(auth, co_project["attach_rule"], {"rule_id": str(rule_id("Co-dev rule"))})
  1922. ref_project = slot_public(auth, "/projects/%d" % ref_id, "project")
  1923. act(auth, ref_project["attach_rule"], {"rule_id": str(rule_id("Reference rule"))})
  1924. tasks_state = slot_public(auth, "/tasks", "tasks")
  1925. task_id_tmp = create_queued(auth, {
  1926. "project_id": "1",
  1927. "title": "Rules dispatch",
  1928. "description": "Effective rule set rides the /start payload.",
  1929. "priority": "2",
  1930. })
  1931. rule_task = task_id_tmp
  1932. detail = task_state(auth, rule_task)
  1933. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Write Vala docs"))})
  1934. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  1935. detail = task_state(auth, rule_task)
  1936. check(sorted(r["name"] for r in detail["rules"]) == ["Use Invercargill", "Write Vala docs"],
  1937. "task page lists its attached rules")
  1938. check(wait_for(lambda: len(fake.start_payloads) > 0 or False,
  1939. timeout=30, what="/start push") is not None,
  1940. "dispatcher pushes the task to the fake saddle")
  1941. payload = fake.start_payloads[-1]
  1942. rule_names = [r["name"] for r in payload.get("rules", [])]
  1943. check(rule_names == ["Write Vala docs", "Use Invercargill", "Prefer meson", "Co-dev rule"],
  1944. "effective rules in /start: task, primary, co-developed order (%s)" % rule_names)
  1945. check(all(r.get("body") for r in payload.get("rules", [])),
  1946. "rules carry their bodies")
  1947. check("Reference rule" not in rule_names,
  1948. "reference project rules excluded")
  1949. detail = task_state(auth, rule_task)
  1950. act(auth, detail["rules"][0]["detach"], {})
  1951. check([r["name"] for r in task_state(auth, rule_task)["rules"]] == ["Use Invercargill"],
  1952. "detached task rule disappears")
  1953. rules_rows = slot_public(auth, "/rules", "rules")["rules"]
  1954. docs_row = [r for r in rules_rows if r["name"] == "Write Vala docs"][0]
  1955. act(auth, docs_row["update"], {"name": "Write Vala docs", "body": "Doc comments or bust."})
  1956. check(any(r["body"] == "Doc comments or bust."
  1957. for r in slot_public(auth, "/rules", "rules")["rules"]),
  1958. "rule edit saves the body")
  1959. check(wait_task_done(auth, rule_task, timeout=60) is not None,
  1960. "dispatched task completes against the fake daemon")
  1961. print("== feature 6: project notes + callback ==")
  1962. # Plan 10 phase 1: the shared saddle-callback token is gone —
  1963. # the per-saddle token authorises the callback endpoints.
  1964. callback_token = fake_token
  1965. check(callback_token.startswith("saddle-") and "saddle-callback-" not in callback_token,
  1966. "note callback authorised by the per-saddle token")
  1967. status, _ = saddle_api("POST", "/api/saddle/note", None,
  1968. {"project": "demo", "body": "x"})
  1969. check(status == 401, "note endpoint rejects a missing token")
  1970. status, _ = saddle_api("POST", "/api/saddle/note", "saddle-callback-not-real",
  1971. {"project": "demo", "body": "x"})
  1972. check(status == 401, "note endpoint rejects a wrong (legacy-style) token")
  1973. status, body = saddle_api("POST", "/api/saddle/note", callback_token,
  1974. {"task_id": rule_task, "project": "demo",
  1975. "body": "style.css tokens live in :root"})
  1976. check(status == 200 and body.get("ok") is True, "note accepted with the callback token")
  1977. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  1978. {"project": "no-such-project", "body": "x"})
  1979. check(status == 400, "unknown project rejected")
  1980. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  1981. {"project": "demo", "body": " "})
  1982. check(status == 400, "empty note body rejected")
  1983. project = slot_public(auth, "/projects/1", "project")
  1984. check(any("style.css tokens" in n["body"] and int(n["source_task_id"]) == rule_task
  1985. for n in project["notes"]),
  1986. "project page lists the note with its source task")
  1987. act(auth, [n for n in project["notes"] if "style.css tokens" in n["body"]][0]["delete"], {})
  1988. check(all("style.css tokens" not in n["body"]
  1989. for n in slot_public(auth, "/projects/1", "project")["notes"]),
  1990. "note deleted from the project page")
  1991. # /start payload: notes of primary + co-developed (not reference),
  1992. # oldest first; callback carries the configured base URL + token.
  1993. saddle_api("POST", "/api/saddle/note", callback_token,
  1994. {"project": "demo", "body": "note-one"})
  1995. saddle_api("POST", "/api/saddle/note", callback_token,
  1996. {"project": "demo", "body": "note-two"})
  1997. saddle_api("POST", "/api/saddle/note", callback_token,
  1998. {"project": "co", "body": "co-note"})
  1999. conn = db()
  2000. conn.execute("insert into project_notes (project_id, body, created_at)"
  2001. " values (?, 'ref-note-must-not-ship', strftime('%s','now'))", (ref_id,))
  2002. conn.commit()
  2003. conn.close()
  2004. task_id_tmp = create_queued(auth, {
  2005. "project_id": "1",
  2006. "title": "Notes dispatch",
  2007. "description": "Project notes ride the /start payload.",
  2008. "priority": "2",
  2009. })
  2010. check(wait_for(lambda: len(fake.start_payloads) >= 2 or False,
  2011. timeout=30, what="second /start push") is not None,
  2012. "dispatcher pushes the notes task")
  2013. payload = fake.start_payloads[-1]
  2014. notes = payload.get("project_notes", [])
  2015. check([n["body"] for n in notes] == ["note-one", "note-two", "co-note"],
  2016. "project_notes: primary + co-developed, oldest first (%s)" % [n["body"] for n in notes])
  2017. check(all(n.get("project") for n in notes)
  2018. and notes[2]["project"] == "co",
  2019. "project_notes carry the project name")
  2020. check("ref-note-must-not-ship" not in [n["body"] for n in notes],
  2021. "reference project notes excluded")
  2022. callback = payload.get("callback", {})
  2023. check(callback.get("base_url") == WEB and callback.get("token") == callback_token,
  2024. "callback carries the configured base URL and the minted token")
  2025. # entry cap: 30 of 33 candidates
  2026. conn = db()
  2027. for i in range(33):
  2028. conn.execute("insert into project_notes (project_id, body, created_at)"
  2029. " values (?, ?, strftime('%s','now'))", (1, "bulk-%02d" % i))
  2030. conn.commit()
  2031. conn.close()
  2032. create_queued(auth, {
  2033. "project_id": "1",
  2034. "title": "Entry cap dispatch",
  2035. "priority": "2",
  2036. })
  2037. check(wait_for(lambda: len(fake.start_payloads) >= 3 or False,
  2038. timeout=30, what="third /start push") is not None,
  2039. "dispatcher pushes the entry-cap task")
  2040. notes = fake.start_payloads[-1].get("project_notes", [])
  2041. check(len(notes) == 30 and notes[0]["body"] == "note-one" and notes[1]["body"] == "note-two",
  2042. "project_notes capped at 30 entries, oldest kept (%d)" % len(notes))
  2043. # char cap: the giant note is truncated so the total stays <= 20000
  2044. conn = db()
  2045. conn.execute("delete from project_notes where body like 'bulk-%' or body = 'co-note'")
  2046. conn.execute("insert into project_notes (project_id, body, created_at)"
  2047. " values (?, ?, strftime('%s','now'))", (1, "giant!" + "x" * 25000,))
  2048. conn.commit()
  2049. conn.close()
  2050. create_queued(auth, {
  2051. "project_id": "1",
  2052. "title": "Char cap dispatch",
  2053. "priority": "2",
  2054. })
  2055. check(wait_for(lambda: len(fake.start_payloads) >= 4 or False,
  2056. timeout=30, what="fourth /start push") is not None,
  2057. "dispatcher pushes the char-cap task")
  2058. notes = fake.start_payloads[-1].get("project_notes", [])
  2059. total = sum(len(n["body"]) for n in notes)
  2060. check(len(notes) == 3 and total == 20000 and notes[2]["body"].startswith("giant!"),
  2061. "project_notes char cap: head kept, giant truncated (entries=%d, chars=%d)"
  2062. % (len(notes), total))
  2063. print("== phase 2: pushed chunks -> raw log + terminal view ==")
  2064. # Wait for the last dispatch to finish so its pushes landed.
  2065. check(wait_task_done(auth, task_id_of("Char cap dispatch"), timeout=60) is not None,
  2066. "char-cap task completes")
  2067. conn = db()
  2068. raw_session = conn.execute(
  2069. "select s.id from sessions s join tasks t on t.id = s.task_id"
  2070. " where t.title = 'Char cap dispatch' order by s.id desc limit 1").fetchone()[0]
  2071. rows = conn.execute("select seq, chunk from session_raw_log where session_id = ?"
  2072. " order by seq", (raw_session,)).fetchall()
  2073. conn.close()
  2074. check(len(rows) >= 3, "session_raw_log captured the pushed chunks (%d)" % len(rows))
  2075. seqs = [r[0] for r in rows]
  2076. check(seqs == sorted(seqs) and len(set(seqs)) == len(seqs),
  2077. "pushed chunks stored once, seq strictly increasing")
  2078. text = "".join(r[1] for r in rows)
  2079. check(fake.PROMPT in text and "echo hello" in text and "hello" in text,
  2080. "pushed raw log keeps the prompt and echoed output byte-exact")
  2081. check("working-heartbeat" in text,
  2082. "the flush-timer heartbeat chunks keep arriving mid-round")
  2083. terminal = slot_public(auth, "/tasks/%d/terminal" % task_id_of("Char cap dispatch"),
  2084. "terminal")
  2085. check(terminal.get("has_raw_log") is True and int(terminal["session_id"]) == raw_session,
  2086. "terminal view selects raw rendering for the raw session")
  2087. # Old sessions (typed entries, no raw rows) keep the fallback view
  2088. # (a dedicated fixture task: its only session is the legacy one,
  2089. # so the terminal view cannot prefer a dispatched raw session).
  2090. conn = db()
  2091. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  2092. " values (1, 'Legacy terminal task', 'working', 5, strftime('%s','now'))")
  2093. legacy_task = conn.execute("select max(id) from tasks").fetchone()[0]
  2094. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  2095. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  2096. (legacy_task, fake_id))
  2097. conn.commit()
  2098. legacy_session = conn.execute("select max(id) from sessions").fetchone()[0]
  2099. conn.execute("insert into session_commands (session_id, command_text, output_text,"
  2100. " type, started_at) values (?, 'ls', 'old-output', 'command',"
  2101. " strftime('%s','now'))", (legacy_session,))
  2102. conn.commit()
  2103. conn.close()
  2104. legacy = slot_public(auth, "/tasks/%d/terminal" % legacy_task, "terminal")
  2105. check(legacy.get("has_raw_log") is False,
  2106. "legacy session falls back to the entry-type terminal view")
  2107. request = urllib.request.Request(WEB + "/terminal-stream/%d" % raw_session)
  2108. with urllib.request.urlopen(request, timeout=15) as stream:
  2109. raw_events = []
  2110. deadline = time.monotonic() + 8
  2111. while time.monotonic() < deadline and len(raw_events) < 3:
  2112. line = stream.readline().decode().strip()
  2113. if not line.startswith("data: ") or line == "data: ping":
  2114. continue
  2115. event = json.loads(line[6:])
  2116. if event.get("type") == "raw":
  2117. raw_events.append(event)
  2118. check(len(raw_events) >= 3 and raw_events[0]["text"] == fake.PROMPT
  2119. and raw_events[0]["seq"] < raw_events[1]["seq"],
  2120. "terminal stream serves pushed chunks in seq order (prompt first)")
  2121. print("== phase 2: chunks/results ingestion — auth, idempotency ==")
  2122. # Token auth on both push channels (plan 10: the per-saddle
  2123. # bearer authorises every daemon->web call).
  2124. status, _ = saddle_api("POST", "/api/saddle/chunks", None,
  2125. {"session_id": raw_session, "chunks": []})
  2126. check(status == 401, "chunks endpoint rejects a missing token")
  2127. status, _ = saddle_api("POST", "/api/saddle/results", "saddle-bogus-token",
  2128. {"session_id": raw_session, "state": "working"})
  2129. check(status == 401, "results endpoint rejects a wrong token")
  2130. status, _ = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2131. {"session_id": 99999, "chunks": []})
  2132. check(status == 400, "chunks for an unknown session rejected")
  2133. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2134. {"session_id": raw_session, "state": "done"})
  2135. check(status == 200, "the owning saddle's session accepts its results")
  2136. # Pushed chunk idempotency: re-pushing a batch (the outbox's
  2137. # at-least-once redelivery after a lost response) consumes the
  2138. # duplicates and stores only the tail.
  2139. conn = db()
  2140. before = conn.execute("select count(*) from session_raw_log where session_id = ?",
  2141. (raw_session,)).fetchone()[0]
  2142. conn.close()
  2143. redelivery = [{"seq": r[0], "text": r[1]} for r in rows[:3]]
  2144. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2145. {"session_id": raw_session, "chunks": redelivery})
  2146. check(status == 200 and body.get("ok") is True and int(body.get("stored") or 0) == 0,
  2147. "a fully-duplicate batch stores nothing (duplicates consumed)")
  2148. fresh = [{"seq": 9000, "text": "late-flush\r\n"},
  2149. {"seq": 9001, "text": ""}] # truly empty text: no row
  2150. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2151. {"session_id": raw_session, "chunks": fresh})
  2152. check(status == 200 and int(body.get("stored") or 0) == 1,
  2153. "a partial-redelivery batch stores only the new chunks")
  2154. conn = db()
  2155. after = conn.execute("select count(*) from session_raw_log where session_id = ?",
  2156. (raw_session,)).fetchone()[0]
  2157. empty_row = conn.execute(
  2158. "select count(*) from session_raw_log where session_id = ? and seq = 9001",
  2159. (raw_session,)).fetchone()[0]
  2160. conn.close()
  2161. check(after == before + 1 and empty_row == 0,
  2162. "redelivered chunks never duplicate rows; empty text stores nothing")
  2163. # Pushed entries: today's OutputEntry shape with the daemon's
  2164. # global entry ids — a redelivered results push stores its
  2165. # entries exactly once.
  2166. def command_rows(session):
  2167. conn = db()
  2168. try:
  2169. return conn.execute(
  2170. "select command_text, type from session_commands"
  2171. " where session_id = ? order by id", (session,)).fetchall()
  2172. finally:
  2173. conn.close()
  2174. entries = [{"id": 8101, "command": "sed -n 1p README.md", "output": "# demo",
  2175. "exit_code": 0, "type": "command", "timestamp": "2026-09-06T00:00:00Z"}]
  2176. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2177. {"session_id": raw_session, "state": "working",
  2178. "entries": entries})
  2179. check(status == 200, "entries push accepted")
  2180. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2181. {"session_id": raw_session, "state": "working",
  2182. "entries": entries})
  2183. check(status == 200, "redelivered entries push accepted (at-least-once)")
  2184. stored = command_rows(raw_session)
  2185. check(len([r for r in stored if r[0] == "sed -n 1p README.md"]) == 1,
  2186. "redelivered entries store exactly once (entry-id cursor)")
  2187. # The retired daemon routes 404 (phase 2 deleted /output, /log
  2188. # and /start serving) — and the web app never calls them.
  2189. for method, path in (("GET", "/output?since=0"), ("GET", "/log?since=0"),
  2190. ("POST", "/start")):
  2191. request = urllib.request.Request(
  2192. "http://127.0.0.1:%d%s" % (fake.port, path),
  2193. data=b"{}" if method == "POST" else None, method=method)
  2194. try:
  2195. urllib.request.urlopen(request, timeout=5)
  2196. gone = False
  2197. except urllib.error.HTTPError as error:
  2198. gone = error.code == 404
  2199. check(gone, "the fake daemon's %s %s is deleted (404)" % (method, path))
  2200. with open(os.path.join(WORK, "app.log")) as handle:
  2201. app_log = handle.read()
  2202. check("Saddle output request" not in app_log and "Saddle log request" not in app_log,
  2203. "the web never polls /output or /log anymore")
  2204. print("== capabilities: tag-based routing ==")
  2205. saddles_state = slot_public(auth, "/saddles", "saddles")
  2206. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2207. act(auth, saddles_state["create_capability"], {"name": "bigmem"})
  2208. saddles_state = slot_public(auth, "/saddles", "saddles")
  2209. caps = {c["name"]: c for c in saddles_state["capabilities"]}
  2210. check(len(caps) == 2 and all(int(c["saddle_count"]) == 0 and int(c["task_count"]) == 0
  2211. for c in caps.values()),
  2212. "capabilities created and listed with zero usage")
  2213. fake_card = saddle_card(auth, "fake-saddle")
  2214. check(fake_card["capabilities"] == [],
  2215. "saddle card starts with no capability chips")
  2216. # A task requiring 'gpu' waits while the only idle saddle lacks it;
  2217. # a later task without requirements still dispatches (skip-and-continue).
  2218. tasks_state = slot_public(auth, "/tasks", "tasks")
  2219. task_id_tmp = create_queued(auth, {
  2220. "project_id": "1",
  2221. "title": "GPU task",
  2222. "priority": "2",
  2223. })
  2224. gpu_task = task_id_tmp
  2225. detail = task_state(auth, gpu_task)
  2226. act(auth, detail["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  2227. detail = task_state(auth, gpu_task)
  2228. check([c["name"] for c in detail["capabilities"]] == ["gpu"],
  2229. "task page lists the required capability")
  2230. # The only idle saddle lacks the tag, so the queue flags the wait
  2231. # (read before any other task claims the idle saddle).
  2232. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2233. if int(t["id"]) == gpu_task][0]
  2234. check(queue["status"] == "queued" and queue["capabilities"] == ["gpu"]
  2235. and queue.get("waiting_for_saddle") is True,
  2236. "queue row shows the waiting task with its tag and wait flag")
  2237. task_id_tmp = create_queued(auth, {
  2238. "project_id": "1",
  2239. "title": "Any-saddle task",
  2240. "priority": "3",
  2241. })
  2242. any_task = task_id_tmp
  2243. check(wait_for(lambda: task_state(auth, any_task).get("status") != "queued" or False,
  2244. timeout=30, what="uncapable task dispatches") is not None,
  2245. "task without requirements dispatches past the waiting task")
  2246. def capability_wait_logged():
  2247. with open(os.path.join(WORK, "app.log")) as handle:
  2248. app_log = handle.read()
  2249. return "waits for a capable saddle" in app_log and "requires: gpu" in app_log
  2250. check(wait_for(capability_wait_logged, timeout=20,
  2251. what="capability wait log") is not None,
  2252. "dispatcher logs the capability wait")
  2253. # Attaching the tag to the saddle releases the task.
  2254. fake_card = saddle_card(auth, "fake-saddle")
  2255. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  2256. fake_card = saddle_card(auth, "fake-saddle")
  2257. check([c["name"] for c in fake_card["capabilities"]] == ["gpu"],
  2258. "saddle card shows the attached chip")
  2259. check(wait_task_done(auth, gpu_task, timeout=60) is not None,
  2260. "task dispatches once the saddle carries the required tag")
  2261. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2262. if int(t["id"]) == gpu_task][0]
  2263. check(queue.get("waiting_for_saddle") is not True,
  2264. "wait flag clears once dispatched")
  2265. # Multi-tag: gpu + bigmem required, only gpu carried → waits; adding
  2266. # bigmem completes the superset. Both requirements ride the create
  2267. # form (atomic — attaching them one at a time would race a tick
  2268. # into dispatching on the partial set).
  2269. task_id_tmp = create_queued(auth, {
  2270. "project_id": "1",
  2271. "title": "Big task",
  2272. "priority": "2",
  2273. "capability_id": [str(int(caps["gpu"]["id"])), str(int(caps["bigmem"]["id"]))],
  2274. })
  2275. big_task = task_id_tmp
  2276. check(wait_for(lambda: ([t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2277. if int(t["id"]) == big_task][0].get("waiting_for_saddle")
  2278. is True) or False, timeout=30, what="big task waits") is not None,
  2279. "task waits when the saddle's tags are not a superset")
  2280. fake_card = saddle_card(auth, "fake-saddle")
  2281. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["bigmem"]["id"]))})
  2282. check(wait_task_done(auth, big_task, timeout=60) is not None,
  2283. "task dispatches once the superset is complete")
  2284. # Detach a requirement (on a draft — capabilities lock once a
  2285. # worker has the job); delete a capability everywhere.
  2286. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2287. "project_id": "1",
  2288. "title": "Detach probe task",
  2289. "priority": "4",
  2290. "capability_id": [str(int(caps["gpu"]["id"])), str(int(caps["bigmem"]["id"]))],
  2291. })
  2292. detach_probe = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2293. if t["title"] == "Detach probe task"][0])
  2294. act(auth, [c for c in task_state(auth, detach_probe)["capabilities"]
  2295. if c["name"] == "bigmem"][0]["detach"], {})
  2296. check([c["name"] for c in task_state(auth, detach_probe)["capabilities"]] == ["gpu"],
  2297. "detached requirement disappears from the task")
  2298. bigmem_row = [c for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2299. if c["name"] == "bigmem"][0]
  2300. act(auth, bigmem_row["delete"], {})
  2301. saddles_state = slot_public(auth, "/saddles", "saddles")
  2302. check(all(c["name"] != "bigmem" for c in saddles_state["capabilities"]),
  2303. "deleted capability gone from the catalogue")
  2304. check([c["name"] for c in task_state(auth, big_task)["capabilities"]] == ["gpu"],
  2305. "deleting a capability drops its task requirements")
  2306. check(all(c["name"] != "bigmem"
  2307. for c in saddle_card(auth, "fake-saddle")["capabilities"]),
  2308. "deleting a capability drops it from saddles")
  2309. print("== B4: required capabilities on the create form ==")
  2310. tasks_state = slot_public(auth, "/tasks", "tasks")
  2311. gpu_option = [o for o in tasks_state.get("capability_options", [])
  2312. if o["name"] == "gpu"][0]
  2313. check(len(tasks_state.get("capability_options", [])) >= 1,
  2314. "queue page offers capability options in the create form")
  2315. conn = db()
  2316. before = conn.execute("select count(*) from tasks").fetchone()[0]
  2317. conn.close()
  2318. act(auth, tasks_state["create"], {
  2319. "project_id": "1",
  2320. "title": "Bad cap task",
  2321. "capability_id": [gpu_option["id"], "999"],
  2322. })
  2323. conn = db()
  2324. after = conn.execute("select count(*) from tasks").fetchone()[0]
  2325. conn.close()
  2326. check(after == before, "unknown capability id rejects the create")
  2327. task_id_tmp = create_queued(auth, {
  2328. "project_id": "1",
  2329. "title": "Cap-on-create task",
  2330. "capability_id": [gpu_option["id"]],
  2331. })
  2332. cap_create = task_id_tmp
  2333. detail = task_state(auth, cap_create)
  2334. check([c["name"] for c in detail["capabilities"]] == ["gpu"],
  2335. "capabilities from the create form land on the task")
  2336. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2337. if int(t["id"]) == cap_create][0]
  2338. check(queue["capabilities"] == ["gpu"],
  2339. "queue row shows the created task's requirements")
  2340. # The waiting flag must hold it back until the capable saddle frees
  2341. # up (the fake saddle still carries gpu from the routing checks).
  2342. check(queue.get("waiting_for_saddle") is not True,
  2343. "capable saddle available: no wait flag on the new task")
  2344. print("== retry + resume ==")
  2345. # A daemon-side failure fails the task with its explanation.
  2346. fake.fail_next = True
  2347. task_id_tmp = create_queued(auth, {
  2348. "project_id": "1",
  2349. "title": "Flaky task",
  2350. "priority": "2",
  2351. })
  2352. flaky = task_id_tmp
  2353. check(wait_for(lambda: task_state(auth, flaky).get("status") == "failed" or False,
  2354. timeout=60, what="flaky task fails") is not None,
  2355. "daemon failure fails the task")
  2356. detail = task_state(auth, flaky)
  2357. check("bash -n rejected" in (detail.get("summary") or ""),
  2358. "failure summary shows the daemon's explanation")
  2359. # Retry: summary moves into a comment and clears, task requeues,
  2360. # history stays, and the re-dispatch restores the workspace.
  2361. comments_before = len(detail.get("comments", []))
  2362. progress_before = len(detail.get("progress", []))
  2363. act(auth, detail["retry"], {})
  2364. detail = task_state(auth, flaky)
  2365. check(detail["status"] == "queued" and (detail.get("summary") or "") == "",
  2366. "retry requeues the task and clears the stale summary")
  2367. check(any("bash -n rejected" in c["body"] for c in detail["comments"]),
  2368. "failure explanation kept as a bot comment")
  2369. check(any(c["body"] == "Task retried by user" for c in detail["comments"]),
  2370. "retry lands its audit comment")
  2371. check(len(detail["comments"]) >= comments_before + 1,
  2372. "retry keeps the comment history")
  2373. pushes_before = len([p for p in fake.start_payloads
  2374. if int(p.get("task", {}).get("id") or 0) == flaky])
  2375. check(wait_for(lambda: len([p for p in fake.start_payloads
  2376. if int(p.get("task", {}).get("id") or 0) == flaky])
  2377. > pushes_before or False, timeout=60,
  2378. what="flaky task re-dispatched") is not None,
  2379. "retried task dispatches again")
  2380. # The resumed arc surfaces on the next /status read — in the
  2381. # push world that is the operator's manual refresh.
  2382. act(auth, saddle_card(auth, "fake-saddle")["refresh"], {})
  2383. check(wait_task_done(auth, flaky, timeout=60) is not None,
  2384. "retried task completes on the restored workspace")
  2385. detail = task_state(auth, flaky)
  2386. check(any("restored the session context" in p["summary"]
  2387. for p in detail.get("progress", [])),
  2388. "daemon resume reported on the first status after the restore")
  2389. check(len(detail["progress"]) > progress_before,
  2390. "resume note appended to the progress timeline")
  2391. # Manual resume: a task stuck working on an offline saddle.
  2392. task_id_tmp = create_queued(auth, {
  2393. "project_id": "1",
  2394. "title": "Stuck task",
  2395. "priority": "2",
  2396. })
  2397. stuck = task_id_tmp
  2398. check(wait_for(lambda: task_state(auth, stuck).get("status") == "working" or False,
  2399. timeout=60, what="stuck task starts working") is not None,
  2400. "stuck task reaches working")
  2401. # Deterministic claim for the resume leg below: the round's end,
  2402. # the refresh probe AND the dispatcher's wake for the requeued task
  2403. # all trigger self-asks that could steal it — freeze every trigger
  2404. # until the manual ask below has made the claim.
  2405. fake.ask_on_terminal = False
  2406. fake.ask_on_idle_status = False
  2407. fake.ask_on_wake = False
  2408. fake.settle_asks()
  2409. conn = db()
  2410. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  2411. conn.commit()
  2412. conn.close()
  2413. detail = task_state(auth, stuck)
  2414. check(detail.get("resume_available") is True,
  2415. "task page offers resume while its saddle is offline")
  2416. # The resume POSTs task-update cancel to the daemon; the abort
  2417. # handler fires an ungated re-ask that would race the manual claim
  2418. # below — slow it past the manual ask (the knob the slow-ask
  2419. # regression uses).
  2420. fake.ask_delay = 5.0
  2421. act(auth, detail["resume"], {})
  2422. detail = task_state(auth, stuck)
  2423. check(detail["status"] == "queued",
  2424. "manual resume requeues the stuck task")
  2425. check(any(c["body"] == "Saddle became unreachable; task requeued"
  2426. for c in detail["comments"]),
  2427. "manual resume lands the interruption comment")
  2428. check(all(s["status"] == "offline"
  2429. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  2430. "saddle stays offline after the manual requeue")
  2431. # Bringing the saddle back lets the requeued task resume and finish.
  2432. fake.state = "idle"
  2433. fake_card = saddle_card(auth, "fake-saddle")
  2434. act(auth, fake_card["refresh"], {})
  2435. check(any(s["status"] == "idle"
  2436. for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2437. if s["name"] == "fake-saddle"),
  2438. "refreshed saddle returns idle")
  2439. # The refreshed daemon is idle-awake: it asks (the real loop's
  2440. # own ask; driven directly for determinism — every self-ask trigger
  2441. # is frozen and the abort re-ask is slowed past it; joining that
  2442. # delayed thread here would fire its ask first, so it is left to
  2443. # sleep out the rest of the bundle).
  2444. status, payload = fake.ask_now()
  2445. fake.ask_on_idle_status = True
  2446. fake.ask_on_terminal = True
  2447. fake.ask_on_wake = True
  2448. fake.ask_delay = 0.0
  2449. check(status == 200, "the refreshed daemon's ask claims the requeued task")
  2450. check(wait_task_done(auth, stuck, timeout=60) is not None,
  2451. "requeued task resumes on the refreshed saddle and completes")
  2452. # =============================================================================
  2453. # Bundle: subtasks — the plan-12 task graph: plain-task parking (no
  2454. # subtask events exist to resume it), the DELETED subtask machinery's
  2455. # verbatim refusals, and the goal agent's task CLI in depth
  2456. # (capabilities, ownership, the daemon's task-reading API, the
  2457. # goal-run mirror block answered from the task page).
  2458. # =============================================================================
  2459. def bundle_subtasks(ctx):
  2460. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2461. app = ctx.app
  2462. # A hold tag nothing carries: goal tasks created with it stay
  2463. # queued (a stable parked agent) until released at the settle.
  2464. saddles_state = slot_public(auth, "/saddles", "saddles")
  2465. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2466. gpu_cap_id = [c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2467. if c["name"] == "gpu"][0]
  2468. def goal_state(goal_id):
  2469. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  2470. def create_goal_row(fields):
  2471. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  2472. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  2473. if g["title"] == fields["title"]]
  2474. return int(rows[0]["id"])
  2475. print("== B7: plain-task parking stays put (no subtask events) ==")
  2476. fake.suspend_on_title = "Suspend plain"
  2477. pushes_before = len(fake.start_payloads)
  2478. plain = create_queued(auth, {
  2479. "project_id": "1",
  2480. "title": "Suspend plain",
  2481. "priority": "2",
  2482. })
  2483. check(wait_for(lambda: task_state(auth, plain).get("status") == "suspended"
  2484. or False, timeout=60, what="plain task parks") is not None,
  2485. "daemon 'suspended' state parks the task")
  2486. detail = task_state(auth, plain)
  2487. check(detail.get("display") == "parked",
  2488. "a parked plain task displays as parked (%s)" % detail.get("display"))
  2489. check(any(s["status"] == "idle"
  2490. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  2491. "suspension frees the saddle")
  2492. first_push = fake.start_payloads[pushes_before]
  2493. check(first_push.get("kind") == "task" and first_push.get("creator") == "human"
  2494. and first_push.get("mode") == "implement",
  2495. "the /start payload carries the plan-12 identity triplet (kind/creator/mode)")
  2496. check("subtasks" not in first_push and "parent" not in first_push,
  2497. "the plan-12 payload drops the subtasks/parent members")
  2498. # Other tasks finishing must NOT resume a parked plain task (the
  2499. # subtask-event channel is gone; only goal events resume goal runs).
  2500. conn = db()
  2501. conn.execute("insert into tasks (project_id, title, status, priority, summary,"
  2502. " completed_at, created_at) values (1, 'Unrelated finisher', 'done',"
  2503. " 5, 'finished loudly', strftime('%s','now','+1 second'),"
  2504. " strftime('%s','now'))")
  2505. conn.commit()
  2506. conn.close()
  2507. check(quiet_window(quiet_seconds(),
  2508. lambda: task_state(auth, plain)["status"] == "suspended",
  2509. "plain park survives unrelated finishes"),
  2510. "a parked plain task never resumes on other tasks' events")
  2511. print("== the deleted machinery refuses, verbatim ==")
  2512. status, body = saddle_api("POST", "/api/saddle/subtask", fake_token,
  2513. {"parent_task_id": plain, "title": "ghost"})
  2514. check(status == 404,
  2515. "the /api/saddle/subtask callback route is gone (404)")
  2516. conn = db()
  2517. plain_session = conn.execute(
  2518. "select id from sessions where task_id = ? and ended_at is null",
  2519. (plain,)).fetchone()[0]
  2520. conn.close()
  2521. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2522. {"type": "subtask", "session_id": plain_session,
  2523. "data": {"title": "Ghost child"}})
  2524. check(status == 400 and "subtask" in (body.get("error") or "")
  2525. and "gone" in (body.get("error") or ""),
  2526. "the 'subtask' update type errors verbatim (%s)" % body.get("error"))
  2527. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2528. {"type": "plan", "session_id": plain_session,
  2529. "data": {"plan": "# nope"}})
  2530. check(status == 400 and "plan" in (body.get("error") or ""),
  2531. "the task-level 'plan' update type errors verbatim (%s)" % body.get("error"))
  2532. # The daemon's task CLI: no parent/plan members; goal context instead.
  2533. status, body = saddle_api("GET", "/api/saddle/task/%d" % plain, fake_token)
  2534. check(status == 200 and "plan" not in body.get("task", {})
  2535. and "parent_task_id" not in body.get("task", {})
  2536. and "goal_id" in body.get("task", {}),
  2537. "the task CLI detail drops parent/plan and carries goal_id")
  2538. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", fake_token)
  2539. check(status == 200 and all("parent_task_id" not in t and "goal_id" in t
  2540. for t in body.get("tasks", [])),
  2541. "the task CLI list drops parent_task_id and carries goal_id")
  2542. # Settle the parked plain task: nothing will resume it — cancel it.
  2543. act(auth, task_state(auth, plain)["cancel"], {})
  2544. check(wait_for(lambda: task_state(auth, plain)["status"] == "failed" or False,
  2545. timeout=30, what="parked plain task cancelled") is not None,
  2546. "the parked plain task cancels (the human cleanup path)")
  2547. print("== the goal agent's task CLI in depth ==")
  2548. goal = create_goal_row({"project_id": "1", "title": "Sequencing goal",
  2549. "brief": "Fan tasks out with the CLI.",
  2550. "branch_name": "goal/sequence"})
  2551. fake.goal_script = [("plan", "# Plan\n\n1. Fan out")]
  2552. act(auth, goal_state(goal)["start"], {})
  2553. check(wait_for(lambda: goal_state(goal)["status"] == "plan_review" or False,
  2554. timeout=60, what="sequencing goal plans") is not None,
  2555. "the sequencing goal reaches plan review")
  2556. fake.goal_script = [("suspend",)]
  2557. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  2558. {"answer": "Plan approved. Proceed with implementation."})
  2559. conn = db()
  2560. run_task = conn.execute(
  2561. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  2562. (goal,)).fetchone()[0]
  2563. agent_session = conn.execute(
  2564. "select id from sessions where task_id = ? and ended_at is null",
  2565. (run_task,)).fetchone()[0]
  2566. conn.close()
  2567. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  2568. or False, timeout=60, what="sequencing agent parks") is not None,
  2569. "the sequencing goal agent parks")
  2570. # Create with capabilities: attached until assignment (the hold
  2571. # keeps the task queued), mandate + mode stored, ephemeral branch.
  2572. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  2573. "session_id": agent_session, "title": "Held worker",
  2574. "mandate": "Do the held work.", "mode": "review",
  2575. "capabilities": ["gpu"]})
  2576. check(status == 200 and body.get("ok") is True,
  2577. "task create with a capability tag succeeds")
  2578. held = int(body["task_id"])
  2579. detail = task_state(auth, held)
  2580. check(detail["status"] == "draft" and detail["mode"] == "review",
  2581. "the held worker drafts with its mode")
  2582. check([c["name"] for c in detail.get("capabilities", [])] == ["gpu"],
  2583. "the capability attaches to the created task")
  2584. check(detail["task_branch"] == "task/%d-%d" % (goal, held)
  2585. and detail["branch_from"] == "goal/sequence",
  2586. "the CLI task's ephemeral branch pair is stored")
  2587. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  2588. "session_id": agent_session, "task_id": held})
  2589. check(status == 200, "the held worker enqueues")
  2590. check(quiet_window(3, lambda: task_state(auth, held)["status"] == "queued",
  2591. "unsatisfiable capability holds dispatch"),
  2592. "the unsatisfiable capability holds the queued worker (never assigned)")
  2593. queue_row = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2594. if int(t["id"]) == held][0]
  2595. check(queue_row.get("waiting_for_saddle") is True,
  2596. "the queue annotates the held worker as waiting for a saddle")
  2597. # The human edit path: goal tasks never carry enqueue-after (the
  2598. # field is human-tasks-only — the update silently ignores it).
  2599. act(auth, task_state(auth, held)["update"], {
  2600. "priority": "4", "enqueue_after_task_id": str(held - 1)})
  2601. check(task_state(auth, held).get("enqueue_after_task_id") in (None, 0, "0"),
  2602. "a goal task ignores the auto-enqueue-after field on edit")
  2603. # Ownership: the same saddle's goal agent cannot touch another
  2604. # goal's task; a plain session is not a goal-agent identity.
  2605. other_goal = create_goal_row({"project_id": "1", "title": "Other goal",
  2606. "brief": "b", "branch_name": "goal/other",
  2607. "priority": "9"})
  2608. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token,
  2609. {"session_id": agent_session, "title": "x",
  2610. "mandate": "m"})
  2611. scope_task = int(body["task_id"])
  2612. check(int(task_state(auth, scope_task)["goal_id"] or 0) == goal,
  2613. "the callback scopes task creation to its own goal")
  2614. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token,
  2615. {"session_id": agent_session, "task_id": scope_task})
  2616. check(status == 200, "the owned draft deletes")
  2617. check(not any(t["id"] == scope_task
  2618. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  2619. "the deleted task is gone from the queue")
  2620. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  2621. {"session_id": agent_session, "task_id": plain})
  2622. check(status == 400 and "does not belong to your goal" in (body.get("error") or ""),
  2623. "the goal agent cannot enqueue a standalone task")
  2624. # The daemon's task CLI detail carries the goal context.
  2625. status, body = saddle_api("GET", "/api/saddle/task/%d" % held, fake_token)
  2626. check(status == 200
  2627. and int(body["task"].get("goal_id") or 0) == goal
  2628. and body["task"].get("goal_title") == "Sequencing goal",
  2629. "the task CLI detail names the owning goal")
  2630. print("== the goal-run mirror block answers from the task page ==")
  2631. # A question block raised in goal context mirrors onto the run
  2632. # task; the TASK page's answer action resumes the agent with the
  2633. # verdict riding the allocation (the goal page shares the path).
  2634. fake.goal_script = [("question", "Which harness: pytest or vitest?",
  2635. ["pytest", "vitest"])]
  2636. conn = db()
  2637. conn.execute("insert into goal_events (goal_id, kind, text, created_at)"
  2638. " values (?, 'task-done', 'Task #999 Nudge — done',"
  2639. " strftime('%s','now','-5 seconds'))", (goal,))
  2640. conn.commit()
  2641. conn.close()
  2642. check(wait_for(lambda: task_state(auth, run_task)["status"] == "blocked"
  2643. or False, timeout=60, what="mirror block parks the run") is not None,
  2644. "a goal question parks the run task via its mirror block")
  2645. run_detail = task_state(auth, run_task)
  2646. mirror = [b for b in run_detail["blocks"]
  2647. if b["block_type"] == "question"][0]
  2648. check(mirror.get("question") == "Which harness: pytest or vitest?",
  2649. "the mirror block carries the goal question verbatim")
  2650. check(any(b.get("block_type") == "question" and not b.get("answered")
  2651. for b in goal_state(goal)["blocks"]),
  2652. "the goal block exists alongside (the goal page's card)")
  2653. act(auth, mirror["answer_action"], {"answer": "pytest"})
  2654. fake.goal_script = [("suspend",)]
  2655. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  2656. or False, timeout=60, what="answered mirror resumes the agent")
  2657. is not None,
  2658. "the answered mirror block resumes the goal agent")
  2659. answered = [b for b in task_state(auth, run_task)["blocks"]
  2660. if b["block_type"] == "question"][0]
  2661. check(answered.get("answer") == "pytest",
  2662. "the verdict is stored on the mirror block")
  2663. print("== settle: release the hold and let the shard drain ==")
  2664. # Drop the hold tag so the held worker can dispatch and complete;
  2665. # the parked agent resumes on its completion, re-parks (script),
  2666. # and the shard shuts down with an empty queue.
  2667. act(auth, task_state(auth, held)["capabilities"][0]["detach"], {})
  2668. check(wait_task_done(auth, held, timeout=90) is not None,
  2669. "the released held worker completes")
  2670. check(wait_for(lambda: any(e["kind"] == "task-done" and int(e["task_id"]) == held
  2671. for e in goal_state(goal)["events"]) or False,
  2672. timeout=30, what="narrative hears the held worker") is not None,
  2673. "the narrative records the held worker's completion")
  2674. act(auth, goal_state(goal)["cancel"], {})
  2675. check(wait_for(lambda: goal_state(goal)["status"] == "cancelled" or False,
  2676. timeout=30, what="sequencing goal cancelled") is not None,
  2677. "the sequencing goal cancels (the shard's cleanup path)")
  2678. # =============================================================================
  2679. # Bundle: lineage — the plan-12 goal lineage: goal context on worker
  2680. # dispatches (read-only reference + ephemeral branch), the daemon's
  2681. # task-reading API (goal members, no parent/plan), and the goal
  2682. # agent's workspace affinity while parked.
  2683. # =============================================================================
  2684. def bundle_lineage(ctx):
  2685. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2686. app = ctx.app
  2687. r4_token = fake_token
  2688. # gpu exists only as a hold (no saddle carries it): the held goal
  2689. # worker stays queued until the release loop lifts it.
  2690. saddles_state = slot_public(auth, "/saddles", "saddles")
  2691. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2692. def goal_state(goal_id):
  2693. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  2694. def create_goal_row(fields):
  2695. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  2696. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  2697. if g["title"] == fields["title"]]
  2698. return int(rows[0]["id"])
  2699. goal = create_goal_row({"project_id": "1", "title": "Lineage goal",
  2700. "brief": "Carry the goal lineage.",
  2701. "branch_name": "goal/lineage"})
  2702. fake.goal_script = [("plan", "# Lineage plan\n\n1. Fan out\n2. Verify")]
  2703. act(auth, goal_state(goal)["start"], {})
  2704. check(wait_for(lambda: goal_state(goal)["status"] == "plan_review" or False,
  2705. timeout=60, what="lineage goal plans") is not None,
  2706. "the lineage goal reaches plan review")
  2707. fake.goal_script = [("suspend",)]
  2708. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  2709. {"answer": "Plan approved. Proceed with implementation."})
  2710. conn = db()
  2711. auto_parent = conn.execute(
  2712. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  2713. (goal,)).fetchone()[0]
  2714. agent_session = conn.execute(
  2715. "select id from sessions where task_id = ? and ended_at is null",
  2716. (auto_parent,)).fetchone()[0]
  2717. conn.close()
  2718. check(wait_for(lambda: task_state(auth, auto_parent)["status"] == "suspended"
  2719. or False, timeout=60, what="lineage goal agent parks") is not None,
  2720. "the lineage goal agent parks")
  2721. # Two workers under the goal: one free, one held by the gpu tag.
  2722. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2723. "session_id": agent_session, "title": "Auto child",
  2724. "mandate": "build the widget", "mode": "implement"})
  2725. auto_child = int(body["task_id"])
  2726. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2727. "session_id": agent_session, "title": "Auto grandchild",
  2728. "mandate": "verify the widget", "mode": "test",
  2729. "capabilities": ["gpu"]})
  2730. auto_grand = int(body["task_id"])
  2731. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2732. "session_id": agent_session, "title": "Wire the flange",
  2733. "description": "torque to spec"})
  2734. check(status == 400 and "mandate is required" in (body.get("error") or ""),
  2735. "task create without a mandate errors verbatim (%s)" % body.get("error"))
  2736. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2737. "session_id": agent_session, "title": "Wire the flange",
  2738. "mandate": "torque to spec"})
  2739. flange_task = int(body["task_id"])
  2740. for held in (auto_child, auto_grand, flange_task):
  2741. saddle_api("POST", "/api/saddle/task/enqueue", r4_token,
  2742. {"session_id": agent_session, "task_id": held})
  2743. check(wait_for(lambda: task_state(auth, auto_child)["status"] in
  2744. ("queued", "assigned", "working", "done") or False,
  2745. timeout=30, what="free goal worker dispatches") is not None,
  2746. "the free goal worker dispatches")
  2747. check(quiet_window(3, lambda: task_state(auth, auto_grand)["status"] == "queued",
  2748. "held goal worker stays queued"),
  2749. "the gpu-held goal worker stays queued")
  2750. # A goal worker's dispatch carries the read-only goal context.
  2751. lineage_push = [p for p in fake.start_payloads
  2752. if int(p.get("task", {}).get("id") or 0) == auto_child][-1]
  2753. goal_ctx = lineage_push.get("goal") or {}
  2754. check(int(goal_ctx.get("id") or 0) == goal
  2755. and goal_ctx.get("branch") == "goal/lineage"
  2756. and "Carry the goal lineage." in goal_ctx.get("brief", "")
  2757. and "# Lineage plan" in goal_ctx.get("plan", ""),
  2758. "the worker dispatch carries the goal context (brief + approved plan)")
  2759. check(lineage_push.get("ephemeral_branch") == "task/%d-%d" % (goal, auto_child)
  2760. and lineage_push.get("kind") == "task"
  2761. and lineage_push.get("mode") == "implement"
  2762. and lineage_push.get("creator") == "goal",
  2763. "the worker dispatch carries the ephemeral branch + identity triplet")
  2764. check("parent" not in lineage_push and "subtasks" not in lineage_push,
  2765. "the plan-12 payload drops the parent/subtasks members")
  2766. print("== R5 B2: task-reading API ==")
  2767. status, _ = saddle_api("GET", "/api/saddle/tasks", None)
  2768. check(status == 401, "tasks endpoint rejects a missing token")
  2769. status, _ = saddle_api("GET", "/api/saddle/task/%d" % auto_child, None)
  2770. check(status == 401, "task detail endpoint rejects a missing token")
  2771. # Fixture: a second project whose tasks all carry the "Diff " title
  2772. # prefix for the project_id filter checks — created first so the
  2773. # unfiltered list has the population the count check expects.
  2774. state = slot_public(auth, "/projects", "projects")
  2775. act(auth, state["create"], {"name": "diff-fabrica",
  2776. "git_url": "ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git"})
  2777. conn = db()
  2778. other_project = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  2779. if p["name"] == "diff-fabrica"][0])
  2780. for suffix in ("fabrica", "scp"):
  2781. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  2782. " values (?, ?, 'done', 5, strftime('%s','now'))",
  2783. (other_project, "Diff %s" % suffix))
  2784. conn.commit()
  2785. conn.close()
  2786. status, body = saddle_api("GET", "/api/saddle/tasks", r4_token)
  2787. check(status == 200 and len(body.get("tasks", [])) > 5,
  2788. "tasks endpoint lists tasks without filters")
  2789. row = [t for t in body["tasks"] if int(t["id"]) == auto_child][0]
  2790. check(row["title"] == "Auto child" and int(row["goal_id"] or 0) == goal
  2791. and row["status"] in ("done", "queued", "working"),
  2792. "compact rows carry id/title/status/goal_id")
  2793. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", r4_token)
  2794. check(all(True for _ in [1]) # project 1 dominates the data set
  2795. and not any(int(t["id"]) == 0 for t in body["tasks"]),
  2796. "project_id filter accepted")
  2797. status, body = saddle_api("GET",
  2798. "/api/saddle/tasks?project_id=%d" % other_project, r4_token)
  2799. check(all(t["title"].startswith("Diff") for t in body["tasks"]),
  2800. "other project lists only its own tasks")
  2801. status, body = saddle_api("GET", "/api/saddle/tasks?q=FLANGE", r4_token)
  2802. titles = [t["title"] for t in body["tasks"]]
  2803. check("Wire the flange" in titles,
  2804. "q matches titles case-insensitively")
  2805. status, body = saddle_api("GET", "/api/saddle/tasks?q=torque%20to%20spec", r4_token)
  2806. check(any(t["title"] == "Wire the flange" for t in body["tasks"]),
  2807. "q matches mandate text")
  2808. status, body = saddle_api("GET", "/api/saddle/task/%d" % auto_child, r4_token)
  2809. task_view = body.get("task", {})
  2810. check(status == 200 and int(task_view.get("id") or 0) == auto_child
  2811. and task_view.get("goal_title") == "Lineage goal"
  2812. and int(task_view.get("goal_id") or 0) == goal,
  2813. "single-task view joins the goal title")
  2814. check("status" in task_view and "description" in task_view
  2815. and "summary" in task_view,
  2816. "single-task view carries the full detail fields")
  2817. check("plan" not in task_view and "parent_task_id" not in task_view,
  2818. "the single-task view drops the deleted parent/plan members")
  2819. status, body = saddle_api("GET", "/api/saddle/task/99999", r4_token)
  2820. check(status == 404, "unknown task id returns 404")
  2821. print("== settle: released workers resume the parked agent (coalesced) ==")
  2822. # Release the held workers: their completions wake the parked goal
  2823. # agent (affinity — the same fake hosts it) with the batched
  2824. # notice; the free worker already completed.
  2825. check(wait_task_done(auth, auto_child, timeout=90) is not None,
  2826. "the free worker settles first")
  2827. def agent_push_count():
  2828. return len([p for p in fake.goal_assignments
  2829. if int(p.get("task", {}).get("id") or 0) == auto_parent])
  2830. before_pushes = agent_push_count()
  2831. for held_task in (auto_grand, flange_task):
  2832. caps = task_state(auth, held_task).get("capabilities") or []
  2833. if caps:
  2834. act(auth, caps[0]["detach"], {})
  2835. check(wait_task_done(auth, held_task, timeout=90) is not None,
  2836. "released worker settles (%d)" % held_task)
  2837. check(wait_for(lambda: agent_push_count() > before_pushes or False,
  2838. timeout=90, what="goal agent resumes") is not None,
  2839. "the workers' completions resume the parked goal agent")
  2840. notice = ""
  2841. for p in fake.goal_assignments:
  2842. if int(p.get("task", {}).get("id") or 0) == auto_parent:
  2843. notice = p.get("resume_notice") or ""
  2844. check("Auto child" in notice and "Auto grandchild" in notice
  2845. and "Wire the flange" in notice,
  2846. "the coalesced resume notice covers every plan task")
  2847. check("New completion reports" in notice and "fake daemon finished" in notice,
  2848. "the notice carries the new completion reports")
  2849. act(auth, goal_state(goal)["cancel"], {})
  2850. check(wait_for(lambda: goal_state(goal)["status"] == "cancelled" or False,
  2851. timeout=30, what="lineage goal cancelled") is not None,
  2852. "the lineage goal cancels (drain)")
  2853. # =============================================================================
  2854. # Bundle: allocation — the ask/wake/allocate machinery: concurrent ask
  2855. # race, token revocation, workspace affinity, the lost-wake guard, the
  2856. # slow-ask regression, assignment capability context + the tag
  2857. # catalogue, and the pinned-blocks/activity dashboard.
  2858. # =============================================================================
  2859. def bundle_allocation(ctx):
  2860. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2861. app = ctx.app
  2862. r4_token = fake_token
  2863. # gpu rides the primary fake from the start (the routing bundle's
  2864. # early attach, replayed): its attach row precedes lostwake's, so
  2865. # the assignment's saddle_tags order matches the assertion in the
  2866. # capability-context section below.
  2867. saddles_state = slot_public(auth, "/saddles", "saddles")
  2868. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2869. act(auth, saddle_card(auth, "fake-saddle")["attach_capability"],
  2870. {"capability_id": str(int([c["id"] for c in
  2871. slot_public(auth, "/saddles", "saddles")["capabilities"]
  2872. if c["name"] == "gpu"][0]))})
  2873. print("== phase 1: ask/allocation — token auth + concurrent race ==")
  2874. # Plan 10 phase 1. Registration mints per-saddle tokens; the
  2875. # ask endpoint authenticates by them; concurrent asks race to
  2876. # exactly one winner through the allocation transaction.
  2877. status, _ = saddle_api("POST", "/api/saddle/next-task", None)
  2878. check(status == 401, "next-task rejects a missing token")
  2879. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-bogus-token")
  2880. check(status == 401, "next-task rejects a wrong token")
  2881. status, body = saddle_api("POST", "/api/saddle/next-task", fake_token)
  2882. check(status == 204, "next-task answers 204 (nothing offerable — daemon sleeps)")
  2883. # Two more racers: real daemons on their own ports; fake2 reports
  2884. # its ssh key at /register so the key lands on the row directly.
  2885. fake2 = FakeSaddle()
  2886. fake2.ssh_public_key = "ssh-ed25519 AAAAFake2RacerKey saddle-2@fedora"
  2887. fake2.serve(port=free_port())
  2888. fake3 = FakeSaddle()
  2889. fake3.serve(port=free_port())
  2890. saddles_state = slot_public(auth, "/saddles", "saddles")
  2891. act(auth, saddles_state["register"], {"name": "racer-two",
  2892. "host": "127.0.0.1:%d" % fake2.port})
  2893. act(auth, saddles_state["register"], {"name": "racer-three",
  2894. "host": "127.0.0.1:%d" % fake3.port})
  2895. check(wait_for(lambda: len(fake2.register_log) > 0 and len(fake3.register_log) > 0
  2896. or False, timeout=15, what="racers registered") is not None,
  2897. "both racers received /register")
  2898. check(wait_for(lambda: "AAAAFake2RacerKey" in
  2899. [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2900. if s["name"] == "racer-two"][0].get("ssh_public_key", "") or False,
  2901. timeout=15, what="register-reported key") is not None,
  2902. "the ssh key reported at /register lands on the saddle row")
  2903. racer_cards = {}
  2904. for name, daemon in (("fake-saddle", fake), ("racer-two", fake2), ("racer-three", fake3)):
  2905. card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2906. if s["name"] == name][0]
  2907. racer_cards[daemon] = {"id": int(card["id"]), "token": card["token"]}
  2908. # Revocation: a registered saddle's token works until the saddle
  2909. # is removed, then nothing authorises its calls.
  2910. fake4 = FakeSaddle()
  2911. fake4.ask_on_register = False # a pre-flip daemon: never asks
  2912. fake4.serve(port=free_port())
  2913. saddles_state = slot_public(auth, "/saddles", "saddles")
  2914. act(auth, saddles_state["register"], {"name": "old-daemon",
  2915. "host": "127.0.0.1:%d" % fake4.port})
  2916. old_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2917. if s["name"] == "old-daemon"][0]
  2918. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  2919. check(status in (200, 204),
  2920. "the old daemon's fresh token authenticates next-task")
  2921. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  2922. {"project": "demo", "body": "from the old daemon"})
  2923. check(status == 200, "note accepts any registered saddle's token")
  2924. act(auth, old_card["unregister"], {})
  2925. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  2926. check(status == 401, "removing the saddle revokes its token")
  2927. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  2928. {"project": "demo", "body": "should fail"})
  2929. check(status == 401, "revocation covers the note endpoint too")
  2930. # Deterministic race: settle the queue first (this shard runs the
  2931. # race before any parked work exists, so only in-flight asks need
  2932. # draining), freeze every daemon's self-ask triggers, put all three
  2933. # to sleep (204), then fire one task worth of concurrent asks.
  2934. for daemon in (fake, fake2, fake3):
  2935. daemon.ask_on_register = False
  2936. daemon.ask_on_wake = False
  2937. daemon.ask_on_terminal = False
  2938. daemon.ask_on_idle_status = False
  2939. daemon.settle_asks() # converted sleep: in-flight asks land (204)
  2940. def queued_count():
  2941. conn = db()
  2942. try:
  2943. return conn.execute(
  2944. "select count(*) from tasks where status = 'queued'").fetchone()[0]
  2945. finally:
  2946. conn.close()
  2947. check(wait_for(lambda: queued_count() == 0 or False,
  2948. timeout=60, what="queue settles before the race") is not None,
  2949. "the queue settles before the race")
  2950. sleep_statuses = [daemon.ask_now()[0] for daemon in (fake, fake2, fake3)]
  2951. check(sleep_statuses == [204, 204, 204],
  2952. "all three racers sleep (204) before the task exists")
  2953. task_id_tmp = create_queued(auth, {
  2954. "project_id": "1",
  2955. "title": "Race task",
  2956. "priority": "2",
  2957. })
  2958. race_task = task_id_tmp
  2959. race_results = []
  2960. def race_ask(daemon):
  2961. # A real racing daemon accepts the assignment it wins — the
  2962. # manual ask path does exactly that on a 200.
  2963. race_results.append(daemon.ask_now())
  2964. threads = [threading.Thread(target=race_ask, args=(daemon,))
  2965. for daemon in (fake, fake2, fake3)]
  2966. for thread in threads:
  2967. thread.start()
  2968. for thread in threads:
  2969. thread.join()
  2970. race_statuses = sorted(r[0] for r in race_results)
  2971. check(race_statuses == [200, 204, 204],
  2972. "concurrent asks race to exactly one winner (%s)" % race_statuses)
  2973. winner = [r for r in race_results if r[0] == 200][0][1]
  2974. check(int(winner["task"]["id"]) == race_task, "the winner's payload carries the task")
  2975. check(int(winner["session_id"]) > 0, "the assignment carries the session id")
  2976. conn = db()
  2977. race_sessions = conn.execute(
  2978. "select count(*) from sessions where task_id = ?", (race_task,)).fetchone()[0]
  2979. conn.close()
  2980. check(race_sessions == 1,
  2981. "exactly one session row — the transaction serialised the claims (%d)"
  2982. % race_sessions)
  2983. check(wait_task_done(auth, race_task, timeout=60) is not None,
  2984. "the raced task completes on the winning daemon")
  2985. for daemon in (fake, fake2, fake3):
  2986. daemon.ask_on_register = True
  2987. daemon.ask_on_wake = True
  2988. daemon.ask_on_terminal = True
  2989. daemon.ask_on_idle_status = True
  2990. # Re-establish sleeping explicitly: the winner's post-race
  2991. # re-ask timing is not deterministic, and the affinity section
  2992. # below needs every racer provably asleep. Any stray offerable
  2993. # drains into these asks first.
  2994. def all_asleep():
  2995. return all(daemon.ask_now()[0] == 204 for daemon in (fake, fake2, fake3))
  2996. check(wait_for(lambda: all_asleep() or False, timeout=30,
  2997. what="racers re-sleep after the race") is not None,
  2998. "all racers re-sleep after the race")
  2999. print("== phase 1: workspace affinity pins parked tasks ==")
  3000. # A suspended parent parked on racer-two may be resumed ONLY by
  3001. # racer-two: a tag-capable non-affine saddle asking gets 204, and
  3002. # the wake targets the affine saddle. Only racer-two carries the
  3003. # tag at dispatch time (the race's winner is nondeterministic, so
  3004. # the park must not depend on which racers are free); racer-three
  3005. # gains it afterwards to prove the pinning is by workspace, not
  3006. # tags.
  3007. saddles_state = slot_public(auth, "/saddles", "saddles")
  3008. act(auth, saddles_state["create_capability"], {"name": "affinity-tag"})
  3009. affinity_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3010. if c["name"] == "affinity-tag"][0])
  3011. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3012. if s["name"] == "racer-two"][0]
  3013. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3014. if s["name"] == "racer-three"][0]
  3015. act(auth, racer2_card["attach_capability"], {"capability_id": str(affinity_cap)})
  3016. # Plan 12: the parked workspace is the goal agent's run task. The
  3017. # other racers sleep (frozen ask triggers), so racer-two claims
  3018. # the goal run and parks it; the goal-task event then resumes the
  3019. # agent AFFINE to racer-two — racer-three (tag-capable or not)
  3020. # gets 204, the dispatcher's wake targets racer-two.
  3021. fake.ask_on_wake = False
  3022. fake.ask_on_idle_status = False
  3023. fake.settle_asks()
  3024. fake3.ask_on_wake = False
  3025. fake3.ask_on_idle_status = False
  3026. fake3.settle_asks()
  3027. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  3028. "project_id": "1", "title": "Affinity goal",
  3029. "brief": "Parks on racer-two.", "branch_name": "goal/affinity"})
  3030. conn = db()
  3031. affinity_goal = conn.execute(
  3032. "select id from goals where title = 'Affinity goal'").fetchone()[0]
  3033. conn.close()
  3034. fake2.goal_script = [("plan", "# Affinity plan\n\n1. Park")]
  3035. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")["start"], {})
  3036. check(wait_for(lambda: slot_public(auth, "/goals/%d" % affinity_goal,
  3037. "goal")["status"] == "plan_review" or False,
  3038. timeout=60, what="affinity goal plans") is not None,
  3039. "the affinity goal reaches plan review (racer-two hosting)")
  3040. fake2.goal_script = [("suspend",)]
  3041. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")
  3042. ["plan_pending_block"]["answer_action"],
  3043. {"answer": "Plan approved. Proceed with implementation."})
  3044. conn = db()
  3045. affinity_parent = conn.execute(
  3046. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  3047. (affinity_goal,)).fetchone()[0]
  3048. agent_session = conn.execute(
  3049. "select id from sessions where task_id = ? and ended_at is null",
  3050. (affinity_parent,)).fetchone()[0]
  3051. conn.close()
  3052. status, resume_payload = fake2.ask_now()
  3053. check(status == 200 and int(resume_payload["task"]["id"]) == affinity_parent,
  3054. "the approved plan resumes the agent on racer-two (its workspace)")
  3055. check(wait_for(lambda: task_state(auth, affinity_parent).get("status") == "suspended"
  3056. or False, timeout=60, what="affinity agent parks") is not None,
  3057. "the affinity goal agent parks on racer-two")
  3058. conn = db()
  3059. affinity_session = conn.execute(
  3060. "select saddle_id from sessions where task_id = ? and ended_at is null",
  3061. (affinity_parent,)).fetchone()[0]
  3062. conn.close()
  3063. check(affinity_session == int(racer2_card["id"]),
  3064. "the parked workspace sits on racer-two")
  3065. # Now racer-three carries the tag too — the pinning is by
  3066. # workspace, not tags. With nothing due, a non-affine ask gets 204.
  3067. act(auth, racer3_card["attach_capability"], {"capability_id": str(affinity_cap)})
  3068. status, _ = fake3.ask_now()
  3069. check(status == 204,
  3070. "a tag-capable non-affine saddle is refused the parked agent (204)")
  3071. # A goal task completing makes the parked agent resume-offerable —
  3072. # affine to racer-two only. The other racers wake back up (they
  3073. # host the worker; their claims of the parked agent get refused as
  3074. # non-affine), while racer-two's ask triggers stay frozen so the
  3075. # wake measurement stays clean. A wake may have hit the frozen
  3076. # racers while the goal run queued (the lost-wake guard marks them
  3077. # offline): the refresh probe brings them back before the worker.
  3078. fake.ask_on_wake = True
  3079. fake.ask_on_idle_status = True
  3080. fake3.ask_on_wake = True
  3081. fake3.ask_on_idle_status = True
  3082. for racer_name in ("fake-saddle", "racer-three"):
  3083. act(auth, saddle_card(auth, racer_name)["refresh"], {})
  3084. check(wait_for(lambda name=racer_name: [s for s in
  3085. slot_public(auth, "/saddles", "saddles")["saddles"]
  3086. if s["name"] == name][0]["status"] == "idle"
  3087. or False, timeout=15, what="racer re-onlined") is not None,
  3088. "%s re-onlined after its frozen-window wake" % racer_name)
  3089. fake2.ask_on_wake = False
  3090. fake2.ask_on_idle_status = False
  3091. wakes_before_2 = len(fake2.wake_log)
  3092. fake2.settle_asks() # converted sleep: park-time ask lands (204)
  3093. status, body = saddle_api("POST", "/api/saddle/task/create", fake2.token, {
  3094. "session_id": agent_session, "title": "Affinity child",
  3095. "mandate": "finish the affinity fixture"})
  3096. check(status == 200, "the parked agent fans its worker out via the CLI")
  3097. affinity_child = int(body["task_id"])
  3098. saddle_api("POST", "/api/saddle/task/enqueue", fake2.token,
  3099. {"session_id": agent_session, "task_id": affinity_child})
  3100. check(wait_task_done(auth, affinity_child, timeout=90) is not None,
  3101. "the affinity worker completes (on a non-affine racer)")
  3102. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_2 or False,
  3103. timeout=30, what="affine wake") is not None,
  3104. "the dispatcher's wake targets the affine saddle")
  3105. status, resume_payload = fake2.ask_now()
  3106. fake2.ask_on_wake = True # restored whatever the claim returned
  3107. fake2.ask_on_idle_status = True
  3108. check(status == 200 and int(resume_payload["task"]["id"]) == affinity_parent,
  3109. "the affine saddle's ask claims the parked agent")
  3110. check("Affinity child" in (resume_payload.get("resume_notice") or "")
  3111. and "fake daemon finished" in (resume_payload.get("resume_notice") or ""),
  3112. "the resume assignment carries the goal's batched report notice")
  3113. check(wait_for(lambda: task_state(auth, affinity_parent).get("status")
  3114. == "suspended" or False,
  3115. timeout=60, what="affinity agent re-parks") is not None,
  3116. "the resumed agent re-parks (script)")
  3117. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")["cancel"], {})
  3118. check(wait_for(lambda: slot_public(auth, "/goals/%d" % affinity_goal,
  3119. "goal")["status"] == "cancelled" or False,
  3120. timeout=30, what="affinity goal cancelled") is not None,
  3121. "the affinity goal cancels (drain)")
  3122. print("== phase 1: lost wake -> offline + re-wake of the next capable ==")
  3123. # racer-three sleeps through wakes (a daemon that died after its
  3124. # last 204): the guard window (SADDLE_LOST_WAKE_S=2) passes with
  3125. # no ask, the saddle goes offline, and the work moves to the
  3126. # next capable sleeping saddle.
  3127. fake3.ask_on_wake = False
  3128. fake3.ask_on_idle_status = False # sleeps through everything
  3129. saddles_state = slot_public(auth, "/saddles", "saddles")
  3130. act(auth, saddles_state["create_capability"], {"name": "lostwake"})
  3131. lostwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3132. if c["name"] == "lostwake"][0])
  3133. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3134. if s["name"] == "racer-three"][0]
  3135. act(auth, racer3_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  3136. # Racer-three must be asleep to be woken: park it with a manual
  3137. # 204 ask (nothing offerable for it — the task below is not
  3138. # created yet).
  3139. status, _ = fake3.ask_now()
  3140. check(status == 204, "racer-three sleeps before the lost-wake run")
  3141. task_id_tmp = create_queued(auth, {
  3142. "project_id": "1",
  3143. "title": "Lost wake task",
  3144. "priority": "2",
  3145. "capability_id": [str(lostwake_cap)],
  3146. })
  3147. lost_task = task_id_tmp
  3148. check(wait_for(lambda: len(fake3.wake_log) > 0 or False,
  3149. timeout=30, what="wake sent to racer-three") is not None,
  3150. "the only capable sleeping saddle is woken")
  3151. check(wait_for(lambda: [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3152. if s["name"] == "racer-three"][0]["status"] == "offline"
  3153. or False, timeout=30, what="lost-wake -> offline") is not None,
  3154. "no ask after the wake: the saddle goes offline (lost-wake guard)")
  3155. check(task_state(auth, lost_task)["status"] == "queued",
  3156. "the task is untouched while its wake was pending")
  3157. # Re-wake the next capable: the healthy saddle gains the tag and
  3158. # picks the work up via its own wake -> ask -> allocate roundtrip.
  3159. fake_card = saddle_card(auth, "fake-saddle")
  3160. act(auth, fake_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  3161. wakes_before = len(fake.wake_log)
  3162. check(wait_for(lambda: len(fake.wake_log) > wakes_before or False,
  3163. timeout=30, what="re-wake of the next capable") is not None,
  3164. "the next capable sleeping saddle is woken for the task")
  3165. check(wait_task_done(auth, lost_task, timeout=60) is not None,
  3166. "wake -> ask -> allocate: the task completes on the healthy saddle")
  3167. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == lost_task
  3168. for p in fake.start_payloads) or False,
  3169. timeout=10, what="lost task assignment captured") is not None,
  3170. "the re-woken saddle's ask produced the assignment")
  3171. fake3.ask_on_wake = True
  3172. fake3.ask_on_idle_status = True
  3173. print("== phase 3: capability context, catalogue, subtask tags ==")
  3174. # Assignment capability context (plan 10 phase 3): every
  3175. # assignment carries {saddle_tags: the allocated saddle's tags,
  3176. # fleet_tags: every tag name known across the fleet} — the
  3177. # daemon renders it into its system prompt. fake-saddle carries
  3178. # gpu + lostwake; the catalogue is affinity-tag, gpu, lostwake.
  3179. fake2.ask_on_register = False
  3180. fake2.ask_on_wake = False
  3181. fake2.ask_on_terminal = False
  3182. fake2.ask_on_idle_status = False
  3183. fake2.settle_asks() # converted sleep: in-flight trigger asks land
  3184. task_id_tmp = create_queued(auth, {
  3185. "project_id": "1",
  3186. "title": "Capabilities context",
  3187. "priority": "2",
  3188. })
  3189. cap_task = task_id_tmp
  3190. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == cap_task
  3191. for p in fake.start_payloads) or False,
  3192. timeout=60, what="capabilities-context task dispatched") is not None,
  3193. "the capabilities-context task dispatches")
  3194. cap_payload = [p for p in fake.start_payloads
  3195. if int(p.get("task", {}).get("id") or 0) == cap_task][-1]
  3196. context = cap_payload.get("capabilities") or {}
  3197. check(context.get("saddle_tags") == ["gpu", "lostwake"],
  3198. "assignment saddle_tags = the allocated saddle's tags (%s)"
  3199. % context.get("saddle_tags"))
  3200. check(context.get("fleet_tags") == ["affinity-tag", "gpu", "lostwake"],
  3201. "assignment fleet_tags = every tag name known across the fleet (%s)"
  3202. % context.get("fleet_tags"))
  3203. check(wait_task_done(auth, cap_task, timeout=60) is not None,
  3204. "capabilities-context task completes")
  3205. # GET /api/saddle/capabilities feeds the daemon's `saddle
  3206. # capabilities` CLI: per-saddle-token auth, tag order by name,
  3207. # each tag with the saddles carrying it (name order).
  3208. status, _ = saddle_api("GET", "/api/saddle/capabilities", None)
  3209. check(status == 401, "capabilities endpoint rejects a missing token")
  3210. status, body = saddle_api("GET", "/api/saddle/capabilities", "saddle-bogus")
  3211. check(status == 401, "capabilities endpoint rejects a wrong token")
  3212. status, body = saddle_api("GET", "/api/saddle/capabilities", fake_token)
  3213. catalogue = {t["name"]: t["saddles"] for t in body.get("tags", [])}
  3214. check(status == 200 and body.get("ok") is True
  3215. and [t["name"] for t in body.get("tags", [])]
  3216. == ["affinity-tag", "gpu", "lostwake"],
  3217. "catalogue lists every tag by name")
  3218. check(catalogue.get("gpu") == ["fake-saddle"]
  3219. and catalogue.get("affinity-tag") == ["racer-three", "racer-two"]
  3220. and catalogue.get("lostwake") == ["fake-saddle", "racer-three"],
  3221. "each tag names its carrying saddles in name order (%s)" % catalogue)
  3222. # Task CLI capabilities (`task create --capability`): validated
  3223. # against the operator tag set; unknown tags reject with the valid
  3224. # list in the error (the agent reads it verbatim in the CLI
  3225. # output). A goal agent's parked session hosts the calls.
  3226. fake.suspend_on_title = "Tag host"
  3227. tag_host = create_queued(auth, {
  3228. "project_id": "1", "title": "Tag host", "priority": "3"})
  3229. check(wait_for(lambda: task_state(auth, tag_host)["status"] == "suspended"
  3230. or False, timeout=60, what="tag host parks") is not None,
  3231. "a parked plain task hosts nothing (no goal scope)")
  3232. # The goal callbacks need a real goal agent: reuse the sequencing
  3233. # goal pattern — a fresh parked agent under this shard.
  3234. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  3235. "project_id": "1", "title": "Tag goal", "brief": "b",
  3236. "branch_name": "goal/tags"})
  3237. conn = db()
  3238. tag_goal = conn.execute("select id from goals where title = 'Tag goal'").fetchone()[0]
  3239. conn.close()
  3240. fake.goal_script = [("suspend",)]
  3241. act(auth, slot_public(auth, "/goals/%d" % tag_goal, "goal")["start"], {})
  3242. conn = db()
  3243. tag_run = conn.execute(
  3244. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  3245. (tag_goal,)).fetchone()[0]
  3246. conn.close()
  3247. check(wait_for(lambda: task_state(auth, tag_run)["status"] == "suspended"
  3248. or False, timeout=60, what="tag goal agent parks") is not None,
  3249. "the tag goal agent parks")
  3250. conn = db()
  3251. tag_session = conn.execute(
  3252. "select id from sessions where task_id = ? and ended_at is null",
  3253. (tag_run,)).fetchone()[0]
  3254. conn.close()
  3255. conn = db()
  3256. tag_host_saddle = conn.execute(
  3257. "select saddle_id from sessions where id = ?", (tag_session,)).fetchone()[0]
  3258. conn.close()
  3259. racer2_card_id = int([c for c in slot_public(auth, "/saddles", "saddles")["saddles"]
  3260. if c["name"] == "racer-two"][0]["id"])
  3261. racer3_card_id = int([c for c in slot_public(auth, "/saddles", "saddles")["saddles"]
  3262. if c["name"] == "racer-three"][0]["id"])
  3263. host_daemon = {int(fake_id): fake, racer2_card_id: fake2,
  3264. racer3_card_id: fake3}[int(tag_host_saddle)]
  3265. status, body = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3266. "session_id": tag_session, "title": "Bad tag worker",
  3267. "mandate": "m", "capabilities": ["gpu", "warp-drive"]})
  3268. check(status == 400, "an unknown capability tag rejects the task call")
  3269. error_text = body.get("error", "")
  3270. check("warp-drive" in error_text and "valid tags" in error_text
  3271. and "gpu" in error_text and "lostwake" in error_text,
  3272. "the rejection names the unknown tag and the valid list (%s)" % error_text)
  3273. status, _ = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3274. "session_id": tag_session, "title": "Bad shape worker",
  3275. "mandate": "m", "capabilities": "gpu"})
  3276. check(status == 400, "a non-array capabilities member rejects")
  3277. # A valid tag creates the goal worker in draft with exactly the
  3278. # explicit tag attached; the goal agent enqueues it.
  3279. status, body = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3280. "session_id": tag_session, "title": "Explicit tag worker",
  3281. "mandate": "do the tagged work", "capabilities": ["gpu"]})
  3282. check(status == 200 and body.get("ok") is True,
  3283. "a valid tag creates the task synchronously")
  3284. tagged_worker = int(body["task_id"])
  3285. detail = task_state(auth, tagged_worker)
  3286. check([c["name"] for c in detail.get("capabilities", [])] == ["gpu"],
  3287. "the worker carries exactly the explicit tag")
  3288. conn = db()
  3289. tag_rows = conn.execute(
  3290. "select c.name from task_capabilities tc"
  3291. " join capabilities c on c.id = tc.capability_id"
  3292. " where tc.task_id = ?", (tagged_worker,)).fetchall()
  3293. conn.close()
  3294. check([r[0] for r in tag_rows] == ["gpu"],
  3295. "the task_capabilities rows record the explicit tag")
  3296. check(detail["status"] == "draft",
  3297. "the callback's task lands in draft until its agent enqueues")
  3298. saddle_api("POST", "/api/saddle/task/enqueue", host_daemon.token,
  3299. {"session_id": tag_session, "task_id": tagged_worker})
  3300. check(wait_task_done(auth, tagged_worker, timeout=90) is not None,
  3301. "the tagged worker dispatches and completes")
  3302. act(auth, slot_public(auth, "/goals/%d" % tag_goal, "goal")["cancel"], {})
  3303. act(auth, task_state(auth, tag_host)["cancel"], {})
  3304. print("== phase 3: dashboard — pinned blocks + activity timeline ==")
  3305. # Pinned OPEN blocking items as link-through cards, newest
  3306. # first; no inline answer forms (the card links to the task
  3307. # page). Fixture: one open question + one open review raised on a
  3308. # local task (stand-ins for the auto-approve grandchild's
  3309. # leftovers) join the probe RFC raised below.
  3310. conn = db()
  3311. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  3312. " values (1, 'Dash fixture task', 'working', 5, strftime('%s','now'))")
  3313. dash_task = conn.execute("select max(id) from tasks").fetchone()[0]
  3314. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  3315. " values (?, ?, strftime('%s','now'))", (dash_task, fake_id))
  3316. dash_session = conn.execute("select max(id) from sessions").fetchone()[0]
  3317. conn.commit()
  3318. conn.close()
  3319. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3320. {"type": "block", "session_id": dash_session, "data": {
  3321. "question": "Dash fixture question?", "type": "question"}})
  3322. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3323. {"type": "review", "session_id": dash_session, "data": {
  3324. "summary": "dash fixture review"}})
  3325. # The activity timeline: last <= 50 events, newest first, fed
  3326. # from the existing tables. Fixture rows a few seconds old
  3327. # guarantee the progress kind and a human-authored comment ride
  3328. # along; the probe block below proves same-source ordering.
  3329. conn = db()
  3330. conn.execute("insert into task_comments (task_id, author, body, created_at)"
  3331. " values (?, 'user:admin', 'timeline fixture comment by a human',"
  3332. " strftime('%s','now','-5 seconds'))", (cap_task,))
  3333. conn.execute("insert into task_progress (task_id, summary, created_at)"
  3334. " values (?, 'timeline fixture progress',"
  3335. " strftime('%s','now','-5 seconds'))",
  3336. (cap_task,))
  3337. conn.commit()
  3338. conn.close()
  3339. # The probe RFC raised last: the newest pinned card and the newest
  3340. # timeline event (its raise+answer below prove same-source ordering
  3341. # both ways). The timeline sorts same-second events by source
  3342. # materialisation order, so the probe must land in a LATER clock
  3343. # second than the fixtures — wait for the boundary (bounded).
  3344. fixtures_epoch = int(time.time())
  3345. wait_for(lambda: int(time.time()) > fixtures_epoch or False,
  3346. timeout=3, what="next clock second before the probe raise")
  3347. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3348. {"type": "block", "session_id": dash_session, "data": {
  3349. "question": "Timeline probe: approve the dashboard flow",
  3350. "type": "rfc", "body": "# Probe"}})
  3351. dash = slot_public(auth, "/", "dashboard")
  3352. pinned = dash.get("pinned", [])
  3353. pinned_ids = [int(b["id"]) for b in pinned]
  3354. check(len(pinned_ids) >= 3 and pinned_ids == sorted(pinned_ids, reverse=True),
  3355. "pinned open blocks order newest-first (%s)" % pinned_ids)
  3356. check({b["block_type"] for b in pinned} >= {"question", "rfc", "review"},
  3357. "pinned cards cover questions, RFCs and reviews")
  3358. check(all(b["question"] and b["task_title"] and int(b["task_id"]) > 0
  3359. for b in pinned)
  3360. and all("answer_action" not in b for b in pinned),
  3361. "pinned cards are link-through only (task title, kind badge, question)")
  3362. activity = dash.get("activity", [])
  3363. epochs = [int(e["at_epoch"]) for e in activity]
  3364. check(0 < len(activity) <= 50 and epochs == sorted(epochs, reverse=True),
  3365. "the timeline shows the last <=50 events newest-first (%d events)"
  3366. % len(activity))
  3367. kinds = {e["kind"] for e in activity}
  3368. check({"created", "started", "dispatch", "comment", "progress", "completed"} <= kinds,
  3369. "the timeline covers status changes, dispatches, comments, progress and"
  3370. " completions (%s)" % sorted(kinds))
  3371. check(any(e["kind"] == "comment" and e["text"].startswith("user:admin:")
  3372. and "fixture comment" in e["text"] for e in activity),
  3373. "comment events carry author + snippet")
  3374. # The freshly raised probe pinned as the newest card and landed
  3375. # atop the timeline as block-raised; answering it records
  3376. # block-answered.
  3377. check(dash["pinned"][0]["question"] == "Timeline probe: approve the dashboard flow"
  3378. and int(dash["pinned"][0]["task_id"]) == dash_task,
  3379. "the freshest open block pins as the first card")
  3380. check(dash["activity"][0]["kind"] == "block-raised"
  3381. and "Timeline probe" in dash["activity"][0]["text"],
  3382. "the raised block lands atop the timeline")
  3383. probe_block = [b for b in task_state(auth, dash_task)["blocks"]
  3384. if b["question"] == "Timeline probe: approve the dashboard flow"][0]
  3385. act(auth, probe_block["answer_action"], {"answer": "Ship the dashboard"})
  3386. dash = slot_public(auth, "/", "dashboard")
  3387. activity = dash.get("activity", [])
  3388. raised_at = next((i for i, e in enumerate(activity)
  3389. if e["kind"] == "block-raised" and "Timeline probe" in e["text"]), -1)
  3390. answered_at = next((i for i, e in enumerate(activity)
  3391. if e["kind"] == "block-answered"
  3392. and "Ship the dashboard" in e["text"]), -1)
  3393. check(answered_at >= 0 and raised_at >= 0 and answered_at < raised_at,
  3394. "the answered event sorts above its raised event (newest-first, same source)")
  3395. check(all(b["question"] != "Timeline probe: approve the dashboard flow"
  3396. for b in dash["pinned"]),
  3397. "the answered block leaves the pinned cards")
  3398. print("== phase 3 regression: a slow ask after a wake is never dropped ==")
  3399. # The daemon worker's lost-wake-guard regression: a saddle whose
  3400. # ask arrives SLOWLY after the wake (busy winding down when the
  3401. # wake lands) must not lose the wake — the delayed ask (inside
  3402. # the guard window) claims the task, no re-wake storm fires
  3403. # while it is pending, and the saddle stays healthy. The
  3404. # never-asks path (guard -> offline + re-wake of the next
  3405. # capable) is proven by the racer-three section above.
  3406. check(wait_for(lambda: queued_count() == 0 or False,
  3407. timeout=60, what="queue settles before the slow-wake run") is not None,
  3408. "the queue settles before the slow-wake run")
  3409. status, _ = fake2.ask_now()
  3410. check(status == 204, "the slow-ask racer sleeps before its wake")
  3411. saddles_state = slot_public(auth, "/saddles", "saddles")
  3412. act(auth, saddles_state["create_capability"], {"name": "slowwake"})
  3413. slowwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")
  3414. ["capabilities"] if c["name"] == "slowwake"][0])
  3415. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3416. if s["name"] == "racer-two"][0]
  3417. act(auth, racer2_card["attach_capability"], {"capability_id": str(slowwake_cap)})
  3418. fake2.ask_delay = 1.2 # slow: asks well after the wake, inside the 2s guard
  3419. fake2.ask_on_wake = True
  3420. wakes_before_slow = len(fake2.wake_log)
  3421. task_id_tmp = create_queued(auth, {
  3422. "project_id": "1",
  3423. "title": "Slow wake task",
  3424. "priority": "2",
  3425. "capability_id": [str(slowwake_cap)],
  3426. })
  3427. slow_task = task_id_tmp
  3428. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_slow or False,
  3429. timeout=30, what="the slow-ask racer woken") is not None,
  3430. "the only capable sleeping saddle is woken")
  3431. check(wait_task_done(auth, slow_task, timeout=120) is not None,
  3432. "the delayed ask claims the task — the wake was not dropped")
  3433. check(any(a.get("status") == 200
  3434. and int((a.get("payload") or {}).get("task", {}).get("id") or 0)
  3435. == slow_task for a in fake2.asks),
  3436. "the slow ask's 200 carries the task")
  3437. check(len(fake2.wake_log) == wakes_before_slow + 1,
  3438. "the pending-wake skip re-wakes nobody while the slow ask is in flight")
  3439. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3440. if s["name"] == "racer-two"][0]
  3441. check(racer2_card["status"] in ("idle", "busy"),
  3442. "the slow asker never went offline (guard did not fire)")
  3443. fake2.ask_delay = 0.0
  3444. fake2.ask_on_wake = False # stays out of the pool below
  3445. # =============================================================================
  3446. # Bundle: lifecycle — offline requeues, the hung-request tick survival,
  3447. # parked-refresh bookkeeping, cancellation, the health panel, raw-log
  3448. # losslessness, git identity and the live blocked-push roundtrip.
  3449. # =============================================================================
  3450. def bundle_lifecycle(ctx):
  3451. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  3452. app = ctx.app
  3453. print("== plan 11: draft state machine, edit matrix, enqueue/delete guards ==")
  3454. # New tasks default to draft; Enqueue is the only path to the
  3455. # queue (there is no agent path — the ingest API refuses to queue).
  3456. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3457. "project_id": "1",
  3458. "title": "Draft lifecycle task",
  3459. "priority": "4",
  3460. })
  3461. draft_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3462. if t["title"] == "Draft lifecycle task"][0])
  3463. detail = task_state(auth, draft_task)
  3464. check(detail["status"] == "draft", "a created task lands in draft")
  3465. check(detail.get("enqueue") is not None and detail.get("delete") is not None,
  3466. "draft exposes the enqueue + delete actions")
  3467. check(detail.get("cancel") is not None, "the cancel action stays authored")
  3468. status, page = http("GET", "/tasks/%d" % draft_task, timeout=15)
  3469. check(status == 200 and "Enqueue task" in page and ">Delete<" in page,
  3470. "the task page shows Enqueue + Delete in draft")
  3471. check("Mark done" not in page,
  3472. "the user Mark-complete action is gone (bot-only completion)")
  3473. # Plan 12: the auto-enqueue-after predecessor REPLACES draft
  3474. # dependencies — setting it is allowed while the predecessor is
  3475. # still pending (the enqueue itself succeeds; the DISPATCHER holds
  3476. # dispatch back until the predecessor is done).
  3477. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3478. "project_id": "1",
  3479. "title": "Draft dependency",
  3480. "priority": "4",
  3481. })
  3482. draft_dep = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3483. if t["title"] == "Draft dependency"][0])
  3484. act(auth, detail["update"], {"enqueue_after_task_id": str(draft_dep)})
  3485. check(int(task_state(auth, draft_task).get("enqueue_after_task_id") or 0)
  3486. == draft_dep,
  3487. "the draft edit sets the auto-enqueue predecessor")
  3488. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3489. "project_id": "1", "title": "Eager dependent", "priority": "4",
  3490. "enqueue_after_task_id": str(draft_dep)})
  3491. eager = task_id_of("Eager dependent")
  3492. enqueue_task(auth, eager)
  3493. check(task_state(auth, eager)["status"] == "queued",
  3494. "enqueue succeeds while the predecessor is pending (no draft guard)")
  3495. check(quiet_window(quiet_seconds(),
  3496. lambda: task_state(auth, eager)["status"] == "queued",
  3497. "pending predecessor holds dispatch"),
  3498. "the pending predecessor holds dispatch back (never assigned)")
  3499. # The edit matrix starts in DRAFT: every field except status.
  3500. act(auth, detail["update"], {
  3501. "title": "Draft lifecycle task (edited)",
  3502. "description": "Now with a description",
  3503. "priority": "2",
  3504. "task_branch": "feature/draft",
  3505. "branch_from": "main",
  3506. "mode": "investigate",
  3507. })
  3508. detail = task_state(auth, draft_task)
  3509. check(detail["title"] == "Draft lifecycle task (edited)"
  3510. and detail["description"] == "Now with a description"
  3511. and detail["priority"] == 2
  3512. and detail["task_branch"] == "feature/draft"
  3513. and detail["branch_from"] == "main"
  3514. and detail["mode"] == "investigate",
  3515. "draft edits apply to every field (incl. the mode)")
  3516. # Clear the predecessor (the empty sentinel): dispatch gates on
  3517. # the hold tag alone now.
  3518. act(auth, detail["update"], {"enqueue_after_task_id": "0"})
  3519. check(not int(task_state(auth, draft_task).get("enqueue_after_task_id") or 0),
  3520. "the draft edit clears the auto-enqueue predecessor")
  3521. # A hold tag nothing carries keeps the dependent QUEUED (never
  3522. # dispatched) through the remaining edit-matrix checks.
  3523. saddles_state = slot_public(auth, "/saddles", "saddles")
  3524. act(auth, saddles_state["create_capability"], {"name": "holdlock"})
  3525. holdlock_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3526. if c["name"] == "holdlock"][0])
  3527. act(auth, detail["attach_capability"], {"capability_id": str(holdlock_cap)})
  3528. # Enqueue the now-cleared dependent: the hold tag keeps it queued
  3529. # (never dispatched), so the non-draft edit matrix applies.
  3530. enqueue_task(auth, draft_task)
  3531. check(quiet_window(3, lambda: task_state(auth, draft_task)["status"] == "queued",
  3532. "held dependent stays queued"),
  3533. "the held dependent stays queued (never dispatched)")
  3534. # The predecessor settles for the shard drain.
  3535. enqueue_task(auth, draft_dep)
  3536. check(wait_task_done(auth, draft_dep, timeout=90) is not None,
  3537. "the predecessor settles")
  3538. # Drafts are never dispatched even with an idle saddle available.
  3539. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3540. "project_id": "1",
  3541. "title": "Never-dispatched draft",
  3542. "priority": "1",
  3543. })
  3544. silent_draft = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3545. if t["title"] == "Never-dispatched draft"][0])
  3546. check(quiet_window(quiet_seconds(),
  3547. lambda: task_state(auth, silent_draft)["status"] == "draft",
  3548. "draft never dispatched"),
  3549. "an idle saddle never picks a draft up (no agent enqueue path)")
  3550. # Once work can begin (queued here), only priority is editable.
  3551. act(auth, detail["update"], {
  3552. "title": "Should not apply",
  3553. "priority": "3",
  3554. })
  3555. detail = task_state(auth, draft_task)
  3556. check(detail["title"] == "Draft lifecycle task (edited)" and detail["priority"] == 3,
  3557. "non-draft edits apply priority only (title locked)")
  3558. # A terminal task edits nothing.
  3559. conn = db()
  3560. conn.execute("update tasks set status = 'done', completed_at = strftime('%s','now')"
  3561. " where id = ?", (draft_task,))
  3562. conn.commit()
  3563. conn.close()
  3564. act(auth, task_state(auth, draft_task)["update"], {"priority": "8"})
  3565. check(task_state(auth, draft_task)["priority"] == 3,
  3566. "terminal tasks edit nothing (priority locked)")
  3567. # Capabilities lock once a worker has the job: editable while
  3568. # queued, locked once working.
  3569. act(auth, saddles_state["create_capability"], {"name": "editlock"})
  3570. editlock_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")
  3571. ["capabilities"] if c["name"] == "editlock"][0])
  3572. act(auth, saddle_card(auth, "fake-saddle")["attach_capability"],
  3573. {"capability_id": str(editlock_cap)})
  3574. locked_task = create_queued(auth, {"project_id": "1", "title": "Caplock task",
  3575. "priority": "2"})
  3576. detail = task_state(auth, locked_task)
  3577. act(auth, detail["attach_capability"], {"capability_id": str(editlock_cap)})
  3578. check(any(c["name"] == "editlock"
  3579. for c in task_state(auth, locked_task)["capabilities"]),
  3580. "capabilities attach while queued (no worker yet)")
  3581. check(wait_for(lambda: task_state(auth, locked_task).get("status") == "working"
  3582. or False, timeout=60, what="caplock working") is not None,
  3583. "the caplock task reaches working")
  3584. detach_directives = act(auth, task_state(auth, locked_task)["capabilities"][0]["detach"], {})
  3585. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  3586. for d in detach_directives),
  3587. "capabilities are locked once a worker has the job")
  3588. # The ingest API has no queue transition either (only working and
  3589. # blocked are accepted states).
  3590. conn = db()
  3591. caplock_session = conn.execute(
  3592. "select id from sessions where task_id = ? and ended_at is null",
  3593. (locked_task,)).fetchone()
  3594. conn.close()
  3595. if caplock_session is not None:
  3596. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3597. {"type": "status", "session_id": caplock_session[0],
  3598. "data": {"state": "queued"}})
  3599. check(status == 200
  3600. and task_state(auth, locked_task)["status"] in ("working", "done"),
  3601. "the ingest API's status push never queues a task")
  3602. # Delete guards: a clean draft deletes; non-draft refuses; a draft
  3603. # with dependents is refused naming them.
  3604. act(auth, task_state(auth, silent_draft)["delete"], {})
  3605. check(not any(t["id"] == silent_draft
  3606. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  3607. "a clean draft task deletes")
  3608. delete_directives = act(auth, task_state(auth, draft_task)["delete"], {})
  3609. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  3610. for d in delete_directives),
  3611. "a non-draft task refuses the delete")
  3612. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3613. "project_id": "1", "title": "Guarded draft", "priority": "4"})
  3614. guarded = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3615. if t["title"] == "Guarded draft"][0])
  3616. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3617. "project_id": "1", "title": "Dependent namer", "priority": "4"})
  3618. namer = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3619. if t["title"] == "Dependent namer"][0])
  3620. act(auth, task_state(auth, namer)["update"],
  3621. {"enqueue_after_task_id": str(guarded)})
  3622. check(int(task_state(auth, namer).get("enqueue_after_task_id") or 0) == guarded,
  3623. "the namer points at the guarded predecessor")
  3624. act(auth, task_state(auth, guarded)["delete"], {})
  3625. check(not any(t["id"] == guarded
  3626. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  3627. "deleting a predecessor succeeds")
  3628. check(not int(task_state(auth, namer).get("enqueue_after_task_id") or 0),
  3629. "the delete clears the dependent's dangling predecessor reference")
  3630. print("== offline requeues ==")
  3631. # Tasks caught working on a saddle that went offline requeue with a
  3632. # bot comment each tick.
  3633. task_id_tmp = create_queued(auth, {
  3634. "project_id": "1",
  3635. "title": "Offline saddle task",
  3636. "priority": "2",
  3637. })
  3638. offline_task = task_id_tmp
  3639. check(wait_for(lambda: task_state(auth, offline_task).get("status") == "working"
  3640. or False, timeout=60, what="offline task starts working") is not None,
  3641. "task reaches working before its saddle disappears")
  3642. # Hold the daemon mid-round across the requeue window (the
  3643. # original relied on its 8s work period outlasting the 5s tick):
  3644. # the task completing on its own would race the offline pass and
  3645. # skip the requeue the check exists to observe.
  3646. fake.hold_state = True
  3647. conn = db()
  3648. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  3649. conn.commit()
  3650. conn.close()
  3651. # The requeue frees the saddle in the same tick, so 'queued' is
  3652. # transient; the durable evidence is the bot comment (and the task
  3653. # completing again on the healthy daemon).
  3654. check(wait_for(lambda: any(c["body"] == "saddle went offline; task requeued"
  3655. for c in task_state(auth, offline_task).get("comments", []))
  3656. or False, timeout=30, what="offline requeue comment") is not None,
  3657. "offline saddle requeues the task")
  3658. fake.hold_state = False # release: the round ends, the daemon re-asks
  3659. check(wait_task_done(auth, offline_task, timeout=60) is not None,
  3660. "requeued task completes again on the healthy daemon")
  3661. print("== R6 F1: a hanging request cannot freeze the tick ==")
  3662. # One wedged /task-update (never responds) blocks the comment/
  3663. # subtask-event delivery pass; the Soup timeout must fail it and
  3664. # later ticks keep dispatching.
  3665. conn = db()
  3666. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  3667. " values (1, 'Hang survivor', 'queued', 2, strftime('%s','now'))")
  3668. hang_task = conn.execute("select max(id) from tasks").fetchone()[0]
  3669. conn.close()
  3670. task_id_tmp = create_queued(auth, {
  3671. "project_id": "1",
  3672. "title": "Hang runner",
  3673. "priority": "3",
  3674. })
  3675. hang_runner = task_id_tmp
  3676. # A human comment on the running task gives the tick a
  3677. # /task-update delivery to make; the next one hangs.
  3678. check(wait_for(lambda: task_state(auth, hang_runner).get("status") == "working"
  3679. or False, timeout=60, what="hang runner working") is not None,
  3680. "hang runner reaches working")
  3681. act(auth, task_state(auth, hang_runner)["comment"],
  3682. {"body": "operator ping while wedged"})
  3683. fake.hang_next["/task-update"] = 1
  3684. check(wait_task_done(auth, hang_runner, timeout=90) is not None,
  3685. "dispatching task survives a hung daemon request")
  3686. check(wait_for(lambda: any(c.get("text") == "operator ping while wedged"
  3687. or c.get("body") == "operator ping while wedged"
  3688. for c in fake.comment_log) or False,
  3689. timeout=30, what="wedged comment eventually delivered") is not None,
  3690. "the comment delivery retries after the hang")
  3691. # The hung delivery itself fails after the timeout; the system
  3692. # kept moving either way.
  3693. with open(os.path.join(WORK, "app.log")) as handle:
  3694. app_log = handle.read()
  3695. check("tick exceeded" not in app_log or "Dispatch tick failed" in app_log,
  3696. "a hung request never freezes the tick latch")
  3697. print("== R6 F2: refresh must not corrupt parked bookkeeping ==")
  3698. fake.suspend_on_title = "Parked refresh parent"
  3699. task_id_tmp = create_queued(auth, {
  3700. "project_id": "1",
  3701. "title": "Parked refresh parent",
  3702. "priority": "2",
  3703. })
  3704. parked = task_id_tmp
  3705. check(wait_for(lambda: task_state(auth, parked).get("status") == "suspended"
  3706. or False, timeout=60, what="parked parent suspends") is not None,
  3707. "parent parks before the refresh")
  3708. fake_card = saddle_card(auth, "fake-saddle")
  3709. act(auth, fake_card["refresh"], {})
  3710. fake_card = saddle_card(auth, "fake-saddle")
  3711. check(fake_card["status"] == "idle" and int(fake_card["current_task_id"] or 0) == 0,
  3712. "refresh on a parked (suspended) daemon leaves the saddle idle")
  3713. # The parked task keeps its open session and stays put: plain
  3714. # tasks have no subtask events to resume them (the goal machinery
  3715. # owns resumes); the human resumes it explicitly.
  3716. check(quiet_window(quiet_seconds(),
  3717. lambda: task_state(auth, parked)["status"] == "suspended",
  3718. "parked task stays parked"),
  3719. "a parked plain task stays parked after the refresh (no resume channel)")
  3720. act(auth, task_state(auth, parked)["cancel"], {})
  3721. check(wait_for(lambda: task_state(auth, parked)["status"] == "failed" or False,
  3722. timeout=30, what="parked task cancelled") is not None,
  3723. "the parked task cancels cleanly after the refresh")
  3724. print("== R7 B1: cancel reaches the daemon ==")
  3725. # Plan 10 phase 2: cancellation is POST /task-update {kind: cancel}
  3726. # to the RUNNING daemon (the abort machinery, workspace kept).
  3727. task_id_tmp = create_queued(auth, {
  3728. "project_id": "1",
  3729. "title": "Cancel live",
  3730. "priority": "2",
  3731. })
  3732. cancel_live = task_id_tmp
  3733. check(wait_for(lambda: task_state(auth, cancel_live).get("status") == "working"
  3734. or False, timeout=60, what="cancel-live working") is not None,
  3735. "task reaches working before the cancel")
  3736. act(auth, task_state(auth, cancel_live)["cancel"], {})
  3737. check(wait_for(lambda: cancel_live in fake.abort_log or False,
  3738. timeout=30, what="daemon abort recorded") is not None,
  3739. "cancelling POSTs task-update cancel to the daemon")
  3740. check(any(c["body"] == "cancelled; daemon aborted"
  3741. for c in task_state(auth, cancel_live).get("comments", [])),
  3742. "the abort outcome is narrated")
  3743. check(task_state(auth, cancel_live)["status"] == "failed",
  3744. "cancelled task lands failed as before")
  3745. # A 500 on the cancel marks the saddle offline (no fence layer
  3746. # anymore); nothing dispatches to it while offline, and the
  3747. # daemon's own ask flips the row back to idle (proof of life).
  3748. task_id_tmp = create_queued(auth, {
  3749. "project_id": "1",
  3750. "title": "Fence runner",
  3751. "priority": "2",
  3752. })
  3753. fence_runner = task_id_tmp
  3754. check(wait_for(lambda: task_state(auth, fence_runner).get("status") == "working"
  3755. or False, timeout=60, what="fence runner working") is not None,
  3756. "second task reaches working")
  3757. fake.abort_failures = 1
  3758. act(auth, task_state(auth, fence_runner)["cancel"], {})
  3759. check(any(c["body"] == "cancelled; daemon unreachable — saddle marked offline"
  3760. for c in task_state(auth, fence_runner).get("comments", [])),
  3761. "failed cancel narrates the offline marking")
  3762. check(saddle_card(auth, "fake-saddle")["status"] == "offline",
  3763. "saddle marked offline after the failed cancel")
  3764. task_id_tmp = create_queued(auth, {
  3765. "project_id": "1",
  3766. "title": "During fence",
  3767. "priority": "3",
  3768. })
  3769. during_fence = task_id_tmp
  3770. # Converted sleep(7): a quiet window spanning several dispatch
  3771. # ticks in which the task MUST stay queued — if the offline
  3772. # saddle ever dispatches it, this fails loudly. The daemon is held
  3773. # mid-round for the window (the original relied on its 8s work
  3774. # period outlasting the sleep): a finishing round would ask, prove
  3775. # liveness and flip the offline row — only after the window may it.
  3776. fake.hold_state = True
  3777. check(quiet_window(quiet_seconds(),
  3778. lambda: task_state(auth, during_fence)["status"] == "queued",
  3779. "offline saddle does not dispatch during_fence"),
  3780. "offline saddle is not dispatchable")
  3781. fake.hold_state = False
  3782. # The (unaborted) daemon finishes its round, goes idle-awake and
  3783. # asks — the ask is the proof of life that flips the row back.
  3784. check(wait_for(lambda: saddle_card(auth, "fake-saddle")["status"] == "idle" or False,
  3785. timeout=30, what="ask flips offline to idle") is not None,
  3786. "the daemon's ask flips the offline row back to idle")
  3787. check(wait_task_done(auth, during_fence, timeout=60) is not None,
  3788. "queued work dispatches once the saddle proves it is alive")
  3789. print("== R7 B3: health panel + pushed raw log from the first round ==")
  3790. # A normally dispatched task pushes its chunks immediately: raw
  3791. # rows exist from the first round (the session-4 gap stays
  3792. # fixed without any probe machinery).
  3793. task_id_tmp = create_queued(auth, {
  3794. "project_id": "1",
  3795. "title": "Raw from first push",
  3796. "priority": "2",
  3797. })
  3798. raw_first = task_id_tmp
  3799. def raw_count(task_id):
  3800. conn = db()
  3801. try:
  3802. return conn.execute(
  3803. "select count(*) from session_raw_log where session_id in"
  3804. " (select id from sessions where task_id = ?)", (task_id,)).fetchone()[0]
  3805. finally:
  3806. conn.close()
  3807. check(wait_for(lambda: raw_count(raw_first) > 0 or False,
  3808. timeout=60, what="raw rows from first push") is not None,
  3809. "pushed chunks land from the first round (session-4 gap)")
  3810. check(wait_task_done(auth, raw_first, timeout=60) is not None,
  3811. "raw-first task completes")
  3812. # Health panel: a manual refresh populates the snapshot.
  3813. fake_card = saddle_card(auth, "fake-saddle")
  3814. act(auth, fake_card["refresh"], {})
  3815. card = saddle_card(auth, "fake-saddle")
  3816. check(card.get("health") in ("healthy", "stale")
  3817. and card.get("daemon_state") in ("working", "idle", "done")
  3818. and card.get("uptime_display", "") != ""
  3819. and card.get("last_contact_display", "") not in ("", "never"),
  3820. "saddles page shows daemon state, uptime and last contact")
  3821. print("== R8: pushed chunk ingestion is lossless ==")
  3822. # The daemon's opening flush: a coloured prompt run, plain text,
  3823. # a bare CRLF between prompts and the tail — every non-empty
  3824. # chunk must land, exactly once, in seq order. A mid-flight
  3825. # redelivery of the whole batch (the outbox's at-least-once
  3826. # retry) consumes the duplicates.
  3827. corpus = [
  3828. {"seq": 1, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  3829. {"seq": 2, "text": "echo hello\r\n"},
  3830. {"seq": 3, "text": "\r\n"},
  3831. {"seq": 4, "text": "hello\r\n"},
  3832. {"seq": 5, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  3833. {"seq": 6, "text": "done\r\n"},
  3834. ]
  3835. fake.scripted_corpus = corpus
  3836. fake.hold_state = True
  3837. task_id_tmp = create_queued(auth, {
  3838. "project_id": "1",
  3839. "title": "Lossless log task",
  3840. "priority": "2",
  3841. })
  3842. lossless = task_id_tmp
  3843. def stored_seqs(task_id):
  3844. conn = db()
  3845. try:
  3846. return [r[0] for r in conn.execute(
  3847. "select seq from session_raw_log where session_id in"
  3848. " (select id from sessions where task_id = ?)"
  3849. " order by seq", (task_id,))]
  3850. finally:
  3851. conn.close()
  3852. check(wait_for(lambda: task_state(auth, lossless).get("status") == "working"
  3853. or False, timeout=60, what="lossless task working") is not None,
  3854. "lossless task dispatches and pushes its opening flush")
  3855. check(wait_for(lambda: stored_seqs(lossless) == [1, 2, 3, 4, 5, 6] or False,
  3856. timeout=30, what="all six chunks stored") is not None,
  3857. "every pushed chunk lands in session_raw_log, CRLF-only included (%s)"
  3858. % stored_seqs(lossless))
  3859. status, _ = saddle_api("POST", "/api/saddle/chunks", fake.token,
  3860. {"session_id": fake.session_id,
  3861. "chunks": [dict(chunk) for chunk in corpus]})
  3862. check(status == 200 and stored_seqs(lossless) == [1, 2, 3, 4, 5, 6],
  3863. "a full-batch redelivery stores nothing new (exactly-once)")
  3864. request = urllib.request.Request(
  3865. WEB + "/terminal-stream/%d" % [r[0] for r in db().execute(
  3866. "select id from sessions where task_id = ?", (lossless,))][0])
  3867. with urllib.request.urlopen(request, timeout=15) as stream:
  3868. texts = []
  3869. deadline = time.monotonic() + 8
  3870. while time.monotonic() < deadline and len(texts) < 6:
  3871. line = stream.readline().decode().strip()
  3872. if not line.startswith("data: ") or line == "data: ping":
  3873. continue
  3874. event = json.loads(line[6:])
  3875. if event.get("type") == "raw":
  3876. texts.append(event.get("text") or "")
  3877. check("\r\n" in texts and len(texts) == 6,
  3878. "SSE serves the whitespace chunk unfiltered")
  3879. fake.hold_state = False
  3880. fake.scripted_corpus = None
  3881. check(wait_task_done(auth, lossless, timeout=60) is not None,
  3882. "lossless task completes")
  3883. print("== R9 B1/B2: git identity + ssh key ==")
  3884. # The key travels on /status into the saddle row and the page view
  3885. # (the manual refresh's exceptional probe).
  3886. fake.ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1teStKey saddle-1@fedora"
  3887. fake_card = saddle_card(auth, "fake-saddle")
  3888. check(fake_card.get("ssh_public_key", "") == "",
  3889. "no key shown before the daemon reports one")
  3890. act(auth, fake_card["refresh"], {})
  3891. check(wait_for(lambda: "AAAAC3NzaC1lZDI1teStKey" in
  3892. saddle_card(auth, "fake-saddle").get("ssh_public_key", "") or False,
  3893. timeout=30, what="key lands on the row") is not None,
  3894. "reported ssh_public_key persists onto the saddle row")
  3895. conn = db()
  3896. row_key = conn.execute("select ssh_public_key from saddles where name = 'fake-saddle'"
  3897. ).fetchone()[0]
  3898. conn.close()
  3899. check(row_key == fake.ssh_public_key,
  3900. "the key is stored verbatim in the database")
  3901. # Identity edit flows through the UI into the assignment payload.
  3902. fake_card = saddle_card(auth, "fake-saddle")
  3903. act(auth, fake_card["update_identity"],
  3904. {"git_name": "clanker-bot", "git_email": "bot@unitatem.net"})
  3905. fake_card = saddle_card(auth, "fake-saddle")
  3906. check(fake_card.get("git_name") == "clanker-bot"
  3907. and fake_card.get("git_email") == "bot@unitatem.net",
  3908. "inline edit saves the git identity")
  3909. task_id_tmp = create_queued(auth, {
  3910. "project_id": "1",
  3911. "title": "Identity task",
  3912. "priority": "2",
  3913. })
  3914. identity_task = task_id_tmp
  3915. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == identity_task
  3916. for p in fake.start_payloads) or False,
  3917. timeout=60, what="identity task dispatched") is not None,
  3918. "identity task dispatches")
  3919. payload = [p for p in fake.start_payloads
  3920. if int(p.get("task", {}).get("id") or 0) == identity_task][-1]
  3921. identity = payload.get("git_identity") or {}
  3922. check(identity.get("name") == "clanker-bot"
  3923. and identity.get("email") == "bot@unitatem.net",
  3924. "the assignment carries the saddle's git_identity")
  3925. # Earlier assignments (identity unset) carry no git_identity member.
  3926. check(all("git_identity" not in p for p in fake.start_payloads[:-1]),
  3927. "unset identity omits the member (daemon fallback applies)")
  3928. # Clearing the identity omits it from later assignments.
  3929. fake_card = saddle_card(auth, "fake-saddle")
  3930. act(auth, fake_card["update_identity"], {"git_name": "", "git_email": ""})
  3931. check(saddle_card(auth, "fake-saddle").get("git_name", "") == "",
  3932. "clearing the identity empties the row")
  3933. check(wait_task_done(auth, identity_task, timeout=60) is not None,
  3934. "identity task completes")
  3935. print("== phase 2: blocked push -> block row + pulse ==")
  3936. # The browser flow on each pulse: statum.act(task.refresh) — the
  3937. # sealed GET action must rehydrate the task slot with the new
  3938. # block the daemon just PUSHED (state blocked + block payload).
  3939. task_id_tmp = create_queued(auth, {
  3940. "project_id": "1",
  3941. "title": "Live block task",
  3942. "priority": "2",
  3943. })
  3944. live_task = task_id_tmp
  3945. check(wait_for(lambda: task_state(auth, live_task).get("status") == "working"
  3946. or False, timeout=60, what="live task working") is not None,
  3947. "live-block task reaches working")
  3948. fake.hold_state = True
  3949. fake.state = "blocked" # the daemon parks on its question
  3950. status = fake.push_results("blocked", block={
  3951. "question": "Pick one", "type": "question", "options": ["A", "B"]})
  3952. check(status == 200, "blocked state push accepted")
  3953. # The parked daemon is idle-awake: it asks (and sleeps on 204).
  3954. fake.maybe_trigger_ask("parked")
  3955. check(wait_for(lambda: any(b.get("question") == "Pick one"
  3956. for b in task_state(auth, live_task).get("blocks", []))
  3957. or False, timeout=30, what="block lands in state") is not None,
  3958. "the pushed block reaches the sealed refresh without a reload")
  3959. detail = task_state(auth, live_task)
  3960. check(detail.get("status") == "blocked",
  3961. "the blocked push flips the task to blocked")
  3962. pushed_block = [b for b in detail["blocks"] if b.get("question") == "Pick one"][0]
  3963. conn = db()
  3964. options_json = conn.execute(
  3965. "select options from task_blocks where id = ?", (int(pushed_block["id"]),)
  3966. ).fetchone()[0]
  3967. conn.close()
  3968. check(json.loads(options_json) == ["A", "B"],
  3969. "the block row carries its options payload")
  3970. check(any(s["status"] == "idle"
  3971. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  3972. "the blocked push parks the saddle")
  3973. detail = task_state(auth, live_task)
  3974. check(detail.get("refresh") is not None,
  3975. "the sealed GET refresh action is still authored")
  3976. status, _ = http("GET", detail["refresh"]["uri"], timeout=15)
  3977. check(status in (200, 401),
  3978. "the refresh URI resolves as a GET (client roundtrip shape)")
  3979. act(auth, pushed_block["answer_action"], {"answer": "A"})
  3980. # The answer makes the parked task resume-offerable: the affine
  3981. # saddle is woken, asks, and its assignment carries the answer.
  3982. pushes_before = len([p for p in fake.start_payloads
  3983. if int(p.get("task", {}).get("id") or 0) == live_task])
  3984. check(wait_for(lambda: len([p for p in fake.start_payloads
  3985. if int(p.get("task", {}).get("id") or 0) == live_task])
  3986. > pushes_before or False, timeout=60,
  3987. what="blocked task resumes") is not None,
  3988. "answering the pushed block resumes the parked workspace")
  3989. fake.hold_state = False # the resumed round runs to completion
  3990. resume_payload = [p for p in fake.start_payloads
  3991. if int(p.get("task", {}).get("id") or 0) == live_task][-1]
  3992. answers = resume_payload.get("task", {}).get("answers", [])
  3993. check(any(a.get("answer") == "A" for a in answers),
  3994. "the resume assignment carries the human's answer")
  3995. check(wait_task_done(auth, live_task, timeout=60) is not None,
  3996. "live-block task completes after answering")
  3997. # =============================================================================
  3998. # Bundle: answers — the answer-resume machinery in both daemon shapes
  3999. # (sleeping affine wake, mid-round verdict delivery), offline requeue
  4000. # keeping parked-with-answered tasks, the staleness probe, and the
  4001. # startup token migration (this shard's one deliberate app restart).
  4002. # =============================================================================
  4003. def bundle_answers(ctx):
  4004. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4005. app = ctx.app
  4006. print("== phase 2: answer resume — wake -> ask -> affinity claim ==")
  4007. # The full live sequence against a daemon that asks after its
  4008. # park: ask -> assignment -> blocked push (park) -> ask -> 204
  4009. # -> sleeps (row idle) -> human answers -> the dispatcher WAKES
  4010. # the sleeping affine saddle -> its ask allocates the resume,
  4011. # the verdict riding the assignment -> the session continues.
  4012. # A private capability tag keeps the fleet's other sleeping
  4013. # saddles from claiming these tasks.
  4014. saddles_state = slot_public(auth, "/saddles", "saddles")
  4015. act(auth, saddles_state["create_capability"], {"name": "answerflow"})
  4016. answerflow_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  4017. if c["name"] == "answerflow"][0])
  4018. def answerflow_daemon(**kwargs):
  4019. daemon = FakeSaddle()
  4020. daemon.ask_on_register = False # manual, deterministic asks
  4021. daemon.hold_state = True # the tests drive the lifecycle
  4022. for key, value in kwargs.items():
  4023. setattr(daemon, key, value)
  4024. daemon.serve()
  4025. return daemon
  4026. def register_answerflow(daemon, name):
  4027. act(auth, slot_public(auth, "/saddles", "saddles")["register"], {
  4028. "name": name, "host": "127.0.0.1:%d" % daemon.port})
  4029. act(auth, saddle_card(auth, name)["attach_capability"],
  4030. {"capability_id": str(answerflow_cap)})
  4031. def create_answerflow_task(title):
  4032. return create_queued(auth, {
  4033. "project_id": "1", "title": title, "priority": "2",
  4034. "capability_id": [str(answerflow_cap)]})
  4035. def retire_daemon(daemon, name):
  4036. # deterministic teardown: a dead daemon and an offline row
  4037. # never interfere with the sections that follow
  4038. daemon.kill()
  4039. act(auth, saddle_card(auth, name)["refresh"], {})
  4040. sleeper = answerflow_daemon(ask_on_wake=True)
  4041. register_answerflow(sleeper, "resume-sleeper")
  4042. sleeping_task = create_answerflow_task("Sleeping resume task")
  4043. ask_status, assignment = sleeper.ask_now()
  4044. check(ask_status == 200 and int(assignment["task"]["id"]) == sleeping_task,
  4045. "the daemon's ask claims the queued task")
  4046. sleeping_session = assignment.get("session_id")
  4047. sleeper.state = "blocked"
  4048. check(sleeper.push_results("blocked", block={
  4049. "question": "Pick a side", "type": "question",
  4050. "options": ["Port", "Starboard"]}) == 200,
  4051. "the blocked push parks the session")
  4052. check(wait_for(lambda: task_state(auth, sleeping_task).get("status") == "blocked"
  4053. or False, timeout=30, what="sleeping task parked") is not None,
  4054. "the task parks as blocked")
  4055. check(saddle_card(auth, "resume-sleeper")["status"] == "idle",
  4056. "the parked session's saddle row reads idle")
  4057. ask_status, _ = sleeper.ask_now()
  4058. check(ask_status == 204,
  4059. "the parked daemon's ask returns 204 — it sleeps until woken")
  4060. # Converted sleep(3): ticks pass with the daemon asleep and no
  4061. # wake may arrive — a wake during the window fails loudly.
  4062. check(quiet_window(quiet_seconds(),
  4063. lambda: len(sleeper.wake_log) == 0,
  4064. "sleeping daemon never woken"),
  4065. "the sleeping daemon is never woken while the block waits")
  4066. detail = task_state(auth, sleeping_task)
  4067. side_block = [b for b in detail["blocks"] if b["question"] == "Pick a side"][0]
  4068. act(auth, side_block["answer_action"], {"option": "Starboard"})
  4069. check(wait_for(lambda: len(sleeper.wake_log) > 0 or False,
  4070. timeout=30, what="wake after the answer") is not None,
  4071. "answering the block wakes the sleeping affine saddle")
  4072. # Answering = allocating (plan 11): the resume assignment carries
  4073. # the verdict as resume_notice (stable wording) AND a FRESH
  4074. # session id — the parked row closed, the daemon keys its resumed
  4075. # pushes on the new one.
  4076. check(wait_for(lambda: any(
  4077. int(p.get("task", {}).get("id") or 0) == sleeping_task
  4078. and p.get("session_id") != sleeping_session
  4079. and p.get("resume_notice") == "Human selected: Starboard"
  4080. and any(a.get("answer") == "Starboard"
  4081. for a in p.get("task", {}).get("answers", []))
  4082. for p in sleeper.start_payloads[1:]) or False,
  4083. timeout=30, what="resume allocation carries the verdict") is not None,
  4084. "the woken daemon's ask allocates the resume — fresh session, notice carried")
  4085. # Barrier: the resume's own working push must commit before the
  4086. # manual done push (a late working write would otherwise race the
  4087. # completion's full-row write).
  4088. check(wait_for(lambda: task_state(auth, sleeping_task).get("status") == "working"
  4089. or False, timeout=15, what="resumed round working") is not None,
  4090. "the resumed round reports working before its completion push")
  4091. # The resumed round runs to completion keyed on the fresh session.
  4092. sleeper.push_results("done", summary="sleep-resumed round complete")
  4093. check(wait_task_done(auth, sleeping_task, timeout=30) is not None,
  4094. "the resumed session continues to completion")
  4095. conn = db()
  4096. rows = conn.execute(
  4097. "select id, outcome, ended_at is not null from sessions where task_id = ?"
  4098. " order by id", (sleeping_task,)).fetchall()
  4099. conn.close()
  4100. check(len(rows) == 2 and rows[0][1] == "resumed" and rows[0][2]
  4101. and rows[1][1] == "done" and rows[1][2],
  4102. "parked session closed 'resumed'; the resumed round ran on a fresh row to done (%s)"
  4103. % (rows,))
  4104. retire_daemon(sleeper, "resume-sleeper")
  4105. print("== phase 2: answer resume — the parked daemon is woken (POST /answer retired) ==")
  4106. # Post Task A every park FREES the daemon: after the blocked push
  4107. # it lands idle and asks (204). The retired POST /answer channel
  4108. # always refuses; the verdict reaches the parked workspace purely
  4109. # through the wake -> ask -> affinity allocation carrying the
  4110. # resume_notice + a fresh session id.
  4111. parked = answerflow_daemon(ask_on_wake=True,
  4112. ask_on_terminal=False)
  4113. register_answerflow(parked, "resume-parked")
  4114. parked_task = create_answerflow_task("Parked resume task")
  4115. ask_status, assignment = parked.ask_now()
  4116. check(ask_status == 200 and int(assignment["task"]["id"]) == parked_task,
  4117. "the daemon's ask claims the task")
  4118. parked_session = assignment.get("session_id")
  4119. parked.state = "blocked"
  4120. check(parked.push_results("blocked", block={
  4121. "question": "Which database?", "type": "question",
  4122. "options": ["SQLite", "Postgres"]}) == 200,
  4123. "the blocked push parks the session mid-round")
  4124. check(wait_for(lambda: task_state(auth, parked_task).get("status") == "blocked"
  4125. or False, timeout=30, what="parked task blocked") is not None,
  4126. "the task parks as blocked")
  4127. check(saddle_card(auth, "resume-parked")["status"] == "idle",
  4128. "the parked session's saddle row reads idle")
  4129. # The freed daemon re-asks (its idle loop) and sleeps on 204.
  4130. ask_status, _ = parked.ask_now()
  4131. check(ask_status == 204,
  4132. "the freed parked daemon asks again and sleeps (204)")
  4133. # The retired channel always refuses — the web never depends on it.
  4134. request = urllib.request.Request(
  4135. "http://127.0.0.1:%d/answer" % parked.port,
  4136. data=json.dumps({"answer": "SQLite", "branch_advanced": False}).encode(),
  4137. method="POST")
  4138. request.add_header("Content-Type", "application/json")
  4139. try:
  4140. urllib.request.urlopen(request, timeout=5)
  4141. refused = False
  4142. except urllib.error.HTTPError as error:
  4143. refused = error.code == 409
  4144. check(refused, "POST /answer always refuses (409) — parks resume via allocation")
  4145. detail = task_state(auth, parked_task)
  4146. db_block = [b for b in detail["blocks"] if b["question"] == "Which database?"][0]
  4147. act(auth, db_block["answer_action"], {"option": "SQLite"})
  4148. check(wait_for(lambda: len(parked.wake_log) > 0 or False,
  4149. timeout=30, what="wake after the answer") is not None,
  4150. "answering the block wakes the parked (idle) affine saddle")
  4151. check(wait_for(lambda: any(
  4152. int(p.get("task", {}).get("id") or 0) == parked_task
  4153. and p.get("session_id") != parked_session
  4154. and p.get("resume_notice") == "Human selected: SQLite"
  4155. for p in parked.start_payloads[1:]) or False,
  4156. timeout=30, what="parked resume allocation") is not None,
  4157. "the parked daemon's ask allocates the resume — fresh session, formatted notice")
  4158. # The hold_state daemon drives its round manually: the resumed
  4159. # round completes on the fresh session row.
  4160. parked.push_results("done", summary="parked round resumed and finished")
  4161. check(wait_task_done(auth, parked_task, timeout=30) is not None,
  4162. "the parked session continues to completion")
  4163. conn = db()
  4164. row = conn.execute("select outcome from sessions where id = ?",
  4165. (parked_session,)).fetchone()
  4166. session_rows = conn.execute(
  4167. "select id, outcome from sessions where task_id = ? order by id",
  4168. (parked_task,)).fetchall()
  4169. conn.close()
  4170. check(row is not None and row[0] == "resumed"
  4171. and len(session_rows) == 2 and session_rows[0] == (parked_session, "resumed"),
  4172. "the parked session closed 'resumed' and the resumed round kept its own row (%s)"
  4173. % (session_rows,))
  4174. retire_daemon(parked, "resume-parked")
  4175. print("== plan 11: plan acceptance — accept / reject / auto-approve ==")
  4176. # A type 'plan' block parks like any other; Accept and
  4177. # Reject-with-feedback drive the same wake -> ask -> allocation
  4178. # resume as any verdict, the stable wording riding the
  4179. # resume_notice. Plan 12: the daemon only SENDS plan blocks on
  4180. # goal runs now (the goal page owns the review); this covers the
  4181. # generic verdict path a goal-run's mirrored block also uses. The
  4182. # auto-approve option is gone.
  4183. planner = answerflow_daemon(ask_on_wake=True, ask_on_terminal=False)
  4184. register_answerflow(planner, "plan-planner")
  4185. def park_on_plan(task_id, markdown):
  4186. planner.state = "blocked"
  4187. check(planner.push_results("blocked", block={
  4188. "question": "Plan submitted for review", "type": "plan",
  4189. "body": markdown}) == 200,
  4190. "the plan push parks the session")
  4191. # Wait for the block row itself (the auto-approve variant is
  4192. # answered — and may resume — before any status poll lands).
  4193. check(wait_for(lambda: any(b["block_type"] == "plan"
  4194. for b in task_state(auth, task_id)["blocks"])
  4195. or False, timeout=30, what="plan block raised") is not None,
  4196. "the plan block reaches the task")
  4197. return [b for b in task_state(auth, task_id)["blocks"]
  4198. if b["block_type"] == "plan"][0]
  4199. # (a) Accept resumes with the approval notice.
  4200. accept_task = create_answerflow_task("Plan accept task")
  4201. ask_status, accept_assignment = planner.ask_now()
  4202. check(ask_status == 200 and int(accept_assignment["task"]["id"]) == accept_task,
  4203. "the planner claims the accept task")
  4204. accept_parked_session = accept_assignment.get("session_id")
  4205. plan_block = park_on_plan(accept_task, "# Steps\n\n1. Wire\n2. Test")
  4206. check(plan_block.get("answered") is not True,
  4207. "the plan block waits for a human verdict")
  4208. act(auth, plan_block["answer_action"],
  4209. {"answer": "Plan approved. Proceed with implementation."})
  4210. check(wait_for(lambda: any(
  4211. int(p.get("task", {}).get("id") or 0) == accept_task
  4212. and p.get("session_id") != accept_parked_session
  4213. and p.get("resume_notice") == "Plan approved. Proceed with implementation."
  4214. for p in planner.start_payloads[1:]) or False,
  4215. timeout=30, what="accept resume allocation") is not None,
  4216. "accept resumes the parked daemon with the approval notice")
  4217. planner.push_results("done", summary="plan accepted and implemented")
  4218. check(wait_task_done(auth, accept_task, timeout=30) is not None,
  4219. "the accepted plan's task completes")
  4220. planner.set_state("idle")
  4221. # (b) Reject-with-feedback loops the feedback notice back.
  4222. reject_task = create_answerflow_task("Plan reject task")
  4223. ask_status, reject_assignment = planner.ask_now()
  4224. check(ask_status == 200 and int(reject_assignment["task"]["id"]) == reject_task,
  4225. "the planner claims the reject task")
  4226. reject_parked_session = reject_assignment.get("session_id")
  4227. plan_block = park_on_plan(reject_task, "# Draft\n\nJust wing it")
  4228. act(auth, plan_block["answer_action"], {"feedback": "Add a test section"})
  4229. reject_block = [b for b in task_state(auth, reject_task)["blocks"]
  4230. if b["block_type"] == "plan"][0]
  4231. check(reject_block.get("answer")
  4232. == "Plan feedback received:\nAdd a test section",
  4233. "reject stores the feedback in the stable wording (%s)"
  4234. % reject_block.get("answer"))
  4235. check(wait_for(lambda: any(
  4236. int(p.get("task", {}).get("id") or 0) == reject_task
  4237. and p.get("session_id") != reject_parked_session
  4238. and p.get("resume_notice") == "Plan feedback received:\nAdd a test section"
  4239. for p in planner.start_payloads[1:]) or False,
  4240. timeout=30, what="reject resume allocation") is not None,
  4241. "reject resumes the parked daemon with the feedback notice")
  4242. planner.push_results("done", summary="plan revised and delivered")
  4243. check(wait_task_done(auth, reject_task, timeout=30) is not None,
  4244. "the revised plan's task completes")
  4245. planner.set_state("idle")
  4246. retire_daemon(planner, "plan-planner")
  4247. print("== phase 2: offline requeue keeps parked-with-answered tasks ==")
  4248. # A daemon dying while its parked task carries an answered
  4249. # verdict: going offline must not requeue the task or close its
  4250. # session — the resume machinery (delivery once the daemon
  4251. # returns, or the affinity allocation on its next ask) needs
  4252. # both. The question park leaves the row idle; the review park
  4253. # keeps it busy@task (`saddle review` blocks the round without
  4254. # a parking state push), exercising the unreachable path's
  4255. # requeue decision both ways.
  4256. stranded = answerflow_daemon()
  4257. register_answerflow(stranded, "resume-stranded")
  4258. stranded_task = create_answerflow_task("Stranded answered task")
  4259. ask_status, _ = stranded.ask_now()
  4260. check(ask_status == 200, "the stranded daemon claims its task")
  4261. stranded.state = "blocked"
  4262. stranded.push_results("blocked", block={
  4263. "question": "Hold or fold?", "type": "question", "options": ["Hold", "Fold"]})
  4264. check(wait_for(lambda: task_state(auth, stranded_task).get("status") == "blocked"
  4265. or False, timeout=30, what="stranded task parked") is not None,
  4266. "the stranded task parks as blocked")
  4267. detail = task_state(auth, stranded_task)
  4268. hold_block = [b for b in detail["blocks"] if b["question"] == "Hold or fold?"][0]
  4269. act(auth, hold_block["answer_action"], {"option": "Hold"})
  4270. stranded.kill() # the daemon dies before the verdict is delivered
  4271. act(auth, saddle_card(auth, "resume-stranded")["refresh"], {})
  4272. check(wait_for(lambda: saddle_card(auth, "resume-stranded")["status"] == "offline"
  4273. or False, timeout=30, what="stranded saddle offline") is not None,
  4274. "the dead daemon's saddle row goes offline")
  4275. # Converted sleep(7): offline ticks run while the task MUST stay
  4276. # parked — a requeue during the window fails loudly.
  4277. check(quiet_window(quiet_seconds(),
  4278. lambda: task_state(auth, stranded_task)["status"] == "blocked",
  4279. "stranded task not requeued"),
  4280. "the parked-with-answered task is not requeued by the offline pass")
  4281. conn = db()
  4282. open_session = conn.execute(
  4283. "select count(*) from sessions where task_id = ? and ended_at is null",
  4284. (stranded_task,)).fetchone()[0]
  4285. conn.close()
  4286. check(open_session == 1,
  4287. "the parked-with-answered task keeps its open session for the resume")
  4288. reviewer = answerflow_daemon(ask_on_terminal=False)
  4289. register_answerflow(reviewer, "resume-reviewer")
  4290. review_task = create_answerflow_task("Review park task")
  4291. ask_status, _ = reviewer.ask_now()
  4292. check(ask_status == 200, "the reviewer claims its task")
  4293. # Post Task A the review park frees the daemon: the blocked push
  4294. # carries the review block and parks the row idle.
  4295. reviewer.state = "blocked"
  4296. check(reviewer.push_results("blocked", block={
  4297. "question": "Review requested", "type": "review",
  4298. "body": "Ready for review: wired and tested."}) == 200,
  4299. "the review park push carries the review block")
  4300. check(wait_for(lambda: task_state(auth, review_task).get("status") == "review_requested"
  4301. or False, timeout=30, what="review park raised") is not None,
  4302. "the review block parks the task as review_requested (row freed)")
  4303. # The verdict lands (nothing delivers it anymore); THEN the daemon
  4304. # dies and the manual refresh offlines it — the parked-with-answered
  4305. # task must keep its session for the eventual resume.
  4306. detail = task_state(auth, review_task)
  4307. verdict_block = [b for b in detail["blocks"]
  4308. if b["block_type"] == "review"][0]
  4309. act(auth, verdict_block["answer_action"],
  4310. {"answer": "Review approved. Continue with the task."})
  4311. reviewer.kill()
  4312. act(auth, saddle_card(auth, "resume-reviewer")["refresh"], {})
  4313. check(wait_for(lambda: saddle_card(auth, "resume-reviewer")["status"] == "offline"
  4314. or False, timeout=30, what="reviewer offline") is not None,
  4315. "the dead reviewer goes offline on the failed probe")
  4316. # Converted sleep(7): offline ticks run while the task MUST stay
  4317. # review-parked — a requeue during the window fails loudly.
  4318. check(quiet_window(quiet_seconds(),
  4319. lambda: task_state(auth, review_task)["status"] == "review_requested",
  4320. "review-parked task not requeued"),
  4321. "the review-parked task with an answered verdict is never requeued")
  4322. conn = db()
  4323. open_session = conn.execute(
  4324. "select count(*) from sessions where task_id = ? and ended_at is null",
  4325. (review_task,)).fetchone()[0]
  4326. conn.close()
  4327. check(open_session == 1,
  4328. "the review-parked task keeps its open session for the resume")
  4329. print("== phase 2: staleness — one probe decides ==")
  4330. # A silent-but-alive runner (long think, nothing to flush): after
  4331. # SADDLE_STALE_S (3s here) of silence it owes ONE exceptional
  4332. # GET /status; the answer keeps it running and the silence
  4333. # episode gets no second probe.
  4334. task_id_tmp = create_queued(auth, {
  4335. "project_id": "1",
  4336. "title": "Silent thinker",
  4337. "priority": "2",
  4338. })
  4339. thinker = task_id_tmp
  4340. check(wait_for(lambda: task_state(auth, thinker).get("status") == "working"
  4341. or False, timeout=60, what="thinker working") is not None,
  4342. "silent thinker reaches working")
  4343. fake.silent = True # the daemon goes quiet mid-round (alive)
  4344. probes_at_start = fake.status_hits
  4345. check(wait_for(lambda: fake.status_hits > probes_at_start or False,
  4346. timeout=30, what="exceptional probe arrives") is not None,
  4347. "a silent runner gets its exceptional GET /status probe")
  4348. # Converted sleep(8)+sleep(6): a quiet window across several
  4349. # ticks in which the probe count MUST NOT move — a second probe
  4350. # (the poll drumbeat this guards against) fails loudly.
  4351. second_window = fake.status_hits
  4352. check(quiet_window(quiet_seconds(),
  4353. lambda: fake.status_hits == second_window,
  4354. "no second staleness probe"),
  4355. "the silence episode is probed exactly once (no poll drumbeat)")
  4356. check(task_state(auth, thinker).get("status") == "working"
  4357. and saddle_card(auth, "fake-saddle")["status"] == "busy",
  4358. "the answered probe keeps the task running (no requeue)")
  4359. # Output flows again: the episode ends, the clock resets.
  4360. fake.silent = False
  4361. fake.push_chunks(["resumed output\r\n"])
  4362. check(wait_task_done(auth, thinker, timeout=60) is not None,
  4363. "the silent thinker completes once output flows again")
  4364. # The daemon vanishing mid-task: silence for the window, the
  4365. # probe fails, the task requeues with a bot comment and the
  4366. # saddle goes offline.
  4367. task_id_tmp = create_queued(auth, {
  4368. "project_id": "1",
  4369. "title": "Vanish victim",
  4370. "priority": "2",
  4371. })
  4372. vanish = task_id_tmp
  4373. check(wait_for(lambda: task_state(auth, vanish).get("status") == "working"
  4374. or False, timeout=60, what="vanish victim working") is not None,
  4375. "vanish victim reaches working")
  4376. fake.kill()
  4377. check(wait_for(lambda: saddle_card(auth, "fake-saddle")["status"] == "offline" or False,
  4378. timeout=60, what="daemon death -> offline") is not None,
  4379. "vanishing daemon drives the saddle offline (failed staleness probe)")
  4380. check(wait_for(lambda: any("unreachable" in c["body"]
  4381. for c in task_state(auth, vanish).get("comments", []))
  4382. or False, timeout=30, what="unreachable comment") is not None,
  4383. "the affected task gets an unreachable bot comment")
  4384. check(task_state(auth, vanish)["status"] == "queued",
  4385. "the task requeues after the daemon death")
  4386. card = saddle_card(auth, "fake-saddle")
  4387. check(card.get("health") == "offline",
  4388. "health badge reports offline")
  4389. # The unreachable row flag marks the detection window: a task the
  4390. # web still sees working while its saddle is offline/fenced, before
  4391. # the requeue pass moves it. Controlled window (the real
  4392. # transitions above are atomic with their requeues).
  4393. conn = db()
  4394. conn.execute("insert into tasks (project_id, title, status, priority,"
  4395. " created_at) values (1, 'Unreachable row', 'working', 5,"
  4396. " strftime('%s','now'))")
  4397. unreachable_row = conn.execute("select max(id) from tasks").fetchone()[0]
  4398. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  4399. " values (?, ?, strftime('%s','now'))", (unreachable_row, fake_id))
  4400. conn.commit()
  4401. conn.close()
  4402. row = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  4403. if int(t["id"]) == unreachable_row][0]
  4404. check(row.get("unreachable") is True,
  4405. "queue row shows the unreachable state in the window")
  4406. print("== phase 1: startup migrates the per-saddle token ==")
  4407. # Saddles registered before the flip hold legacy api_tokens rows.
  4408. # On startup every saddle row gets its canonical token: the
  4409. # legacy value it already holds (daemons keep their credential)
  4410. # or a freshly minted one. Fixture: this shard's own racer.
  4411. fake2 = FakeSaddle()
  4412. fake2.ask_on_register = False
  4413. fake2.serve(port=free_port())
  4414. saddles_state = slot_public(auth, "/saddles", "saddles")
  4415. act(auth, saddles_state["register"], {"name": "racer-two",
  4416. "host": "127.0.0.1:%d" % fake2.port})
  4417. racer_two_id = int([s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  4418. if s["name"] == "racer-two"][0]["id"])
  4419. conn = db()
  4420. conn.execute("insert into api_tokens (saddle_id, token, created_at)"
  4421. " values (?, 'saddle-legacy-copied-token', strftime('%s','now'))",
  4422. (racer_two_id,))
  4423. conn.execute("update saddles set token = null where name = 'racer-two'")
  4424. conn.execute("insert into saddles (name, host, status, current_task_id)"
  4425. " values ('tokenless-orphan', '127.0.0.1:1', 'offline', 0)")
  4426. conn.commit()
  4427. conn.close()
  4428. app.terminate()
  4429. app.wait(timeout=10)
  4430. app = start_app()
  4431. auth = login("admin", "adminpass123")
  4432. ctx.app = app # teardown tracks the restarted process
  4433. ctx.auth = auth
  4434. def saddle_row(name):
  4435. conn = db()
  4436. try:
  4437. return conn.execute("select id, token from saddles where name = ?",
  4438. (name,)).fetchone()
  4439. finally:
  4440. conn.close()
  4441. check(wait_for(lambda: saddle_row("tokenless-orphan") is not None
  4442. and (saddle_row("tokenless-orphan")[1] or "").startswith("saddle-")
  4443. or False, timeout=20, what="tokenless row minted") is not None,
  4444. "startup mints a token for a saddle row without one")
  4445. check(wait_for(lambda: saddle_row("racer-two") is not None
  4446. and saddle_row("racer-two")[1] == "saddle-legacy-copied-token"
  4447. or False, timeout=20, what="legacy token copied") is not None,
  4448. "startup copies the legacy api_tokens value onto the row")
  4449. fake2.token = "saddle-legacy-copied-token" # the daemon asks with it
  4450. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-legacy-copied-token")
  4451. check(status in (200, 204),
  4452. "the legacy token still authenticates (copied, not replaced)")
  4453. conn = db()
  4454. conn.execute("delete from saddles where name = 'tokenless-orphan'")
  4455. conn.commit()
  4456. conn.close()
  4457. # The restart wiped the in-memory ask bookkeeping; the fleet's
  4458. # daemons re-establish sleeping with a fresh ask each (the real
  4459. # daemons' idle-awake ask / 15-minute safety self-ask).
  4460. for daemon in (fake2,):
  4461. daemon.ask_now()
  4462. check(True, "fleet re-asks after the restart (sleeping re-established)")
  4463. # =============================================================================
  4464. # Bundle: push — plan 11 task E: real Web Push over VAPID. VAPID
  4465. # persistence, the service worker, subscription CRUD + validation,
  4466. # notify-me prefs, the block/lifecycle dispatch matrix (global vs
  4467. # opted-in), 410 pruning, retry-next-tick delivery and protocol-level
  4468. # payload verification (RFC 8291 decryption + ES256 JWT) against the
  4469. # fake push service.
  4470. # =============================================================================
  4471. def bundle_push(ctx):
  4472. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4473. def subscription_count(endpoint):
  4474. conn = db()
  4475. try:
  4476. return conn.execute(
  4477. "select count(*) from push_subscriptions where endpoint = ?",
  4478. (endpoint,)).fetchone()[0]
  4479. finally:
  4480. conn.close()
  4481. print("== task E: service worker asset ==")
  4482. status, sw = http("GET", "/sw.js", timeout=15)
  4483. check(status == 200 and "addEventListener('push'" in sw
  4484. and "notificationclick" in sw and "clients.openWindow" in sw,
  4485. "the service worker serves at the origin root with push + click routing")
  4486. print("== task E: VAPID keypair generation + persistence ==")
  4487. config = json.load(open(os.path.join(WORK, "web-config.json")))
  4488. vapid = config.get("vapid") or {}
  4489. check(bool(vapid.get("public_key")) and bool(vapid.get("private_key")),
  4490. "the VAPID keypair persists into web-config.json's vapid section")
  4491. vapid_private_key = ec.derive_private_key(
  4492. int.from_bytes(b64url_dec(vapid["private_key"]), "big"), ec.SECP256R1())
  4493. derived_public = vapid_private_key.public_key().public_bytes(
  4494. Encoding.X962, PublicFormat.UncompressedPoint)
  4495. check(b64url_dec(vapid["public_key"]) == derived_public,
  4496. "the persisted public key matches the private scalar (a valid P-256 pair)")
  4497. dash = slot_public(auth, "/", "dashboard")
  4498. check(dash.get("push_vapid_key") == vapid["public_key"],
  4499. "the dashboard exposes the same VAPID key to subscribers")
  4500. check(dash.get("push_subscribed") is False and bool(dash.get("push_subscribe")),
  4501. "the bell starts unsubscribed and carries the subscribe action")
  4502. print("== task E: subscription CRUD + auth validation ==")
  4503. browser = ec.generate_private_key(ec.SECP256R1())
  4504. browser_public = browser.public_key().public_bytes(
  4505. Encoding.X962, PublicFormat.UncompressedPoint)
  4506. browser_auth = os.urandom(16)
  4507. subscribe_fields = {"p256dh": b64url(browser_public), "auth": b64url(browser_auth)}
  4508. valid_endpoint = "http://127.0.0.1:1/x"
  4509. check("absolute http(s)" in (action_notify(act(auth, dash["push_subscribe"],
  4510. {"endpoint": "ftp://example.com/push", **subscribe_fields})) or ""),
  4511. "a non-http endpoint is rejected")
  4512. check("p256dh" in (action_notify(act(auth, dash["push_subscribe"],
  4513. {"endpoint": valid_endpoint, "p256dh": b64url(os.urandom(64)),
  4514. "auth": subscribe_fields["auth"]})) or ""),
  4515. "a malformed p256dh point is rejected")
  4516. check("auth" in (action_notify(act(auth, dash["push_subscribe"],
  4517. {"endpoint": valid_endpoint, "p256dh": subscribe_fields["p256dh"],
  4518. "auth": b64url(os.urandom(15))})) or ""),
  4519. "a malformed auth secret is rejected")
  4520. push = FakePushService()
  4521. push.serve()
  4522. endpoint_main = push.url("/main")
  4523. act(auth, dash["push_subscribe"],
  4524. {"endpoint": endpoint_main, **subscribe_fields})
  4525. conn = db()
  4526. rows = conn.execute("select user_id, p256dh, auth from push_subscriptions"
  4527. " where endpoint = ?", (endpoint_main,)).fetchall()
  4528. admin_id = conn.execute("select id from spry_users where username = 'admin'"
  4529. ).fetchone()[0]
  4530. conn.close()
  4531. check(len(rows) == 1 and rows[0][0] == admin_id,
  4532. "a valid subscription stores against the signed-in user")
  4533. # Re-subscribing the same endpoint replaces (never duplicates).
  4534. rotated_auth = os.urandom(16)
  4535. act(auth, dash["push_subscribe"],
  4536. {"endpoint": endpoint_main, "p256dh": subscribe_fields["p256dh"],
  4537. "auth": b64url(rotated_auth)})
  4538. conn = db()
  4539. rows = conn.execute("select auth from push_subscriptions where endpoint = ?",
  4540. (endpoint_main,)).fetchall()
  4541. conn.close()
  4542. check(len(rows) == 1 and rows[0][0] == b64url(rotated_auth),
  4543. "re-subscribing an endpoint replaces its keys in place")
  4544. print("== task E: notify-me pref persistence ==")
  4545. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4546. {"project_id": "1", "title": "Push pref task", "priority": "5"})
  4547. pref_task = task_id_of("Push pref task")
  4548. act(auth, task_state(auth, pref_task)["toggle_notify"], {})
  4549. conn = db()
  4550. check(conn.execute("select count(*) from task_notify_prefs where task_id = ?"
  4551. " and user_id = ?", (pref_task, admin_id)).fetchone()[0] == 1,
  4552. "Notify me persists a task_notify_prefs row for the user")
  4553. conn.close()
  4554. check(task_state(auth, pref_task).get("notify_me") is True,
  4555. "the task slot reflects notify_me after the toggle")
  4556. act(auth, task_state(auth, pref_task)["toggle_notify"], {})
  4557. conn = db()
  4558. check(conn.execute("select count(*) from task_notify_prefs where task_id = ?",
  4559. (pref_task,)).fetchone()[0] == 0,
  4560. "Don't notify me removes the pref row")
  4561. conn.close()
  4562. check(task_state(auth, pref_task).get("notify_me") is False,
  4563. "the task slot reflects the opt-out")
  4564. print("== task E: dispatch matrix — global blocks vs opted-in lifecycle ==")
  4565. # Two "browsers" for admin (/main, /gone) and one for another user
  4566. # (id 999, rows seeded directly — push targeting is per user).
  4567. endpoint_gone = push.url("/gone")
  4568. push.status_for["/gone"] = 410
  4569. act(auth, dash["push_subscribe"],
  4570. {"endpoint": endpoint_gone, **subscribe_fields})
  4571. other_browser = ec.generate_private_key(ec.SECP256R1())
  4572. other_public = other_browser.public_key().public_bytes(
  4573. Encoding.X962, PublicFormat.UncompressedPoint)
  4574. other_auth = os.urandom(16)
  4575. endpoint_other = push.url("/other")
  4576. conn = db()
  4577. conn.execute("insert into push_subscriptions (user_id, endpoint, p256dh, auth,"
  4578. " created_at) values (999, ?, ?, ?, strftime('%s','now'))",
  4579. (endpoint_other, b64url(other_public), b64url(other_auth)))
  4580. conn.commit()
  4581. conn.close()
  4582. # Task 1: admin opted in via the UI toggle; the other user is not.
  4583. # Baselines are captured BEFORE the enqueue: the first-start push
  4584. # fires at the allocation, the instant the dispatch lands.
  4585. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4586. {"project_id": "1", "title": "Push lifecycle task", "priority": "5"})
  4587. task1 = task_id_of("Push lifecycle task")
  4588. act(auth, task_state(auth, task1)["toggle_notify"], {})
  4589. main_before = len(push.hits("/main"))
  4590. other_before = len(push.hits("/other"))
  4591. gone_before = len(push.hits("/gone"))
  4592. enqueue_task(auth, task1)
  4593. check(wait_for(lambda: fake.running_task == task1 or False, timeout=30,
  4594. what="task 1 assignment") is not None,
  4595. "task 1 dispatches to the fake daemon")
  4596. task1_session = fake.session_id
  4597. check(wait_for(lambda: len(push.hits("/main")) > main_before, timeout=15,
  4598. what="first-start push to the opted-in admin") is not None,
  4599. "first start notifies the opted-in user's subscription")
  4600. check(wait_for(lambda: len(push.hits("/gone")) > gone_before, timeout=15,
  4601. what="first-start push to the gone endpoint") is not None,
  4602. "first start reaches every subscription of the opted-in user")
  4603. check(quiet_window(quiet_seconds(),
  4604. lambda: len(push.hits("/other")) == other_before,
  4605. "no first-start push to the not-opted-in user"),
  4606. "first start never reaches users without the notify pref")
  4607. check(wait_task_done(auth, task1, timeout=60) is not None,
  4608. "task 1 completes")
  4609. _, done_payload = decrypt_webpush(push.hits("/main")[-1], browser,
  4610. browser_public, rotated_auth)
  4611. check(done_payload["title"] == "Push lifecycle task — completed"
  4612. and done_payload["url"] == "/tasks/%d" % task1,
  4613. "completion notifies the opted-in user (decrypted payload)")
  4614. check(len(push.hits("/other")) == other_before,
  4615. "completion stays with the opted-in user only")
  4616. check(wait_for(lambda: subscription_count(endpoint_gone) == 0, timeout=15,
  4617. what="410 endpoint pruned") is not None,
  4618. "a 410 Gone endpoint is pruned from push_subscriptions")
  4619. # Block events go to EVERY push-subscribed user globally.
  4620. main_before = len(push.hits("/main"))
  4621. other_before = len(push.hits("/other"))
  4622. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  4623. {"type": "block", "session_id": task1_session, "data": {
  4624. "question": "Global question for everyone?", "type": "question"}})
  4625. check(wait_for(lambda: len(push.hits("/main")) > main_before
  4626. and len(push.hits("/other")) > other_before, timeout=15,
  4627. what="global block push") is not None,
  4628. "a raised block notifies every push-subscribed user globally")
  4629. block_hit = push.hits("/other")[-1]
  4630. _, payload = decrypt_webpush(block_hit, other_browser, other_public, other_auth)
  4631. check(payload["title"] == "Push lifecycle task — question raised"
  4632. and payload["body"] == "Global question for everyone?"
  4633. and payload["url"] == "/tasks/%d" % task1,
  4634. "the block payload carries task title + kind, question and click URL (%s)"
  4635. % payload)
  4636. ciphertext_len = len(block_hit["body"]) - (21 + 65)
  4637. envelope = block_hit["body"]
  4638. record_size = int.from_bytes(envelope[16:20], "big")
  4639. # rs = plaintext + delimiter (1) + tag (16) == ciphertext-with-tag len.
  4640. check(record_size == ciphertext_len,
  4641. "the RFC 8291 envelope record size covers payload + delimiter + tag")
  4642. claims = verify_vapid(block_hit, vapid["public_key"], vapid["private_key"])
  4643. check(claims.get("aud") == "http://127.0.0.1:%d" % push.port
  4644. and claims.get("sub", "").startswith("mailto:")
  4645. and claims.get("exp", 0) > time.time(),
  4646. "the VAPID JWT verifies: aud = the endpoint origin, mailto sub, future exp")
  4647. check(block_hit["headers"].get("ttl") == "60"
  4648. and block_hit["headers"].get("content-type") == "application/octet-stream",
  4649. "the push POST carries TTL and the encrypted content type")
  4650. # Task 2: only the OTHER user opted in — start + failure reach them
  4651. # alone. Baseline again before the enqueue (first start fires at
  4652. # the allocation).
  4653. fake.fail_next = True
  4654. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4655. {"project_id": "1", "title": "Push failure task", "priority": "5"})
  4656. task2 = task_id_of("Push failure task")
  4657. conn = db()
  4658. conn.execute("insert into task_notify_prefs (task_id, user_id) values (?, 999)",
  4659. (task2,))
  4660. conn.commit()
  4661. conn.close()
  4662. main_before2 = len(push.hits("/main"))
  4663. other_before2 = len(push.hits("/other"))
  4664. enqueue_task(auth, task2)
  4665. check(wait_for(lambda: fake.running_task == task2 or False, timeout=30,
  4666. what="task 2 assignment") is not None,
  4667. "task 2 dispatches (scripted to fail)")
  4668. check(wait_for(lambda: task_state(auth, task2)["status"] == "failed"
  4669. or False, timeout=30, what="task 2 failed") is not None,
  4670. "task 2 fails")
  4671. check(wait_for(lambda: len(push.hits("/other")) >= other_before2 + 2,
  4672. timeout=15, what="opted-in user's started+failed pushes"),
  4673. "the opted-in user gets first start AND failure for the task")
  4674. started_hit = [hit for hit in push.hits("/other")[other_before2:]][0]
  4675. _, started_payload = decrypt_webpush(started_hit, other_browser,
  4676. other_public, other_auth)
  4677. check(started_payload["title"] == "Push failure task — started",
  4678. "the first-start payload names task + kind (%s)" % started_payload)
  4679. _, failure_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4680. other_public, other_auth)
  4681. check(failure_payload["title"] == "Push failure task — failed"
  4682. and failure_payload["url"] == "/tasks/%d" % task2,
  4683. "the failure payload names the task and links its page")
  4684. check(len(push.hits("/main")) == main_before2,
  4685. "an agent failure never reaches users without the pref")
  4686. print("== task E: retry next tick (best-effort delivery) ==")
  4687. endpoint_flaky = push.url("/flaky")
  4688. act(auth, dash["push_subscribe"],
  4689. {"endpoint": endpoint_flaky, **subscribe_fields})
  4690. push.fail_next["/flaky"] = 1
  4691. flaky_before = len(push.hits("/flaky"))
  4692. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  4693. {"type": "block", "session_id": task1_session, "data": {
  4694. "question": "Flaky delivery question?", "type": "question"}})
  4695. check(wait_for(lambda: len(push.hits("/flaky")) >= flaky_before + 2,
  4696. timeout=20, what="flaky endpoint retried") is not None,
  4697. "a failed send retries on the next dispatcher tick and lands")
  4698. print("== plan 12: goal notifications — blocks/success/failure always ==")
  4699. # Goal blocks, completion approval and failure push to EVERY
  4700. # subscribed user (the mirror on the goal-run task stays quiet).
  4701. def goal_state(goal_id):
  4702. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  4703. push_goal = None
  4704. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4705. "project_id": "1", "title": "Push goal", "brief": "Notifies everyone.",
  4706. "branch_name": "goal/push"})
  4707. conn = db()
  4708. row = conn.execute("select id from goals where title = 'Push goal'").fetchone()
  4709. conn.close()
  4710. push_goal = int(row[0])
  4711. fake.goal_script = [("plan", "# Push plan\n\n1. Ring the bells")]
  4712. main_before = len(push.hits("/main"))
  4713. other_before = len(push.hits("/other"))
  4714. act(auth, goal_state(push_goal)["start"], {})
  4715. check(wait_for(lambda: goal_state(push_goal)["status"] == "plan_review" or False,
  4716. timeout=60, what="push goal enters plan review") is not None,
  4717. "the push goal reaches plan review")
  4718. check(wait_for(lambda: len(push.hits("/main")) > main_before
  4719. and len(push.hits("/other")) > other_before, timeout=15,
  4720. what="goal plan-review push") is not None,
  4721. "a goal plan review notifies every subscribed user globally")
  4722. _, plan_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4723. other_public, other_auth)
  4724. check("Push goal" in plan_payload["title"] and "plan" in plan_payload["title"]
  4725. and plan_payload["url"] == "/goals/%d" % push_goal,
  4726. "the goal block payload carries the goal title + click URL (%s)"
  4727. % plan_payload)
  4728. main_before = len(push.hits("/main"))
  4729. fake.goal_script = [("suspend",)]
  4730. act(auth, goal_state(push_goal)["plan_pending_block"]["answer_action"],
  4731. {"answer": "Plan approved. Proceed with implementation."})
  4732. check(wait_for(lambda: goal_state(push_goal)["status"] == "active" or False,
  4733. timeout=30, what="push goal active") is not None,
  4734. "the push goal activates")
  4735. check(quiet_window(3, lambda: len(push.hits("/main")) == main_before,
  4736. "no push for an internal resume"),
  4737. "the goal agent's own park/resume does not notify (internal)")
  4738. # `saddle failure` in goal context fails the goal — global push.
  4739. fake.goal_script = [("fail", "the harness collapsed")]
  4740. other_before2 = len(push.hits("/other"))
  4741. main_before2 = len(push.hits("/main"))
  4742. conn = db()
  4743. conn.execute("insert into goal_events (goal_id, kind, text, created_at)"
  4744. " values (?, 'task-done', 'Task #999 Warm — done',"
  4745. " strftime('%s','now','-5 seconds'))", (push_goal,))
  4746. conn.commit()
  4747. conn.close()
  4748. check(wait_for(lambda: goal_state(push_goal)["status"] == "failed" or False,
  4749. timeout=60, what="goal failure lands") is not None,
  4750. "the goal agent's failure fails the goal")
  4751. check(wait_for(lambda: len(push.hits("/other")) > other_before2
  4752. and len(push.hits("/main")) > main_before2, timeout=15,
  4753. what="goal failure push") is not None,
  4754. "a goal failure notifies every subscribed user globally")
  4755. _, fail_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4756. other_public, other_auth)
  4757. check("Push goal" in fail_payload["title"] and "failed" in fail_payload["title"]
  4758. and fail_payload["url"] == "/goals/%d" % push_goal,
  4759. "the goal failure payload carries the goal title + click URL (%s)"
  4760. % fail_payload)
  4761. # Completion approval pushes "complete" globally (success always).
  4762. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4763. "project_id": "1", "title": "Push done goal", "brief": "Completes.",
  4764. "branch_name": "goal/push-done"})
  4765. conn = db()
  4766. row = conn.execute("select id from goals where title = 'Push done goal'").fetchone()
  4767. conn.close()
  4768. done_goal = int(row[0])
  4769. fake.goal_script = [("plan", "# Done plan")]
  4770. act(auth, goal_state(done_goal)["start"], {})
  4771. check(wait_for(lambda: goal_state(done_goal)["status"] == "plan_review" or False,
  4772. timeout=60, what="done goal plan review") is not None,
  4773. "the done goal reaches plan review")
  4774. fake.goal_script = [("done", "# Completion\n\nShipped.")]
  4775. act(auth, goal_state(done_goal)["plan_pending_block"]["answer_action"],
  4776. {"answer": "Plan approved. Proceed with implementation."})
  4777. check(wait_for(lambda: goal_state(done_goal)["status"] == "completion_review"
  4778. or False, timeout=60, what="done goal completion review") is not None,
  4779. "the approved done goal reaches completion review")
  4780. main_before = len(push.hits("/main"))
  4781. act(auth, goal_state(done_goal)["completion_pending_block"]["answer_action"],
  4782. {"answer": "Review approved. Continue with the task."})
  4783. check(wait_for(lambda: goal_state(done_goal)["status"] == "complete" or False,
  4784. timeout=30, what="done goal completes") is not None,
  4785. "the done goal completes")
  4786. check(wait_for(lambda: len(push.hits("/main")) > main_before, timeout=15,
  4787. what="goal success push") is not None,
  4788. "a goal completion notifies every subscribed user globally")
  4789. _, done_goal_payload = decrypt_webpush(push.hits("/main")[-1], browser,
  4790. browser_public, rotated_auth)
  4791. check("Push done goal" in done_goal_payload["title"]
  4792. and "complete" in done_goal_payload["title"]
  4793. and done_goal_payload["url"] == "/goals/%d" % done_goal,
  4794. "the goal success payload carries the goal title + click URL (%s)"
  4795. % done_goal_payload)
  4796. print("== task E: unsubscribe removes the subscription ==")
  4797. dash = slot_public(auth, "/", "dashboard")
  4798. check(dash.get("push_subscribed") is True,
  4799. "the bell shows subscribed while endpoints exist")
  4800. act(auth, dash["push_unsubscribe"], {"endpoint": endpoint_main})
  4801. check(subscription_count(endpoint_main) == 0,
  4802. "unsubscribing removes the endpoint's row")
  4803. # =============================================================================
  4804. # Bundle: goals — the plan-12 goal lifecycle: creation with branch-name
  4805. # uniqueness, the start → planning → plan review → active flow with
  4806. # revisions, the goal agent's task fan-out through the task CLI
  4807. # callbacks (ownership + creator-only enqueue), the event-driven
  4808. # coalesced resume, pause/resume queueing, the completion review with
  4809. # branch push state, the cancel cascade, and the human tasks'
  4810. # auto-enqueue-after predecessor.
  4811. # =============================================================================
  4812. def bundle_goals(ctx):
  4813. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4814. app = ctx.app
  4815. def goal_state(goal_id):
  4816. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  4817. def create_goal(fields):
  4818. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  4819. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  4820. if g["title"] == fields["title"]]
  4821. return int(rows[0]["id"])
  4822. print("== plan 12: goal creation, validation, lifecycle actions ==")
  4823. goal1 = create_goal({"project_id": "1", "title": "Ship the flange",
  4824. "brief": "Make the flange module production-grade.",
  4825. "branch_name": "goal/flange", "priority": "3"})
  4826. state = goal_state(goal1)
  4827. check(state["status"] == "draft" and state["display"] == "draft"
  4828. and state["branch_name"] == "goal/flange"
  4829. and state["base_branch"] == "main",
  4830. "a goal lands in draft with its branch pair")
  4831. check(state.get("start") is not None and state.get("cancel") is not None
  4832. and state.get("pause") is None,
  4833. "draft offers start + cancel only")
  4834. # Branch-name uniqueness: same name, same involved project → refuse.
  4835. duplicate_directives = act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4836. "project_id": "1", "title": "Clash", "brief": "b", "branch_name": "goal/flange"})
  4837. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  4838. and "goal/flange" in (d.get("message") or "")
  4839. for d in duplicate_directives),
  4840. "a live goal's branch name cannot be reused in an involved project (%s)"
  4841. % [d.get("message") for d in duplicate_directives if d.get("type") == "notify"])
  4842. conn = db()
  4843. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  4844. " values ('other-repo', 'https://example.com/other.git', 'main',"
  4845. " strftime('%s','now'))")
  4846. conn.commit()
  4847. conn.close()
  4848. goal_elsewhere = create_goal({"project_id": "2", "title": "Elsewhere",
  4849. "brief": "b", "branch_name": "goal/flange"})
  4850. check(goal_elsewhere > 0,
  4851. "the same branch name in a disjoint project is fine (one per repo)")
  4852. # Brief validation.
  4853. brief_directives = act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4854. "project_id": "1", "title": "No brief", "brief": " ", "branch_name": "goal/x1"})
  4855. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  4856. and "brief" in (d.get("message") or "").lower()
  4857. for d in brief_directives),
  4858. "an empty brief rejects")
  4859. # Start: planning + the goal-run internal task.
  4860. act(auth, state["start"], {})
  4861. state = goal_state(goal1)
  4862. check(state["status"] == "planning" and state.get("start") is None,
  4863. "start moves the goal to planning")
  4864. conn = db()
  4865. run_row = conn.execute(
  4866. "select id, kind, mode, creator, goal_id, priority, status from tasks"
  4867. " where goal_id = ? and kind = 'goal_run'", (goal1,)).fetchone()
  4868. conn.close()
  4869. check(run_row is not None and run_row[1] == "goal_run"
  4870. and run_row[2] == "orchestrate" and run_row[3] == "goal"
  4871. and run_row[4] == goal1 and run_row[5] == 3
  4872. and run_row[6] in ("queued", "assigned", "working"),
  4873. "start creates the goal-run task (orchestrate, priority 3, creator goal,"
  4874. " queued)")
  4875. run_task = int(run_row[0])
  4876. check(goal_state(goal1)["run_task_id"] == run_task,
  4877. "the goal state carries the run task id")
  4878. check(any(e["kind"] == "started" for e in goal_state(goal1)["events"]),
  4879. "the narrative records the start")
  4880. print("== plan 12: the goal agent plans, plan review, revisions ==")
  4881. fake.goal_script = [("plan", "# Plan v1\n\n1. Add tests\n2. Ship")]
  4882. check(wait_for(lambda: goal_state(goal1)["status"] == "plan_review" or False,
  4883. timeout=60, what="goal agent submits its plan") is not None,
  4884. "the goal agent's plan push enters plan review")
  4885. state = goal_state(goal1)
  4886. check(task_state(auth, run_task)["status"] == "blocked",
  4887. "the goal-run task parks on the plan review")
  4888. pending = state.get("plan_pending_block")
  4889. check(pending and "# Plan v1" in (pending.get("body") or ""),
  4890. "the pending plan review carries the submitted markdown")
  4891. check(any(b["block_type"] == "plan" and b["is_plan_review"]
  4892. for b in state["blocks"]),
  4893. "the goal blocks list carries the pending plan block")
  4894. # Reject with feedback: the agent revises.
  4895. fake.goal_script = [("plan", "# Plan v2\n\n1. Add tests\n2. Add docs\n3. Ship")]
  4896. act(auth, pending["answer_action"], {"answer": "Add documentation please"})
  4897. check(wait_for(lambda: goal_state(goal1)["status"] == "plan_review" or False,
  4898. timeout=60, what="revised plan enters review") is not None,
  4899. "feedback sends the agent back to planning; the revision re-enters review")
  4900. state = goal_state(goal1)
  4901. revisions = state["plan_revisions"]
  4902. check(len(revisions) == 2
  4903. and revisions[0]["answered"] and "Add documentation please" in revisions[0]["answer"]
  4904. and not revisions[1]["answered"],
  4905. "rejected revisions stay as answered history (historical-blocks data)")
  4906. # Approve: goal.plan = v2, status active, agent resumes and parks.
  4907. fake.goal_script = [("suspend",)]
  4908. pending = state["plan_pending_block"]
  4909. act(auth, pending["answer_action"],
  4910. {"answer": "Plan approved. Proceed with implementation."})
  4911. check(wait_for(lambda: goal_state(goal1)["status"] == "active" or False,
  4912. timeout=60, what="approved plan activates the goal") is not None,
  4913. "approving the plan activates the goal")
  4914. state = goal_state(goal1)
  4915. check("# Plan v2" in state["plan"], "the approved plan markdown is stored on the goal")
  4916. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  4917. or False, timeout=60, what="goal agent parks after approval") is not None,
  4918. "the resumed goal agent parks (saddle suspend)")
  4919. print("== plan 12: task fan-out via the task CLI callbacks ==")
  4920. # The goal agent (parked, open session on its saddle) creates,
  4921. # enqueues and deletes its tasks through /api/saddle/task/*.
  4922. conn = db()
  4923. agent_session = conn.execute(
  4924. "select id from sessions where task_id = ? and ended_at is null",
  4925. (run_task,)).fetchone()[0]
  4926. conn.close()
  4927. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  4928. "session_id": agent_session, "title": "Flange tests",
  4929. "mandate": "Write the test suite for the flange module.",
  4930. "mode": "test"})
  4931. check(status == 200 and body.get("ok") is True,
  4932. "task create under the goal succeeds (%s)" % body.get("error"))
  4933. fan_task = int(body["task_id"])
  4934. detail = task_state(auth, fan_task)
  4935. check(detail["status"] == "draft" and detail["mode"] == "test"
  4936. and detail["creator"] == "goal" and detail.get("goal_id") == goal1,
  4937. "the created task is a draft goal task with its mode and creator")
  4938. check(detail["task_branch"] == "task/%d-%d" % (goal1, fan_task)
  4939. and detail["branch_from"] == "goal/flange",
  4940. "goal worker tasks get ephemeral branches cut from the goal branch")
  4941. check(any(e["kind"] == "task-created" and int(e["task_id"]) == fan_task
  4942. for e in goal_state(goal1)["events"]),
  4943. "the narrative records the agent's task creation")
  4944. # Draft until the agent enqueues; humans may not (creator-only).
  4945. check(detail.get("enqueue") is None,
  4946. "the human Enqueue action is not offered for goal tasks (creator-only)")
  4947. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  4948. "session_id": agent_session, "task_id": fan_task})
  4949. check(status == 200 and task_state(auth, fan_task)["status"] == "queued",
  4950. "task enqueue by the goal agent queues the draft")
  4951. # Ownership + shape errors, verbatim for the CLI.
  4952. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  4953. "session_id": agent_session, "task_id": 999999})
  4954. check(status == 400 and "No task exists" in (body.get("error") or ""),
  4955. "enqueue of a missing task errors verbatim")
  4956. create_queued(auth, {"project_id": "1", "title": "Innocent bystander", "priority": "4"})
  4957. bystander = task_id_of("Innocent bystander")
  4958. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  4959. "session_id": agent_session, "task_id": bystander})
  4960. check(status == 400 and "does not belong to your goal" in (body.get("error") or ""),
  4961. "the goal agent cannot touch tasks outside its goal")
  4962. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  4963. "session_id": agent_session, "title": "Bad mode", "mandate": "m", "mode": "party"})
  4964. check(status == 400 and "valid modes" in (body.get("error") or ""),
  4965. "an unknown mode rejects with the valid list")
  4966. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  4967. "session_id": agent_session, "title": "Bad tag", "mandate": "m",
  4968. "capabilities": ["warp-drive"]})
  4969. check(status == 400 and "warp-drive" in (body.get("error") or "")
  4970. and "valid tags" in (body.get("error") or ""),
  4971. "an unknown capability tag rejects naming the valid set")
  4972. # A plain task's session is not a goal-agent identity.
  4973. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token,
  4974. {"session_id": 999999, "title": "x", "mandate": "m"})
  4975. check(status == 400 and "session" in (body.get("error") or ""),
  4976. "an unknown session_id errors verbatim")
  4977. # Delete: draft + owned.
  4978. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  4979. "session_id": agent_session, "title": "Scratch task", "mandate": "m"})
  4980. scratch = int(body["task_id"])
  4981. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  4982. "session_id": agent_session, "task_id": scratch})
  4983. check(status == 200 and not any(
  4984. t["id"] == scratch for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  4985. "task delete removes the owned draft")
  4986. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  4987. "session_id": agent_session, "task_id": fan_task})
  4988. check(status == 400 and "draft" in (body.get("error") or ""),
  4989. "deleting a queued task refuses (draft only)")
  4990. print("== plan 12: goal context in the worker assignment + coalesced resume ==")
  4991. # The queued fan-out task dispatches to the daemon with the goal
  4992. # reference + ephemeral branch; its completion schedules the parked
  4993. # goal agent's resume (>= SADDLE_GOAL_RESUME_S after the event).
  4994. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == fan_task
  4995. for p in fake.start_payloads) or False,
  4996. timeout=60, what="fan-out task dispatches") is not None,
  4997. "the goal worker task dispatches")
  4998. fan_payload = [p for p in fake.start_payloads
  4999. if int(p.get("task", {}).get("id") or 0) == fan_task][-1]
  5000. goal_ctx = fan_payload.get("goal") or {}
  5001. check(goal_ctx.get("id") == goal1 and goal_ctx.get("branch") == "goal/flange"
  5002. and goal_ctx.get("base_branch") == "main"
  5003. and "flange module" in goal_ctx.get("brief", "")
  5004. and "# Plan v2" in goal_ctx.get("plan", ""),
  5005. "the worker assignment carries the goal context (read-only brief + plan)")
  5006. check(fan_payload.get("ephemeral_branch") == "task/%d-%d" % (goal1, fan_task)
  5007. and fan_payload.get("kind") == "task" and fan_payload.get("mode") == "test"
  5008. and fan_payload.get("creator") == "goal",
  5009. "the worker assignment carries the ephemeral branch + identity triplet")
  5010. check(wait_task_done(auth, fan_task, timeout=60) is not None,
  5011. "the goal worker task completes")
  5012. check(any(e["kind"] == "task-done" and int(e["task_id"]) == fan_task
  5013. for e in goal_state(goal1)["events"]),
  5014. "the narrative records the task's completion")
  5015. goal_runs_before = len(fake.goal_assignments)
  5016. check(wait_for(lambda: len(fake.goal_assignments) > goal_runs_before or False,
  5017. timeout=30, what="parked goal agent resumes") is not None,
  5018. "the task-terminal event resumes the parked goal agent")
  5019. resume_payload = fake.goal_assignments[-1]
  5020. notice = resume_payload.get("resume_notice") or ""
  5021. check("Task statuses" in notice and "Flange tests" in notice
  5022. and "done" in notice,
  5023. "the resume notice batches ALL plan task statuses")
  5024. check("New completion reports" in notice and "fake daemon finished" in notice,
  5025. "the resume notice carries the new completion report")
  5026. check(resume_payload.get("kind") == "goal_run"
  5027. and resume_payload.get("mode") == "orchestrate",
  5028. "the resumed goal agent carries its identity triplet")
  5029. # The resumed agent parked again (script): two events at once must
  5030. # coalesce into ONE resume within the window.
  5031. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5032. or False, timeout=60, what="goal agent re-parks") is not None,
  5033. "the resumed goal agent parks again")
  5034. print("== plan 12: pause freezes supervision; events coalesce on resume ==")
  5035. state = goal_state(goal1)
  5036. act(auth, state["pause"], {})
  5037. check(goal_state(goal1)["status"] == "paused"
  5038. and goal_state(goal1).get("resume") is not None,
  5039. "an active goal pauses and offers resume")
  5040. # Terminal events under a paused goal queue without waking anybody.
  5041. conn = db()
  5042. conn.execute("insert into tasks (project_id, goal_id, kind, title, status, priority,"
  5043. " summary, completed_at, created_at) values (1, ?, 'task',"
  5044. " 'Quiet task', 'done', 5, 'finished while paused',"
  5045. " strftime('%s','now','+1 second'), strftime('%s','now'))", (goal1,))
  5046. conn.commit()
  5047. conn.close()
  5048. paused_runs = len(fake.goal_assignments)
  5049. check(quiet_window(quiet_seconds(),
  5050. lambda: len(fake.goal_assignments) == paused_runs,
  5051. "paused goal does not resume"),
  5052. "a paused goal's events queue without scheduling a resume")
  5053. state = goal_state(goal1)
  5054. act(auth, state["resume"], {})
  5055. check(goal_state(goal1)["status"] == "active",
  5056. "resume returns the goal to active")
  5057. check(wait_for(lambda: len(fake.goal_assignments) > paused_runs or False,
  5058. timeout=30, what="queued events flush on resume") is not None,
  5059. "the queued events coalesce into the post-resume wake")
  5060. check("finished while paused" in (fake.goal_assignments[-1].get("resume_notice") or ""),
  5061. "the flushed notice reports the task that finished while paused")
  5062. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5063. or False, timeout=60, what="goal agent parks again") is not None,
  5064. "the goal agent parks again after the flush")
  5065. print("== plan 12: completion review, push state, accept ==")
  5066. # The daemon exposes goal-branch push state on /status; the web
  5067. # caches it on the goal when it probes the goal agent's saddle.
  5068. def status_extra():
  5069. return None
  5070. fake.status_extra = {"goal_branches": [
  5071. {"branch": "goal/flange", "pushed": True},
  5072. {"branch": "goal/other-repo", "pushed": False}]}
  5073. fake_card = saddle_card(auth, "fake-saddle")
  5074. act(auth, fake_card["refresh"], {})
  5075. check(wait_for(lambda: goal_state(goal1).get("push_branches") or False,
  5076. timeout=30, what="push state lands on the goal") is not None,
  5077. "the daemon's /status goal_branches exposure caches on the goal")
  5078. branches = goal_state(goal1)["push_branches"]
  5079. check({(b["branch"], b["pushed"]) for b in branches}
  5080. == {("goal/flange", True), ("goal/other-repo", False)},
  5081. "the push state renders per branch")
  5082. fake.status_extra = None
  5083. # `saddle done` in goal context: the completion review.
  5084. fake.goal_script = [("done", "# Completion\n\nThe flange ships.")]
  5085. # Wake the parked agent: a pending event has waited out the window
  5086. # (the pause-flush above consumed the queue, so arm one directly —
  5087. # the queued 'Quiet task' row was consumed; use a fresh event).
  5088. conn = db()
  5089. conn.execute("insert into goal_events (goal_id, kind, text, created_at)"
  5090. " values (?, 'task-done', 'Task #999 Warmup — done',"
  5091. " strftime('%s','now','-5 seconds'))", (goal1,))
  5092. conn.commit()
  5093. conn.close()
  5094. check(wait_for(lambda: goal_state(goal1)["status"] == "completion_review" or False,
  5095. timeout=60, what="goal agent submits its completion") is not None,
  5096. "`saddle done` in goal context enters completion review")
  5097. state = goal_state(goal1)
  5098. check("# Completion" in state["completion_report"]
  5099. and state["completion_pending"] is True
  5100. and state["completion_pending_block"] is not None
  5101. and state["completion_pending_block"] is not False,
  5102. "the completion review state carries the report + pending block")
  5103. check(task_state(auth, run_task)["status"] == "blocked",
  5104. "the goal-run task parks on the completion review")
  5105. check(state["compare_url"].endswith("/compare/main...goal/flange"),
  5106. "the completion review links the compare view")
  5107. # Reject first: feedback returns the goal to active.
  5108. fake.goal_script = [("suspend",)]
  5109. act(auth, state["completion_pending_block"]["answer_action"],
  5110. {"answer": "Not done — the docs are missing"})
  5111. check(wait_for(lambda: goal_state(goal1)["status"] == "active" or False,
  5112. timeout=30, what="rejected completion reactivates") is not None,
  5113. "rejecting the completion returns the goal to active")
  5114. # Round 2: submit again and accept.
  5115. fake.goal_script = [("done", "# Completion v2\n\nThe flange ships, with docs.")]
  5116. conn = db()
  5117. conn.execute("insert into goal_events (goal_id, kind, text, created_at)"
  5118. " values (?, 'task-done', 'Task #998 Warmup2 — done',"
  5119. " strftime('%s','now','-5 seconds'))", (goal1,))
  5120. conn.commit()
  5121. conn.close()
  5122. check(wait_for(lambda: goal_state(goal1)["status"] == "completion_review" or False,
  5123. timeout=60, what="resubmitted completion") is not None,
  5124. "the agent resubmits its completion after feedback")
  5125. state = goal_state(goal1)
  5126. act(auth, state["completion_pending_block"]["answer_action"],
  5127. {"answer": "Review approved. Continue with the task."})
  5128. check(wait_for(lambda: goal_state(goal1)["status"] == "complete" or False,
  5129. timeout=30, what="accepted completion completes") is not None,
  5130. "accepting the completion completes the goal")
  5131. state = goal_state(goal1)
  5132. check(state["terminal"] is True and state.get("cancel") is None
  5133. and "# Completion v2" in state["completion_report"],
  5134. "a complete goal is terminal with its report stored")
  5135. check(wait_for(lambda: task_state(auth, run_task)["status"] == "done" or False,
  5136. timeout=30, what="goal run task closes") is not None,
  5137. "approving the completion closes the goal-run task done")
  5138. print("== plan 12: cancel cascades to the goal's tasks ==")
  5139. goal2 = create_goal({"project_id": "1", "title": "Doomed goal",
  5140. "brief": "This goal will be cancelled.",
  5141. "branch_name": "goal/doomed"})
  5142. fake.goal_script = [("suspend",)]
  5143. act(auth, goal_state(goal2)["start"], {})
  5144. conn = db()
  5145. run2 = conn.execute("select id from tasks where goal_id = ? and kind = 'goal_run'",
  5146. (goal2,)).fetchone()[0]
  5147. conn.close()
  5148. check(wait_for(lambda: task_state(auth, run2)["status"] == "suspended" or False,
  5149. timeout=60, what="doomed goal agent parks") is not None,
  5150. "the doomed goal's agent parks")
  5151. conn = db()
  5152. agent_session2 = conn.execute(
  5153. "select id from sessions where task_id = ? and ended_at is null",
  5154. (run2,)).fetchone()[0]
  5155. conn.close()
  5156. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5157. "session_id": agent_session2, "title": "Doomed draft", "mandate": "m"})
  5158. doomed_draft = int(body["task_id"])
  5159. doomed_queued_task = None
  5160. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5161. "session_id": agent_session2, "title": "Doomed runner", "mandate": "m"})
  5162. doomed_runner = int(body["task_id"])
  5163. saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  5164. {"session_id": agent_session2, "task_id": doomed_runner})
  5165. act(auth, goal_state(goal2)["cancel"], {})
  5166. check(goal_state(goal2)["status"] == "cancelled",
  5167. "the goal cancels from active (parked-agent) state")
  5168. check(task_state(auth, run2)["status"] == "failed",
  5169. "the cascade cancels the goal agent's run task")
  5170. check(wait_for(lambda: task_state(auth, doomed_runner)["status"] == "failed"
  5171. or False, timeout=30, what="cascade cancels the queued task") is not None,
  5172. "the cascade cancels the goal's queued task")
  5173. check(not any(t["id"] == doomed_draft
  5174. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5175. "the cascade deletes the goal's draft tasks")
  5176. # A cancelled goal frees its branch name.
  5177. reuse = create_goal({"project_id": "1", "title": "Reused name",
  5178. "brief": "b", "branch_name": "goal/doomed"})
  5179. check(reuse > goal2, "a cancelled goal's branch name is reusable")
  5180. print("== plan 12: auto-enqueue-after for human tasks ==")
  5181. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5182. "project_id": "1", "title": "Predecessor task", "priority": "4"})
  5183. predecessor = task_id_of("Predecessor task")
  5184. enqueue_task(auth, predecessor)
  5185. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5186. "project_id": "1", "title": "Successor task", "priority": "4",
  5187. "enqueue_after_task_id": str(predecessor)})
  5188. successor = task_id_of("Successor task")
  5189. check(task_state(auth, successor)["status"] == "draft"
  5190. and task_state(auth, successor).get("enqueue_after_task_id") == predecessor,
  5191. "a human task can carry an auto-enqueue predecessor")
  5192. check(wait_task_done(auth, predecessor, timeout=60) is not None,
  5193. "the predecessor completes")
  5194. check(wait_for(lambda: task_state(auth, successor)["status"] in
  5195. ("queued", "assigned", "working") or False,
  5196. timeout=30, what="successor auto-enqueues") is not None,
  5197. "the done predecessor auto-enqueues its dependent")
  5198. # Cycle validation refuses a predecessor chain that loops.
  5199. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5200. "project_id": "1", "title": "Cycle A", "priority": "4"})
  5201. cycle_a = task_id_of("Cycle A")
  5202. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5203. "project_id": "1", "title": "Cycle B", "priority": "4",
  5204. "enqueue_after_task_id": str(cycle_a)})
  5205. cycle_b = task_id_of("Cycle B")
  5206. cycle_directives = act(auth, task_state(auth, cycle_a)["update"], {
  5207. "title": "Cycle A", "description": "x", "priority": "4",
  5208. "enqueue_after_task_id": str(cycle_b)})
  5209. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  5210. and "cycle" in (d.get("message") or "").lower()
  5211. for d in cycle_directives),
  5212. "a predecessor cycle rejects with a naming error")
  5213. # A failed predecessor leaves the dependent in draft.
  5214. fake.fail_next = True
  5215. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5216. "project_id": "1", "title": "Failing predecessor", "priority": "1"})
  5217. failing_pred = task_id_of("Failing predecessor")
  5218. enqueue_task(auth, failing_pred)
  5219. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5220. "project_id": "1", "title": "Stranded successor", "priority": "4",
  5221. "enqueue_after_task_id": str(failing_pred)})
  5222. stranded = task_id_of("Stranded successor")
  5223. check(wait_for(lambda: task_state(auth, failing_pred)["status"] == "failed"
  5224. or False, timeout=60, what="failing predecessor fails") is not None,
  5225. "the scripted-failure predecessor fails")
  5226. check(quiet_window(quiet_seconds(),
  5227. lambda: task_state(auth, stranded)["status"] == "draft",
  5228. "failed predecessor leaves the draft"),
  5229. "a failed predecessor leaves its dependent in draft")
  5230. # Successor cleanup: let the queued successor finish so the
  5231. # shard's app shuts down with an empty queue.
  5232. check(wait_task_done(auth, successor, timeout=90) is not None,
  5233. "the auto-enqueued successor completes")
  5234. BUNDLES_ORDER = ("pages", "dispatch", "subtasks", "lineage",
  5235. "allocation", "lifecycle", "answers", "push", "goals")
  5236. def run_bundle(name):
  5237. """Runs one shard to completion; returns a failure count."""
  5238. started = time.monotonic()
  5239. ctx = start_bundle(name)
  5240. runner = globals()["bundle_" + name]
  5241. try:
  5242. runner(ctx)
  5243. finally:
  5244. # Exit-code diagnostic: distinguishes a crashed app (negative
  5245. # returncode, e.g. -11 SIGSEGV) from a clean shutdown. When
  5246. # tearing down mid-exception, also capture the still-alive
  5247. # app's stacks before killing it (a wedged-but-alive server
  5248. # otherwise leaves no evidence).
  5249. print("(app returncode at teardown: %s)" % ctx.app.poll())
  5250. if ctx.app.poll() is None and sys.exc_info()[0] is not None:
  5251. dump_app_stacks(ctx.app.pid)
  5252. ctx.fake.kill()
  5253. try:
  5254. ctx.app.terminate()
  5255. try:
  5256. ctx.app.wait(timeout=5)
  5257. except subprocess.TimeoutExpired:
  5258. ctx.app.kill()
  5259. check(ctx.app.poll() in (0, -15),
  5260. "bundle %s app shut down cleanly (exit %s)"
  5261. % (name, ctx.app.poll()))
  5262. except OSError:
  5263. pass
  5264. print("%d passed, %d failed" % (passes, failures))
  5265. print("[bundle %s] %.1fs" % (name, time.monotonic() - started))
  5266. return failures
  5267. def run_all_parallel():
  5268. """The default meson entry: one subprocess per bundle (each with its
  5269. own app, daemons and database), verdicts aggregated into one exit
  5270. code and one combined check-count summary."""
  5271. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  5272. log_dir = os.path.join(os.path.dirname(base) or "/tmp/kilo",
  5273. "webstack-shards")
  5274. os.makedirs(log_dir, exist_ok=True)
  5275. procs = {}
  5276. started = time.monotonic()
  5277. for name in BUNDLES_ORDER:
  5278. out_path = os.path.join(log_dir, "bundle-%s.log" % name)
  5279. handle = open(out_path, "w")
  5280. procs[name] = (subprocess.Popen(
  5281. [sys.executable, "-u", os.path.abspath(__file__), APP,
  5282. "--bundle", name],
  5283. stdout=handle, stderr=subprocess.STDOUT), handle, out_path)
  5284. total_pass = total_fail = 0
  5285. broken = []
  5286. for name, (proc, handle, out_path) in procs.items():
  5287. try:
  5288. proc.wait(timeout=SHARD_TIMEOUT_S)
  5289. except subprocess.TimeoutExpired:
  5290. proc.kill()
  5291. proc.wait()
  5292. handle.close()
  5293. text = open(out_path).read()
  5294. match = re.search(r"(\d+) passed, (\d+) failed", text)
  5295. took = re.search(r"\[bundle %s\] ([0-9.]+)s" % name, text)
  5296. bundle_pass = int(match.group(1)) if match else 0
  5297. bundle_fail = int(match.group(2)) if match else -1
  5298. total_pass += max(bundle_pass, 0)
  5299. total_fail += max(bundle_fail, 0)
  5300. status = "ok"
  5301. if proc.returncode != 0 or bundle_fail != 0 or match is None:
  5302. status = "BROKEN (exit %s)" % proc.returncode
  5303. broken.append(name)
  5304. print("[shard %-10s] %6ss %3d passed %3d failed %s"
  5305. % (name, took.group(1) if took else "?",
  5306. bundle_pass, bundle_fail, status))
  5307. if status != "ok":
  5308. tail = "\n".join(text.rstrip().split("\n")[-60:])
  5309. print("--- web-stack/%s tail (full log: %s) ---" % (name, out_path))
  5310. print(tail)
  5311. print("--- end web-stack/%s tail ---" % name)
  5312. print("shards wall: %.1fs (logs under %s)" % (time.monotonic() - started, log_dir))
  5313. print("ALL SHARDS: %d passed, %d failed%s"
  5314. % (total_pass, total_fail,
  5315. "" if not broken else " BROKEN: " + ", ".join(broken)))
  5316. return 1 if broken or total_fail else 0
  5317. def main():
  5318. if not os.path.exists(APP):
  5319. raise SystemExit("app binary not found at %s (build first)" % APP)
  5320. argv = sys.argv[2:]
  5321. if "--bundle" in argv:
  5322. sys.exit(1 if run_bundle(argv[argv.index("--bundle") + 1]) else 0)
  5323. if os.environ.get("WEBSTACK_SEQUENTIAL"):
  5324. # Debug path: every bundle in-process, one after another.
  5325. for name in BUNDLES_ORDER:
  5326. if run_bundle(name):
  5327. return 1
  5328. return 0
  5329. return run_all_parallel()
  5330. if __name__ == "__main__":
  5331. sys.exit(main())