web_stack_test.py 301 KB

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