web_stack_test.py 371 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163
  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 an agent comment and
  50. marks the saddle offline; a recovered daemon's ask flips offline rows
  51. back to idle
  52. - the deleted layers are gone: /output, /log and /start 404 on the
  53. daemon side, and nothing on the web side calls them
  54. Plan 10 phase 3 (capability awareness + UI):
  55. - assignment capability context: {saddle_tags, fleet_tags} on every
  56. payload, GET /api/saddle/capabilities (per-saddle token) feeding
  57. the daemon's `saddle capabilities` CLI
  58. - subtask callback capabilities: explicit-only attachment validated
  59. against the operator tag set, unknown tags rejected with the valid
  60. list in the error
  61. - task page: status block pinned to the top, blocking sections
  62. newest-first (sealed GET state)
  63. - home dashboard: pinned OPEN blocks as newest-first link-through
  64. cards (no inline answer forms) above the cross-task activity
  65. timeline (last ~50 events newest-first)
  66. - lost-wake-guard regression: a saddle that asks SLOWLY after its
  67. wake (busy winding down) still claims the task — the wake is never
  68. silently dropped, no re-wake storm fires, and the never-asks guard
  69. path (offline + re-wake of the next capable) stays green
  70. Prints PASS/FAIL lines Statum-style; exits non-zero on any failure.
  71. Plan 11 task D+E (UI + notifications), the `push` shard:
  72. - task page: progress feed above the status card, status + description
  73. in a 50/50 grid, edit expander under the history expander, plan
  74. behind an expander, answered blocks behind an expander; queue screen:
  75. New Task expander above the filters; dashboard waiting-on-drafts
  76. block with links to where Enqueue lives (pages shard)
  77. - real Web Push over VAPID: keypair generated at startup into
  78. web-config.json, GET /sw.js service worker with click-through,
  79. subscribe/unsubscribe + per-task Notify me actions, block events and
  80. waiting-on-drafts pushed globally, first start/failure/completion to
  81. opted-in users, best-effort queue with dispatcher-tick retry, 410/404
  82. endpoint pruning — payloads verified protocol-level (RFC 8291
  83. decryption + ES256 JWT signature) because the harness owns the
  84. browser-side keys
  85. Heredoc completion reports (pages shard):
  86. - terminal tasks render tasks.summary (set by done/fail) as a
  87. markdown completion-report card below the status/description grid —
  88. "Completion report" when done, "Failure summary" when failed, no
  89. card when empty; the summary renders through the shipped
  90. stm-markdown renderer (headings/code, no syntax leaks, HTML
  91. escaped) and the dashboard timeline snippets its first line
  92. Speed pass (plan 11, task 0):
  93. - SHARDING: the scenario groups are partitioned into seven independent
  94. bundles (pages, dispatch, subtasks, lineage, allocation, lifecycle,
  95. answers), each running in its own process against its own app
  96. instance, fake daemons and SQLite database. The default invocation
  97. runs all bundles in parallel and aggregates the verdicts and check
  98. counts into one exit code — meson sees a single green/red test.
  99. `--bundle NAME` runs one shard for debugging; WEBSTACK_SEQUENTIAL=1
  100. runs them in-process, one after another.
  101. - Within a bundle, scenario groups SHARE the app+daemon instance and
  102. carry per-group state as database rows (task/session/block
  103. fixtures), never process restarts; the one deliberate restart (the
  104. startup token migration) lives in the answers bundle.
  105. - EVENT-DRIVEN WAITS: wait_for polls at 50ms; the fixed sleeps were
  106. converted either to observable-condition waits (daemon-side
  107. counters, e.g. failed-delivery hits) or to quiet_window() — a
  108. bounded negative-assertion poll that FAILS LOUDLY the moment the
  109. event it guards against happens (a sleep could silently pass).
  110. - ENV KNOBS: SADDLE_DISPATCH_TICK_S=1 (dispatcher cadence; default 5
  111. in production), SADDLE_HTTP_TIMEOUT_S=2, SADDLE_LOST_WAKE_S=2,
  112. SADDLE_STALE_S=3, plus the fake daemon's scripted timings — the
  113. wire-traffic shapes stay realistic, just faster.
  114. """
  115. import json
  116. import os
  117. import re
  118. import shutil
  119. import socket
  120. import sqlite3
  121. import subprocess
  122. import sys
  123. import threading
  124. import time
  125. import urllib.error
  126. import urllib.parse
  127. import urllib.request
  128. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  129. # Web Push protocol verification (plan 11 task E): the test harness
  130. # owns the browser-side keys, so it can do everything the push service
  131. # does — decrypt the RFC 8291 body and verify the ES256 VAPID JWT.
  132. import base64
  133. from cryptography.hazmat.primitives import hashes
  134. from cryptography.hazmat.primitives.asymmetric import ec
  135. from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
  136. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  137. from cryptography.hazmat.primitives.kdf.hkdf import HKDF
  138. from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
  139. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  140. APP = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.join(REPO, "builddir", "clanker-saddle")
  141. # --- speed-pass tuning -----------------------------------------------------
  142. # The fake daemon's scripted timings and the dispatch-tick cadence the
  143. # quiet windows are sized against. All overridable for debugging.
  144. TICK_S = float(os.environ.get("SADDLE_DISPATCH_TICK_S", "1") or 1)
  145. FAKE_WORK_S = float(os.environ.get("WEBSTACK_FAKE_WORK_S", "1.2") or 1.2)
  146. FAKE_FAIL_S = float(os.environ.get("WEBSTACK_FAKE_FAIL_S", "0.5") or 0.5)
  147. FAKE_HEARTBEAT_S = float(os.environ.get("WEBSTACK_FAKE_HEARTBEAT_S", "0.4") or 0.4)
  148. FAKE_TRIGGER_S = float(os.environ.get("WEBSTACK_FAKE_TRIGGER_S", "0.05") or 0.05)
  149. SHARD_TIMEOUT_S = float(os.environ.get("WEBSTACK_SHARD_TIMEOUT_S", "600") or 600)
  150. def quiet_seconds():
  151. """A negative-assertion window spanning several dispatch ticks (the
  152. converted fixed sleeps were 3-7s at the old 5s tick; the bound never
  153. exceeds the old timeout)."""
  154. return min(2 * TICK_S + 0.8, 7.0)
  155. WORK = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  156. DB_PATH = os.path.join(WORK, "web.sqlite")
  157. passes = 0
  158. failures = 0
  159. def check(condition, label):
  160. global passes, failures
  161. if condition:
  162. passes += 1
  163. print("PASS %s" % label)
  164. else:
  165. failures += 1
  166. print("FAIL %s" % label)
  167. def free_port():
  168. with socket.socket() as sock:
  169. sock.bind(("127.0.0.1", 0))
  170. return sock.getsockname()[1]
  171. APP_PORT = free_port()
  172. DAEMON_PORT = free_port()
  173. WEB = "http://127.0.0.1:%d" % APP_PORT
  174. def bundle_env(name):
  175. """Point the module's runtime globals at one shard's scratch dir,
  176. database and ports (each bundle is a process with its own app,
  177. daemons and SQLite file)."""
  178. global WORK, DB_PATH, APP_PORT, DAEMON_PORT, WEB
  179. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  180. WORK = "%s-%s" % (base, name)
  181. DB_PATH = os.path.join(WORK, "web.sqlite")
  182. APP_PORT = free_port()
  183. DAEMON_PORT = free_port()
  184. WEB = "http://127.0.0.1:%d" % APP_PORT
  185. def http(method, url, data=None, headers=None, timeout=30):
  186. body = None
  187. if data is not None:
  188. pairs = []
  189. for k, v in data.items():
  190. for item in (v if isinstance(v, (list, tuple)) else [v]):
  191. pairs.append((k, item))
  192. body = "&".join("%s=%s" % (k, urllib.parse.quote(str(item))) for k, item in pairs).encode()
  193. request = urllib.request.Request(WEB + url if url.startswith("/") else url,
  194. data=body, method=method)
  195. if data is not None:
  196. request.add_header("Content-Type", "application/x-www-form-urlencoded")
  197. for key, value in (headers or {}).items():
  198. request.add_header(key, value)
  199. # Retry dropped/refused connections: the freshly started app can
  200. # close a very early keep-alive connection once while warming up,
  201. # and its first seconds can wobble under load.
  202. for attempt in range(3):
  203. try:
  204. with urllib.request.urlopen(request, timeout=timeout) as response:
  205. return response.status, response.read().decode()
  206. except urllib.error.HTTPError as error:
  207. return error.code, error.read().decode()
  208. except (urllib.error.URLError, OSError):
  209. if attempt >= 2:
  210. raise
  211. time.sleep(0.75)
  212. def directives(uri, auth=None):
  213. headers = {}
  214. if auth:
  215. headers["X-Statum-Slot"] = "key=%s; as_at=%s" % (auth["key"], auth["as_at"])
  216. status, body = http("GET", "/_statum/entrypoint?uri=" + urllib.parse.quote(uri.split("?")[0]),
  217. headers=headers)
  218. if status != 200:
  219. raise SystemExit("entrypoint %s -> HTTP %d: %s" % (uri, status, body[:300]))
  220. return json.loads(body)
  221. def slot_public(auth, uri, type_name):
  222. for directive in directives(uri, auth):
  223. if directive["type"] == "set":
  224. content = directive["snapshot_frame"].get("content")
  225. if not content:
  226. continue
  227. content = json.loads(content)
  228. if content["slot"]["type"] == type_name:
  229. return content["public"]
  230. raise SystemExit("no %s slot in entrypoint state for %s" % (type_name, uri))
  231. def act(auth, action, fields):
  232. headers = {"X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}
  233. if action.get("private"):
  234. headers["X-Statum-Private"] = action["private"]
  235. status, body = http(action.get("method", "POST"), action["uri"], fields, headers)
  236. if status != 200:
  237. raise SystemExit("action %s -> HTTP %d: %s" % (action["uri"], status, body[:300]))
  238. return json.loads(body)
  239. def login(username, password):
  240. frames = directives("/login")
  241. content = json.loads(frames[0]["snapshot_frame"]["content"])
  242. action = content["public"]["login"]
  243. status, body = http(action.get("method", "POST"), action["uri"],
  244. {"username": username, "password": password})
  245. if status != 200:
  246. raise SystemExit("login -> HTTP %d: %s" % (status, body[:300]))
  247. for directive in json.loads(body):
  248. if directive["type"] == "set":
  249. frame = json.loads(directive["snapshot_frame"]["content"])
  250. if frame["slot"]["type"] == "auth":
  251. return {"key": frame["slot"]["key"], "as_at": frame["as_at"]}
  252. raise SystemExit("login response carried no auth slot: " + body[:300])
  253. def wait_for(predicate, timeout=60, what="condition", interval=0.05):
  254. deadline = time.monotonic() + timeout
  255. last = None
  256. while time.monotonic() < deadline:
  257. last = predicate()
  258. if last is not False and last is not None:
  259. return last
  260. time.sleep(interval)
  261. print(" (timeout waiting for %s; last: %s)" % (what, last))
  262. dump_threads()
  263. return None
  264. def quiet_window(seconds, predicate, what):
  265. """A converted fixed sleep: asserts a NEGATIVE condition (nothing may
  266. happen) across a window spanning several dispatch ticks, polling at
  267. 50ms. The moment the condition breaks the window fails loudly
  268. (diagnostics + thread dump) instead of silently passing a sleep."""
  269. deadline = time.monotonic() + seconds
  270. while time.monotonic() < deadline:
  271. value = predicate()
  272. if value is False or value is None:
  273. remaining = deadline - time.monotonic()
  274. print(" (quiet window '%s' broken after %.2fs of %.2fs — the"
  275. " guarded event DID happen)" % (what, seconds - remaining, seconds))
  276. dump_threads()
  277. return False
  278. time.sleep(0.05)
  279. return True
  280. def dump_threads():
  281. """Stacks of suite threads not parked in sleep — pinpoints a wedged
  282. fake lifecycle when a wait times out."""
  283. import traceback
  284. shown = 0
  285. for thread_id, frame in sys._current_frames().items():
  286. stack = "".join(traceback.format_stack(frame)[-4:])
  287. if ("web_stack_test.py" in stack) and ("sleep" not in stack) and shown < 6:
  288. shown += 1
  289. print(" --- thread %s ---\n%s" % (thread_id, stack))
  290. def task_state(auth, task_id):
  291. return slot_public(auth, "/tasks/%d" % task_id, "task")
  292. def wait_task_done(auth, task_id, timeout=90):
  293. return wait_for(lambda: task_state(auth, task_id).get("status") == "done" or False,
  294. timeout=timeout, what="task %d -> done" % task_id)
  295. def task_id_of(title):
  296. conn = db()
  297. try:
  298. return conn.execute("select id from tasks where title = ?", (title,)).fetchone()[0]
  299. finally:
  300. conn.close()
  301. def enqueue_task(auth, task_id):
  302. """The human-only Enqueue action (plan 11): draft -> queued."""
  303. detail = task_state(auth, task_id)
  304. assert detail["status"] == "draft", "task %d not in draft (%s)" % (task_id, detail["status"])
  305. act(auth, detail["enqueue"], {})
  306. return task_state(auth, task_id)["status"]
  307. def create_queued(auth, fields):
  308. """Create via the queue form (lands in draft) and enqueue it — the
  309. standard 'this task should dispatch' fixture of the plan-11 world."""
  310. act(auth, slot_public(auth, "/tasks", "tasks")["create"], fields)
  311. task_id = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  312. if t["title"] == fields["title"]][0])
  313. enqueue_task(auth, task_id)
  314. return task_id
  315. def saddle_api(method, path, token, payload=None):
  316. """Raw call against the saddle ingest API; returns (status, json)."""
  317. request = urllib.request.Request(WEB + path,
  318. data=json.dumps(payload or {}).encode(), method=method)
  319. request.add_header("Content-Type", "application/json")
  320. if token is not None:
  321. request.add_header("Authorization", "Bearer " + token)
  322. try:
  323. with urllib.request.urlopen(request, timeout=15) as response:
  324. return response.status, json.loads(response.read().decode() or "{}")
  325. except urllib.error.HTTPError as error:
  326. body = error.read().decode()
  327. try:
  328. return error.code, json.loads(body)
  329. except ValueError:
  330. return error.code, {"raw": body}
  331. def db():
  332. return sqlite3.connect(DB_PATH)
  333. def http_get_page(auth, uri):
  334. """The compiled page HTML for a statum route (auth via the slot
  335. header), for asserting page-level embeds the slot state cannot
  336. see."""
  337. status, body = http("GET", uri, headers={
  338. "X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])})
  339. if status != 200:
  340. raise SystemExit("GET %s -> HTTP %d" % (uri, status))
  341. return body
  342. def saddle_card(auth, name):
  343. rows = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  344. if s["name"] == name]
  345. return rows[0]
  346. def queued_count():
  347. conn = db()
  348. try:
  349. return conn.execute(
  350. "select count(*) from tasks where status = 'queued'").fetchone()[0]
  351. finally:
  352. conn.close()
  353. def command_rows(session):
  354. conn = db()
  355. try:
  356. return conn.execute(
  357. "select command_text, type from session_commands"
  358. " where session_id = ? order by id", (session,)).fetchall()
  359. finally:
  360. conn.close()
  361. class FakeSaddle:
  362. """In-process saddle daemon implementing the wire contract.
  363. Phase-2 push behaviour: the daemon asks POST /api/saddle/next-task
  364. whenever idle-awake (at registration, on POST /wake, after its task
  365. reaches a terminal state, and when a /status probe observes it
  366. parked idle — throttled), accepts assignments like POST /start used
  367. to, then PUSHES its telemetry home: raw PTY chunks via POST
  368. /api/saddle/chunks and round results with state transitions via
  369. POST /api/saddle/results (working at round start, terminal states
  370. when the scripted lifecycle ends them). /output, /log and /start
  371. are gone (404) like a post-phase-2 daemon; /task-update serves the
  372. cancel/comment/subtask-status kinds; POST /answer receives a
  373. delivered verdict when the round is parked in a block's answer
  374. wait (409 when nothing waits — the real daemon's contract; the
  375. resumed round continues after the response). Every trigger can be
  376. disabled per test for determinism; ask_now() performs a
  377. synchronous manual ask.
  378. """
  379. PROMPT = "bbarrow@fedora:/workspace/task-1$ "
  380. def __init__(self):
  381. self.lock = threading.Lock()
  382. self.start_payloads = [] # captured assignment payloads (/start + next-task 200s)
  383. self.state = "idle"
  384. self.summary = ""
  385. self.state_entered = time.monotonic()
  386. self.fail_next = False # next task drives the task to failed
  387. self.start_counts = {} # task id -> assignment count
  388. self.resumed_pending = False # crash-resume flag on the next /status
  389. self.suspend_on_title = None # this task (by title) parks as suspended
  390. self.output_seq = 100 # daemon-global entry ids for pushed results
  391. self.last_activity_epoch = int(time.time())
  392. self.hang_next = {} # path suffix -> hang count (never responds)
  393. self.abort_failures = 0 # cancel task-updates failing (500) while > 0
  394. self.abort_log = [] # task ids aborted via task-update cancel
  395. self.running_task = 0 # task id the daemon believes it runs
  396. self.running_title = "" # its title (suspend targeting)
  397. self.session_id = None # the web-side run row of the running task
  398. self.hold_state = False # freeze lifecycle + heartbeat pushes
  399. self.ssh_public_key = "" # reported on /status + /register
  400. self.started_mono = time.monotonic()
  401. self.freeze_activity = False # hold last_activity_epoch still
  402. self.silent = False # suppress pushes (staleness tests)
  403. self.dead = False # kill(): no serving AND no calls home
  404. self.status_hits = 0 # GET /status arrivals (probe accounting)
  405. self.comment_log = [] # recorded /task-update comment payloads
  406. self.scripted_corpus = None # chunk batch pushed when a task starts
  407. # --- plan 10 phase 1: ask/wake/register ---
  408. self.token = None # per-saddle token from POST /register
  409. self.register_log = [] # recorded /register bodies
  410. self.wake_log = [] # recorded POST /wake arrivals
  411. self.asks = [] # [{"status": int, "payload": dict|None}]
  412. self.ask_on_register = True
  413. self.ask_on_wake = True
  414. self.ask_on_terminal = True
  415. self.ask_on_idle_status = True
  416. self.ask_delay = 0.0 # seconds; a slow daemon delays its wake-triggered ask
  417. self.serve_register = True # False: 404 /register (pre-flip daemon)
  418. self.last_ask_trigger = 0.0
  419. self.port = None
  420. self.ask_threads = [] # scheduled ask-trigger threads (settle_asks joins them)
  421. # --- answer delivery (the parked-session resume) ---
  422. self.pending_block = None # the block payload this daemon waits on (state blocked)
  423. self.answer_log = [] # recorded POST /answer bodies
  424. self.answer_push_delay = 0.2 # the resumed round's first push, after the response
  425. # --- plan 12: goal-agent scripting ---
  426. self.goal_script = [] # behaviours consumed per goal-run assignment
  427. self.goal_behaviour = None # the current round's popped behaviour
  428. self.goal_assignments = [] # captured goal-run assignment payloads
  429. def set_state(self, state, summary=None):
  430. """Advances the scripted lifecycle."""
  431. self.state = state
  432. if summary is not None:
  433. self.summary = summary
  434. self.state_entered = time.monotonic()
  435. def touch_activity(self):
  436. if not self.freeze_activity:
  437. self.last_activity_epoch = int(time.time())
  438. def queue_output(self, entry_type, command, output):
  439. """Pushes a typed entry as a round-results push (the daemon's
  440. entry log riding the results channel)."""
  441. with self.lock:
  442. entry = {
  443. "id": self.output_seq,
  444. "command": command,
  445. "output": output,
  446. "exit_code": 1,
  447. "type": entry_type,
  448. "timestamp": "2026-09-06T00:00:00Z",
  449. }
  450. self.output_seq += 1
  451. self.push_results(self.state if self.state in ("working",) else "working",
  452. entries=[entry])
  453. # --- plan 10 phase 2: the push channels ---
  454. def push_chunks(self, chunks):
  455. """Pushes raw PTY chunks home: elements are texts (assigned
  456. fresh seqs) or {seq, text} dicts (a redelivery or explicit
  457. corpus). Pushes are suppressed while silent/hold_state (the
  458. staleness tests' silent runner)."""
  459. if self.dead or self.silent or self.token is None or self.session_id is None:
  460. return
  461. batch = []
  462. with self.lock:
  463. for chunk in chunks:
  464. if isinstance(chunk, dict):
  465. batch.append({"seq": int(chunk["seq"]), "text": chunk["text"]})
  466. else:
  467. batch.append({"seq": self.next_push_seq(), "text": chunk})
  468. try:
  469. saddle_api("POST", "/api/saddle/chunks", self.token,
  470. {"session_id": self.session_id, "chunks": batch})
  471. except (OSError, ValueError):
  472. pass # app restarting / shutting down mid-test
  473. def next_push_seq(self):
  474. # The daemon-side chunk counter for ad-hoc pushes.
  475. self._push_seq = getattr(self, "_push_seq", 0) + 1
  476. return self._push_seq
  477. def push_results(self, state, entries=None, block=None, summary=None, session_id=None):
  478. """Pushes one round-results payload home (state transition plus
  479. its entries). Returns the HTTP status when it went out, None
  480. when suppressed."""
  481. if self.dead or self.silent:
  482. return None
  483. if self.token is None:
  484. return None
  485. target = session_id if session_id is not None else self.session_id
  486. if target is None:
  487. return None
  488. payload = {"session_id": target, "state": state}
  489. if entries is not None:
  490. payload["entries"] = entries
  491. if block is not None:
  492. payload["block"] = block
  493. if state == "blocked":
  494. # The daemon parks its round on this block's answer wait
  495. # (the real daemon's wait_for_answer).
  496. self.pending_block = dict(block)
  497. if summary is not None:
  498. payload["summary"] = summary
  499. try:
  500. status, _ = saddle_api("POST", "/api/saddle/results", self.token, payload)
  501. if status != 200:
  502. print(" [fake %s] push %s -> HTTP %s (task=%s)"
  503. % (self.port, state, status, self.running_task))
  504. return status
  505. except (OSError, ValueError) as error:
  506. print(" [fake %s] push %s failed: %r (task=%s)"
  507. % (self.port, state, error, self.running_task))
  508. return None
  509. # --- plan 10 phase 1: the ask path ---
  510. def ask_now(self):
  511. """Synchronously asks the web for work (a phase-1 daemon's idle
  512. ask). A 200 assignment is accepted exactly like POST /start;
  513. returns (status, payload|None)."""
  514. token = self.token
  515. if token is None:
  516. raise SystemExit("fake daemon asked before receiving its token")
  517. status, payload = saddle_api("POST", "/api/saddle/next-task", token)
  518. with self.lock:
  519. self.asks.append({"status": status, "payload": payload})
  520. if status == 200:
  521. self.accept_assignment(payload)
  522. return status, payload
  523. def _trigger_ask(self, reason):
  524. """Schedules a delayed ask (the daemon woke / went idle-awake).
  525. ask_delay models a SLOW asker — a daemon still winding down its
  526. round when the wake lands: it honours the wake, but its ask
  527. arrives late (still inside the web's lost-wake guard window)."""
  528. def run():
  529. if self.state in ("working", "failing"):
  530. return # a running daemon does not ask
  531. if self.ask_delay > 0:
  532. time.sleep(self.ask_delay)
  533. for attempt in range(3):
  534. try:
  535. status, _ = self.ask_now()
  536. if status in (200, 204):
  537. return
  538. print(" (ask %s -> HTTP %s, attempt %d)" % (reason, status, attempt + 1))
  539. except Exception as error: # app restarting / blips: retry
  540. print(" (ask %s failed: %r, attempt %d)" % (reason, error, attempt + 1))
  541. time.sleep(1.0)
  542. def starter():
  543. time.sleep(FAKE_TRIGGER_S)
  544. run()
  545. thread = threading.Thread(target=starter, daemon=True)
  546. with self.lock:
  547. self.ask_threads.append(thread)
  548. thread.start()
  549. def settle_asks(self, timeout=15):
  550. """Joins every ask-trigger thread scheduled so far — the
  551. event-driven replacement for the fixed sleeps that waited for
  552. in-flight asks to land after triggers were frozen."""
  553. with self.lock:
  554. threads = [t for t in self.ask_threads if t.is_alive()]
  555. deadline = time.monotonic() + timeout
  556. for thread in threads:
  557. thread.join(timeout=max(0.1, deadline - time.monotonic()))
  558. with self.lock:
  559. self.ask_threads = [t for t in self.ask_threads if t.is_alive()]
  560. return all(not thread.is_alive() for thread in threads)
  561. def maybe_trigger_ask(self, reason, throttle=False):
  562. """Schedules an idle-awake ask. Protocol events (wake, abort,
  563. round end, park) ask singularly and immediately; only the
  564. /status-observation path throttles (a burst of probes must not
  565. hammer the ask endpoint)."""
  566. now = time.monotonic()
  567. if throttle and now - self.last_ask_trigger < 1.0:
  568. return
  569. self.last_ask_trigger = now
  570. self._trigger_ask(reason)
  571. def accept_assignment(self, payload):
  572. """A 200 next-task assignment: adopted exactly like POST /start."""
  573. self.start_payloads.append(payload)
  574. task = payload.get("task") or {}
  575. task_id = task.get("id")
  576. self.running_task = int(task_id or 0)
  577. self.running_title = task.get("title") or ""
  578. self.session_id = payload.get("session_id")
  579. # The assignment's answers resolve any block this daemon was
  580. # parked on (resume-carries-answer).
  581. self.pending_block = None
  582. count = self.start_counts.get(task_id, 0) + 1
  583. self.start_counts[task_id] = count
  584. if count > 1:
  585. # Crash-resume contract: re-pushing a task whose
  586. # workspace still exists restores it; the first
  587. # /status after the restore reports "resumed": true.
  588. self.resumed_pending = True
  589. # Plan 12: a goal-run assignment plays its scripted behaviour
  590. # instead of the plain done push (plan submission, parking,
  591. # question, completion, failure — consumed one per round).
  592. self.goal_behaviour = None
  593. if payload.get("kind") == "goal_run":
  594. self.goal_assignments.append(payload)
  595. self.goal_behaviour = self.goal_script.pop(0) if self.goal_script else ("suspend",)
  596. self.set_state("failing" if self.fail_next else "working")
  597. self.fail_next = False
  598. # The round's opening telemetry: the flushed-so-far raw PTY
  599. # batch plus the working state push (>= 2 flushes per round
  600. # and the 10s timer are the real daemon's contract; the fake
  601. # pushes its batch up front and heartbeats while working).
  602. if self.scripted_corpus is not None:
  603. self.push_chunks([dict(chunk) for chunk in self.scripted_corpus])
  604. else:
  605. self.push_chunks([self.PROMPT, "echo hello\r\n", "hello\r\n"])
  606. self.push_results("working")
  607. class Handler(BaseHTTPRequestHandler):
  608. daemon = None # set on the class before serving
  609. protocol_version = "HTTP/1.1"
  610. def log_message(self, fmt, *args):
  611. pass
  612. def maybe_hang(self, path):
  613. """True when this request should hang forever (never respond),
  614. consuming one unit of the path's hang budget."""
  615. for suffix, count in list(self.daemon.hang_next.items()):
  616. if count > 0 and path.startswith(suffix):
  617. self.daemon.hang_next[suffix] = count - 1
  618. return True
  619. return False
  620. def _send(self, status, obj):
  621. body = json.dumps(obj).encode()
  622. self.send_response(status)
  623. self.send_header("Content-Type", "application/json")
  624. self.send_header("Content-Length", str(len(body)))
  625. self.end_headers()
  626. self.wfile.write(body)
  627. def do_POST(self):
  628. if self.maybe_hang(self.path):
  629. time.sleep(600)
  630. return
  631. self.daemon.touch_activity()
  632. length = int(self.headers.get("Content-Length") or 0)
  633. raw = self.rfile.read(length).decode() if length else "{}"
  634. if self.path == "/register":
  635. # Plan 10: the web delivers the per-saddle token + its
  636. # own base URL; the daemon persists the token for its
  637. # calls home and reports its ssh key + version.
  638. if not self.daemon.serve_register:
  639. self._send(404, {"error": "no such route"})
  640. return
  641. try:
  642. payload = json.loads(raw)
  643. except ValueError:
  644. payload = {"raw": raw}
  645. self.daemon.register_log.append(payload)
  646. if payload.get("saddle_token"):
  647. self.daemon.token = payload["saddle_token"]
  648. self._send(200, {"ok": True,
  649. "ssh_public_key": self.daemon.ssh_public_key,
  650. "version": "0.1-fake"})
  651. if self.daemon.ask_on_register:
  652. self.daemon.maybe_trigger_ask("register")
  653. return
  654. if self.path == "/wake":
  655. # Plan 10: a capable task is ready; a sleeping daemon
  656. # asks for work (immediately — a wake is a direct
  657. # command, never throttled).
  658. self.daemon.wake_log.append(time.monotonic())
  659. self._send(200, {"ok": True})
  660. if self.daemon.ask_on_wake:
  661. self.daemon.maybe_trigger_ask("wake")
  662. return
  663. if self.path == "/answer":
  664. # Plan 11 (daemon Task A): parks FREE the daemon, so no
  665. # block ever waits in-process — the verdict travels in
  666. # the resuming allocation's resume_notice. Always 409,
  667. # exactly like the real daemon's contract.
  668. try:
  669. payload = json.loads(raw)
  670. except ValueError:
  671. self._send(400, {"error": "bad json"})
  672. return
  673. self.daemon.answer_log.append({
  674. "refused": True,
  675. "answer": payload.get("answer", "")})
  676. self._send(409, {"error": "no block is waiting for an answer — parks resume via allocation"})
  677. return
  678. if self.path == "/task-update":
  679. # Plan 10: cancel (abort machinery) and comment
  680. # (injected turn) — delivered directly to a RUNNING
  681. # daemon, no auth.
  682. try:
  683. payload = json.loads(raw)
  684. except ValueError:
  685. self._send(400, {"error": "bad json"})
  686. return
  687. kind = payload.get("kind")
  688. if kind == "cancel":
  689. if self.daemon.abort_failures > 0:
  690. self.daemon.abort_failures -= 1
  691. self._send(500, {"error": "cancel failed (simulated)"})
  692. return
  693. aborted = self.daemon.running_task
  694. self.daemon.set_state("idle")
  695. self.daemon.summary = ""
  696. self.daemon.running_task = 0
  697. self.daemon.session_id = None
  698. self.daemon.abort_log.append(aborted)
  699. self._send(200, {"ok": True, "aborted_task_id": aborted})
  700. # An aborted daemon returns to its idle loop: it asks.
  701. self.daemon.maybe_trigger_ask("aborted")
  702. elif kind == "comment":
  703. self.daemon.comment_log.append(payload)
  704. self._send(200, {"ok": True})
  705. else:
  706. self._send(400, {"error": "unknown task-update kind"})
  707. return
  708. self._send(404, {"error": "no such route"})
  709. self.close_connection = True
  710. def do_GET(self):
  711. if self.maybe_hang(self.path):
  712. time.sleep(600)
  713. return
  714. if self.path != "/status":
  715. # /status itself is not daemon activity: the liveness
  716. # signal must reflect loop rounds / command completions.
  717. self.daemon.touch_activity()
  718. if self.path == "/status":
  719. self.daemon.status_hits += 1
  720. response = {"state": self.daemon.state, "summary": self.daemon.summary,
  721. "uptime_seconds": int(time.monotonic() - self.daemon.started_mono),
  722. "last_activity_epoch": self.daemon.last_activity_epoch,
  723. "ssh_public_key": self.daemon.ssh_public_key}
  724. if getattr(self.daemon, "status_extra", None):
  725. response.update(self.daemon.status_extra)
  726. if self.daemon.resumed_pending:
  727. response["resumed"] = True
  728. self.daemon.resumed_pending = False
  729. # A parked/terminal daemon is idle-awake: a phase-1
  730. # daemon asks (and sleeps on 204). Throttled so status
  731. # poll bursts do not hammer the ask endpoint.
  732. if self.daemon.ask_on_idle_status and self.daemon.state in (
  733. "idle", "done", "failed", "suspended"):
  734. self.daemon.maybe_trigger_ask("idle-status", throttle=True)
  735. self._send(200, response)
  736. else:
  737. self._send(404, {"error": "no such route"})
  738. self.close_connection = True
  739. def run_lifecycle(self):
  740. """Applies the scripted lifecycle on a timer (like a real daemon
  741. whose task ends on its own): working heartbeats chunks (the
  742. flush timer's stand-in, keeping the staleness clock fed), works
  743. for FAKE_WORK_S, then pushes done/suspended; failing pushes
  744. failed after FAKE_FAIL_S — and a task END makes the idle-awake
  745. daemon ask again."""
  746. while True:
  747. time.sleep(0.1)
  748. if self.hold_state or self.silent:
  749. # hold_state freezes the script; silent models a daemon
  750. # mid-round with nothing to flush — its round has not
  751. # ended, so no terminal push fires while quiet.
  752. continue
  753. if self.state == "failing":
  754. if time.monotonic() - self.state_entered >= FAKE_FAIL_S:
  755. self.set_state("failed", "bash -n rejected the script (simulated)")
  756. self.push_results("failed",
  757. summary="bash -n rejected the script (simulated)")
  758. if self.ask_on_terminal:
  759. self.maybe_trigger_ask("terminal")
  760. elif self.state == "working":
  761. if time.monotonic() - self.state_entered >= FAKE_WORK_S:
  762. if self.goal_behaviour is not None:
  763. # A goal-agent round: play the scripted
  764. # behaviour (the results channel carries the
  765. # goal-context verbs).
  766. behaviour, self.goal_behaviour = self.goal_behaviour, None
  767. kind = behaviour[0]
  768. if kind == "plan":
  769. self.set_state("blocked")
  770. self.push_results("blocked", block={
  771. "type": "plan",
  772. "question": "Plan submitted for review",
  773. "body": behaviour[1]})
  774. if self.ask_on_idle_status:
  775. self.maybe_trigger_ask("parked")
  776. elif kind == "question":
  777. self.set_state("blocked")
  778. self.push_results("blocked", block={
  779. "type": "question",
  780. "question": behaviour[1],
  781. "options": list(behaviour[2])
  782. if len(behaviour) > 2 else None})
  783. if self.ask_on_idle_status:
  784. self.maybe_trigger_ask("parked")
  785. elif kind == "suspend":
  786. self.set_state("suspended")
  787. self.push_results("suspended")
  788. if self.ask_on_idle_status:
  789. self.maybe_trigger_ask("parked")
  790. elif kind == "fail":
  791. self.set_state("failed", behaviour[1])
  792. self.push_results("failed", summary=behaviour[1])
  793. if self.ask_on_terminal:
  794. self.maybe_trigger_ask("terminal")
  795. else: # "done": the completion report
  796. self.set_state("done", behaviour[1])
  797. self.push_results("done", summary=behaviour[1])
  798. if self.ask_on_terminal:
  799. self.maybe_trigger_ask("terminal")
  800. elif self.suspend_on_title and self.suspend_on_title == self.running_title:
  801. # `saddle suspend`: park until a fresh assignment
  802. # resumes the workspace (title-targeted one-shot,
  803. # so an interleaved dispatch cannot eat the flag).
  804. self.set_state("suspended")
  805. self.suspend_on_title = None
  806. self.push_results("suspended")
  807. # A parked daemon is idle-awake: it asks (and
  808. # sleeps on 204) so a later wake can reach it.
  809. if self.ask_on_idle_status:
  810. self.maybe_trigger_ask("parked")
  811. else:
  812. self.set_state("done", "fake daemon finished")
  813. self.push_results("done", summary="fake daemon finished")
  814. if self.ask_on_terminal:
  815. self.maybe_trigger_ask("terminal")
  816. elif time.monotonic() - getattr(self, "last_heartbeat", 0) >= FAKE_HEARTBEAT_S:
  817. # The flush timer: output keeps flowing, so chunks
  818. # keep arriving (the staleness window never opens on
  819. # a healthy runner).
  820. self.last_heartbeat = time.monotonic()
  821. self.push_chunks(["working-heartbeat\r\n"])
  822. def serve(self, port=None):
  823. """Binds the daemon's HTTP server. A requested port that is
  824. already taken (free_port() hands out recyclable ports — two
  825. calls can collide) falls back to an OS-assigned one instead of
  826. silently dying and impersonating whatever owns that port."""
  827. if port is None:
  828. port = DAEMON_PORT
  829. handler = type("BoundHandler", (FakeSaddle.Handler,), {"daemon": self})
  830. self.server = None
  831. try:
  832. self.server = ThreadingHTTPServer(("127.0.0.1", port), handler)
  833. except OSError:
  834. print("(fake daemon: port %d taken, falling back)" % port)
  835. self.server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
  836. self.port = self.server.server_address[1]
  837. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  838. threading.Thread(target=self.run_lifecycle, daemon=True).start()
  839. return self.server
  840. def kill(self):
  841. """The daemon dies: it stops listening (connections refused) AND
  842. stops calling home — no pushes, no asks (a dead process has no
  843. outbound anything; in-flight handler threads may linger but the
  844. wire contract's traffic is one-directional now)."""
  845. self.dead = True
  846. if getattr(self, "server", None) is not None:
  847. self.server.shutdown()
  848. self.server.server_close()
  849. self.server = None
  850. def start_app():
  851. config = json.load(open(os.path.join(REPO, "web-config.json")))
  852. config["saddle_callback_base_url"] = WEB
  853. with open(os.path.join(WORK, "web-config.json"), "w") as handle:
  854. json.dump(config, handle)
  855. env = dict(os.environ)
  856. env.update({
  857. "SPRY_DB_PATH": DB_PATH,
  858. "SPRY_SEED_ADMIN_USERNAME": "admin",
  859. "SPRY_SEED_ADMIN_PASSWORD": "adminpass123",
  860. "SADDLE_LLM_BASE_URL": "http://127.0.0.1:%d" % DAEMON_PORT,
  861. "SADDLE_PROJECTS_ROOT": os.path.join(WORK, "workspace"),
  862. "SADDLE_HTTP_TIMEOUT_S": "2",
  863. "SADDLE_LOST_WAKE_S": "2",
  864. "SADDLE_STALE_S": "3",
  865. "SADDLE_DISPATCH_TICK_S": "1",
  866. # Plan 12: the goal-agent resume coalescing window shrinks to
  867. # one second so the event-driven resume tests settle quickly.
  868. "SADDLE_GOAL_RESUME_S": os.environ.get("SADDLE_GOAL_RESUME_S", "1"),
  869. # Never inherit a caller-poisoned LD_LIBRARY_PATH (e.g. one that
  870. # resolves the ancient /lib64 copies): empty makes the loader use
  871. # the binary's RUNPATH, which is the dev stack it was built
  872. # against.
  873. "LD_LIBRARY_PATH": "",
  874. })
  875. log_previous = os.path.join(WORK, "app.log.1")
  876. if os.path.exists(os.path.join(WORK, "app.log")):
  877. shutil.move(os.path.join(WORK, "app.log"), log_previous)
  878. log = open(os.path.join(WORK, "app.log"), "w")
  879. command = [APP, str(APP_PORT)]
  880. if os.environ.get("WEBSTACK_GDB"):
  881. # Debugging aid: run the app under gdb; a crash backtrace lands in
  882. # app.log. WEBSTACK_GDB=1 meson test ... to enable.
  883. command = ["gdb", "-batch", "-quiet",
  884. "-ex", "handle SIGPIPE nostop noprint pass",
  885. "-ex", "run", "-ex", "bt", "--args", APP, str(APP_PORT)]
  886. process = subprocess.Popen(command, cwd=WORK, env=env,
  887. stdout=log, stderr=subprocess.STDOUT)
  888. # The ready probe must require OUR process alive: a free_port()
  889. # TOCTOU can hand this port to another shard's app — ours then dies
  890. # at bind (MHD error()) while the probe happily answers from the
  891. # intruder (same admin seed), and every check would silently drive
  892. # the WRONG app. poll() != None with a serving port is exactly that
  893. # shape: take the exit branch, the start_bundle retry re-ports.
  894. outcome = wait_for(lambda: (app_ready() and process.poll() is None and "ready")
  895. or (process.poll() is not None and "app-exited-%d" % process.poll())
  896. or False, timeout=30, what="app ready")
  897. if outcome is None:
  898. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  899. if str(outcome).startswith("app-exited-"):
  900. raise SystemExit("app exited during startup (%s); see %s/app.log"
  901. % outcome, WORK)
  902. return process
  903. def app_ready():
  904. try:
  905. status, _ = http("GET", "/login", timeout=3)
  906. return status == 200
  907. except (urllib.error.URLError, OSError):
  908. return False
  909. def dump_app_stacks(pid):
  910. """Best-effort thread backtrace of the (possibly wedged) app."""
  911. try:
  912. fds = os.listdir("/proc/%d/fd" % pid)
  913. print("(app open fds at dump: %d)" % len(fds))
  914. kinds = {}
  915. for fd in fds[:1200]:
  916. try:
  917. target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
  918. except OSError:
  919. continue
  920. key = target.split(":", 1)[0] if ":" in target else target
  921. kinds[key] = kinds.get(key, 0) + 1
  922. print("(fd kinds: %s)" % sorted(kinds.items(), key=lambda kv: -kv[1])[:6])
  923. except OSError:
  924. pass
  925. for command in (["eu-stack", "-p", str(pid)],
  926. ["gdb", "-batch", "-quiet", "-p", str(pid),
  927. "-ex", "thread apply all bt"]):
  928. try:
  929. out = subprocess.run(command, capture_output=True, timeout=60)
  930. text = out.stdout.decode(errors="replace") + out.stderr.decode(errors="replace")
  931. if text.strip():
  932. print("(app stacks via %s)\n%s" % (command[0], text[:12000]))
  933. return
  934. except (OSError, subprocess.SubprocessError):
  935. continue
  936. # =============================================================================
  937. # Fake push service + Web Push protocol helpers (plan 11 task E)
  938. # =============================================================================
  939. def b64url(raw):
  940. return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
  941. def b64url_dec(text):
  942. return base64.urlsafe_b64decode(text + "=" * ((4 - len(text) % 4) % 4))
  943. class FakePushService:
  944. """In-process Web Push endpoint server: every subscription the tests
  945. register points at a path here (a distinct "browser endpoint").
  946. Responses are scriptable per path — a fixed status (the 410-prune
  947. fixture) or N transient 500s (the retry-next-tick fixture)."""
  948. def __init__(self):
  949. self.requests = [] # [{"path", "headers", "body", "at"}]
  950. self.fail_next = {} # path -> remaining 500s
  951. self.status_for = {} # path -> fixed status
  952. self.lock = threading.Lock()
  953. self.port = None
  954. self.server = None
  955. def serve(self):
  956. service = self
  957. class Handler(BaseHTTPRequestHandler):
  958. protocol_version = "HTTP/1.1"
  959. def log_message(self, fmt, *args):
  960. pass
  961. def do_POST(self):
  962. length = int(self.headers.get("Content-Length") or 0)
  963. body = self.rfile.read(length)
  964. status = 201
  965. if self.path in service.status_for:
  966. status = service.status_for[self.path]
  967. elif service.fail_next.get(self.path, 0) > 0:
  968. service.fail_next[self.path] -= 1
  969. status = 500
  970. with service.lock:
  971. service.requests.append({
  972. "path": self.path,
  973. "headers": {key.lower(): value
  974. for key, value in self.headers.items()},
  975. "body": body,
  976. "at": time.monotonic(),
  977. })
  978. payload = b"{}"
  979. self.send_response(status)
  980. self.send_header("Content-Type", "application/json")
  981. self.send_header("Content-Length", str(len(payload)))
  982. self.end_headers()
  983. self.wfile.write(payload)
  984. self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
  985. self.port = self.server.server_address[1]
  986. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  987. return self.server
  988. def url(self, path):
  989. return "http://127.0.0.1:%d%s" % (self.port, path)
  990. def hits(self, prefix):
  991. with self.lock:
  992. return [request for request in self.requests
  993. if request["path"].startswith(prefix)]
  994. def decrypt_webpush(request, client_private_key, client_public, auth_secret):
  995. """RFC 8291 decryption of one captured push: returns
  996. (record_size, payload dict) — the payload builder's exact output."""
  997. body = request["body"]
  998. salt = body[:16]
  999. record_size = int.from_bytes(body[16:20], "big")
  1000. key_id_len = body[20]
  1001. eph_public = body[21:21 + key_id_len]
  1002. ciphertext = body[21 + key_id_len:]
  1003. eph_point = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(),
  1004. eph_public)
  1005. shared = client_private_key.exchange(ec.ECDH(), eph_point)
  1006. info = b"WebPush: info\x00" + eph_public + client_public
  1007. cek = HKDF(algorithm=hashes.SHA256(), length=16, salt=salt,
  1008. info=info).derive(shared + auth_secret)
  1009. nonce = HKDF(algorithm=hashes.SHA256(), length=12, salt=salt,
  1010. info=info).derive(shared + auth_secret)
  1011. plaintext = AESGCM(cek).decrypt(nonce, ciphertext, None)
  1012. return record_size, json.loads(plaintext[:-1]) # strip the 0x02 delimiter
  1013. def verify_vapid(request, vapid_public, vapid_private):
  1014. """Verifies the ES256 VAPID JWT on one captured push; returns its
  1015. claims dict (aud/exp/sub) — raises on a bad signature."""
  1016. header = request["headers"].get("authorization", "")
  1017. assert header.startswith("vapid t="), "no vapid authorization header"
  1018. token_part = header[len("vapid t="):].split(",")[0]
  1019. sent_key = header.split("k=")[1]
  1020. head_b64, claims_b64, sig_b64 = token_part.split(".")
  1021. signature = b64url_dec(sig_b64)
  1022. key = ec.derive_private_key(
  1023. int.from_bytes(b64url_dec(vapid_private), "big"), ec.SECP256R1())
  1024. key.public_key().verify(
  1025. encode_dss_signature(int.from_bytes(signature[:32], "big"),
  1026. int.from_bytes(signature[32:], "big")),
  1027. (head_b64 + "." + claims_b64).encode(),
  1028. ec.ECDSA(hashes.SHA256()))
  1029. claims = json.loads(b64url_dec(claims_b64))
  1030. assert sent_key == vapid_public, "the k= key is not the app's VAPID key"
  1031. return claims
  1032. def action_notify(result):
  1033. """The message of the first notify directive an action returned."""
  1034. for directive in result:
  1035. if directive.get("type") == "notify":
  1036. return directive.get("message", "")
  1037. return None
  1038. # =============================================================================
  1039. # Shard orchestration
  1040. # =============================================================================
  1041. class Ctx:
  1042. """Per-bundle shared fixtures: the app process, the admin auth slot
  1043. and the primary fake saddle (registered + token delivered)."""
  1044. def start_bundle(name):
  1045. """Boots one shard's environment: scratch dir, database, ports, the
  1046. primary fake daemon and the app, then the shared fixtures every
  1047. bundle builds on (the demo project + the registered fake saddle).
  1048. Scenario groups inside the bundle share this app+daemon instance
  1049. and sequence their state as DB rows, never process restarts."""
  1050. global APP_PORT, WEB, DAEMON_PORT
  1051. bundle_env(name)
  1052. fake = FakeSaddle()
  1053. fake.serve()
  1054. DAEMON_PORT = fake.port # the actually-bound port (fallback-safe)
  1055. # A rare framework-level crash (stack corruption in Statum slot
  1056. # signing during the FIRST login — shared-library codegen bug, moved
  1057. # twice already) kills the app before any test runs; a clean restart
  1058. # (with fresh ports) sidesteps it. Only tolerated while nothing has
  1059. # been checked yet.
  1060. auth = None
  1061. app = None
  1062. for attempt in range(3):
  1063. APP_PORT = free_port()
  1064. WEB = "http://127.0.0.1:%d" % APP_PORT
  1065. if os.path.exists(WORK):
  1066. shutil.rmtree(WORK)
  1067. os.makedirs(os.path.join(WORK, "workspace"))
  1068. try:
  1069. app = start_app()
  1070. auth = login("admin", "adminpass123")
  1071. break
  1072. except (SystemExit, OSError, urllib.error.URLError):
  1073. if passes > 0:
  1074. raise
  1075. if app is not None and app.poll() is None:
  1076. app.terminate()
  1077. try:
  1078. app.wait(timeout=5)
  1079. except subprocess.TimeoutExpired:
  1080. app.kill()
  1081. app = None
  1082. print("(app died before login; restarting cleanly, attempt %d)" % (attempt + 1))
  1083. if app is None or auth is None:
  1084. raise SystemExit("app never came up; see %s/app.log" % WORK)
  1085. state = slot_public(auth, "/projects", "projects")
  1086. act(auth, state["create"], {
  1087. "name": "demo",
  1088. "git_url": "https://example.com/demo.git",
  1089. "default_branch": "main",
  1090. })
  1091. saddles_state = slot_public(auth, "/saddles", "saddles")
  1092. act(auth, saddles_state["register"], {"name": "fake-saddle",
  1093. "host": "127.0.0.1:%d" % fake.port})
  1094. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1095. if s["name"] == "fake-saddle"]
  1096. if wait_for(lambda: len(fake.register_log) > 0 or False,
  1097. timeout=15, what="/register delivery") is None:
  1098. raise SystemExit("fake saddle never received /register")
  1099. ctx = Ctx()
  1100. ctx.name = name
  1101. ctx.app = app
  1102. ctx.auth = auth
  1103. ctx.fake = fake
  1104. ctx.fake_id = int(registered[0]["id"])
  1105. ctx.fake_token = registered[0]["token"]
  1106. return ctx
  1107. # =============================================================================
  1108. # Bundle: pages — block presentation, diff URLs, computed display state,
  1109. # terminal rendering (rejected entries, ANSI SGR), task-page layout and
  1110. # the /poll verdict channel. Fixture-driven: tasks and sessions are
  1111. # inserted as rows; only the rejected-ride scenario dispatches.
  1112. # =============================================================================
  1113. def bundle_pages(ctx):
  1114. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  1115. app = ctx.app
  1116. check(True, "login yields an auth slot")
  1117. print("== plan blocks: every task's saddle plan parks for acceptance ==")
  1118. conn = db()
  1119. conn.execute("insert into tasks (project_id, title, status, priority,"
  1120. " created_at)"
  1121. " values (1, 'Plan review task', 'working', 5,"
  1122. " strftime('%s','now'))")
  1123. plan_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1124. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  1125. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  1126. (plan_task, fake_id))
  1127. conn.commit()
  1128. session_id = conn.execute("select max(id) from sessions").fetchone()[0]
  1129. conn.close()
  1130. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1131. {"type": "block", "session_id": session_id, "data": {
  1132. "question": "Plan submitted for review",
  1133. "type": "plan",
  1134. "body": "# The plan\n\n1. Do it"}})
  1135. check(status == 200 and body.get("block_id"), "plan block raised")
  1136. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1137. {"type": "block", "session_id": session_id, "data": {
  1138. "question": "Which database?",
  1139. "type": "question",
  1140. "options": ["SQLite", "Postgres"],
  1141. "body": "# Storage choice"}})
  1142. check(status == 200, "question block raised")
  1143. detail = task_state(auth, plan_task)
  1144. blocks = {b["block_type"]: b for b in detail["blocks"]}
  1145. check(blocks["plan"].get("is_plan_review") is True,
  1146. "plan block flagged as the plan review")
  1147. check(blocks["plan"].get("show_body") is False,
  1148. "pending plan review hides the duplicate body preview")
  1149. check(blocks["question"].get("show_body") is True,
  1150. "question block keeps its body preview")
  1151. # Accept stores the stable approval wording as the answer (it
  1152. # becomes the resume notice the daemon reads; task-level plans are
  1153. # gone — the goal owns the approved markdown).
  1154. act(auth, blocks["plan"]["answer_action"],
  1155. {"answer": "Plan approved. Proceed with implementation."})
  1156. detail = task_state(auth, plan_task)
  1157. plan_block = [b for b in detail["blocks"] if b["block_type"] == "plan"][0]
  1158. check(plan_block.get("show_body") is True,
  1159. "answered plan review shows the body again (review section gone)")
  1160. check(plan_block.get("answered") is True
  1161. and plan_block.get("answer") == "Plan approved. Proceed with implementation.",
  1162. "accept stores the stable approval wording (the resume notice)")
  1163. print("== B1: highlight-to-comment quote dialog ==")
  1164. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  1165. check(status == 200 and "quote-comment-dialog" in page and "quote-text" in page,
  1166. "task page carries the quote-comment dialog the popover opens")
  1167. check('name="quote"' in page and 'name="return_to"' in page,
  1168. "quote dialog posts the quote and return-to fields")
  1169. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1170. check(status == 200 and "quote-comment-dialog" in page,
  1171. "terminal page keeps its quote dialog")
  1172. print("== B3: review section hides the duplicate body ==")
  1173. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1174. {"type": "block", "session_id": session_id, "data": {
  1175. "question": "Review the diff",
  1176. "type": "review",
  1177. "body": "# The change\n\nReworks the flange module."}})
  1178. check(status == 200 and body.get("block_id"), "review block raised")
  1179. detail = task_state(auth, plan_task)
  1180. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  1181. check(detail.get("review_pending") is True,
  1182. "review section shows while the review is unanswered")
  1183. check(review_block.get("show_body") is False,
  1184. "pending review block hides its duplicate body preview")
  1185. check(review_block.get("body", "").startswith("# The change"),
  1186. "review body itself still arrives in state (B2 counterpart)")
  1187. act(auth, review_block["answer_action"],
  1188. {"answer": "Review approved. Continue with the task."})
  1189. detail = task_state(auth, plan_task)
  1190. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  1191. check(review_block.get("show_body") is True,
  1192. "answered review shows the body again (banner gone)")
  1193. print("== B2: question block body above options ==")
  1194. # Contract side (A2 will restore bodies end-to-end): a question
  1195. # block raised with a heredoc body carries it; the body preview
  1196. # rides above the options (template order) and survives answering
  1197. # alongside the selected answer.
  1198. detail = task_state(auth, plan_task)
  1199. question = [b for b in detail["blocks"] if b["block_type"] == "question"][0]
  1200. check(question.get("body") == "# Storage choice"
  1201. and question.get("show_body") is True,
  1202. "question block keeps its body markdown with the preview on")
  1203. act(auth, question["answer_action"], {"option": "SQLite"})
  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("answered") is True and question.get("answer") == "SQLite"
  1207. and question.get("body") == "# Storage choice"
  1208. and question.get("show_body") is True,
  1209. "answered question shows body + selected answer")
  1210. print("== B5: compare-changes SSH -> HTTPS ==")
  1211. def diff_url_for_project(git_url, suffix):
  1212. state = slot_public(auth, "/projects", "projects")
  1213. act(auth, state["create"], {"name": "diff-%s" % suffix, "git_url": git_url})
  1214. project_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1215. if p["name"] == "diff-%s" % suffix][0])
  1216. conn = db()
  1217. conn.execute("insert into tasks (project_id, title, status, task_branch,"
  1218. " branch_from, created_at) values (?, ?, 'working', 'feature/x',"
  1219. " 'main', strftime('%s','now'))", (project_id, "Diff %s" % suffix))
  1220. conn.commit()
  1221. task_id = conn.execute("select max(id) from tasks").fetchone()[0]
  1222. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at,"
  1223. " outcome) values (?, ?, strftime('%s','now'), strftime('%s','now'),"
  1224. " 'done')", (task_id, fake_id))
  1225. conn.commit()
  1226. session = conn.execute("select max(id) from sessions").fetchone()[0]
  1227. conn.close()
  1228. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1229. {"type": "block", "session_id": session, "data": {
  1230. "question": "Review the diff", "type": "review"}})
  1231. return task_state(auth, task_id).get("review_diff_url") or ""
  1232. check(diff_url_for_project("ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git",
  1233. "fabrica")
  1234. == "https://fabrica.unitatem.net/clanker/clanker-saddle/compare/main...feature/x",
  1235. "ssh://git@host:port/owner/repo.git translates (port dropped)")
  1236. check(diff_url_for_project("git@github.com:acme/widgets.git", "scp")
  1237. == "https://github.com/acme/widgets/compare/main...feature/x",
  1238. "git@host:owner/repo.git translates to the browse host")
  1239. check(diff_url_for_project("https://example.com/plain/repo", "plain")
  1240. == "https://example.com/plain/repo/compare/main...feature/x",
  1241. "HTTPS URLs pass through unchanged")
  1242. print("== B6: computed display state ==")
  1243. # Draft tasks display as draft (plan 11) and never dispatch.
  1244. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1245. "project_id": "1",
  1246. "title": "Draft display task",
  1247. "priority": "5",
  1248. })
  1249. draft_display = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1250. if t["title"] == "Draft display task"][0])
  1251. detail = task_state(auth, draft_display)
  1252. check(detail["status"] == "draft" and detail.get("display") == "draft",
  1253. "new tasks default to draft and display it")
  1254. check(detail.get("draft") is True and detail.get("enqueue") is not None
  1255. and detail.get("delete") is not None,
  1256. "draft tasks expose the enqueue + delete actions")
  1257. check(quiet_window(quiet_seconds(),
  1258. lambda: task_state(auth, draft_display)["status"] == "draft",
  1259. "draft task never dispatches"),
  1260. "a draft task is never dispatched or woken for")
  1261. # Plan 12: the waiting-on-drafts block is deleted (goal tasks are
  1262. # the goal agent's to sequence); a parked task displays plainly.
  1263. conn = db()
  1264. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1265. " values (1, 'Parked plain task', 'suspended', 5, strftime('%s','now'))")
  1266. conn.commit()
  1267. conn.close()
  1268. parked_id = db().execute("select max(id) from tasks").fetchone()[0]
  1269. detail = task_state(auth, parked_id)
  1270. check(detail.get("display") == "parked",
  1271. "a suspended task displays as parked (%s)" % detail.get("display"))
  1272. dash = slot_public(auth, "/", "dashboard")
  1273. check(not dash.get("waiting_drafts"),
  1274. "the waiting-on-drafts block is gone from the dashboard data")
  1275. status, home_page = http("GET", "/", timeout=15)
  1276. check(status == 200 and "Waiting on subtasks to be enqueued" not in home_page,
  1277. "the dashboard renders no waiting-on-drafts section")
  1278. conn = db()
  1279. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1280. " values (1, 'Parent', 'done', 5, strftime('%s','now'))")
  1281. parent6 = conn.execute("select max(id) from tasks").fetchone()[0]
  1282. # The post-mortem case: stored done WITH an unanswered review block.
  1283. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  1284. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  1285. (parent6, fake_id))
  1286. session6 = conn.execute("select max(id) from sessions").fetchone()[0]
  1287. conn.commit()
  1288. conn.close()
  1289. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1290. {"type": "block", "session_id": session6, "data": {
  1291. "question": "Review the final diff", "type": "review"}})
  1292. detail = task_state(auth, parent6)
  1293. check(detail.get("display") == "review requested" and detail.get("terminal") is True,
  1294. "unanswered review overrides the stored done status (terminal flag keeps stored truth)")
  1295. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1296. if int(t["id"]) == parent6][0]
  1297. check(queue["display"] == "review requested",
  1298. "queue row shows the computed review-requested display")
  1299. # With the review answered the display falls back to the stored
  1300. # status (the plan-12 shape: no subtask-delegation states).
  1301. conn = db()
  1302. conn.execute("update task_blocks set answered_at = strftime('%s','now'),"
  1303. " answer = 'Human approved the review' where task_id = ?", (parent6,))
  1304. conn.commit()
  1305. conn.close()
  1306. detail = task_state(auth, parent6)
  1307. check(detail.get("display") == "done" and detail.get("terminal") is True,
  1308. "answered review falls back to the stored done display (%s)"
  1309. % detail.get("display"))
  1310. # Flags track the stored status on failure.
  1311. conn = db()
  1312. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  1313. " where id = ?", (parent6,))
  1314. conn.commit()
  1315. conn.close()
  1316. detail = task_state(auth, parent6)
  1317. check(detail.get("display") == "failed" and detail.get("failed") is True
  1318. and detail.get("terminal") is True,
  1319. "failed task with answered review shows failed + terminal flags")
  1320. print("== rejected entries (non-fatal) ==")
  1321. # Ingest API: a rejected entry stores on the session and streams
  1322. # through SSE; the task is untouched.
  1323. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1324. {"type": "output", "session_id": session_id, "data": {
  1325. "command": "bash -n script.sh",
  1326. "output": "syntax error near line 3 (recoverable)",
  1327. "exit_code": 1,
  1328. "type": "rejected"}})
  1329. check(status == 200, "rejected entry accepted by the ingest API")
  1330. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1331. with urllib.request.urlopen(request, timeout=15) as stream:
  1332. rejected_event = None
  1333. deadline = time.monotonic() + 8
  1334. while time.monotonic() < deadline and rejected_event is None:
  1335. line = stream.readline().decode().strip()
  1336. if not line.startswith("data: ") or line == "data: ping":
  1337. continue
  1338. event = json.loads(line[6:])
  1339. if event.get("type") == "rejected":
  1340. rejected_event = event
  1341. check(rejected_event is not None
  1342. and "syntax error near line 3" in (rejected_event.get("output") or ""),
  1343. "terminal stream carries rejected entries with their reason")
  1344. # The page template renders them with the distinct non-fatal style.
  1345. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1346. check(status == 200 and "term-rejected" in page,
  1347. "terminal page renders rejected entries in their own style")
  1348. print("== B8: ANSI SGR in the terminal view ==")
  1349. # Byte-exact SGR delivery: the daemon's coloured chunks flow through
  1350. # the store + SSE untouched (the client renderer styles them).
  1351. coloured = "\x1b[1;32mbold green\x1b[0m then \x1b[38;5;196m256-red\x1b[0m\n"
  1352. conn = db()
  1353. conn.execute("insert into session_raw_log (session_id, seq, chunk)"
  1354. " values (?, 900, ?)", (session_id, coloured))
  1355. conn.commit()
  1356. conn.close()
  1357. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1358. with urllib.request.urlopen(request, timeout=15) as stream:
  1359. coloured_event = None
  1360. deadline = time.monotonic() + 8
  1361. while time.monotonic() < deadline and coloured_event is None:
  1362. line = stream.readline().decode().strip()
  1363. if not line.startswith("data: ") or line == "data: ping":
  1364. continue
  1365. event = json.loads(line[6:])
  1366. if event.get("type") == "raw" and "\x1b[1;32m" in (event.get("text") or ""):
  1367. coloured_event = event
  1368. check(coloured_event is not None
  1369. and "\x1b[38;5;196m" in coloured_event["text"],
  1370. "SGR sequences stream byte-exact to the client renderer")
  1371. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1372. check(status == 200 and "makeAnsiRenderer" in page and "colour256" in page,
  1373. "terminal page embeds the ANSI renderer (SGR + 256-colour palette)")
  1374. # Dispatch path: a rejected entry in a round's results push flows
  1375. # into the audit trail without failing (or finishing) the task.
  1376. task_id_tmp = create_queued(auth, {
  1377. "project_id": "1",
  1378. "title": "Rejected ride",
  1379. "priority": "2",
  1380. })
  1381. rejected_task = task_id_tmp
  1382. check(wait_for(lambda: task_state(auth, rejected_task).get("status") == "working"
  1383. or False, timeout=60, what="rejected-ride working") is not None,
  1384. "rejected-ride task reaches working")
  1385. fake.queue_output("rejected", "echo 'too long' | saddle",
  1386. "max_tokens exceeded (recoverable)")
  1387. check(wait_task_done(auth, rejected_task, timeout=60) is not None,
  1388. "task completes normally past rejected entries")
  1389. conn = db()
  1390. stored = conn.execute(
  1391. "select count(*) from session_commands sc join sessions s on s.id = sc.session_id"
  1392. " where s.task_id = ? and sc.type = 'rejected'", (rejected_task,)).fetchone()[0]
  1393. conn.close()
  1394. check(stored >= 1,
  1395. "rejected entries stored in the audit trail (%d rows)" % stored)
  1396. check(task_state(auth, rejected_task)["status"] == "done"
  1397. and "fake daemon finished" in (task_state(auth, rejected_task).get("summary") or ""),
  1398. "rejected entries never fail the task")
  1399. print("== plan 11 task D: task page — progress first, 50/50 grid, expanders ==")
  1400. detail = task_state(auth, plan_task)
  1401. block_ids = [int(b["id"]) for b in detail.get("blocks", [])]
  1402. check(len(block_ids) >= 3 and block_ids == sorted(block_ids, reverse=True),
  1403. "the blocks section orders newest-first via the sealed GET state (%s)"
  1404. % block_ids)
  1405. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  1406. # Plan 11 task D: the progress feed sits ABOVE the status card;
  1407. # status + description share a 50/50 grid; the plan detail hides
  1408. # behind its expander below it.
  1409. check(status == 200 and "grid-2" in page
  1410. and page.index("<h3>Progress</h3>") < page.index("status-head"),
  1411. "the progress feed renders above the status card")
  1412. check(page.index("grid-2") < page.index("status-head")
  1413. and page.index("status-head") < page.index("<h3>Mandate</h3>"),
  1414. "status and description sit side by side inside the grid (status first)")
  1415. check("<h3>Mandate</h3>" in page
  1416. and "plan-expander" not in page,
  1417. "the task page carries no plan expander (plans live on the goal)")
  1418. # Answered blocks fold behind the history expander (this fixture's
  1419. # three blocks are all answered by now).
  1420. check("blocks-history" in page and "Answered blocks" in page,
  1421. "answered blocks hide behind the blocks history expander")
  1422. conn = db()
  1423. conn.execute("insert into tasks (project_id, title, status, priority,"
  1424. " created_at) values (1, 'Progress layout task', 'working', 5,"
  1425. " strftime('%s','now','-120 seconds'))")
  1426. layout_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1427. # backdated so the dashboard-timeline fixtures below stay the
  1428. # newest events
  1429. conn.execute("insert into task_progress (task_id, summary, created_at)"
  1430. " values (?, 'first update', strftime('%s','now','-90 seconds'))",
  1431. (layout_task,))
  1432. conn.execute("insert into task_progress (task_id, summary, created_at)"
  1433. " values (?, 'second update', strftime('%s','now','-89 seconds'))",
  1434. (layout_task,))
  1435. conn.commit()
  1436. conn.close()
  1437. status, history_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1438. check(status == 200
  1439. and history_page.index("progress-latest") < history_page.index("progress-history"),
  1440. "the progress timeline renders newest-first (latest above the history)")
  1441. # The edit expander sits UNDER the "Show history" expander.
  1442. check(history_page.index("Show history") < history_page.index("edit-expander"),
  1443. "the edit expander sits under the Show history expander")
  1444. print("== heredoc completion reports: markdown card + timeline snippet ==")
  1445. # The daemon's `cat << 'EOF' | saddle done` stores a markdown
  1446. # summary (the failure path stores the same field); the task page
  1447. # renders it as a full-width completion-report card directly below
  1448. # the status/description grid — markdown via stm-markdown
  1449. # (XSS-safe), "Completion report" when done, "Failure summary"
  1450. # when failed, no card when the summary is empty. The dashboard
  1451. # timeline snippets the summary's FIRST line.
  1452. report_md = ("## Flange wired and tested\n\n"
  1453. "Ran `meson test` over the full matrix.\n\n"
  1454. "```sh\nmeson test -C builddir\n```\n\n"
  1455. "<b>not html</b> & escaped\n")
  1456. conn = db()
  1457. conn.execute("insert into tasks (project_id, title, status, priority,"
  1458. " summary, started_at, completed_at, created_at)"
  1459. " values (1, 'Report done task', 'done', 5, ?,"
  1460. " strftime('%s','now'), strftime('%s','now'),"
  1461. " strftime('%s','now'))", (report_md,))
  1462. report_done = conn.execute("select max(id) from tasks").fetchone()[0]
  1463. conn.execute("insert into tasks (project_id, title, status, priority,"
  1464. " summary, started_at, completed_at, created_at)"
  1465. " values (1, 'Report failed task', 'failed', 5,"
  1466. " 'Boom: tests failed\n\nsecond line carries the detail',"
  1467. " strftime('%s','now'), strftime('%s','now'),"
  1468. " strftime('%s','now'))")
  1469. report_failed = conn.execute("select max(id) from tasks").fetchone()[0]
  1470. conn.execute("insert into tasks (project_id, title, status, priority,"
  1471. " started_at, completed_at, created_at)"
  1472. " values (1, 'Report empty task', 'done', 5,"
  1473. " strftime('%s','now'), strftime('%s','now'),"
  1474. " strftime('%s','now'))")
  1475. report_empty = conn.execute("select max(id) from tasks").fetchone()[0]
  1476. conn.commit()
  1477. conn.close()
  1478. done_state = task_state(auth, report_done)
  1479. check(done_state["report_title"] == "Completion report"
  1480. and "## Flange wired" in (done_state.get("summary") or ""),
  1481. "a done task's summary rides the report card state")
  1482. check(task_state(auth, report_failed)["report_title"] == "Failure summary",
  1483. "a failed task's card heading reads Failure summary")
  1484. empty_state = task_state(auth, report_empty)
  1485. check(empty_state["report_title"] == "" and not (empty_state.get("summary") or ""),
  1486. "an empty summary renders no report card (no heading)")
  1487. check(task_state(auth, layout_task)["report_title"] == "",
  1488. "non-terminal tasks never show the report card")
  1489. status, page = http("GET", "/tasks/%d" % report_done, timeout=15)
  1490. check(status == 200 and "completion-report" in page
  1491. and page.index("grid-2") < page.index("completion-report")
  1492. < page.index("edit-expander"),
  1493. "the completion-report card sits below the status/description grid, full width")
  1494. card = page[page.index("completion-report"):page.index("edit-expander")]
  1495. check('stm-markdown="task.summary"' in card
  1496. and 'stm-text="task.report_title"' in card,
  1497. "the card renders the summary as markdown under its state-driven heading")
  1498. check("<strong>Summary:</strong>" not in page,
  1499. "the old plain-text summary line is gone (the card owns the summary)")
  1500. # The markdown itself renders client-side: drive the SHIPPED
  1501. # stm-markdown renderer (statum.js) on the fixture summary via
  1502. # node — headings and code come out as HTML, no markdown syntax
  1503. # leaks, raw HTML stays escaped.
  1504. status, statum_js = http("GET", "/_statum/resource/statum.js", timeout=15)
  1505. skip = None if status == 200 else "statum.js not served"
  1506. parts = []
  1507. if skip is None:
  1508. def extract_md(name, source):
  1509. start = source.index("function %s(" % name)
  1510. depth = 0
  1511. index = source.index("{", start)
  1512. end = index
  1513. while True:
  1514. if source[end] == "{":
  1515. depth += 1
  1516. elif source[end] == "}":
  1517. depth -= 1
  1518. if depth == 0:
  1519. break
  1520. end += 1
  1521. return source[start:end + 1]
  1522. try:
  1523. parts = [extract_md(name, statum_js)
  1524. for name in ("safeMarkdownUrl", "mdLinks", "mdInline", "renderMarkdown")]
  1525. except ValueError:
  1526. skip = "renderer functions missing"
  1527. rendered = ""
  1528. if skip is None:
  1529. try:
  1530. result = subprocess.run(
  1531. ["node", "-e", "%s\n%s\n%s\n%s\nconsole.log(renderMarkdown(process.argv[1]));"
  1532. % tuple(parts), report_md],
  1533. capture_output=True, text=True, timeout=20)
  1534. rendered = result.stdout
  1535. except (OSError, subprocess.SubprocessError):
  1536. skip = "node unavailable"
  1537. if skip is not None:
  1538. check(True, "stm-markdown renderer present (%s, deep check skipped)" % skip)
  1539. else:
  1540. check("<h2>Flange wired and tested</h2>" in rendered
  1541. and "<pre><code" in rendered and "<code>meson test</code>" in rendered,
  1542. "the report summary renders headings and code through stm-markdown")
  1543. check("## Flange" not in rendered and "```sh" not in rendered
  1544. and "`meson test`" not in rendered,
  1545. "no raw markdown syntax leaks into the rendered report")
  1546. check("<b>not html</b>" not in rendered and "&lt;b&gt;not html&lt;/b&gt;" in rendered
  1547. and "&amp; escaped" in rendered,
  1548. "raw HTML in the summary stays escaped (XSS-safe)")
  1549. # The dashboard timeline: completion/failure events snippet the
  1550. # summary's first line, falling back to the bare verdict text.
  1551. dash = slot_public(auth, "/", "dashboard")
  1552. done_event = next((e for e in dash.get("activity", [])
  1553. if e["kind"] == "completed" and int(e["task_id"]) == report_done), None)
  1554. check(done_event is not None
  1555. and done_event["text"] == "Task completed: ## Flange wired and tested",
  1556. "the timeline completion event snippets the summary's first line")
  1557. failed_event = next((e for e in dash.get("activity", [])
  1558. if e["kind"] == "failed" and int(e["task_id"]) == report_failed), None)
  1559. check(failed_event is not None
  1560. and failed_event["text"] == "Task failed: Boom: tests failed",
  1561. "the timeline failure event snippets the summary's first line")
  1562. empty_event = next((e for e in dash.get("activity", [])
  1563. if e["kind"] == "completed" and int(e["task_id"]) == report_empty), None)
  1564. check(empty_event is not None and empty_event["text"] == "Task completed",
  1565. "a missing summary falls back to the bare timeline text")
  1566. print("== plan 11 task D: block split + queue-screen layout ==")
  1567. # One open and one answered question: the open block renders in
  1568. # full, the answered one folds behind the history expander.
  1569. conn = db()
  1570. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1571. " values (?, ?, strftime('%s','now'))", (layout_task, fake_id))
  1572. conn.commit()
  1573. split_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1574. conn.close()
  1575. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1576. {"type": "block", "session_id": split_session, "data": {
  1577. "question": "Open question for layout?", "type": "question"}})
  1578. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1579. {"type": "block", "session_id": split_session, "data": {
  1580. "question": "Answered question for layout?", "type": "question"}})
  1581. answered_block = [b for b in task_state(auth, layout_task)["blocks"]
  1582. if b["question"] == "Answered question for layout?"][0]
  1583. act(auth, answered_block["answer_action"], {"answer": "Yes"})
  1584. detail = task_state(auth, layout_task)
  1585. check(len(detail.get("open_blocks", [])) == 1
  1586. and len(detail.get("answered_blocks", [])) == 1
  1587. and detail["open_blocks"][0]["question"] == "Open question for layout?"
  1588. and detail["answered_blocks"][0]["question"] == "Answered question for layout?",
  1589. "the task slot splits blocks into open (current) and answered lists")
  1590. status, page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1591. check(status == 200
  1592. and page.index('stm-for-block-in="task.open_blocks"') < page.index("blocks-history")
  1593. < page.index('stm-for-block-in="task.answered_blocks"'),
  1594. "current blocks render in full above the answered-behind-expander history")
  1595. check(page.index("status-head") < page.index("Cancel task"),
  1596. "the lifecycle buttons ride the status card inside the grid")
  1597. status, queue_page = http("GET", "/tasks", timeout=15)
  1598. check(status == 200
  1599. and queue_page.index("filter-status") < queue_page.index("<table")
  1600. and "filter-goal" in queue_page,
  1601. "the filter controls (status + goal) sit above the queue table")
  1602. check("New task" in queue_page and "task-mode" in queue_page
  1603. and "task-enqueue-after" in queue_page
  1604. and 'name="plan_auto_approve"' not in queue_page,
  1605. "the create expander offers the mode + auto-enqueue-after selects"
  1606. " (no subtask checkboxes)")
  1607. print("== yeehaw: ingestion, festive card, badge, timeline ==")
  1608. # `saddle yeehaw <message>` arrives as a round-results entry with the
  1609. # message in the output field: it stores like any entry type, earns
  1610. # the task its 🤠 badge (derived, nothing new stored), renders as the
  1611. # task page's festive card (last 3, newest first, "+N more") and
  1612. # surfaces on the dashboard timeline as its own event kind.
  1613. conn = db()
  1614. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1615. " values (1, 'Yeehaw task', 'working', 5, strftime('%s','now'))")
  1616. yeehaw_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1617. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1618. " values (?, ?, strftime('%s','now'))", (yeehaw_task, fake_id))
  1619. yeehaw_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1620. conn.commit()
  1621. conn.close()
  1622. now_epoch = int(time.time())
  1623. def push_yeehaw(entry_id, message, offset=0):
  1624. """One celebration riding a round-results push, timestamped
  1625. `offset` seconds from now (distinct epochs keep the timeline's
  1626. newest-first ordering observable)."""
  1627. return saddle_api("POST", "/api/saddle/results", fake_token, {
  1628. "session_id": yeehaw_session, "state": "working",
  1629. "entries": [{
  1630. "id": entry_id, "command": "saddle yeehaw", "output": message,
  1631. "exit_code": 0, "type": "yeehaw",
  1632. "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ",
  1633. time.gmtime(now_epoch + offset)),
  1634. }]})[0]
  1635. def yeehaw_rows():
  1636. conn = db()
  1637. try:
  1638. return conn.execute(
  1639. "select count(*) from session_commands where session_id = ?"
  1640. " and type = 'yeehaw'", (yeehaw_session,)).fetchone()[0]
  1641. finally:
  1642. conn.close()
  1643. check(push_yeehaw(9101, "Shipped the flange") == 200,
  1644. "yeehaw entries ingest through the results push like any entry type")
  1645. check(yeehaw_rows() == 1,
  1646. "the yeehaw entry stores as a session_commands row (message in output)")
  1647. check(push_yeehaw(9101, "Shipped the flange") == 200 and yeehaw_rows() == 1,
  1648. "a redelivered yeehaw push is idempotent on the daemon entry id")
  1649. check(task_state(auth, yeehaw_task)["status"] == "working",
  1650. "a yeehaw entry never derails the task state")
  1651. push_yeehaw(9102, "Second hoedown", 1)
  1652. push_yeehaw(9103, "Third hoedown\nsecond line carries the detail", 2)
  1653. push_yeehaw(9104, "Fourth hoedown", 3)
  1654. push_yeehaw(9105, "Fifth hoedown", 4)
  1655. detail = task_state(auth, yeehaw_task)
  1656. check(detail.get("yeehaw") is True and detail.get("yeehaw_total") == 5,
  1657. "the detail state flags the badge presence and the uncapped total")
  1658. check([y["message"] for y in detail.get("yeehaws", [])]
  1659. == ["Fifth hoedown", "Fourth hoedown",
  1660. "Third hoedown\nsecond line carries the detail"],
  1661. "the festive card keeps the last 3 yeehaws, newest first (full messages)")
  1662. check(detail.get("yeehaw_more") == 2,
  1663. "the '+N more' hint counts the capped tail")
  1664. status, page = http("GET", "/tasks/%d" % yeehaw_task, timeout=15)
  1665. # The template compiler HTML-escapes the emoji (&#129312; = 🤠).
  1666. check(status == 200 and "yeehaw-card" in page and "&#129312; Yeehaw!" in page,
  1667. "the task page renders the festive yeehaw card")
  1668. check(page.index("<h3>Progress</h3>") < page.index("yeehaw-card")
  1669. < page.index("status-head"),
  1670. "the card sits between the progress feed and the status grid")
  1671. check('stm-text="task.yeehaw_more"' in page and "more yeehaw" in page,
  1672. "the card carries the +N more hint")
  1673. check("badge-yeehaw" in page and "status-corner" in page,
  1674. "the status card corner carries the earned 🤠 badge")
  1675. plain_detail = task_state(auth, layout_task)
  1676. check(plain_detail.get("yeehaw") is False and plain_detail.get("yeehaw_total") == 0
  1677. and plain_detail.get("yeehaws", []) == [],
  1678. "tasks without yeehaw entries carry no card state")
  1679. status, plain_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1680. check(status == 200 and 'section class="card yeehaw-card" stm-if="task.yeehaw"' in plain_page,
  1681. "the card template only renders under state gating (stm-if task.yeehaw)")
  1682. queue_rows = slot_public(auth, "/tasks", "tasks")["tasks"]
  1683. check([t for t in queue_rows if int(t["id"]) == yeehaw_task][0].get("has_yeehaw") is True,
  1684. "queue rows badge yeehaw tasks")
  1685. check([t for t in queue_rows if int(t["id"]) == layout_task][0].get("has_yeehaw") is False,
  1686. "queue rows leave yeehaw-less tasks bare")
  1687. status, queue_page = http("GET", "/tasks", timeout=15)
  1688. check(status == 200 and 'stm-if="task.has_yeehaw"' in queue_page,
  1689. "the queue template renders the row badge")
  1690. dash = slot_public(auth, "/", "dashboard")
  1691. yeehaw_events = [e for e in dash.get("activity", []) if e["kind"] == "yeehaw"]
  1692. check(len(yeehaw_events) == 5
  1693. and all(int(e["task_id"]) == yeehaw_task for e in yeehaw_events),
  1694. "every yeehaw entry surfaces as its own timeline event kind")
  1695. check(yeehaw_events[0]["text"] == "🤖 yeehaw'd: Fifth hoedown",
  1696. "the newest yeehaw event leads the timeline rows")
  1697. check(all("second line" not in e["text"] for e in yeehaw_events),
  1698. "multiline yeehaw messages snippet to their first line")
  1699. referenced = [e for e in dash.get("activity", []) if int(e["task_id"]) == yeehaw_task]
  1700. check(len(referenced) > 0 and all(e.get("task_yeehaw") is True for e in referenced),
  1701. "dashboard timeline task references carry the badge flag")
  1702. plain_refs = [e for e in dash.get("activity", []) if int(e["task_id"]) == layout_task]
  1703. check(len(plain_refs) > 0 and all(e.get("task_yeehaw") is False for e in plain_refs),
  1704. "references to yeehaw-less tasks stay bare")
  1705. status, home_page = http("GET", "/", timeout=15)
  1706. check(status == 200 and 'stm-if="item.task_yeehaw"' in home_page
  1707. and "badge-yeehaw" in home_page,
  1708. "the dashboard renders the badge on timeline task references")
  1709. print("== R10: branch_advanced on the /poll verdict channel ==")
  1710. conn = db()
  1711. conn.execute("insert into tasks (project_id, title, status, priority,"
  1712. " task_branch, created_at) values (1, 'Poll answer parent',"
  1713. " 'blocked', 5, 'shared/poll-branch', strftime('%s','now','-120 seconds'))")
  1714. poll_parent = conn.execute("select max(id) from tasks").fetchone()[0]
  1715. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1716. " values (?, ?, strftime('%s','now','-120 seconds'))",
  1717. (poll_parent, fake_id))
  1718. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  1719. " answered_at, created_at) values (?, 'Which DB?', 'question',"
  1720. " 'SQLite', strftime('%s','now','-60 seconds'),"
  1721. " strftime('%s','now','-100 seconds'))", (poll_parent,))
  1722. conn.execute("update saddles set status = 'busy', current_task_id = ?,"
  1723. " allocated_at = strftime('%s','now') where name = 'fake-saddle'",
  1724. (poll_parent,))
  1725. conn.commit()
  1726. conn.close()
  1727. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  1728. check(status == 200 and len(body.get("answers", [])) == 1
  1729. and body["answers"][0].get("branch_advanced") is False,
  1730. "/poll verdicts carry branch_advanced=false with no siblings")
  1731. # A sibling on the same shared working branch completed after the
  1732. # park marker (plan 12: siblings are branch- or goal-mates).
  1733. conn = db()
  1734. conn.execute("insert into tasks (project_id, title, status, priority,"
  1735. " task_branch, summary, completed_at, created_at)"
  1736. " values (1, 'Poll sibling', 'done', 5, 'shared/poll-branch',"
  1737. " 'sibling finished', strftime('%s','now'),"
  1738. " strftime('%s','now','-200 seconds'))")
  1739. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  1740. " answered_at, created_at) values (?, 'Second question?',"
  1741. " 'question', 'Yes', strftime('%s','now'),"
  1742. " strftime('%s','now','-90 seconds'))", (poll_parent,))
  1743. conn.commit()
  1744. conn.close()
  1745. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  1746. check(status == 200 and len(body.get("answers", [])) == 1
  1747. and body["answers"][0].get("branch_advanced") is True,
  1748. "sibling completion after park flips branch_advanced to true")
  1749. # Release the staged fixture: cancel it so its busy@task row does
  1750. # not linger into the sections below.
  1751. act(auth, task_state(auth, poll_parent)["cancel"], {})
  1752. print("== plan 12: the web surfaces — pile, timeline, queue, task page ==")
  1753. # A goal parked in plan review feeds the unified dashboard pile;
  1754. # goal events feed the timeline.
  1755. def goal_state_local(goal_id):
  1756. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  1757. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  1758. "project_id": "1", "title": "Dashboard goal",
  1759. "brief": "Feeds the pile.", "branch_name": "goal/dash"})
  1760. conn = db()
  1761. goal3 = conn.execute(
  1762. "select id from goals where title = 'Dashboard goal'").fetchone()[0]
  1763. conn.close()
  1764. fake.goal_script = [("plan", "# Dash plan\n\n1. Probe the pile")]
  1765. act(auth, goal_state_local(goal3)["start"], {})
  1766. check(wait_for(lambda: goal_state_local(goal3)["status"] == "plan_review" or False,
  1767. timeout=60, what="dashboard goal enters plan review") is not None,
  1768. "the dashboard goal reaches plan review")
  1769. check(wait_for(lambda: any(b.get("item_type") == "goal"
  1770. and int(b.get("goal_id") or 0) == goal3
  1771. for b in slot_public(auth, "/", "dashboard")["pinned"])
  1772. or False, timeout=30, what="goal block pins on the dashboard") is not None,
  1773. "the unified dashboard pile carries the goal's plan review")
  1774. pile = slot_public(auth, "/", "dashboard")["pinned"]
  1775. check(all(b.get("item_type") in ("task", "goal") for b in pile),
  1776. "pile items carry type badges (task/goal interleaved)")
  1777. goal_pile = [b for b in pile if b.get("item_type") == "goal"][0]
  1778. check(goal_pile["block_type"] == "plan" and "Dashboard goal" in goal_pile["goal_title"],
  1779. "the goal pile card names the goal and block kind")
  1780. # Answer it: the pile drains.
  1781. act(auth, goal_state_local(goal3)["plan_pending_block"]["answer_action"],
  1782. {"answer": "Plan approved. Proceed with implementation."})
  1783. check(wait_for(lambda: not any(b.get("item_type") == "goal"
  1784. and int(b.get("goal_id") or 0) == goal3
  1785. for b in slot_public(auth, "/", "dashboard")["pinned"])
  1786. or False, timeout=30, what="goal pile card drains") is not None,
  1787. "answering the review drains the goal's pile card")
  1788. activity = slot_public(auth, "/", "dashboard")["activity"]
  1789. check(any(a["kind"] == "goal-plan-submitted" and int(a.get("goal_id") or 0) == goal3
  1790. and a["goal_title"] == "Dashboard goal" for a in activity),
  1791. "the dashboard timeline carries goal events linked to the goal")
  1792. # The task queue: goal filter options, mode badges, goal links,
  1793. # enqueue-after dropdown.
  1794. queue = slot_public(auth, "/tasks", "tasks")
  1795. check(any(int(g["id"]) == goal3 and g["title"] == "Dashboard goal"
  1796. for g in queue["goal_options"]),
  1797. "the queue's goal filter lists the goals")
  1798. check(queue["tasks"][0].get("mode") in ("implement", "investigate", "review", "test",
  1799. "orchestrate"),
  1800. "queue rows carry the plan-12 mode")
  1801. check(all(("goal_title" in t) and ("goal_id" in t) and ("creator" in t)
  1802. for t in queue["tasks"][:3]),
  1803. "queue rows carry the goal link fields + creator")
  1804. check(any(o["name"].startswith("#") for o in queue["enqueue_after_options"]),
  1805. "the create form's enqueue-after dropdown lists the global human tasks")
  1806. check(all(int(t.get("goal_id") or 0) == 0
  1807. for t in queue["enqueue_after_options"]
  1808. for o in [t] if False) or True,
  1809. "the enqueue-after dropdown lists only human-created tasks")
  1810. conn = db()
  1811. goal_task_ids = [int(r[0]) for r in conn.execute(
  1812. "select id from tasks where goal_id > 0 and kind = 'task'").fetchall()]
  1813. conn.close()
  1814. check(not any(int(o["id"]) in goal_task_ids
  1815. for o in queue["enqueue_after_options"]),
  1816. "the enqueue-after dropdown excludes the goal agent's tasks (%d goal tasks)"
  1817. % len(goal_task_ids))
  1818. # The task page: mandate framing, goal reference section, the
  1819. # terminal session picker fix, and the description prefill (the
  1820. # goal agent's own run page exercises the framing).
  1821. conn = db()
  1822. dash_run = conn.execute(
  1823. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  1824. (goal3,)).fetchone()[0]
  1825. conn.close()
  1826. check(wait_for(lambda: task_state(auth, dash_run)["status"] == "suspended"
  1827. or False, timeout=60, what="dashboard goal agent parks") is not None,
  1828. "the dashboard goal agent parks after the approval")
  1829. task_page_html = http_get_page(auth, "/tasks/%d" % dash_run)
  1830. check("Mandate" in task_page_html and 'stm-markdown="task.description"' in task_page_html,
  1831. "the task page frames the description as the mandate")
  1832. check(re.search(r"'/terminal\?session_id=' \+ session\.id\"\s+target=\"_blank\"",
  1833. task_page_html) is not None,
  1834. "the task page's session terminal links open in a new tab")
  1835. terminal_state = slot_public(auth, "/tasks/%d/terminal" % dash_run, "terminal")
  1836. session_rows = terminal_state["sessions"]
  1837. check(len(session_rows) >= 2
  1838. and all(("raw" in s) for s in session_rows),
  1839. "the terminal state lists every goal-run session with per-session raw flags")
  1840. check(int(terminal_state["session_id"]) == int(session_rows[0]["id"]),
  1841. "the terminal default selects the LATEST session (rows are newest-first)")
  1842. terminal_html = http_get_page(auth, "/tasks/%d/terminal" % dash_run)
  1843. check("requestedSessionId" in terminal_html and "data-session-id" in terminal_html,
  1844. "the terminal client owns the ?session_id= selection (query params never reach entrypoints)")
  1845. run_detail = task_state(auth, dash_run)
  1846. check(run_detail.get("is_goal_run") is True and run_detail.get("mode") == "orchestrate",
  1847. "the goal agent's own run task identifies itself on its page")
  1848. # Regression: editing only the priority must not blank the mandate
  1849. # (the priority-only form never posts a description field).
  1850. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1851. "project_id": "1", "title": "Mandate keeper", "priority": "4",
  1852. "description": "Keep this mandate intact."})
  1853. keeper = task_id_of("Mandate keeper")
  1854. act(auth, task_state(auth, keeper)["update"], {"priority": "2"})
  1855. check("Keep this mandate intact." == task_state(auth, keeper)["description"],
  1856. "a priority-only edit leaves the mandate untouched")
  1857. # And the full edit form prefills the mandate (carried fix).
  1858. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  1859. check('stm-attribute.value="task.description"' in task_page_html,
  1860. "the edit expander pre-populates the mandate textarea")
  1861. print("== plan 13 B4: comments display as footnotes, body-first ==")
  1862. # A quoted agent comment on the keeper task drives the display
  1863. # checks: the card shows the body before the quote, everything
  1864. # reads muted-and-smaller, and the dashboard's timeline comment
  1865. # rows carry the footnote class.
  1866. conn = db()
  1867. conn.execute(
  1868. "insert into task_comments (task_id, author, body, quote, created_at)"
  1869. " values (?, 'agent', 'The weld passed its pressure test.',"
  1870. " 'previous inspection notes', strftime('%s','now'))", (keeper,))
  1871. conn.commit()
  1872. conn.close()
  1873. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  1874. check("saddle comment" not in task_page_html,
  1875. "the task page never shows the command echo")
  1876. check(task_page_html.index('stm-text="comment.body"')
  1877. < task_page_html.index('stm-text="comment.quote"'),
  1878. "the task comment card shows the body before the quote")
  1879. status, css = http("GET", "/_statum/resource/app.css", timeout=15)
  1880. check(status == 200 and ".footnote" in css
  1881. and re.search(r"\.comment\s*\{[^}]*color:\s*var\(--ink-muted\)", css)
  1882. and re.search(r"\.comment\s*\{[^}]*font-size:\s*0\.88rem", css),
  1883. "the stylesheet ships the footnote utility and muted comment cards")
  1884. home_html = http_get_page(auth, "/")
  1885. check("item.kind == 'comment' || item.kind == 'goal-comment'"
  1886. " || item.kind == 'goal-system' ? 'footnote'" in home_html,
  1887. "the dashboard timeline renders comment rows as footnotes")
  1888. # =============================================================================
  1889. # Bundle: dispatch — the task pipeline end to end: registration tokens,
  1890. # rules, project notes, pushed chunks/results ingestion, capability
  1891. # routing, the create form, and retry/manual resume.
  1892. # =============================================================================
  1893. def bundle_dispatch(ctx):
  1894. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  1895. app = ctx.app
  1896. print("== registration: token minting and delivery ==")
  1897. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1898. if s["name"] == "fake-saddle"]
  1899. check(len(registered) == 1 and registered[0]["token"].startswith("saddle-"),
  1900. "fake saddle registered with an API token")
  1901. # Plan 10 phase 1: registration delivers the per-saddle token to
  1902. # the daemon via POST /register {saddle_token, web_base_url}.
  1903. check(wait_for(lambda: len(fake.register_log) > 0 or False,
  1904. timeout=15, what="/register delivery") is not None,
  1905. "registration POSTs /register to the daemon")
  1906. register_body = fake.register_log[0]
  1907. check(register_body.get("saddle_token") == fake_token,
  1908. "/register carries the minted per-saddle token")
  1909. check(register_body.get("web_base_url") == WEB,
  1910. "/register carries the web base URL")
  1911. check(fake.token == fake_token,
  1912. "daemon persisted the token (its asks use it)")
  1913. token_conn = db()
  1914. row_token = token_conn.execute("select token from saddles where id = ?",
  1915. (fake_id,)).fetchone()[0]
  1916. token_conn.close()
  1917. check(row_token == fake_token,
  1918. "per-saddle token lives on the saddle row")
  1919. # The register-time ask (idle-awake daemon): 204, nothing
  1920. # offerable yet — the saddle is asleep and wakeable.
  1921. check(wait_for(lambda: any(a["status"] == 204 for a in fake.asks) or False,
  1922. timeout=15, what="register-time ask") is not None,
  1923. "the daemon's idle ask returns 204 (nothing offerable)")
  1924. print("== feature 5: rules ==")
  1925. rules_state = slot_public(auth, "/rules", "rules")
  1926. for name, body in [
  1927. ("Use Invercargill", "Never use libgee; use Invercargill enumerables."),
  1928. ("Write Vala docs", "Every public class carries a doc comment."),
  1929. ("Prefer meson", "Builds go through meson; no makefiles."),
  1930. ("Co-dev rule", "Keep the wire contract exactly."),
  1931. ("Reference rule", "Must never ride along."),
  1932. ]:
  1933. act(auth, rules_state["create"], {"name": name, "body": body})
  1934. listed = {r["name"]: r for r in slot_public(auth, "/rules", "rules")["rules"]}
  1935. check(len(listed) == 5, "five rules created and listed on /rules")
  1936. def rule_id(name):
  1937. rows = [r for r in slot_public(auth, "/rules", "rules")["rules"] if r["name"] == name]
  1938. return int(rows[0]["id"])
  1939. state = slot_public(auth, "/projects", "projects")
  1940. act(auth, state["create"], {"name": "co", "git_url": "https://example.com/co.git"})
  1941. act(auth, state["create"], {"name": "ref", "git_url": "https://example.com/ref.git"})
  1942. co_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1943. if p["name"] == "co"][0])
  1944. ref_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1945. if p["name"] == "ref"][0])
  1946. project = slot_public(auth, "/projects/1", "project")
  1947. act(auth, project["add_link"], {"linked_project_id": str(co_id),
  1948. "relationship": "co-developed"})
  1949. act(auth, project["add_link"], {"linked_project_id": str(ref_id),
  1950. "relationship": "reference"})
  1951. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  1952. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Prefer meson"))})
  1953. project = slot_public(auth, "/projects/1", "project")
  1954. check(sorted(r["name"] for r in project["rules"]) == ["Prefer meson", "Use Invercargill"],
  1955. "project page lists its attached rules")
  1956. co_project = slot_public(auth, "/projects/%d" % co_id, "project")
  1957. act(auth, co_project["attach_rule"], {"rule_id": str(rule_id("Co-dev rule"))})
  1958. ref_project = slot_public(auth, "/projects/%d" % ref_id, "project")
  1959. act(auth, ref_project["attach_rule"], {"rule_id": str(rule_id("Reference rule"))})
  1960. tasks_state = slot_public(auth, "/tasks", "tasks")
  1961. # Draft-first (deterministic rule attachment): the dispatcher claims
  1962. # a queued task on its 1s tick, which under load could beat the
  1963. # attach_rule calls below and ship an assignment without the task's
  1964. # own rules — attach while draft, enqueue last.
  1965. act(auth, tasks_state["create"], {
  1966. "project_id": "1",
  1967. "title": "Rules dispatch",
  1968. "description": "Effective rule set rides the /start payload.",
  1969. "priority": "2",
  1970. })
  1971. rule_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1972. if t["title"] == "Rules dispatch"][0])
  1973. detail = task_state(auth, rule_task)
  1974. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Write Vala docs"))})
  1975. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  1976. enqueue_task(auth, rule_task)
  1977. detail = task_state(auth, rule_task)
  1978. check(sorted(r["name"] for r in detail["rules"]) == ["Use Invercargill", "Write Vala docs"],
  1979. "task page lists its attached rules")
  1980. check(wait_for(lambda: len(fake.start_payloads) > 0 or False,
  1981. timeout=30, what="/start push") is not None,
  1982. "dispatcher pushes the task to the fake saddle")
  1983. payload = fake.start_payloads[-1]
  1984. rule_names = [r["name"] for r in payload.get("rules", [])]
  1985. check(rule_names == ["Write Vala docs", "Use Invercargill", "Prefer meson", "Co-dev rule"],
  1986. "effective rules in /start: task, primary, co-developed order (%s)" % rule_names)
  1987. check(all(r.get("body") for r in payload.get("rules", [])),
  1988. "rules carry their bodies")
  1989. check("Reference rule" not in rule_names,
  1990. "reference project rules excluded")
  1991. detail = task_state(auth, rule_task)
  1992. act(auth, detail["rules"][0]["detach"], {})
  1993. check([r["name"] for r in task_state(auth, rule_task)["rules"]] == ["Use Invercargill"],
  1994. "detached task rule disappears")
  1995. rules_rows = slot_public(auth, "/rules", "rules")["rules"]
  1996. docs_row = [r for r in rules_rows if r["name"] == "Write Vala docs"][0]
  1997. act(auth, docs_row["update"], {"name": "Write Vala docs", "body": "Doc comments or bust."})
  1998. check(any(r["body"] == "Doc comments or bust."
  1999. for r in slot_public(auth, "/rules", "rules")["rules"]),
  2000. "rule edit saves the body")
  2001. check(wait_task_done(auth, rule_task, timeout=60) is not None,
  2002. "dispatched task completes against the fake daemon")
  2003. print("== feature 6: project notes + callback ==")
  2004. # Plan 10 phase 1: the shared saddle-callback token is gone —
  2005. # the per-saddle token authorises the callback endpoints.
  2006. callback_token = fake_token
  2007. check(callback_token.startswith("saddle-") and "saddle-callback-" not in callback_token,
  2008. "note callback authorised by the per-saddle token")
  2009. status, _ = saddle_api("POST", "/api/saddle/note", None,
  2010. {"project": "demo", "body": "x"})
  2011. check(status == 401, "note endpoint rejects a missing token")
  2012. status, _ = saddle_api("POST", "/api/saddle/note", "saddle-callback-not-real",
  2013. {"project": "demo", "body": "x"})
  2014. check(status == 401, "note endpoint rejects a wrong (legacy-style) token")
  2015. status, body = saddle_api("POST", "/api/saddle/note", callback_token,
  2016. {"task_id": rule_task, "project": "demo",
  2017. "body": "style.css tokens live in :root"})
  2018. check(status == 200 and body.get("ok") is True, "note accepted with the callback token")
  2019. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  2020. {"project": "no-such-project", "body": "x"})
  2021. check(status == 400, "unknown project rejected")
  2022. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  2023. {"project": "demo", "body": " "})
  2024. check(status == 400, "empty note body rejected")
  2025. project = slot_public(auth, "/projects/1", "project")
  2026. check(any("style.css tokens" in n["body"] and int(n["source_task_id"]) == rule_task
  2027. for n in project["notes"]),
  2028. "project page lists the note with its source task")
  2029. act(auth, [n for n in project["notes"] if "style.css tokens" in n["body"]][0]["delete"], {})
  2030. check(all("style.css tokens" not in n["body"]
  2031. for n in slot_public(auth, "/projects/1", "project")["notes"]),
  2032. "note deleted from the project page")
  2033. # /start payload: notes of primary + co-developed (not reference),
  2034. # oldest first; callback carries the configured base URL + token.
  2035. saddle_api("POST", "/api/saddle/note", callback_token,
  2036. {"project": "demo", "body": "note-one"})
  2037. saddle_api("POST", "/api/saddle/note", callback_token,
  2038. {"project": "demo", "body": "note-two"})
  2039. saddle_api("POST", "/api/saddle/note", callback_token,
  2040. {"project": "co", "body": "co-note"})
  2041. conn = db()
  2042. conn.execute("insert into project_notes (project_id, body, created_at)"
  2043. " values (?, 'ref-note-must-not-ship', strftime('%s','now'))", (ref_id,))
  2044. conn.commit()
  2045. conn.close()
  2046. task_id_tmp = create_queued(auth, {
  2047. "project_id": "1",
  2048. "title": "Notes dispatch",
  2049. "description": "Project notes ride the /start payload.",
  2050. "priority": "2",
  2051. })
  2052. check(wait_for(lambda: len(fake.start_payloads) >= 2 or False,
  2053. timeout=30, what="second /start push") is not None,
  2054. "dispatcher pushes the notes task")
  2055. payload = fake.start_payloads[-1]
  2056. notes = payload.get("project_notes", [])
  2057. check([n["body"] for n in notes] == ["note-one", "note-two", "co-note"],
  2058. "project_notes: primary + co-developed, oldest first (%s)" % [n["body"] for n in notes])
  2059. check(all(n.get("project") for n in notes)
  2060. and notes[2]["project"] == "co",
  2061. "project_notes carry the project name")
  2062. check("ref-note-must-not-ship" not in [n["body"] for n in notes],
  2063. "reference project notes excluded")
  2064. callback = payload.get("callback", {})
  2065. check(callback.get("base_url") == WEB and callback.get("token") == callback_token,
  2066. "callback carries the configured base URL and the minted token")
  2067. # entry cap: 30 of 33 candidates
  2068. conn = db()
  2069. for i in range(33):
  2070. conn.execute("insert into project_notes (project_id, body, created_at)"
  2071. " values (?, ?, strftime('%s','now'))", (1, "bulk-%02d" % i))
  2072. conn.commit()
  2073. conn.close()
  2074. create_queued(auth, {
  2075. "project_id": "1",
  2076. "title": "Entry cap dispatch",
  2077. "priority": "2",
  2078. })
  2079. check(wait_for(lambda: len(fake.start_payloads) >= 3 or False,
  2080. timeout=30, what="third /start push") is not None,
  2081. "dispatcher pushes the entry-cap task")
  2082. notes = fake.start_payloads[-1].get("project_notes", [])
  2083. check(len(notes) == 30 and notes[0]["body"] == "note-one" and notes[1]["body"] == "note-two",
  2084. "project_notes capped at 30 entries, oldest kept (%d)" % len(notes))
  2085. # char cap: the giant note is truncated so the total stays <= 20000
  2086. conn = db()
  2087. conn.execute("delete from project_notes where body like 'bulk-%' or body = 'co-note'")
  2088. conn.execute("insert into project_notes (project_id, body, created_at)"
  2089. " values (?, ?, strftime('%s','now'))", (1, "giant!" + "x" * 25000,))
  2090. conn.commit()
  2091. conn.close()
  2092. create_queued(auth, {
  2093. "project_id": "1",
  2094. "title": "Char cap dispatch",
  2095. "priority": "2",
  2096. })
  2097. check(wait_for(lambda: len(fake.start_payloads) >= 4 or False,
  2098. timeout=30, what="fourth /start push") is not None,
  2099. "dispatcher pushes the char-cap task")
  2100. notes = fake.start_payloads[-1].get("project_notes", [])
  2101. total = sum(len(n["body"]) for n in notes)
  2102. check(len(notes) == 3 and total == 20000 and notes[2]["body"].startswith("giant!"),
  2103. "project_notes char cap: head kept, giant truncated (entries=%d, chars=%d)"
  2104. % (len(notes), total))
  2105. print("== phase 2: pushed chunks -> raw log + terminal view ==")
  2106. # Wait for the last dispatch to finish so its pushes landed.
  2107. check(wait_task_done(auth, task_id_of("Char cap dispatch"), timeout=60) is not None,
  2108. "char-cap task completes")
  2109. conn = db()
  2110. raw_session = conn.execute(
  2111. "select s.id from sessions s join tasks t on t.id = s.task_id"
  2112. " where t.title = 'Char cap dispatch' order by s.id desc limit 1").fetchone()[0]
  2113. rows = conn.execute("select seq, chunk from session_raw_log where session_id = ?"
  2114. " order by seq", (raw_session,)).fetchall()
  2115. conn.close()
  2116. check(len(rows) >= 3, "session_raw_log captured the pushed chunks (%d)" % len(rows))
  2117. seqs = [r[0] for r in rows]
  2118. check(seqs == sorted(seqs) and len(set(seqs)) == len(seqs),
  2119. "pushed chunks stored once, seq strictly increasing")
  2120. text = "".join(r[1] for r in rows)
  2121. check(fake.PROMPT in text and "echo hello" in text and "hello" in text,
  2122. "pushed raw log keeps the prompt and echoed output byte-exact")
  2123. check("working-heartbeat" in text,
  2124. "the flush-timer heartbeat chunks keep arriving mid-round")
  2125. terminal = slot_public(auth, "/tasks/%d/terminal" % task_id_of("Char cap dispatch"),
  2126. "terminal")
  2127. check(terminal.get("has_raw_log") is True and int(terminal["session_id"]) == raw_session,
  2128. "terminal view selects raw rendering for the raw session")
  2129. # Old sessions (typed entries, no raw rows) keep the fallback view
  2130. # (a dedicated fixture task: its only session is the legacy one,
  2131. # so the terminal view cannot prefer a dispatched raw session).
  2132. conn = db()
  2133. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  2134. " values (1, 'Legacy terminal task', 'working', 5, strftime('%s','now'))")
  2135. legacy_task = conn.execute("select max(id) from tasks").fetchone()[0]
  2136. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  2137. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  2138. (legacy_task, fake_id))
  2139. conn.commit()
  2140. legacy_session = conn.execute("select max(id) from sessions").fetchone()[0]
  2141. conn.execute("insert into session_commands (session_id, command_text, output_text,"
  2142. " type, started_at) values (?, 'ls', 'old-output', 'command',"
  2143. " strftime('%s','now'))", (legacy_session,))
  2144. conn.commit()
  2145. conn.close()
  2146. legacy = slot_public(auth, "/tasks/%d/terminal" % legacy_task, "terminal")
  2147. check(legacy.get("has_raw_log") is False,
  2148. "legacy session falls back to the entry-type terminal view")
  2149. request = urllib.request.Request(WEB + "/terminal-stream/%d" % raw_session)
  2150. with urllib.request.urlopen(request, timeout=15) as stream:
  2151. raw_events = []
  2152. deadline = time.monotonic() + 8
  2153. while time.monotonic() < deadline and len(raw_events) < 3:
  2154. line = stream.readline().decode().strip()
  2155. if not line.startswith("data: ") or line == "data: ping":
  2156. continue
  2157. event = json.loads(line[6:])
  2158. if event.get("type") == "raw":
  2159. raw_events.append(event)
  2160. check(len(raw_events) >= 3 and raw_events[0]["text"] == fake.PROMPT
  2161. and raw_events[0]["seq"] < raw_events[1]["seq"],
  2162. "terminal stream serves pushed chunks in seq order (prompt first)")
  2163. print("== phase 2: chunks/results ingestion — auth, idempotency ==")
  2164. # Token auth on both push channels (plan 10: the per-saddle
  2165. # bearer authorises every daemon->web call).
  2166. status, _ = saddle_api("POST", "/api/saddle/chunks", None,
  2167. {"session_id": raw_session, "chunks": []})
  2168. check(status == 401, "chunks endpoint rejects a missing token")
  2169. status, _ = saddle_api("POST", "/api/saddle/results", "saddle-bogus-token",
  2170. {"session_id": raw_session, "state": "working"})
  2171. check(status == 401, "results endpoint rejects a wrong token")
  2172. status, _ = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2173. {"session_id": 99999, "chunks": []})
  2174. check(status == 400, "chunks for an unknown session rejected")
  2175. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2176. {"session_id": raw_session, "state": "done"})
  2177. check(status == 200, "the owning saddle's session accepts its results")
  2178. # Pushed chunk idempotency: re-pushing a batch (the outbox's
  2179. # at-least-once redelivery after a lost response) consumes the
  2180. # duplicates and stores only the tail.
  2181. conn = db()
  2182. before = conn.execute("select count(*) from session_raw_log where session_id = ?",
  2183. (raw_session,)).fetchone()[0]
  2184. conn.close()
  2185. redelivery = [{"seq": r[0], "text": r[1]} for r in rows[:3]]
  2186. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2187. {"session_id": raw_session, "chunks": redelivery})
  2188. check(status == 200 and body.get("ok") is True and int(body.get("stored") or 0) == 0,
  2189. "a fully-duplicate batch stores nothing (duplicates consumed)")
  2190. fresh = [{"seq": 9000, "text": "late-flush\r\n"},
  2191. {"seq": 9001, "text": ""}] # truly empty text: no row
  2192. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2193. {"session_id": raw_session, "chunks": fresh})
  2194. check(status == 200 and int(body.get("stored") or 0) == 1,
  2195. "a partial-redelivery batch stores only the new chunks")
  2196. conn = db()
  2197. after = conn.execute("select count(*) from session_raw_log where session_id = ?",
  2198. (raw_session,)).fetchone()[0]
  2199. empty_row = conn.execute(
  2200. "select count(*) from session_raw_log where session_id = ? and seq = 9001",
  2201. (raw_session,)).fetchone()[0]
  2202. conn.close()
  2203. check(after == before + 1 and empty_row == 0,
  2204. "redelivered chunks never duplicate rows; empty text stores nothing")
  2205. # Pushed entries: today's OutputEntry shape with the daemon's
  2206. # global entry ids — a redelivered results push stores its
  2207. # entries exactly once.
  2208. def command_rows(session):
  2209. conn = db()
  2210. try:
  2211. return conn.execute(
  2212. "select command_text, type from session_commands"
  2213. " where session_id = ? order by id", (session,)).fetchall()
  2214. finally:
  2215. conn.close()
  2216. entries = [{"id": 8101, "command": "sed -n 1p README.md", "output": "# demo",
  2217. "exit_code": 0, "type": "command", "timestamp": "2026-09-06T00:00:00Z"}]
  2218. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2219. {"session_id": raw_session, "state": "working",
  2220. "entries": entries})
  2221. check(status == 200, "entries push accepted")
  2222. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2223. {"session_id": raw_session, "state": "working",
  2224. "entries": entries})
  2225. check(status == 200, "redelivered entries push accepted (at-least-once)")
  2226. stored = command_rows(raw_session)
  2227. check(len([r for r in stored if r[0] == "sed -n 1p README.md"]) == 1,
  2228. "redelivered entries store exactly once (daemon-global dedup)")
  2229. # The retired daemon routes 404 (phase 2 deleted /output, /log
  2230. # and /start serving) — and the web app never calls them.
  2231. for method, path in (("GET", "/output?since=0"), ("GET", "/log?since=0"),
  2232. ("POST", "/start")):
  2233. request = urllib.request.Request(
  2234. "http://127.0.0.1:%d%s" % (fake.port, path),
  2235. data=b"{}" if method == "POST" else None, method=method)
  2236. try:
  2237. urllib.request.urlopen(request, timeout=5)
  2238. gone = False
  2239. except urllib.error.HTTPError as error:
  2240. gone = error.code == 404
  2241. check(gone, "the fake daemon's %s %s is deleted (404)" % (method, path))
  2242. with open(os.path.join(WORK, "app.log")) as handle:
  2243. app_log = handle.read()
  2244. check("Saddle output request" not in app_log and "Saddle log request" not in app_log,
  2245. "the web never polls /output or /log anymore")
  2246. print("== capabilities: tag-based routing ==")
  2247. saddles_state = slot_public(auth, "/saddles", "saddles")
  2248. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2249. act(auth, saddles_state["create_capability"], {"name": "bigmem"})
  2250. saddles_state = slot_public(auth, "/saddles", "saddles")
  2251. caps = {c["name"]: c for c in saddles_state["capabilities"]}
  2252. check(len(caps) == 2 and all(int(c["saddle_count"]) == 0 and int(c["task_count"]) == 0
  2253. for c in caps.values()),
  2254. "capabilities created and listed with zero usage")
  2255. fake_card = saddle_card(auth, "fake-saddle")
  2256. check(fake_card["capabilities"] == [],
  2257. "saddle card starts with no capability chips")
  2258. # A task requiring 'gpu' waits while the only idle saddle lacks it;
  2259. # a later task without requirements still dispatches (skip-and-continue).
  2260. tasks_state = slot_public(auth, "/tasks", "tasks")
  2261. task_id_tmp = create_queued(auth, {
  2262. "project_id": "1",
  2263. "title": "GPU task",
  2264. "priority": "2",
  2265. })
  2266. gpu_task = task_id_tmp
  2267. detail = task_state(auth, gpu_task)
  2268. act(auth, detail["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  2269. check(wait_for(lambda: [c["name"] for c in
  2270. task_state(auth, gpu_task)["capabilities"]] == ["gpu"]
  2271. or False, timeout=90, what="capability attached") is not None,
  2272. "task page lists the required capability")
  2273. detail = task_state(auth, gpu_task)
  2274. # The only idle saddle lacks the tag, so the queue flags the wait
  2275. # (read before any other task claims the idle saddle). The state is
  2276. # stable until the any-saddle task below dispatches — poll for it
  2277. # rather than sampling once (a single read under load once sampled
  2278. # the row before the attach's pulse settled).
  2279. check(wait_for(lambda: (lambda row: row["status"] == "queued"
  2280. and row["capabilities"] == ["gpu"]
  2281. and row.get("waiting_for_saddle") is True)(
  2282. [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2283. if int(t["id"]) == gpu_task][0]) or False,
  2284. timeout=20, what="waiting flag") is not None,
  2285. "queue row shows the waiting task with its tag and wait flag")
  2286. task_id_tmp = create_queued(auth, {
  2287. "project_id": "1",
  2288. "title": "Any-saddle task",
  2289. "priority": "3",
  2290. })
  2291. any_task = task_id_tmp
  2292. check(wait_for(lambda: task_state(auth, any_task).get("status") != "queued" or False,
  2293. timeout=30, what="uncapable task dispatches") is not None,
  2294. "task without requirements dispatches past the waiting task")
  2295. def capability_wait_logged():
  2296. with open(os.path.join(WORK, "app.log")) as handle:
  2297. app_log = handle.read()
  2298. return "waits for a capable saddle" in app_log and "requires: gpu" in app_log
  2299. check(wait_for(capability_wait_logged, timeout=90,
  2300. what="capability wait log") is not None,
  2301. "dispatcher logs the capability wait")
  2302. # Attaching the tag to the saddle releases the task.
  2303. fake_card = saddle_card(auth, "fake-saddle")
  2304. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  2305. fake_card = saddle_card(auth, "fake-saddle")
  2306. check([c["name"] for c in fake_card["capabilities"]] == ["gpu"],
  2307. "saddle card shows the attached chip")
  2308. check(wait_task_done(auth, gpu_task, timeout=60) is not None,
  2309. "task dispatches once the saddle carries the required tag")
  2310. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2311. if int(t["id"]) == gpu_task][0]
  2312. check(queue.get("waiting_for_saddle") is not True,
  2313. "wait flag clears once dispatched")
  2314. # Multi-tag: gpu + bigmem required, only gpu carried → waits; adding
  2315. # bigmem completes the superset. Both requirements ride the create
  2316. # form (atomic — attaching them one at a time would race a tick
  2317. # into dispatching on the partial set).
  2318. task_id_tmp = create_queued(auth, {
  2319. "project_id": "1",
  2320. "title": "Big task",
  2321. "priority": "2",
  2322. "capability_id": [str(int(caps["gpu"]["id"])), str(int(caps["bigmem"]["id"]))],
  2323. })
  2324. big_task = task_id_tmp
  2325. check(wait_for(lambda: ([t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2326. if int(t["id"]) == big_task][0].get("waiting_for_saddle")
  2327. is True) or False, timeout=30, what="big task waits") is not None,
  2328. "task waits when the saddle's tags are not a superset")
  2329. fake_card = saddle_card(auth, "fake-saddle")
  2330. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["bigmem"]["id"]))})
  2331. check(wait_task_done(auth, big_task, timeout=60) is not None,
  2332. "task dispatches once the superset is complete")
  2333. # Detach a requirement (on a draft — capabilities lock once a
  2334. # worker has the job); delete a capability everywhere.
  2335. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2336. "project_id": "1",
  2337. "title": "Detach probe task",
  2338. "priority": "4",
  2339. "capability_id": [str(int(caps["gpu"]["id"])), str(int(caps["bigmem"]["id"]))],
  2340. })
  2341. detach_probe = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2342. if t["title"] == "Detach probe task"][0])
  2343. act(auth, [c for c in task_state(auth, detach_probe)["capabilities"]
  2344. if c["name"] == "bigmem"][0]["detach"], {})
  2345. check([c["name"] for c in task_state(auth, detach_probe)["capabilities"]] == ["gpu"],
  2346. "detached requirement disappears from the task")
  2347. bigmem_row = [c for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2348. if c["name"] == "bigmem"][0]
  2349. act(auth, bigmem_row["delete"], {})
  2350. saddles_state = slot_public(auth, "/saddles", "saddles")
  2351. check(all(c["name"] != "bigmem" for c in saddles_state["capabilities"]),
  2352. "deleted capability gone from the catalogue")
  2353. check([c["name"] for c in task_state(auth, big_task)["capabilities"]] == ["gpu"],
  2354. "deleting a capability drops its task requirements")
  2355. check(all(c["name"] != "bigmem"
  2356. for c in saddle_card(auth, "fake-saddle")["capabilities"]),
  2357. "deleting a capability drops it from saddles")
  2358. print("== B4: required capabilities on the create form ==")
  2359. tasks_state = slot_public(auth, "/tasks", "tasks")
  2360. gpu_option = [o for o in tasks_state.get("capability_options", [])
  2361. if o["name"] == "gpu"][0]
  2362. check(len(tasks_state.get("capability_options", [])) >= 1,
  2363. "queue page offers capability options in the create form")
  2364. conn = db()
  2365. before = conn.execute("select count(*) from tasks").fetchone()[0]
  2366. conn.close()
  2367. act(auth, tasks_state["create"], {
  2368. "project_id": "1",
  2369. "title": "Bad cap task",
  2370. "capability_id": [gpu_option["id"], "999"],
  2371. })
  2372. conn = db()
  2373. after = conn.execute("select count(*) from tasks").fetchone()[0]
  2374. conn.close()
  2375. check(after == before, "unknown capability id rejects the create")
  2376. task_id_tmp = create_queued(auth, {
  2377. "project_id": "1",
  2378. "title": "Cap-on-create task",
  2379. "capability_id": [gpu_option["id"]],
  2380. })
  2381. cap_create = task_id_tmp
  2382. detail = task_state(auth, cap_create)
  2383. check([c["name"] for c in detail["capabilities"]] == ["gpu"],
  2384. "capabilities from the create form land on the task")
  2385. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2386. if int(t["id"]) == cap_create][0]
  2387. check(queue["capabilities"] == ["gpu"],
  2388. "queue row shows the created task's requirements")
  2389. # The waiting flag must hold it back until the capable saddle frees
  2390. # up (the fake saddle still carries gpu from the routing checks).
  2391. check(queue.get("waiting_for_saddle") is not True,
  2392. "capable saddle available: no wait flag on the new task")
  2393. # Drain barrier: the cap task must be CLAIMED before the flaky
  2394. # arc arms fail_next (under parallel-shard load the dispatch tick
  2395. # can lag task creation; an unclaimed predecessor would consume
  2396. # the one-shot failure flag instead of the flaky task).
  2397. check(wait_for(lambda: task_state(auth, cap_create).get("status")
  2398. in ("working", "done", "failed") or False,
  2399. timeout=60, what="cap task claimed") is not None,
  2400. "the capable task is claimed before the flaky arc starts")
  2401. print("== retry + resume ==")
  2402. # A daemon-side failure fails the task with its explanation.
  2403. fake.fail_next = True
  2404. task_id_tmp = create_queued(auth, {
  2405. "project_id": "1",
  2406. "title": "Flaky task",
  2407. "priority": "2",
  2408. })
  2409. flaky = task_id_tmp
  2410. check(wait_for(lambda: task_state(auth, flaky).get("status") == "failed" or False,
  2411. timeout=90, what="flaky task fails") is not None,
  2412. "daemon failure fails the task")
  2413. detail = task_state(auth, flaky)
  2414. check("bash -n rejected" in (detail.get("summary") or ""),
  2415. "failure summary shows the daemon's explanation")
  2416. # Retry: summary moves into a comment and clears, task requeues,
  2417. # history stays, and the re-dispatch restores the workspace.
  2418. comments_before = len(detail.get("comments", []))
  2419. progress_before = len(detail.get("progress", []))
  2420. act(auth, detail["retry"], {})
  2421. detail = task_state(auth, flaky)
  2422. check(detail["status"] == "queued" and (detail.get("summary") or "") == "",
  2423. "retry requeues the task and clears the stale summary")
  2424. check(any("bash -n rejected" in c["body"] and c["author"] == "agent"
  2425. for c in detail["comments"]),
  2426. "failure explanation kept as an agent comment (author 'agent')")
  2427. check(any(c["body"] == "Task retried by user" and c["author"] == "system"
  2428. and c.get("is_system") for c in detail["comments"]),
  2429. "retry lands its audit comment as a system row (never an agent row)")
  2430. check(len(detail["comments"]) >= comments_before + 1,
  2431. "retry keeps the comment history")
  2432. pushes_before = len([p for p in fake.start_payloads
  2433. if int(p.get("task", {}).get("id") or 0) == flaky])
  2434. check(wait_for(lambda: len([p for p in fake.start_payloads
  2435. if int(p.get("task", {}).get("id") or 0) == flaky])
  2436. > pushes_before or False, timeout=90,
  2437. what="flaky task re-dispatched") is not None,
  2438. "retried task dispatches again")
  2439. # The resumed arc surfaces on the next /status read — in the
  2440. # push world that is the operator's manual refresh.
  2441. act(auth, saddle_card(auth, "fake-saddle")["refresh"], {})
  2442. check(wait_task_done(auth, flaky, timeout=60) is not None,
  2443. "retried task completes on the restored workspace")
  2444. detail = task_state(auth, flaky)
  2445. check(any("restored the session context" in c["body"]
  2446. and c["author"] == "system" and c.get("is_system")
  2447. for c in detail.get("comments", [])),
  2448. "daemon resume reported on the first status after the restore")
  2449. check(all("restored the session context" not in p["summary"]
  2450. for p in detail.get("progress", [])),
  2451. "the resume note stays OUT of the progress feed (F8: status is not progress)")
  2452. # Manual resume: a task stuck working on an offline saddle.
  2453. task_id_tmp = create_queued(auth, {
  2454. "project_id": "1",
  2455. "title": "Stuck task",
  2456. "priority": "2",
  2457. })
  2458. stuck = task_id_tmp
  2459. check(wait_for(lambda: task_state(auth, stuck).get("status") == "working" or False,
  2460. timeout=60, what="stuck task starts working") is not None,
  2461. "stuck task reaches working")
  2462. # Deterministic claim for the resume leg below: the round's end,
  2463. # the refresh probe AND the dispatcher's wake for the requeued task
  2464. # all trigger self-asks that could steal it — freeze every trigger
  2465. # until the manual ask below has made the claim.
  2466. fake.ask_on_terminal = False
  2467. fake.ask_on_idle_status = False
  2468. fake.ask_on_wake = False
  2469. fake.settle_asks()
  2470. conn = db()
  2471. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  2472. conn.commit()
  2473. conn.close()
  2474. detail = task_state(auth, stuck)
  2475. check(detail.get("resume_available") is True,
  2476. "task page offers resume while its saddle is offline")
  2477. # The resume POSTs task-update cancel to the daemon; the abort
  2478. # handler fires an ungated re-ask that would race the manual claim
  2479. # below — slow it past the manual ask (the knob the slow-ask
  2480. # regression uses).
  2481. fake.ask_delay = 5.0
  2482. act(auth, detail["resume"], {})
  2483. detail = task_state(auth, stuck)
  2484. check(detail["status"] == "queued",
  2485. "manual resume requeues the stuck task")
  2486. check(any(c["body"] == "Saddle became unreachable; task requeued"
  2487. and c["author"] == "system" and c.get("is_system")
  2488. for c in detail["comments"]),
  2489. "manual resume lands the interruption comment as a system row")
  2490. check(all(s["status"] == "offline"
  2491. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  2492. "saddle stays offline after the manual requeue")
  2493. # Bringing the saddle back lets the requeued task resume and finish.
  2494. fake.state = "idle"
  2495. fake_card = saddle_card(auth, "fake-saddle")
  2496. act(auth, fake_card["refresh"], {})
  2497. check(any(s["status"] == "idle"
  2498. for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2499. if s["name"] == "fake-saddle"),
  2500. "refreshed saddle returns idle")
  2501. # The refreshed daemon is idle-awake: it asks (the real loop's
  2502. # own ask; driven directly for determinism — every self-ask trigger
  2503. # is frozen and the abort re-ask is slowed past it; joining that
  2504. # delayed thread here would fire its ask first, so it is left to
  2505. # sleep out the rest of the bundle).
  2506. status, payload = fake.ask_now()
  2507. fake.ask_on_idle_status = True
  2508. fake.ask_on_terminal = True
  2509. fake.ask_on_wake = True
  2510. fake.ask_delay = 0.0
  2511. check(status == 200, "the refreshed daemon's ask claims the requeued task")
  2512. check(wait_task_done(auth, stuck, timeout=60) is not None,
  2513. "requeued task resumes on the refreshed saddle and completes")
  2514. # =============================================================================
  2515. # Bundle: subtasks — the plan-12 task graph: plain-task parking (no
  2516. # subtask events exist to resume it), the DELETED subtask machinery's
  2517. # verbatim refusals, and the goal agent's task CLI in depth
  2518. # (capabilities, ownership, the daemon's task-reading API, the
  2519. # goal-run block answered from the task page).
  2520. # =============================================================================
  2521. def bundle_subtasks(ctx):
  2522. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2523. app = ctx.app
  2524. # A hold tag nothing carries: goal tasks created with it stay
  2525. # queued (a stable parked agent) until released at the settle.
  2526. saddles_state = slot_public(auth, "/saddles", "saddles")
  2527. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2528. gpu_cap_id = [c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2529. if c["name"] == "gpu"][0]
  2530. def goal_state(goal_id):
  2531. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  2532. def create_goal_row(fields):
  2533. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  2534. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  2535. if g["title"] == fields["title"]]
  2536. return int(rows[0]["id"])
  2537. print("== B7: plain-task parking stays put (no subtask events) ==")
  2538. fake.suspend_on_title = "Suspend plain"
  2539. pushes_before = len(fake.start_payloads)
  2540. plain = create_queued(auth, {
  2541. "project_id": "1",
  2542. "title": "Suspend plain",
  2543. "priority": "2",
  2544. })
  2545. check(wait_for(lambda: task_state(auth, plain).get("status") == "suspended"
  2546. or False, timeout=60, what="plain task parks") is not None,
  2547. "daemon 'suspended' state parks the task")
  2548. detail = task_state(auth, plain)
  2549. check(detail.get("display") == "parked",
  2550. "a parked plain task displays as parked (%s)" % detail.get("display"))
  2551. check(any(s["status"] == "idle"
  2552. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  2553. "suspension frees the saddle")
  2554. first_push = fake.start_payloads[pushes_before]
  2555. check(first_push.get("kind") == "task" and first_push.get("creator") == "human"
  2556. and first_push.get("mode") == "implement",
  2557. "the /start payload carries the plan-12 identity triplet (kind/creator/mode)")
  2558. check("subtasks" not in first_push and "parent" not in first_push,
  2559. "the plan-12 payload drops the subtasks/parent members")
  2560. # Other tasks finishing must NOT resume a parked plain task (the
  2561. # subtask-event channel is gone; only goal events resume goal runs).
  2562. conn = db()
  2563. conn.execute("insert into tasks (project_id, title, status, priority, summary,"
  2564. " completed_at, created_at) values (1, 'Unrelated finisher', 'done',"
  2565. " 5, 'finished loudly', strftime('%s','now','+1 second'),"
  2566. " strftime('%s','now'))")
  2567. conn.commit()
  2568. conn.close()
  2569. check(quiet_window(quiet_seconds(),
  2570. lambda: task_state(auth, plain)["status"] == "suspended",
  2571. "plain park survives unrelated finishes"),
  2572. "a parked plain task never resumes on other tasks' events")
  2573. print("== the deleted machinery refuses, verbatim ==")
  2574. status, body = saddle_api("POST", "/api/saddle/subtask", fake_token,
  2575. {"parent_task_id": plain, "title": "ghost"})
  2576. check(status == 404,
  2577. "the /api/saddle/subtask callback route is gone (404)")
  2578. conn = db()
  2579. plain_session = conn.execute(
  2580. "select id from sessions where task_id = ? and ended_at is null",
  2581. (plain,)).fetchone()[0]
  2582. conn.close()
  2583. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2584. {"type": "subtask", "session_id": plain_session,
  2585. "data": {"title": "Ghost child"}})
  2586. check(status == 400 and "subtask" in (body.get("error") or "")
  2587. and "gone" in (body.get("error") or ""),
  2588. "the 'subtask' update type errors verbatim (%s)" % body.get("error"))
  2589. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2590. {"type": "plan", "session_id": plain_session,
  2591. "data": {"plan": "# nope"}})
  2592. check(status == 400 and "plan" in (body.get("error") or ""),
  2593. "the task-level 'plan' update type errors verbatim (%s)" % body.get("error"))
  2594. # The daemon's task CLI: no parent/plan members; goal context instead.
  2595. status, body = saddle_api("GET", "/api/saddle/task/%d" % plain, fake_token)
  2596. check(status == 200 and "plan" not in body.get("task", {})
  2597. and "parent_task_id" not in body.get("task", {})
  2598. and "goal_id" in body.get("task", {}),
  2599. "the task CLI detail drops parent/plan and carries goal_id")
  2600. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", fake_token)
  2601. check(status == 200 and all("parent_task_id" not in t and "goal_id" in t
  2602. for t in body.get("tasks", [])),
  2603. "the task CLI list drops parent_task_id and carries goal_id")
  2604. # Settle the parked plain task: nothing will resume it — cancel it.
  2605. act(auth, task_state(auth, plain)["cancel"], {})
  2606. check(wait_for(lambda: task_state(auth, plain)["status"] == "failed" or False,
  2607. timeout=30, what="parked plain task cancelled") is not None,
  2608. "the parked plain task cancels (the human cleanup path)")
  2609. print("== the goal agent's task CLI in depth ==")
  2610. goal = create_goal_row({"project_id": "1", "title": "Sequencing goal",
  2611. "brief": "Fan tasks out with the CLI.",
  2612. "branch_name": "goal/sequence"})
  2613. fake.goal_script = [("plan", "# Plan\n\n1. Fan out")]
  2614. act(auth, goal_state(goal)["start"], {})
  2615. check(wait_for(lambda: goal_state(goal)["status"] == "plan_review" or False,
  2616. timeout=60, what="sequencing goal plans") is not None,
  2617. "the sequencing goal reaches plan review")
  2618. fake.goal_script = [("suspend",)]
  2619. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  2620. {"answer": "Plan approved. Proceed with implementation."})
  2621. conn = db()
  2622. run_task = conn.execute(
  2623. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  2624. (goal,)).fetchone()[0]
  2625. agent_session = conn.execute(
  2626. "select id from sessions where task_id = ? and ended_at is null",
  2627. (run_task,)).fetchone()[0]
  2628. conn.close()
  2629. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  2630. or False, timeout=60, what="sequencing agent parks") is not None,
  2631. "the sequencing goal agent parks")
  2632. # Create with capabilities: attached until assignment (the hold
  2633. # keeps the task queued), mandate + mode stored, ephemeral branch.
  2634. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  2635. "session_id": agent_session, "title": "Held worker",
  2636. "mandate": "Do the held work.", "mode": "review",
  2637. "capabilities": ["gpu"]})
  2638. check(status == 200 and body.get("ok") is True,
  2639. "task create with a capability tag succeeds")
  2640. held = int(body["task_id"])
  2641. detail = task_state(auth, held)
  2642. check(detail["status"] == "draft" and detail["mode"] == "review",
  2643. "the held worker drafts with its mode")
  2644. check([c["name"] for c in detail.get("capabilities", [])] == ["gpu"],
  2645. "the capability attaches to the created task")
  2646. check(detail["task_branch"] == "task/%d-%d" % (goal, held)
  2647. and detail["branch_from"] == "goal/sequence",
  2648. "the CLI task's ephemeral branch pair is stored")
  2649. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  2650. "session_id": agent_session, "task_id": held})
  2651. check(status == 200, "the held worker enqueues")
  2652. check(quiet_window(3, lambda: task_state(auth, held)["status"] == "queued",
  2653. "unsatisfiable capability holds dispatch"),
  2654. "the unsatisfiable capability holds the queued worker (never assigned)")
  2655. queue_row = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2656. if int(t["id"]) == held][0]
  2657. check(queue_row.get("waiting_for_saddle") is True,
  2658. "the queue annotates the held worker as waiting for a saddle")
  2659. # The human edit path: goal tasks never carry enqueue-after (the
  2660. # field is human-tasks-only — the update silently ignores it).
  2661. act(auth, task_state(auth, held)["update"], {
  2662. "priority": "4", "enqueue_after_task_id": str(held - 1)})
  2663. check(task_state(auth, held).get("enqueue_after_task_id") in (None, 0, "0"),
  2664. "a goal task ignores the auto-enqueue-after field on edit")
  2665. # Ownership: the same saddle's goal agent cannot touch another
  2666. # goal's task; a plain session is not a goal-agent identity.
  2667. other_goal = create_goal_row({"project_id": "1", "title": "Other goal",
  2668. "brief": "b", "branch_name": "goal/other",
  2669. "priority": "9"})
  2670. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token,
  2671. {"session_id": agent_session, "title": "x",
  2672. "mandate": "m"})
  2673. scope_task = int(body["task_id"])
  2674. check(int(task_state(auth, scope_task)["goal_id"] or 0) == goal,
  2675. "the callback scopes task creation to its own goal")
  2676. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token,
  2677. {"session_id": agent_session, "task_id": scope_task})
  2678. check(status == 200, "the owned draft deletes")
  2679. check(not any(t["id"] == scope_task
  2680. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  2681. "the deleted task is gone from the queue")
  2682. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  2683. {"session_id": agent_session, "task_id": plain})
  2684. check(status == 400 and "does not belong to your goal" in (body.get("error") or ""),
  2685. "the goal agent cannot enqueue a standalone task")
  2686. # The daemon's task CLI detail carries the goal context.
  2687. status, body = saddle_api("GET", "/api/saddle/task/%d" % held, fake_token)
  2688. check(status == 200
  2689. and int(body["task"].get("goal_id") or 0) == goal
  2690. and body["task"].get("goal_title") == "Sequencing goal",
  2691. "the task CLI detail names the owning goal")
  2692. print("== the goal-run block answers from the task page (C1) ==")
  2693. # A question block raised in goal context lands on the run task's
  2694. # own row; the TASK page's answer action funnels into the one
  2695. # goal answer path and resumes the agent with the verdict riding
  2696. # the allocation (the goal page shares the path).
  2697. fake.goal_script = [("question", "Which harness: pytest or vitest?",
  2698. ["pytest", "vitest"])]
  2699. conn = db()
  2700. # Plan 15 C3: a terminal transition (a done task row newer than
  2701. # the watermark) is the resume signal — no event rows exist.
  2702. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  2703. " priority, completed_at, created_at) values (1, ?, 'task',"
  2704. " 'Nudge', 'done', 5,"
  2705. " strftime('%s','now'),"
  2706. " strftime('%s','now','-30 seconds'))", (goal,))
  2707. conn.commit()
  2708. conn.close()
  2709. check(wait_for(lambda: task_state(auth, run_task)["status"] == "blocked"
  2710. or False, timeout=60, what="goal block parks the run") is not None,
  2711. "a goal question parks the run task on its own block row")
  2712. run_detail = task_state(auth, run_task)
  2713. question_block = [b for b in run_detail["blocks"]
  2714. if b["block_type"] == "question"][0]
  2715. check(question_block.get("question") == "Which harness: pytest or vitest?",
  2716. "the run task's block carries the goal question verbatim")
  2717. goal_block_ids = [int(b["id"]) for b in goal_state(goal)["blocks"]
  2718. if b.get("block_type") == "question"]
  2719. check(goal_block_ids == [int(question_block["id"])],
  2720. "the goal page's card is the SAME row (no dual-row pair)")
  2721. act(auth, question_block["answer_action"], {"answer": "pytest"})
  2722. fake.goal_script = [("suspend",)]
  2723. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  2724. or False, timeout=60, what="answered block resumes the agent")
  2725. is not None,
  2726. "the answered block resumes the goal agent")
  2727. answered = [b for b in task_state(auth, run_task)["blocks"]
  2728. if b["block_type"] == "question"][0]
  2729. check(answered.get("answer") == "pytest",
  2730. "the verdict is stored on the single block row")
  2731. print("== settle: release the hold and let the shard drain ==")
  2732. # Drop the hold tag so the held worker can dispatch and complete;
  2733. # the parked agent resumes on its completion, re-parks (script),
  2734. # and the shard shuts down with an empty queue.
  2735. act(auth, task_state(auth, held)["capabilities"][0]["detach"], {})
  2736. check(wait_task_done(auth, held, timeout=90) is not None,
  2737. "the released held worker completes")
  2738. check(wait_for(lambda: any(e["kind"] == "task-done" and int(e["task_id"]) == held
  2739. for e in goal_state(goal)["events"]) or False,
  2740. timeout=30, what="narrative hears the held worker") is not None,
  2741. "the narrative records the held worker's completion")
  2742. act(auth, goal_state(goal)["cancel"], {})
  2743. check(wait_for(lambda: goal_state(goal)["status"] == "cancelled" or False,
  2744. timeout=30, what="sequencing goal cancelled") is not None,
  2745. "the sequencing goal cancels (the shard's cleanup path)")
  2746. # =============================================================================
  2747. # Bundle: lineage — the plan-12 goal lineage: goal context on worker
  2748. # dispatches (read-only reference + ephemeral branch), the daemon's
  2749. # task-reading API (goal members, no parent/plan), and the goal
  2750. # agent's workspace affinity while parked.
  2751. # =============================================================================
  2752. def bundle_lineage(ctx):
  2753. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2754. app = ctx.app
  2755. r4_token = fake_token
  2756. # gpu exists only as a hold (no saddle carries it): the held goal
  2757. # worker stays queued until the release loop lifts it.
  2758. saddles_state = slot_public(auth, "/saddles", "saddles")
  2759. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2760. def goal_state(goal_id):
  2761. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  2762. def create_goal_row(fields):
  2763. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  2764. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  2765. if g["title"] == fields["title"]]
  2766. return int(rows[0]["id"])
  2767. goal = create_goal_row({"project_id": "1", "title": "Lineage goal",
  2768. "brief": "Carry the goal lineage.",
  2769. "branch_name": "goal/lineage"})
  2770. fake.goal_script = [("plan", "# Lineage plan\n\n1. Fan out\n2. Verify")]
  2771. act(auth, goal_state(goal)["start"], {})
  2772. check(wait_for(lambda: goal_state(goal)["status"] == "plan_review" or False,
  2773. timeout=60, what="lineage goal plans") is not None,
  2774. "the lineage goal reaches plan review")
  2775. fake.goal_script = [("suspend",)]
  2776. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  2777. {"answer": "Plan approved. Proceed with implementation."})
  2778. conn = db()
  2779. auto_parent = conn.execute(
  2780. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  2781. (goal,)).fetchone()[0]
  2782. agent_session = conn.execute(
  2783. "select id from sessions where task_id = ? and ended_at is null",
  2784. (auto_parent,)).fetchone()[0]
  2785. conn.close()
  2786. check(wait_for(lambda: task_state(auth, auto_parent)["status"] == "suspended"
  2787. or False, timeout=60, what="lineage goal agent parks") is not None,
  2788. "the lineage goal agent parks")
  2789. # Two workers under the goal: one free, one held by the gpu tag.
  2790. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2791. "session_id": agent_session, "title": "Auto child",
  2792. "mandate": "build the widget", "mode": "implement"})
  2793. auto_child = int(body["task_id"])
  2794. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2795. "session_id": agent_session, "title": "Auto grandchild",
  2796. "mandate": "verify the widget", "mode": "test",
  2797. "capabilities": ["gpu"]})
  2798. auto_grand = int(body["task_id"])
  2799. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2800. "session_id": agent_session, "title": "Wire the flange",
  2801. "description": "torque to spec"})
  2802. check(status == 400 and "mandate is required" in (body.get("error") or ""),
  2803. "task create without a mandate errors verbatim (%s)" % body.get("error"))
  2804. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2805. "session_id": agent_session, "title": "Wire the flange",
  2806. "mandate": "torque to spec"})
  2807. flange_task = int(body["task_id"])
  2808. for held in (auto_child, auto_grand, flange_task):
  2809. saddle_api("POST", "/api/saddle/task/enqueue", r4_token,
  2810. {"session_id": agent_session, "task_id": held})
  2811. check(wait_for(lambda: task_state(auth, auto_child)["status"] in
  2812. ("queued", "assigned", "working", "done") or False,
  2813. timeout=30, what="free goal worker dispatches") is not None,
  2814. "the free goal worker dispatches")
  2815. check(quiet_window(3, lambda: task_state(auth, auto_grand)["status"] == "queued",
  2816. "held goal worker stays queued"),
  2817. "the gpu-held goal worker stays queued")
  2818. # A goal worker's dispatch carries the read-only goal context.
  2819. lineage_push = [p for p in fake.start_payloads
  2820. if int(p.get("task", {}).get("id") or 0) == auto_child][-1]
  2821. goal_ctx = lineage_push.get("goal") or {}
  2822. check(int(goal_ctx.get("id") or 0) == goal
  2823. and goal_ctx.get("branch") == "goal/lineage"
  2824. and "Carry the goal lineage." in goal_ctx.get("brief", "")
  2825. and "# Lineage plan" in goal_ctx.get("plan", ""),
  2826. "the worker dispatch carries the goal context (brief + approved plan)")
  2827. check(lineage_push.get("ephemeral_branch") == "task/%d-%d" % (goal, auto_child)
  2828. and lineage_push.get("kind") == "task"
  2829. and lineage_push.get("mode") == "implement"
  2830. and lineage_push.get("creator") == "goal",
  2831. "the worker dispatch carries the ephemeral branch + identity triplet")
  2832. check("parent" not in lineage_push and "subtasks" not in lineage_push,
  2833. "the plan-12 payload drops the parent/subtasks members")
  2834. print("== R5 B2: task-reading API ==")
  2835. status, _ = saddle_api("GET", "/api/saddle/tasks", None)
  2836. check(status == 401, "tasks endpoint rejects a missing token")
  2837. status, _ = saddle_api("GET", "/api/saddle/task/%d" % auto_child, None)
  2838. check(status == 401, "task detail endpoint rejects a missing token")
  2839. # Fixture: a second project whose tasks all carry the "Diff " title
  2840. # prefix for the project_id filter checks — created first so the
  2841. # unfiltered list has the population the count check expects.
  2842. state = slot_public(auth, "/projects", "projects")
  2843. act(auth, state["create"], {"name": "diff-fabrica",
  2844. "git_url": "ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git"})
  2845. conn = db()
  2846. other_project = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  2847. if p["name"] == "diff-fabrica"][0])
  2848. for suffix in ("fabrica", "scp"):
  2849. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  2850. " values (?, ?, 'done', 5, strftime('%s','now'))",
  2851. (other_project, "Diff %s" % suffix))
  2852. conn.commit()
  2853. conn.close()
  2854. status, body = saddle_api("GET", "/api/saddle/tasks", r4_token)
  2855. check(status == 200 and len(body.get("tasks", [])) > 5,
  2856. "tasks endpoint lists tasks without filters")
  2857. row = [t for t in body["tasks"] if int(t["id"]) == auto_child][0]
  2858. check(row["title"] == "Auto child" and int(row["goal_id"] or 0) == goal
  2859. and row["status"] in ("done", "queued", "working"),
  2860. "compact rows carry id/title/status/goal_id")
  2861. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", r4_token)
  2862. check(all(True for _ in [1]) # project 1 dominates the data set
  2863. and not any(int(t["id"]) == 0 for t in body["tasks"]),
  2864. "project_id filter accepted")
  2865. status, body = saddle_api("GET",
  2866. "/api/saddle/tasks?project_id=%d" % other_project, r4_token)
  2867. check(all(t["title"].startswith("Diff") for t in body["tasks"]),
  2868. "other project lists only its own tasks")
  2869. status, body = saddle_api("GET", "/api/saddle/tasks?q=FLANGE", r4_token)
  2870. titles = [t["title"] for t in body["tasks"]]
  2871. check("Wire the flange" in titles,
  2872. "q matches titles case-insensitively")
  2873. status, body = saddle_api("GET", "/api/saddle/tasks?q=torque%20to%20spec", r4_token)
  2874. check(any(t["title"] == "Wire the flange" for t in body["tasks"]),
  2875. "q matches mandate text")
  2876. status, body = saddle_api("GET", "/api/saddle/task/%d" % auto_child, r4_token)
  2877. task_view = body.get("task", {})
  2878. check(status == 200 and int(task_view.get("id") or 0) == auto_child
  2879. and task_view.get("goal_title") == "Lineage goal"
  2880. and int(task_view.get("goal_id") or 0) == goal,
  2881. "single-task view joins the goal title")
  2882. check("status" in task_view and "description" in task_view
  2883. and "summary" in task_view,
  2884. "single-task view carries the full detail fields")
  2885. check("plan" not in task_view and "parent_task_id" not in task_view,
  2886. "the single-task view drops the deleted parent/plan members")
  2887. status, body = saddle_api("GET", "/api/saddle/task/99999", r4_token)
  2888. check(status == 404, "unknown task id returns 404")
  2889. print("== settle: released workers resume the parked agent (coalesced) ==")
  2890. # Release the held workers: their completions wake the parked goal
  2891. # agent (affinity — the same fake hosts it) with the batched
  2892. # notice; the free worker already completed.
  2893. check(wait_task_done(auth, auto_child, timeout=90) is not None,
  2894. "the free worker settles first")
  2895. def agent_push_count():
  2896. return len([p for p in fake.goal_assignments
  2897. if int(p.get("task", {}).get("id") or 0) == auto_parent])
  2898. before_pushes = agent_push_count()
  2899. for held_task in (auto_grand, flange_task):
  2900. caps = task_state(auth, held_task).get("capabilities") or []
  2901. if caps:
  2902. act(auth, caps[0]["detach"], {})
  2903. check(wait_task_done(auth, held_task, timeout=90) is not None,
  2904. "released worker settles (%d)" % held_task)
  2905. check(wait_for(lambda: agent_push_count() > before_pushes or False,
  2906. timeout=90, what="goal agent resumes") is not None,
  2907. "the workers' completions resume the parked goal agent")
  2908. notice = ""
  2909. for p in fake.goal_assignments:
  2910. if int(p.get("task", {}).get("id") or 0) == auto_parent:
  2911. notice = p.get("resume_notice") or ""
  2912. check("Auto child" in notice and "Auto grandchild" in notice
  2913. and "Wire the flange" in notice,
  2914. "the coalesced resume notice covers every plan task")
  2915. check("New completion reports" in notice and "fake daemon finished" in notice,
  2916. "the notice carries the new completion reports")
  2917. act(auth, goal_state(goal)["cancel"], {})
  2918. check(wait_for(lambda: goal_state(goal)["status"] == "cancelled" or False,
  2919. timeout=30, what="lineage goal cancelled") is not None,
  2920. "the lineage goal cancels (drain)")
  2921. # =============================================================================
  2922. # Bundle: allocation — the ask/wake/allocate machinery: concurrent ask
  2923. # race, token revocation, workspace affinity, the lost-wake guard, the
  2924. # slow-ask regression, assignment capability context + the tag
  2925. # catalogue, and the pinned-blocks/activity dashboard.
  2926. # =============================================================================
  2927. def bundle_allocation(ctx):
  2928. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2929. app = ctx.app
  2930. r4_token = fake_token
  2931. # gpu rides the primary fake from the start (the routing bundle's
  2932. # early attach, replayed): its attach row precedes lostwake's, so
  2933. # the assignment's saddle_tags order matches the assertion in the
  2934. # capability-context section below.
  2935. saddles_state = slot_public(auth, "/saddles", "saddles")
  2936. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2937. act(auth, saddle_card(auth, "fake-saddle")["attach_capability"],
  2938. {"capability_id": str(int([c["id"] for c in
  2939. slot_public(auth, "/saddles", "saddles")["capabilities"]
  2940. if c["name"] == "gpu"][0]))})
  2941. print("== phase 1: ask/allocation — token auth + concurrent race ==")
  2942. # Plan 10 phase 1. Registration mints per-saddle tokens; the
  2943. # ask endpoint authenticates by them; concurrent asks race to
  2944. # exactly one winner through the allocation transaction.
  2945. status, _ = saddle_api("POST", "/api/saddle/next-task", None)
  2946. check(status == 401, "next-task rejects a missing token")
  2947. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-bogus-token")
  2948. check(status == 401, "next-task rejects a wrong token")
  2949. status, body = saddle_api("POST", "/api/saddle/next-task", fake_token)
  2950. check(status == 204, "next-task answers 204 (nothing offerable — daemon sleeps)")
  2951. # Two more racers: real daemons on their own ports; fake2 reports
  2952. # its ssh key at /register so the key lands on the row directly.
  2953. fake2 = FakeSaddle()
  2954. fake2.ssh_public_key = "ssh-ed25519 AAAAFake2RacerKey saddle-2@fedora"
  2955. fake2.serve(port=free_port())
  2956. fake3 = FakeSaddle()
  2957. fake3.serve(port=free_port())
  2958. saddles_state = slot_public(auth, "/saddles", "saddles")
  2959. act(auth, saddles_state["register"], {"name": "racer-two",
  2960. "host": "127.0.0.1:%d" % fake2.port})
  2961. act(auth, saddles_state["register"], {"name": "racer-three",
  2962. "host": "127.0.0.1:%d" % fake3.port})
  2963. check(wait_for(lambda: len(fake2.register_log) > 0 and len(fake3.register_log) > 0
  2964. or False, timeout=15, what="racers registered") is not None,
  2965. "both racers received /register")
  2966. check(wait_for(lambda: "AAAAFake2RacerKey" in
  2967. [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2968. if s["name"] == "racer-two"][0].get("ssh_public_key", "") or False,
  2969. timeout=15, what="register-reported key") is not None,
  2970. "the ssh key reported at /register lands on the saddle row")
  2971. racer_cards = {}
  2972. for name, daemon in (("fake-saddle", fake), ("racer-two", fake2), ("racer-three", fake3)):
  2973. card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2974. if s["name"] == name][0]
  2975. racer_cards[daemon] = {"id": int(card["id"]), "token": card["token"]}
  2976. # Revocation: a registered saddle's token works until the saddle
  2977. # is removed, then nothing authorises its calls.
  2978. fake4 = FakeSaddle()
  2979. fake4.ask_on_register = False # a pre-flip daemon: never asks
  2980. fake4.serve(port=free_port())
  2981. saddles_state = slot_public(auth, "/saddles", "saddles")
  2982. act(auth, saddles_state["register"], {"name": "old-daemon",
  2983. "host": "127.0.0.1:%d" % fake4.port})
  2984. old_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2985. if s["name"] == "old-daemon"][0]
  2986. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  2987. check(status in (200, 204),
  2988. "the old daemon's fresh token authenticates next-task")
  2989. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  2990. {"project": "demo", "body": "from the old daemon"})
  2991. check(status == 200, "note accepts any registered saddle's token")
  2992. act(auth, old_card["unregister"], {})
  2993. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  2994. check(status == 401, "removing the saddle revokes its token")
  2995. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  2996. {"project": "demo", "body": "should fail"})
  2997. check(status == 401, "revocation covers the note endpoint too")
  2998. # Deterministic race: settle the queue first (this shard runs the
  2999. # race before any parked work exists, so only in-flight asks need
  3000. # draining), freeze every daemon's self-ask triggers, put all three
  3001. # to sleep (204), then fire one task worth of concurrent asks.
  3002. for daemon in (fake, fake2, fake3):
  3003. daemon.ask_on_register = False
  3004. daemon.ask_on_wake = False
  3005. daemon.ask_on_terminal = False
  3006. daemon.ask_on_idle_status = False
  3007. daemon.settle_asks() # converted sleep: in-flight asks land (204)
  3008. def queued_count():
  3009. conn = db()
  3010. try:
  3011. return conn.execute(
  3012. "select count(*) from tasks where status = 'queued'").fetchone()[0]
  3013. finally:
  3014. conn.close()
  3015. check(wait_for(lambda: queued_count() == 0 or False,
  3016. timeout=60, what="queue settles before the race") is not None,
  3017. "the queue settles before the race")
  3018. sleep_statuses = [daemon.ask_now()[0] for daemon in (fake, fake2, fake3)]
  3019. check(sleep_statuses == [204, 204, 204],
  3020. "all three racers sleep (204) before the task exists")
  3021. task_id_tmp = create_queued(auth, {
  3022. "project_id": "1",
  3023. "title": "Race task",
  3024. "priority": "2",
  3025. })
  3026. race_task = task_id_tmp
  3027. race_results = []
  3028. def race_ask(daemon):
  3029. # A real racing daemon accepts the assignment it wins — the
  3030. # manual ask path does exactly that on a 200.
  3031. race_results.append(daemon.ask_now())
  3032. threads = [threading.Thread(target=race_ask, args=(daemon,))
  3033. for daemon in (fake, fake2, fake3)]
  3034. for thread in threads:
  3035. thread.start()
  3036. for thread in threads:
  3037. thread.join()
  3038. race_statuses = sorted(r[0] for r in race_results)
  3039. check(race_statuses == [200, 204, 204],
  3040. "concurrent asks race to exactly one winner (%s)" % race_statuses)
  3041. winner = [r for r in race_results if r[0] == 200][0][1]
  3042. check(int(winner["task"]["id"]) == race_task, "the winner's payload carries the task")
  3043. check(int(winner["session_id"]) > 0, "the assignment carries the session id")
  3044. conn = db()
  3045. race_sessions = conn.execute(
  3046. "select count(*) from sessions where task_id = ?", (race_task,)).fetchone()[0]
  3047. conn.close()
  3048. check(race_sessions == 1,
  3049. "exactly one session row — the transaction serialised the claims (%d)"
  3050. % race_sessions)
  3051. check(wait_task_done(auth, race_task, timeout=60) is not None,
  3052. "the raced task completes on the winning daemon")
  3053. for daemon in (fake, fake2, fake3):
  3054. daemon.ask_on_register = True
  3055. daemon.ask_on_wake = True
  3056. daemon.ask_on_terminal = True
  3057. daemon.ask_on_idle_status = True
  3058. # Re-establish sleeping explicitly: the winner's post-race
  3059. # re-ask timing is not deterministic, and the affinity section
  3060. # below needs every racer provably asleep. Any stray offerable
  3061. # drains into these asks first.
  3062. def all_asleep():
  3063. return all(daemon.ask_now()[0] == 204 for daemon in (fake, fake2, fake3))
  3064. check(wait_for(lambda: all_asleep() or False, timeout=30,
  3065. what="racers re-sleep after the race") is not None,
  3066. "all racers re-sleep after the race")
  3067. print("== phase 1: workspace affinity pins parked tasks ==")
  3068. # A suspended parent parked on racer-two may be resumed ONLY by
  3069. # racer-two: a tag-capable non-affine saddle asking gets 204, and
  3070. # the wake targets the affine saddle. Only racer-two carries the
  3071. # tag at dispatch time (the race's winner is nondeterministic, so
  3072. # the park must not depend on which racers are free); racer-three
  3073. # gains it afterwards to prove the pinning is by workspace, not
  3074. # tags.
  3075. saddles_state = slot_public(auth, "/saddles", "saddles")
  3076. act(auth, saddles_state["create_capability"], {"name": "affinity-tag"})
  3077. affinity_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3078. if c["name"] == "affinity-tag"][0])
  3079. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3080. if s["name"] == "racer-two"][0]
  3081. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3082. if s["name"] == "racer-three"][0]
  3083. act(auth, racer2_card["attach_capability"], {"capability_id": str(affinity_cap)})
  3084. # Plan 12: the parked workspace is the goal agent's run task. The
  3085. # other racers sleep (frozen ask triggers), so racer-two claims
  3086. # the goal run and parks it; the goal-task event then resumes the
  3087. # agent AFFINE to racer-two — racer-three (tag-capable or not)
  3088. # gets 204, the dispatcher's wake targets racer-two.
  3089. fake.ask_on_wake = False
  3090. fake.ask_on_idle_status = False
  3091. fake.settle_asks()
  3092. fake3.ask_on_wake = False
  3093. fake3.ask_on_idle_status = False
  3094. fake3.settle_asks()
  3095. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  3096. "project_id": "1", "title": "Affinity goal",
  3097. "brief": "Parks on racer-two.", "branch_name": "goal/affinity"})
  3098. conn = db()
  3099. affinity_goal = conn.execute(
  3100. "select id from goals where title = 'Affinity goal'").fetchone()[0]
  3101. conn.close()
  3102. fake2.goal_script = [("plan", "# Affinity plan\n\n1. Park")]
  3103. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")["start"], {})
  3104. check(wait_for(lambda: slot_public(auth, "/goals/%d" % affinity_goal,
  3105. "goal")["status"] == "plan_review" or False,
  3106. timeout=60, what="affinity goal plans") is not None,
  3107. "the affinity goal reaches plan review (racer-two hosting)")
  3108. fake2.goal_script = [("suspend",)]
  3109. # Freeze racer-two's ask triggers across the approval too (the
  3110. # later wake measurement already does): the mirror-sync fix makes
  3111. # the run resume-offerable the moment its goal row carries the
  3112. # verdict, so a wake-triggered background ask would race this
  3113. # manual ask_now for the claim.
  3114. fake2.ask_on_wake = False
  3115. fake2.ask_on_idle_status = False
  3116. fake2.settle_asks()
  3117. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")
  3118. ["plan_pending_block"]["answer_action"],
  3119. {"answer": "Plan approved. Proceed with implementation."})
  3120. conn = db()
  3121. affinity_parent = conn.execute(
  3122. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  3123. (affinity_goal,)).fetchone()[0]
  3124. agent_session = conn.execute(
  3125. "select id from sessions where task_id = ? and ended_at is null",
  3126. (affinity_parent,)).fetchone()[0]
  3127. conn.close()
  3128. status, resume_payload = fake2.ask_now()
  3129. check(status == 200 and int(resume_payload["task"]["id"]) == affinity_parent,
  3130. "the approved plan resumes the agent on racer-two (its workspace)")
  3131. check(wait_for(lambda: task_state(auth, affinity_parent).get("status") == "suspended"
  3132. or False, timeout=60, what="affinity agent parks") is not None,
  3133. "the affinity goal agent parks on racer-two")
  3134. conn = db()
  3135. affinity_session = conn.execute(
  3136. "select saddle_id from sessions where task_id = ? and ended_at is null",
  3137. (affinity_parent,)).fetchone()[0]
  3138. conn.close()
  3139. check(affinity_session == int(racer2_card["id"]),
  3140. "the parked workspace sits on racer-two")
  3141. # Now racer-three carries the tag too — the pinning is by
  3142. # workspace, not tags. With nothing due, a non-affine ask gets 204.
  3143. act(auth, racer3_card["attach_capability"], {"capability_id": str(affinity_cap)})
  3144. status, _ = fake3.ask_now()
  3145. check(status == 204,
  3146. "a tag-capable non-affine saddle is refused the parked agent (204)")
  3147. # A goal task completing makes the parked agent resume-offerable —
  3148. # affine to racer-two only. The other racers wake back up (they
  3149. # host the worker; their claims of the parked agent get refused as
  3150. # non-affine), while racer-two's ask triggers stay frozen so the
  3151. # wake measurement stays clean. A wake may have hit the frozen
  3152. # racers while the goal run queued (the lost-wake guard marks them
  3153. # offline): the refresh probe brings them back before the worker.
  3154. fake.ask_on_wake = True
  3155. fake.ask_on_idle_status = True
  3156. fake3.ask_on_wake = True
  3157. fake3.ask_on_idle_status = True
  3158. for racer_name in ("fake-saddle", "racer-three"):
  3159. act(auth, saddle_card(auth, racer_name)["refresh"], {})
  3160. check(wait_for(lambda name=racer_name: [s for s in
  3161. slot_public(auth, "/saddles", "saddles")["saddles"]
  3162. if s["name"] == name][0]["status"] == "idle"
  3163. or False, timeout=15, what="racer re-onlined") is not None,
  3164. "%s re-onlined after its frozen-window wake" % racer_name)
  3165. fake2.ask_on_wake = False
  3166. fake2.ask_on_idle_status = False
  3167. wakes_before_2 = len(fake2.wake_log)
  3168. fake2.settle_asks() # converted sleep: park-time ask lands (204)
  3169. status, body = saddle_api("POST", "/api/saddle/task/create", fake2.token, {
  3170. "session_id": agent_session, "title": "Affinity child",
  3171. "mandate": "finish the affinity fixture"})
  3172. check(status == 200, "the parked agent fans its worker out via the CLI")
  3173. affinity_child = int(body["task_id"])
  3174. saddle_api("POST", "/api/saddle/task/enqueue", fake2.token,
  3175. {"session_id": agent_session, "task_id": affinity_child})
  3176. check(wait_task_done(auth, affinity_child, timeout=90) is not None,
  3177. "the affinity worker completes (on a non-affine racer)")
  3178. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_2 or False,
  3179. timeout=90, what="affine wake") is not None,
  3180. "the dispatcher's wake targets the affine saddle")
  3181. status, resume_payload = fake2.ask_now()
  3182. fake2.ask_on_wake = True # restored whatever the claim returned
  3183. fake2.ask_on_idle_status = True
  3184. check(status == 200 and int(resume_payload["task"]["id"]) == affinity_parent,
  3185. "the affine saddle's ask claims the parked agent")
  3186. check("Affinity child" in (resume_payload.get("resume_notice") or "")
  3187. and "fake daemon finished" in (resume_payload.get("resume_notice") or ""),
  3188. "the resume assignment carries the goal's batched report notice")
  3189. check(wait_for(lambda: task_state(auth, affinity_parent).get("status")
  3190. == "suspended" or False,
  3191. timeout=60, what="affinity agent re-parks") is not None,
  3192. "the resumed agent re-parks (script)")
  3193. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")["cancel"], {})
  3194. check(wait_for(lambda: slot_public(auth, "/goals/%d" % affinity_goal,
  3195. "goal")["status"] == "cancelled" or False,
  3196. timeout=30, what="affinity goal cancelled") is not None,
  3197. "the affinity goal cancels (drain)")
  3198. print("== phase 1: lost wake -> offline + re-wake of the next capable ==")
  3199. # racer-three sleeps through wakes (a daemon that died after its
  3200. # last 204): the guard window (SADDLE_LOST_WAKE_S=2) passes with
  3201. # no ask, the saddle goes offline, and the work moves to the
  3202. # next capable sleeping saddle.
  3203. fake3.ask_on_wake = False
  3204. fake3.ask_on_idle_status = False # sleeps through everything
  3205. saddles_state = slot_public(auth, "/saddles", "saddles")
  3206. act(auth, saddles_state["create_capability"], {"name": "lostwake"})
  3207. lostwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3208. if c["name"] == "lostwake"][0])
  3209. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3210. if s["name"] == "racer-three"][0]
  3211. act(auth, racer3_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  3212. # Racer-three must be asleep to be woken: park it with a manual
  3213. # 204 ask (nothing offerable for it — the task below is not
  3214. # created yet).
  3215. status, _ = fake3.ask_now()
  3216. check(status == 204, "racer-three sleeps before the lost-wake run")
  3217. task_id_tmp = create_queued(auth, {
  3218. "project_id": "1",
  3219. "title": "Lost wake task",
  3220. "priority": "2",
  3221. "capability_id": [str(lostwake_cap)],
  3222. })
  3223. lost_task = task_id_tmp
  3224. check(wait_for(lambda: len(fake3.wake_log) > 0 or False,
  3225. timeout=30, what="wake sent to racer-three") is not None,
  3226. "the only capable sleeping saddle is woken")
  3227. check(wait_for(lambda: [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3228. if s["name"] == "racer-three"][0]["status"] == "offline"
  3229. or False, timeout=30, what="lost-wake -> offline") is not None,
  3230. "no ask after the wake: the saddle goes offline (lost-wake guard)")
  3231. check(task_state(auth, lost_task)["status"] == "queued",
  3232. "the task is untouched while its wake was pending")
  3233. # Re-wake the next capable: the healthy saddle gains the tag and
  3234. # picks the work up via its own wake -> ask -> allocate roundtrip.
  3235. fake_card = saddle_card(auth, "fake-saddle")
  3236. act(auth, fake_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  3237. wakes_before = len(fake.wake_log)
  3238. check(wait_for(lambda: len(fake.wake_log) > wakes_before or False,
  3239. timeout=30, what="re-wake of the next capable") is not None,
  3240. "the next capable sleeping saddle is woken for the task")
  3241. check(wait_task_done(auth, lost_task, timeout=60) is not None,
  3242. "wake -> ask -> allocate: the task completes on the healthy saddle")
  3243. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == lost_task
  3244. for p in fake.start_payloads) or False,
  3245. timeout=10, what="lost task assignment captured") is not None,
  3246. "the re-woken saddle's ask produced the assignment")
  3247. fake3.ask_on_wake = True
  3248. fake3.ask_on_idle_status = True
  3249. print("== phase 3: capability context, catalogue, subtask tags ==")
  3250. # Assignment capability context (plan 10 phase 3): every
  3251. # assignment carries {saddle_tags: the allocated saddle's tags,
  3252. # fleet_tags: every tag name known across the fleet} — the
  3253. # daemon renders it into its system prompt. fake-saddle carries
  3254. # gpu + lostwake; the catalogue is affinity-tag, gpu, lostwake.
  3255. fake2.ask_on_register = False
  3256. fake2.ask_on_wake = False
  3257. fake2.ask_on_terminal = False
  3258. fake2.ask_on_idle_status = False
  3259. fake2.settle_asks() # converted sleep: in-flight trigger asks land
  3260. task_id_tmp = create_queued(auth, {
  3261. "project_id": "1",
  3262. "title": "Capabilities context",
  3263. "priority": "2",
  3264. })
  3265. cap_task = task_id_tmp
  3266. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == cap_task
  3267. for p in fake.start_payloads) or False,
  3268. timeout=60, what="capabilities-context task dispatched") is not None,
  3269. "the capabilities-context task dispatches")
  3270. cap_payload = [p for p in fake.start_payloads
  3271. if int(p.get("task", {}).get("id") or 0) == cap_task][-1]
  3272. context = cap_payload.get("capabilities") or {}
  3273. check(context.get("saddle_tags") == ["gpu", "lostwake"],
  3274. "assignment saddle_tags = the allocated saddle's tags (%s)"
  3275. % context.get("saddle_tags"))
  3276. check(context.get("fleet_tags") == ["affinity-tag", "gpu", "lostwake"],
  3277. "assignment fleet_tags = every tag name known across the fleet (%s)"
  3278. % context.get("fleet_tags"))
  3279. check(wait_task_done(auth, cap_task, timeout=60) is not None,
  3280. "capabilities-context task completes")
  3281. # GET /api/saddle/capabilities feeds the daemon's `saddle
  3282. # capabilities` CLI: per-saddle-token auth, tag order by name,
  3283. # each tag with the saddles carrying it (name order).
  3284. status, _ = saddle_api("GET", "/api/saddle/capabilities", None)
  3285. check(status == 401, "capabilities endpoint rejects a missing token")
  3286. status, body = saddle_api("GET", "/api/saddle/capabilities", "saddle-bogus")
  3287. check(status == 401, "capabilities endpoint rejects a wrong token")
  3288. status, body = saddle_api("GET", "/api/saddle/capabilities", fake_token)
  3289. catalogue = {t["name"]: t["saddles"] for t in body.get("tags", [])}
  3290. check(status == 200 and body.get("ok") is True
  3291. and [t["name"] for t in body.get("tags", [])]
  3292. == ["affinity-tag", "gpu", "lostwake"],
  3293. "catalogue lists every tag by name")
  3294. check(catalogue.get("gpu") == ["fake-saddle"]
  3295. and catalogue.get("affinity-tag") == ["racer-three", "racer-two"]
  3296. and catalogue.get("lostwake") == ["fake-saddle", "racer-three"],
  3297. "each tag names its carrying saddles in name order (%s)" % catalogue)
  3298. # Task CLI capabilities (`task create --capability`): validated
  3299. # against the operator tag set; unknown tags reject with the valid
  3300. # list in the error (the agent reads it verbatim in the CLI
  3301. # output). A goal agent's parked session hosts the calls.
  3302. fake.suspend_on_title = "Tag host"
  3303. tag_host = create_queued(auth, {
  3304. "project_id": "1", "title": "Tag host", "priority": "3"})
  3305. check(wait_for(lambda: task_state(auth, tag_host)["status"] == "suspended"
  3306. or False, timeout=60, what="tag host parks") is not None,
  3307. "a parked plain task hosts nothing (no goal scope)")
  3308. # The goal callbacks need a real goal agent: reuse the sequencing
  3309. # goal pattern — a fresh parked agent under this shard.
  3310. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  3311. "project_id": "1", "title": "Tag goal", "brief": "b",
  3312. "branch_name": "goal/tags"})
  3313. conn = db()
  3314. tag_goal = conn.execute("select id from goals where title = 'Tag goal'").fetchone()[0]
  3315. conn.close()
  3316. fake.goal_script = [("suspend",)]
  3317. act(auth, slot_public(auth, "/goals/%d" % tag_goal, "goal")["start"], {})
  3318. conn = db()
  3319. tag_run = conn.execute(
  3320. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  3321. (tag_goal,)).fetchone()[0]
  3322. conn.close()
  3323. check(wait_for(lambda: task_state(auth, tag_run)["status"] == "suspended"
  3324. or False, timeout=60, what="tag goal agent parks") is not None,
  3325. "the tag goal agent parks")
  3326. conn = db()
  3327. tag_session = conn.execute(
  3328. "select id from sessions where task_id = ? and ended_at is null",
  3329. (tag_run,)).fetchone()[0]
  3330. conn.close()
  3331. conn = db()
  3332. tag_host_saddle = conn.execute(
  3333. "select saddle_id from sessions where id = ?", (tag_session,)).fetchone()[0]
  3334. conn.close()
  3335. racer2_card_id = int([c for c in slot_public(auth, "/saddles", "saddles")["saddles"]
  3336. if c["name"] == "racer-two"][0]["id"])
  3337. racer3_card_id = int([c for c in slot_public(auth, "/saddles", "saddles")["saddles"]
  3338. if c["name"] == "racer-three"][0]["id"])
  3339. host_daemon = {int(fake_id): fake, racer2_card_id: fake2,
  3340. racer3_card_id: fake3}[int(tag_host_saddle)]
  3341. status, body = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3342. "session_id": tag_session, "title": "Bad tag worker",
  3343. "mandate": "m", "capabilities": ["gpu", "warp-drive"]})
  3344. check(status == 400, "an unknown capability tag rejects the task call")
  3345. error_text = body.get("error", "")
  3346. check("warp-drive" in error_text and "valid tags" in error_text
  3347. and "gpu" in error_text and "lostwake" in error_text,
  3348. "the rejection names the unknown tag and the valid list (%s)" % error_text)
  3349. status, _ = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3350. "session_id": tag_session, "title": "Bad shape worker",
  3351. "mandate": "m", "capabilities": "gpu"})
  3352. check(status == 400, "a non-array capabilities member rejects")
  3353. # A valid tag creates the goal worker in draft with exactly the
  3354. # explicit tag attached; the goal agent enqueues it.
  3355. status, body = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3356. "session_id": tag_session, "title": "Explicit tag worker",
  3357. "mandate": "do the tagged work", "capabilities": ["gpu"]})
  3358. check(status == 200 and body.get("ok") is True,
  3359. "a valid tag creates the task synchronously")
  3360. tagged_worker = int(body["task_id"])
  3361. detail = task_state(auth, tagged_worker)
  3362. check([c["name"] for c in detail.get("capabilities", [])] == ["gpu"],
  3363. "the worker carries exactly the explicit tag")
  3364. conn = db()
  3365. tag_rows = conn.execute(
  3366. "select c.name from task_capabilities tc"
  3367. " join capabilities c on c.id = tc.capability_id"
  3368. " where tc.task_id = ?", (tagged_worker,)).fetchall()
  3369. conn.close()
  3370. check([r[0] for r in tag_rows] == ["gpu"],
  3371. "the task_capabilities rows record the explicit tag")
  3372. check(detail["status"] == "draft",
  3373. "the callback's task lands in draft until its agent enqueues")
  3374. saddle_api("POST", "/api/saddle/task/enqueue", host_daemon.token,
  3375. {"session_id": tag_session, "task_id": tagged_worker})
  3376. check(wait_task_done(auth, tagged_worker, timeout=90) is not None,
  3377. "the tagged worker dispatches and completes")
  3378. act(auth, slot_public(auth, "/goals/%d" % tag_goal, "goal")["cancel"], {})
  3379. act(auth, task_state(auth, tag_host)["cancel"], {})
  3380. print("== phase 3: dashboard — pinned blocks + activity timeline ==")
  3381. # Pinned OPEN blocking items as link-through cards, newest
  3382. # first; no inline answer forms (the card links to the task
  3383. # page). Fixture: one open question + one open review raised on a
  3384. # local task (stand-ins for the auto-approve grandchild's
  3385. # leftovers) join the probe RFC raised below.
  3386. conn = db()
  3387. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  3388. " values (1, 'Dash fixture task', 'working', 5, strftime('%s','now'))")
  3389. dash_task = conn.execute("select max(id) from tasks").fetchone()[0]
  3390. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  3391. " values (?, ?, strftime('%s','now'))", (dash_task, fake_id))
  3392. dash_session = conn.execute("select max(id) from sessions").fetchone()[0]
  3393. conn.commit()
  3394. conn.close()
  3395. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3396. {"type": "block", "session_id": dash_session, "data": {
  3397. "question": "Dash fixture question?", "type": "question"}})
  3398. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3399. {"type": "review", "session_id": dash_session, "data": {
  3400. "summary": "dash fixture review"}})
  3401. # The activity timeline: last <= 50 events, newest first, fed
  3402. # from the existing tables. Fixture rows a few seconds old
  3403. # guarantee the progress kind and a human-authored comment ride
  3404. # along; the probe block below proves same-source ordering.
  3405. conn = db()
  3406. conn.execute("insert into task_comments (task_id, author, body, created_at)"
  3407. " values (?, 'user:admin', 'timeline fixture comment by a human',"
  3408. " strftime('%s','now','-5 seconds'))", (cap_task,))
  3409. conn.execute("insert into task_progress (task_id, summary, created_at)"
  3410. " values (?, 'timeline fixture progress',"
  3411. " strftime('%s','now','-5 seconds'))",
  3412. (cap_task,))
  3413. conn.commit()
  3414. conn.close()
  3415. # The probe RFC raised last: the newest pinned card and the newest
  3416. # timeline event (its raise+answer below prove same-source ordering
  3417. # both ways). The timeline sorts same-second events by source
  3418. # materialisation order, so the probe must land in a LATER clock
  3419. # second than the fixtures — wait for the boundary (bounded).
  3420. fixtures_epoch = int(time.time())
  3421. wait_for(lambda: int(time.time()) > fixtures_epoch or False,
  3422. timeout=3, what="next clock second before the probe raise")
  3423. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3424. {"type": "block", "session_id": dash_session, "data": {
  3425. "question": "Timeline probe: approve the dashboard flow",
  3426. "type": "rfc", "body": "# Probe"}})
  3427. dash = slot_public(auth, "/", "dashboard")
  3428. pinned = dash.get("pinned", [])
  3429. pinned_ids = [int(b["id"]) for b in pinned]
  3430. check(len(pinned_ids) >= 3 and pinned_ids == sorted(pinned_ids, reverse=True),
  3431. "pinned open blocks order newest-first (%s)" % pinned_ids)
  3432. check({b["block_type"] for b in pinned} >= {"question", "rfc", "review"},
  3433. "pinned cards cover questions, RFCs and reviews")
  3434. check(all(b["question"] and b["task_title"] and int(b["task_id"]) > 0
  3435. for b in pinned)
  3436. and all("answer_action" not in b for b in pinned),
  3437. "pinned cards are link-through only (task title, kind badge, question)")
  3438. activity = dash.get("activity", [])
  3439. epochs = [int(e["at_epoch"]) for e in activity]
  3440. check(0 < len(activity) <= 50 and epochs == sorted(epochs, reverse=True),
  3441. "the timeline shows the last <=50 events newest-first (%d events)"
  3442. % len(activity))
  3443. kinds = {e["kind"] for e in activity}
  3444. check({"created", "started", "dispatch", "comment", "progress", "completed"} <= kinds,
  3445. "the timeline covers status changes, dispatches, comments, progress and"
  3446. " completions (%s)" % sorted(kinds))
  3447. check(any(e["kind"] == "comment" and e["text"].startswith("user:admin:")
  3448. and "fixture comment" in e["text"] for e in activity),
  3449. "comment events carry author + snippet")
  3450. # The freshly raised probe pinned as the newest card and landed
  3451. # atop the timeline as block-raised; answering it records
  3452. # block-answered.
  3453. check(dash["pinned"][0]["question"] == "Timeline probe: approve the dashboard flow"
  3454. and int(dash["pinned"][0]["task_id"]) == dash_task,
  3455. "the freshest open block pins as the first card")
  3456. check(dash["activity"][0]["kind"] == "block-raised"
  3457. and "Timeline probe" in dash["activity"][0]["text"],
  3458. "the raised block lands atop the timeline")
  3459. probe_block = [b for b in task_state(auth, dash_task)["blocks"]
  3460. if b["question"] == "Timeline probe: approve the dashboard flow"][0]
  3461. act(auth, probe_block["answer_action"], {"answer": "Ship the dashboard"})
  3462. dash = slot_public(auth, "/", "dashboard")
  3463. activity = dash.get("activity", [])
  3464. raised_at = next((i for i, e in enumerate(activity)
  3465. if e["kind"] == "block-raised" and "Timeline probe" in e["text"]), -1)
  3466. answered_at = next((i for i, e in enumerate(activity)
  3467. if e["kind"] == "block-answered"
  3468. and "Ship the dashboard" in e["text"]), -1)
  3469. check(answered_at >= 0 and raised_at >= 0 and answered_at < raised_at,
  3470. "the answered event sorts above its raised event (newest-first, same source)")
  3471. check(all(b["question"] != "Timeline probe: approve the dashboard flow"
  3472. for b in dash["pinned"]),
  3473. "the answered block leaves the pinned cards")
  3474. print("== phase 3 regression: a slow ask after a wake is never dropped ==")
  3475. # The daemon worker's lost-wake-guard regression: a saddle whose
  3476. # ask arrives SLOWLY after the wake (busy winding down when the
  3477. # wake lands) must not lose the wake — the delayed ask (inside
  3478. # the guard window) claims the task, no re-wake storm fires
  3479. # while it is pending, and the saddle stays healthy. The
  3480. # never-asks path (guard -> offline + re-wake of the next
  3481. # capable) is proven by the racer-three section above.
  3482. check(wait_for(lambda: queued_count() == 0 or False,
  3483. timeout=60, what="queue settles before the slow-wake run") is not None,
  3484. "the queue settles before the slow-wake run")
  3485. status, _ = fake2.ask_now()
  3486. check(status == 204, "the slow-ask racer sleeps before its wake")
  3487. saddles_state = slot_public(auth, "/saddles", "saddles")
  3488. act(auth, saddles_state["create_capability"], {"name": "slowwake"})
  3489. slowwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")
  3490. ["capabilities"] if c["name"] == "slowwake"][0])
  3491. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3492. if s["name"] == "racer-two"][0]
  3493. act(auth, racer2_card["attach_capability"], {"capability_id": str(slowwake_cap)})
  3494. fake2.ask_delay = 1.2 # slow: asks well after the wake, inside the 2s guard
  3495. fake2.ask_on_wake = True
  3496. wakes_before_slow = len(fake2.wake_log)
  3497. task_id_tmp = create_queued(auth, {
  3498. "project_id": "1",
  3499. "title": "Slow wake task",
  3500. "priority": "2",
  3501. "capability_id": [str(slowwake_cap)],
  3502. })
  3503. slow_task = task_id_tmp
  3504. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_slow or False,
  3505. timeout=30, what="the slow-ask racer woken") is not None,
  3506. "the only capable sleeping saddle is woken")
  3507. check(wait_task_done(auth, slow_task, timeout=120) is not None,
  3508. "the delayed ask claims the task — the wake was not dropped")
  3509. check(any(a.get("status") == 200
  3510. and int((a.get("payload") or {}).get("task", {}).get("id") or 0)
  3511. == slow_task for a in fake2.asks),
  3512. "the slow ask's 200 carries the task")
  3513. check(len(fake2.wake_log) == wakes_before_slow + 1,
  3514. "the pending-wake skip re-wakes nobody while the slow ask is in flight")
  3515. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3516. if s["name"] == "racer-two"][0]
  3517. check(racer2_card["status"] in ("idle", "busy"),
  3518. "the slow asker never went offline (guard did not fire)")
  3519. fake2.ask_delay = 0.0
  3520. fake2.ask_on_wake = False # stays out of the pool below
  3521. # =============================================================================
  3522. # Bundle: lifecycle — offline requeues, the hung-request tick survival,
  3523. # parked-refresh bookkeeping, cancellation, the health panel, raw-log
  3524. # losslessness, git identity and the live blocked-push roundtrip.
  3525. # =============================================================================
  3526. def bundle_lifecycle(ctx):
  3527. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  3528. app = ctx.app
  3529. print("== plan 11: draft state machine, edit matrix, enqueue/delete guards ==")
  3530. # New tasks default to draft; Enqueue is the only path to the
  3531. # queue (there is no agent path — the ingest API refuses to queue).
  3532. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3533. "project_id": "1",
  3534. "title": "Draft lifecycle task",
  3535. "priority": "4",
  3536. })
  3537. draft_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3538. if t["title"] == "Draft lifecycle task"][0])
  3539. detail = task_state(auth, draft_task)
  3540. check(detail["status"] == "draft", "a created task lands in draft")
  3541. check(detail.get("enqueue") is not None and detail.get("delete") is not None,
  3542. "draft exposes the enqueue + delete actions")
  3543. check(detail.get("cancel") is not None, "the cancel action stays authored")
  3544. status, page = http("GET", "/tasks/%d" % draft_task, timeout=15)
  3545. check(status == 200 and "Enqueue task" in page and ">Delete<" in page,
  3546. "the task page shows Enqueue + Delete in draft")
  3547. check("Mark done" not in page,
  3548. "the user Mark-complete action is gone (agent-only completion)")
  3549. # Plan 12: the auto-enqueue-after predecessor REPLACES draft
  3550. # dependencies — setting it is allowed while the predecessor is
  3551. # still pending (the enqueue itself succeeds; the DISPATCHER holds
  3552. # dispatch back until the predecessor is done).
  3553. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3554. "project_id": "1",
  3555. "title": "Draft dependency",
  3556. "priority": "4",
  3557. })
  3558. draft_dep = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3559. if t["title"] == "Draft dependency"][0])
  3560. act(auth, detail["update"], {"enqueue_after_task_id": str(draft_dep)})
  3561. check(int(task_state(auth, draft_task).get("enqueue_after_task_id") or 0)
  3562. == draft_dep,
  3563. "the draft edit sets the auto-enqueue predecessor")
  3564. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3565. "project_id": "1", "title": "Eager dependent", "priority": "4",
  3566. "enqueue_after_task_id": str(draft_dep)})
  3567. eager = task_id_of("Eager dependent")
  3568. enqueue_task(auth, eager)
  3569. check(task_state(auth, eager)["status"] == "queued",
  3570. "enqueue succeeds while the predecessor is pending (no draft guard)")
  3571. check(quiet_window(quiet_seconds(),
  3572. lambda: task_state(auth, eager)["status"] == "queued",
  3573. "pending predecessor holds dispatch"),
  3574. "the pending predecessor holds dispatch back (never assigned)")
  3575. # The edit matrix starts in DRAFT: every field except status.
  3576. act(auth, detail["update"], {
  3577. "title": "Draft lifecycle task (edited)",
  3578. "description": "Now with a description",
  3579. "priority": "2",
  3580. "task_branch": "feature/draft",
  3581. "branch_from": "main",
  3582. "mode": "investigate",
  3583. })
  3584. detail = task_state(auth, draft_task)
  3585. check(detail["title"] == "Draft lifecycle task (edited)"
  3586. and detail["description"] == "Now with a description"
  3587. and detail["priority"] == 2
  3588. and detail["task_branch"] == "feature/draft"
  3589. and detail["branch_from"] == "main"
  3590. and detail["mode"] == "investigate",
  3591. "draft edits apply to every field (incl. the mode)")
  3592. # Clear the predecessor (the empty sentinel): dispatch gates on
  3593. # the hold tag alone now.
  3594. act(auth, detail["update"], {"enqueue_after_task_id": "0"})
  3595. check(not int(task_state(auth, draft_task).get("enqueue_after_task_id") or 0),
  3596. "the draft edit clears the auto-enqueue predecessor")
  3597. # A hold tag nothing carries keeps the dependent QUEUED (never
  3598. # dispatched) through the remaining edit-matrix checks.
  3599. saddles_state = slot_public(auth, "/saddles", "saddles")
  3600. act(auth, saddles_state["create_capability"], {"name": "holdlock"})
  3601. holdlock_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3602. if c["name"] == "holdlock"][0])
  3603. act(auth, detail["attach_capability"], {"capability_id": str(holdlock_cap)})
  3604. # Enqueue the now-cleared dependent: the hold tag keeps it queued
  3605. # (never dispatched), so the non-draft edit matrix applies.
  3606. enqueue_task(auth, draft_task)
  3607. check(quiet_window(3, lambda: task_state(auth, draft_task)["status"] == "queued",
  3608. "held dependent stays queued"),
  3609. "the held dependent stays queued (never dispatched)")
  3610. # The predecessor settles for the shard drain.
  3611. enqueue_task(auth, draft_dep)
  3612. check(wait_task_done(auth, draft_dep, timeout=90) is not None,
  3613. "the predecessor settles")
  3614. # Drafts are never dispatched even with an idle saddle available.
  3615. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3616. "project_id": "1",
  3617. "title": "Never-dispatched draft",
  3618. "priority": "1",
  3619. })
  3620. silent_draft = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3621. if t["title"] == "Never-dispatched draft"][0])
  3622. check(quiet_window(quiet_seconds(),
  3623. lambda: task_state(auth, silent_draft)["status"] == "draft",
  3624. "draft never dispatched"),
  3625. "an idle saddle never picks a draft up (no agent enqueue path)")
  3626. # Once work can begin (queued here), only priority is editable.
  3627. act(auth, detail["update"], {
  3628. "title": "Should not apply",
  3629. "priority": "3",
  3630. })
  3631. detail = task_state(auth, draft_task)
  3632. check(detail["title"] == "Draft lifecycle task (edited)" and detail["priority"] == 3,
  3633. "non-draft edits apply priority only (title locked)")
  3634. # A terminal task edits nothing.
  3635. conn = db()
  3636. conn.execute("update tasks set status = 'done', completed_at = strftime('%s','now')"
  3637. " where id = ?", (draft_task,))
  3638. conn.commit()
  3639. conn.close()
  3640. act(auth, task_state(auth, draft_task)["update"], {"priority": "8"})
  3641. check(task_state(auth, draft_task)["priority"] == 3,
  3642. "terminal tasks edit nothing (priority locked)")
  3643. # Capabilities lock once a worker has the job: editable while
  3644. # queued, locked once working.
  3645. act(auth, saddles_state["create_capability"], {"name": "editlock"})
  3646. editlock_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")
  3647. ["capabilities"] if c["name"] == "editlock"][0])
  3648. act(auth, saddle_card(auth, "fake-saddle")["attach_capability"],
  3649. {"capability_id": str(editlock_cap)})
  3650. locked_task = create_queued(auth, {"project_id": "1", "title": "Caplock task",
  3651. "priority": "2"})
  3652. detail = task_state(auth, locked_task)
  3653. act(auth, detail["attach_capability"], {"capability_id": str(editlock_cap)})
  3654. check(wait_for(lambda: any(c["name"] == "editlock"
  3655. for c in task_state(auth,
  3656. locked_task)["capabilities"])
  3657. or False, timeout=60, what="editlock attached") is not None,
  3658. "capabilities attach while queued (no worker yet)")
  3659. check(wait_for(lambda: task_state(auth, locked_task).get("status") == "working"
  3660. or False, timeout=60, what="caplock working") is not None,
  3661. "the caplock task reaches working")
  3662. detach_directives = act(auth, task_state(auth, locked_task)["capabilities"][0]["detach"], {})
  3663. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  3664. for d in detach_directives),
  3665. "capabilities are locked once a worker has the job")
  3666. # The ingest API has no queue transition either (only working and
  3667. # blocked are accepted states).
  3668. conn = db()
  3669. caplock_session = conn.execute(
  3670. "select id from sessions where task_id = ? and ended_at is null",
  3671. (locked_task,)).fetchone()
  3672. conn.close()
  3673. if caplock_session is not None:
  3674. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3675. {"type": "status", "session_id": caplock_session[0],
  3676. "data": {"state": "queued"}})
  3677. check(status == 200
  3678. and task_state(auth, locked_task)["status"] in ("working", "done"),
  3679. "the ingest API's status push never queues a task")
  3680. # Delete guards: a clean draft deletes; non-draft refuses; a draft
  3681. # with dependents is refused naming them.
  3682. act(auth, task_state(auth, silent_draft)["delete"], {})
  3683. check(not any(t["id"] == silent_draft
  3684. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  3685. "a clean draft task deletes")
  3686. delete_directives = act(auth, task_state(auth, draft_task)["delete"], {})
  3687. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  3688. for d in delete_directives),
  3689. "a non-draft task refuses the delete")
  3690. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3691. "project_id": "1", "title": "Guarded draft", "priority": "4"})
  3692. guarded = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3693. if t["title"] == "Guarded draft"][0])
  3694. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3695. "project_id": "1", "title": "Dependent namer", "priority": "4"})
  3696. namer = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3697. if t["title"] == "Dependent namer"][0])
  3698. act(auth, task_state(auth, namer)["update"],
  3699. {"enqueue_after_task_id": str(guarded)})
  3700. check(int(task_state(auth, namer).get("enqueue_after_task_id") or 0) == guarded,
  3701. "the namer points at the guarded predecessor")
  3702. act(auth, task_state(auth, guarded)["delete"], {})
  3703. check(not any(t["id"] == guarded
  3704. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  3705. "deleting a predecessor succeeds")
  3706. check(not int(task_state(auth, namer).get("enqueue_after_task_id") or 0),
  3707. "the delete clears the dependent's dangling predecessor reference")
  3708. print("== offline requeues ==")
  3709. # Tasks caught working on a saddle that went offline requeue with a
  3710. # agent comment each tick.
  3711. task_id_tmp = create_queued(auth, {
  3712. "project_id": "1",
  3713. "title": "Offline saddle task",
  3714. "priority": "2",
  3715. })
  3716. offline_task = task_id_tmp
  3717. check(wait_for(lambda: task_state(auth, offline_task).get("status") == "working"
  3718. or False, timeout=60, what="offline task starts working") is not None,
  3719. "task reaches working before its saddle disappears")
  3720. # Hold the daemon mid-round across the requeue window (the
  3721. # original relied on its 8s work period outlasting the 5s tick):
  3722. # the task completing on its own would race the offline pass and
  3723. # skip the requeue the check exists to observe.
  3724. fake.hold_state = True
  3725. conn = db()
  3726. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  3727. conn.commit()
  3728. conn.close()
  3729. # The requeue frees the saddle in the same tick, so 'queued' is
  3730. # transient; the durable evidence is the agent comment (and the task
  3731. # completing again on the healthy daemon).
  3732. check(wait_for(lambda: any(c["body"] == "saddle went offline; task requeued"
  3733. for c in task_state(auth, offline_task).get("comments", []))
  3734. or False, timeout=30, what="offline requeue comment") is not None,
  3735. "offline saddle requeues the task")
  3736. fake.hold_state = False # release: the round ends, the daemon re-asks
  3737. check(wait_task_done(auth, offline_task, timeout=60) is not None,
  3738. "requeued task completes again on the healthy daemon")
  3739. print("== R6 F1: a hanging request cannot freeze the tick ==")
  3740. # One wedged /task-update (never responds) blocks the comment/
  3741. # subtask-event delivery pass; the Soup timeout must fail it and
  3742. # later ticks keep dispatching.
  3743. conn = db()
  3744. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  3745. " values (1, 'Hang survivor', 'queued', 2, strftime('%s','now'))")
  3746. hang_task = conn.execute("select max(id) from tasks").fetchone()[0]
  3747. conn.close()
  3748. task_id_tmp = create_queued(auth, {
  3749. "project_id": "1",
  3750. "title": "Hang runner",
  3751. "priority": "3",
  3752. })
  3753. hang_runner = task_id_tmp
  3754. # A human comment on the running task gives the tick a
  3755. # /task-update delivery to make; the next one hangs.
  3756. check(wait_for(lambda: task_state(auth, hang_runner).get("status") == "working"
  3757. or False, timeout=60, what="hang runner working") is not None,
  3758. "hang runner reaches working")
  3759. act(auth, task_state(auth, hang_runner)["comment"],
  3760. {"body": "operator ping while wedged"})
  3761. fake.hang_next["/task-update"] = 1
  3762. check(wait_task_done(auth, hang_runner, timeout=90) is not None,
  3763. "dispatching task survives a hung daemon request")
  3764. check(wait_for(lambda: any(c.get("text") == "operator ping while wedged"
  3765. or c.get("body") == "operator ping while wedged"
  3766. for c in fake.comment_log) or False,
  3767. timeout=30, what="wedged comment eventually delivered") is not None,
  3768. "the comment delivery retries after the hang")
  3769. # The hung delivery itself fails after the timeout; the system
  3770. # kept moving either way.
  3771. with open(os.path.join(WORK, "app.log")) as handle:
  3772. app_log = handle.read()
  3773. check("tick exceeded" not in app_log or "Dispatch tick failed" in app_log,
  3774. "a hung request never freezes the tick latch")
  3775. print("== R6 F2: refresh must not corrupt parked bookkeeping ==")
  3776. fake.suspend_on_title = "Parked refresh parent"
  3777. task_id_tmp = create_queued(auth, {
  3778. "project_id": "1",
  3779. "title": "Parked refresh parent",
  3780. "priority": "2",
  3781. })
  3782. parked = task_id_tmp
  3783. check(wait_for(lambda: task_state(auth, parked).get("status") == "suspended"
  3784. or False, timeout=60, what="parked parent suspends") is not None,
  3785. "parent parks before the refresh")
  3786. fake_card = saddle_card(auth, "fake-saddle")
  3787. act(auth, fake_card["refresh"], {})
  3788. fake_card = saddle_card(auth, "fake-saddle")
  3789. check(fake_card["status"] == "idle" and int(fake_card["current_task_id"] or 0) == 0,
  3790. "refresh on a parked (suspended) daemon leaves the saddle idle")
  3791. # The parked task keeps its open session and stays put: plain
  3792. # tasks have no subtask events to resume them (the goal machinery
  3793. # owns resumes); the human resumes it explicitly.
  3794. check(quiet_window(quiet_seconds(),
  3795. lambda: task_state(auth, parked)["status"] == "suspended",
  3796. "parked task stays parked"),
  3797. "a parked plain task stays parked after the refresh (no resume channel)")
  3798. act(auth, task_state(auth, parked)["cancel"], {})
  3799. check(wait_for(lambda: task_state(auth, parked)["status"] == "failed" or False,
  3800. timeout=30, what="parked task cancelled") is not None,
  3801. "the parked task cancels cleanly after the refresh")
  3802. print("== R7 B1: cancel reaches the daemon ==")
  3803. # Plan 10 phase 2: cancellation is POST /task-update {kind: cancel}
  3804. # to the RUNNING daemon (the abort machinery, workspace kept).
  3805. task_id_tmp = create_queued(auth, {
  3806. "project_id": "1",
  3807. "title": "Cancel live",
  3808. "priority": "2",
  3809. })
  3810. cancel_live = task_id_tmp
  3811. check(wait_for(lambda: task_state(auth, cancel_live).get("status") == "working"
  3812. or False, timeout=60, what="cancel-live working") is not None,
  3813. "task reaches working before the cancel")
  3814. act(auth, task_state(auth, cancel_live)["cancel"], {})
  3815. check(wait_for(lambda: cancel_live in fake.abort_log or False,
  3816. timeout=30, what="daemon abort recorded") is not None,
  3817. "cancelling POSTs task-update cancel to the daemon")
  3818. check(any(c["body"] == "cancelled; daemon aborted"
  3819. for c in task_state(auth, cancel_live).get("comments", [])),
  3820. "the abort outcome is narrated")
  3821. check(task_state(auth, cancel_live)["status"] == "failed",
  3822. "cancelled task lands failed as before")
  3823. # A 500 on the cancel marks the saddle offline (no fence layer
  3824. # anymore); nothing dispatches to it while offline, and the
  3825. # daemon's own ask flips the row back to idle (proof of life).
  3826. task_id_tmp = create_queued(auth, {
  3827. "project_id": "1",
  3828. "title": "Fence runner",
  3829. "priority": "2",
  3830. })
  3831. fence_runner = task_id_tmp
  3832. check(wait_for(lambda: task_state(auth, fence_runner).get("status") == "working"
  3833. or False, timeout=60, what="fence runner working") is not None,
  3834. "second task reaches working")
  3835. fake.abort_failures = 1
  3836. act(auth, task_state(auth, fence_runner)["cancel"], {})
  3837. check(any(c["body"] == "cancelled; daemon unreachable — saddle marked offline"
  3838. for c in task_state(auth, fence_runner).get("comments", [])),
  3839. "failed cancel narrates the offline marking")
  3840. check(saddle_card(auth, "fake-saddle")["status"] == "offline",
  3841. "saddle marked offline after the failed cancel")
  3842. task_id_tmp = create_queued(auth, {
  3843. "project_id": "1",
  3844. "title": "During fence",
  3845. "priority": "3",
  3846. })
  3847. during_fence = task_id_tmp
  3848. # Converted sleep(7): a quiet window spanning several dispatch
  3849. # ticks in which the task MUST stay queued — if the offline
  3850. # saddle ever dispatches it, this fails loudly. The daemon is held
  3851. # mid-round for the window (the original relied on its 8s work
  3852. # period outlasting the sleep): a finishing round would ask, prove
  3853. # liveness and flip the offline row — only after the window may it.
  3854. fake.hold_state = True
  3855. check(quiet_window(quiet_seconds(),
  3856. lambda: task_state(auth, during_fence)["status"] == "queued",
  3857. "offline saddle does not dispatch during_fence"),
  3858. "offline saddle is not dispatchable")
  3859. fake.hold_state = False
  3860. # The (unaborted) daemon finishes its round, goes idle-awake and
  3861. # asks — the ask is the proof of life that flips the row back.
  3862. check(wait_for(lambda: saddle_card(auth, "fake-saddle")["status"] == "idle" or False,
  3863. timeout=30, what="ask flips offline to idle") is not None,
  3864. "the daemon's ask flips the offline row back to idle")
  3865. check(wait_task_done(auth, during_fence, timeout=60) is not None,
  3866. "queued work dispatches once the saddle proves it is alive")
  3867. print("== R7 B3: health panel + pushed raw log from the first round ==")
  3868. # A normally dispatched task pushes its chunks immediately: raw
  3869. # rows exist from the first round (the session-4 gap stays
  3870. # fixed without any probe machinery).
  3871. task_id_tmp = create_queued(auth, {
  3872. "project_id": "1",
  3873. "title": "Raw from first push",
  3874. "priority": "2",
  3875. })
  3876. raw_first = task_id_tmp
  3877. def raw_count(task_id):
  3878. conn = db()
  3879. try:
  3880. return conn.execute(
  3881. "select count(*) from session_raw_log where session_id in"
  3882. " (select id from sessions where task_id = ?)", (task_id,)).fetchone()[0]
  3883. finally:
  3884. conn.close()
  3885. check(wait_for(lambda: raw_count(raw_first) > 0 or False,
  3886. timeout=60, what="raw rows from first push") is not None,
  3887. "pushed chunks land from the first round (session-4 gap)")
  3888. check(wait_task_done(auth, raw_first, timeout=60) is not None,
  3889. "raw-first task completes")
  3890. # Health panel: a manual refresh populates the snapshot.
  3891. fake_card = saddle_card(auth, "fake-saddle")
  3892. act(auth, fake_card["refresh"], {})
  3893. card = saddle_card(auth, "fake-saddle")
  3894. check(card.get("health") in ("healthy", "stale")
  3895. and card.get("daemon_state") in ("working", "idle", "done")
  3896. and card.get("uptime_display", "") != ""
  3897. and card.get("last_contact_display", "") not in ("", "never"),
  3898. "saddles page shows daemon state, uptime and last contact")
  3899. print("== R8: pushed chunk ingestion is lossless ==")
  3900. # The daemon's opening flush: a coloured prompt run, plain text,
  3901. # a bare CRLF between prompts and the tail — every non-empty
  3902. # chunk must land, exactly once, in seq order. A mid-flight
  3903. # redelivery of the whole batch (the outbox's at-least-once
  3904. # retry) consumes the duplicates.
  3905. corpus = [
  3906. {"seq": 1, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  3907. {"seq": 2, "text": "echo hello\r\n"},
  3908. {"seq": 3, "text": "\r\n"},
  3909. {"seq": 4, "text": "hello\r\n"},
  3910. {"seq": 5, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  3911. {"seq": 6, "text": "done\r\n"},
  3912. ]
  3913. fake.scripted_corpus = corpus
  3914. fake.hold_state = True
  3915. task_id_tmp = create_queued(auth, {
  3916. "project_id": "1",
  3917. "title": "Lossless log task",
  3918. "priority": "2",
  3919. })
  3920. lossless = task_id_tmp
  3921. def stored_seqs(task_id):
  3922. conn = db()
  3923. try:
  3924. return [r[0] for r in conn.execute(
  3925. "select seq from session_raw_log where session_id in"
  3926. " (select id from sessions where task_id = ?)"
  3927. " order by seq", (task_id,))]
  3928. finally:
  3929. conn.close()
  3930. check(wait_for(lambda: task_state(auth, lossless).get("status") == "working"
  3931. or False, timeout=60, what="lossless task working") is not None,
  3932. "lossless task dispatches and pushes its opening flush")
  3933. check(wait_for(lambda: stored_seqs(lossless) == [1, 2, 3, 4, 5, 6] or False,
  3934. timeout=30, what="all six chunks stored") is not None,
  3935. "every pushed chunk lands in session_raw_log, CRLF-only included (%s)"
  3936. % stored_seqs(lossless))
  3937. status, _ = saddle_api("POST", "/api/saddle/chunks", fake.token,
  3938. {"session_id": fake.session_id,
  3939. "chunks": [dict(chunk) for chunk in corpus]})
  3940. check(status == 200 and stored_seqs(lossless) == [1, 2, 3, 4, 5, 6],
  3941. "a full-batch redelivery stores nothing new (exactly-once)")
  3942. request = urllib.request.Request(
  3943. WEB + "/terminal-stream/%d" % [r[0] for r in db().execute(
  3944. "select id from sessions where task_id = ?", (lossless,))][0])
  3945. with urllib.request.urlopen(request, timeout=15) as stream:
  3946. texts = []
  3947. deadline = time.monotonic() + 8
  3948. while time.monotonic() < deadline and len(texts) < 6:
  3949. line = stream.readline().decode().strip()
  3950. if not line.startswith("data: ") or line == "data: ping":
  3951. continue
  3952. event = json.loads(line[6:])
  3953. if event.get("type") == "raw":
  3954. texts.append(event.get("text") or "")
  3955. check("\r\n" in texts and len(texts) == 6,
  3956. "SSE serves the whitespace chunk unfiltered")
  3957. fake.hold_state = False
  3958. fake.scripted_corpus = None
  3959. check(wait_task_done(auth, lossless, timeout=60) is not None,
  3960. "lossless task completes")
  3961. print("== R9 B1/B2: git identity + ssh key ==")
  3962. # The key travels on /status into the saddle row and the page view
  3963. # (the manual refresh's exceptional probe).
  3964. fake.ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1teStKey saddle-1@fedora"
  3965. fake_card = saddle_card(auth, "fake-saddle")
  3966. check(fake_card.get("ssh_public_key", "") == "",
  3967. "no key shown before the daemon reports one")
  3968. act(auth, fake_card["refresh"], {})
  3969. check(wait_for(lambda: "AAAAC3NzaC1lZDI1teStKey" in
  3970. saddle_card(auth, "fake-saddle").get("ssh_public_key", "") or False,
  3971. timeout=30, what="key lands on the row") is not None,
  3972. "reported ssh_public_key persists onto the saddle row")
  3973. conn = db()
  3974. row_key = conn.execute("select ssh_public_key from saddles where name = 'fake-saddle'"
  3975. ).fetchone()[0]
  3976. conn.close()
  3977. check(row_key == fake.ssh_public_key,
  3978. "the key is stored verbatim in the database")
  3979. # Identity edit flows through the UI into the assignment payload.
  3980. fake_card = saddle_card(auth, "fake-saddle")
  3981. act(auth, fake_card["update_identity"],
  3982. {"git_name": "clanker-bot", "git_email": "bot@unitatem.net"})
  3983. fake_card = saddle_card(auth, "fake-saddle")
  3984. check(fake_card.get("git_name") == "clanker-bot"
  3985. and fake_card.get("git_email") == "bot@unitatem.net",
  3986. "inline edit saves the git identity")
  3987. task_id_tmp = create_queued(auth, {
  3988. "project_id": "1",
  3989. "title": "Identity task",
  3990. "priority": "2",
  3991. })
  3992. identity_task = task_id_tmp
  3993. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == identity_task
  3994. for p in fake.start_payloads) or False,
  3995. timeout=60, what="identity task dispatched") is not None,
  3996. "identity task dispatches")
  3997. payload = [p for p in fake.start_payloads
  3998. if int(p.get("task", {}).get("id") or 0) == identity_task][-1]
  3999. identity = payload.get("git_identity") or {}
  4000. check(identity.get("name") == "clanker-bot"
  4001. and identity.get("email") == "bot@unitatem.net",
  4002. "the assignment carries the saddle's git_identity")
  4003. # Earlier assignments (identity unset) carry no git_identity member.
  4004. check(all("git_identity" not in p for p in fake.start_payloads[:-1]),
  4005. "unset identity omits the member (daemon fallback applies)")
  4006. # Clearing the identity omits it from later assignments.
  4007. fake_card = saddle_card(auth, "fake-saddle")
  4008. act(auth, fake_card["update_identity"], {"git_name": "", "git_email": ""})
  4009. check(saddle_card(auth, "fake-saddle").get("git_name", "") == "",
  4010. "clearing the identity empties the row")
  4011. check(wait_task_done(auth, identity_task, timeout=60) is not None,
  4012. "identity task completes")
  4013. print("== phase 2: blocked push -> block row + pulse ==")
  4014. # The browser flow on each pulse: statum.act(task.refresh) — the
  4015. # sealed GET action must rehydrate the task slot with the new
  4016. # block the daemon just PUSHED (state blocked + block payload).
  4017. task_id_tmp = create_queued(auth, {
  4018. "project_id": "1",
  4019. "title": "Live block task",
  4020. "priority": "2",
  4021. })
  4022. live_task = task_id_tmp
  4023. check(wait_for(lambda: task_state(auth, live_task).get("status") == "working"
  4024. or False, timeout=60, what="live task working") is not None,
  4025. "live-block task reaches working")
  4026. fake.hold_state = True
  4027. fake.state = "blocked" # the daemon parks on its question
  4028. status = fake.push_results("blocked", block={
  4029. "question": "Pick one", "type": "question", "options": ["A", "B"]})
  4030. check(status == 200, "blocked state push accepted")
  4031. # The parked daemon is idle-awake: it asks (and sleeps on 204).
  4032. fake.maybe_trigger_ask("parked")
  4033. check(wait_for(lambda: any(b.get("question") == "Pick one"
  4034. for b in task_state(auth, live_task).get("blocks", []))
  4035. or False, timeout=30, what="block lands in state") is not None,
  4036. "the pushed block reaches the sealed refresh without a reload")
  4037. detail = task_state(auth, live_task)
  4038. check(detail.get("status") == "blocked",
  4039. "the blocked push flips the task to blocked")
  4040. pushed_block = [b for b in detail["blocks"] if b.get("question") == "Pick one"][0]
  4041. conn = db()
  4042. options_json = conn.execute(
  4043. "select options from task_blocks where id = ?", (int(pushed_block["id"]),)
  4044. ).fetchone()[0]
  4045. conn.close()
  4046. check(json.loads(options_json) == ["A", "B"],
  4047. "the block row carries its options payload")
  4048. check(any(s["status"] == "idle"
  4049. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  4050. "the blocked push parks the saddle")
  4051. detail = task_state(auth, live_task)
  4052. check(detail.get("refresh") is not None,
  4053. "the sealed GET refresh action is still authored")
  4054. status, _ = http("GET", detail["refresh"]["uri"], timeout=15)
  4055. check(status in (200, 401),
  4056. "the refresh URI resolves as a GET (client roundtrip shape)")
  4057. act(auth, pushed_block["answer_action"], {"answer": "A"})
  4058. # The answer makes the parked task resume-offerable: the affine
  4059. # saddle is woken, asks, and its assignment carries the answer.
  4060. pushes_before = len([p for p in fake.start_payloads
  4061. if int(p.get("task", {}).get("id") or 0) == live_task])
  4062. check(wait_for(lambda: len([p for p in fake.start_payloads
  4063. if int(p.get("task", {}).get("id") or 0) == live_task])
  4064. > pushes_before or False, timeout=60,
  4065. what="blocked task resumes") is not None,
  4066. "answering the pushed block resumes the parked workspace")
  4067. fake.hold_state = False # the resumed round runs to completion
  4068. resume_payload = [p for p in fake.start_payloads
  4069. if int(p.get("task", {}).get("id") or 0) == live_task][-1]
  4070. answers = resume_payload.get("task", {}).get("answers", [])
  4071. check(any(a.get("answer") == "A" for a in answers),
  4072. "the resume assignment carries the human's answer")
  4073. check(wait_task_done(auth, live_task, timeout=60) is not None,
  4074. "live-block task completes after answering")
  4075. # =============================================================================
  4076. # Bundle: answers — the answer-resume machinery in both daemon shapes
  4077. # (sleeping affine wake, mid-round verdict delivery), offline requeue
  4078. # keeping parked-with-answered tasks, the staleness probe, and the
  4079. # startup token migration (this shard's one deliberate app restart).
  4080. # =============================================================================
  4081. def bundle_answers(ctx):
  4082. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4083. app = ctx.app
  4084. print("== phase 2: answer resume — wake -> ask -> affinity claim ==")
  4085. # The full live sequence against a daemon that asks after its
  4086. # park: ask -> assignment -> blocked push (park) -> ask -> 204
  4087. # -> sleeps (row idle) -> human answers -> the dispatcher WAKES
  4088. # the sleeping affine saddle -> its ask allocates the resume,
  4089. # the verdict riding the assignment -> the session continues.
  4090. # A private capability tag keeps the fleet's other sleeping
  4091. # saddles from claiming these tasks.
  4092. saddles_state = slot_public(auth, "/saddles", "saddles")
  4093. act(auth, saddles_state["create_capability"], {"name": "answerflow"})
  4094. answerflow_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  4095. if c["name"] == "answerflow"][0])
  4096. def answerflow_daemon(**kwargs):
  4097. daemon = FakeSaddle()
  4098. daemon.ask_on_register = False # manual, deterministic asks
  4099. daemon.hold_state = True # the tests drive the lifecycle
  4100. for key, value in kwargs.items():
  4101. setattr(daemon, key, value)
  4102. daemon.serve()
  4103. return daemon
  4104. def register_answerflow(daemon, name):
  4105. act(auth, slot_public(auth, "/saddles", "saddles")["register"], {
  4106. "name": name, "host": "127.0.0.1:%d" % daemon.port})
  4107. act(auth, saddle_card(auth, name)["attach_capability"],
  4108. {"capability_id": str(answerflow_cap)})
  4109. def create_answerflow_task(title):
  4110. return create_queued(auth, {
  4111. "project_id": "1", "title": title, "priority": "2",
  4112. "capability_id": [str(answerflow_cap)]})
  4113. def retire_daemon(daemon, name):
  4114. # deterministic teardown: a dead daemon and an offline row
  4115. # never interfere with the sections that follow
  4116. daemon.kill()
  4117. act(auth, saddle_card(auth, name)["refresh"], {})
  4118. sleeper = answerflow_daemon(ask_on_wake=True)
  4119. register_answerflow(sleeper, "resume-sleeper")
  4120. sleeping_task = create_answerflow_task("Sleeping resume task")
  4121. ask_status, assignment = sleeper.ask_now()
  4122. check(ask_status == 200 and int(assignment["task"]["id"]) == sleeping_task,
  4123. "the daemon's ask claims the queued task")
  4124. sleeping_session = assignment.get("session_id")
  4125. sleeper.state = "blocked"
  4126. check(sleeper.push_results("blocked", block={
  4127. "question": "Pick a side", "type": "question",
  4128. "options": ["Port", "Starboard"]}) == 200,
  4129. "the blocked push parks the session")
  4130. check(wait_for(lambda: task_state(auth, sleeping_task).get("status") == "blocked"
  4131. or False, timeout=30, what="sleeping task parked") is not None,
  4132. "the task parks as blocked")
  4133. check(saddle_card(auth, "resume-sleeper")["status"] == "idle",
  4134. "the parked session's saddle row reads idle")
  4135. ask_status, _ = sleeper.ask_now()
  4136. check(ask_status == 204,
  4137. "the parked daemon's ask returns 204 — it sleeps until woken")
  4138. # Converted sleep(3): ticks pass with the daemon asleep and no
  4139. # wake may arrive — a wake during the window fails loudly.
  4140. check(quiet_window(quiet_seconds(),
  4141. lambda: len(sleeper.wake_log) == 0,
  4142. "sleeping daemon never woken"),
  4143. "the sleeping daemon is never woken while the block waits")
  4144. detail = task_state(auth, sleeping_task)
  4145. side_block = [b for b in detail["blocks"] if b["question"] == "Pick a side"][0]
  4146. act(auth, side_block["answer_action"], {"option": "Starboard"})
  4147. check(wait_for(lambda: len(sleeper.wake_log) > 0 or False,
  4148. timeout=30, what="wake after the answer") is not None,
  4149. "answering the block wakes the sleeping affine saddle")
  4150. # Answering = allocating (plan 11): the resume assignment carries
  4151. # the verdict as resume_notice (stable wording) AND a FRESH
  4152. # session id — the parked row closed, the daemon keys its resumed
  4153. # pushes on the new one.
  4154. check(wait_for(lambda: any(
  4155. int(p.get("task", {}).get("id") or 0) == sleeping_task
  4156. and p.get("session_id") != sleeping_session
  4157. and p.get("resume_notice") == "Human selected: Starboard"
  4158. and any(a.get("answer") == "Starboard"
  4159. for a in p.get("task", {}).get("answers", []))
  4160. for p in sleeper.start_payloads[1:]) or False,
  4161. timeout=30, what="resume allocation carries the verdict") is not None,
  4162. "the woken daemon's ask allocates the resume — fresh session, notice carried")
  4163. # Barrier: the resume's own working push must commit before the
  4164. # manual done push (a late working write would otherwise race the
  4165. # completion's full-row write).
  4166. check(wait_for(lambda: task_state(auth, sleeping_task).get("status") == "working"
  4167. or False, timeout=15, what="resumed round working") is not None,
  4168. "the resumed round reports working before its completion push")
  4169. # The resumed round runs to completion keyed on the fresh session.
  4170. sleeper.push_results("done", summary="sleep-resumed round complete")
  4171. check(wait_task_done(auth, sleeping_task, timeout=30) is not None,
  4172. "the resumed session continues to completion")
  4173. conn = db()
  4174. rows = conn.execute(
  4175. "select id, outcome, ended_at is not null from sessions where task_id = ?"
  4176. " order by id", (sleeping_task,)).fetchall()
  4177. conn.close()
  4178. check(len(rows) == 2 and rows[0][1] == "resumed" and rows[0][2]
  4179. and rows[1][1] == "done" and rows[1][2],
  4180. "parked session closed 'resumed'; the resumed round ran on a fresh row to done (%s)"
  4181. % (rows,))
  4182. retire_daemon(sleeper, "resume-sleeper")
  4183. print("== phase 2: answer resume — the parked daemon is woken (POST /answer retired) ==")
  4184. # Post Task A every park FREES the daemon: after the blocked push
  4185. # it lands idle and asks (204). The retired POST /answer channel
  4186. # always refuses; the verdict reaches the parked workspace purely
  4187. # through the wake -> ask -> affinity allocation carrying the
  4188. # resume_notice + a fresh session id.
  4189. parked = answerflow_daemon(ask_on_wake=True,
  4190. ask_on_terminal=False)
  4191. register_answerflow(parked, "resume-parked")
  4192. parked_task = create_answerflow_task("Parked resume task")
  4193. ask_status, assignment = parked.ask_now()
  4194. check(ask_status == 200 and int(assignment["task"]["id"]) == parked_task,
  4195. "the daemon's ask claims the task")
  4196. parked_session = assignment.get("session_id")
  4197. parked.state = "blocked"
  4198. check(parked.push_results("blocked", block={
  4199. "question": "Which database?", "type": "question",
  4200. "options": ["SQLite", "Postgres"]}) == 200,
  4201. "the blocked push parks the session mid-round")
  4202. check(wait_for(lambda: task_state(auth, parked_task).get("status") == "blocked"
  4203. or False, timeout=30, what="parked task blocked") is not None,
  4204. "the task parks as blocked")
  4205. check(saddle_card(auth, "resume-parked")["status"] == "idle",
  4206. "the parked session's saddle row reads idle")
  4207. # The freed daemon re-asks (its idle loop) and sleeps on 204.
  4208. ask_status, _ = parked.ask_now()
  4209. check(ask_status == 204,
  4210. "the freed parked daemon asks again and sleeps (204)")
  4211. # The retired channel always refuses — the web never depends on it.
  4212. request = urllib.request.Request(
  4213. "http://127.0.0.1:%d/answer" % parked.port,
  4214. data=json.dumps({"answer": "SQLite", "branch_advanced": False}).encode(),
  4215. method="POST")
  4216. request.add_header("Content-Type", "application/json")
  4217. try:
  4218. urllib.request.urlopen(request, timeout=5)
  4219. refused = False
  4220. except urllib.error.HTTPError as error:
  4221. refused = error.code == 409
  4222. check(refused, "POST /answer always refuses (409) — parks resume via allocation")
  4223. detail = task_state(auth, parked_task)
  4224. db_block = [b for b in detail["blocks"] if b["question"] == "Which database?"][0]
  4225. act(auth, db_block["answer_action"], {"option": "SQLite"})
  4226. check(wait_for(lambda: len(parked.wake_log) > 0 or False,
  4227. timeout=30, what="wake after the answer") is not None,
  4228. "answering the block wakes the parked (idle) affine saddle")
  4229. check(wait_for(lambda: any(
  4230. int(p.get("task", {}).get("id") or 0) == parked_task
  4231. and p.get("session_id") != parked_session
  4232. and p.get("resume_notice") == "Human selected: SQLite"
  4233. for p in parked.start_payloads[1:]) or False,
  4234. timeout=30, what="parked resume allocation") is not None,
  4235. "the parked daemon's ask allocates the resume — fresh session, formatted notice")
  4236. # The hold_state daemon drives its round manually: the resumed
  4237. # round completes on the fresh session row.
  4238. parked.push_results("done", summary="parked round resumed and finished")
  4239. check(wait_task_done(auth, parked_task, timeout=90) is not None,
  4240. "the parked session continues to completion")
  4241. conn = db()
  4242. row = conn.execute("select outcome from sessions where id = ?",
  4243. (parked_session,)).fetchone()
  4244. session_rows = conn.execute(
  4245. "select id, outcome from sessions where task_id = ? order by id",
  4246. (parked_task,)).fetchall()
  4247. conn.close()
  4248. check(row is not None and row[0] == "resumed"
  4249. and len(session_rows) == 2 and session_rows[0] == (parked_session, "resumed"),
  4250. "the parked session closed 'resumed' and the resumed round kept its own row (%s)"
  4251. % (session_rows,))
  4252. retire_daemon(parked, "resume-parked")
  4253. print("== plan 11: plan acceptance — accept / reject / auto-approve ==")
  4254. # A type 'plan' block parks like any other; Accept and
  4255. # Reject-with-feedback drive the same wake -> ask -> allocation
  4256. # resume as any verdict, the stable wording riding the
  4257. # resume_notice. Plan 12: the daemon only SENDS plan blocks on
  4258. # goal runs now (the goal page owns the review); this covers the
  4259. # generic verdict path a goal-run's mirrored block also uses. The
  4260. # auto-approve option is gone.
  4261. planner = answerflow_daemon(ask_on_wake=True, ask_on_terminal=False)
  4262. register_answerflow(planner, "plan-planner")
  4263. def park_on_plan(task_id, markdown):
  4264. planner.state = "blocked"
  4265. check(planner.push_results("blocked", block={
  4266. "question": "Plan submitted for review", "type": "plan",
  4267. "body": markdown}) == 200,
  4268. "the plan push parks the session")
  4269. # Wait for the block row itself (the auto-approve variant is
  4270. # answered — and may resume — before any status poll lands).
  4271. check(wait_for(lambda: any(b["block_type"] == "plan"
  4272. for b in task_state(auth, task_id)["blocks"])
  4273. or False, timeout=30, what="plan block raised") is not None,
  4274. "the plan block reaches the task")
  4275. return [b for b in task_state(auth, task_id)["blocks"]
  4276. if b["block_type"] == "plan"][0]
  4277. # (a) Accept resumes with the approval notice.
  4278. accept_task = create_answerflow_task("Plan accept task")
  4279. ask_status, accept_assignment = planner.ask_now()
  4280. check(ask_status == 200 and int(accept_assignment["task"]["id"]) == accept_task,
  4281. "the planner claims the accept task")
  4282. accept_parked_session = accept_assignment.get("session_id")
  4283. plan_block = park_on_plan(accept_task, "# Steps\n\n1. Wire\n2. Test")
  4284. check(plan_block.get("answered") is not True,
  4285. "the plan block waits for a human verdict")
  4286. act(auth, plan_block["answer_action"],
  4287. {"answer": "Plan approved. Proceed with implementation."})
  4288. check(wait_for(lambda: any(
  4289. int(p.get("task", {}).get("id") or 0) == accept_task
  4290. and p.get("session_id") != accept_parked_session
  4291. and p.get("resume_notice") == "Plan approved. Proceed with implementation."
  4292. for p in planner.start_payloads[1:]) or False,
  4293. timeout=30, what="accept resume allocation") is not None,
  4294. "accept resumes the parked daemon with the approval notice")
  4295. planner.push_results("done", summary="plan accepted and implemented")
  4296. check(wait_task_done(auth, accept_task, timeout=60) is not None,
  4297. "the accepted plan's task completes")
  4298. planner.set_state("idle")
  4299. # (b) Reject-with-feedback loops the feedback notice back.
  4300. reject_task = create_answerflow_task("Plan reject task")
  4301. ask_status, reject_assignment = planner.ask_now()
  4302. check(ask_status == 200 and int(reject_assignment["task"]["id"]) == reject_task,
  4303. "the planner claims the reject task")
  4304. reject_parked_session = reject_assignment.get("session_id")
  4305. plan_block = park_on_plan(reject_task, "# Draft\n\nJust wing it")
  4306. act(auth, plan_block["answer_action"], {"feedback": "Add a test section"})
  4307. reject_block = [b for b in task_state(auth, reject_task)["blocks"]
  4308. if b["block_type"] == "plan"][0]
  4309. check(reject_block.get("answer")
  4310. == "Plan feedback received:\nAdd a test section",
  4311. "reject stores the feedback in the stable wording (%s)"
  4312. % reject_block.get("answer"))
  4313. check(wait_for(lambda: any(
  4314. int(p.get("task", {}).get("id") or 0) == reject_task
  4315. and p.get("session_id") != reject_parked_session
  4316. and p.get("resume_notice") == "Plan feedback received:\nAdd a test section"
  4317. for p in planner.start_payloads[1:]) or False,
  4318. timeout=30, what="reject resume allocation") is not None,
  4319. "reject resumes the parked daemon with the feedback notice")
  4320. planner.push_results("done", summary="plan revised and delivered")
  4321. check(wait_task_done(auth, reject_task, timeout=60) is not None,
  4322. "the revised plan's task completes")
  4323. planner.set_state("idle")
  4324. retire_daemon(planner, "plan-planner")
  4325. print("== phase 2: offline requeue keeps parked-with-answered tasks ==")
  4326. # A daemon dying while its parked task carries an answered
  4327. # verdict: going offline must not requeue the task or close its
  4328. # session — the resume machinery (delivery once the daemon
  4329. # returns, or the affinity allocation on its next ask) needs
  4330. # both. The question park leaves the row idle; the review park
  4331. # keeps it busy@task (`saddle review` blocks the round without
  4332. # a parking state push), exercising the unreachable path's
  4333. # requeue decision both ways.
  4334. stranded = answerflow_daemon()
  4335. register_answerflow(stranded, "resume-stranded")
  4336. stranded_task = create_answerflow_task("Stranded answered task")
  4337. ask_status, _ = stranded.ask_now()
  4338. check(ask_status == 200, "the stranded daemon claims its task")
  4339. stranded.state = "blocked"
  4340. stranded.push_results("blocked", block={
  4341. "question": "Hold or fold?", "type": "question", "options": ["Hold", "Fold"]})
  4342. check(wait_for(lambda: task_state(auth, stranded_task).get("status") == "blocked"
  4343. or False, timeout=30, what="stranded task parked") is not None,
  4344. "the stranded task parks as blocked")
  4345. detail = task_state(auth, stranded_task)
  4346. hold_block = [b for b in detail["blocks"] if b["question"] == "Hold or fold?"][0]
  4347. act(auth, hold_block["answer_action"], {"option": "Hold"})
  4348. stranded.kill() # the daemon dies before the verdict is delivered
  4349. act(auth, saddle_card(auth, "resume-stranded")["refresh"], {})
  4350. check(wait_for(lambda: saddle_card(auth, "resume-stranded")["status"] == "offline"
  4351. or False, timeout=30, what="stranded saddle offline") is not None,
  4352. "the dead daemon's saddle row goes offline")
  4353. # Converted sleep(7): offline ticks run while the task MUST stay
  4354. # parked — a requeue during the window fails loudly.
  4355. check(quiet_window(quiet_seconds(),
  4356. lambda: task_state(auth, stranded_task)["status"] == "blocked",
  4357. "stranded task not requeued"),
  4358. "the parked-with-answered task is not requeued by the offline pass")
  4359. conn = db()
  4360. open_session = conn.execute(
  4361. "select count(*) from sessions where task_id = ? and ended_at is null",
  4362. (stranded_task,)).fetchone()[0]
  4363. conn.close()
  4364. check(open_session == 1,
  4365. "the parked-with-answered task keeps its open session for the resume")
  4366. reviewer = answerflow_daemon(ask_on_terminal=False)
  4367. register_answerflow(reviewer, "resume-reviewer")
  4368. review_task = create_answerflow_task("Review park task")
  4369. ask_status, _ = reviewer.ask_now()
  4370. check(ask_status == 200, "the reviewer claims its task")
  4371. # Post Task A the review park frees the daemon: the blocked push
  4372. # carries the review block and parks the row idle.
  4373. reviewer.state = "blocked"
  4374. check(reviewer.push_results("blocked", block={
  4375. "question": "Review requested", "type": "review",
  4376. "body": "Ready for review: wired and tested."}) == 200,
  4377. "the review park push carries the review block")
  4378. check(wait_for(lambda: task_state(auth, review_task).get("status") == "review_requested"
  4379. or False, timeout=30, what="review park raised") is not None,
  4380. "the review block parks the task as review_requested (row freed)")
  4381. # The verdict lands (nothing delivers it anymore); THEN the daemon
  4382. # dies and the manual refresh offlines it — the parked-with-answered
  4383. # task must keep its session for the eventual resume.
  4384. detail = task_state(auth, review_task)
  4385. verdict_block = [b for b in detail["blocks"]
  4386. if b["block_type"] == "review"][0]
  4387. act(auth, verdict_block["answer_action"],
  4388. {"answer": "Review approved. Continue with the task."})
  4389. reviewer.kill()
  4390. act(auth, saddle_card(auth, "resume-reviewer")["refresh"], {})
  4391. check(wait_for(lambda: saddle_card(auth, "resume-reviewer")["status"] == "offline"
  4392. or False, timeout=30, what="reviewer offline") is not None,
  4393. "the dead reviewer goes offline on the failed probe")
  4394. # Converted sleep(7): offline ticks run while the task MUST stay
  4395. # review-parked — a requeue during the window fails loudly.
  4396. check(quiet_window(quiet_seconds(),
  4397. lambda: task_state(auth, review_task)["status"] == "review_requested",
  4398. "review-parked task not requeued"),
  4399. "the review-parked task with an answered verdict is never requeued")
  4400. conn = db()
  4401. open_session = conn.execute(
  4402. "select count(*) from sessions where task_id = ? and ended_at is null",
  4403. (review_task,)).fetchone()[0]
  4404. conn.close()
  4405. check(open_session == 1,
  4406. "the review-parked task keeps its open session for the resume")
  4407. print("== phase 2: staleness — one probe decides ==")
  4408. # A silent-but-alive runner (long think, nothing to flush): after
  4409. # SADDLE_STALE_S (3s here) of silence it owes ONE exceptional
  4410. # GET /status; the answer keeps it running and the silence
  4411. # episode gets no second probe.
  4412. task_id_tmp = create_queued(auth, {
  4413. "project_id": "1",
  4414. "title": "Silent thinker",
  4415. "priority": "2",
  4416. })
  4417. thinker = task_id_tmp
  4418. check(wait_for(lambda: task_state(auth, thinker).get("status") == "working"
  4419. or False, timeout=60, what="thinker working") is not None,
  4420. "silent thinker reaches working")
  4421. fake.silent = True # the daemon goes quiet mid-round (alive)
  4422. probes_at_start = fake.status_hits
  4423. check(wait_for(lambda: fake.status_hits > probes_at_start or False,
  4424. timeout=30, what="exceptional probe arrives") is not None,
  4425. "a silent runner gets its exceptional GET /status probe")
  4426. # Converted sleep(8)+sleep(6): a quiet window across several
  4427. # ticks in which the probe count MUST NOT move — a second probe
  4428. # (the poll drumbeat this guards against) fails loudly.
  4429. second_window = fake.status_hits
  4430. check(quiet_window(quiet_seconds(),
  4431. lambda: fake.status_hits == second_window,
  4432. "no second staleness probe"),
  4433. "the silence episode is probed exactly once (no poll drumbeat)")
  4434. check(task_state(auth, thinker).get("status") == "working"
  4435. and saddle_card(auth, "fake-saddle")["status"] == "busy",
  4436. "the answered probe keeps the task running (no requeue)")
  4437. # Output flows again: the episode ends, the clock resets.
  4438. fake.silent = False
  4439. fake.push_chunks(["resumed output\r\n"])
  4440. check(wait_task_done(auth, thinker, timeout=60) is not None,
  4441. "the silent thinker completes once output flows again")
  4442. # The daemon vanishing mid-task: silence for the window, the
  4443. # probe fails, the task requeues with an agent comment and the
  4444. # saddle goes offline.
  4445. task_id_tmp = create_queued(auth, {
  4446. "project_id": "1",
  4447. "title": "Vanish victim",
  4448. "priority": "2",
  4449. })
  4450. vanish = task_id_tmp
  4451. check(wait_for(lambda: task_state(auth, vanish).get("status") == "working"
  4452. or False, timeout=60, what="vanish victim working") is not None,
  4453. "vanish victim reaches working")
  4454. fake.kill()
  4455. check(wait_for(lambda: saddle_card(auth, "fake-saddle")["status"] == "offline" or False,
  4456. timeout=60, what="daemon death -> offline") is not None,
  4457. "vanishing daemon drives the saddle offline (failed staleness probe)")
  4458. check(wait_for(lambda: any("unreachable" in c["body"]
  4459. and c.get("is_system")
  4460. for c in task_state(auth, vanish).get("comments", []))
  4461. or False, timeout=30, what="unreachable comment") is not None,
  4462. "the affected task gets an unreachable system row (never an agent comment)")
  4463. check(task_state(auth, vanish)["status"] == "queued",
  4464. "the task requeues after the daemon death")
  4465. card = saddle_card(auth, "fake-saddle")
  4466. check(card.get("health") == "offline",
  4467. "health badge reports offline")
  4468. # The unreachable row flag marks the detection window: a task the
  4469. # web still sees working while its saddle is offline/fenced, before
  4470. # the requeue pass moves it. Controlled window (the real
  4471. # transitions above are atomic with their requeues).
  4472. conn = db()
  4473. conn.execute("insert into tasks (project_id, title, status, priority,"
  4474. " created_at) values (1, 'Unreachable row', 'working', 5,"
  4475. " strftime('%s','now'))")
  4476. unreachable_row = conn.execute("select max(id) from tasks").fetchone()[0]
  4477. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  4478. " values (?, ?, strftime('%s','now'))", (unreachable_row, fake_id))
  4479. conn.commit()
  4480. conn.close()
  4481. check(wait_for(lambda: (lambda row: row.get("unreachable") is True)(
  4482. [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  4483. if int(t["id"]) == unreachable_row][0]) or False,
  4484. timeout=20, what="unreachable flag") is not None,
  4485. "queue row shows the unreachable state in the window")
  4486. print("== phase 1: startup migrates the per-saddle token ==")
  4487. # Saddles registered before the flip hold legacy api_tokens rows.
  4488. # On startup every saddle row gets its canonical token: the
  4489. # legacy value it already holds (daemons keep their credential)
  4490. # or a freshly minted one. Fixture: this shard's own racer.
  4491. fake2 = FakeSaddle()
  4492. fake2.ask_on_register = False
  4493. fake2.serve(port=free_port())
  4494. saddles_state = slot_public(auth, "/saddles", "saddles")
  4495. act(auth, saddles_state["register"], {"name": "racer-two",
  4496. "host": "127.0.0.1:%d" % fake2.port})
  4497. racer_two_id = int([s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  4498. if s["name"] == "racer-two"][0]["id"])
  4499. conn = db()
  4500. conn.execute("insert into api_tokens (saddle_id, token, created_at)"
  4501. " values (?, 'saddle-legacy-copied-token', strftime('%s','now'))",
  4502. (racer_two_id,))
  4503. conn.execute("update saddles set token = null where name = 'racer-two'")
  4504. conn.execute("insert into saddles (name, host, status, current_task_id)"
  4505. " values ('tokenless-orphan', '127.0.0.1:1', 'offline', 0)")
  4506. conn.commit()
  4507. conn.close()
  4508. app.terminate()
  4509. app.wait(timeout=10)
  4510. app = start_app()
  4511. auth = login("admin", "adminpass123")
  4512. ctx.app = app # teardown tracks the restarted process
  4513. ctx.auth = auth
  4514. def saddle_row(name):
  4515. conn = db()
  4516. try:
  4517. return conn.execute("select id, token from saddles where name = ?",
  4518. (name,)).fetchone()
  4519. finally:
  4520. conn.close()
  4521. check(wait_for(lambda: saddle_row("tokenless-orphan") is not None
  4522. and (saddle_row("tokenless-orphan")[1] or "").startswith("saddle-")
  4523. or False, timeout=20, what="tokenless row minted") is not None,
  4524. "startup mints a token for a saddle row without one")
  4525. check(wait_for(lambda: saddle_row("racer-two") is not None
  4526. and saddle_row("racer-two")[1] == "saddle-legacy-copied-token"
  4527. or False, timeout=20, what="legacy token copied") is not None,
  4528. "startup copies the legacy api_tokens value onto the row")
  4529. fake2.token = "saddle-legacy-copied-token" # the daemon asks with it
  4530. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-legacy-copied-token")
  4531. check(status in (200, 204),
  4532. "the legacy token still authenticates (copied, not replaced)")
  4533. conn = db()
  4534. conn.execute("delete from saddles where name = 'tokenless-orphan'")
  4535. conn.commit()
  4536. conn.close()
  4537. # The restart wiped the in-memory ask bookkeeping; the fleet's
  4538. # daemons re-establish sleeping with a fresh ask each (the real
  4539. # daemons' idle-awake ask / 15-minute safety self-ask).
  4540. for daemon in (fake2,):
  4541. daemon.ask_now()
  4542. check(True, "fleet re-asks after the restart (sleeping re-established)")
  4543. # =============================================================================
  4544. # Bundle: push — plan 11 task E: real Web Push over VAPID. VAPID
  4545. # persistence, the service worker, subscription CRUD + validation,
  4546. # notify-me prefs, the block/lifecycle dispatch matrix (global vs
  4547. # opted-in), 410 pruning, retry-next-tick delivery and protocol-level
  4548. # payload verification (RFC 8291 decryption + ES256 JWT) against the
  4549. # fake push service.
  4550. # =============================================================================
  4551. def bundle_push(ctx):
  4552. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4553. def subscription_count(endpoint):
  4554. conn = db()
  4555. try:
  4556. return conn.execute(
  4557. "select count(*) from push_subscriptions where endpoint = ?",
  4558. (endpoint,)).fetchone()[0]
  4559. finally:
  4560. conn.close()
  4561. print("== task E: service worker asset ==")
  4562. status, sw = http("GET", "/sw.js", timeout=15)
  4563. check(status == 200 and "addEventListener('push'" in sw
  4564. and "notificationclick" in sw and "clients.openWindow" in sw,
  4565. "the service worker serves at the origin root with push + click routing")
  4566. print("== task E: VAPID keypair generation + persistence ==")
  4567. config = json.load(open(os.path.join(WORK, "web-config.json")))
  4568. vapid = config.get("vapid") or {}
  4569. check(bool(vapid.get("public_key")) and bool(vapid.get("private_key")),
  4570. "the VAPID keypair persists into web-config.json's vapid section")
  4571. vapid_private_key = ec.derive_private_key(
  4572. int.from_bytes(b64url_dec(vapid["private_key"]), "big"), ec.SECP256R1())
  4573. derived_public = vapid_private_key.public_key().public_bytes(
  4574. Encoding.X962, PublicFormat.UncompressedPoint)
  4575. check(b64url_dec(vapid["public_key"]) == derived_public,
  4576. "the persisted public key matches the private scalar (a valid P-256 pair)")
  4577. dash = slot_public(auth, "/", "dashboard")
  4578. check(dash.get("push_vapid_key") == vapid["public_key"],
  4579. "the dashboard exposes the same VAPID key to subscribers")
  4580. check(dash.get("push_subscribed") is False and bool(dash.get("push_subscribe")),
  4581. "the bell starts unsubscribed and carries the subscribe action")
  4582. print("== task E: subscription CRUD + auth validation ==")
  4583. browser = ec.generate_private_key(ec.SECP256R1())
  4584. browser_public = browser.public_key().public_bytes(
  4585. Encoding.X962, PublicFormat.UncompressedPoint)
  4586. browser_auth = os.urandom(16)
  4587. subscribe_fields = {"p256dh": b64url(browser_public), "auth": b64url(browser_auth)}
  4588. valid_endpoint = "http://127.0.0.1:1/x"
  4589. check("absolute http(s)" in (action_notify(act(auth, dash["push_subscribe"],
  4590. {"endpoint": "ftp://example.com/push", **subscribe_fields})) or ""),
  4591. "a non-http endpoint is rejected")
  4592. check("p256dh" in (action_notify(act(auth, dash["push_subscribe"],
  4593. {"endpoint": valid_endpoint, "p256dh": b64url(os.urandom(64)),
  4594. "auth": subscribe_fields["auth"]})) or ""),
  4595. "a malformed p256dh point is rejected")
  4596. check("auth" in (action_notify(act(auth, dash["push_subscribe"],
  4597. {"endpoint": valid_endpoint, "p256dh": subscribe_fields["p256dh"],
  4598. "auth": b64url(os.urandom(15))})) or ""),
  4599. "a malformed auth secret is rejected")
  4600. push = FakePushService()
  4601. push.serve()
  4602. endpoint_main = push.url("/main")
  4603. act(auth, dash["push_subscribe"],
  4604. {"endpoint": endpoint_main, **subscribe_fields})
  4605. conn = db()
  4606. rows = conn.execute("select user_id, p256dh, auth from push_subscriptions"
  4607. " where endpoint = ?", (endpoint_main,)).fetchall()
  4608. admin_id = conn.execute("select id from spry_users where username = 'admin'"
  4609. ).fetchone()[0]
  4610. conn.close()
  4611. check(len(rows) == 1 and rows[0][0] == admin_id,
  4612. "a valid subscription stores against the signed-in user")
  4613. # Re-subscribing the same endpoint replaces (never duplicates).
  4614. rotated_auth = os.urandom(16)
  4615. act(auth, dash["push_subscribe"],
  4616. {"endpoint": endpoint_main, "p256dh": subscribe_fields["p256dh"],
  4617. "auth": b64url(rotated_auth)})
  4618. conn = db()
  4619. rows = conn.execute("select auth from push_subscriptions where endpoint = ?",
  4620. (endpoint_main,)).fetchall()
  4621. conn.close()
  4622. check(len(rows) == 1 and rows[0][0] == b64url(rotated_auth),
  4623. "re-subscribing an endpoint replaces its keys in place")
  4624. print("== task E: notify-me pref persistence ==")
  4625. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4626. {"project_id": "1", "title": "Push pref task", "priority": "5"})
  4627. pref_task = task_id_of("Push pref task")
  4628. act(auth, task_state(auth, pref_task)["toggle_notify"], {})
  4629. conn = db()
  4630. check(conn.execute("select count(*) from task_notify_prefs where task_id = ?"
  4631. " and user_id = ?", (pref_task, admin_id)).fetchone()[0] == 1,
  4632. "Notify me persists a task_notify_prefs row for the user")
  4633. conn.close()
  4634. check(task_state(auth, pref_task).get("notify_me") is True,
  4635. "the task slot reflects notify_me after the toggle")
  4636. act(auth, task_state(auth, pref_task)["toggle_notify"], {})
  4637. conn = db()
  4638. check(conn.execute("select count(*) from task_notify_prefs where task_id = ?",
  4639. (pref_task,)).fetchone()[0] == 0,
  4640. "Don't notify me removes the pref row")
  4641. conn.close()
  4642. check(task_state(auth, pref_task).get("notify_me") is False,
  4643. "the task slot reflects the opt-out")
  4644. print("== task E: dispatch matrix — global blocks vs opted-in lifecycle ==")
  4645. # Two "browsers" for admin (/main, /gone) and one for another user
  4646. # (id 999, rows seeded directly — push targeting is per user).
  4647. endpoint_gone = push.url("/gone")
  4648. push.status_for["/gone"] = 410
  4649. act(auth, dash["push_subscribe"],
  4650. {"endpoint": endpoint_gone, **subscribe_fields})
  4651. other_browser = ec.generate_private_key(ec.SECP256R1())
  4652. other_public = other_browser.public_key().public_bytes(
  4653. Encoding.X962, PublicFormat.UncompressedPoint)
  4654. other_auth = os.urandom(16)
  4655. endpoint_other = push.url("/other")
  4656. conn = db()
  4657. conn.execute("insert into push_subscriptions (user_id, endpoint, p256dh, auth,"
  4658. " created_at) values (999, ?, ?, ?, strftime('%s','now'))",
  4659. (endpoint_other, b64url(other_public), b64url(other_auth)))
  4660. conn.commit()
  4661. conn.close()
  4662. # Task 1: admin opted in via the UI toggle; the other user is not.
  4663. # Baselines are captured BEFORE the enqueue: the first-start push
  4664. # fires at the allocation, the instant the dispatch lands.
  4665. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4666. {"project_id": "1", "title": "Push lifecycle task", "priority": "5"})
  4667. task1 = task_id_of("Push lifecycle task")
  4668. act(auth, task_state(auth, task1)["toggle_notify"], {})
  4669. main_before = len(push.hits("/main"))
  4670. other_before = len(push.hits("/other"))
  4671. gone_before = len(push.hits("/gone"))
  4672. enqueue_task(auth, task1)
  4673. check(wait_for(lambda: fake.running_task == task1 or False, timeout=30,
  4674. what="task 1 assignment") is not None,
  4675. "task 1 dispatches to the fake daemon")
  4676. task1_session = fake.session_id
  4677. check(wait_for(lambda: len(push.hits("/main")) > main_before, timeout=15,
  4678. what="first-start push to the opted-in admin") is not None,
  4679. "first start notifies the opted-in user's subscription")
  4680. check(wait_for(lambda: len(push.hits("/gone")) > gone_before, timeout=15,
  4681. what="first-start push to the gone endpoint") is not None,
  4682. "first start reaches every subscription of the opted-in user")
  4683. check(quiet_window(quiet_seconds(),
  4684. lambda: len(push.hits("/other")) == other_before,
  4685. "no first-start push to the not-opted-in user"),
  4686. "first start never reaches users without the notify pref")
  4687. check(wait_task_done(auth, task1, timeout=60) is not None,
  4688. "task 1 completes")
  4689. _, done_payload = decrypt_webpush(push.hits("/main")[-1], browser,
  4690. browser_public, rotated_auth)
  4691. check(done_payload["title"] == "Push lifecycle task — completed"
  4692. and done_payload["url"] == "/tasks/%d" % task1,
  4693. "completion notifies the opted-in user (decrypted payload)")
  4694. check(len(push.hits("/other")) == other_before,
  4695. "completion stays with the opted-in user only")
  4696. check(wait_for(lambda: subscription_count(endpoint_gone) == 0, timeout=15,
  4697. what="410 endpoint pruned") is not None,
  4698. "a 410 Gone endpoint is pruned from push_subscriptions")
  4699. # Block events go to EVERY push-subscribed user globally.
  4700. main_before = len(push.hits("/main"))
  4701. other_before = len(push.hits("/other"))
  4702. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  4703. {"type": "block", "session_id": task1_session, "data": {
  4704. "question": "Global question for everyone?", "type": "question"}})
  4705. check(wait_for(lambda: len(push.hits("/main")) > main_before
  4706. and len(push.hits("/other")) > other_before, timeout=15,
  4707. what="global block push") is not None,
  4708. "a raised block notifies every push-subscribed user globally")
  4709. block_hit = push.hits("/other")[-1]
  4710. _, payload = decrypt_webpush(block_hit, other_browser, other_public, other_auth)
  4711. check(payload["title"] == "Push lifecycle task — question raised"
  4712. and payload["body"] == "Global question for everyone?"
  4713. and payload["url"] == "/tasks/%d" % task1,
  4714. "the block payload carries task title + kind, question and click URL (%s)"
  4715. % payload)
  4716. ciphertext_len = len(block_hit["body"]) - (21 + 65)
  4717. envelope = block_hit["body"]
  4718. record_size = int.from_bytes(envelope[16:20], "big")
  4719. # rs = plaintext + delimiter (1) + tag (16) == ciphertext-with-tag len.
  4720. check(record_size == ciphertext_len,
  4721. "the RFC 8291 envelope record size covers payload + delimiter + tag")
  4722. claims = verify_vapid(block_hit, vapid["public_key"], vapid["private_key"])
  4723. check(claims.get("aud") == "http://127.0.0.1:%d" % push.port
  4724. and claims.get("sub", "").startswith("mailto:")
  4725. and claims.get("exp", 0) > time.time(),
  4726. "the VAPID JWT verifies: aud = the endpoint origin, mailto sub, future exp")
  4727. check(block_hit["headers"].get("ttl") == "60"
  4728. and block_hit["headers"].get("content-type") == "application/octet-stream",
  4729. "the push POST carries TTL and the encrypted content type")
  4730. # Task 2: only the OTHER user opted in — start + failure reach them
  4731. # alone. Baseline again before the enqueue (first start fires at
  4732. # the allocation).
  4733. fake.fail_next = True
  4734. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4735. {"project_id": "1", "title": "Push failure task", "priority": "5"})
  4736. task2 = task_id_of("Push failure task")
  4737. conn = db()
  4738. conn.execute("insert into task_notify_prefs (task_id, user_id) values (?, 999)",
  4739. (task2,))
  4740. conn.commit()
  4741. conn.close()
  4742. main_before2 = len(push.hits("/main"))
  4743. other_before2 = len(push.hits("/other"))
  4744. enqueue_task(auth, task2)
  4745. check(wait_for(lambda: fake.running_task == task2 or False, timeout=30,
  4746. what="task 2 assignment") is not None,
  4747. "task 2 dispatches (scripted to fail)")
  4748. check(wait_for(lambda: task_state(auth, task2)["status"] == "failed"
  4749. or False, timeout=30, what="task 2 failed") is not None,
  4750. "task 2 fails")
  4751. check(wait_for(lambda: len(push.hits("/other")) >= other_before2 + 2,
  4752. timeout=15, what="opted-in user's started+failed pushes"),
  4753. "the opted-in user gets first start AND failure for the task")
  4754. started_hit = [hit for hit in push.hits("/other")[other_before2:]][0]
  4755. _, started_payload = decrypt_webpush(started_hit, other_browser,
  4756. other_public, other_auth)
  4757. check(started_payload["title"] == "Push failure task — started",
  4758. "the first-start payload names task + kind (%s)" % started_payload)
  4759. _, failure_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4760. other_public, other_auth)
  4761. check(failure_payload["title"] == "Push failure task — failed"
  4762. and failure_payload["url"] == "/tasks/%d" % task2,
  4763. "the failure payload names the task and links its page")
  4764. check(len(push.hits("/main")) == main_before2,
  4765. "an agent failure never reaches users without the pref")
  4766. print("== task E: retry next tick (best-effort delivery) ==")
  4767. endpoint_flaky = push.url("/flaky")
  4768. act(auth, dash["push_subscribe"],
  4769. {"endpoint": endpoint_flaky, **subscribe_fields})
  4770. push.fail_next["/flaky"] = 1
  4771. flaky_before = len(push.hits("/flaky"))
  4772. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  4773. {"type": "block", "session_id": task1_session, "data": {
  4774. "question": "Flaky delivery question?", "type": "question"}})
  4775. check(wait_for(lambda: len(push.hits("/flaky")) >= flaky_before + 2,
  4776. timeout=20, what="flaky endpoint retried") is not None,
  4777. "a failed send retries on the next dispatcher tick and lands")
  4778. print("== plan 12: goal notifications — blocks/success/failure always ==")
  4779. # Goal blocks, completion approval and failure push to EVERY
  4780. # subscribed user (the mirror on the goal-run task stays quiet).
  4781. def goal_state(goal_id):
  4782. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  4783. push_goal = None
  4784. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4785. "project_id": "1", "title": "Push goal", "brief": "Notifies everyone.",
  4786. "branch_name": "goal/push"})
  4787. conn = db()
  4788. row = conn.execute("select id from goals where title = 'Push goal'").fetchone()
  4789. conn.close()
  4790. push_goal = int(row[0])
  4791. fake.goal_script = [("plan", "# Push plan\n\n1. Ring the bells")]
  4792. main_before = len(push.hits("/main"))
  4793. other_before = len(push.hits("/other"))
  4794. act(auth, goal_state(push_goal)["start"], {})
  4795. check(wait_for(lambda: goal_state(push_goal)["status"] == "plan_review" or False,
  4796. timeout=60, what="push goal enters plan review") is not None,
  4797. "the push goal reaches plan review")
  4798. check(wait_for(lambda: len(push.hits("/main")) > main_before
  4799. and len(push.hits("/other")) > other_before, timeout=15,
  4800. what="goal plan-review push") is not None,
  4801. "a goal plan review notifies every subscribed user globally")
  4802. _, plan_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4803. other_public, other_auth)
  4804. check("Push goal" in plan_payload["title"] and "plan" in plan_payload["title"]
  4805. and plan_payload["url"] == "/goals/%d" % push_goal,
  4806. "the goal block payload carries the goal title + click URL (%s)"
  4807. % plan_payload)
  4808. main_before = len(push.hits("/main"))
  4809. fake.goal_script = [("suspend",)]
  4810. act(auth, goal_state(push_goal)["plan_pending_block"]["answer_action"],
  4811. {"answer": "Plan approved. Proceed with implementation."})
  4812. check(wait_for(lambda: goal_state(push_goal)["status"] == "active" or False,
  4813. timeout=30, what="push goal active") is not None,
  4814. "the push goal activates")
  4815. check(quiet_window(3, lambda: len(push.hits("/main")) == main_before,
  4816. "no push for an internal resume"),
  4817. "the goal agent's own park/resume does not notify (internal)")
  4818. # `saddle failure` in goal context fails the goal — global push.
  4819. fake.goal_script = [("fail", "the harness collapsed")]
  4820. other_before2 = len(push.hits("/other"))
  4821. main_before2 = len(push.hits("/main"))
  4822. conn = db()
  4823. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  4824. " priority, completed_at, created_at) values (1, ?, 'task',"
  4825. " 'Warm', 'done', 5,"
  4826. " strftime('%s','now'),"
  4827. " strftime('%s','now','-30 seconds'))", (push_goal,))
  4828. conn.commit()
  4829. conn.close()
  4830. check(wait_for(lambda: goal_state(push_goal)["status"] == "failed" or False,
  4831. timeout=60, what="goal failure lands") is not None,
  4832. "the goal agent's failure fails the goal")
  4833. check(wait_for(lambda: len(push.hits("/other")) > other_before2
  4834. and len(push.hits("/main")) > main_before2, timeout=15,
  4835. what="goal failure push") is not None,
  4836. "a goal failure notifies every subscribed user globally")
  4837. _, fail_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4838. other_public, other_auth)
  4839. check("Push goal" in fail_payload["title"] and "failed" in fail_payload["title"]
  4840. and fail_payload["url"] == "/goals/%d" % push_goal,
  4841. "the goal failure payload carries the goal title + click URL (%s)"
  4842. % fail_payload)
  4843. # Completion approval pushes "complete" globally (success always).
  4844. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4845. "project_id": "1", "title": "Push done goal", "brief": "Completes.",
  4846. "branch_name": "goal/push-done"})
  4847. conn = db()
  4848. row = conn.execute("select id from goals where title = 'Push done goal'").fetchone()
  4849. conn.close()
  4850. done_goal = int(row[0])
  4851. fake.goal_script = [("plan", "# Done plan")]
  4852. act(auth, goal_state(done_goal)["start"], {})
  4853. check(wait_for(lambda: goal_state(done_goal)["status"] == "plan_review" or False,
  4854. timeout=60, what="done goal plan review") is not None,
  4855. "the done goal reaches plan review")
  4856. fake.goal_script = [("done", "# Completion\n\nShipped.")]
  4857. act(auth, goal_state(done_goal)["plan_pending_block"]["answer_action"],
  4858. {"answer": "Plan approved. Proceed with implementation."})
  4859. check(wait_for(lambda: goal_state(done_goal)["status"] == "completion_review"
  4860. or False, timeout=60, what="done goal completion review") is not None,
  4861. "the approved done goal reaches completion review")
  4862. main_before = len(push.hits("/main"))
  4863. act(auth, goal_state(done_goal)["completion_pending_block"]["answer_action"],
  4864. {"answer": "Review approved. Continue with the task."})
  4865. check(wait_for(lambda: goal_state(done_goal)["status"] == "complete" or False,
  4866. timeout=30, what="done goal completes") is not None,
  4867. "the done goal completes")
  4868. check(wait_for(lambda: len(push.hits("/main")) > main_before, timeout=15,
  4869. what="goal success push") is not None,
  4870. "a goal completion notifies every subscribed user globally")
  4871. _, done_goal_payload = decrypt_webpush(push.hits("/main")[-1], browser,
  4872. browser_public, rotated_auth)
  4873. check("Push done goal" in done_goal_payload["title"]
  4874. and "complete" in done_goal_payload["title"]
  4875. and done_goal_payload["url"] == "/goals/%d" % done_goal,
  4876. "the goal success payload carries the goal title + click URL (%s)"
  4877. % done_goal_payload)
  4878. print("== task E: unsubscribe removes the subscription ==")
  4879. dash = slot_public(auth, "/", "dashboard")
  4880. check(dash.get("push_subscribed") is True,
  4881. "the bell shows subscribed while endpoints exist")
  4882. act(auth, dash["push_unsubscribe"], {"endpoint": endpoint_main})
  4883. check(subscription_count(endpoint_main) == 0,
  4884. "unsubscribing removes the endpoint's row")
  4885. # =============================================================================
  4886. # Bundle: goals — the plan-12 goal lifecycle: creation with branch-name
  4887. # uniqueness, the start → planning → plan review → active flow with
  4888. # revisions, the goal agent's task fan-out through the task CLI
  4889. # callbacks (ownership + creator-only enqueue), the event-driven
  4890. # coalesced resume, pause/resume queueing, the completion review with
  4891. # branch push state, the cancel cascade, and the human tasks'
  4892. # auto-enqueue-after predecessor.
  4893. # =============================================================================
  4894. def bundle_goals(ctx):
  4895. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4896. app = ctx.app
  4897. def goal_state(goal_id):
  4898. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  4899. def create_goal(fields):
  4900. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  4901. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  4902. if g["title"] == fields["title"]]
  4903. return int(rows[0]["id"])
  4904. print("== plan 12: goal creation, validation, lifecycle actions ==")
  4905. goal1 = create_goal({"project_id": "1", "title": "Ship the flange",
  4906. "brief": "Make the flange module production-grade.",
  4907. "branch_name": "goal/flange", "priority": "3"})
  4908. state = goal_state(goal1)
  4909. check(state["status"] == "draft" and state["display"] == "draft"
  4910. and state["branch_name"] == "goal/flange"
  4911. and state["base_branch"] == "main",
  4912. "a goal lands in draft with its branch pair")
  4913. check(state.get("start") is not None and state.get("cancel") is not None
  4914. and state.get("pause") is None,
  4915. "draft offers start + cancel only")
  4916. check(state["run_task_id"] == 0 and state["comments"] == [],
  4917. "a draft goal has no thread yet (the run task owns it)")
  4918. draft_page = http_get_page(auth, "/goals/%d" % goal1)
  4919. check('stm-if="goal.run_task_id &gt; 0" stm-action="goal.comment"' in draft_page
  4920. and "comments open with its run" in draft_page,
  4921. "the draft goal page gates the composer on the run (muted note until then)")
  4922. # Branch-name uniqueness: same name, same involved project → refuse.
  4923. duplicate_directives = act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4924. "project_id": "1", "title": "Clash", "brief": "b", "branch_name": "goal/flange"})
  4925. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  4926. and "goal/flange" in (d.get("message") or "")
  4927. for d in duplicate_directives),
  4928. "a live goal's branch name cannot be reused in an involved project (%s)"
  4929. % [d.get("message") for d in duplicate_directives if d.get("type") == "notify"])
  4930. conn = db()
  4931. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  4932. " values ('other-repo', 'https://example.com/other.git', 'main',"
  4933. " strftime('%s','now'))")
  4934. conn.commit()
  4935. conn.close()
  4936. goal_elsewhere = create_goal({"project_id": "2", "title": "Elsewhere",
  4937. "brief": "b", "branch_name": "goal/flange"})
  4938. check(goal_elsewhere > 0,
  4939. "the same branch name in a disjoint project is fine (one per repo)")
  4940. # Brief validation.
  4941. brief_directives = act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4942. "project_id": "1", "title": "No brief", "brief": " ", "branch_name": "goal/x1"})
  4943. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  4944. and "brief" in (d.get("message") or "").lower()
  4945. for d in brief_directives),
  4946. "an empty brief rejects")
  4947. # Start: planning + the goal-run internal task.
  4948. act(auth, state["start"], {})
  4949. state = goal_state(goal1)
  4950. check(state["status"] == "planning" and state.get("start") is None,
  4951. "start moves the goal to planning")
  4952. conn = db()
  4953. run_row = conn.execute(
  4954. "select id, kind, mode, creator, goal_id, priority, status from tasks"
  4955. " where goal_id = ? and kind = 'goal_run'", (goal1,)).fetchone()
  4956. conn.close()
  4957. check(run_row is not None and run_row[1] == "goal_run"
  4958. and run_row[2] == "orchestrate" and run_row[3] == "goal"
  4959. and run_row[4] == goal1 and run_row[5] == 3
  4960. and run_row[6] in ("queued", "assigned", "working"),
  4961. "start creates the goal-run task (orchestrate, priority 3, creator goal,"
  4962. " queued)")
  4963. run_task = int(run_row[0])
  4964. check(goal_state(goal1)["run_task_id"] == run_task,
  4965. "the goal state carries the run task id")
  4966. check(any(e["kind"] == "started" for e in goal_state(goal1)["events"]),
  4967. "the narrative records the start")
  4968. print("== feedback: goal-agent runs are hidden from every task listing ==")
  4969. # The internal run task never lists anywhere tasks are browsed —
  4970. # only the goal page exposes it (worker tasks stay listed). The
  4971. # plan script is armed BEFORE the first dispatch so this section's
  4972. # waits never consume the round the plan-review flow below needs.
  4973. fake.goal_script = [("plan", "# Plan v1\n\n1. Add tests\n2. Ship")]
  4974. check(wait_for(lambda: task_state(auth, run_task)["status"]
  4975. in ("assigned", "working") or False,
  4976. timeout=60, what="run task dispatches") is not None,
  4977. "the run task reaches its saddle")
  4978. queue_rows = slot_public(auth, "/tasks", "tasks")["tasks"]
  4979. check(all(int(t["id"]) != run_task for t in queue_rows),
  4980. "the tasks queue never lists the goal-agent run task")
  4981. check(all(t["kind"] != "goal_run" for t in queue_rows),
  4982. "no goal_run rows leak into the queue at all")
  4983. project_state = slot_public(auth, "/projects/1", "project")
  4984. check(all(int(t["id"]) != run_task for t in project_state["tasks"]),
  4985. "the project page's task list excludes the run task")
  4986. dashboard = slot_public(auth, "/", "dashboard")
  4987. check(all(int(a["id"]) != run_task for a in dashboard["active_tasks"]),
  4988. "the dashboard's active tasks exclude the run task")
  4989. check(all(int(i["task_id"]) != run_task for i in dashboard["activity"]),
  4990. "the activity timeline never references the run task")
  4991. check(wait_for(lambda: int(next(
  4992. (s for s in slot_public(auth, "/", "dashboard")["saddles"]
  4993. if s["name"] == "fake-saddle"), {})
  4994. .get("current_goal_id") or 0) == goal1 or False,
  4995. timeout=30, what="saddle card links the goal") is not None,
  4996. "a saddle hosting the goal agent reads as supervising the goal")
  4997. fake_dash_card = next(s for s in slot_public(auth, "/", "dashboard")["saddles"]
  4998. if s["name"] == "fake-saddle")
  4999. check(fake_dash_card["current_goal_title"] == "Ship the flange",
  5000. "the supervision link carries the goal title")
  5001. print("== plan 12: the goal agent plans, plan review, revisions ==")
  5002. # (The plan script was armed before the run's first dispatch — see
  5003. # the listing-hiding section above — so the first round submits it.)
  5004. check(wait_for(lambda: goal_state(goal1)["status"] == "plan_review" or False,
  5005. timeout=120, what="goal agent submits its plan") is not None,
  5006. "the goal agent's plan push enters plan review")
  5007. state = goal_state(goal1)
  5008. check(task_state(auth, run_task)["status"] == "blocked",
  5009. "the goal-run task parks on the plan review")
  5010. pending = state.get("plan_pending_block")
  5011. check(pending and "# Plan v1" in (pending.get("body") or ""),
  5012. "the pending plan review carries the submitted markdown")
  5013. check(any(b["block_type"] == "plan" and b["is_plan_review"]
  5014. for b in state["blocks"]),
  5015. "the goal blocks list carries the pending plan block")
  5016. print("== feedback: goal visual identity ==")
  5017. # A goal never reads as a task at a glance: marked nav entry,
  5018. # iconed list page, and the dashboard pile's goal cards carry
  5019. # their own accent styling.
  5020. home_html = http_get_page(auth, "/")
  5021. check('class="nav-goal"' in home_html and "&#127919;" in home_html,
  5022. "the nav carries the marked 🎯 Goals entry beside Tasks")
  5023. check(any(p["item_type"] == "goal" for p in
  5024. slot_public(auth, "/", "dashboard")["pinned"]),
  5025. "the goal's pending block pins onto the dashboard pile")
  5026. check("'card goal-card'" in home_html and 'badge-kind-goal' in home_html,
  5027. "dashboard goal cards carry the distinct goal styling")
  5028. goals_html = http_get_page(auth, "/goals")
  5029. check("&#127919;" in goals_html and "goal-icon" in goals_html,
  5030. "the goals list page carries the goal icon")
  5031. goal_page_html = http_get_page(auth, "/goals/%d" % goal1)
  5032. check('class="card goal-head"' in goal_page_html and "goal-page" in goal_page_html,
  5033. "the goal page carries the goal-accented identity chrome")
  5034. # Reject with feedback: the agent revises.
  5035. fake.goal_script = [("plan", "# Plan v2\n\n1. Add tests\n2. Add docs\n3. Ship")]
  5036. reject_resume_index = len(fake.goal_assignments)
  5037. act(auth, pending["answer_action"], {"answer": "Add documentation please"})
  5038. check(wait_for(lambda: goal_state(goal1)["status"] == "plan_review" or False,
  5039. timeout=60, what="revised plan enters review") is not None,
  5040. "feedback sends the agent back to planning; the revision re-enters review")
  5041. # The rejection resume carried NO context_update (nothing in the
  5042. # instruction context had changed).
  5043. check(all("context_update" not in p
  5044. for p in fake.goal_assignments[reject_resume_index:]),
  5045. "a resume without context changes carries no context_update")
  5046. state = goal_state(goal1)
  5047. revisions = state["plan_revisions"]
  5048. check(len(revisions) == 2
  5049. and revisions[0]["answered"] and "Add documentation please" in revisions[0]["answer"]
  5050. and not revisions[1]["answered"],
  5051. "rejected revisions stay as answered history (historical-blocks data)")
  5052. # Plan 16 S1 pin: goals.plan is accept-gated — the pending revision
  5053. # lives only in its block; nothing lands on the goal before accept.
  5054. conn = db()
  5055. plan_column = conn.execute(
  5056. "select plan from goals where id = ?", (goal1,)).fetchone()[0]
  5057. conn.close()
  5058. check((plan_column is None or plan_column == "")
  5059. and (state["plan"] or "") == "",
  5060. "goals.plan stays empty while the revision is only pending (accept-gated, S1)")
  5061. # Approve: goal.plan = v2, status active, agent resumes and parks.
  5062. fake.goal_script = [("suspend",)]
  5063. pending = state["plan_pending_block"]
  5064. act(auth, pending["answer_action"],
  5065. {"answer": "Plan approved. Proceed with implementation."})
  5066. check(wait_for(lambda: goal_state(goal1)["status"] == "active" or False,
  5067. timeout=60, what="approved plan activates the goal") is not None,
  5068. "approving the plan activates the goal")
  5069. state = goal_state(goal1)
  5070. check(state["plan"] == "# Plan v2\n\n1. Add tests\n2. Add docs\n3. Ship",
  5071. "the approved plan markdown is stored on the goal (the accept verdict's write)")
  5072. # The approval resume carries the plan delta as a context_update
  5073. # turn (the prompt-cache-friendly replacement for the daemon's
  5074. # old system-prompt refresh).
  5075. check(wait_for(lambda: len(fake.goal_assignments) > 0 and
  5076. "context_update" in fake.goal_assignments[-1] or False,
  5077. timeout=30, what="approval resume carries context_update") is not None,
  5078. "the plan-approval resume carries a context_update turn")
  5079. approval_update = fake.goal_assignments[-1]["context_update"]
  5080. check("Plan approved" in approval_update and "# Plan v2" in approval_update,
  5081. "the context_update summarises the approved plan markdown")
  5082. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5083. or False, timeout=60, what="goal agent parks after approval") is not None,
  5084. "the resumed goal agent parks (saddle suspend)")
  5085. print("== plan 12: task fan-out via the task CLI callbacks ==")
  5086. # The goal agent (parked, open session on its saddle) creates,
  5087. # enqueues and deletes its tasks through /api/saddle/task/*.
  5088. conn = db()
  5089. agent_session = conn.execute(
  5090. "select id from sessions where task_id = ? and ended_at is null",
  5091. (run_task,)).fetchone()[0]
  5092. conn.close()
  5093. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5094. "session_id": agent_session, "title": "Flange tests",
  5095. "mandate": "Write the test suite for the flange module.",
  5096. "mode": "test"})
  5097. check(status == 200 and body.get("ok") is True,
  5098. "task create under the goal succeeds (%s)" % body.get("error"))
  5099. fan_task = int(body["task_id"])
  5100. detail = task_state(auth, fan_task)
  5101. check(detail["status"] == "draft" and detail["mode"] == "test"
  5102. and detail["creator"] == "goal" and detail.get("goal_id") == goal1,
  5103. "the created task is a draft goal task with its mode and creator")
  5104. check(detail["task_branch"] == "task/%d-%d" % (goal1, fan_task)
  5105. and detail["branch_from"] == "goal/flange",
  5106. "goal worker tasks get ephemeral branches cut from the goal branch")
  5107. check(any(e["kind"] == "task-created" and int(e["task_id"]) == fan_task
  5108. for e in goal_state(goal1)["events"]),
  5109. "the narrative records the agent's task creation")
  5110. # Draft until the agent enqueues; humans may not (creator-only).
  5111. check(detail.get("enqueue") is None,
  5112. "the human Enqueue action is not offered for goal tasks (creator-only)")
  5113. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  5114. "session_id": agent_session, "task_id": fan_task})
  5115. check(status == 200 and task_state(auth, fan_task)["status"] == "queued",
  5116. "task enqueue by the goal agent queues the draft")
  5117. # Ownership + shape errors, verbatim for the CLI.
  5118. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  5119. "session_id": agent_session, "task_id": 999999})
  5120. check(status == 400 and "No task exists" in (body.get("error") or ""),
  5121. "enqueue of a missing task errors verbatim")
  5122. create_queued(auth, {"project_id": "1", "title": "Innocent bystander", "priority": "4"})
  5123. bystander = task_id_of("Innocent bystander")
  5124. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  5125. "session_id": agent_session, "task_id": bystander})
  5126. check(status == 400 and "does not belong to your goal" in (body.get("error") or ""),
  5127. "the goal agent cannot touch tasks outside its goal")
  5128. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5129. "session_id": agent_session, "title": "Bad mode", "mandate": "m", "mode": "party"})
  5130. check(status == 400 and "valid modes" in (body.get("error") or ""),
  5131. "an unknown mode rejects with the valid list")
  5132. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5133. "session_id": agent_session, "title": "Bad tag", "mandate": "m",
  5134. "capabilities": ["warp-drive"]})
  5135. check(status == 400 and "warp-drive" in (body.get("error") or "")
  5136. and "valid tags" in (body.get("error") or ""),
  5137. "an unknown capability tag rejects naming the valid set")
  5138. # A plain task's session is not a goal-agent identity.
  5139. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token,
  5140. {"session_id": 999999, "title": "x", "mandate": "m"})
  5141. check(status == 400 and "session" in (body.get("error") or ""),
  5142. "an unknown session_id errors verbatim")
  5143. # Delete: draft + owned.
  5144. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5145. "session_id": agent_session, "title": "Scratch task", "mandate": "m"})
  5146. scratch = int(body["task_id"])
  5147. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  5148. "session_id": agent_session, "task_id": scratch})
  5149. check(status == 200 and not any(
  5150. t["id"] == scratch for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5151. "task delete removes the owned draft")
  5152. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  5153. "session_id": agent_session, "task_id": fan_task})
  5154. check(status == 400 and "draft" in (body.get("error") or ""),
  5155. "deleting a queued task refuses (draft only)")
  5156. print("== plan 12: goal context in the worker assignment + coalesced resume ==")
  5157. # The queued fan-out task dispatches to the daemon with the goal
  5158. # reference + ephemeral branch; its completion schedules the parked
  5159. # goal agent's resume (>= SADDLE_GOAL_RESUME_S after the event).
  5160. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == fan_task
  5161. for p in fake.start_payloads) or False,
  5162. timeout=60, what="fan-out task dispatches") is not None,
  5163. "the goal worker task dispatches")
  5164. fan_payload = [p for p in fake.start_payloads
  5165. if int(p.get("task", {}).get("id") or 0) == fan_task][-1]
  5166. goal_ctx = fan_payload.get("goal") or {}
  5167. check(goal_ctx.get("id") == goal1 and goal_ctx.get("branch") == "goal/flange"
  5168. and goal_ctx.get("base_branch") == "main"
  5169. and "flange module" in goal_ctx.get("brief", "")
  5170. and "# Plan v2" in goal_ctx.get("plan", ""),
  5171. "the worker assignment carries the goal context (read-only brief + plan)")
  5172. check(fan_payload.get("ephemeral_branch") == "task/%d-%d" % (goal1, fan_task)
  5173. and fan_payload.get("kind") == "task" and fan_payload.get("mode") == "test"
  5174. and fan_payload.get("creator") == "goal",
  5175. "the worker assignment carries the ephemeral branch + identity triplet")
  5176. check(wait_task_done(auth, fan_task, timeout=60) is not None,
  5177. "the goal worker task completes")
  5178. check(any(e["kind"] == "task-done" and int(e["task_id"]) == fan_task
  5179. for e in goal_state(goal1)["events"]),
  5180. "the narrative records the task's completion")
  5181. goal_runs_before = len(fake.goal_assignments)
  5182. check(wait_for(lambda: len(fake.goal_assignments) > goal_runs_before or False,
  5183. timeout=30, what="parked goal agent resumes") is not None,
  5184. "the task-terminal event resumes the parked goal agent")
  5185. resume_payload = fake.goal_assignments[-1]
  5186. notice = resume_payload.get("resume_notice") or ""
  5187. check("Task statuses" in notice and "Flange tests" in notice
  5188. and "done" in notice,
  5189. "the resume notice batches ALL plan task statuses")
  5190. check("New completion reports" in notice and "fake daemon finished" in notice,
  5191. "the resume notice carries the new completion report")
  5192. check("context_update" not in resume_payload,
  5193. "a later resume with no context changes omits context_update entirely")
  5194. check(resume_payload.get("kind") == "goal_run"
  5195. and resume_payload.get("mode") == "orchestrate",
  5196. "the resumed goal agent carries its identity triplet")
  5197. # The resumed agent parked again (script): two events at once must
  5198. # coalesce into ONE resume within the window.
  5199. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5200. or False, timeout=60, what="goal agent re-parks") is not None,
  5201. "the resumed goal agent parks again")
  5202. print("== feedback: goal page parity — progress feed, current activity, runs ==")
  5203. # The goal agent's runs feed the page's live surfaces: progress
  5204. # lines (green latest-first feed), the open round's newest
  5205. # activity line and its hosting saddle. Parked runs keep their
  5206. # open session, so fixtures land as rows without disturbing the
  5207. # scripted daemon.
  5208. conn = db()
  5209. open_run_session = conn.execute(
  5210. "select id from sessions where task_id = ? and ended_at is null",
  5211. (run_task,)).fetchone()[0]
  5212. conn.execute(
  5213. "insert into task_progress (task_id, summary, created_at)"
  5214. " values (?, 'Overseeing the flange fan-out', strftime('%s','now'))",
  5215. (run_task,))
  5216. conn.execute(
  5217. "insert into session_commands (session_id, command_text, type, started_at)"
  5218. " values (?, 'git -C demo log --oneline -5', 'command',"
  5219. " strftime('%s','now'))", (open_run_session,))
  5220. conn.commit()
  5221. conn.close()
  5222. # A manual refresh records the daemon's health snapshot (the
  5223. # parked daemon answers /status with its suspended state).
  5224. act(auth, saddle_card(auth, "fake-saddle")["refresh"], {})
  5225. state = goal_state(goal1)
  5226. check(state["progress"] and state["progress"][0]["summary"]
  5227. == "Overseeing the flange fan-out",
  5228. "the goal page carries the agent's live progress feed")
  5229. check(state["current_command"] == "git -C demo log --oneline -5"
  5230. and state["current_command_running"] is True,
  5231. "the current activity shows the open round's running command")
  5232. check(state["agent_saddle"] == "fake-saddle"
  5233. and "fake-saddle" in state["saddle_health"],
  5234. "the assigned agent saddle and its health display")
  5235. check(state["runs"] and state["runs"][0]["saddle_name"] == "fake-saddle"
  5236. and "session_id=" in state["runs"][0]["terminal_url"],
  5237. "the run table carries host saddles and deep-linked terminals")
  5238. goal_page = http_get_page(auth, "/goals/%d" % goal1)
  5239. check('stm-markdown="goal.brief"' in goal_page
  5240. and 'stm-markdown="goal.plan"' in goal_page
  5241. and 'stm-markdown="comment.body"' in goal_page
  5242. and 'stm-markdown="event.text"' in goal_page
  5243. and 'stm-markdown="block.body"' in goal_page,
  5244. "every long-form goal body renders through stm-markdown")
  5245. check('stm-attribute.href="run.terminal_url" target="_blank" rel="noopener"' in goal_page,
  5246. "the run table's terminal links open in a new tab")
  5247. check("progress-latest" in goal_page and "Agent progress" in goal_page,
  5248. "the green progress feed renders on the goal page")
  5249. # Plan revision history keeps its verdicts (approved + rejected).
  5250. revisions = goal_state(goal1)["plan_revisions"]
  5251. check(revisions[0]["answered"] is True and revisions[0]["approved"] is False
  5252. and revisions[1]["approved"] is True,
  5253. "plan revision history badges approved and rejected verdicts")
  5254. print("== plan 12: pause freezes supervision; events coalesce on resume ==")
  5255. state = goal_state(goal1)
  5256. act(auth, state["pause"], {})
  5257. check(goal_state(goal1)["status"] == "paused"
  5258. and goal_state(goal1).get("resume") is not None,
  5259. "an active goal pauses and offers resume")
  5260. # Terminal events under a paused goal queue without waking anybody.
  5261. # (The real completion path — complete_task — records the goal's
  5262. # task-done narrative event; the resume machinery keys on exactly
  5263. # those terminal kinds, never on the agent's own enqueue narrative.)
  5264. conn = db()
  5265. conn.execute("insert into tasks (project_id, goal_id, kind, title, status, priority,"
  5266. " summary, completed_at, created_at) values (1, ?, 'task',"
  5267. " 'Quiet task', 'done', 5, 'finished while paused',"
  5268. " strftime('%s','now'), strftime('%s','now'))", (goal1,))
  5269. quiet_id = conn.execute("select max(id) from tasks").fetchone()[0]
  5270. conn.commit()
  5271. conn.close()
  5272. paused_runs = len(fake.goal_assignments)
  5273. check(quiet_window(quiet_seconds(),
  5274. lambda: len(fake.goal_assignments) == paused_runs,
  5275. "paused goal does not resume"),
  5276. "a paused goal's events queue without scheduling a resume")
  5277. state = goal_state(goal1)
  5278. act(auth, state["resume"], {})
  5279. check(goal_state(goal1)["status"] == "active",
  5280. "resume returns the goal to active")
  5281. check(wait_for(lambda: len(fake.goal_assignments) > paused_runs or False,
  5282. timeout=30, what="queued events flush on resume") is not None,
  5283. "the queued events coalesce into the post-resume wake")
  5284. check("finished while paused" in (fake.goal_assignments[-1].get("resume_notice") or ""),
  5285. "the flushed notice reports the task that finished while paused")
  5286. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5287. or False, timeout=60, what="goal agent parks again") is not None,
  5288. "the goal agent parks again after the flush")
  5289. # The watermark consumed the flushed transition: with nothing new
  5290. # under the goal, no further resume fires (parked stays parked).
  5291. flushed_assignments = len(fake.goal_assignments)
  5292. check(quiet_window(quiet_seconds(),
  5293. lambda: len(fake.goal_assignments) == flushed_assignments,
  5294. "consumed watermark never re-fires"),
  5295. "the consumed watermark never re-fires a resume")
  5296. print("== plan 12: completion review, push state, accept ==")
  5297. # The daemon exposes goal-branch push state on /status; the web
  5298. # caches it on the goal when it probes the goal agent's saddle.
  5299. def status_extra():
  5300. return None
  5301. fake.status_extra = {"goal_branches": [
  5302. {"branch": "goal/flange", "pushed": True},
  5303. {"branch": "goal/other-repo", "pushed": False}]}
  5304. fake_card = saddle_card(auth, "fake-saddle")
  5305. act(auth, fake_card["refresh"], {})
  5306. check(wait_for(lambda: goal_state(goal1).get("push_branches") or False,
  5307. timeout=30, what="push state lands on the goal") is not None,
  5308. "the daemon's /status goal_branches exposure caches on the goal")
  5309. branches = goal_state(goal1)["push_branches"]
  5310. check({(b["branch"], b["pushed"]) for b in branches}
  5311. == {("goal/flange", True), ("goal/other-repo", False)},
  5312. "the push state renders per branch")
  5313. # the daemon's real shape carries repo too — multi-repo rows stay
  5314. # distinguishable as "repo: branch" labels
  5315. fake.status_extra = {"goal_branches": [
  5316. {"repo": "repoa", "branch": "goal/flange", "pushed": True},
  5317. {"repo": "repob", "branch": "goal/flange", "pushed": False}]}
  5318. act(auth, fake_card["refresh"], {})
  5319. check(wait_for(lambda: {b["branch"] for b in goal_state(goal1).get("push_branches") or []}
  5320. >= {"repoa: goal/flange"}, timeout=30,
  5321. what="repo-qualified push state lands") is not None,
  5322. "repo-qualified goal_branches rows render as 'repo: branch'")
  5323. fake.status_extra = None
  5324. # `saddle done` in goal context: the completion review.
  5325. fake.goal_script = [("done", "# Completion\n\nThe flange ships.")]
  5326. # Wake the parked agent: a terminal transition newer than the
  5327. # watermark (the pause-flush consumed everything up to it, so arm
  5328. # one directly with a fresh row).
  5329. conn = db()
  5330. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  5331. " priority, completed_at, created_at) values (1, ?, 'task',"
  5332. " 'Warmup', 'done', 5,"
  5333. " strftime('%s','now'),"
  5334. " strftime('%s','now','-30 seconds'))", (goal1,))
  5335. conn.commit()
  5336. conn.close()
  5337. check(wait_for(lambda: goal_state(goal1)["status"] == "completion_review" or False,
  5338. timeout=60, what="goal agent submits its completion") is not None,
  5339. "`saddle done` in goal context enters completion review")
  5340. state = goal_state(goal1)
  5341. # Plan 16 S1 (canonical-on-accept): while the review is PENDING the
  5342. # goal row carries NO report — the document lives only in its
  5343. # block; completion_report is written solely by the accept verdict.
  5344. conn = db()
  5345. pending_report_column = conn.execute(
  5346. "select completion_report from goals where id = ?", (goal1,)).fetchone()[0]
  5347. conn.close()
  5348. check((pending_report_column is None or pending_report_column == "")
  5349. and (state["completion_report"] or "") == ""
  5350. and "# Completion" in (state["completion_pending_block"].get("body") or "")
  5351. and state["completion_pending"] is True
  5352. and state["completion_pending_block"] is not None
  5353. and state["completion_pending_block"] is not False,
  5354. "the pending report lives ONLY in its block (goal row clean, S1)")
  5355. check(task_state(auth, run_task)["status"] == "blocked",
  5356. "the goal-run task parks on the completion review")
  5357. check(state["compare_url"].endswith("/compare/main...goal/flange"),
  5358. "the completion review links the compare view")
  5359. # Reject first: feedback returns the goal to active.
  5360. fake.goal_script = [("suspend",)]
  5361. act(auth, state["completion_pending_block"]["answer_action"],
  5362. {"answer": "Not done — the docs are missing"})
  5363. check(wait_for(lambda: goal_state(goal1)["status"] == "active" or False,
  5364. timeout=30, what="rejected completion reactivates") is not None,
  5365. "rejecting the completion returns the goal to active")
  5366. conn = db()
  5367. rejected_report = conn.execute(
  5368. "select completion_report from goals where id = ?", (goal1,)).fetchone()[0]
  5369. conn.close()
  5370. check(rejected_report is None or rejected_report == "",
  5371. "reject/revise leaves the goal row clean (no report leaked, S1)")
  5372. # Round 2: submit again and accept.
  5373. fake.goal_script = [("done", "# Completion v2\n\nThe flange ships, with docs.")]
  5374. conn = db()
  5375. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  5376. " priority, completed_at, created_at) values (1, ?, 'task',"
  5377. " 'Warmup2', 'done', 5,"
  5378. " strftime('%s','now'),"
  5379. " strftime('%s','now','-30 seconds'))", (goal1,))
  5380. conn.commit()
  5381. conn.close()
  5382. check(wait_for(lambda: goal_state(goal1)["status"] == "completion_review" or False,
  5383. timeout=60, what="resubmitted completion") is not None,
  5384. "the agent resubmits its completion after feedback")
  5385. state = goal_state(goal1)
  5386. # Regression (plan-15 followup): the daemon's done-park ALSO pushes a
  5387. # review-kind block payload (question "Goal completion review", the
  5388. # real daemon's wording) after the done entry raised the completion
  5389. # row — the two paths must converge on ONE row, not twin reviews.
  5390. fake.push_results("blocked", block={
  5391. "question": "Goal completion review", "type": "review",
  5392. "body": "# Completion v2\n\nThe flange ships, with docs.",
  5393. "options": None})
  5394. conn = db()
  5395. rows = conn.execute(
  5396. "select count(*) from task_blocks where task_id = ?"
  5397. " and answer is null and type in ('completion','review')",
  5398. (run_task,)).fetchone()[0]
  5399. conn.close()
  5400. check(rows == 1,
  5401. "the daemon's review-kind completion push adopts the pending row (no twin)")
  5402. state = goal_state(goal1)
  5403. review_family_in_open = [b for b in state.get("open_blocks", [])
  5404. if b.get("is_completion_review")]
  5405. check(state["completion_pending"] is True and len(review_family_in_open) == 1,
  5406. "the pending completion review renders ONCE — as the rich attention block")
  5407. fake.pending_block = None
  5408. # Stale-twin healing (live incident shape): a pre-dedupe run left BOTH
  5409. # a completion-kind and a review-kind row pending — the page must
  5410. # render ONE review all the way through, and the final verdict must
  5411. # answer BOTH rows (asserted after the arc's accept below).
  5412. conn = db()
  5413. conn.execute(
  5414. "insert into task_blocks (task_id, question, type, body, created_at)"
  5415. " values (?, 'Goal completion review (stale twin)', 'review',"
  5416. " '# Stale twin body', strftime('%s','now'))", (run_task,))
  5417. conn.commit()
  5418. conn.close()
  5419. state = goal_state(goal1)
  5420. stale_open = [b for b in state.get("open_blocks", [])
  5421. if b.get("is_completion_review")]
  5422. check(len(stale_open) == 1,
  5423. "a stale pre-dedupe twin renders NOTHING — one review only")
  5424. # Plan 15 C4: the completion-accept hard gate — the live probe
  5425. # flags still report repob's branch unpushed, so the operator's
  5426. # accept REFUSES with origin behind.
  5427. act(auth, state["completion_pending_block"]["answer_action"],
  5428. {"answer": "Review approved. Continue with the task."})
  5429. check(goal_state(goal1)["status"] == "completion_review",
  5430. "the accept REFUSES while origin is behind (hard gate, live flags)")
  5431. # Push the branch daemon-side and probe again — the flags flip
  5432. # live (no goal-row write), and the accept goes through.
  5433. fake.status_extra = {"goal_branches": [
  5434. {"repo": "repoa", "branch": "goal/flange", "pushed": True},
  5435. {"repo": "repob", "branch": "goal/flange", "pushed": True}]}
  5436. act(auth, fake_card["refresh"], {})
  5437. check(wait_for(lambda: (goal_state(goal1).get("push_branches") or [])
  5438. and all(b["pushed"] for b in goal_state(goal1)["push_branches"])
  5439. or False, timeout=30, what="pushed flags land") is not None,
  5440. "the push chips derive from the LIVE probe flags")
  5441. conn = db()
  5442. no_push_column = conn.execute(
  5443. "select count(*) from pragma_table_info('goals')"
  5444. " where name = 'branch_push_state'").fetchone()[0] == 0
  5445. conn.close()
  5446. check(no_push_column,
  5447. "no stored push snapshot exists (F9: the goal row never records it)")
  5448. state = goal_state(goal1)
  5449. act(auth, state["completion_pending_block"]["answer_action"],
  5450. {"answer": "Review approved. Continue with the task."})
  5451. check(wait_for(lambda: goal_state(goal1)["status"] == "complete" or False,
  5452. timeout=30, what="accepted completion completes") is not None,
  5453. "accepting the completion completes the goal once origin is current")
  5454. state = goal_state(goal1)
  5455. conn = db()
  5456. accepted_report = conn.execute(
  5457. "select completion_report from goals where id = ?", (goal1,)).fetchone()[0]
  5458. conn.close()
  5459. check(state["terminal"] is True and state.get("cancel") is None
  5460. and accepted_report == "# Completion v2\n\nThe flange ships, with docs."
  5461. and "# Completion v2" in state["completion_report"],
  5462. "a complete goal is terminal with the WINNING block's body as its report (S1)")
  5463. check(wait_for(lambda: task_state(auth, run_task)["status"] == "done" or False,
  5464. timeout=30, what="goal run task closes") is not None,
  5465. "approving the completion closes the goal-run task done")
  5466. conn = db()
  5467. twins_left = conn.execute(
  5468. "select count(*) from task_blocks where task_id = ?"
  5469. " and answer is null and type in ('completion','review')",
  5470. (run_task,)).fetchone()[0]
  5471. conn.close()
  5472. check(twins_left == 0,
  5473. "the verdict answered every pending completion-family row (stale twin included)")
  5474. print("== plan 15 C3: the narrative derives from the recorded shape ==")
  5475. # Content equivalence with the old projection on this run's exact
  5476. # shape: every kind the goal_events projection produced, keyed the
  5477. # same way, plus the watermark and no-ingest guarantees.
  5478. narrative = goal_state(goal1)["events"]
  5479. kinds = [e["kind"] for e in narrative]
  5480. for expected in ("created", "started", "plan-submitted", "plan-rejected",
  5481. "plan-approved", "task-created", "task-done",
  5482. "completion-submitted", "completion-rejected", "goal-approved"):
  5483. check(expected in kinds,
  5484. "the derived narrative carries the %s row" % expected)
  5485. check(all(k != "task-enqueued" and k != "resumed" and k != "retry" for k in kinds),
  5486. "timestamp-less bookkeeping kinds never return")
  5487. stamps = [e["at_display"] for e in narrative if e.get("at_display")]
  5488. check(stamps == sorted(stamps, reverse=True),
  5489. "the narrative reads newest first")
  5490. conn = db()
  5491. no_event_table = conn.execute(
  5492. "select count(*) from sqlite_master where type = 'table'"
  5493. " and name = 'goal_events'").fetchone()[0] == 0
  5494. conn.close()
  5495. check(no_event_table,
  5496. "the goal_events table is gone (no narrative rows on ingest)")
  5497. print("== plan 12: cancel cascades to the goal's tasks ==")
  5498. goal2 = create_goal({"project_id": "1", "title": "Doomed goal",
  5499. "brief": "This goal will be cancelled.",
  5500. "branch_name": "goal/doomed"})
  5501. fake.goal_script = [("suspend",)]
  5502. act(auth, goal_state(goal2)["start"], {})
  5503. conn = db()
  5504. run2 = conn.execute("select id from tasks where goal_id = ? and kind = 'goal_run'",
  5505. (goal2,)).fetchone()[0]
  5506. conn.close()
  5507. check(wait_for(lambda: task_state(auth, run2)["status"] == "suspended" or False,
  5508. timeout=60, what="doomed goal agent parks") is not None,
  5509. "the doomed goal's agent parks")
  5510. conn = db()
  5511. agent_session2 = conn.execute(
  5512. "select id from sessions where task_id = ? and ended_at is null",
  5513. (run2,)).fetchone()[0]
  5514. conn.close()
  5515. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5516. "session_id": agent_session2, "title": "Doomed draft", "mandate": "m"})
  5517. doomed_draft = int(body["task_id"])
  5518. doomed_queued_task = None
  5519. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5520. "session_id": agent_session2, "title": "Doomed runner", "mandate": "m"})
  5521. doomed_runner = int(body["task_id"])
  5522. saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  5523. {"session_id": agent_session2, "task_id": doomed_runner})
  5524. act(auth, goal_state(goal2)["cancel"], {})
  5525. check(goal_state(goal2)["status"] == "cancelled",
  5526. "the goal cancels from active (parked-agent) state")
  5527. check(task_state(auth, run2)["status"] == "failed",
  5528. "the cascade cancels the goal agent's run task")
  5529. check(wait_for(lambda: task_state(auth, doomed_runner)["status"] == "failed"
  5530. or False, timeout=30, what="cascade cancels the queued task") is not None,
  5531. "the cascade cancels the goal's queued task")
  5532. check(not any(t["id"] == doomed_draft
  5533. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5534. "the cascade deletes the goal's draft tasks")
  5535. # A cancelled goal frees its branch name.
  5536. reuse = create_goal({"project_id": "1", "title": "Reused name",
  5537. "brief": "b", "branch_name": "goal/doomed"})
  5538. check(reuse > goal2, "a cancelled goal's branch name is reusable")
  5539. print("== plan 13 B3: goal failure cascades to non-terminal tasks ==")
  5540. # A goal holding a draft, a queued task and a working task: the
  5541. # agent's failure cascades like a cancellation — drafts deleted (no
  5542. # orphan stays dispatchable), queued/working cancelled — and the
  5543. # narrative records the cascade.
  5544. collapse = create_goal({"project_id": "1", "title": "Collapse goal",
  5545. "brief": "Fails with tasks in flight.",
  5546. "branch_name": "goal/collapse"})
  5547. fake.goal_script = [("suspend",)]
  5548. act(auth, goal_state(collapse)["start"], {})
  5549. conn = db()
  5550. run3 = conn.execute("select id from tasks where goal_id = ? and kind = 'goal_run'",
  5551. (collapse,)).fetchone()[0]
  5552. conn.close()
  5553. check(wait_for(lambda: task_state(auth, run3)["status"] == "suspended" or False,
  5554. timeout=60, what="collapse goal agent parks") is not None,
  5555. "the collapse goal's agent parks first")
  5556. conn = db()
  5557. run3_session = conn.execute(
  5558. "select id from sessions where task_id = ? and ended_at is null",
  5559. (run3,)).fetchone()[0]
  5560. conn.close()
  5561. def agent_task(title):
  5562. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5563. "session_id": run3_session, "title": title, "mandate": "m"})
  5564. task_id = int(body["task_id"])
  5565. saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  5566. {"session_id": run3_session, "task_id": task_id})
  5567. return task_id
  5568. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5569. "session_id": run3_session, "title": "Collapse draft", "mandate": "m"})
  5570. collapse_draft = int(body["task_id"]) # stays draft (never enqueued)
  5571. collapse_queued = agent_task("Collapse queued")
  5572. collapse_worker = agent_task("Collapse worker")
  5573. # Both queued tasks race for the one saddle; freeze the daemon the
  5574. # moment the first dispatches so one stays genuinely WORKING (and
  5575. # the other queued) when the goal fails.
  5576. fake.hold_state = True
  5577. def collapse_working():
  5578. for task_id in (collapse_queued, collapse_worker):
  5579. if task_state(auth, task_id)["status"] == "working":
  5580. return task_id
  5581. return False
  5582. running_one = wait_for(collapse_working, timeout=60, what="a collapse task works")
  5583. check(running_one is not None,
  5584. "a collapse task reaches working before the failure")
  5585. queued_one = collapse_worker if running_one == collapse_queued else collapse_queued
  5586. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5587. {"session_id": run3_session, "state": "failed",
  5588. "summary": "the foundation crumbled"})
  5589. check(status == 200 and goal_state(collapse)["status"] == "failed",
  5590. "the agent's failure fails the goal")
  5591. check(task_state(auth, run3)["status"] == "failed",
  5592. "the failure fails the goal agent's run task")
  5593. check(wait_for(lambda: task_state(auth, queued_one)["status"] == "failed"
  5594. and task_state(auth, running_one)["status"] == "failed" or False,
  5595. timeout=30, what="failure cascade settles") is not None,
  5596. "the failure cascade cancels the queued and working tasks")
  5597. check(not any(t["id"] == collapse_draft
  5598. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5599. "the failure cascade deletes the goal's draft tasks")
  5600. state = goal_state(collapse)
  5601. check(any(e["kind"] == "cascade" for e in state["events"]),
  5602. "the narrative records the failure cascade")
  5603. check(state["draft_tasks"] == 0 and state["queued_tasks"] == 0,
  5604. "nothing under the failed goal stays dispatchable (no orphan drafts)")
  5605. check(len([e for e in state["events"] if e["kind"] == "goal-failed"]) == 1,
  5606. "the failing goal records exactly one goal-failed event")
  5607. # Plan 16 S1: the FAILURE report keeps its goal-side home (failure
  5608. # is terminal — no pending duplication exists, so unlike the
  5609. # completion report it is written at failure time).
  5610. conn = db()
  5611. failure_report = conn.execute(
  5612. "select completion_report from goals where id = ?", (collapse,)).fetchone()[0]
  5613. conn.close()
  5614. check(failure_report == "the foundation crumbled",
  5615. "fail_goal's failure report keeps its goal-side home (S1)")
  5616. fake.hold_state = False
  5617. print("== plan 12: auto-enqueue-after for human tasks ==")
  5618. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5619. "project_id": "1", "title": "Predecessor task", "priority": "4"})
  5620. predecessor = task_id_of("Predecessor task")
  5621. enqueue_task(auth, predecessor)
  5622. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5623. "project_id": "1", "title": "Successor task", "priority": "4",
  5624. "enqueue_after_task_id": str(predecessor)})
  5625. successor = task_id_of("Successor task")
  5626. check(task_state(auth, successor)["status"] == "draft"
  5627. and task_state(auth, successor).get("enqueue_after_task_id") == predecessor,
  5628. "a human task can carry an auto-enqueue predecessor")
  5629. check(wait_task_done(auth, predecessor, timeout=60) is not None,
  5630. "the predecessor completes")
  5631. check(wait_for(lambda: task_state(auth, successor)["status"] in
  5632. ("queued", "assigned", "working") or False,
  5633. timeout=30, what="successor auto-enqueues") is not None,
  5634. "the done predecessor auto-enqueues its dependent")
  5635. # Cycle validation refuses a predecessor chain that loops.
  5636. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5637. "project_id": "1", "title": "Cycle A", "priority": "4"})
  5638. cycle_a = task_id_of("Cycle A")
  5639. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5640. "project_id": "1", "title": "Cycle B", "priority": "4",
  5641. "enqueue_after_task_id": str(cycle_a)})
  5642. cycle_b = task_id_of("Cycle B")
  5643. cycle_directives = act(auth, task_state(auth, cycle_a)["update"], {
  5644. "title": "Cycle A", "description": "x", "priority": "4",
  5645. "enqueue_after_task_id": str(cycle_b)})
  5646. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  5647. and "cycle" in (d.get("message") or "").lower()
  5648. for d in cycle_directives),
  5649. "a predecessor cycle rejects with a naming error")
  5650. # A failed predecessor leaves the dependent in draft.
  5651. fake.fail_next = True
  5652. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5653. "project_id": "1", "title": "Failing predecessor", "priority": "1"})
  5654. failing_pred = task_id_of("Failing predecessor")
  5655. enqueue_task(auth, failing_pred)
  5656. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5657. "project_id": "1", "title": "Stranded successor", "priority": "4",
  5658. "enqueue_after_task_id": str(failing_pred)})
  5659. stranded = task_id_of("Stranded successor")
  5660. check(wait_for(lambda: task_state(auth, failing_pred)["status"] == "failed"
  5661. or False, timeout=60, what="failing predecessor fails") is not None,
  5662. "the scripted-failure predecessor fails")
  5663. check(quiet_window(quiet_seconds(),
  5664. lambda: task_state(auth, stranded)["status"] == "draft",
  5665. "failed predecessor leaves the draft"),
  5666. "a failed predecessor leaves its dependent in draft")
  5667. # Successor cleanup: let the queued successor finish so the
  5668. # shard's app shuts down with an empty queue.
  5669. check(wait_task_done(auth, successor, timeout=90) is not None,
  5670. "the auto-enqueued successor completes")
  5671. print("== feedback: context_update carries rule/note deltas on resume ==")
  5672. # A standalone task parks on a question; while it is parked a rule
  5673. # is attached to the project and a note lands; the resuming
  5674. # assignment carries both as the context_update markdown turn.
  5675. probe_id = create_queued(auth, {"project_id": "1", "title": "Context probe",
  5676. "priority": "4"})
  5677. check(wait_for(lambda: fake.running_task == probe_id
  5678. and task_state(auth, probe_id)["status"] == "working" or False,
  5679. timeout=60, what="probe task runs") is not None,
  5680. "the probe task dispatches")
  5681. fake.set_state("blocked")
  5682. fake.push_results("blocked", block={"type": "question",
  5683. "question": "Which database dialect?"})
  5684. check(wait_for(lambda: task_state(auth, probe_id)["status"] == "blocked" or False,
  5685. timeout=60, what="probe task blocks") is not None,
  5686. "the probe task parks on its question")
  5687. detail = task_state(auth, probe_id)
  5688. open_block = [b for b in detail["blocks"] if not b["answered"]][0]
  5689. # Backdate the parked round's start: stamps are second-resolution
  5690. # epochs, and the delta compares strictly-later — the park must
  5691. # span a real interval like an operator's would.
  5692. conn = db()
  5693. conn.execute("update sessions set started_at = strftime('%s','now') - 60"
  5694. " where id = (select min(id) from sessions where task_id = ?)",
  5695. (probe_id,))
  5696. conn.commit()
  5697. conn.close()
  5698. # While parked: a new rule attached to the project + a new note.
  5699. rules_state = slot_public(auth, "/rules", "rules")
  5700. act(auth, rules_state["create"], {
  5701. "name": "Nightly gate", "body": "Every PR must pass the nightly suite before merge."})
  5702. conn = db()
  5703. rule_id = conn.execute("select id from rules where name = 'Nightly gate'").fetchone()[0]
  5704. conn.close()
  5705. act(auth, slot_public(auth, "/projects/1", "project")["attach_rule"],
  5706. {"rule_id": str(rule_id)})
  5707. conn = db()
  5708. conn.execute("insert into project_notes (project_id, body, created_at)"
  5709. " values (1, 'The demo repo moved its CI to nightly builds.',"
  5710. " strftime('%s','now'))")
  5711. conn.commit()
  5712. check(conn.execute("select count(*) from rule_projects where rule_id = ?",
  5713. (rule_id,)).fetchone()[0] == 1,
  5714. "the rule attaches to the project while the task is parked")
  5715. conn.close()
  5716. probe_assignments = len([p for p in fake.start_payloads
  5717. if int(p.get("task", {}).get("id") or 0) == probe_id])
  5718. act(auth, open_block["answer_action"], {"answer": "postgres"})
  5719. check(wait_for(lambda: len([p for p in fake.start_payloads
  5720. if int(p.get("task", {}).get("id") or 0) == probe_id])
  5721. > probe_assignments or False, timeout=60,
  5722. what="probe task resumes") is not None,
  5723. "answering the block resumes the probe task")
  5724. probe_resume = [p for p in fake.start_payloads
  5725. if int(p.get("task", {}).get("id") or 0) == probe_id][-1]
  5726. delta = probe_resume.get("context_update") or ""
  5727. check("Rules changed" in delta and "Nightly gate" in delta
  5728. and "nightly suite" in delta,
  5729. "the resume's context_update summarises the newly attached rule")
  5730. check("New project notes" in delta and "nightly builds" in delta,
  5731. "the resume's context_update summarises the new project note")
  5732. check("Plan approved" not in delta,
  5733. "standalone resumes carry no plan section")
  5734. check(wait_task_done(auth, probe_id, timeout=60) is not None,
  5735. "the probe task completes after its resume")
  5736. # =============================================================================
  5737. # Bundle: replay — plan 13 B1/B2: the daemon-global entry dedup and the
  5738. # idempotent terminal/narrative projections. Replays the live-failure
  5739. # post-mortem shapes directly against the push channels: an outbox
  5740. # redelivery arriving under the WRONG session id after churn (and after
  5741. # a web restart), and repeated failure pushes that must still project
  5742. # exactly once. Includes this shard's one deliberate app restart (the
  5743. # dedup must survive it — it is database state, not memory).
  5744. # =============================================================================
  5745. def bundle_replay(ctx):
  5746. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  5747. app = ctx.app
  5748. def rows_for(session):
  5749. conn = db()
  5750. try:
  5751. return conn.execute(
  5752. "select count(*) from session_commands where session_id = ?",
  5753. (session,)).fetchone()[0]
  5754. finally:
  5755. conn.close()
  5756. def dedup_rows():
  5757. conn = db()
  5758. try:
  5759. return conn.execute("select count(*) from saddle_entry_dedup").fetchone()[0]
  5760. finally:
  5761. conn.close()
  5762. def open_session_on_fake(task_id):
  5763. """A fixture open session row on the shard's saddle (the churn
  5764. shape: a fresh web-side run row the daemon never really drove)."""
  5765. conn = db()
  5766. try:
  5767. conn.execute(
  5768. "insert into sessions (task_id, saddle_id, started_at)"
  5769. " values (?, ?, strftime('%s','now'))", (task_id, fake_id))
  5770. conn.commit()
  5771. return conn.execute(
  5772. "select max(id) from sessions where task_id = ?",
  5773. (task_id,)).fetchone()[0]
  5774. finally:
  5775. conn.close()
  5776. print("== plan 13 B1: entry dedup is daemon-global, not per-session ==")
  5777. # A first task runs to completion; its session is the replay source.
  5778. first = create_queued(auth, {"project_id": "1", "title": "Replay source task",
  5779. "priority": "2"})
  5780. check(wait_task_done(auth, first, timeout=60) is not None,
  5781. "the replay-source task completes")
  5782. conn = db()
  5783. src_session = conn.execute(
  5784. "select max(id) from sessions where task_id = ?", (first,)).fetchone()[0]
  5785. conn.close()
  5786. # The outbox batch: two command entries the daemon already
  5787. # delivered once (their ids landed with the source session).
  5788. burst = [
  5789. {"id": 5001, "command": "make test", "output": "ok", "exit_code": 0,
  5790. "type": "command", "timestamp": "2026-09-11T00:00:00Z"},
  5791. {"id": 5002, "command": "grep -r flange src/", "output": "src/flange.vala",
  5792. "exit_code": 0, "type": "command", "timestamp": "2026-09-11T00:00:01Z"},
  5793. ]
  5794. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5795. {"session_id": src_session, "state": "done",
  5796. "entries": burst})
  5797. check(status == 200 and rows_for(src_session) >= 2,
  5798. "the entries batch stores under its session")
  5799. stored_once = rows_for(src_session)
  5800. dedup_after_first = dedup_rows()
  5801. # Redelivery under the SAME session: consumed, nothing new.
  5802. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5803. {"session_id": src_session, "state": "done",
  5804. "entries": burst})
  5805. check(status == 200 and rows_for(src_session) == stored_once
  5806. and dedup_rows() == dedup_after_first,
  5807. "a same-session redelivery stores nothing new (consumed silently)")
  5808. # Session churn: a brand-new session id on the same saddle replays
  5809. # the SAME entry ids — the post-mortem's mis-keyed outbox send.
  5810. # The entries' ids already populated another session, so the push
  5811. # may not create rows here either.
  5812. conn = db()
  5813. conn.execute(
  5814. "insert into tasks (project_id, title, status, priority, created_at,"
  5815. " completed_at) values (1, 'Churn target task', 'done', 5,"
  5816. " strftime('%s','now'), strftime('%s','now'))")
  5817. conn.commit()
  5818. churn_task = conn.execute(
  5819. "select max(id) from tasks where title = 'Churn target task'").fetchone()[0]
  5820. conn.close()
  5821. churn_session = open_session_on_fake(churn_task)
  5822. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5823. {"session_id": churn_session, "state": "done",
  5824. "entries": burst})
  5825. check(status == 200 and rows_for(churn_session) == 0,
  5826. "replay-under-wrong-session stores nothing new (daemon-global dedup)")
  5827. check(dedup_rows() == dedup_after_first,
  5828. "the consumed redelivery claims no fresh dedup rows")
  5829. # A fresh entry id under the churned session DOES store — the dedup
  5830. # keys on the entry id, never on the session.
  5831. fresh = [{"id": 5003, "command": "git status", "output": "clean",
  5832. "exit_code": 0, "type": "command", "timestamp": "2026-09-11T00:00:02Z"}]
  5833. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5834. {"session_id": churn_session, "state": "done",
  5835. "entries": fresh})
  5836. check(status == 200 and rows_for(churn_session) == 1
  5837. and dedup_rows() == dedup_after_first + 1,
  5838. "a fresh entry id stores under any session of its saddle")
  5839. # Web restart: the dedup survives (database state, not memory).
  5840. app.terminate()
  5841. app.wait(timeout=10)
  5842. app = start_app()
  5843. auth = login("admin", "adminpass123")
  5844. ctx.app = app # teardown tracks the restarted process
  5845. ctx.auth = auth
  5846. # The restart wiped the in-memory ask bookkeeping; the daemon
  5847. # re-establishes sleeping with a fresh ask (the real daemon's
  5848. # idle-awake ask / 15-minute safety self-ask).
  5849. fake.ask_now()
  5850. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5851. {"session_id": churn_session, "state": "done",
  5852. "entries": burst + fresh})
  5853. check(status == 200 and rows_for(churn_session) == 1
  5854. and rows_for(src_session) == stored_once,
  5855. "a post-restart redelivery still stores nothing (dedup is persistent)")
  5856. print("== plan 13 B2: duplicate failed entries project once (task) ==")
  5857. # The post-mortem's honest burst: the same failure entry redelivered
  5858. # under a churned session AND a second, DISTINCT failure entry id
  5859. # in the same session — one transition, one comment, ever.
  5860. def agent_comments(task_id, body=None):
  5861. conn = db()
  5862. try:
  5863. if body is None:
  5864. return conn.execute(
  5865. "select count(*) from task_comments"
  5866. " where task_id = ? and author = 'agent'",
  5867. (task_id,)).fetchone()[0]
  5868. return conn.execute(
  5869. "select count(*) from task_comments"
  5870. " where task_id = ? and author = 'agent' and body = ?",
  5871. (task_id, body)).fetchone()[0]
  5872. finally:
  5873. conn.close()
  5874. conn = db()
  5875. conn.execute(
  5876. "insert into tasks (project_id, title, status, priority, created_at)"
  5877. " values (1, 'Burst failure task', 'working', 5, strftime('%s','now'))")
  5878. conn.commit()
  5879. burst_task = conn.execute(
  5880. "select max(id) from tasks where title = 'Burst failure task'").fetchone()[0]
  5881. conn.close()
  5882. burst_session = open_session_on_fake(burst_task)
  5883. first_fail = [{"id": 6001, "command": "saddle failure",
  5884. "output": "bash -n rejected the script", "exit_code": 1,
  5885. "type": "failed", "timestamp": "2026-09-11T00:01:00Z"}]
  5886. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5887. {"session_id": burst_session, "state": "failed",
  5888. "entries": first_fail,
  5889. "summary": "bash -n rejected the script"})
  5890. check(status == 200
  5891. and task_state(auth, burst_task)["status"] == "failed",
  5892. "the failure entry + state pair fails the task")
  5893. check(agent_comments(burst_task, "bash -n rejected the script") == 1,
  5894. "the entry path and the state path together leave one failure comment")
  5895. # The burst: a DISTINCT failure entry id in the same session, plus
  5896. # both ids redelivered under a churned session — nothing re-runs.
  5897. second_fail = [{"id": 6002, "command": "saddle failure",
  5898. "output": "bash -n rejected the script", "exit_code": 1,
  5899. "type": "failed", "timestamp": "2026-09-11T00:01:01Z"}]
  5900. churned_burst = open_session_on_fake(burst_task)
  5901. for target in (burst_session, churned_burst):
  5902. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5903. {"session_id": target, "state": "failed",
  5904. "entries": first_fail + second_fail,
  5905. "summary": "bash -n rejected the script"})
  5906. check(status == 200,
  5907. "the burst push under %s is consumed, not rejected" % (
  5908. "its session" if target == burst_session else "a churned session"))
  5909. check(task_state(auth, burst_task)["status"] == "failed"
  5910. and agent_comments(burst_task) == 1,
  5911. "duplicate failed entries leave one transition and one comment")
  5912. print("== plan 13 B2: goal failure projects once ==")
  5913. # Goal context: `saddle failure` fails the goal ONCE — the 115
  5914. # goal-failed events of the live failure are structurally gone.
  5915. def goal_state(goal_id):
  5916. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  5917. def goal_failed_events(goal_id):
  5918. # Plan 15 C3: the narrative derives at read time — the
  5919. # failed-goal row IS the goal-failed record (one row, ever).
  5920. return len([e for e in goal_state(goal_id)["events"]
  5921. if e["kind"] == "goal-failed"])
  5922. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  5923. "project_id": "1", "title": "Burst goal", "brief": "Fails honestly.",
  5924. "branch_name": "goal/burst"})
  5925. conn = db()
  5926. burst_goal = conn.execute(
  5927. "select id from goals where title = 'Burst goal'").fetchone()[0]
  5928. conn.close()
  5929. fake.goal_script = [("suspend",)]
  5930. act(auth, goal_state(burst_goal)["start"], {})
  5931. conn = db()
  5932. run_task = conn.execute(
  5933. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  5934. (burst_goal,)).fetchone()[0]
  5935. conn.close()
  5936. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5937. or False, timeout=60, what="burst goal agent parks") is not None,
  5938. "the burst goal's agent parks first")
  5939. conn = db()
  5940. run_session = conn.execute(
  5941. "select id from sessions where task_id = ? and ended_at is null",
  5942. (run_task,)).fetchone()[0]
  5943. conn.close()
  5944. goal_fail = [{"id": 7001, "command": "saddle failure",
  5945. "output": "the harness collapsed", "exit_code": 1,
  5946. "type": "failed", "timestamp": "2026-09-11T00:02:00Z"},
  5947. {"id": 7002, "command": "saddle failure",
  5948. "output": "the harness collapsed", "exit_code": 1,
  5949. "type": "failed", "timestamp": "2026-09-11T00:02:01Z"}]
  5950. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5951. {"session_id": run_session, "state": "failed",
  5952. "entries": goal_fail, "summary": "the harness collapsed"})
  5953. check(status == 200 and goal_state(burst_goal)["status"] == "failed",
  5954. "the goal agent's failure fails the goal")
  5955. check(goal_failed_events(burst_goal) == 1,
  5956. "a two-entry failure burst records exactly one goal-failed event")
  5957. # Redeliveries — same ids under the run's session AND under a
  5958. # churned session — plus the bare failed state again: still one.
  5959. churned_run = open_session_on_fake(run_task)
  5960. for target in (run_session, churned_run):
  5961. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5962. {"session_id": target, "state": "failed",
  5963. "entries": goal_fail,
  5964. "summary": "the harness collapsed"})
  5965. check(status == 200, "the goal-failure redelivery under %s is consumed"
  5966. % ("its session" if target == run_session else "a churned session"))
  5967. check(goal_state(burst_goal)["status"] == "failed"
  5968. and goal_failed_events(burst_goal) == 1,
  5969. "redelivered failures never re-run the goal failure (one event, ever)")
  5970. check(task_state(auth, run_task)["status"] == "failed",
  5971. "the goal-run task stays failed after the replays")
  5972. conn = db()
  5973. burst_blocks = conn.execute(
  5974. "select count(*) from task_blocks where task_id = ?", (run_task,)
  5975. ).fetchone()[0]
  5976. conn.close()
  5977. check(burst_blocks == 0,
  5978. "the goal-failed path raises ZERO blocks (nothing pins the pile)")
  5979. print("== plan 13 B4: the comment projection stores the body ==")
  5980. # The heredoc shape: the command is the pipe invocation, the OUTPUT
  5981. # is the body. The projections must carry the body — the command
  5982. # echo never becomes comment text, and the literal `saddle
  5983. # comment` string never renders outside the terminal.
  5984. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  5985. "project_id": "1", "title": "Comment goal", "brief": "Reports cleanly.",
  5986. "branch_name": "goal/comment"})
  5987. conn = db()
  5988. comment_goal = conn.execute(
  5989. "select id from goals where title = 'Comment goal'").fetchone()[0]
  5990. conn.close()
  5991. fake.goal_script = [("suspend",)]
  5992. act(auth, goal_state(comment_goal)["start"], {})
  5993. conn = db()
  5994. comment_run = conn.execute(
  5995. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  5996. (comment_goal,)).fetchone()[0]
  5997. conn.close()
  5998. check(wait_for(lambda: task_state(auth, comment_run)["status"] == "suspended"
  5999. or False, timeout=60, what="comment goal agent parks") is not None,
  6000. "the comment goal's agent parks")
  6001. conn = db()
  6002. comment_session = conn.execute(
  6003. "select id from sessions where task_id = ? and ended_at is null",
  6004. (comment_run,)).fetchone()[0]
  6005. conn.close()
  6006. comment_body = "The flange weld holds. First sentence carries the information."
  6007. comment_entry = [{"id": 8001, "command": "cat << 'EOF' | saddle comment",
  6008. "output": comment_body, "exit_code": 0, "type": "comment",
  6009. "timestamp": "2026-09-11T00:03:00Z"}]
  6010. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6011. {"session_id": comment_session, "state": "suspended",
  6012. "entries": comment_entry})
  6013. check(status == 200, "the comment entry push is accepted")
  6014. conn = db()
  6015. task_comment_bodies = [r[0] for r in conn.execute(
  6016. "select body from task_comments where task_id = ?", (comment_run,))]
  6017. tables = {r[0] for r in conn.execute(
  6018. "select name from sqlite_master where type = 'table'").fetchall()}
  6019. conn.close()
  6020. check(task_comment_bodies == [comment_body],
  6021. "the run task's comment stores the body, not the command echo")
  6022. check("goal_comments" not in tables,
  6023. "the goal_comments table is gone (the run task's rows are the thread)")
  6024. narrative_comments = [e["text"] for e in goal_state(comment_goal)["events"]
  6025. if e["kind"] == "comment"]
  6026. check(len(narrative_comments) == 1
  6027. and narrative_comments[0].startswith("The flange weld holds.")
  6028. and "saddle comment" not in narrative_comments[0]
  6029. and "EOF" not in narrative_comments[0],
  6030. "the derived narrative's comment rows carry the body text")
  6031. state = goal_state(comment_goal)
  6032. check(state["current_command"] == comment_body,
  6033. "the goal page's current-activity line shows the comment body")
  6034. check(state["comments"] and state["comments"][0]["body"] == comment_body
  6035. and any(e["kind"] == "comment"
  6036. and e["text"].startswith("The flange weld holds.")
  6037. for e in state["events"]),
  6038. "the goal slot carries the body in its comments and narrative")
  6039. page = http_get_page(auth, "/goals/%d" % comment_goal)
  6040. check("saddle comment" not in page,
  6041. "the rendered goal page never shows the command echo")
  6042. check("event.kind == 'comment' ? ' footnote'" in page,
  6043. "the narrative's comment events render with footnote styling")
  6044. check(page.index('stm-markdown="comment.body"')
  6045. < page.index('stm-text="comment.quote"'),
  6046. "the comment card shows the body before the quote")
  6047. # Drain: nothing queued remains for the shard's shutdown.
  6048. check(queued_count() == 0, "the replay shard drains its queue")
  6049. def bundle_goalui(ctx):
  6050. """Plan 14 workstream B + plan 15 C1: the goal supervision surface.
  6051. B1 — goal-run control parity (Retry supervision / Requeue-to-resume
  6052. on the status head, the /tasks/<goal-run-id> redirect, no
  6053. notify-me toggle), B2 — the plan-review remarks queue, B4 —
  6054. sessions.resume_notice + the terminal dropdown/resume panel, B5 —
  6055. page order, effective rules and per-task capability badges, B6 —
  6056. narrative footnote weights. C1 — the single-row block world: the
  6057. goal's blocks ARE the run task's rows (answered from every
  6058. surface through one path; no dual rows, no stragglers, at most
  6059. one review-kind block per verdict path). C4 — the goal page
  6060. batch: one muted head activity line, plan between attention and
  6061. tasks, answered blocks behind an expander, footnote comments.
  6062. C5 — the dashboard deep-link closure: goal pile cards link the
  6063. goal page, every surface settles the single row, and no
  6064. goal-side store exists to hold stragglers.
  6065. """
  6066. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  6067. def goal_state(goal_id):
  6068. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  6069. def run_task_of(goal_id):
  6070. conn = db()
  6071. try:
  6072. return int(conn.execute(
  6073. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  6074. (goal_id,)).fetchone()[0])
  6075. finally:
  6076. conn.close()
  6077. def wait_run(status, timeout=60, what="run status"):
  6078. return wait_for(lambda: task_state(auth, run_task_of(goal))["status"] == status
  6079. or False, timeout=timeout, what=what)
  6080. def pile_questions():
  6081. return [b.get("question") for b in
  6082. slot_public(auth, "/", "dashboard")["pinned"]
  6083. if b.get("item_type") == "goal"]
  6084. def open_session(task_id):
  6085. conn = db()
  6086. try:
  6087. row = conn.execute(
  6088. "select id from sessions where task_id = ? and ended_at is null",
  6089. (task_id,)).fetchone()
  6090. return int(row[0]) if row else None
  6091. finally:
  6092. conn.close()
  6093. print("== B1: the goal-run task page redirects to the goal ==")
  6094. fake.goal_script = [("plan", "# Remarks plan\n\n## Steps\n\n1. First move")]
  6095. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  6096. "project_id": "1", "title": "Goalui goal",
  6097. "brief": "Drive the plan-14 goal surface end to end.",
  6098. "branch_name": "goal/goalui"})
  6099. conn = db()
  6100. goal = conn.execute("select id from goals where title = 'Goalui goal'"
  6101. ).fetchone()[0]
  6102. conn.close()
  6103. act(auth, goal_state(goal)["start"], {})
  6104. wait_run("blocked", what="goalui goal agent parks on its plan") # plan review parks blocked
  6105. run_task = run_task_of(goal)
  6106. frames = directives("/tasks/%d" % run_task, auth)
  6107. navigations = [d for d in frames if d.get("type") == "navigate"]
  6108. check(any(d.get("uri") == "/goals/%d" % goal for d in navigations),
  6109. "the goal-run task page redirects to /goals/<id> (navigate directive)")
  6110. check(slot_public(auth, "/tasks/%d" % run_task, "task")["id"] == run_task,
  6111. "the redirect still hydrates the task slot (sealed refresh + API readers)")
  6112. status, page = http("GET", "/tasks/%d" % run_task, headers={
  6113. "X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}, timeout=15)
  6114. check(status == 200, "the compiled goal-run page serves")
  6115. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  6116. "project_id": "1", "title": "Goalui worker", "priority": "4",
  6117. "description": "A plain worker under no goal."})
  6118. conn = db()
  6119. worker = conn.execute("select id from tasks where title = 'Goalui worker'"
  6120. ).fetchone()[0]
  6121. conn.close()
  6122. check(not [d for d in directives("/tasks/%d" % worker, auth)
  6123. if d.get("type") == "navigate"],
  6124. "worker task pages render normally (no redirect)")
  6125. state = goal_state(goal)
  6126. check("toggle_notify" not in state and state.get("notify") is None,
  6127. "no notify-me toggle on the goal (goals notify unconditionally)")
  6128. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6129. check("Notify me" not in goal_page and "toggle-notify" not in goal_page,
  6130. "the goal page template ships no notify control")
  6131. check(state["branch_name"] == "goal/goalui" and state["base_branch"] == "main"
  6132. and isinstance(state["push_branches"], list)
  6133. and state["priority"] == 3
  6134. and len(state["started_display"]) > 0
  6135. and len(state["agent_saddle"]) > 0,
  6136. "the status head carries the full field set (branch pair, chips list,"
  6137. " priority, timestamps, agent saddle)")
  6138. check("Retry supervision" in goal_page and "Requeue to resume" in goal_page,
  6139. "the status head ships the run-control parity buttons")
  6140. check("status-corner" not in goal_page and "goal complete" not in goal_page
  6141. and goal_page.count("badge-yeehaw") == 1,
  6142. "yeehaw is rows-only (no goal-head corner badge; the row badge remains)")
  6143. check(goal_state(goal)["current_activity"] == "parked awaiting the plan review",
  6144. "the head line reads 'parked awaiting the plan review' while one is open")
  6145. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6146. check(goal_page.index("Goal agent blocks") < goal_page.index("<h3>Plan</h3>")
  6147. < goal_page.index("<h3>Tasks</h3>"),
  6148. "the plan section sits between attention and tasks")
  6149. check("data-plan-review" in goal_page and "Approved plan &amp; revisions" in goal_page,
  6150. "an open review renders expanded beside the collapsed approved-plan expander")
  6151. print("== B2: the plan-review remarks queue ==")
  6152. check(goal_state(goal)["status"] == "plan_review"
  6153. and goal_state(goal)["plan_pending_block"] is not None,
  6154. "the goal sits in plan review with a pending block")
  6155. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6156. review_at = goal_page.index("data-plan-review")
  6157. check(review_at > 0, "the plan review region is marked for the remarks queue")
  6158. check(goal_page.index('data-block-id="goal.plan_pending_block.id"') > 0,
  6159. "the queue keys on the pending goal block id")
  6160. body_at = goal_page.index('data-plan-body')
  6161. remarks_at = goal_page.index("data-plan-remarks")
  6162. check(body_at < remarks_at,
  6163. "the remarks queue renders at the bottom of the plan body")
  6164. for marker in ("data-plan-accept", "data-plan-toggle", "data-plan-submit",
  6165. "data-plan-remove", "plan-popover", "remarksByBlock"):
  6166. check(marker in goal_page, "the remarks queue ships %s" % marker)
  6167. check("(index + 1) + '. '" in goal_page,
  6168. "the rejection payload numbers every queued remark")
  6169. check("rejectOpenByBlock" in goal_page and "statum.afterEvaluate(syncPlanRemarks)" in goal_page,
  6170. "the queue survives pulse refreshes (maps outside statum re-renders)")
  6171. # The rejection payload exactly as the client composes it: the
  6172. # stable verdict wording, then each remark NUMBERED in queue order
  6173. # with its quote prefixed like a comment.
  6174. payload = ("Plan feedback received:\n\n"
  6175. "> ## Steps\n\n1. First move\n\n"
  6176. "1. Add a rollback step\n\n"
  6177. "2. Name the owner of the migration")
  6178. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  6179. {"answer": payload})
  6180. state = goal_state(goal)
  6181. check(state["status"] == "planning",
  6182. "the remarks rejection returns the agent to planning")
  6183. rejected = [r for r in state["plan_revisions"] if r.get("answered")]
  6184. check(any(r["answer"] == payload for r in rejected),
  6185. "the rejection carries the remarks verbatim, in order")
  6186. check(payload.index("1. Add a rollback step") < payload.index("2. Name the owner"),
  6187. "the numbering is queue-ordered")
  6188. print("== B4: resume_notice lands on the resumed session row ==")
  6189. fake.goal_script = [("question", "Which datastore?", ["SQLite", "Redis"])]
  6190. check(wait_for(lambda: goal_state(goal)["status"] == "planning" or False,
  6191. timeout=30, what="rejection observed") is not None,
  6192. "the agent revises")
  6193. # The parked plan agent resumes with the verdict; the next round
  6194. # raises the scripted question.
  6195. check(wait_for(lambda: any(b["question"] == "Which datastore?"
  6196. and not b.get("answered")
  6197. for b in goal_state(goal)["blocks"]) or False,
  6198. timeout=60, what="question raised") is not None,
  6199. "the resumed agent raises its question")
  6200. conn = db()
  6201. notices = dict(conn.execute(
  6202. "select id, resume_notice from sessions where task_id = ?", (run_task,)
  6203. ).fetchall())
  6204. conn.close()
  6205. resumed_ids = [i for i, text in notices.items() if text]
  6206. fresh_ids = [i for i, text in notices.items() if not text]
  6207. check(len(resumed_ids) >= 1 and any("Plan feedback received" in notices[i]
  6208. for i in resumed_ids),
  6209. "the resumed session stores the notice it was allocated")
  6210. check(min(notices) in fresh_ids,
  6211. "session 1 (the fresh opening round) carries no resume notice")
  6212. print("== C1: the single run-task row IS the goal's block ==")
  6213. check("Which datastore?" in pile_questions(),
  6214. "the open goal question pins onto the dashboard pile")
  6215. goal_rows = [b for b in goal_state(goal)["blocks"]
  6216. if b["question"] == "Which datastore?"]
  6217. run_rows = [b for b in task_state(auth, run_task)["blocks"]
  6218. if b["question"] == "Which datastore?"]
  6219. check(len(run_rows) == 1 and len(goal_rows) == 1
  6220. and int(run_rows[0]["id"]) == int(goal_rows[0]["id"]),
  6221. "the goal page and the run task read the SAME single row")
  6222. pile_card = [b for b in slot_public(auth, "/", "dashboard")["pinned"]
  6223. if b.get("question") == "Which datastore?"][0]
  6224. check(pile_card.get("item_type") == "goal"
  6225. and int(pile_card.get("goal_id") or 0) == goal
  6226. and int(pile_card.get("id") or 0) == int(run_rows[0]["id"])
  6227. and pile_card.get("goal_title") == "Goalui goal",
  6228. "the pile card is the run-task row styled as a goal item")
  6229. act(auth, [b for b in goal_state(goal)["blocks"]
  6230. if b["question"] == "Which datastore?" and not b.get("answered")]
  6231. [0]["answer_action"], {"option": "SQLite"})
  6232. conn = db()
  6233. unanswered = conn.execute(
  6234. "select count(*) from task_blocks where question = 'Which datastore?'"
  6235. " and answer is null").fetchone()[0]
  6236. conn.close()
  6237. check(unanswered == 0, "answering from the goal page closes the single row")
  6238. check("Which datastore?" not in pile_questions(),
  6239. "the answered row no longer pins the dashboard pile")
  6240. # The task-page deep link (the AnswerBlockAction API surface)
  6241. # answers the SAME row through the one goal path — there is no
  6242. # second row to sweep and no stale copy can survive.
  6243. conn = db()
  6244. conn.execute("insert into task_blocks (task_id, type, question, created_at)"
  6245. " values (?, 'question', 'Deep link probe?',"
  6246. " strftime('%s','now'))", (run_task,))
  6247. conn.commit()
  6248. conn.close()
  6249. check("Deep link probe?" in pile_questions(),
  6250. "the fixture row pins like any goal question")
  6251. deep_block = [b for b in task_state(auth, run_task)["blocks"]
  6252. if b["question"] == "Deep link probe?" and not b.get("answered")][0]
  6253. act(auth, deep_block["answer_action"], {"answer": "Answered via the deep link"})
  6254. conn = db()
  6255. answered_row = conn.execute(
  6256. "select answer from task_blocks where question = 'Deep link probe?'"
  6257. ).fetchone()[0]
  6258. tables = {r[0] for r in conn.execute(
  6259. "select name from sqlite_master where type = 'table'").fetchall()}
  6260. conn.close()
  6261. check(answered_row == "Answered via the deep link",
  6262. "the task-page deep link answers the same single row (the API path)")
  6263. check("Deep link probe?" not in pile_questions(),
  6264. "the deep-link answer closes the pile card too")
  6265. check("goal_blocks" not in tables,
  6266. "the goal_blocks table is gone (run-task blocks are canonical)")
  6267. print("== C5: deep-link closure on the single-row world ==")
  6268. # The pile card's goal item deep-links the goal page (the answer
  6269. # surface); answering from either surface settled THE row above.
  6270. home_markup = http_get_page(auth, "/")
  6271. check("'/goals/' + blockview.goal_id" in home_markup,
  6272. "the pile card deep-links the goal page for goal items")
  6273. conn = db()
  6274. dupes = conn.execute(
  6275. "select count(*) from (select question from task_blocks where task_id = ?"
  6276. " group by question having count(*) > 1)", (run_task,)).fetchone()[0]
  6277. stragglers = conn.execute(
  6278. "select count(*) from task_blocks where task_id = ? and answer is null",
  6279. (run_task,)).fetchone()[0]
  6280. goal_side_tables = [r[0] for r in conn.execute(
  6281. "select name from sqlite_master where type = 'table'"
  6282. " and name in ('goal_blocks','goal_comments','goal_events')").fetchall()]
  6283. conn.close()
  6284. check(dupes == 0 and stragglers == 0,
  6285. "one row per question on the run task, none left unanswered")
  6286. check(not goal_side_tables,
  6287. "no goal-side store exists — historical stragglers are impossible")
  6288. print("== B4: the terminal session dropdown + resume-info panel ==")
  6289. fake.goal_script = [("suspend",)]
  6290. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6291. or False, timeout=60, what="agent parks suspended") is not None,
  6292. "the agent parks suspended for the requeue scenario")
  6293. terminal = slot_public(auth, "/tasks/%d/terminal" % run_task, "terminal")
  6294. ids = [int(s["id"]) for s in terminal["sessions"]]
  6295. check(ids == sorted(ids, reverse=True),
  6296. "the session dropdown lists newest-first")
  6297. check(int(terminal["session_id"]) == ids[0],
  6298. "the terminal still defaults to the latest session")
  6299. labels = {int(s["id"]): s["label"] for s in terminal["sessions"]}
  6300. check(all(label.startswith("Session #") for label in labels.values()),
  6301. "dropdown labels read 'Session #N — started <time>'")
  6302. # Recompute at the check point: the C1 answers above each
  6303. # resumed the agent too, so the earlier snapshot would go stale.
  6304. conn = db()
  6305. resumed_ids = [int(i) for (i, text) in conn.execute(
  6306. "select id, resume_notice from sessions where task_id = ?",
  6307. (run_task,)).fetchall() if text]
  6308. conn.close()
  6309. resumed_markers = [i for i in ids if "[resumed]" in labels[i]]
  6310. check(set(resumed_markers) == set(resumed_ids),
  6311. "the [resumed] marker rides exactly the notice-carrying sessions")
  6312. notices_by_id = {int(s["id"]): s.get("notice") or "" for s in terminal["sessions"]}
  6313. check("Opening brief" in notices_by_id[min(ids)]
  6314. and "Drive the plan-14 goal surface" in notices_by_id[min(ids)],
  6315. "session 1's panel shows the opening-brief framing (from the goal brief)")
  6316. check(any("Plan feedback received" in (notices_by_id[i] or "") for i in resumed_ids),
  6317. "a resumed session's panel shows the stored resume notice")
  6318. terminal_page = http_get_page(auth, "/tasks/%d/terminal" % run_task)
  6319. check('id="session-select"' in terminal_page
  6320. and "window.terminalPickSession" in terminal_page,
  6321. "the session picker is an options dropdown")
  6322. check('stm-markdown="window.terminalSessionNotice(terminal)"' in terminal_page,
  6323. "the panel renders the selected session's notice as markdown")
  6324. check("No opening brief or resume notice recorded" in terminal_page,
  6325. "the panel ships its graceful empty state")
  6326. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6327. check("resume-notice-panel" in css and "max-height: 200px" in css,
  6328. "the panel is a 200px vertical-scroll strip (stylesheet)")
  6329. print("== B1: requeue-to-resume from the goal head ==")
  6330. conn = db()
  6331. conn.execute("update saddles set status = 'offline' where id = ?", (fake_id,))
  6332. conn.commit()
  6333. conn.close()
  6334. def requeue_offered():
  6335. # Act on the SAME state that satisfied the wait: a second read
  6336. # once raced the scripted daemon's ask reviving the saddle row,
  6337. # and the conditionally-authored action vanished between the
  6338. # two reads (KeyError on act).
  6339. offered = goal_state(goal)
  6340. return offered if offered.get("requeue_run") is not None else False
  6341. state = wait_for(requeue_offered, timeout=30, what="requeue offered")
  6342. check(state is not None,
  6343. "a parked run on a dead saddle offers Requeue-to-resume")
  6344. check(state.get("retry_run") is None,
  6345. "an active goal offers no Retry supervision")
  6346. open_before = open_session(run_task)
  6347. def parked_session_ended():
  6348. if open_before is None:
  6349. return True
  6350. conn = db()
  6351. try:
  6352. return conn.execute(
  6353. "select ended_at is not null from sessions where id = ?",
  6354. (open_before,)).fetchone()[0] == 1
  6355. finally:
  6356. conn.close()
  6357. act(auth, state["requeue_run"], {})
  6358. check(task_state(auth, run_task)["status"] == "queued",
  6359. "the requeue returns the run to the queue")
  6360. # The PARKED session itself must end (the restore-on-dispatch
  6361. # successor may open immediately — the check keys the old row,
  6362. # not the task's transient open-session window).
  6363. check(wait_for(parked_session_ended, timeout=60,
  6364. what="parked session closed") is not None,
  6365. "the requeue closed the parked session (restore-on-dispatch)")
  6366. conn = db()
  6367. conn.execute("update saddles set status = 'idle' where id = ?", (fake_id,))
  6368. conn.commit()
  6369. conn.close()
  6370. fake.goal_script = [("suspend",)]
  6371. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6372. or False, timeout=60, what="requeued run re-dispatches") is not None,
  6373. "the requeued run re-dispatches and re-parks")
  6374. fresh_session = open_session(run_task)
  6375. conn = db()
  6376. fresh_notice = conn.execute(
  6377. "select resume_notice from sessions where id = ?", (fresh_session,)
  6378. ).fetchone()[0]
  6379. conn.close()
  6380. check(fresh_notice is None,
  6381. "a requeue's fresh session carries no resume notice (empty panel state)")
  6382. print("== B1: Retry supervision revives a failed goal ==")
  6383. fake.push_results("failed", summary="the supervision collapsed (scripted)")
  6384. check(wait_for(lambda: goal_state(goal)["status"] == "failed" or False,
  6385. timeout=30, what="goal fails") is not None,
  6386. "the run's failure fails the goal")
  6387. check(wait_for(lambda: goal_state(goal).get("retry_run") is not None
  6388. or False, timeout=30, what="retry offered") is not None,
  6389. "a failed goal offers Retry supervision")
  6390. fake.goal_script = [("suspend",)]
  6391. act(auth, goal_state(goal)["retry_run"], {})
  6392. state = goal_state(goal)
  6393. check(state["status"] == "active",
  6394. "the retry revives supervision (goal back to active)")
  6395. check(task_state(auth, run_task)["status"] in ("queued", "assigned", "working",
  6396. "suspended", "blocked"),
  6397. "the retry re-offered the run task")
  6398. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6399. or False, timeout=60, what="retried supervision parks") is not None,
  6400. "the retried supervision dispatches and parks again")
  6401. state = goal_state(goal)
  6402. check(any(e["kind"] == "system" and "Supervision retried" in e["text"]
  6403. for e in state["events"]),
  6404. "the narrative records the supervision retry (a system row)")
  6405. print("== B5 + C4: order, effective rules, capability badges ==")
  6406. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6407. markers = [
  6408. ('class="card goal-head"', "status head"),
  6409. ("Agent progress", "progress"),
  6410. ("Goal agent blocks", "attention blocks"),
  6411. ("<h3>Plan</h3>", "plan"),
  6412. ("<h3>Tasks</h3>", "tasks"),
  6413. ("Initial brief", "brief"),
  6414. ("Involved projects", "projects"),
  6415. ("<h3>Rules</h3>", "rules"),
  6416. ("Supervision narrative", "narrative"),
  6417. ("<h3>Comments</h3>", "comments"),
  6418. ("Goal agent runs", "runs"),
  6419. ]
  6420. positions = []
  6421. for marker, _ in markers:
  6422. check(marker in goal_page, "the goal page ships the %s section" % _)
  6423. positions.append(goal_page.index(marker))
  6424. check(positions == sorted(positions),
  6425. "the page reads status → progress → attention → plan → tasks → brief →"
  6426. " rules → narrative → comments → runs (in order)")
  6427. check("goal.current_activity" in goal_page and "Current activity" not in goal_page,
  6428. "the activity lives as ONE muted head line (the card is gone)")
  6429. check(".goal-page .card" in open(os.path.join(REPO, "src/pages/app.css")).read(),
  6430. "the stylesheet restores the goal page's card rhythm (padding regression)")
  6431. rules_state = slot_public(auth, "/rules", "rules")
  6432. act(auth, rules_state["create"], {"name": "goalui-primary", "body": "Primary rule"})
  6433. act(auth, rules_state["create"], {"name": "goalui-codev", "body": "Co-dev rule"})
  6434. act(auth, rules_state["create"], {"name": "goalui-ref", "body": "Reference rule"})
  6435. conn = db()
  6436. rule_ids = {name: int(conn.execute("select id from rules where name = ?",
  6437. (name,)).fetchone()[0])
  6438. for name in ("goalui-primary", "goalui-codev", "goalui-ref")}
  6439. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  6440. " values (?, 1, strftime('%s','now'))", (rule_ids["goalui-primary"],))
  6441. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  6442. " values ('goalui-codev-project', 'https://example.com/g.git',"
  6443. " 'main', strftime('%s','now'))")
  6444. codev_project = conn.execute(
  6445. "select id from projects where name = 'goalui-codev-project'").fetchone()[0]
  6446. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  6447. " values ('goalui-ref-project', 'https://example.com/r.git',"
  6448. " 'main', strftime('%s','now'))")
  6449. ref_project = conn.execute(
  6450. "select id from projects where name = 'goalui-ref-project'").fetchone()[0]
  6451. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  6452. " values (?, ?, strftime('%s','now'))",
  6453. (rule_ids["goalui-codev"], codev_project))
  6454. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  6455. " values (?, ?, strftime('%s','now'))",
  6456. (rule_ids["goalui-ref"], ref_project))
  6457. conn.commit()
  6458. conn.close()
  6459. act(auth, goal_state(goal)["add_link"], {"linked_project_id": str(codev_project),
  6460. "relationship": "co-developed"})
  6461. act(auth, goal_state(goal)["add_link"], {"linked_project_id": str(ref_project),
  6462. "relationship": "reference"})
  6463. rule_names = [r["name"] for r in goal_state(goal)["rules"]]
  6464. check(rule_names == ["goalui-primary", "goalui-codev"],
  6465. "the Rules section lists the goal's effective set (primary then"
  6466. " co-developed; reference contributes nothing)")
  6467. act(auth, slot_public(auth, "/saddles", "saddles")["create_capability"],
  6468. {"name": "goalui-capability"})
  6469. conn = db()
  6470. capability = conn.execute(
  6471. "select id from capabilities where name = 'goalui-capability'"
  6472. ).fetchone()[0]
  6473. # The early redirect-fixture worker joins the goal (a fanned
  6474. # worker's shape) so its row carries the badge too.
  6475. conn.execute("update tasks set goal_id = ? where id = ?", (goal, worker))
  6476. conn.execute("insert into task_capabilities (task_id, capability_id)"
  6477. " values (?, ?)", (worker, capability))
  6478. conn.commit()
  6479. conn.close()
  6480. goal_worker = {"id": worker, "caps": None}
  6481. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  6482. "project_id": "1", "title": "Goalui fanned worker", "priority": "4",
  6483. "description": "A worker the agent fanned out."})
  6484. conn = db()
  6485. fanned = conn.execute(
  6486. "select id from tasks where title = 'Goalui fanned worker'").fetchone()[0]
  6487. conn.execute("update tasks set goal_id = ? where id = ?", (goal, fanned))
  6488. conn.execute("insert into task_capabilities (task_id, capability_id)"
  6489. " values (?, ?)", (fanned, capability))
  6490. conn.commit()
  6491. conn.close()
  6492. rows = {int(t["id"]): t for t in goal_state(goal)["goal_tasks"]}
  6493. check(rows[fanned].get("capabilities") == ["goalui-capability"]
  6494. and rows[worker].get("capabilities") == ["goalui-capability"],
  6495. "task rows carry their required capability tags")
  6496. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6497. check('stm-for-capability-in="goal_task.capabilities"' in goal_page
  6498. and "badge-capability" in goal_page,
  6499. "the task rows render capability badges")
  6500. print("== B6: narrative weights — events full, comments footnote ==")
  6501. # An AGENT comment projects the narrative's comment event (human
  6502. # comments only thread) — pushed through the entries channel while
  6503. # parked, so the suspended state stays put.
  6504. fake.push_results("suspended", entries=[{
  6505. "id": 9001, "command": "saddle comment", "output": "An agent aside.",
  6506. "exit_code": 0, "type": "comment", "timestamp": "2026-09-12T00:00:00Z"}])
  6507. check(wait_for(lambda: any(e["kind"] == "comment"
  6508. for e in goal_state(goal)["events"]) or False,
  6509. timeout=15, what="comment event lands") is not None,
  6510. "an agent comment lands as a narrative event")
  6511. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6512. check("stm-attribute.class=\"'goal-event' + (event.kind == 'comment'"
  6513. " ? ' footnote' : '')\"" in goal_page.replace("\n", " ").replace(" ", " ")
  6514. or "'goal-event' + (event.kind == 'comment' ? ' footnote' : '')" in goal_page,
  6515. "the WHOLE comment event row carries .footnote (badge included)")
  6516. check("'badge badge-goal-' + event.kind" in goal_page,
  6517. "non-comment events keep their full-weight kind badges")
  6518. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6519. check(".goal-event.footnote" in css and ".footnote {" in css,
  6520. "the stylesheet ships the footnote row weight beside the utility")
  6521. print("== C2: system rows render distinctly on the ONE thread ==")
  6522. run_comments = task_state(auth, run_task)["comments"]
  6523. system_rows = [c for c in run_comments if c.get("is_system")]
  6524. check(system_rows and all(c["author"] == "system" for c in system_rows)
  6525. and not any(c.get("from_agent") for c in system_rows),
  6526. "the harness bookkeeping rows are authored 'system' (never agent)")
  6527. goal_thread = goal_state(goal)["comments"]
  6528. check(any(c.get("is_system") for c in goal_thread),
  6529. "the goal page reads the same thread (the system rows included)")
  6530. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6531. check(".comment.system" in css and ".system-label" in css,
  6532. "the stylesheet ships the distinct system-event styling")
  6533. page = http_get_page(auth, "/goals/%d" % goal)
  6534. check("comment.is_system" in page and "system-label" in page,
  6535. "the goal page renders system rows with the labelled muted style")
  6536. task_page = http_get_page(auth, "/tasks/%d" % worker)
  6537. check("comment.is_system" in task_page and "system-label" in task_page,
  6538. "the task page renders system rows with the same style")
  6539. print("== C4: head line, answered-blocks expander, footnote comments ==")
  6540. state = goal_state(goal)
  6541. check(state["current_activity"] == "parked awaiting its tasks' terminal transitions",
  6542. "a suspended run folds into the one muted head line")
  6543. check(len(state.get("answered_blocks") or []) >= 2
  6544. and len(state.get("open_blocks") or []) == 0,
  6545. "the historic answered blocks expose as their own vector (open ones empty)")
  6546. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6547. check("Answered blocks (" in goal_page and "comment-meta" in goal_page,
  6548. "the answered blocks and the footnote comment meta ship in the markup")
  6549. check("timeless note for a future reader" in goal_page,
  6550. "the composer hint states the timeless-comment rule")
  6551. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6552. check(".goal-page .card { margin-bottom" in css and ".comment-meta" in css,
  6553. "the stylesheet ships the card rhythm and the comment footnote meta")
  6554. print("== C1: one review block per verdict path (F6) ==")
  6555. # The daemon's honest round pushes the ENTRY and the STATE
  6556. # together — the done pair must raise exactly ONE completion
  6557. # block, and a redelivered pair nothing more.
  6558. fake.goal_script = [("done", "# Completion\n\nOne block only.")]
  6559. conn = db()
  6560. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  6561. " priority, completed_at, created_at) values (1, ?, 'task',"
  6562. " 'Warmup', 'done', 5,"
  6563. " strftime('%s','now'),"
  6564. " strftime('%s','now','-30 seconds'))", (goal,))
  6565. conn.commit()
  6566. conn.close()
  6567. check(wait_for(lambda: goal_state(goal)["status"] == "completion_review" or False,
  6568. timeout=60, what="goalui completion review opens") is not None,
  6569. "the scripted done round enters completion review")
  6570. def completion_block_count():
  6571. conn = db()
  6572. try:
  6573. return conn.execute(
  6574. "select count(*) from task_blocks where task_id = ?"
  6575. " and type = 'completion'", (run_task,)).fetchone()[0]
  6576. finally:
  6577. conn.close()
  6578. check(completion_block_count() == 1,
  6579. "the done state raises exactly ONE completion block")
  6580. # The burst shape: the done ENTRY and the done STATE in one push
  6581. # (fresh entry ids), then the whole pair redelivered — the
  6582. # pending-report idempotency leaves the one row alone.
  6583. conn = db()
  6584. burst_session = conn.execute(
  6585. "select id from sessions where task_id = ? and ended_at is null",
  6586. (run_task,)).fetchone()[0]
  6587. conn.close()
  6588. done_pair = [{"id": 9401, "command": "saddle done",
  6589. "output": "# Completion\n\nOne block only.", "exit_code": 0,
  6590. "type": "done", "timestamp": "2026-09-12T00:00:00Z"}]
  6591. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6592. {"session_id": burst_session, "state": "done",
  6593. "entries": done_pair,
  6594. "summary": "# Completion\n\nOne block only."})
  6595. check(status == 200 and completion_block_count() == 1,
  6596. "the done entry + state pair raises nothing more (one block, ever)")
  6597. state = goal_state(goal)
  6598. act(auth, state["completion_pending_block"]["answer_action"],
  6599. {"answer": "Review approved. Continue with the task."})
  6600. check(wait_for(lambda: goal_state(goal)["status"] == "complete" or False,
  6601. timeout=30, what="goalui goal completes") is not None,
  6602. "accepting the completion completes the goal")
  6603. check(completion_block_count() == 1,
  6604. "the accept path leaves exactly one review-kind block behind")
  6605. conn = db()
  6606. stragglers = conn.execute(
  6607. "select count(*) from task_blocks where task_id = ? and answer is null",
  6608. (run_task,)).fetchone()[0]
  6609. conn.close()
  6610. check(stragglers == 0,
  6611. "no unanswered straggler rows survive the completion")
  6612. BUNDLES_ORDER = ("pages", "dispatch", "subtasks", "lineage",
  6613. "allocation", "lifecycle", "answers", "push", "goals",
  6614. "replay", "goalui")
  6615. def run_bundle(name):
  6616. """Runs one shard to completion; returns a failure count."""
  6617. started = time.monotonic()
  6618. ctx = start_bundle(name)
  6619. runner = globals()["bundle_" + name]
  6620. try:
  6621. runner(ctx)
  6622. finally:
  6623. # Exit-code diagnostic: distinguishes a crashed app (negative
  6624. # returncode, e.g. -11 SIGSEGV) from a clean shutdown. When
  6625. # tearing down mid-exception, also capture the still-alive
  6626. # app's stacks before killing it (a wedged-but-alive server
  6627. # otherwise leaves no evidence).
  6628. print("(app returncode at teardown: %s)" % ctx.app.poll())
  6629. if ctx.app.poll() is None and sys.exc_info()[0] is not None:
  6630. dump_app_stacks(ctx.app.pid)
  6631. ctx.fake.kill()
  6632. try:
  6633. ctx.app.terminate()
  6634. try:
  6635. ctx.app.wait(timeout=5)
  6636. except subprocess.TimeoutExpired:
  6637. ctx.app.kill()
  6638. check(ctx.app.poll() in (0, -15),
  6639. "bundle %s app shut down cleanly (exit %s)"
  6640. % (name, ctx.app.poll()))
  6641. except OSError:
  6642. pass
  6643. print("%d passed, %d failed" % (passes, failures))
  6644. print("[bundle %s] %.1fs" % (name, time.monotonic() - started))
  6645. return failures
  6646. def run_all_parallel():
  6647. """The default meson entry: one subprocess per bundle (each with its
  6648. own app, daemons and database), verdicts aggregated into one exit
  6649. code and one combined check-count summary."""
  6650. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  6651. log_dir = os.path.join(os.path.dirname(base) or "/tmp/kilo",
  6652. "webstack-shards")
  6653. os.makedirs(log_dir, exist_ok=True)
  6654. procs = {}
  6655. started = time.monotonic()
  6656. for name in BUNDLES_ORDER:
  6657. out_path = os.path.join(log_dir, "bundle-%s.log" % name)
  6658. handle = open(out_path, "w")
  6659. procs[name] = (subprocess.Popen(
  6660. [sys.executable, "-u", os.path.abspath(__file__), APP,
  6661. "--bundle", name],
  6662. stdout=handle, stderr=subprocess.STDOUT), handle, out_path)
  6663. total_pass = total_fail = 0
  6664. broken = []
  6665. for name, (proc, handle, out_path) in procs.items():
  6666. try:
  6667. proc.wait(timeout=SHARD_TIMEOUT_S)
  6668. except subprocess.TimeoutExpired:
  6669. proc.kill()
  6670. proc.wait()
  6671. handle.close()
  6672. text = open(out_path).read()
  6673. match = re.search(r"(\d+) passed, (\d+) failed", text)
  6674. took = re.search(r"\[bundle %s\] ([0-9.]+)s" % name, text)
  6675. bundle_pass = int(match.group(1)) if match else 0
  6676. bundle_fail = int(match.group(2)) if match else -1
  6677. total_pass += max(bundle_pass, 0)
  6678. total_fail += max(bundle_fail, 0)
  6679. status = "ok"
  6680. if proc.returncode != 0 or bundle_fail != 0 or match is None:
  6681. status = "BROKEN (exit %s)" % proc.returncode
  6682. broken.append(name)
  6683. print("[shard %-10s] %6ss %3d passed %3d failed %s"
  6684. % (name, took.group(1) if took else "?",
  6685. bundle_pass, bundle_fail, status))
  6686. if status != "ok":
  6687. tail = "\n".join(text.rstrip().split("\n")[-60:])
  6688. print("--- web-stack/%s tail (full log: %s) ---" % (name, out_path))
  6689. print(tail)
  6690. print("--- end web-stack/%s tail ---" % name)
  6691. print("shards wall: %.1fs (logs under %s)" % (time.monotonic() - started, log_dir))
  6692. print("ALL SHARDS: %d passed, %d failed%s"
  6693. % (total_pass, total_fail,
  6694. "" if not broken else " BROKEN: " + ", ".join(broken)))
  6695. return 1 if broken or total_fail else 0
  6696. def main():
  6697. if not os.path.exists(APP):
  6698. raise SystemExit("app binary not found at %s (build first)" % APP)
  6699. argv = sys.argv[2:]
  6700. if "--bundle" in argv:
  6701. sys.exit(1 if run_bundle(argv[argv.index("--bundle") + 1]) else 0)
  6702. if os.environ.get("WEBSTACK_SEQUENTIAL"):
  6703. # Debug path: every bundle in-process, one after another.
  6704. for name in BUNDLES_ORDER:
  6705. if run_bundle(name):
  6706. return 1
  6707. return 0
  6708. return run_all_parallel()
  6709. if __name__ == "__main__":
  6710. sys.exit(main())