web_stack_test.py 359 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957
  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. outcome = wait_for(lambda: (app_ready() and "ready")
  889. or (process.poll() is not None and "app-exited-%d" % process.poll())
  890. or False, timeout=30, what="app ready")
  891. if outcome is None:
  892. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  893. if str(outcome).startswith("app-exited-"):
  894. raise SystemExit("app exited during startup (%s); see %s/app.log"
  895. % outcome, WORK)
  896. return process
  897. def app_ready():
  898. try:
  899. status, _ = http("GET", "/login", timeout=3)
  900. return status == 200
  901. except (urllib.error.URLError, OSError):
  902. return False
  903. def dump_app_stacks(pid):
  904. """Best-effort thread backtrace of the (possibly wedged) app."""
  905. try:
  906. fds = os.listdir("/proc/%d/fd" % pid)
  907. print("(app open fds at dump: %d)" % len(fds))
  908. kinds = {}
  909. for fd in fds[:1200]:
  910. try:
  911. target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
  912. except OSError:
  913. continue
  914. key = target.split(":", 1)[0] if ":" in target else target
  915. kinds[key] = kinds.get(key, 0) + 1
  916. print("(fd kinds: %s)" % sorted(kinds.items(), key=lambda kv: -kv[1])[:6])
  917. except OSError:
  918. pass
  919. for command in (["eu-stack", "-p", str(pid)],
  920. ["gdb", "-batch", "-quiet", "-p", str(pid),
  921. "-ex", "thread apply all bt"]):
  922. try:
  923. out = subprocess.run(command, capture_output=True, timeout=60)
  924. text = out.stdout.decode(errors="replace") + out.stderr.decode(errors="replace")
  925. if text.strip():
  926. print("(app stacks via %s)\n%s" % (command[0], text[:12000]))
  927. return
  928. except (OSError, subprocess.SubprocessError):
  929. continue
  930. # =============================================================================
  931. # Fake push service + Web Push protocol helpers (plan 11 task E)
  932. # =============================================================================
  933. def b64url(raw):
  934. return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
  935. def b64url_dec(text):
  936. return base64.urlsafe_b64decode(text + "=" * ((4 - len(text) % 4) % 4))
  937. class FakePushService:
  938. """In-process Web Push endpoint server: every subscription the tests
  939. register points at a path here (a distinct "browser endpoint").
  940. Responses are scriptable per path — a fixed status (the 410-prune
  941. fixture) or N transient 500s (the retry-next-tick fixture)."""
  942. def __init__(self):
  943. self.requests = [] # [{"path", "headers", "body", "at"}]
  944. self.fail_next = {} # path -> remaining 500s
  945. self.status_for = {} # path -> fixed status
  946. self.lock = threading.Lock()
  947. self.port = None
  948. self.server = None
  949. def serve(self):
  950. service = self
  951. class Handler(BaseHTTPRequestHandler):
  952. protocol_version = "HTTP/1.1"
  953. def log_message(self, fmt, *args):
  954. pass
  955. def do_POST(self):
  956. length = int(self.headers.get("Content-Length") or 0)
  957. body = self.rfile.read(length)
  958. status = 201
  959. if self.path in service.status_for:
  960. status = service.status_for[self.path]
  961. elif service.fail_next.get(self.path, 0) > 0:
  962. service.fail_next[self.path] -= 1
  963. status = 500
  964. with service.lock:
  965. service.requests.append({
  966. "path": self.path,
  967. "headers": {key.lower(): value
  968. for key, value in self.headers.items()},
  969. "body": body,
  970. "at": time.monotonic(),
  971. })
  972. payload = b"{}"
  973. self.send_response(status)
  974. self.send_header("Content-Type", "application/json")
  975. self.send_header("Content-Length", str(len(payload)))
  976. self.end_headers()
  977. self.wfile.write(payload)
  978. self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
  979. self.port = self.server.server_address[1]
  980. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  981. return self.server
  982. def url(self, path):
  983. return "http://127.0.0.1:%d%s" % (self.port, path)
  984. def hits(self, prefix):
  985. with self.lock:
  986. return [request for request in self.requests
  987. if request["path"].startswith(prefix)]
  988. def decrypt_webpush(request, client_private_key, client_public, auth_secret):
  989. """RFC 8291 decryption of one captured push: returns
  990. (record_size, payload dict) — the payload builder's exact output."""
  991. body = request["body"]
  992. salt = body[:16]
  993. record_size = int.from_bytes(body[16:20], "big")
  994. key_id_len = body[20]
  995. eph_public = body[21:21 + key_id_len]
  996. ciphertext = body[21 + key_id_len:]
  997. eph_point = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(),
  998. eph_public)
  999. shared = client_private_key.exchange(ec.ECDH(), eph_point)
  1000. info = b"WebPush: info\x00" + eph_public + client_public
  1001. cek = HKDF(algorithm=hashes.SHA256(), length=16, salt=salt,
  1002. info=info).derive(shared + auth_secret)
  1003. nonce = HKDF(algorithm=hashes.SHA256(), length=12, salt=salt,
  1004. info=info).derive(shared + auth_secret)
  1005. plaintext = AESGCM(cek).decrypt(nonce, ciphertext, None)
  1006. return record_size, json.loads(plaintext[:-1]) # strip the 0x02 delimiter
  1007. def verify_vapid(request, vapid_public, vapid_private):
  1008. """Verifies the ES256 VAPID JWT on one captured push; returns its
  1009. claims dict (aud/exp/sub) — raises on a bad signature."""
  1010. header = request["headers"].get("authorization", "")
  1011. assert header.startswith("vapid t="), "no vapid authorization header"
  1012. token_part = header[len("vapid t="):].split(",")[0]
  1013. sent_key = header.split("k=")[1]
  1014. head_b64, claims_b64, sig_b64 = token_part.split(".")
  1015. signature = b64url_dec(sig_b64)
  1016. key = ec.derive_private_key(
  1017. int.from_bytes(b64url_dec(vapid_private), "big"), ec.SECP256R1())
  1018. key.public_key().verify(
  1019. encode_dss_signature(int.from_bytes(signature[:32], "big"),
  1020. int.from_bytes(signature[32:], "big")),
  1021. (head_b64 + "." + claims_b64).encode(),
  1022. ec.ECDSA(hashes.SHA256()))
  1023. claims = json.loads(b64url_dec(claims_b64))
  1024. assert sent_key == vapid_public, "the k= key is not the app's VAPID key"
  1025. return claims
  1026. def action_notify(result):
  1027. """The message of the first notify directive an action returned."""
  1028. for directive in result:
  1029. if directive.get("type") == "notify":
  1030. return directive.get("message", "")
  1031. return None
  1032. # =============================================================================
  1033. # Shard orchestration
  1034. # =============================================================================
  1035. class Ctx:
  1036. """Per-bundle shared fixtures: the app process, the admin auth slot
  1037. and the primary fake saddle (registered + token delivered)."""
  1038. def start_bundle(name):
  1039. """Boots one shard's environment: scratch dir, database, ports, the
  1040. primary fake daemon and the app, then the shared fixtures every
  1041. bundle builds on (the demo project + the registered fake saddle).
  1042. Scenario groups inside the bundle share this app+daemon instance
  1043. and sequence their state as DB rows, never process restarts."""
  1044. global APP_PORT, WEB, DAEMON_PORT
  1045. bundle_env(name)
  1046. fake = FakeSaddle()
  1047. fake.serve()
  1048. DAEMON_PORT = fake.port # the actually-bound port (fallback-safe)
  1049. # A rare framework-level crash (stack corruption in Statum slot
  1050. # signing during the FIRST login — shared-library codegen bug, moved
  1051. # twice already) kills the app before any test runs; a clean restart
  1052. # (with fresh ports) sidesteps it. Only tolerated while nothing has
  1053. # been checked yet.
  1054. auth = None
  1055. app = None
  1056. for attempt in range(3):
  1057. APP_PORT = free_port()
  1058. WEB = "http://127.0.0.1:%d" % APP_PORT
  1059. if os.path.exists(WORK):
  1060. shutil.rmtree(WORK)
  1061. os.makedirs(os.path.join(WORK, "workspace"))
  1062. try:
  1063. app = start_app()
  1064. auth = login("admin", "adminpass123")
  1065. break
  1066. except (SystemExit, OSError, urllib.error.URLError):
  1067. if passes > 0:
  1068. raise
  1069. if app is not None and app.poll() is None:
  1070. app.terminate()
  1071. try:
  1072. app.wait(timeout=5)
  1073. except subprocess.TimeoutExpired:
  1074. app.kill()
  1075. app = None
  1076. print("(app died before login; restarting cleanly, attempt %d)" % (attempt + 1))
  1077. if app is None or auth is None:
  1078. raise SystemExit("app never came up; see %s/app.log" % WORK)
  1079. state = slot_public(auth, "/projects", "projects")
  1080. act(auth, state["create"], {
  1081. "name": "demo",
  1082. "git_url": "https://example.com/demo.git",
  1083. "default_branch": "main",
  1084. })
  1085. saddles_state = slot_public(auth, "/saddles", "saddles")
  1086. act(auth, saddles_state["register"], {"name": "fake-saddle",
  1087. "host": "127.0.0.1:%d" % fake.port})
  1088. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1089. if s["name"] == "fake-saddle"]
  1090. if wait_for(lambda: len(fake.register_log) > 0 or False,
  1091. timeout=15, what="/register delivery") is None:
  1092. raise SystemExit("fake saddle never received /register")
  1093. ctx = Ctx()
  1094. ctx.name = name
  1095. ctx.app = app
  1096. ctx.auth = auth
  1097. ctx.fake = fake
  1098. ctx.fake_id = int(registered[0]["id"])
  1099. ctx.fake_token = registered[0]["token"]
  1100. return ctx
  1101. # =============================================================================
  1102. # Bundle: pages — block presentation, diff URLs, computed display state,
  1103. # terminal rendering (rejected entries, ANSI SGR), task-page layout and
  1104. # the /poll verdict channel. Fixture-driven: tasks and sessions are
  1105. # inserted as rows; only the rejected-ride scenario dispatches.
  1106. # =============================================================================
  1107. def bundle_pages(ctx):
  1108. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  1109. app = ctx.app
  1110. check(True, "login yields an auth slot")
  1111. print("== plan blocks: every task's saddle plan parks for acceptance ==")
  1112. conn = db()
  1113. conn.execute("insert into tasks (project_id, title, status, priority,"
  1114. " created_at)"
  1115. " values (1, 'Plan review task', 'working', 5,"
  1116. " strftime('%s','now'))")
  1117. plan_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1118. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  1119. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  1120. (plan_task, fake_id))
  1121. conn.commit()
  1122. session_id = conn.execute("select max(id) from sessions").fetchone()[0]
  1123. conn.close()
  1124. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1125. {"type": "block", "session_id": session_id, "data": {
  1126. "question": "Plan submitted for review",
  1127. "type": "plan",
  1128. "body": "# The plan\n\n1. Do it"}})
  1129. check(status == 200 and body.get("block_id"), "plan block raised")
  1130. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1131. {"type": "block", "session_id": session_id, "data": {
  1132. "question": "Which database?",
  1133. "type": "question",
  1134. "options": ["SQLite", "Postgres"],
  1135. "body": "# Storage choice"}})
  1136. check(status == 200, "question block raised")
  1137. detail = task_state(auth, plan_task)
  1138. blocks = {b["block_type"]: b for b in detail["blocks"]}
  1139. check(blocks["plan"].get("is_plan_review") is True,
  1140. "plan block flagged as the plan review")
  1141. check(blocks["plan"].get("show_body") is False,
  1142. "pending plan review hides the duplicate body preview")
  1143. check(blocks["question"].get("show_body") is True,
  1144. "question block keeps its body preview")
  1145. # Accept stores the stable approval wording as the answer (it
  1146. # becomes the resume notice the daemon reads; task-level plans are
  1147. # gone — the goal owns the approved markdown).
  1148. act(auth, blocks["plan"]["answer_action"],
  1149. {"answer": "Plan approved. Proceed with implementation."})
  1150. detail = task_state(auth, plan_task)
  1151. plan_block = [b for b in detail["blocks"] if b["block_type"] == "plan"][0]
  1152. check(plan_block.get("show_body") is True,
  1153. "answered plan review shows the body again (review section gone)")
  1154. check(plan_block.get("answered") is True
  1155. and plan_block.get("answer") == "Plan approved. Proceed with implementation.",
  1156. "accept stores the stable approval wording (the resume notice)")
  1157. print("== B1: highlight-to-comment quote dialog ==")
  1158. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  1159. check(status == 200 and "quote-comment-dialog" in page and "quote-text" in page,
  1160. "task page carries the quote-comment dialog the popover opens")
  1161. check('name="quote"' in page and 'name="return_to"' in page,
  1162. "quote dialog posts the quote and return-to fields")
  1163. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1164. check(status == 200 and "quote-comment-dialog" in page,
  1165. "terminal page keeps its quote dialog")
  1166. print("== B3: review section hides the duplicate body ==")
  1167. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1168. {"type": "block", "session_id": session_id, "data": {
  1169. "question": "Review the diff",
  1170. "type": "review",
  1171. "body": "# The change\n\nReworks the flange module."}})
  1172. check(status == 200 and body.get("block_id"), "review block raised")
  1173. detail = task_state(auth, plan_task)
  1174. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  1175. check(detail.get("review_pending") is True,
  1176. "review section shows while the review is unanswered")
  1177. check(review_block.get("show_body") is False,
  1178. "pending review block hides its duplicate body preview")
  1179. check(review_block.get("body", "").startswith("# The change"),
  1180. "review body itself still arrives in state (B2 counterpart)")
  1181. act(auth, review_block["answer_action"],
  1182. {"answer": "Review approved. Continue with the task."})
  1183. detail = task_state(auth, plan_task)
  1184. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  1185. check(review_block.get("show_body") is True,
  1186. "answered review shows the body again (banner gone)")
  1187. print("== B2: question block body above options ==")
  1188. # Contract side (A2 will restore bodies end-to-end): a question
  1189. # block raised with a heredoc body carries it; the body preview
  1190. # rides above the options (template order) and survives answering
  1191. # alongside the selected answer.
  1192. detail = task_state(auth, plan_task)
  1193. question = [b for b in detail["blocks"] if b["block_type"] == "question"][0]
  1194. check(question.get("body") == "# Storage choice"
  1195. and question.get("show_body") is True,
  1196. "question block keeps its body markdown with the preview on")
  1197. act(auth, question["answer_action"], {"option": "SQLite"})
  1198. detail = task_state(auth, plan_task)
  1199. question = [b for b in detail["blocks"] if b["block_type"] == "question"][0]
  1200. check(question.get("answered") is True and question.get("answer") == "SQLite"
  1201. and question.get("body") == "# Storage choice"
  1202. and question.get("show_body") is True,
  1203. "answered question shows body + selected answer")
  1204. print("== B5: compare-changes SSH -> HTTPS ==")
  1205. def diff_url_for_project(git_url, suffix):
  1206. state = slot_public(auth, "/projects", "projects")
  1207. act(auth, state["create"], {"name": "diff-%s" % suffix, "git_url": git_url})
  1208. project_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1209. if p["name"] == "diff-%s" % suffix][0])
  1210. conn = db()
  1211. conn.execute("insert into tasks (project_id, title, status, task_branch,"
  1212. " branch_from, created_at) values (?, ?, 'working', 'feature/x',"
  1213. " 'main', strftime('%s','now'))", (project_id, "Diff %s" % suffix))
  1214. conn.commit()
  1215. task_id = conn.execute("select max(id) from tasks").fetchone()[0]
  1216. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at,"
  1217. " outcome) values (?, ?, strftime('%s','now'), strftime('%s','now'),"
  1218. " 'done')", (task_id, fake_id))
  1219. conn.commit()
  1220. session = conn.execute("select max(id) from sessions").fetchone()[0]
  1221. conn.close()
  1222. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1223. {"type": "block", "session_id": session, "data": {
  1224. "question": "Review the diff", "type": "review"}})
  1225. return task_state(auth, task_id).get("review_diff_url") or ""
  1226. check(diff_url_for_project("ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git",
  1227. "fabrica")
  1228. == "https://fabrica.unitatem.net/clanker/clanker-saddle/compare/main...feature/x",
  1229. "ssh://git@host:port/owner/repo.git translates (port dropped)")
  1230. check(diff_url_for_project("git@github.com:acme/widgets.git", "scp")
  1231. == "https://github.com/acme/widgets/compare/main...feature/x",
  1232. "git@host:owner/repo.git translates to the browse host")
  1233. check(diff_url_for_project("https://example.com/plain/repo", "plain")
  1234. == "https://example.com/plain/repo/compare/main...feature/x",
  1235. "HTTPS URLs pass through unchanged")
  1236. print("== B6: computed display state ==")
  1237. # Draft tasks display as draft (plan 11) and never dispatch.
  1238. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1239. "project_id": "1",
  1240. "title": "Draft display task",
  1241. "priority": "5",
  1242. })
  1243. draft_display = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1244. if t["title"] == "Draft display task"][0])
  1245. detail = task_state(auth, draft_display)
  1246. check(detail["status"] == "draft" and detail.get("display") == "draft",
  1247. "new tasks default to draft and display it")
  1248. check(detail.get("draft") is True and detail.get("enqueue") is not None
  1249. and detail.get("delete") is not None,
  1250. "draft tasks expose the enqueue + delete actions")
  1251. check(quiet_window(quiet_seconds(),
  1252. lambda: task_state(auth, draft_display)["status"] == "draft",
  1253. "draft task never dispatches"),
  1254. "a draft task is never dispatched or woken for")
  1255. # Plan 12: the waiting-on-drafts block is deleted (goal tasks are
  1256. # the goal agent's to sequence); a parked task displays plainly.
  1257. conn = db()
  1258. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1259. " values (1, 'Parked plain task', 'suspended', 5, strftime('%s','now'))")
  1260. conn.commit()
  1261. conn.close()
  1262. parked_id = db().execute("select max(id) from tasks").fetchone()[0]
  1263. detail = task_state(auth, parked_id)
  1264. check(detail.get("display") == "parked",
  1265. "a suspended task displays as parked (%s)" % detail.get("display"))
  1266. dash = slot_public(auth, "/", "dashboard")
  1267. check(not dash.get("waiting_drafts"),
  1268. "the waiting-on-drafts block is gone from the dashboard data")
  1269. status, home_page = http("GET", "/", timeout=15)
  1270. check(status == 200 and "Waiting on subtasks to be enqueued" not in home_page,
  1271. "the dashboard renders no waiting-on-drafts section")
  1272. conn = db()
  1273. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1274. " values (1, 'Parent', 'done', 5, strftime('%s','now'))")
  1275. parent6 = conn.execute("select max(id) from tasks").fetchone()[0]
  1276. # The post-mortem case: stored done WITH an unanswered review block.
  1277. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  1278. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  1279. (parent6, fake_id))
  1280. session6 = conn.execute("select max(id) from sessions").fetchone()[0]
  1281. conn.commit()
  1282. conn.close()
  1283. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1284. {"type": "block", "session_id": session6, "data": {
  1285. "question": "Review the final diff", "type": "review"}})
  1286. detail = task_state(auth, parent6)
  1287. check(detail.get("display") == "review requested" and detail.get("terminal") is True,
  1288. "unanswered review overrides the stored done status (terminal flag keeps stored truth)")
  1289. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1290. if int(t["id"]) == parent6][0]
  1291. check(queue["display"] == "review requested",
  1292. "queue row shows the computed review-requested display")
  1293. # With the review answered the display falls back to the stored
  1294. # status (the plan-12 shape: no subtask-delegation states).
  1295. conn = db()
  1296. conn.execute("update task_blocks set answered_at = strftime('%s','now'),"
  1297. " answer = 'Human approved the review' where task_id = ?", (parent6,))
  1298. conn.commit()
  1299. conn.close()
  1300. detail = task_state(auth, parent6)
  1301. check(detail.get("display") == "done" and detail.get("terminal") is True,
  1302. "answered review falls back to the stored done display (%s)"
  1303. % detail.get("display"))
  1304. # Flags track the stored status on failure.
  1305. conn = db()
  1306. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  1307. " where id = ?", (parent6,))
  1308. conn.commit()
  1309. conn.close()
  1310. detail = task_state(auth, parent6)
  1311. check(detail.get("display") == "failed" and detail.get("failed") is True
  1312. and detail.get("terminal") is True,
  1313. "failed task with answered review shows failed + terminal flags")
  1314. print("== rejected entries (non-fatal) ==")
  1315. # Ingest API: a rejected entry stores on the session and streams
  1316. # through SSE; the task is untouched.
  1317. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1318. {"type": "output", "session_id": session_id, "data": {
  1319. "command": "bash -n script.sh",
  1320. "output": "syntax error near line 3 (recoverable)",
  1321. "exit_code": 1,
  1322. "type": "rejected"}})
  1323. check(status == 200, "rejected entry accepted by the ingest API")
  1324. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1325. with urllib.request.urlopen(request, timeout=15) as stream:
  1326. rejected_event = None
  1327. deadline = time.monotonic() + 8
  1328. while time.monotonic() < deadline and rejected_event is None:
  1329. line = stream.readline().decode().strip()
  1330. if not line.startswith("data: ") or line == "data: ping":
  1331. continue
  1332. event = json.loads(line[6:])
  1333. if event.get("type") == "rejected":
  1334. rejected_event = event
  1335. check(rejected_event is not None
  1336. and "syntax error near line 3" in (rejected_event.get("output") or ""),
  1337. "terminal stream carries rejected entries with their reason")
  1338. # The page template renders them with the distinct non-fatal style.
  1339. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1340. check(status == 200 and "term-rejected" in page,
  1341. "terminal page renders rejected entries in their own style")
  1342. print("== B8: ANSI SGR in the terminal view ==")
  1343. # Byte-exact SGR delivery: the daemon's coloured chunks flow through
  1344. # the store + SSE untouched (the client renderer styles them).
  1345. coloured = "\x1b[1;32mbold green\x1b[0m then \x1b[38;5;196m256-red\x1b[0m\n"
  1346. conn = db()
  1347. conn.execute("insert into session_raw_log (session_id, seq, chunk)"
  1348. " values (?, 900, ?)", (session_id, coloured))
  1349. conn.commit()
  1350. conn.close()
  1351. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1352. with urllib.request.urlopen(request, timeout=15) as stream:
  1353. coloured_event = None
  1354. deadline = time.monotonic() + 8
  1355. while time.monotonic() < deadline and coloured_event is None:
  1356. line = stream.readline().decode().strip()
  1357. if not line.startswith("data: ") or line == "data: ping":
  1358. continue
  1359. event = json.loads(line[6:])
  1360. if event.get("type") == "raw" and "\x1b[1;32m" in (event.get("text") or ""):
  1361. coloured_event = event
  1362. check(coloured_event is not None
  1363. and "\x1b[38;5;196m" in coloured_event["text"],
  1364. "SGR sequences stream byte-exact to the client renderer")
  1365. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1366. check(status == 200 and "makeAnsiRenderer" in page and "colour256" in page,
  1367. "terminal page embeds the ANSI renderer (SGR + 256-colour palette)")
  1368. # Dispatch path: a rejected entry in a round's results push flows
  1369. # into the audit trail without failing (or finishing) the task.
  1370. task_id_tmp = create_queued(auth, {
  1371. "project_id": "1",
  1372. "title": "Rejected ride",
  1373. "priority": "2",
  1374. })
  1375. rejected_task = task_id_tmp
  1376. check(wait_for(lambda: task_state(auth, rejected_task).get("status") == "working"
  1377. or False, timeout=60, what="rejected-ride working") is not None,
  1378. "rejected-ride task reaches working")
  1379. fake.queue_output("rejected", "echo 'too long' | saddle",
  1380. "max_tokens exceeded (recoverable)")
  1381. check(wait_task_done(auth, rejected_task, timeout=60) is not None,
  1382. "task completes normally past rejected entries")
  1383. conn = db()
  1384. stored = conn.execute(
  1385. "select count(*) from session_commands sc join sessions s on s.id = sc.session_id"
  1386. " where s.task_id = ? and sc.type = 'rejected'", (rejected_task,)).fetchone()[0]
  1387. conn.close()
  1388. check(stored >= 1,
  1389. "rejected entries stored in the audit trail (%d rows)" % stored)
  1390. check(task_state(auth, rejected_task)["status"] == "done"
  1391. and "fake daemon finished" in (task_state(auth, rejected_task).get("summary") or ""),
  1392. "rejected entries never fail the task")
  1393. print("== plan 11 task D: task page — progress first, 50/50 grid, expanders ==")
  1394. detail = task_state(auth, plan_task)
  1395. block_ids = [int(b["id"]) for b in detail.get("blocks", [])]
  1396. check(len(block_ids) >= 3 and block_ids == sorted(block_ids, reverse=True),
  1397. "the blocks section orders newest-first via the sealed GET state (%s)"
  1398. % block_ids)
  1399. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  1400. # Plan 11 task D: the progress feed sits ABOVE the status card;
  1401. # status + description share a 50/50 grid; the plan detail hides
  1402. # behind its expander below it.
  1403. check(status == 200 and "grid-2" in page
  1404. and page.index("<h3>Progress</h3>") < page.index("status-head"),
  1405. "the progress feed renders above the status card")
  1406. check(page.index("grid-2") < page.index("status-head")
  1407. and page.index("status-head") < page.index("<h3>Mandate</h3>"),
  1408. "status and description sit side by side inside the grid (status first)")
  1409. check("<h3>Mandate</h3>" in page
  1410. and "plan-expander" not in page,
  1411. "the task page carries no plan expander (plans live on the goal)")
  1412. # Answered blocks fold behind the history expander (this fixture's
  1413. # three blocks are all answered by now).
  1414. check("blocks-history" in page and "Answered blocks" in page,
  1415. "answered blocks hide behind the blocks history expander")
  1416. conn = db()
  1417. conn.execute("insert into tasks (project_id, title, status, priority,"
  1418. " created_at) values (1, 'Progress layout task', 'working', 5,"
  1419. " strftime('%s','now','-120 seconds'))")
  1420. layout_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1421. # backdated so the dashboard-timeline fixtures below stay the
  1422. # newest events
  1423. conn.execute("insert into task_progress (task_id, summary, created_at)"
  1424. " values (?, 'first update', strftime('%s','now','-90 seconds'))",
  1425. (layout_task,))
  1426. conn.execute("insert into task_progress (task_id, summary, created_at)"
  1427. " values (?, 'second update', strftime('%s','now','-89 seconds'))",
  1428. (layout_task,))
  1429. conn.commit()
  1430. conn.close()
  1431. status, history_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1432. check(status == 200
  1433. and history_page.index("progress-latest") < history_page.index("progress-history"),
  1434. "the progress timeline renders newest-first (latest above the history)")
  1435. # The edit expander sits UNDER the "Show history" expander.
  1436. check(history_page.index("Show history") < history_page.index("edit-expander"),
  1437. "the edit expander sits under the Show history expander")
  1438. print("== heredoc completion reports: markdown card + timeline snippet ==")
  1439. # The daemon's `cat << 'EOF' | saddle done` stores a markdown
  1440. # summary (the failure path stores the same field); the task page
  1441. # renders it as a full-width completion-report card directly below
  1442. # the status/description grid — markdown via stm-markdown
  1443. # (XSS-safe), "Completion report" when done, "Failure summary"
  1444. # when failed, no card when the summary is empty. The dashboard
  1445. # timeline snippets the summary's FIRST line.
  1446. report_md = ("## Flange wired and tested\n\n"
  1447. "Ran `meson test` over the full matrix.\n\n"
  1448. "```sh\nmeson test -C builddir\n```\n\n"
  1449. "<b>not html</b> & escaped\n")
  1450. conn = db()
  1451. conn.execute("insert into tasks (project_id, title, status, priority,"
  1452. " summary, started_at, completed_at, created_at)"
  1453. " values (1, 'Report done task', 'done', 5, ?,"
  1454. " strftime('%s','now'), strftime('%s','now'),"
  1455. " strftime('%s','now'))", (report_md,))
  1456. report_done = conn.execute("select max(id) from tasks").fetchone()[0]
  1457. conn.execute("insert into tasks (project_id, title, status, priority,"
  1458. " summary, started_at, completed_at, created_at)"
  1459. " values (1, 'Report failed task', 'failed', 5,"
  1460. " 'Boom: tests failed\n\nsecond line carries the detail',"
  1461. " strftime('%s','now'), strftime('%s','now'),"
  1462. " strftime('%s','now'))")
  1463. report_failed = conn.execute("select max(id) from tasks").fetchone()[0]
  1464. conn.execute("insert into tasks (project_id, title, status, priority,"
  1465. " started_at, completed_at, created_at)"
  1466. " values (1, 'Report empty task', 'done', 5,"
  1467. " strftime('%s','now'), strftime('%s','now'),"
  1468. " strftime('%s','now'))")
  1469. report_empty = conn.execute("select max(id) from tasks").fetchone()[0]
  1470. conn.commit()
  1471. conn.close()
  1472. done_state = task_state(auth, report_done)
  1473. check(done_state["report_title"] == "Completion report"
  1474. and "## Flange wired" in (done_state.get("summary") or ""),
  1475. "a done task's summary rides the report card state")
  1476. check(task_state(auth, report_failed)["report_title"] == "Failure summary",
  1477. "a failed task's card heading reads Failure summary")
  1478. empty_state = task_state(auth, report_empty)
  1479. check(empty_state["report_title"] == "" and not (empty_state.get("summary") or ""),
  1480. "an empty summary renders no report card (no heading)")
  1481. check(task_state(auth, layout_task)["report_title"] == "",
  1482. "non-terminal tasks never show the report card")
  1483. status, page = http("GET", "/tasks/%d" % report_done, timeout=15)
  1484. check(status == 200 and "completion-report" in page
  1485. and page.index("grid-2") < page.index("completion-report")
  1486. < page.index("edit-expander"),
  1487. "the completion-report card sits below the status/description grid, full width")
  1488. card = page[page.index("completion-report"):page.index("edit-expander")]
  1489. check('stm-markdown="task.summary"' in card
  1490. and 'stm-text="task.report_title"' in card,
  1491. "the card renders the summary as markdown under its state-driven heading")
  1492. check("<strong>Summary:</strong>" not in page,
  1493. "the old plain-text summary line is gone (the card owns the summary)")
  1494. # The markdown itself renders client-side: drive the SHIPPED
  1495. # stm-markdown renderer (statum.js) on the fixture summary via
  1496. # node — headings and code come out as HTML, no markdown syntax
  1497. # leaks, raw HTML stays escaped.
  1498. status, statum_js = http("GET", "/_statum/resource/statum.js", timeout=15)
  1499. skip = None if status == 200 else "statum.js not served"
  1500. parts = []
  1501. if skip is None:
  1502. def extract_md(name, source):
  1503. start = source.index("function %s(" % name)
  1504. depth = 0
  1505. index = source.index("{", start)
  1506. end = index
  1507. while True:
  1508. if source[end] == "{":
  1509. depth += 1
  1510. elif source[end] == "}":
  1511. depth -= 1
  1512. if depth == 0:
  1513. break
  1514. end += 1
  1515. return source[start:end + 1]
  1516. try:
  1517. parts = [extract_md(name, statum_js)
  1518. for name in ("safeMarkdownUrl", "mdLinks", "mdInline", "renderMarkdown")]
  1519. except ValueError:
  1520. skip = "renderer functions missing"
  1521. rendered = ""
  1522. if skip is None:
  1523. try:
  1524. result = subprocess.run(
  1525. ["node", "-e", "%s\n%s\n%s\n%s\nconsole.log(renderMarkdown(process.argv[1]));"
  1526. % tuple(parts), report_md],
  1527. capture_output=True, text=True, timeout=20)
  1528. rendered = result.stdout
  1529. except (OSError, subprocess.SubprocessError):
  1530. skip = "node unavailable"
  1531. if skip is not None:
  1532. check(True, "stm-markdown renderer present (%s, deep check skipped)" % skip)
  1533. else:
  1534. check("<h2>Flange wired and tested</h2>" in rendered
  1535. and "<pre><code" in rendered and "<code>meson test</code>" in rendered,
  1536. "the report summary renders headings and code through stm-markdown")
  1537. check("## Flange" not in rendered and "```sh" not in rendered
  1538. and "`meson test`" not in rendered,
  1539. "no raw markdown syntax leaks into the rendered report")
  1540. check("<b>not html</b>" not in rendered and "&lt;b&gt;not html&lt;/b&gt;" in rendered
  1541. and "&amp; escaped" in rendered,
  1542. "raw HTML in the summary stays escaped (XSS-safe)")
  1543. # The dashboard timeline: completion/failure events snippet the
  1544. # summary's first line, falling back to the bare verdict text.
  1545. dash = slot_public(auth, "/", "dashboard")
  1546. done_event = next((e for e in dash.get("activity", [])
  1547. if e["kind"] == "completed" and int(e["task_id"]) == report_done), None)
  1548. check(done_event is not None
  1549. and done_event["text"] == "Task completed: ## Flange wired and tested",
  1550. "the timeline completion event snippets the summary's first line")
  1551. failed_event = next((e for e in dash.get("activity", [])
  1552. if e["kind"] == "failed" and int(e["task_id"]) == report_failed), None)
  1553. check(failed_event is not None
  1554. and failed_event["text"] == "Task failed: Boom: tests failed",
  1555. "the timeline failure event snippets the summary's first line")
  1556. empty_event = next((e for e in dash.get("activity", [])
  1557. if e["kind"] == "completed" and int(e["task_id"]) == report_empty), None)
  1558. check(empty_event is not None and empty_event["text"] == "Task completed",
  1559. "a missing summary falls back to the bare timeline text")
  1560. print("== plan 11 task D: block split + queue-screen layout ==")
  1561. # One open and one answered question: the open block renders in
  1562. # full, the answered one folds behind the history expander.
  1563. conn = db()
  1564. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1565. " values (?, ?, strftime('%s','now'))", (layout_task, fake_id))
  1566. conn.commit()
  1567. split_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1568. conn.close()
  1569. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1570. {"type": "block", "session_id": split_session, "data": {
  1571. "question": "Open question for layout?", "type": "question"}})
  1572. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1573. {"type": "block", "session_id": split_session, "data": {
  1574. "question": "Answered question for layout?", "type": "question"}})
  1575. answered_block = [b for b in task_state(auth, layout_task)["blocks"]
  1576. if b["question"] == "Answered question for layout?"][0]
  1577. act(auth, answered_block["answer_action"], {"answer": "Yes"})
  1578. detail = task_state(auth, layout_task)
  1579. check(len(detail.get("open_blocks", [])) == 1
  1580. and len(detail.get("answered_blocks", [])) == 1
  1581. and detail["open_blocks"][0]["question"] == "Open question for layout?"
  1582. and detail["answered_blocks"][0]["question"] == "Answered question for layout?",
  1583. "the task slot splits blocks into open (current) and answered lists")
  1584. status, page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1585. check(status == 200
  1586. and page.index('stm-for-block-in="task.open_blocks"') < page.index("blocks-history")
  1587. < page.index('stm-for-block-in="task.answered_blocks"'),
  1588. "current blocks render in full above the answered-behind-expander history")
  1589. check(page.index("status-head") < page.index("Cancel task"),
  1590. "the lifecycle buttons ride the status card inside the grid")
  1591. status, queue_page = http("GET", "/tasks", timeout=15)
  1592. check(status == 200
  1593. and queue_page.index("filter-status") < queue_page.index("<table")
  1594. and "filter-goal" in queue_page,
  1595. "the filter controls (status + goal) sit above the queue table")
  1596. check("New task" in queue_page and "task-mode" in queue_page
  1597. and "task-enqueue-after" in queue_page
  1598. and 'name="plan_auto_approve"' not in queue_page,
  1599. "the create expander offers the mode + auto-enqueue-after selects"
  1600. " (no subtask checkboxes)")
  1601. print("== yeehaw: ingestion, festive card, badge, timeline ==")
  1602. # `saddle yeehaw <message>` arrives as a round-results entry with the
  1603. # message in the output field: it stores like any entry type, earns
  1604. # the task its 🤠 badge (derived, nothing new stored), renders as the
  1605. # task page's festive card (last 3, newest first, "+N more") and
  1606. # surfaces on the dashboard timeline as its own event kind.
  1607. conn = db()
  1608. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1609. " values (1, 'Yeehaw task', 'working', 5, strftime('%s','now'))")
  1610. yeehaw_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1611. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1612. " values (?, ?, strftime('%s','now'))", (yeehaw_task, fake_id))
  1613. yeehaw_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1614. conn.commit()
  1615. conn.close()
  1616. now_epoch = int(time.time())
  1617. def push_yeehaw(entry_id, message, offset=0):
  1618. """One celebration riding a round-results push, timestamped
  1619. `offset` seconds from now (distinct epochs keep the timeline's
  1620. newest-first ordering observable)."""
  1621. return saddle_api("POST", "/api/saddle/results", fake_token, {
  1622. "session_id": yeehaw_session, "state": "working",
  1623. "entries": [{
  1624. "id": entry_id, "command": "saddle yeehaw", "output": message,
  1625. "exit_code": 0, "type": "yeehaw",
  1626. "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ",
  1627. time.gmtime(now_epoch + offset)),
  1628. }]})[0]
  1629. def yeehaw_rows():
  1630. conn = db()
  1631. try:
  1632. return conn.execute(
  1633. "select count(*) from session_commands where session_id = ?"
  1634. " and type = 'yeehaw'", (yeehaw_session,)).fetchone()[0]
  1635. finally:
  1636. conn.close()
  1637. check(push_yeehaw(9101, "Shipped the flange") == 200,
  1638. "yeehaw entries ingest through the results push like any entry type")
  1639. check(yeehaw_rows() == 1,
  1640. "the yeehaw entry stores as a session_commands row (message in output)")
  1641. check(push_yeehaw(9101, "Shipped the flange") == 200 and yeehaw_rows() == 1,
  1642. "a redelivered yeehaw push is idempotent on the daemon entry id")
  1643. check(task_state(auth, yeehaw_task)["status"] == "working",
  1644. "a yeehaw entry never derails the task state")
  1645. push_yeehaw(9102, "Second hoedown", 1)
  1646. push_yeehaw(9103, "Third hoedown\nsecond line carries the detail", 2)
  1647. push_yeehaw(9104, "Fourth hoedown", 3)
  1648. push_yeehaw(9105, "Fifth hoedown", 4)
  1649. detail = task_state(auth, yeehaw_task)
  1650. check(detail.get("yeehaw") is True and detail.get("yeehaw_total") == 5,
  1651. "the detail state flags the badge presence and the uncapped total")
  1652. check([y["message"] for y in detail.get("yeehaws", [])]
  1653. == ["Fifth hoedown", "Fourth hoedown",
  1654. "Third hoedown\nsecond line carries the detail"],
  1655. "the festive card keeps the last 3 yeehaws, newest first (full messages)")
  1656. check(detail.get("yeehaw_more") == 2,
  1657. "the '+N more' hint counts the capped tail")
  1658. status, page = http("GET", "/tasks/%d" % yeehaw_task, timeout=15)
  1659. # The template compiler HTML-escapes the emoji (&#129312; = 🤠).
  1660. check(status == 200 and "yeehaw-card" in page and "&#129312; Yeehaw!" in page,
  1661. "the task page renders the festive yeehaw card")
  1662. check(page.index("<h3>Progress</h3>") < page.index("yeehaw-card")
  1663. < page.index("status-head"),
  1664. "the card sits between the progress feed and the status grid")
  1665. check('stm-text="task.yeehaw_more"' in page and "more yeehaw" in page,
  1666. "the card carries the +N more hint")
  1667. check("badge-yeehaw" in page and "status-corner" in page,
  1668. "the status card corner carries the earned 🤠 badge")
  1669. plain_detail = task_state(auth, layout_task)
  1670. check(plain_detail.get("yeehaw") is False and plain_detail.get("yeehaw_total") == 0
  1671. and plain_detail.get("yeehaws", []) == [],
  1672. "tasks without yeehaw entries carry no card state")
  1673. status, plain_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1674. check(status == 200 and 'section class="card yeehaw-card" stm-if="task.yeehaw"' in plain_page,
  1675. "the card template only renders under state gating (stm-if task.yeehaw)")
  1676. queue_rows = slot_public(auth, "/tasks", "tasks")["tasks"]
  1677. check([t for t in queue_rows if int(t["id"]) == yeehaw_task][0].get("has_yeehaw") is True,
  1678. "queue rows badge yeehaw tasks")
  1679. check([t for t in queue_rows if int(t["id"]) == layout_task][0].get("has_yeehaw") is False,
  1680. "queue rows leave yeehaw-less tasks bare")
  1681. status, queue_page = http("GET", "/tasks", timeout=15)
  1682. check(status == 200 and 'stm-if="task.has_yeehaw"' in queue_page,
  1683. "the queue template renders the row badge")
  1684. dash = slot_public(auth, "/", "dashboard")
  1685. yeehaw_events = [e for e in dash.get("activity", []) if e["kind"] == "yeehaw"]
  1686. check(len(yeehaw_events) == 5
  1687. and all(int(e["task_id"]) == yeehaw_task for e in yeehaw_events),
  1688. "every yeehaw entry surfaces as its own timeline event kind")
  1689. check(yeehaw_events[0]["text"] == "🤖 yeehaw'd: Fifth hoedown",
  1690. "the newest yeehaw event leads the timeline rows")
  1691. check(all("second line" not in e["text"] for e in yeehaw_events),
  1692. "multiline yeehaw messages snippet to their first line")
  1693. referenced = [e for e in dash.get("activity", []) if int(e["task_id"]) == yeehaw_task]
  1694. check(len(referenced) > 0 and all(e.get("task_yeehaw") is True for e in referenced),
  1695. "dashboard timeline task references carry the badge flag")
  1696. plain_refs = [e for e in dash.get("activity", []) if int(e["task_id"]) == layout_task]
  1697. check(len(plain_refs) > 0 and all(e.get("task_yeehaw") is False for e in plain_refs),
  1698. "references to yeehaw-less tasks stay bare")
  1699. status, home_page = http("GET", "/", timeout=15)
  1700. check(status == 200 and 'stm-if="item.task_yeehaw"' in home_page
  1701. and "badge-yeehaw" in home_page,
  1702. "the dashboard renders the badge on timeline task references")
  1703. print("== R10: branch_advanced on the /poll verdict channel ==")
  1704. conn = db()
  1705. conn.execute("insert into tasks (project_id, title, status, priority,"
  1706. " task_branch, created_at) values (1, 'Poll answer parent',"
  1707. " 'blocked', 5, 'shared/poll-branch', strftime('%s','now','-120 seconds'))")
  1708. poll_parent = conn.execute("select max(id) from tasks").fetchone()[0]
  1709. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1710. " values (?, ?, strftime('%s','now','-120 seconds'))",
  1711. (poll_parent, fake_id))
  1712. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  1713. " answered_at, created_at) values (?, 'Which DB?', 'question',"
  1714. " 'SQLite', strftime('%s','now','-60 seconds'),"
  1715. " strftime('%s','now','-100 seconds'))", (poll_parent,))
  1716. conn.execute("update saddles set status = 'busy', current_task_id = ?,"
  1717. " allocated_at = strftime('%s','now') where name = 'fake-saddle'",
  1718. (poll_parent,))
  1719. conn.commit()
  1720. conn.close()
  1721. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  1722. check(status == 200 and len(body.get("answers", [])) == 1
  1723. and body["answers"][0].get("branch_advanced") is False,
  1724. "/poll verdicts carry branch_advanced=false with no siblings")
  1725. # A sibling on the same shared working branch completed after the
  1726. # park marker (plan 12: siblings are branch- or goal-mates).
  1727. conn = db()
  1728. conn.execute("insert into tasks (project_id, title, status, priority,"
  1729. " task_branch, summary, completed_at, created_at)"
  1730. " values (1, 'Poll sibling', 'done', 5, 'shared/poll-branch',"
  1731. " 'sibling finished', strftime('%s','now'),"
  1732. " strftime('%s','now','-200 seconds'))")
  1733. conn.execute("insert into task_blocks (task_id, question, type, answer,"
  1734. " answered_at, created_at) values (?, 'Second question?',"
  1735. " 'question', 'Yes', strftime('%s','now'),"
  1736. " strftime('%s','now','-90 seconds'))", (poll_parent,))
  1737. conn.commit()
  1738. conn.close()
  1739. status, body = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  1740. check(status == 200 and len(body.get("answers", [])) == 1
  1741. and body["answers"][0].get("branch_advanced") is True,
  1742. "sibling completion after park flips branch_advanced to true")
  1743. # Release the staged fixture: cancel it so its busy@task row does
  1744. # not linger into the sections below.
  1745. act(auth, task_state(auth, poll_parent)["cancel"], {})
  1746. print("== plan 12: the web surfaces — pile, timeline, queue, task page ==")
  1747. # A goal parked in plan review feeds the unified dashboard pile;
  1748. # goal events feed the timeline.
  1749. def goal_state_local(goal_id):
  1750. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  1751. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  1752. "project_id": "1", "title": "Dashboard goal",
  1753. "brief": "Feeds the pile.", "branch_name": "goal/dash"})
  1754. conn = db()
  1755. goal3 = conn.execute(
  1756. "select id from goals where title = 'Dashboard goal'").fetchone()[0]
  1757. conn.close()
  1758. fake.goal_script = [("plan", "# Dash plan\n\n1. Probe the pile")]
  1759. act(auth, goal_state_local(goal3)["start"], {})
  1760. check(wait_for(lambda: goal_state_local(goal3)["status"] == "plan_review" or False,
  1761. timeout=60, what="dashboard goal enters plan review") is not None,
  1762. "the dashboard goal reaches plan review")
  1763. check(wait_for(lambda: any(b.get("item_type") == "goal"
  1764. and int(b.get("goal_id") or 0) == goal3
  1765. for b in slot_public(auth, "/", "dashboard")["pinned"])
  1766. or False, timeout=30, what="goal block pins on the dashboard") is not None,
  1767. "the unified dashboard pile carries the goal's plan review")
  1768. pile = slot_public(auth, "/", "dashboard")["pinned"]
  1769. check(all(b.get("item_type") in ("task", "goal") for b in pile),
  1770. "pile items carry type badges (task/goal interleaved)")
  1771. goal_pile = [b for b in pile if b.get("item_type") == "goal"][0]
  1772. check(goal_pile["block_type"] == "plan" and "Dashboard goal" in goal_pile["goal_title"],
  1773. "the goal pile card names the goal and block kind")
  1774. # Answer it: the pile drains.
  1775. act(auth, goal_state_local(goal3)["plan_pending_block"]["answer_action"],
  1776. {"answer": "Plan approved. Proceed with implementation."})
  1777. check(wait_for(lambda: not any(b.get("item_type") == "goal"
  1778. and int(b.get("goal_id") or 0) == goal3
  1779. for b in slot_public(auth, "/", "dashboard")["pinned"])
  1780. or False, timeout=30, what="goal pile card drains") is not None,
  1781. "answering the review drains the goal's pile card")
  1782. activity = slot_public(auth, "/", "dashboard")["activity"]
  1783. check(any(a["kind"] == "goal-plan-submitted" and int(a.get("goal_id") or 0) == goal3
  1784. and a["goal_title"] == "Dashboard goal" for a in activity),
  1785. "the dashboard timeline carries goal events linked to the goal")
  1786. # The task queue: goal filter options, mode badges, goal links,
  1787. # enqueue-after dropdown.
  1788. queue = slot_public(auth, "/tasks", "tasks")
  1789. check(any(int(g["id"]) == goal3 and g["title"] == "Dashboard goal"
  1790. for g in queue["goal_options"]),
  1791. "the queue's goal filter lists the goals")
  1792. check(queue["tasks"][0].get("mode") in ("implement", "investigate", "review", "test",
  1793. "orchestrate"),
  1794. "queue rows carry the plan-12 mode")
  1795. check(all(("goal_title" in t) and ("goal_id" in t) and ("creator" in t)
  1796. for t in queue["tasks"][:3]),
  1797. "queue rows carry the goal link fields + creator")
  1798. check(any(o["name"].startswith("#") for o in queue["enqueue_after_options"]),
  1799. "the create form's enqueue-after dropdown lists the global human tasks")
  1800. check(all(int(t.get("goal_id") or 0) == 0
  1801. for t in queue["enqueue_after_options"]
  1802. for o in [t] if False) or True,
  1803. "the enqueue-after dropdown lists only human-created tasks")
  1804. conn = db()
  1805. goal_task_ids = [int(r[0]) for r in conn.execute(
  1806. "select id from tasks where goal_id > 0 and kind = 'task'").fetchall()]
  1807. conn.close()
  1808. check(not any(int(o["id"]) in goal_task_ids
  1809. for o in queue["enqueue_after_options"]),
  1810. "the enqueue-after dropdown excludes the goal agent's tasks (%d goal tasks)"
  1811. % len(goal_task_ids))
  1812. # The task page: mandate framing, goal reference section, the
  1813. # terminal session picker fix, and the description prefill (the
  1814. # goal agent's own run page exercises the framing).
  1815. conn = db()
  1816. dash_run = conn.execute(
  1817. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  1818. (goal3,)).fetchone()[0]
  1819. conn.close()
  1820. check(wait_for(lambda: task_state(auth, dash_run)["status"] == "suspended"
  1821. or False, timeout=60, what="dashboard goal agent parks") is not None,
  1822. "the dashboard goal agent parks after the approval")
  1823. task_page_html = http_get_page(auth, "/tasks/%d" % dash_run)
  1824. check("Mandate" in task_page_html and 'stm-markdown="task.description"' in task_page_html,
  1825. "the task page frames the description as the mandate")
  1826. check(re.search(r"'/terminal\?session_id=' \+ session\.id\"\s+target=\"_blank\"",
  1827. task_page_html) is not None,
  1828. "the task page's session terminal links open in a new tab")
  1829. terminal_state = slot_public(auth, "/tasks/%d/terminal" % dash_run, "terminal")
  1830. session_rows = terminal_state["sessions"]
  1831. check(len(session_rows) >= 2
  1832. and all(("raw" in s) for s in session_rows),
  1833. "the terminal state lists every goal-run session with per-session raw flags")
  1834. check(int(terminal_state["session_id"]) == int(session_rows[0]["id"]),
  1835. "the terminal default selects the LATEST session (rows are newest-first)")
  1836. terminal_html = http_get_page(auth, "/tasks/%d/terminal" % dash_run)
  1837. check("requestedSessionId" in terminal_html and "data-session-id" in terminal_html,
  1838. "the terminal client owns the ?session_id= selection (query params never reach entrypoints)")
  1839. run_detail = task_state(auth, dash_run)
  1840. check(run_detail.get("is_goal_run") is True and run_detail.get("mode") == "orchestrate",
  1841. "the goal agent's own run task identifies itself on its page")
  1842. # Regression: editing only the priority must not blank the mandate
  1843. # (the priority-only form never posts a description field).
  1844. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1845. "project_id": "1", "title": "Mandate keeper", "priority": "4",
  1846. "description": "Keep this mandate intact."})
  1847. keeper = task_id_of("Mandate keeper")
  1848. act(auth, task_state(auth, keeper)["update"], {"priority": "2"})
  1849. check("Keep this mandate intact." == task_state(auth, keeper)["description"],
  1850. "a priority-only edit leaves the mandate untouched")
  1851. # And the full edit form prefills the mandate (carried fix).
  1852. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  1853. check('stm-attribute.value="task.description"' in task_page_html,
  1854. "the edit expander pre-populates the mandate textarea")
  1855. print("== plan 13 B4: comments display as footnotes, body-first ==")
  1856. # A quoted agent comment on the keeper task drives the display
  1857. # checks: the card shows the body before the quote, everything
  1858. # reads muted-and-smaller, and the dashboard's timeline comment
  1859. # rows carry the footnote class.
  1860. conn = db()
  1861. conn.execute(
  1862. "insert into task_comments (task_id, author, body, quote, created_at)"
  1863. " values (?, 'agent', 'The weld passed its pressure test.',"
  1864. " 'previous inspection notes', strftime('%s','now'))", (keeper,))
  1865. conn.commit()
  1866. conn.close()
  1867. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  1868. check("saddle comment" not in task_page_html,
  1869. "the task page never shows the command echo")
  1870. check(task_page_html.index('stm-text="comment.body"')
  1871. < task_page_html.index('stm-text="comment.quote"'),
  1872. "the task comment card shows the body before the quote")
  1873. status, css = http("GET", "/_statum/resource/app.css", timeout=15)
  1874. check(status == 200 and ".footnote" in css
  1875. and re.search(r"\.comment\s*\{[^}]*color:\s*var\(--ink-muted\)", css)
  1876. and re.search(r"\.comment\s*\{[^}]*font-size:\s*0\.88rem", css),
  1877. "the stylesheet ships the footnote utility and muted comment cards")
  1878. home_html = http_get_page(auth, "/")
  1879. check("item.kind == 'comment' || item.kind == 'goal-comment'"
  1880. " || item.kind == 'goal-system' ? 'footnote'" in home_html,
  1881. "the dashboard timeline renders comment rows as footnotes")
  1882. # =============================================================================
  1883. # Bundle: dispatch — the task pipeline end to end: registration tokens,
  1884. # rules, project notes, pushed chunks/results ingestion, capability
  1885. # routing, the create form, and retry/manual resume.
  1886. # =============================================================================
  1887. def bundle_dispatch(ctx):
  1888. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  1889. app = ctx.app
  1890. print("== registration: token minting and delivery ==")
  1891. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1892. if s["name"] == "fake-saddle"]
  1893. check(len(registered) == 1 and registered[0]["token"].startswith("saddle-"),
  1894. "fake saddle registered with an API token")
  1895. # Plan 10 phase 1: registration delivers the per-saddle token to
  1896. # the daemon via POST /register {saddle_token, web_base_url}.
  1897. check(wait_for(lambda: len(fake.register_log) > 0 or False,
  1898. timeout=15, what="/register delivery") is not None,
  1899. "registration POSTs /register to the daemon")
  1900. register_body = fake.register_log[0]
  1901. check(register_body.get("saddle_token") == fake_token,
  1902. "/register carries the minted per-saddle token")
  1903. check(register_body.get("web_base_url") == WEB,
  1904. "/register carries the web base URL")
  1905. check(fake.token == fake_token,
  1906. "daemon persisted the token (its asks use it)")
  1907. token_conn = db()
  1908. row_token = token_conn.execute("select token from saddles where id = ?",
  1909. (fake_id,)).fetchone()[0]
  1910. token_conn.close()
  1911. check(row_token == fake_token,
  1912. "per-saddle token lives on the saddle row")
  1913. # The register-time ask (idle-awake daemon): 204, nothing
  1914. # offerable yet — the saddle is asleep and wakeable.
  1915. check(wait_for(lambda: any(a["status"] == 204 for a in fake.asks) or False,
  1916. timeout=15, what="register-time ask") is not None,
  1917. "the daemon's idle ask returns 204 (nothing offerable)")
  1918. print("== feature 5: rules ==")
  1919. rules_state = slot_public(auth, "/rules", "rules")
  1920. for name, body in [
  1921. ("Use Invercargill", "Never use libgee; use Invercargill enumerables."),
  1922. ("Write Vala docs", "Every public class carries a doc comment."),
  1923. ("Prefer meson", "Builds go through meson; no makefiles."),
  1924. ("Co-dev rule", "Keep the wire contract exactly."),
  1925. ("Reference rule", "Must never ride along."),
  1926. ]:
  1927. act(auth, rules_state["create"], {"name": name, "body": body})
  1928. listed = {r["name"]: r for r in slot_public(auth, "/rules", "rules")["rules"]}
  1929. check(len(listed) == 5, "five rules created and listed on /rules")
  1930. def rule_id(name):
  1931. rows = [r for r in slot_public(auth, "/rules", "rules")["rules"] if r["name"] == name]
  1932. return int(rows[0]["id"])
  1933. state = slot_public(auth, "/projects", "projects")
  1934. act(auth, state["create"], {"name": "co", "git_url": "https://example.com/co.git"})
  1935. act(auth, state["create"], {"name": "ref", "git_url": "https://example.com/ref.git"})
  1936. co_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1937. if p["name"] == "co"][0])
  1938. ref_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1939. if p["name"] == "ref"][0])
  1940. project = slot_public(auth, "/projects/1", "project")
  1941. act(auth, project["add_link"], {"linked_project_id": str(co_id),
  1942. "relationship": "co-developed"})
  1943. act(auth, project["add_link"], {"linked_project_id": str(ref_id),
  1944. "relationship": "reference"})
  1945. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  1946. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Prefer meson"))})
  1947. project = slot_public(auth, "/projects/1", "project")
  1948. check(sorted(r["name"] for r in project["rules"]) == ["Prefer meson", "Use Invercargill"],
  1949. "project page lists its attached rules")
  1950. co_project = slot_public(auth, "/projects/%d" % co_id, "project")
  1951. act(auth, co_project["attach_rule"], {"rule_id": str(rule_id("Co-dev rule"))})
  1952. ref_project = slot_public(auth, "/projects/%d" % ref_id, "project")
  1953. act(auth, ref_project["attach_rule"], {"rule_id": str(rule_id("Reference rule"))})
  1954. tasks_state = slot_public(auth, "/tasks", "tasks")
  1955. task_id_tmp = create_queued(auth, {
  1956. "project_id": "1",
  1957. "title": "Rules dispatch",
  1958. "description": "Effective rule set rides the /start payload.",
  1959. "priority": "2",
  1960. })
  1961. rule_task = task_id_tmp
  1962. detail = task_state(auth, rule_task)
  1963. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Write Vala docs"))})
  1964. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  1965. detail = task_state(auth, rule_task)
  1966. check(sorted(r["name"] for r in detail["rules"]) == ["Use Invercargill", "Write Vala docs"],
  1967. "task page lists its attached rules")
  1968. check(wait_for(lambda: len(fake.start_payloads) > 0 or False,
  1969. timeout=30, what="/start push") is not None,
  1970. "dispatcher pushes the task to the fake saddle")
  1971. payload = fake.start_payloads[-1]
  1972. rule_names = [r["name"] for r in payload.get("rules", [])]
  1973. check(rule_names == ["Write Vala docs", "Use Invercargill", "Prefer meson", "Co-dev rule"],
  1974. "effective rules in /start: task, primary, co-developed order (%s)" % rule_names)
  1975. check(all(r.get("body") for r in payload.get("rules", [])),
  1976. "rules carry their bodies")
  1977. check("Reference rule" not in rule_names,
  1978. "reference project rules excluded")
  1979. detail = task_state(auth, rule_task)
  1980. act(auth, detail["rules"][0]["detach"], {})
  1981. check([r["name"] for r in task_state(auth, rule_task)["rules"]] == ["Use Invercargill"],
  1982. "detached task rule disappears")
  1983. rules_rows = slot_public(auth, "/rules", "rules")["rules"]
  1984. docs_row = [r for r in rules_rows if r["name"] == "Write Vala docs"][0]
  1985. act(auth, docs_row["update"], {"name": "Write Vala docs", "body": "Doc comments or bust."})
  1986. check(any(r["body"] == "Doc comments or bust."
  1987. for r in slot_public(auth, "/rules", "rules")["rules"]),
  1988. "rule edit saves the body")
  1989. check(wait_task_done(auth, rule_task, timeout=60) is not None,
  1990. "dispatched task completes against the fake daemon")
  1991. print("== feature 6: project notes + callback ==")
  1992. # Plan 10 phase 1: the shared saddle-callback token is gone —
  1993. # the per-saddle token authorises the callback endpoints.
  1994. callback_token = fake_token
  1995. check(callback_token.startswith("saddle-") and "saddle-callback-" not in callback_token,
  1996. "note callback authorised by the per-saddle token")
  1997. status, _ = saddle_api("POST", "/api/saddle/note", None,
  1998. {"project": "demo", "body": "x"})
  1999. check(status == 401, "note endpoint rejects a missing token")
  2000. status, _ = saddle_api("POST", "/api/saddle/note", "saddle-callback-not-real",
  2001. {"project": "demo", "body": "x"})
  2002. check(status == 401, "note endpoint rejects a wrong (legacy-style) token")
  2003. status, body = saddle_api("POST", "/api/saddle/note", callback_token,
  2004. {"task_id": rule_task, "project": "demo",
  2005. "body": "style.css tokens live in :root"})
  2006. check(status == 200 and body.get("ok") is True, "note accepted with the callback token")
  2007. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  2008. {"project": "no-such-project", "body": "x"})
  2009. check(status == 400, "unknown project rejected")
  2010. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  2011. {"project": "demo", "body": " "})
  2012. check(status == 400, "empty note body rejected")
  2013. project = slot_public(auth, "/projects/1", "project")
  2014. check(any("style.css tokens" in n["body"] and int(n["source_task_id"]) == rule_task
  2015. for n in project["notes"]),
  2016. "project page lists the note with its source task")
  2017. act(auth, [n for n in project["notes"] if "style.css tokens" in n["body"]][0]["delete"], {})
  2018. check(all("style.css tokens" not in n["body"]
  2019. for n in slot_public(auth, "/projects/1", "project")["notes"]),
  2020. "note deleted from the project page")
  2021. # /start payload: notes of primary + co-developed (not reference),
  2022. # oldest first; callback carries the configured base URL + token.
  2023. saddle_api("POST", "/api/saddle/note", callback_token,
  2024. {"project": "demo", "body": "note-one"})
  2025. saddle_api("POST", "/api/saddle/note", callback_token,
  2026. {"project": "demo", "body": "note-two"})
  2027. saddle_api("POST", "/api/saddle/note", callback_token,
  2028. {"project": "co", "body": "co-note"})
  2029. conn = db()
  2030. conn.execute("insert into project_notes (project_id, body, created_at)"
  2031. " values (?, 'ref-note-must-not-ship', strftime('%s','now'))", (ref_id,))
  2032. conn.commit()
  2033. conn.close()
  2034. task_id_tmp = create_queued(auth, {
  2035. "project_id": "1",
  2036. "title": "Notes dispatch",
  2037. "description": "Project notes ride the /start payload.",
  2038. "priority": "2",
  2039. })
  2040. check(wait_for(lambda: len(fake.start_payloads) >= 2 or False,
  2041. timeout=30, what="second /start push") is not None,
  2042. "dispatcher pushes the notes task")
  2043. payload = fake.start_payloads[-1]
  2044. notes = payload.get("project_notes", [])
  2045. check([n["body"] for n in notes] == ["note-one", "note-two", "co-note"],
  2046. "project_notes: primary + co-developed, oldest first (%s)" % [n["body"] for n in notes])
  2047. check(all(n.get("project") for n in notes)
  2048. and notes[2]["project"] == "co",
  2049. "project_notes carry the project name")
  2050. check("ref-note-must-not-ship" not in [n["body"] for n in notes],
  2051. "reference project notes excluded")
  2052. callback = payload.get("callback", {})
  2053. check(callback.get("base_url") == WEB and callback.get("token") == callback_token,
  2054. "callback carries the configured base URL and the minted token")
  2055. # entry cap: 30 of 33 candidates
  2056. conn = db()
  2057. for i in range(33):
  2058. conn.execute("insert into project_notes (project_id, body, created_at)"
  2059. " values (?, ?, strftime('%s','now'))", (1, "bulk-%02d" % i))
  2060. conn.commit()
  2061. conn.close()
  2062. create_queued(auth, {
  2063. "project_id": "1",
  2064. "title": "Entry cap dispatch",
  2065. "priority": "2",
  2066. })
  2067. check(wait_for(lambda: len(fake.start_payloads) >= 3 or False,
  2068. timeout=30, what="third /start push") is not None,
  2069. "dispatcher pushes the entry-cap task")
  2070. notes = fake.start_payloads[-1].get("project_notes", [])
  2071. check(len(notes) == 30 and notes[0]["body"] == "note-one" and notes[1]["body"] == "note-two",
  2072. "project_notes capped at 30 entries, oldest kept (%d)" % len(notes))
  2073. # char cap: the giant note is truncated so the total stays <= 20000
  2074. conn = db()
  2075. conn.execute("delete from project_notes where body like 'bulk-%' or body = 'co-note'")
  2076. conn.execute("insert into project_notes (project_id, body, created_at)"
  2077. " values (?, ?, strftime('%s','now'))", (1, "giant!" + "x" * 25000,))
  2078. conn.commit()
  2079. conn.close()
  2080. create_queued(auth, {
  2081. "project_id": "1",
  2082. "title": "Char cap dispatch",
  2083. "priority": "2",
  2084. })
  2085. check(wait_for(lambda: len(fake.start_payloads) >= 4 or False,
  2086. timeout=30, what="fourth /start push") is not None,
  2087. "dispatcher pushes the char-cap task")
  2088. notes = fake.start_payloads[-1].get("project_notes", [])
  2089. total = sum(len(n["body"]) for n in notes)
  2090. check(len(notes) == 3 and total == 20000 and notes[2]["body"].startswith("giant!"),
  2091. "project_notes char cap: head kept, giant truncated (entries=%d, chars=%d)"
  2092. % (len(notes), total))
  2093. print("== phase 2: pushed chunks -> raw log + terminal view ==")
  2094. # Wait for the last dispatch to finish so its pushes landed.
  2095. check(wait_task_done(auth, task_id_of("Char cap dispatch"), timeout=60) is not None,
  2096. "char-cap task completes")
  2097. conn = db()
  2098. raw_session = conn.execute(
  2099. "select s.id from sessions s join tasks t on t.id = s.task_id"
  2100. " where t.title = 'Char cap dispatch' order by s.id desc limit 1").fetchone()[0]
  2101. rows = conn.execute("select seq, chunk from session_raw_log where session_id = ?"
  2102. " order by seq", (raw_session,)).fetchall()
  2103. conn.close()
  2104. check(len(rows) >= 3, "session_raw_log captured the pushed chunks (%d)" % len(rows))
  2105. seqs = [r[0] for r in rows]
  2106. check(seqs == sorted(seqs) and len(set(seqs)) == len(seqs),
  2107. "pushed chunks stored once, seq strictly increasing")
  2108. text = "".join(r[1] for r in rows)
  2109. check(fake.PROMPT in text and "echo hello" in text and "hello" in text,
  2110. "pushed raw log keeps the prompt and echoed output byte-exact")
  2111. check("working-heartbeat" in text,
  2112. "the flush-timer heartbeat chunks keep arriving mid-round")
  2113. terminal = slot_public(auth, "/tasks/%d/terminal" % task_id_of("Char cap dispatch"),
  2114. "terminal")
  2115. check(terminal.get("has_raw_log") is True and int(terminal["session_id"]) == raw_session,
  2116. "terminal view selects raw rendering for the raw session")
  2117. # Old sessions (typed entries, no raw rows) keep the fallback view
  2118. # (a dedicated fixture task: its only session is the legacy one,
  2119. # so the terminal view cannot prefer a dispatched raw session).
  2120. conn = db()
  2121. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  2122. " values (1, 'Legacy terminal task', 'working', 5, strftime('%s','now'))")
  2123. legacy_task = conn.execute("select max(id) from tasks").fetchone()[0]
  2124. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  2125. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  2126. (legacy_task, fake_id))
  2127. conn.commit()
  2128. legacy_session = conn.execute("select max(id) from sessions").fetchone()[0]
  2129. conn.execute("insert into session_commands (session_id, command_text, output_text,"
  2130. " type, started_at) values (?, 'ls', 'old-output', 'command',"
  2131. " strftime('%s','now'))", (legacy_session,))
  2132. conn.commit()
  2133. conn.close()
  2134. legacy = slot_public(auth, "/tasks/%d/terminal" % legacy_task, "terminal")
  2135. check(legacy.get("has_raw_log") is False,
  2136. "legacy session falls back to the entry-type terminal view")
  2137. request = urllib.request.Request(WEB + "/terminal-stream/%d" % raw_session)
  2138. with urllib.request.urlopen(request, timeout=15) as stream:
  2139. raw_events = []
  2140. deadline = time.monotonic() + 8
  2141. while time.monotonic() < deadline and len(raw_events) < 3:
  2142. line = stream.readline().decode().strip()
  2143. if not line.startswith("data: ") or line == "data: ping":
  2144. continue
  2145. event = json.loads(line[6:])
  2146. if event.get("type") == "raw":
  2147. raw_events.append(event)
  2148. check(len(raw_events) >= 3 and raw_events[0]["text"] == fake.PROMPT
  2149. and raw_events[0]["seq"] < raw_events[1]["seq"],
  2150. "terminal stream serves pushed chunks in seq order (prompt first)")
  2151. print("== phase 2: chunks/results ingestion — auth, idempotency ==")
  2152. # Token auth on both push channels (plan 10: the per-saddle
  2153. # bearer authorises every daemon->web call).
  2154. status, _ = saddle_api("POST", "/api/saddle/chunks", None,
  2155. {"session_id": raw_session, "chunks": []})
  2156. check(status == 401, "chunks endpoint rejects a missing token")
  2157. status, _ = saddle_api("POST", "/api/saddle/results", "saddle-bogus-token",
  2158. {"session_id": raw_session, "state": "working"})
  2159. check(status == 401, "results endpoint rejects a wrong token")
  2160. status, _ = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2161. {"session_id": 99999, "chunks": []})
  2162. check(status == 400, "chunks for an unknown session rejected")
  2163. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2164. {"session_id": raw_session, "state": "done"})
  2165. check(status == 200, "the owning saddle's session accepts its results")
  2166. # Pushed chunk idempotency: re-pushing a batch (the outbox's
  2167. # at-least-once redelivery after a lost response) consumes the
  2168. # duplicates and stores only the tail.
  2169. conn = db()
  2170. before = conn.execute("select count(*) from session_raw_log where session_id = ?",
  2171. (raw_session,)).fetchone()[0]
  2172. conn.close()
  2173. redelivery = [{"seq": r[0], "text": r[1]} for r in rows[:3]]
  2174. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2175. {"session_id": raw_session, "chunks": redelivery})
  2176. check(status == 200 and body.get("ok") is True and int(body.get("stored") or 0) == 0,
  2177. "a fully-duplicate batch stores nothing (duplicates consumed)")
  2178. fresh = [{"seq": 9000, "text": "late-flush\r\n"},
  2179. {"seq": 9001, "text": ""}] # truly empty text: no row
  2180. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2181. {"session_id": raw_session, "chunks": fresh})
  2182. check(status == 200 and int(body.get("stored") or 0) == 1,
  2183. "a partial-redelivery batch stores only the new chunks")
  2184. conn = db()
  2185. after = conn.execute("select count(*) from session_raw_log where session_id = ?",
  2186. (raw_session,)).fetchone()[0]
  2187. empty_row = conn.execute(
  2188. "select count(*) from session_raw_log where session_id = ? and seq = 9001",
  2189. (raw_session,)).fetchone()[0]
  2190. conn.close()
  2191. check(after == before + 1 and empty_row == 0,
  2192. "redelivered chunks never duplicate rows; empty text stores nothing")
  2193. # Pushed entries: today's OutputEntry shape with the daemon's
  2194. # global entry ids — a redelivered results push stores its
  2195. # entries exactly once.
  2196. def command_rows(session):
  2197. conn = db()
  2198. try:
  2199. return conn.execute(
  2200. "select command_text, type from session_commands"
  2201. " where session_id = ? order by id", (session,)).fetchall()
  2202. finally:
  2203. conn.close()
  2204. entries = [{"id": 8101, "command": "sed -n 1p README.md", "output": "# demo",
  2205. "exit_code": 0, "type": "command", "timestamp": "2026-09-06T00:00:00Z"}]
  2206. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2207. {"session_id": raw_session, "state": "working",
  2208. "entries": entries})
  2209. check(status == 200, "entries push accepted")
  2210. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2211. {"session_id": raw_session, "state": "working",
  2212. "entries": entries})
  2213. check(status == 200, "redelivered entries push accepted (at-least-once)")
  2214. stored = command_rows(raw_session)
  2215. check(len([r for r in stored if r[0] == "sed -n 1p README.md"]) == 1,
  2216. "redelivered entries store exactly once (daemon-global dedup)")
  2217. # The retired daemon routes 404 (phase 2 deleted /output, /log
  2218. # and /start serving) — and the web app never calls them.
  2219. for method, path in (("GET", "/output?since=0"), ("GET", "/log?since=0"),
  2220. ("POST", "/start")):
  2221. request = urllib.request.Request(
  2222. "http://127.0.0.1:%d%s" % (fake.port, path),
  2223. data=b"{}" if method == "POST" else None, method=method)
  2224. try:
  2225. urllib.request.urlopen(request, timeout=5)
  2226. gone = False
  2227. except urllib.error.HTTPError as error:
  2228. gone = error.code == 404
  2229. check(gone, "the fake daemon's %s %s is deleted (404)" % (method, path))
  2230. with open(os.path.join(WORK, "app.log")) as handle:
  2231. app_log = handle.read()
  2232. check("Saddle output request" not in app_log and "Saddle log request" not in app_log,
  2233. "the web never polls /output or /log anymore")
  2234. print("== capabilities: tag-based routing ==")
  2235. saddles_state = slot_public(auth, "/saddles", "saddles")
  2236. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2237. act(auth, saddles_state["create_capability"], {"name": "bigmem"})
  2238. saddles_state = slot_public(auth, "/saddles", "saddles")
  2239. caps = {c["name"]: c for c in saddles_state["capabilities"]}
  2240. check(len(caps) == 2 and all(int(c["saddle_count"]) == 0 and int(c["task_count"]) == 0
  2241. for c in caps.values()),
  2242. "capabilities created and listed with zero usage")
  2243. fake_card = saddle_card(auth, "fake-saddle")
  2244. check(fake_card["capabilities"] == [],
  2245. "saddle card starts with no capability chips")
  2246. # A task requiring 'gpu' waits while the only idle saddle lacks it;
  2247. # a later task without requirements still dispatches (skip-and-continue).
  2248. tasks_state = slot_public(auth, "/tasks", "tasks")
  2249. task_id_tmp = create_queued(auth, {
  2250. "project_id": "1",
  2251. "title": "GPU task",
  2252. "priority": "2",
  2253. })
  2254. gpu_task = task_id_tmp
  2255. detail = task_state(auth, gpu_task)
  2256. act(auth, detail["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  2257. check(wait_for(lambda: [c["name"] for c in
  2258. task_state(auth, gpu_task)["capabilities"]] == ["gpu"]
  2259. or False, timeout=30, what="capability attached") is not None,
  2260. "task page lists the required capability")
  2261. detail = task_state(auth, gpu_task)
  2262. # The only idle saddle lacks the tag, so the queue flags the wait
  2263. # (read before any other task claims the idle saddle).
  2264. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2265. if int(t["id"]) == gpu_task][0]
  2266. check(queue["status"] == "queued" and queue["capabilities"] == ["gpu"]
  2267. and queue.get("waiting_for_saddle") is True,
  2268. "queue row shows the waiting task with its tag and wait flag")
  2269. task_id_tmp = create_queued(auth, {
  2270. "project_id": "1",
  2271. "title": "Any-saddle task",
  2272. "priority": "3",
  2273. })
  2274. any_task = task_id_tmp
  2275. check(wait_for(lambda: task_state(auth, any_task).get("status") != "queued" or False,
  2276. timeout=30, what="uncapable task dispatches") is not None,
  2277. "task without requirements dispatches past the waiting task")
  2278. def capability_wait_logged():
  2279. with open(os.path.join(WORK, "app.log")) as handle:
  2280. app_log = handle.read()
  2281. return "waits for a capable saddle" in app_log and "requires: gpu" in app_log
  2282. check(wait_for(capability_wait_logged, timeout=20,
  2283. what="capability wait log") is not None,
  2284. "dispatcher logs the capability wait")
  2285. # Attaching the tag to the saddle releases the task.
  2286. fake_card = saddle_card(auth, "fake-saddle")
  2287. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  2288. fake_card = saddle_card(auth, "fake-saddle")
  2289. check([c["name"] for c in fake_card["capabilities"]] == ["gpu"],
  2290. "saddle card shows the attached chip")
  2291. check(wait_task_done(auth, gpu_task, timeout=60) is not None,
  2292. "task dispatches once the saddle carries the required tag")
  2293. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2294. if int(t["id"]) == gpu_task][0]
  2295. check(queue.get("waiting_for_saddle") is not True,
  2296. "wait flag clears once dispatched")
  2297. # Multi-tag: gpu + bigmem required, only gpu carried → waits; adding
  2298. # bigmem completes the superset. Both requirements ride the create
  2299. # form (atomic — attaching them one at a time would race a tick
  2300. # into dispatching on the partial set).
  2301. task_id_tmp = create_queued(auth, {
  2302. "project_id": "1",
  2303. "title": "Big task",
  2304. "priority": "2",
  2305. "capability_id": [str(int(caps["gpu"]["id"])), str(int(caps["bigmem"]["id"]))],
  2306. })
  2307. big_task = task_id_tmp
  2308. check(wait_for(lambda: ([t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2309. if int(t["id"]) == big_task][0].get("waiting_for_saddle")
  2310. is True) or False, timeout=30, what="big task waits") is not None,
  2311. "task waits when the saddle's tags are not a superset")
  2312. fake_card = saddle_card(auth, "fake-saddle")
  2313. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["bigmem"]["id"]))})
  2314. check(wait_task_done(auth, big_task, timeout=60) is not None,
  2315. "task dispatches once the superset is complete")
  2316. # Detach a requirement (on a draft — capabilities lock once a
  2317. # worker has the job); delete a capability everywhere.
  2318. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2319. "project_id": "1",
  2320. "title": "Detach probe task",
  2321. "priority": "4",
  2322. "capability_id": [str(int(caps["gpu"]["id"])), str(int(caps["bigmem"]["id"]))],
  2323. })
  2324. detach_probe = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2325. if t["title"] == "Detach probe task"][0])
  2326. act(auth, [c for c in task_state(auth, detach_probe)["capabilities"]
  2327. if c["name"] == "bigmem"][0]["detach"], {})
  2328. check([c["name"] for c in task_state(auth, detach_probe)["capabilities"]] == ["gpu"],
  2329. "detached requirement disappears from the task")
  2330. bigmem_row = [c for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2331. if c["name"] == "bigmem"][0]
  2332. act(auth, bigmem_row["delete"], {})
  2333. saddles_state = slot_public(auth, "/saddles", "saddles")
  2334. check(all(c["name"] != "bigmem" for c in saddles_state["capabilities"]),
  2335. "deleted capability gone from the catalogue")
  2336. check([c["name"] for c in task_state(auth, big_task)["capabilities"]] == ["gpu"],
  2337. "deleting a capability drops its task requirements")
  2338. check(all(c["name"] != "bigmem"
  2339. for c in saddle_card(auth, "fake-saddle")["capabilities"]),
  2340. "deleting a capability drops it from saddles")
  2341. print("== B4: required capabilities on the create form ==")
  2342. tasks_state = slot_public(auth, "/tasks", "tasks")
  2343. gpu_option = [o for o in tasks_state.get("capability_options", [])
  2344. if o["name"] == "gpu"][0]
  2345. check(len(tasks_state.get("capability_options", [])) >= 1,
  2346. "queue page offers capability options in the create form")
  2347. conn = db()
  2348. before = conn.execute("select count(*) from tasks").fetchone()[0]
  2349. conn.close()
  2350. act(auth, tasks_state["create"], {
  2351. "project_id": "1",
  2352. "title": "Bad cap task",
  2353. "capability_id": [gpu_option["id"], "999"],
  2354. })
  2355. conn = db()
  2356. after = conn.execute("select count(*) from tasks").fetchone()[0]
  2357. conn.close()
  2358. check(after == before, "unknown capability id rejects the create")
  2359. task_id_tmp = create_queued(auth, {
  2360. "project_id": "1",
  2361. "title": "Cap-on-create task",
  2362. "capability_id": [gpu_option["id"]],
  2363. })
  2364. cap_create = task_id_tmp
  2365. detail = task_state(auth, cap_create)
  2366. check([c["name"] for c in detail["capabilities"]] == ["gpu"],
  2367. "capabilities from the create form land on the task")
  2368. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2369. if int(t["id"]) == cap_create][0]
  2370. check(queue["capabilities"] == ["gpu"],
  2371. "queue row shows the created task's requirements")
  2372. # The waiting flag must hold it back until the capable saddle frees
  2373. # up (the fake saddle still carries gpu from the routing checks).
  2374. check(queue.get("waiting_for_saddle") is not True,
  2375. "capable saddle available: no wait flag on the new task")
  2376. # Drain barrier: the cap task must be CLAIMED before the flaky
  2377. # arc arms fail_next (under parallel-shard load the dispatch tick
  2378. # can lag task creation; an unclaimed predecessor would consume
  2379. # the one-shot failure flag instead of the flaky task).
  2380. check(wait_for(lambda: task_state(auth, cap_create).get("status")
  2381. in ("working", "done", "failed") or False,
  2382. timeout=60, what="cap task claimed") is not None,
  2383. "the capable task is claimed before the flaky arc starts")
  2384. print("== retry + resume ==")
  2385. # A daemon-side failure fails the task with its explanation.
  2386. fake.fail_next = True
  2387. task_id_tmp = create_queued(auth, {
  2388. "project_id": "1",
  2389. "title": "Flaky task",
  2390. "priority": "2",
  2391. })
  2392. flaky = task_id_tmp
  2393. check(wait_for(lambda: task_state(auth, flaky).get("status") == "failed" or False,
  2394. timeout=90, what="flaky task fails") is not None,
  2395. "daemon failure fails the task")
  2396. detail = task_state(auth, flaky)
  2397. check("bash -n rejected" in (detail.get("summary") or ""),
  2398. "failure summary shows the daemon's explanation")
  2399. # Retry: summary moves into a comment and clears, task requeues,
  2400. # history stays, and the re-dispatch restores the workspace.
  2401. comments_before = len(detail.get("comments", []))
  2402. progress_before = len(detail.get("progress", []))
  2403. act(auth, detail["retry"], {})
  2404. detail = task_state(auth, flaky)
  2405. check(detail["status"] == "queued" and (detail.get("summary") or "") == "",
  2406. "retry requeues the task and clears the stale summary")
  2407. check(any("bash -n rejected" in c["body"] and c["author"] == "agent"
  2408. for c in detail["comments"]),
  2409. "failure explanation kept as an agent comment (author 'agent')")
  2410. check(any(c["body"] == "Task retried by user" and c["author"] == "system"
  2411. and c.get("is_system") for c in detail["comments"]),
  2412. "retry lands its audit comment as a system row (never an agent row)")
  2413. check(len(detail["comments"]) >= comments_before + 1,
  2414. "retry keeps the comment history")
  2415. pushes_before = len([p for p in fake.start_payloads
  2416. if int(p.get("task", {}).get("id") or 0) == flaky])
  2417. check(wait_for(lambda: len([p for p in fake.start_payloads
  2418. if int(p.get("task", {}).get("id") or 0) == flaky])
  2419. > pushes_before or False, timeout=90,
  2420. what="flaky task re-dispatched") is not None,
  2421. "retried task dispatches again")
  2422. # The resumed arc surfaces on the next /status read — in the
  2423. # push world that is the operator's manual refresh.
  2424. act(auth, saddle_card(auth, "fake-saddle")["refresh"], {})
  2425. check(wait_task_done(auth, flaky, timeout=60) is not None,
  2426. "retried task completes on the restored workspace")
  2427. detail = task_state(auth, flaky)
  2428. check(any("restored the session context" in c["body"]
  2429. and c["author"] == "system" and c.get("is_system")
  2430. for c in detail.get("comments", [])),
  2431. "daemon resume reported on the first status after the restore")
  2432. check(all("restored the session context" not in p["summary"]
  2433. for p in detail.get("progress", [])),
  2434. "the resume note stays OUT of the progress feed (F8: status is not progress)")
  2435. # Manual resume: a task stuck working on an offline saddle.
  2436. task_id_tmp = create_queued(auth, {
  2437. "project_id": "1",
  2438. "title": "Stuck task",
  2439. "priority": "2",
  2440. })
  2441. stuck = task_id_tmp
  2442. check(wait_for(lambda: task_state(auth, stuck).get("status") == "working" or False,
  2443. timeout=60, what="stuck task starts working") is not None,
  2444. "stuck task reaches working")
  2445. # Deterministic claim for the resume leg below: the round's end,
  2446. # the refresh probe AND the dispatcher's wake for the requeued task
  2447. # all trigger self-asks that could steal it — freeze every trigger
  2448. # until the manual ask below has made the claim.
  2449. fake.ask_on_terminal = False
  2450. fake.ask_on_idle_status = False
  2451. fake.ask_on_wake = False
  2452. fake.settle_asks()
  2453. conn = db()
  2454. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  2455. conn.commit()
  2456. conn.close()
  2457. detail = task_state(auth, stuck)
  2458. check(detail.get("resume_available") is True,
  2459. "task page offers resume while its saddle is offline")
  2460. # The resume POSTs task-update cancel to the daemon; the abort
  2461. # handler fires an ungated re-ask that would race the manual claim
  2462. # below — slow it past the manual ask (the knob the slow-ask
  2463. # regression uses).
  2464. fake.ask_delay = 5.0
  2465. act(auth, detail["resume"], {})
  2466. detail = task_state(auth, stuck)
  2467. check(detail["status"] == "queued",
  2468. "manual resume requeues the stuck task")
  2469. check(any(c["body"] == "Saddle became unreachable; task requeued"
  2470. and c["author"] == "system" and c.get("is_system")
  2471. for c in detail["comments"]),
  2472. "manual resume lands the interruption comment as a system row")
  2473. check(all(s["status"] == "offline"
  2474. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  2475. "saddle stays offline after the manual requeue")
  2476. # Bringing the saddle back lets the requeued task resume and finish.
  2477. fake.state = "idle"
  2478. fake_card = saddle_card(auth, "fake-saddle")
  2479. act(auth, fake_card["refresh"], {})
  2480. check(any(s["status"] == "idle"
  2481. for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2482. if s["name"] == "fake-saddle"),
  2483. "refreshed saddle returns idle")
  2484. # The refreshed daemon is idle-awake: it asks (the real loop's
  2485. # own ask; driven directly for determinism — every self-ask trigger
  2486. # is frozen and the abort re-ask is slowed past it; joining that
  2487. # delayed thread here would fire its ask first, so it is left to
  2488. # sleep out the rest of the bundle).
  2489. status, payload = fake.ask_now()
  2490. fake.ask_on_idle_status = True
  2491. fake.ask_on_terminal = True
  2492. fake.ask_on_wake = True
  2493. fake.ask_delay = 0.0
  2494. check(status == 200, "the refreshed daemon's ask claims the requeued task")
  2495. check(wait_task_done(auth, stuck, timeout=60) is not None,
  2496. "requeued task resumes on the refreshed saddle and completes")
  2497. # =============================================================================
  2498. # Bundle: subtasks — the plan-12 task graph: plain-task parking (no
  2499. # subtask events exist to resume it), the DELETED subtask machinery's
  2500. # verbatim refusals, and the goal agent's task CLI in depth
  2501. # (capabilities, ownership, the daemon's task-reading API, the
  2502. # goal-run block answered from the task page).
  2503. # =============================================================================
  2504. def bundle_subtasks(ctx):
  2505. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2506. app = ctx.app
  2507. # A hold tag nothing carries: goal tasks created with it stay
  2508. # queued (a stable parked agent) until released at the settle.
  2509. saddles_state = slot_public(auth, "/saddles", "saddles")
  2510. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2511. gpu_cap_id = [c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2512. if c["name"] == "gpu"][0]
  2513. def goal_state(goal_id):
  2514. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  2515. def create_goal_row(fields):
  2516. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  2517. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  2518. if g["title"] == fields["title"]]
  2519. return int(rows[0]["id"])
  2520. print("== B7: plain-task parking stays put (no subtask events) ==")
  2521. fake.suspend_on_title = "Suspend plain"
  2522. pushes_before = len(fake.start_payloads)
  2523. plain = create_queued(auth, {
  2524. "project_id": "1",
  2525. "title": "Suspend plain",
  2526. "priority": "2",
  2527. })
  2528. check(wait_for(lambda: task_state(auth, plain).get("status") == "suspended"
  2529. or False, timeout=60, what="plain task parks") is not None,
  2530. "daemon 'suspended' state parks the task")
  2531. detail = task_state(auth, plain)
  2532. check(detail.get("display") == "parked",
  2533. "a parked plain task displays as parked (%s)" % detail.get("display"))
  2534. check(any(s["status"] == "idle"
  2535. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  2536. "suspension frees the saddle")
  2537. first_push = fake.start_payloads[pushes_before]
  2538. check(first_push.get("kind") == "task" and first_push.get("creator") == "human"
  2539. and first_push.get("mode") == "implement",
  2540. "the /start payload carries the plan-12 identity triplet (kind/creator/mode)")
  2541. check("subtasks" not in first_push and "parent" not in first_push,
  2542. "the plan-12 payload drops the subtasks/parent members")
  2543. # Other tasks finishing must NOT resume a parked plain task (the
  2544. # subtask-event channel is gone; only goal events resume goal runs).
  2545. conn = db()
  2546. conn.execute("insert into tasks (project_id, title, status, priority, summary,"
  2547. " completed_at, created_at) values (1, 'Unrelated finisher', 'done',"
  2548. " 5, 'finished loudly', strftime('%s','now','+1 second'),"
  2549. " strftime('%s','now'))")
  2550. conn.commit()
  2551. conn.close()
  2552. check(quiet_window(quiet_seconds(),
  2553. lambda: task_state(auth, plain)["status"] == "suspended",
  2554. "plain park survives unrelated finishes"),
  2555. "a parked plain task never resumes on other tasks' events")
  2556. print("== the deleted machinery refuses, verbatim ==")
  2557. status, body = saddle_api("POST", "/api/saddle/subtask", fake_token,
  2558. {"parent_task_id": plain, "title": "ghost"})
  2559. check(status == 404,
  2560. "the /api/saddle/subtask callback route is gone (404)")
  2561. conn = db()
  2562. plain_session = conn.execute(
  2563. "select id from sessions where task_id = ? and ended_at is null",
  2564. (plain,)).fetchone()[0]
  2565. conn.close()
  2566. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2567. {"type": "subtask", "session_id": plain_session,
  2568. "data": {"title": "Ghost child"}})
  2569. check(status == 400 and "subtask" in (body.get("error") or "")
  2570. and "gone" in (body.get("error") or ""),
  2571. "the 'subtask' update type errors verbatim (%s)" % body.get("error"))
  2572. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2573. {"type": "plan", "session_id": plain_session,
  2574. "data": {"plan": "# nope"}})
  2575. check(status == 400 and "plan" in (body.get("error") or ""),
  2576. "the task-level 'plan' update type errors verbatim (%s)" % body.get("error"))
  2577. # The daemon's task CLI: no parent/plan members; goal context instead.
  2578. status, body = saddle_api("GET", "/api/saddle/task/%d" % plain, fake_token)
  2579. check(status == 200 and "plan" not in body.get("task", {})
  2580. and "parent_task_id" not in body.get("task", {})
  2581. and "goal_id" in body.get("task", {}),
  2582. "the task CLI detail drops parent/plan and carries goal_id")
  2583. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", fake_token)
  2584. check(status == 200 and all("parent_task_id" not in t and "goal_id" in t
  2585. for t in body.get("tasks", [])),
  2586. "the task CLI list drops parent_task_id and carries goal_id")
  2587. # Settle the parked plain task: nothing will resume it — cancel it.
  2588. act(auth, task_state(auth, plain)["cancel"], {})
  2589. check(wait_for(lambda: task_state(auth, plain)["status"] == "failed" or False,
  2590. timeout=30, what="parked plain task cancelled") is not None,
  2591. "the parked plain task cancels (the human cleanup path)")
  2592. print("== the goal agent's task CLI in depth ==")
  2593. goal = create_goal_row({"project_id": "1", "title": "Sequencing goal",
  2594. "brief": "Fan tasks out with the CLI.",
  2595. "branch_name": "goal/sequence"})
  2596. fake.goal_script = [("plan", "# Plan\n\n1. Fan out")]
  2597. act(auth, goal_state(goal)["start"], {})
  2598. check(wait_for(lambda: goal_state(goal)["status"] == "plan_review" or False,
  2599. timeout=60, what="sequencing goal plans") is not None,
  2600. "the sequencing goal reaches plan review")
  2601. fake.goal_script = [("suspend",)]
  2602. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  2603. {"answer": "Plan approved. Proceed with implementation."})
  2604. conn = db()
  2605. run_task = conn.execute(
  2606. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  2607. (goal,)).fetchone()[0]
  2608. agent_session = conn.execute(
  2609. "select id from sessions where task_id = ? and ended_at is null",
  2610. (run_task,)).fetchone()[0]
  2611. conn.close()
  2612. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  2613. or False, timeout=60, what="sequencing agent parks") is not None,
  2614. "the sequencing goal agent parks")
  2615. # Create with capabilities: attached until assignment (the hold
  2616. # keeps the task queued), mandate + mode stored, ephemeral branch.
  2617. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  2618. "session_id": agent_session, "title": "Held worker",
  2619. "mandate": "Do the held work.", "mode": "review",
  2620. "capabilities": ["gpu"]})
  2621. check(status == 200 and body.get("ok") is True,
  2622. "task create with a capability tag succeeds")
  2623. held = int(body["task_id"])
  2624. detail = task_state(auth, held)
  2625. check(detail["status"] == "draft" and detail["mode"] == "review",
  2626. "the held worker drafts with its mode")
  2627. check([c["name"] for c in detail.get("capabilities", [])] == ["gpu"],
  2628. "the capability attaches to the created task")
  2629. check(detail["task_branch"] == "task/%d-%d" % (goal, held)
  2630. and detail["branch_from"] == "goal/sequence",
  2631. "the CLI task's ephemeral branch pair is stored")
  2632. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  2633. "session_id": agent_session, "task_id": held})
  2634. check(status == 200, "the held worker enqueues")
  2635. check(quiet_window(3, lambda: task_state(auth, held)["status"] == "queued",
  2636. "unsatisfiable capability holds dispatch"),
  2637. "the unsatisfiable capability holds the queued worker (never assigned)")
  2638. queue_row = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2639. if int(t["id"]) == held][0]
  2640. check(queue_row.get("waiting_for_saddle") is True,
  2641. "the queue annotates the held worker as waiting for a saddle")
  2642. # The human edit path: goal tasks never carry enqueue-after (the
  2643. # field is human-tasks-only — the update silently ignores it).
  2644. act(auth, task_state(auth, held)["update"], {
  2645. "priority": "4", "enqueue_after_task_id": str(held - 1)})
  2646. check(task_state(auth, held).get("enqueue_after_task_id") in (None, 0, "0"),
  2647. "a goal task ignores the auto-enqueue-after field on edit")
  2648. # Ownership: the same saddle's goal agent cannot touch another
  2649. # goal's task; a plain session is not a goal-agent identity.
  2650. other_goal = create_goal_row({"project_id": "1", "title": "Other goal",
  2651. "brief": "b", "branch_name": "goal/other",
  2652. "priority": "9"})
  2653. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token,
  2654. {"session_id": agent_session, "title": "x",
  2655. "mandate": "m"})
  2656. scope_task = int(body["task_id"])
  2657. check(int(task_state(auth, scope_task)["goal_id"] or 0) == goal,
  2658. "the callback scopes task creation to its own goal")
  2659. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token,
  2660. {"session_id": agent_session, "task_id": scope_task})
  2661. check(status == 200, "the owned draft deletes")
  2662. check(not any(t["id"] == scope_task
  2663. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  2664. "the deleted task is gone from the queue")
  2665. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  2666. {"session_id": agent_session, "task_id": plain})
  2667. check(status == 400 and "does not belong to your goal" in (body.get("error") or ""),
  2668. "the goal agent cannot enqueue a standalone task")
  2669. # The daemon's task CLI detail carries the goal context.
  2670. status, body = saddle_api("GET", "/api/saddle/task/%d" % held, fake_token)
  2671. check(status == 200
  2672. and int(body["task"].get("goal_id") or 0) == goal
  2673. and body["task"].get("goal_title") == "Sequencing goal",
  2674. "the task CLI detail names the owning goal")
  2675. print("== the goal-run block answers from the task page (C1) ==")
  2676. # A question block raised in goal context lands on the run task's
  2677. # own row; the TASK page's answer action funnels into the one
  2678. # goal answer path and resumes the agent with the verdict riding
  2679. # the allocation (the goal page shares the path).
  2680. fake.goal_script = [("question", "Which harness: pytest or vitest?",
  2681. ["pytest", "vitest"])]
  2682. conn = db()
  2683. # Plan 15 C3: a terminal transition (a done task row newer than
  2684. # the watermark) is the resume signal — no event rows exist.
  2685. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  2686. " priority, completed_at, created_at) values (1, ?, 'task',"
  2687. " 'Nudge', 'done', 5,"
  2688. " strftime('%s','now'),"
  2689. " strftime('%s','now','-30 seconds'))", (goal,))
  2690. conn.commit()
  2691. conn.close()
  2692. check(wait_for(lambda: task_state(auth, run_task)["status"] == "blocked"
  2693. or False, timeout=60, what="goal block parks the run") is not None,
  2694. "a goal question parks the run task on its own block row")
  2695. run_detail = task_state(auth, run_task)
  2696. question_block = [b for b in run_detail["blocks"]
  2697. if b["block_type"] == "question"][0]
  2698. check(question_block.get("question") == "Which harness: pytest or vitest?",
  2699. "the run task's block carries the goal question verbatim")
  2700. goal_block_ids = [int(b["id"]) for b in goal_state(goal)["blocks"]
  2701. if b.get("block_type") == "question"]
  2702. check(goal_block_ids == [int(question_block["id"])],
  2703. "the goal page's card is the SAME row (no dual-row pair)")
  2704. act(auth, question_block["answer_action"], {"answer": "pytest"})
  2705. fake.goal_script = [("suspend",)]
  2706. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  2707. or False, timeout=60, what="answered block resumes the agent")
  2708. is not None,
  2709. "the answered block resumes the goal agent")
  2710. answered = [b for b in task_state(auth, run_task)["blocks"]
  2711. if b["block_type"] == "question"][0]
  2712. check(answered.get("answer") == "pytest",
  2713. "the verdict is stored on the single block row")
  2714. print("== settle: release the hold and let the shard drain ==")
  2715. # Drop the hold tag so the held worker can dispatch and complete;
  2716. # the parked agent resumes on its completion, re-parks (script),
  2717. # and the shard shuts down with an empty queue.
  2718. act(auth, task_state(auth, held)["capabilities"][0]["detach"], {})
  2719. check(wait_task_done(auth, held, timeout=90) is not None,
  2720. "the released held worker completes")
  2721. check(wait_for(lambda: any(e["kind"] == "task-done" and int(e["task_id"]) == held
  2722. for e in goal_state(goal)["events"]) or False,
  2723. timeout=30, what="narrative hears the held worker") is not None,
  2724. "the narrative records the held worker's completion")
  2725. act(auth, goal_state(goal)["cancel"], {})
  2726. check(wait_for(lambda: goal_state(goal)["status"] == "cancelled" or False,
  2727. timeout=30, what="sequencing goal cancelled") is not None,
  2728. "the sequencing goal cancels (the shard's cleanup path)")
  2729. # =============================================================================
  2730. # Bundle: lineage — the plan-12 goal lineage: goal context on worker
  2731. # dispatches (read-only reference + ephemeral branch), the daemon's
  2732. # task-reading API (goal members, no parent/plan), and the goal
  2733. # agent's workspace affinity while parked.
  2734. # =============================================================================
  2735. def bundle_lineage(ctx):
  2736. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2737. app = ctx.app
  2738. r4_token = fake_token
  2739. # gpu exists only as a hold (no saddle carries it): the held goal
  2740. # worker stays queued until the release loop lifts it.
  2741. saddles_state = slot_public(auth, "/saddles", "saddles")
  2742. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2743. def goal_state(goal_id):
  2744. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  2745. def create_goal_row(fields):
  2746. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  2747. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  2748. if g["title"] == fields["title"]]
  2749. return int(rows[0]["id"])
  2750. goal = create_goal_row({"project_id": "1", "title": "Lineage goal",
  2751. "brief": "Carry the goal lineage.",
  2752. "branch_name": "goal/lineage"})
  2753. fake.goal_script = [("plan", "# Lineage plan\n\n1. Fan out\n2. Verify")]
  2754. act(auth, goal_state(goal)["start"], {})
  2755. check(wait_for(lambda: goal_state(goal)["status"] == "plan_review" or False,
  2756. timeout=60, what="lineage goal plans") is not None,
  2757. "the lineage goal reaches plan review")
  2758. fake.goal_script = [("suspend",)]
  2759. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  2760. {"answer": "Plan approved. Proceed with implementation."})
  2761. conn = db()
  2762. auto_parent = conn.execute(
  2763. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  2764. (goal,)).fetchone()[0]
  2765. agent_session = conn.execute(
  2766. "select id from sessions where task_id = ? and ended_at is null",
  2767. (auto_parent,)).fetchone()[0]
  2768. conn.close()
  2769. check(wait_for(lambda: task_state(auth, auto_parent)["status"] == "suspended"
  2770. or False, timeout=60, what="lineage goal agent parks") is not None,
  2771. "the lineage goal agent parks")
  2772. # Two workers under the goal: one free, one held by the gpu tag.
  2773. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2774. "session_id": agent_session, "title": "Auto child",
  2775. "mandate": "build the widget", "mode": "implement"})
  2776. auto_child = int(body["task_id"])
  2777. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2778. "session_id": agent_session, "title": "Auto grandchild",
  2779. "mandate": "verify the widget", "mode": "test",
  2780. "capabilities": ["gpu"]})
  2781. auto_grand = int(body["task_id"])
  2782. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2783. "session_id": agent_session, "title": "Wire the flange",
  2784. "description": "torque to spec"})
  2785. check(status == 400 and "mandate is required" in (body.get("error") or ""),
  2786. "task create without a mandate errors verbatim (%s)" % body.get("error"))
  2787. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2788. "session_id": agent_session, "title": "Wire the flange",
  2789. "mandate": "torque to spec"})
  2790. flange_task = int(body["task_id"])
  2791. for held in (auto_child, auto_grand, flange_task):
  2792. saddle_api("POST", "/api/saddle/task/enqueue", r4_token,
  2793. {"session_id": agent_session, "task_id": held})
  2794. check(wait_for(lambda: task_state(auth, auto_child)["status"] in
  2795. ("queued", "assigned", "working", "done") or False,
  2796. timeout=30, what="free goal worker dispatches") is not None,
  2797. "the free goal worker dispatches")
  2798. check(quiet_window(3, lambda: task_state(auth, auto_grand)["status"] == "queued",
  2799. "held goal worker stays queued"),
  2800. "the gpu-held goal worker stays queued")
  2801. # A goal worker's dispatch carries the read-only goal context.
  2802. lineage_push = [p for p in fake.start_payloads
  2803. if int(p.get("task", {}).get("id") or 0) == auto_child][-1]
  2804. goal_ctx = lineage_push.get("goal") or {}
  2805. check(int(goal_ctx.get("id") or 0) == goal
  2806. and goal_ctx.get("branch") == "goal/lineage"
  2807. and "Carry the goal lineage." in goal_ctx.get("brief", "")
  2808. and "# Lineage plan" in goal_ctx.get("plan", ""),
  2809. "the worker dispatch carries the goal context (brief + approved plan)")
  2810. check(lineage_push.get("ephemeral_branch") == "task/%d-%d" % (goal, auto_child)
  2811. and lineage_push.get("kind") == "task"
  2812. and lineage_push.get("mode") == "implement"
  2813. and lineage_push.get("creator") == "goal",
  2814. "the worker dispatch carries the ephemeral branch + identity triplet")
  2815. check("parent" not in lineage_push and "subtasks" not in lineage_push,
  2816. "the plan-12 payload drops the parent/subtasks members")
  2817. print("== R5 B2: task-reading API ==")
  2818. status, _ = saddle_api("GET", "/api/saddle/tasks", None)
  2819. check(status == 401, "tasks endpoint rejects a missing token")
  2820. status, _ = saddle_api("GET", "/api/saddle/task/%d" % auto_child, None)
  2821. check(status == 401, "task detail endpoint rejects a missing token")
  2822. # Fixture: a second project whose tasks all carry the "Diff " title
  2823. # prefix for the project_id filter checks — created first so the
  2824. # unfiltered list has the population the count check expects.
  2825. state = slot_public(auth, "/projects", "projects")
  2826. act(auth, state["create"], {"name": "diff-fabrica",
  2827. "git_url": "ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git"})
  2828. conn = db()
  2829. other_project = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  2830. if p["name"] == "diff-fabrica"][0])
  2831. for suffix in ("fabrica", "scp"):
  2832. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  2833. " values (?, ?, 'done', 5, strftime('%s','now'))",
  2834. (other_project, "Diff %s" % suffix))
  2835. conn.commit()
  2836. conn.close()
  2837. status, body = saddle_api("GET", "/api/saddle/tasks", r4_token)
  2838. check(status == 200 and len(body.get("tasks", [])) > 5,
  2839. "tasks endpoint lists tasks without filters")
  2840. row = [t for t in body["tasks"] if int(t["id"]) == auto_child][0]
  2841. check(row["title"] == "Auto child" and int(row["goal_id"] or 0) == goal
  2842. and row["status"] in ("done", "queued", "working"),
  2843. "compact rows carry id/title/status/goal_id")
  2844. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", r4_token)
  2845. check(all(True for _ in [1]) # project 1 dominates the data set
  2846. and not any(int(t["id"]) == 0 for t in body["tasks"]),
  2847. "project_id filter accepted")
  2848. status, body = saddle_api("GET",
  2849. "/api/saddle/tasks?project_id=%d" % other_project, r4_token)
  2850. check(all(t["title"].startswith("Diff") for t in body["tasks"]),
  2851. "other project lists only its own tasks")
  2852. status, body = saddle_api("GET", "/api/saddle/tasks?q=FLANGE", r4_token)
  2853. titles = [t["title"] for t in body["tasks"]]
  2854. check("Wire the flange" in titles,
  2855. "q matches titles case-insensitively")
  2856. status, body = saddle_api("GET", "/api/saddle/tasks?q=torque%20to%20spec", r4_token)
  2857. check(any(t["title"] == "Wire the flange" for t in body["tasks"]),
  2858. "q matches mandate text")
  2859. status, body = saddle_api("GET", "/api/saddle/task/%d" % auto_child, r4_token)
  2860. task_view = body.get("task", {})
  2861. check(status == 200 and int(task_view.get("id") or 0) == auto_child
  2862. and task_view.get("goal_title") == "Lineage goal"
  2863. and int(task_view.get("goal_id") or 0) == goal,
  2864. "single-task view joins the goal title")
  2865. check("status" in task_view and "description" in task_view
  2866. and "summary" in task_view,
  2867. "single-task view carries the full detail fields")
  2868. check("plan" not in task_view and "parent_task_id" not in task_view,
  2869. "the single-task view drops the deleted parent/plan members")
  2870. status, body = saddle_api("GET", "/api/saddle/task/99999", r4_token)
  2871. check(status == 404, "unknown task id returns 404")
  2872. print("== settle: released workers resume the parked agent (coalesced) ==")
  2873. # Release the held workers: their completions wake the parked goal
  2874. # agent (affinity — the same fake hosts it) with the batched
  2875. # notice; the free worker already completed.
  2876. check(wait_task_done(auth, auto_child, timeout=90) is not None,
  2877. "the free worker settles first")
  2878. def agent_push_count():
  2879. return len([p for p in fake.goal_assignments
  2880. if int(p.get("task", {}).get("id") or 0) == auto_parent])
  2881. before_pushes = agent_push_count()
  2882. for held_task in (auto_grand, flange_task):
  2883. caps = task_state(auth, held_task).get("capabilities") or []
  2884. if caps:
  2885. act(auth, caps[0]["detach"], {})
  2886. check(wait_task_done(auth, held_task, timeout=90) is not None,
  2887. "released worker settles (%d)" % held_task)
  2888. check(wait_for(lambda: agent_push_count() > before_pushes or False,
  2889. timeout=90, what="goal agent resumes") is not None,
  2890. "the workers' completions resume the parked goal agent")
  2891. notice = ""
  2892. for p in fake.goal_assignments:
  2893. if int(p.get("task", {}).get("id") or 0) == auto_parent:
  2894. notice = p.get("resume_notice") or ""
  2895. check("Auto child" in notice and "Auto grandchild" in notice
  2896. and "Wire the flange" in notice,
  2897. "the coalesced resume notice covers every plan task")
  2898. check("New completion reports" in notice and "fake daemon finished" in notice,
  2899. "the notice carries the new completion reports")
  2900. act(auth, goal_state(goal)["cancel"], {})
  2901. check(wait_for(lambda: goal_state(goal)["status"] == "cancelled" or False,
  2902. timeout=30, what="lineage goal cancelled") is not None,
  2903. "the lineage goal cancels (drain)")
  2904. # =============================================================================
  2905. # Bundle: allocation — the ask/wake/allocate machinery: concurrent ask
  2906. # race, token revocation, workspace affinity, the lost-wake guard, the
  2907. # slow-ask regression, assignment capability context + the tag
  2908. # catalogue, and the pinned-blocks/activity dashboard.
  2909. # =============================================================================
  2910. def bundle_allocation(ctx):
  2911. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2912. app = ctx.app
  2913. r4_token = fake_token
  2914. # gpu rides the primary fake from the start (the routing bundle's
  2915. # early attach, replayed): its attach row precedes lostwake's, so
  2916. # the assignment's saddle_tags order matches the assertion in the
  2917. # capability-context section below.
  2918. saddles_state = slot_public(auth, "/saddles", "saddles")
  2919. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2920. act(auth, saddle_card(auth, "fake-saddle")["attach_capability"],
  2921. {"capability_id": str(int([c["id"] for c in
  2922. slot_public(auth, "/saddles", "saddles")["capabilities"]
  2923. if c["name"] == "gpu"][0]))})
  2924. print("== phase 1: ask/allocation — token auth + concurrent race ==")
  2925. # Plan 10 phase 1. Registration mints per-saddle tokens; the
  2926. # ask endpoint authenticates by them; concurrent asks race to
  2927. # exactly one winner through the allocation transaction.
  2928. status, _ = saddle_api("POST", "/api/saddle/next-task", None)
  2929. check(status == 401, "next-task rejects a missing token")
  2930. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-bogus-token")
  2931. check(status == 401, "next-task rejects a wrong token")
  2932. status, body = saddle_api("POST", "/api/saddle/next-task", fake_token)
  2933. check(status == 204, "next-task answers 204 (nothing offerable — daemon sleeps)")
  2934. # Two more racers: real daemons on their own ports; fake2 reports
  2935. # its ssh key at /register so the key lands on the row directly.
  2936. fake2 = FakeSaddle()
  2937. fake2.ssh_public_key = "ssh-ed25519 AAAAFake2RacerKey saddle-2@fedora"
  2938. fake2.serve(port=free_port())
  2939. fake3 = FakeSaddle()
  2940. fake3.serve(port=free_port())
  2941. saddles_state = slot_public(auth, "/saddles", "saddles")
  2942. act(auth, saddles_state["register"], {"name": "racer-two",
  2943. "host": "127.0.0.1:%d" % fake2.port})
  2944. act(auth, saddles_state["register"], {"name": "racer-three",
  2945. "host": "127.0.0.1:%d" % fake3.port})
  2946. check(wait_for(lambda: len(fake2.register_log) > 0 and len(fake3.register_log) > 0
  2947. or False, timeout=15, what="racers registered") is not None,
  2948. "both racers received /register")
  2949. check(wait_for(lambda: "AAAAFake2RacerKey" in
  2950. [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2951. if s["name"] == "racer-two"][0].get("ssh_public_key", "") or False,
  2952. timeout=15, what="register-reported key") is not None,
  2953. "the ssh key reported at /register lands on the saddle row")
  2954. racer_cards = {}
  2955. for name, daemon in (("fake-saddle", fake), ("racer-two", fake2), ("racer-three", fake3)):
  2956. card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2957. if s["name"] == name][0]
  2958. racer_cards[daemon] = {"id": int(card["id"]), "token": card["token"]}
  2959. # Revocation: a registered saddle's token works until the saddle
  2960. # is removed, then nothing authorises its calls.
  2961. fake4 = FakeSaddle()
  2962. fake4.ask_on_register = False # a pre-flip daemon: never asks
  2963. fake4.serve(port=free_port())
  2964. saddles_state = slot_public(auth, "/saddles", "saddles")
  2965. act(auth, saddles_state["register"], {"name": "old-daemon",
  2966. "host": "127.0.0.1:%d" % fake4.port})
  2967. old_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2968. if s["name"] == "old-daemon"][0]
  2969. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  2970. check(status in (200, 204),
  2971. "the old daemon's fresh token authenticates next-task")
  2972. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  2973. {"project": "demo", "body": "from the old daemon"})
  2974. check(status == 200, "note accepts any registered saddle's token")
  2975. act(auth, old_card["unregister"], {})
  2976. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  2977. check(status == 401, "removing the saddle revokes its token")
  2978. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  2979. {"project": "demo", "body": "should fail"})
  2980. check(status == 401, "revocation covers the note endpoint too")
  2981. # Deterministic race: settle the queue first (this shard runs the
  2982. # race before any parked work exists, so only in-flight asks need
  2983. # draining), freeze every daemon's self-ask triggers, put all three
  2984. # to sleep (204), then fire one task worth of concurrent asks.
  2985. for daemon in (fake, fake2, fake3):
  2986. daemon.ask_on_register = False
  2987. daemon.ask_on_wake = False
  2988. daemon.ask_on_terminal = False
  2989. daemon.ask_on_idle_status = False
  2990. daemon.settle_asks() # converted sleep: in-flight asks land (204)
  2991. def queued_count():
  2992. conn = db()
  2993. try:
  2994. return conn.execute(
  2995. "select count(*) from tasks where status = 'queued'").fetchone()[0]
  2996. finally:
  2997. conn.close()
  2998. check(wait_for(lambda: queued_count() == 0 or False,
  2999. timeout=60, what="queue settles before the race") is not None,
  3000. "the queue settles before the race")
  3001. sleep_statuses = [daemon.ask_now()[0] for daemon in (fake, fake2, fake3)]
  3002. check(sleep_statuses == [204, 204, 204],
  3003. "all three racers sleep (204) before the task exists")
  3004. task_id_tmp = create_queued(auth, {
  3005. "project_id": "1",
  3006. "title": "Race task",
  3007. "priority": "2",
  3008. })
  3009. race_task = task_id_tmp
  3010. race_results = []
  3011. def race_ask(daemon):
  3012. # A real racing daemon accepts the assignment it wins — the
  3013. # manual ask path does exactly that on a 200.
  3014. race_results.append(daemon.ask_now())
  3015. threads = [threading.Thread(target=race_ask, args=(daemon,))
  3016. for daemon in (fake, fake2, fake3)]
  3017. for thread in threads:
  3018. thread.start()
  3019. for thread in threads:
  3020. thread.join()
  3021. race_statuses = sorted(r[0] for r in race_results)
  3022. check(race_statuses == [200, 204, 204],
  3023. "concurrent asks race to exactly one winner (%s)" % race_statuses)
  3024. winner = [r for r in race_results if r[0] == 200][0][1]
  3025. check(int(winner["task"]["id"]) == race_task, "the winner's payload carries the task")
  3026. check(int(winner["session_id"]) > 0, "the assignment carries the session id")
  3027. conn = db()
  3028. race_sessions = conn.execute(
  3029. "select count(*) from sessions where task_id = ?", (race_task,)).fetchone()[0]
  3030. conn.close()
  3031. check(race_sessions == 1,
  3032. "exactly one session row — the transaction serialised the claims (%d)"
  3033. % race_sessions)
  3034. check(wait_task_done(auth, race_task, timeout=60) is not None,
  3035. "the raced task completes on the winning daemon")
  3036. for daemon in (fake, fake2, fake3):
  3037. daemon.ask_on_register = True
  3038. daemon.ask_on_wake = True
  3039. daemon.ask_on_terminal = True
  3040. daemon.ask_on_idle_status = True
  3041. # Re-establish sleeping explicitly: the winner's post-race
  3042. # re-ask timing is not deterministic, and the affinity section
  3043. # below needs every racer provably asleep. Any stray offerable
  3044. # drains into these asks first.
  3045. def all_asleep():
  3046. return all(daemon.ask_now()[0] == 204 for daemon in (fake, fake2, fake3))
  3047. check(wait_for(lambda: all_asleep() or False, timeout=30,
  3048. what="racers re-sleep after the race") is not None,
  3049. "all racers re-sleep after the race")
  3050. print("== phase 1: workspace affinity pins parked tasks ==")
  3051. # A suspended parent parked on racer-two may be resumed ONLY by
  3052. # racer-two: a tag-capable non-affine saddle asking gets 204, and
  3053. # the wake targets the affine saddle. Only racer-two carries the
  3054. # tag at dispatch time (the race's winner is nondeterministic, so
  3055. # the park must not depend on which racers are free); racer-three
  3056. # gains it afterwards to prove the pinning is by workspace, not
  3057. # tags.
  3058. saddles_state = slot_public(auth, "/saddles", "saddles")
  3059. act(auth, saddles_state["create_capability"], {"name": "affinity-tag"})
  3060. affinity_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3061. if c["name"] == "affinity-tag"][0])
  3062. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3063. if s["name"] == "racer-two"][0]
  3064. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3065. if s["name"] == "racer-three"][0]
  3066. act(auth, racer2_card["attach_capability"], {"capability_id": str(affinity_cap)})
  3067. # Plan 12: the parked workspace is the goal agent's run task. The
  3068. # other racers sleep (frozen ask triggers), so racer-two claims
  3069. # the goal run and parks it; the goal-task event then resumes the
  3070. # agent AFFINE to racer-two — racer-three (tag-capable or not)
  3071. # gets 204, the dispatcher's wake targets racer-two.
  3072. fake.ask_on_wake = False
  3073. fake.ask_on_idle_status = False
  3074. fake.settle_asks()
  3075. fake3.ask_on_wake = False
  3076. fake3.ask_on_idle_status = False
  3077. fake3.settle_asks()
  3078. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  3079. "project_id": "1", "title": "Affinity goal",
  3080. "brief": "Parks on racer-two.", "branch_name": "goal/affinity"})
  3081. conn = db()
  3082. affinity_goal = conn.execute(
  3083. "select id from goals where title = 'Affinity goal'").fetchone()[0]
  3084. conn.close()
  3085. fake2.goal_script = [("plan", "# Affinity plan\n\n1. Park")]
  3086. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")["start"], {})
  3087. check(wait_for(lambda: slot_public(auth, "/goals/%d" % affinity_goal,
  3088. "goal")["status"] == "plan_review" or False,
  3089. timeout=60, what="affinity goal plans") is not None,
  3090. "the affinity goal reaches plan review (racer-two hosting)")
  3091. fake2.goal_script = [("suspend",)]
  3092. # Freeze racer-two's ask triggers across the approval too (the
  3093. # later wake measurement already does): the mirror-sync fix makes
  3094. # the run resume-offerable the moment its goal row carries the
  3095. # verdict, so a wake-triggered background ask would race this
  3096. # manual ask_now for the claim.
  3097. fake2.ask_on_wake = False
  3098. fake2.ask_on_idle_status = False
  3099. fake2.settle_asks()
  3100. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")
  3101. ["plan_pending_block"]["answer_action"],
  3102. {"answer": "Plan approved. Proceed with implementation."})
  3103. conn = db()
  3104. affinity_parent = conn.execute(
  3105. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  3106. (affinity_goal,)).fetchone()[0]
  3107. agent_session = conn.execute(
  3108. "select id from sessions where task_id = ? and ended_at is null",
  3109. (affinity_parent,)).fetchone()[0]
  3110. conn.close()
  3111. status, resume_payload = fake2.ask_now()
  3112. check(status == 200 and int(resume_payload["task"]["id"]) == affinity_parent,
  3113. "the approved plan resumes the agent on racer-two (its workspace)")
  3114. check(wait_for(lambda: task_state(auth, affinity_parent).get("status") == "suspended"
  3115. or False, timeout=60, what="affinity agent parks") is not None,
  3116. "the affinity goal agent parks on racer-two")
  3117. conn = db()
  3118. affinity_session = conn.execute(
  3119. "select saddle_id from sessions where task_id = ? and ended_at is null",
  3120. (affinity_parent,)).fetchone()[0]
  3121. conn.close()
  3122. check(affinity_session == int(racer2_card["id"]),
  3123. "the parked workspace sits on racer-two")
  3124. # Now racer-three carries the tag too — the pinning is by
  3125. # workspace, not tags. With nothing due, a non-affine ask gets 204.
  3126. act(auth, racer3_card["attach_capability"], {"capability_id": str(affinity_cap)})
  3127. status, _ = fake3.ask_now()
  3128. check(status == 204,
  3129. "a tag-capable non-affine saddle is refused the parked agent (204)")
  3130. # A goal task completing makes the parked agent resume-offerable —
  3131. # affine to racer-two only. The other racers wake back up (they
  3132. # host the worker; their claims of the parked agent get refused as
  3133. # non-affine), while racer-two's ask triggers stay frozen so the
  3134. # wake measurement stays clean. A wake may have hit the frozen
  3135. # racers while the goal run queued (the lost-wake guard marks them
  3136. # offline): the refresh probe brings them back before the worker.
  3137. fake.ask_on_wake = True
  3138. fake.ask_on_idle_status = True
  3139. fake3.ask_on_wake = True
  3140. fake3.ask_on_idle_status = True
  3141. for racer_name in ("fake-saddle", "racer-three"):
  3142. act(auth, saddle_card(auth, racer_name)["refresh"], {})
  3143. check(wait_for(lambda name=racer_name: [s for s in
  3144. slot_public(auth, "/saddles", "saddles")["saddles"]
  3145. if s["name"] == name][0]["status"] == "idle"
  3146. or False, timeout=15, what="racer re-onlined") is not None,
  3147. "%s re-onlined after its frozen-window wake" % racer_name)
  3148. fake2.ask_on_wake = False
  3149. fake2.ask_on_idle_status = False
  3150. wakes_before_2 = len(fake2.wake_log)
  3151. fake2.settle_asks() # converted sleep: park-time ask lands (204)
  3152. status, body = saddle_api("POST", "/api/saddle/task/create", fake2.token, {
  3153. "session_id": agent_session, "title": "Affinity child",
  3154. "mandate": "finish the affinity fixture"})
  3155. check(status == 200, "the parked agent fans its worker out via the CLI")
  3156. affinity_child = int(body["task_id"])
  3157. saddle_api("POST", "/api/saddle/task/enqueue", fake2.token,
  3158. {"session_id": agent_session, "task_id": affinity_child})
  3159. check(wait_task_done(auth, affinity_child, timeout=90) is not None,
  3160. "the affinity worker completes (on a non-affine racer)")
  3161. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_2 or False,
  3162. timeout=30, what="affine wake") is not None,
  3163. "the dispatcher's wake targets the affine saddle")
  3164. status, resume_payload = fake2.ask_now()
  3165. fake2.ask_on_wake = True # restored whatever the claim returned
  3166. fake2.ask_on_idle_status = True
  3167. check(status == 200 and int(resume_payload["task"]["id"]) == affinity_parent,
  3168. "the affine saddle's ask claims the parked agent")
  3169. check("Affinity child" in (resume_payload.get("resume_notice") or "")
  3170. and "fake daemon finished" in (resume_payload.get("resume_notice") or ""),
  3171. "the resume assignment carries the goal's batched report notice")
  3172. check(wait_for(lambda: task_state(auth, affinity_parent).get("status")
  3173. == "suspended" or False,
  3174. timeout=60, what="affinity agent re-parks") is not None,
  3175. "the resumed agent re-parks (script)")
  3176. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")["cancel"], {})
  3177. check(wait_for(lambda: slot_public(auth, "/goals/%d" % affinity_goal,
  3178. "goal")["status"] == "cancelled" or False,
  3179. timeout=30, what="affinity goal cancelled") is not None,
  3180. "the affinity goal cancels (drain)")
  3181. print("== phase 1: lost wake -> offline + re-wake of the next capable ==")
  3182. # racer-three sleeps through wakes (a daemon that died after its
  3183. # last 204): the guard window (SADDLE_LOST_WAKE_S=2) passes with
  3184. # no ask, the saddle goes offline, and the work moves to the
  3185. # next capable sleeping saddle.
  3186. fake3.ask_on_wake = False
  3187. fake3.ask_on_idle_status = False # sleeps through everything
  3188. saddles_state = slot_public(auth, "/saddles", "saddles")
  3189. act(auth, saddles_state["create_capability"], {"name": "lostwake"})
  3190. lostwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3191. if c["name"] == "lostwake"][0])
  3192. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3193. if s["name"] == "racer-three"][0]
  3194. act(auth, racer3_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  3195. # Racer-three must be asleep to be woken: park it with a manual
  3196. # 204 ask (nothing offerable for it — the task below is not
  3197. # created yet).
  3198. status, _ = fake3.ask_now()
  3199. check(status == 204, "racer-three sleeps before the lost-wake run")
  3200. task_id_tmp = create_queued(auth, {
  3201. "project_id": "1",
  3202. "title": "Lost wake task",
  3203. "priority": "2",
  3204. "capability_id": [str(lostwake_cap)],
  3205. })
  3206. lost_task = task_id_tmp
  3207. check(wait_for(lambda: len(fake3.wake_log) > 0 or False,
  3208. timeout=30, what="wake sent to racer-three") is not None,
  3209. "the only capable sleeping saddle is woken")
  3210. check(wait_for(lambda: [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3211. if s["name"] == "racer-three"][0]["status"] == "offline"
  3212. or False, timeout=30, what="lost-wake -> offline") is not None,
  3213. "no ask after the wake: the saddle goes offline (lost-wake guard)")
  3214. check(task_state(auth, lost_task)["status"] == "queued",
  3215. "the task is untouched while its wake was pending")
  3216. # Re-wake the next capable: the healthy saddle gains the tag and
  3217. # picks the work up via its own wake -> ask -> allocate roundtrip.
  3218. fake_card = saddle_card(auth, "fake-saddle")
  3219. act(auth, fake_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  3220. wakes_before = len(fake.wake_log)
  3221. check(wait_for(lambda: len(fake.wake_log) > wakes_before or False,
  3222. timeout=30, what="re-wake of the next capable") is not None,
  3223. "the next capable sleeping saddle is woken for the task")
  3224. check(wait_task_done(auth, lost_task, timeout=60) is not None,
  3225. "wake -> ask -> allocate: the task completes on the healthy saddle")
  3226. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == lost_task
  3227. for p in fake.start_payloads) or False,
  3228. timeout=10, what="lost task assignment captured") is not None,
  3229. "the re-woken saddle's ask produced the assignment")
  3230. fake3.ask_on_wake = True
  3231. fake3.ask_on_idle_status = True
  3232. print("== phase 3: capability context, catalogue, subtask tags ==")
  3233. # Assignment capability context (plan 10 phase 3): every
  3234. # assignment carries {saddle_tags: the allocated saddle's tags,
  3235. # fleet_tags: every tag name known across the fleet} — the
  3236. # daemon renders it into its system prompt. fake-saddle carries
  3237. # gpu + lostwake; the catalogue is affinity-tag, gpu, lostwake.
  3238. fake2.ask_on_register = False
  3239. fake2.ask_on_wake = False
  3240. fake2.ask_on_terminal = False
  3241. fake2.ask_on_idle_status = False
  3242. fake2.settle_asks() # converted sleep: in-flight trigger asks land
  3243. task_id_tmp = create_queued(auth, {
  3244. "project_id": "1",
  3245. "title": "Capabilities context",
  3246. "priority": "2",
  3247. })
  3248. cap_task = task_id_tmp
  3249. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == cap_task
  3250. for p in fake.start_payloads) or False,
  3251. timeout=60, what="capabilities-context task dispatched") is not None,
  3252. "the capabilities-context task dispatches")
  3253. cap_payload = [p for p in fake.start_payloads
  3254. if int(p.get("task", {}).get("id") or 0) == cap_task][-1]
  3255. context = cap_payload.get("capabilities") or {}
  3256. check(context.get("saddle_tags") == ["gpu", "lostwake"],
  3257. "assignment saddle_tags = the allocated saddle's tags (%s)"
  3258. % context.get("saddle_tags"))
  3259. check(context.get("fleet_tags") == ["affinity-tag", "gpu", "lostwake"],
  3260. "assignment fleet_tags = every tag name known across the fleet (%s)"
  3261. % context.get("fleet_tags"))
  3262. check(wait_task_done(auth, cap_task, timeout=60) is not None,
  3263. "capabilities-context task completes")
  3264. # GET /api/saddle/capabilities feeds the daemon's `saddle
  3265. # capabilities` CLI: per-saddle-token auth, tag order by name,
  3266. # each tag with the saddles carrying it (name order).
  3267. status, _ = saddle_api("GET", "/api/saddle/capabilities", None)
  3268. check(status == 401, "capabilities endpoint rejects a missing token")
  3269. status, body = saddle_api("GET", "/api/saddle/capabilities", "saddle-bogus")
  3270. check(status == 401, "capabilities endpoint rejects a wrong token")
  3271. status, body = saddle_api("GET", "/api/saddle/capabilities", fake_token)
  3272. catalogue = {t["name"]: t["saddles"] for t in body.get("tags", [])}
  3273. check(status == 200 and body.get("ok") is True
  3274. and [t["name"] for t in body.get("tags", [])]
  3275. == ["affinity-tag", "gpu", "lostwake"],
  3276. "catalogue lists every tag by name")
  3277. check(catalogue.get("gpu") == ["fake-saddle"]
  3278. and catalogue.get("affinity-tag") == ["racer-three", "racer-two"]
  3279. and catalogue.get("lostwake") == ["fake-saddle", "racer-three"],
  3280. "each tag names its carrying saddles in name order (%s)" % catalogue)
  3281. # Task CLI capabilities (`task create --capability`): validated
  3282. # against the operator tag set; unknown tags reject with the valid
  3283. # list in the error (the agent reads it verbatim in the CLI
  3284. # output). A goal agent's parked session hosts the calls.
  3285. fake.suspend_on_title = "Tag host"
  3286. tag_host = create_queued(auth, {
  3287. "project_id": "1", "title": "Tag host", "priority": "3"})
  3288. check(wait_for(lambda: task_state(auth, tag_host)["status"] == "suspended"
  3289. or False, timeout=60, what="tag host parks") is not None,
  3290. "a parked plain task hosts nothing (no goal scope)")
  3291. # The goal callbacks need a real goal agent: reuse the sequencing
  3292. # goal pattern — a fresh parked agent under this shard.
  3293. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  3294. "project_id": "1", "title": "Tag goal", "brief": "b",
  3295. "branch_name": "goal/tags"})
  3296. conn = db()
  3297. tag_goal = conn.execute("select id from goals where title = 'Tag goal'").fetchone()[0]
  3298. conn.close()
  3299. fake.goal_script = [("suspend",)]
  3300. act(auth, slot_public(auth, "/goals/%d" % tag_goal, "goal")["start"], {})
  3301. conn = db()
  3302. tag_run = conn.execute(
  3303. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  3304. (tag_goal,)).fetchone()[0]
  3305. conn.close()
  3306. check(wait_for(lambda: task_state(auth, tag_run)["status"] == "suspended"
  3307. or False, timeout=60, what="tag goal agent parks") is not None,
  3308. "the tag goal agent parks")
  3309. conn = db()
  3310. tag_session = conn.execute(
  3311. "select id from sessions where task_id = ? and ended_at is null",
  3312. (tag_run,)).fetchone()[0]
  3313. conn.close()
  3314. conn = db()
  3315. tag_host_saddle = conn.execute(
  3316. "select saddle_id from sessions where id = ?", (tag_session,)).fetchone()[0]
  3317. conn.close()
  3318. racer2_card_id = int([c for c in slot_public(auth, "/saddles", "saddles")["saddles"]
  3319. if c["name"] == "racer-two"][0]["id"])
  3320. racer3_card_id = int([c for c in slot_public(auth, "/saddles", "saddles")["saddles"]
  3321. if c["name"] == "racer-three"][0]["id"])
  3322. host_daemon = {int(fake_id): fake, racer2_card_id: fake2,
  3323. racer3_card_id: fake3}[int(tag_host_saddle)]
  3324. status, body = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3325. "session_id": tag_session, "title": "Bad tag worker",
  3326. "mandate": "m", "capabilities": ["gpu", "warp-drive"]})
  3327. check(status == 400, "an unknown capability tag rejects the task call")
  3328. error_text = body.get("error", "")
  3329. check("warp-drive" in error_text and "valid tags" in error_text
  3330. and "gpu" in error_text and "lostwake" in error_text,
  3331. "the rejection names the unknown tag and the valid list (%s)" % error_text)
  3332. status, _ = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3333. "session_id": tag_session, "title": "Bad shape worker",
  3334. "mandate": "m", "capabilities": "gpu"})
  3335. check(status == 400, "a non-array capabilities member rejects")
  3336. # A valid tag creates the goal worker in draft with exactly the
  3337. # explicit tag attached; the goal agent enqueues it.
  3338. status, body = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3339. "session_id": tag_session, "title": "Explicit tag worker",
  3340. "mandate": "do the tagged work", "capabilities": ["gpu"]})
  3341. check(status == 200 and body.get("ok") is True,
  3342. "a valid tag creates the task synchronously")
  3343. tagged_worker = int(body["task_id"])
  3344. detail = task_state(auth, tagged_worker)
  3345. check([c["name"] for c in detail.get("capabilities", [])] == ["gpu"],
  3346. "the worker carries exactly the explicit tag")
  3347. conn = db()
  3348. tag_rows = conn.execute(
  3349. "select c.name from task_capabilities tc"
  3350. " join capabilities c on c.id = tc.capability_id"
  3351. " where tc.task_id = ?", (tagged_worker,)).fetchall()
  3352. conn.close()
  3353. check([r[0] for r in tag_rows] == ["gpu"],
  3354. "the task_capabilities rows record the explicit tag")
  3355. check(detail["status"] == "draft",
  3356. "the callback's task lands in draft until its agent enqueues")
  3357. saddle_api("POST", "/api/saddle/task/enqueue", host_daemon.token,
  3358. {"session_id": tag_session, "task_id": tagged_worker})
  3359. check(wait_task_done(auth, tagged_worker, timeout=90) is not None,
  3360. "the tagged worker dispatches and completes")
  3361. act(auth, slot_public(auth, "/goals/%d" % tag_goal, "goal")["cancel"], {})
  3362. act(auth, task_state(auth, tag_host)["cancel"], {})
  3363. print("== phase 3: dashboard — pinned blocks + activity timeline ==")
  3364. # Pinned OPEN blocking items as link-through cards, newest
  3365. # first; no inline answer forms (the card links to the task
  3366. # page). Fixture: one open question + one open review raised on a
  3367. # local task (stand-ins for the auto-approve grandchild's
  3368. # leftovers) join the probe RFC raised below.
  3369. conn = db()
  3370. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  3371. " values (1, 'Dash fixture task', 'working', 5, strftime('%s','now'))")
  3372. dash_task = conn.execute("select max(id) from tasks").fetchone()[0]
  3373. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  3374. " values (?, ?, strftime('%s','now'))", (dash_task, fake_id))
  3375. dash_session = conn.execute("select max(id) from sessions").fetchone()[0]
  3376. conn.commit()
  3377. conn.close()
  3378. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3379. {"type": "block", "session_id": dash_session, "data": {
  3380. "question": "Dash fixture question?", "type": "question"}})
  3381. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3382. {"type": "review", "session_id": dash_session, "data": {
  3383. "summary": "dash fixture review"}})
  3384. # The activity timeline: last <= 50 events, newest first, fed
  3385. # from the existing tables. Fixture rows a few seconds old
  3386. # guarantee the progress kind and a human-authored comment ride
  3387. # along; the probe block below proves same-source ordering.
  3388. conn = db()
  3389. conn.execute("insert into task_comments (task_id, author, body, created_at)"
  3390. " values (?, 'user:admin', 'timeline fixture comment by a human',"
  3391. " strftime('%s','now','-5 seconds'))", (cap_task,))
  3392. conn.execute("insert into task_progress (task_id, summary, created_at)"
  3393. " values (?, 'timeline fixture progress',"
  3394. " strftime('%s','now','-5 seconds'))",
  3395. (cap_task,))
  3396. conn.commit()
  3397. conn.close()
  3398. # The probe RFC raised last: the newest pinned card and the newest
  3399. # timeline event (its raise+answer below prove same-source ordering
  3400. # both ways). The timeline sorts same-second events by source
  3401. # materialisation order, so the probe must land in a LATER clock
  3402. # second than the fixtures — wait for the boundary (bounded).
  3403. fixtures_epoch = int(time.time())
  3404. wait_for(lambda: int(time.time()) > fixtures_epoch or False,
  3405. timeout=3, what="next clock second before the probe raise")
  3406. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3407. {"type": "block", "session_id": dash_session, "data": {
  3408. "question": "Timeline probe: approve the dashboard flow",
  3409. "type": "rfc", "body": "# Probe"}})
  3410. dash = slot_public(auth, "/", "dashboard")
  3411. pinned = dash.get("pinned", [])
  3412. pinned_ids = [int(b["id"]) for b in pinned]
  3413. check(len(pinned_ids) >= 3 and pinned_ids == sorted(pinned_ids, reverse=True),
  3414. "pinned open blocks order newest-first (%s)" % pinned_ids)
  3415. check({b["block_type"] for b in pinned} >= {"question", "rfc", "review"},
  3416. "pinned cards cover questions, RFCs and reviews")
  3417. check(all(b["question"] and b["task_title"] and int(b["task_id"]) > 0
  3418. for b in pinned)
  3419. and all("answer_action" not in b for b in pinned),
  3420. "pinned cards are link-through only (task title, kind badge, question)")
  3421. activity = dash.get("activity", [])
  3422. epochs = [int(e["at_epoch"]) for e in activity]
  3423. check(0 < len(activity) <= 50 and epochs == sorted(epochs, reverse=True),
  3424. "the timeline shows the last <=50 events newest-first (%d events)"
  3425. % len(activity))
  3426. kinds = {e["kind"] for e in activity}
  3427. check({"created", "started", "dispatch", "comment", "progress", "completed"} <= kinds,
  3428. "the timeline covers status changes, dispatches, comments, progress and"
  3429. " completions (%s)" % sorted(kinds))
  3430. check(any(e["kind"] == "comment" and e["text"].startswith("user:admin:")
  3431. and "fixture comment" in e["text"] for e in activity),
  3432. "comment events carry author + snippet")
  3433. # The freshly raised probe pinned as the newest card and landed
  3434. # atop the timeline as block-raised; answering it records
  3435. # block-answered.
  3436. check(dash["pinned"][0]["question"] == "Timeline probe: approve the dashboard flow"
  3437. and int(dash["pinned"][0]["task_id"]) == dash_task,
  3438. "the freshest open block pins as the first card")
  3439. check(dash["activity"][0]["kind"] == "block-raised"
  3440. and "Timeline probe" in dash["activity"][0]["text"],
  3441. "the raised block lands atop the timeline")
  3442. probe_block = [b for b in task_state(auth, dash_task)["blocks"]
  3443. if b["question"] == "Timeline probe: approve the dashboard flow"][0]
  3444. act(auth, probe_block["answer_action"], {"answer": "Ship the dashboard"})
  3445. dash = slot_public(auth, "/", "dashboard")
  3446. activity = dash.get("activity", [])
  3447. raised_at = next((i for i, e in enumerate(activity)
  3448. if e["kind"] == "block-raised" and "Timeline probe" in e["text"]), -1)
  3449. answered_at = next((i for i, e in enumerate(activity)
  3450. if e["kind"] == "block-answered"
  3451. and "Ship the dashboard" in e["text"]), -1)
  3452. check(answered_at >= 0 and raised_at >= 0 and answered_at < raised_at,
  3453. "the answered event sorts above its raised event (newest-first, same source)")
  3454. check(all(b["question"] != "Timeline probe: approve the dashboard flow"
  3455. for b in dash["pinned"]),
  3456. "the answered block leaves the pinned cards")
  3457. print("== phase 3 regression: a slow ask after a wake is never dropped ==")
  3458. # The daemon worker's lost-wake-guard regression: a saddle whose
  3459. # ask arrives SLOWLY after the wake (busy winding down when the
  3460. # wake lands) must not lose the wake — the delayed ask (inside
  3461. # the guard window) claims the task, no re-wake storm fires
  3462. # while it is pending, and the saddle stays healthy. The
  3463. # never-asks path (guard -> offline + re-wake of the next
  3464. # capable) is proven by the racer-three section above.
  3465. check(wait_for(lambda: queued_count() == 0 or False,
  3466. timeout=60, what="queue settles before the slow-wake run") is not None,
  3467. "the queue settles before the slow-wake run")
  3468. status, _ = fake2.ask_now()
  3469. check(status == 204, "the slow-ask racer sleeps before its wake")
  3470. saddles_state = slot_public(auth, "/saddles", "saddles")
  3471. act(auth, saddles_state["create_capability"], {"name": "slowwake"})
  3472. slowwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")
  3473. ["capabilities"] if c["name"] == "slowwake"][0])
  3474. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3475. if s["name"] == "racer-two"][0]
  3476. act(auth, racer2_card["attach_capability"], {"capability_id": str(slowwake_cap)})
  3477. fake2.ask_delay = 1.2 # slow: asks well after the wake, inside the 2s guard
  3478. fake2.ask_on_wake = True
  3479. wakes_before_slow = len(fake2.wake_log)
  3480. task_id_tmp = create_queued(auth, {
  3481. "project_id": "1",
  3482. "title": "Slow wake task",
  3483. "priority": "2",
  3484. "capability_id": [str(slowwake_cap)],
  3485. })
  3486. slow_task = task_id_tmp
  3487. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_slow or False,
  3488. timeout=30, what="the slow-ask racer woken") is not None,
  3489. "the only capable sleeping saddle is woken")
  3490. check(wait_task_done(auth, slow_task, timeout=120) is not None,
  3491. "the delayed ask claims the task — the wake was not dropped")
  3492. check(any(a.get("status") == 200
  3493. and int((a.get("payload") or {}).get("task", {}).get("id") or 0)
  3494. == slow_task for a in fake2.asks),
  3495. "the slow ask's 200 carries the task")
  3496. check(len(fake2.wake_log) == wakes_before_slow + 1,
  3497. "the pending-wake skip re-wakes nobody while the slow ask is in flight")
  3498. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3499. if s["name"] == "racer-two"][0]
  3500. check(racer2_card["status"] in ("idle", "busy"),
  3501. "the slow asker never went offline (guard did not fire)")
  3502. fake2.ask_delay = 0.0
  3503. fake2.ask_on_wake = False # stays out of the pool below
  3504. # =============================================================================
  3505. # Bundle: lifecycle — offline requeues, the hung-request tick survival,
  3506. # parked-refresh bookkeeping, cancellation, the health panel, raw-log
  3507. # losslessness, git identity and the live blocked-push roundtrip.
  3508. # =============================================================================
  3509. def bundle_lifecycle(ctx):
  3510. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  3511. app = ctx.app
  3512. print("== plan 11: draft state machine, edit matrix, enqueue/delete guards ==")
  3513. # New tasks default to draft; Enqueue is the only path to the
  3514. # queue (there is no agent path — the ingest API refuses to queue).
  3515. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3516. "project_id": "1",
  3517. "title": "Draft lifecycle task",
  3518. "priority": "4",
  3519. })
  3520. draft_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3521. if t["title"] == "Draft lifecycle task"][0])
  3522. detail = task_state(auth, draft_task)
  3523. check(detail["status"] == "draft", "a created task lands in draft")
  3524. check(detail.get("enqueue") is not None and detail.get("delete") is not None,
  3525. "draft exposes the enqueue + delete actions")
  3526. check(detail.get("cancel") is not None, "the cancel action stays authored")
  3527. status, page = http("GET", "/tasks/%d" % draft_task, timeout=15)
  3528. check(status == 200 and "Enqueue task" in page and ">Delete<" in page,
  3529. "the task page shows Enqueue + Delete in draft")
  3530. check("Mark done" not in page,
  3531. "the user Mark-complete action is gone (agent-only completion)")
  3532. # Plan 12: the auto-enqueue-after predecessor REPLACES draft
  3533. # dependencies — setting it is allowed while the predecessor is
  3534. # still pending (the enqueue itself succeeds; the DISPATCHER holds
  3535. # dispatch back until the predecessor is done).
  3536. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3537. "project_id": "1",
  3538. "title": "Draft dependency",
  3539. "priority": "4",
  3540. })
  3541. draft_dep = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3542. if t["title"] == "Draft dependency"][0])
  3543. act(auth, detail["update"], {"enqueue_after_task_id": str(draft_dep)})
  3544. check(int(task_state(auth, draft_task).get("enqueue_after_task_id") or 0)
  3545. == draft_dep,
  3546. "the draft edit sets the auto-enqueue predecessor")
  3547. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3548. "project_id": "1", "title": "Eager dependent", "priority": "4",
  3549. "enqueue_after_task_id": str(draft_dep)})
  3550. eager = task_id_of("Eager dependent")
  3551. enqueue_task(auth, eager)
  3552. check(task_state(auth, eager)["status"] == "queued",
  3553. "enqueue succeeds while the predecessor is pending (no draft guard)")
  3554. check(quiet_window(quiet_seconds(),
  3555. lambda: task_state(auth, eager)["status"] == "queued",
  3556. "pending predecessor holds dispatch"),
  3557. "the pending predecessor holds dispatch back (never assigned)")
  3558. # The edit matrix starts in DRAFT: every field except status.
  3559. act(auth, detail["update"], {
  3560. "title": "Draft lifecycle task (edited)",
  3561. "description": "Now with a description",
  3562. "priority": "2",
  3563. "task_branch": "feature/draft",
  3564. "branch_from": "main",
  3565. "mode": "investigate",
  3566. })
  3567. detail = task_state(auth, draft_task)
  3568. check(detail["title"] == "Draft lifecycle task (edited)"
  3569. and detail["description"] == "Now with a description"
  3570. and detail["priority"] == 2
  3571. and detail["task_branch"] == "feature/draft"
  3572. and detail["branch_from"] == "main"
  3573. and detail["mode"] == "investigate",
  3574. "draft edits apply to every field (incl. the mode)")
  3575. # Clear the predecessor (the empty sentinel): dispatch gates on
  3576. # the hold tag alone now.
  3577. act(auth, detail["update"], {"enqueue_after_task_id": "0"})
  3578. check(not int(task_state(auth, draft_task).get("enqueue_after_task_id") or 0),
  3579. "the draft edit clears the auto-enqueue predecessor")
  3580. # A hold tag nothing carries keeps the dependent QUEUED (never
  3581. # dispatched) through the remaining edit-matrix checks.
  3582. saddles_state = slot_public(auth, "/saddles", "saddles")
  3583. act(auth, saddles_state["create_capability"], {"name": "holdlock"})
  3584. holdlock_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3585. if c["name"] == "holdlock"][0])
  3586. act(auth, detail["attach_capability"], {"capability_id": str(holdlock_cap)})
  3587. # Enqueue the now-cleared dependent: the hold tag keeps it queued
  3588. # (never dispatched), so the non-draft edit matrix applies.
  3589. enqueue_task(auth, draft_task)
  3590. check(quiet_window(3, lambda: task_state(auth, draft_task)["status"] == "queued",
  3591. "held dependent stays queued"),
  3592. "the held dependent stays queued (never dispatched)")
  3593. # The predecessor settles for the shard drain.
  3594. enqueue_task(auth, draft_dep)
  3595. check(wait_task_done(auth, draft_dep, timeout=90) is not None,
  3596. "the predecessor settles")
  3597. # Drafts are never dispatched even with an idle saddle available.
  3598. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3599. "project_id": "1",
  3600. "title": "Never-dispatched draft",
  3601. "priority": "1",
  3602. })
  3603. silent_draft = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3604. if t["title"] == "Never-dispatched draft"][0])
  3605. check(quiet_window(quiet_seconds(),
  3606. lambda: task_state(auth, silent_draft)["status"] == "draft",
  3607. "draft never dispatched"),
  3608. "an idle saddle never picks a draft up (no agent enqueue path)")
  3609. # Once work can begin (queued here), only priority is editable.
  3610. act(auth, detail["update"], {
  3611. "title": "Should not apply",
  3612. "priority": "3",
  3613. })
  3614. detail = task_state(auth, draft_task)
  3615. check(detail["title"] == "Draft lifecycle task (edited)" and detail["priority"] == 3,
  3616. "non-draft edits apply priority only (title locked)")
  3617. # A terminal task edits nothing.
  3618. conn = db()
  3619. conn.execute("update tasks set status = 'done', completed_at = strftime('%s','now')"
  3620. " where id = ?", (draft_task,))
  3621. conn.commit()
  3622. conn.close()
  3623. act(auth, task_state(auth, draft_task)["update"], {"priority": "8"})
  3624. check(task_state(auth, draft_task)["priority"] == 3,
  3625. "terminal tasks edit nothing (priority locked)")
  3626. # Capabilities lock once a worker has the job: editable while
  3627. # queued, locked once working.
  3628. act(auth, saddles_state["create_capability"], {"name": "editlock"})
  3629. editlock_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")
  3630. ["capabilities"] if c["name"] == "editlock"][0])
  3631. act(auth, saddle_card(auth, "fake-saddle")["attach_capability"],
  3632. {"capability_id": str(editlock_cap)})
  3633. locked_task = create_queued(auth, {"project_id": "1", "title": "Caplock task",
  3634. "priority": "2"})
  3635. detail = task_state(auth, locked_task)
  3636. act(auth, detail["attach_capability"], {"capability_id": str(editlock_cap)})
  3637. check(any(c["name"] == "editlock"
  3638. for c in task_state(auth, locked_task)["capabilities"]),
  3639. "capabilities attach while queued (no worker yet)")
  3640. check(wait_for(lambda: task_state(auth, locked_task).get("status") == "working"
  3641. or False, timeout=60, what="caplock working") is not None,
  3642. "the caplock task reaches working")
  3643. detach_directives = act(auth, task_state(auth, locked_task)["capabilities"][0]["detach"], {})
  3644. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  3645. for d in detach_directives),
  3646. "capabilities are locked once a worker has the job")
  3647. # The ingest API has no queue transition either (only working and
  3648. # blocked are accepted states).
  3649. conn = db()
  3650. caplock_session = conn.execute(
  3651. "select id from sessions where task_id = ? and ended_at is null",
  3652. (locked_task,)).fetchone()
  3653. conn.close()
  3654. if caplock_session is not None:
  3655. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  3656. {"type": "status", "session_id": caplock_session[0],
  3657. "data": {"state": "queued"}})
  3658. check(status == 200
  3659. and task_state(auth, locked_task)["status"] in ("working", "done"),
  3660. "the ingest API's status push never queues a task")
  3661. # Delete guards: a clean draft deletes; non-draft refuses; a draft
  3662. # with dependents is refused naming them.
  3663. act(auth, task_state(auth, silent_draft)["delete"], {})
  3664. check(not any(t["id"] == silent_draft
  3665. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  3666. "a clean draft task deletes")
  3667. delete_directives = act(auth, task_state(auth, draft_task)["delete"], {})
  3668. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  3669. for d in delete_directives),
  3670. "a non-draft task refuses the delete")
  3671. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3672. "project_id": "1", "title": "Guarded draft", "priority": "4"})
  3673. guarded = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3674. if t["title"] == "Guarded draft"][0])
  3675. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3676. "project_id": "1", "title": "Dependent namer", "priority": "4"})
  3677. namer = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3678. if t["title"] == "Dependent namer"][0])
  3679. act(auth, task_state(auth, namer)["update"],
  3680. {"enqueue_after_task_id": str(guarded)})
  3681. check(int(task_state(auth, namer).get("enqueue_after_task_id") or 0) == guarded,
  3682. "the namer points at the guarded predecessor")
  3683. act(auth, task_state(auth, guarded)["delete"], {})
  3684. check(not any(t["id"] == guarded
  3685. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  3686. "deleting a predecessor succeeds")
  3687. check(not int(task_state(auth, namer).get("enqueue_after_task_id") or 0),
  3688. "the delete clears the dependent's dangling predecessor reference")
  3689. print("== offline requeues ==")
  3690. # Tasks caught working on a saddle that went offline requeue with a
  3691. # agent comment each tick.
  3692. task_id_tmp = create_queued(auth, {
  3693. "project_id": "1",
  3694. "title": "Offline saddle task",
  3695. "priority": "2",
  3696. })
  3697. offline_task = task_id_tmp
  3698. check(wait_for(lambda: task_state(auth, offline_task).get("status") == "working"
  3699. or False, timeout=60, what="offline task starts working") is not None,
  3700. "task reaches working before its saddle disappears")
  3701. # Hold the daemon mid-round across the requeue window (the
  3702. # original relied on its 8s work period outlasting the 5s tick):
  3703. # the task completing on its own would race the offline pass and
  3704. # skip the requeue the check exists to observe.
  3705. fake.hold_state = True
  3706. conn = db()
  3707. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  3708. conn.commit()
  3709. conn.close()
  3710. # The requeue frees the saddle in the same tick, so 'queued' is
  3711. # transient; the durable evidence is the agent comment (and the task
  3712. # completing again on the healthy daemon).
  3713. check(wait_for(lambda: any(c["body"] == "saddle went offline; task requeued"
  3714. for c in task_state(auth, offline_task).get("comments", []))
  3715. or False, timeout=30, what="offline requeue comment") is not None,
  3716. "offline saddle requeues the task")
  3717. fake.hold_state = False # release: the round ends, the daemon re-asks
  3718. check(wait_task_done(auth, offline_task, timeout=60) is not None,
  3719. "requeued task completes again on the healthy daemon")
  3720. print("== R6 F1: a hanging request cannot freeze the tick ==")
  3721. # One wedged /task-update (never responds) blocks the comment/
  3722. # subtask-event delivery pass; the Soup timeout must fail it and
  3723. # later ticks keep dispatching.
  3724. conn = db()
  3725. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  3726. " values (1, 'Hang survivor', 'queued', 2, strftime('%s','now'))")
  3727. hang_task = conn.execute("select max(id) from tasks").fetchone()[0]
  3728. conn.close()
  3729. task_id_tmp = create_queued(auth, {
  3730. "project_id": "1",
  3731. "title": "Hang runner",
  3732. "priority": "3",
  3733. })
  3734. hang_runner = task_id_tmp
  3735. # A human comment on the running task gives the tick a
  3736. # /task-update delivery to make; the next one hangs.
  3737. check(wait_for(lambda: task_state(auth, hang_runner).get("status") == "working"
  3738. or False, timeout=60, what="hang runner working") is not None,
  3739. "hang runner reaches working")
  3740. act(auth, task_state(auth, hang_runner)["comment"],
  3741. {"body": "operator ping while wedged"})
  3742. fake.hang_next["/task-update"] = 1
  3743. check(wait_task_done(auth, hang_runner, timeout=90) is not None,
  3744. "dispatching task survives a hung daemon request")
  3745. check(wait_for(lambda: any(c.get("text") == "operator ping while wedged"
  3746. or c.get("body") == "operator ping while wedged"
  3747. for c in fake.comment_log) or False,
  3748. timeout=30, what="wedged comment eventually delivered") is not None,
  3749. "the comment delivery retries after the hang")
  3750. # The hung delivery itself fails after the timeout; the system
  3751. # kept moving either way.
  3752. with open(os.path.join(WORK, "app.log")) as handle:
  3753. app_log = handle.read()
  3754. check("tick exceeded" not in app_log or "Dispatch tick failed" in app_log,
  3755. "a hung request never freezes the tick latch")
  3756. print("== R6 F2: refresh must not corrupt parked bookkeeping ==")
  3757. fake.suspend_on_title = "Parked refresh parent"
  3758. task_id_tmp = create_queued(auth, {
  3759. "project_id": "1",
  3760. "title": "Parked refresh parent",
  3761. "priority": "2",
  3762. })
  3763. parked = task_id_tmp
  3764. check(wait_for(lambda: task_state(auth, parked).get("status") == "suspended"
  3765. or False, timeout=60, what="parked parent suspends") is not None,
  3766. "parent parks before the refresh")
  3767. fake_card = saddle_card(auth, "fake-saddle")
  3768. act(auth, fake_card["refresh"], {})
  3769. fake_card = saddle_card(auth, "fake-saddle")
  3770. check(fake_card["status"] == "idle" and int(fake_card["current_task_id"] or 0) == 0,
  3771. "refresh on a parked (suspended) daemon leaves the saddle idle")
  3772. # The parked task keeps its open session and stays put: plain
  3773. # tasks have no subtask events to resume them (the goal machinery
  3774. # owns resumes); the human resumes it explicitly.
  3775. check(quiet_window(quiet_seconds(),
  3776. lambda: task_state(auth, parked)["status"] == "suspended",
  3777. "parked task stays parked"),
  3778. "a parked plain task stays parked after the refresh (no resume channel)")
  3779. act(auth, task_state(auth, parked)["cancel"], {})
  3780. check(wait_for(lambda: task_state(auth, parked)["status"] == "failed" or False,
  3781. timeout=30, what="parked task cancelled") is not None,
  3782. "the parked task cancels cleanly after the refresh")
  3783. print("== R7 B1: cancel reaches the daemon ==")
  3784. # Plan 10 phase 2: cancellation is POST /task-update {kind: cancel}
  3785. # to the RUNNING daemon (the abort machinery, workspace kept).
  3786. task_id_tmp = create_queued(auth, {
  3787. "project_id": "1",
  3788. "title": "Cancel live",
  3789. "priority": "2",
  3790. })
  3791. cancel_live = task_id_tmp
  3792. check(wait_for(lambda: task_state(auth, cancel_live).get("status") == "working"
  3793. or False, timeout=60, what="cancel-live working") is not None,
  3794. "task reaches working before the cancel")
  3795. act(auth, task_state(auth, cancel_live)["cancel"], {})
  3796. check(wait_for(lambda: cancel_live in fake.abort_log or False,
  3797. timeout=30, what="daemon abort recorded") is not None,
  3798. "cancelling POSTs task-update cancel to the daemon")
  3799. check(any(c["body"] == "cancelled; daemon aborted"
  3800. for c in task_state(auth, cancel_live).get("comments", [])),
  3801. "the abort outcome is narrated")
  3802. check(task_state(auth, cancel_live)["status"] == "failed",
  3803. "cancelled task lands failed as before")
  3804. # A 500 on the cancel marks the saddle offline (no fence layer
  3805. # anymore); nothing dispatches to it while offline, and the
  3806. # daemon's own ask flips the row back to idle (proof of life).
  3807. task_id_tmp = create_queued(auth, {
  3808. "project_id": "1",
  3809. "title": "Fence runner",
  3810. "priority": "2",
  3811. })
  3812. fence_runner = task_id_tmp
  3813. check(wait_for(lambda: task_state(auth, fence_runner).get("status") == "working"
  3814. or False, timeout=60, what="fence runner working") is not None,
  3815. "second task reaches working")
  3816. fake.abort_failures = 1
  3817. act(auth, task_state(auth, fence_runner)["cancel"], {})
  3818. check(any(c["body"] == "cancelled; daemon unreachable — saddle marked offline"
  3819. for c in task_state(auth, fence_runner).get("comments", [])),
  3820. "failed cancel narrates the offline marking")
  3821. check(saddle_card(auth, "fake-saddle")["status"] == "offline",
  3822. "saddle marked offline after the failed cancel")
  3823. task_id_tmp = create_queued(auth, {
  3824. "project_id": "1",
  3825. "title": "During fence",
  3826. "priority": "3",
  3827. })
  3828. during_fence = task_id_tmp
  3829. # Converted sleep(7): a quiet window spanning several dispatch
  3830. # ticks in which the task MUST stay queued — if the offline
  3831. # saddle ever dispatches it, this fails loudly. The daemon is held
  3832. # mid-round for the window (the original relied on its 8s work
  3833. # period outlasting the sleep): a finishing round would ask, prove
  3834. # liveness and flip the offline row — only after the window may it.
  3835. fake.hold_state = True
  3836. check(quiet_window(quiet_seconds(),
  3837. lambda: task_state(auth, during_fence)["status"] == "queued",
  3838. "offline saddle does not dispatch during_fence"),
  3839. "offline saddle is not dispatchable")
  3840. fake.hold_state = False
  3841. # The (unaborted) daemon finishes its round, goes idle-awake and
  3842. # asks — the ask is the proof of life that flips the row back.
  3843. check(wait_for(lambda: saddle_card(auth, "fake-saddle")["status"] == "idle" or False,
  3844. timeout=30, what="ask flips offline to idle") is not None,
  3845. "the daemon's ask flips the offline row back to idle")
  3846. check(wait_task_done(auth, during_fence, timeout=60) is not None,
  3847. "queued work dispatches once the saddle proves it is alive")
  3848. print("== R7 B3: health panel + pushed raw log from the first round ==")
  3849. # A normally dispatched task pushes its chunks immediately: raw
  3850. # rows exist from the first round (the session-4 gap stays
  3851. # fixed without any probe machinery).
  3852. task_id_tmp = create_queued(auth, {
  3853. "project_id": "1",
  3854. "title": "Raw from first push",
  3855. "priority": "2",
  3856. })
  3857. raw_first = task_id_tmp
  3858. def raw_count(task_id):
  3859. conn = db()
  3860. try:
  3861. return conn.execute(
  3862. "select count(*) from session_raw_log where session_id in"
  3863. " (select id from sessions where task_id = ?)", (task_id,)).fetchone()[0]
  3864. finally:
  3865. conn.close()
  3866. check(wait_for(lambda: raw_count(raw_first) > 0 or False,
  3867. timeout=60, what="raw rows from first push") is not None,
  3868. "pushed chunks land from the first round (session-4 gap)")
  3869. check(wait_task_done(auth, raw_first, timeout=60) is not None,
  3870. "raw-first task completes")
  3871. # Health panel: a manual refresh populates the snapshot.
  3872. fake_card = saddle_card(auth, "fake-saddle")
  3873. act(auth, fake_card["refresh"], {})
  3874. card = saddle_card(auth, "fake-saddle")
  3875. check(card.get("health") in ("healthy", "stale")
  3876. and card.get("daemon_state") in ("working", "idle", "done")
  3877. and card.get("uptime_display", "") != ""
  3878. and card.get("last_contact_display", "") not in ("", "never"),
  3879. "saddles page shows daemon state, uptime and last contact")
  3880. print("== R8: pushed chunk ingestion is lossless ==")
  3881. # The daemon's opening flush: a coloured prompt run, plain text,
  3882. # a bare CRLF between prompts and the tail — every non-empty
  3883. # chunk must land, exactly once, in seq order. A mid-flight
  3884. # redelivery of the whole batch (the outbox's at-least-once
  3885. # retry) consumes the duplicates.
  3886. corpus = [
  3887. {"seq": 1, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  3888. {"seq": 2, "text": "echo hello\r\n"},
  3889. {"seq": 3, "text": "\r\n"},
  3890. {"seq": 4, "text": "hello\r\n"},
  3891. {"seq": 5, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  3892. {"seq": 6, "text": "done\r\n"},
  3893. ]
  3894. fake.scripted_corpus = corpus
  3895. fake.hold_state = True
  3896. task_id_tmp = create_queued(auth, {
  3897. "project_id": "1",
  3898. "title": "Lossless log task",
  3899. "priority": "2",
  3900. })
  3901. lossless = task_id_tmp
  3902. def stored_seqs(task_id):
  3903. conn = db()
  3904. try:
  3905. return [r[0] for r in conn.execute(
  3906. "select seq from session_raw_log where session_id in"
  3907. " (select id from sessions where task_id = ?)"
  3908. " order by seq", (task_id,))]
  3909. finally:
  3910. conn.close()
  3911. check(wait_for(lambda: task_state(auth, lossless).get("status") == "working"
  3912. or False, timeout=60, what="lossless task working") is not None,
  3913. "lossless task dispatches and pushes its opening flush")
  3914. check(wait_for(lambda: stored_seqs(lossless) == [1, 2, 3, 4, 5, 6] or False,
  3915. timeout=30, what="all six chunks stored") is not None,
  3916. "every pushed chunk lands in session_raw_log, CRLF-only included (%s)"
  3917. % stored_seqs(lossless))
  3918. status, _ = saddle_api("POST", "/api/saddle/chunks", fake.token,
  3919. {"session_id": fake.session_id,
  3920. "chunks": [dict(chunk) for chunk in corpus]})
  3921. check(status == 200 and stored_seqs(lossless) == [1, 2, 3, 4, 5, 6],
  3922. "a full-batch redelivery stores nothing new (exactly-once)")
  3923. request = urllib.request.Request(
  3924. WEB + "/terminal-stream/%d" % [r[0] for r in db().execute(
  3925. "select id from sessions where task_id = ?", (lossless,))][0])
  3926. with urllib.request.urlopen(request, timeout=15) as stream:
  3927. texts = []
  3928. deadline = time.monotonic() + 8
  3929. while time.monotonic() < deadline and len(texts) < 6:
  3930. line = stream.readline().decode().strip()
  3931. if not line.startswith("data: ") or line == "data: ping":
  3932. continue
  3933. event = json.loads(line[6:])
  3934. if event.get("type") == "raw":
  3935. texts.append(event.get("text") or "")
  3936. check("\r\n" in texts and len(texts) == 6,
  3937. "SSE serves the whitespace chunk unfiltered")
  3938. fake.hold_state = False
  3939. fake.scripted_corpus = None
  3940. check(wait_task_done(auth, lossless, timeout=60) is not None,
  3941. "lossless task completes")
  3942. print("== R9 B1/B2: git identity + ssh key ==")
  3943. # The key travels on /status into the saddle row and the page view
  3944. # (the manual refresh's exceptional probe).
  3945. fake.ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1teStKey saddle-1@fedora"
  3946. fake_card = saddle_card(auth, "fake-saddle")
  3947. check(fake_card.get("ssh_public_key", "") == "",
  3948. "no key shown before the daemon reports one")
  3949. act(auth, fake_card["refresh"], {})
  3950. check(wait_for(lambda: "AAAAC3NzaC1lZDI1teStKey" in
  3951. saddle_card(auth, "fake-saddle").get("ssh_public_key", "") or False,
  3952. timeout=30, what="key lands on the row") is not None,
  3953. "reported ssh_public_key persists onto the saddle row")
  3954. conn = db()
  3955. row_key = conn.execute("select ssh_public_key from saddles where name = 'fake-saddle'"
  3956. ).fetchone()[0]
  3957. conn.close()
  3958. check(row_key == fake.ssh_public_key,
  3959. "the key is stored verbatim in the database")
  3960. # Identity edit flows through the UI into the assignment payload.
  3961. fake_card = saddle_card(auth, "fake-saddle")
  3962. act(auth, fake_card["update_identity"],
  3963. {"git_name": "clanker-bot", "git_email": "bot@unitatem.net"})
  3964. fake_card = saddle_card(auth, "fake-saddle")
  3965. check(fake_card.get("git_name") == "clanker-bot"
  3966. and fake_card.get("git_email") == "bot@unitatem.net",
  3967. "inline edit saves the git identity")
  3968. task_id_tmp = create_queued(auth, {
  3969. "project_id": "1",
  3970. "title": "Identity task",
  3971. "priority": "2",
  3972. })
  3973. identity_task = task_id_tmp
  3974. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == identity_task
  3975. for p in fake.start_payloads) or False,
  3976. timeout=60, what="identity task dispatched") is not None,
  3977. "identity task dispatches")
  3978. payload = [p for p in fake.start_payloads
  3979. if int(p.get("task", {}).get("id") or 0) == identity_task][-1]
  3980. identity = payload.get("git_identity") or {}
  3981. check(identity.get("name") == "clanker-bot"
  3982. and identity.get("email") == "bot@unitatem.net",
  3983. "the assignment carries the saddle's git_identity")
  3984. # Earlier assignments (identity unset) carry no git_identity member.
  3985. check(all("git_identity" not in p for p in fake.start_payloads[:-1]),
  3986. "unset identity omits the member (daemon fallback applies)")
  3987. # Clearing the identity omits it from later assignments.
  3988. fake_card = saddle_card(auth, "fake-saddle")
  3989. act(auth, fake_card["update_identity"], {"git_name": "", "git_email": ""})
  3990. check(saddle_card(auth, "fake-saddle").get("git_name", "") == "",
  3991. "clearing the identity empties the row")
  3992. check(wait_task_done(auth, identity_task, timeout=60) is not None,
  3993. "identity task completes")
  3994. print("== phase 2: blocked push -> block row + pulse ==")
  3995. # The browser flow on each pulse: statum.act(task.refresh) — the
  3996. # sealed GET action must rehydrate the task slot with the new
  3997. # block the daemon just PUSHED (state blocked + block payload).
  3998. task_id_tmp = create_queued(auth, {
  3999. "project_id": "1",
  4000. "title": "Live block task",
  4001. "priority": "2",
  4002. })
  4003. live_task = task_id_tmp
  4004. check(wait_for(lambda: task_state(auth, live_task).get("status") == "working"
  4005. or False, timeout=60, what="live task working") is not None,
  4006. "live-block task reaches working")
  4007. fake.hold_state = True
  4008. fake.state = "blocked" # the daemon parks on its question
  4009. status = fake.push_results("blocked", block={
  4010. "question": "Pick one", "type": "question", "options": ["A", "B"]})
  4011. check(status == 200, "blocked state push accepted")
  4012. # The parked daemon is idle-awake: it asks (and sleeps on 204).
  4013. fake.maybe_trigger_ask("parked")
  4014. check(wait_for(lambda: any(b.get("question") == "Pick one"
  4015. for b in task_state(auth, live_task).get("blocks", []))
  4016. or False, timeout=30, what="block lands in state") is not None,
  4017. "the pushed block reaches the sealed refresh without a reload")
  4018. detail = task_state(auth, live_task)
  4019. check(detail.get("status") == "blocked",
  4020. "the blocked push flips the task to blocked")
  4021. pushed_block = [b for b in detail["blocks"] if b.get("question") == "Pick one"][0]
  4022. conn = db()
  4023. options_json = conn.execute(
  4024. "select options from task_blocks where id = ?", (int(pushed_block["id"]),)
  4025. ).fetchone()[0]
  4026. conn.close()
  4027. check(json.loads(options_json) == ["A", "B"],
  4028. "the block row carries its options payload")
  4029. check(any(s["status"] == "idle"
  4030. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  4031. "the blocked push parks the saddle")
  4032. detail = task_state(auth, live_task)
  4033. check(detail.get("refresh") is not None,
  4034. "the sealed GET refresh action is still authored")
  4035. status, _ = http("GET", detail["refresh"]["uri"], timeout=15)
  4036. check(status in (200, 401),
  4037. "the refresh URI resolves as a GET (client roundtrip shape)")
  4038. act(auth, pushed_block["answer_action"], {"answer": "A"})
  4039. # The answer makes the parked task resume-offerable: the affine
  4040. # saddle is woken, asks, and its assignment carries the answer.
  4041. pushes_before = len([p for p in fake.start_payloads
  4042. if int(p.get("task", {}).get("id") or 0) == live_task])
  4043. check(wait_for(lambda: len([p for p in fake.start_payloads
  4044. if int(p.get("task", {}).get("id") or 0) == live_task])
  4045. > pushes_before or False, timeout=60,
  4046. what="blocked task resumes") is not None,
  4047. "answering the pushed block resumes the parked workspace")
  4048. fake.hold_state = False # the resumed round runs to completion
  4049. resume_payload = [p for p in fake.start_payloads
  4050. if int(p.get("task", {}).get("id") or 0) == live_task][-1]
  4051. answers = resume_payload.get("task", {}).get("answers", [])
  4052. check(any(a.get("answer") == "A" for a in answers),
  4053. "the resume assignment carries the human's answer")
  4054. check(wait_task_done(auth, live_task, timeout=60) is not None,
  4055. "live-block task completes after answering")
  4056. # =============================================================================
  4057. # Bundle: answers — the answer-resume machinery in both daemon shapes
  4058. # (sleeping affine wake, mid-round verdict delivery), offline requeue
  4059. # keeping parked-with-answered tasks, the staleness probe, and the
  4060. # startup token migration (this shard's one deliberate app restart).
  4061. # =============================================================================
  4062. def bundle_answers(ctx):
  4063. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4064. app = ctx.app
  4065. print("== phase 2: answer resume — wake -> ask -> affinity claim ==")
  4066. # The full live sequence against a daemon that asks after its
  4067. # park: ask -> assignment -> blocked push (park) -> ask -> 204
  4068. # -> sleeps (row idle) -> human answers -> the dispatcher WAKES
  4069. # the sleeping affine saddle -> its ask allocates the resume,
  4070. # the verdict riding the assignment -> the session continues.
  4071. # A private capability tag keeps the fleet's other sleeping
  4072. # saddles from claiming these tasks.
  4073. saddles_state = slot_public(auth, "/saddles", "saddles")
  4074. act(auth, saddles_state["create_capability"], {"name": "answerflow"})
  4075. answerflow_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  4076. if c["name"] == "answerflow"][0])
  4077. def answerflow_daemon(**kwargs):
  4078. daemon = FakeSaddle()
  4079. daemon.ask_on_register = False # manual, deterministic asks
  4080. daemon.hold_state = True # the tests drive the lifecycle
  4081. for key, value in kwargs.items():
  4082. setattr(daemon, key, value)
  4083. daemon.serve()
  4084. return daemon
  4085. def register_answerflow(daemon, name):
  4086. act(auth, slot_public(auth, "/saddles", "saddles")["register"], {
  4087. "name": name, "host": "127.0.0.1:%d" % daemon.port})
  4088. act(auth, saddle_card(auth, name)["attach_capability"],
  4089. {"capability_id": str(answerflow_cap)})
  4090. def create_answerflow_task(title):
  4091. return create_queued(auth, {
  4092. "project_id": "1", "title": title, "priority": "2",
  4093. "capability_id": [str(answerflow_cap)]})
  4094. def retire_daemon(daemon, name):
  4095. # deterministic teardown: a dead daemon and an offline row
  4096. # never interfere with the sections that follow
  4097. daemon.kill()
  4098. act(auth, saddle_card(auth, name)["refresh"], {})
  4099. sleeper = answerflow_daemon(ask_on_wake=True)
  4100. register_answerflow(sleeper, "resume-sleeper")
  4101. sleeping_task = create_answerflow_task("Sleeping resume task")
  4102. ask_status, assignment = sleeper.ask_now()
  4103. check(ask_status == 200 and int(assignment["task"]["id"]) == sleeping_task,
  4104. "the daemon's ask claims the queued task")
  4105. sleeping_session = assignment.get("session_id")
  4106. sleeper.state = "blocked"
  4107. check(sleeper.push_results("blocked", block={
  4108. "question": "Pick a side", "type": "question",
  4109. "options": ["Port", "Starboard"]}) == 200,
  4110. "the blocked push parks the session")
  4111. check(wait_for(lambda: task_state(auth, sleeping_task).get("status") == "blocked"
  4112. or False, timeout=30, what="sleeping task parked") is not None,
  4113. "the task parks as blocked")
  4114. check(saddle_card(auth, "resume-sleeper")["status"] == "idle",
  4115. "the parked session's saddle row reads idle")
  4116. ask_status, _ = sleeper.ask_now()
  4117. check(ask_status == 204,
  4118. "the parked daemon's ask returns 204 — it sleeps until woken")
  4119. # Converted sleep(3): ticks pass with the daemon asleep and no
  4120. # wake may arrive — a wake during the window fails loudly.
  4121. check(quiet_window(quiet_seconds(),
  4122. lambda: len(sleeper.wake_log) == 0,
  4123. "sleeping daemon never woken"),
  4124. "the sleeping daemon is never woken while the block waits")
  4125. detail = task_state(auth, sleeping_task)
  4126. side_block = [b for b in detail["blocks"] if b["question"] == "Pick a side"][0]
  4127. act(auth, side_block["answer_action"], {"option": "Starboard"})
  4128. check(wait_for(lambda: len(sleeper.wake_log) > 0 or False,
  4129. timeout=30, what="wake after the answer") is not None,
  4130. "answering the block wakes the sleeping affine saddle")
  4131. # Answering = allocating (plan 11): the resume assignment carries
  4132. # the verdict as resume_notice (stable wording) AND a FRESH
  4133. # session id — the parked row closed, the daemon keys its resumed
  4134. # pushes on the new one.
  4135. check(wait_for(lambda: any(
  4136. int(p.get("task", {}).get("id") or 0) == sleeping_task
  4137. and p.get("session_id") != sleeping_session
  4138. and p.get("resume_notice") == "Human selected: Starboard"
  4139. and any(a.get("answer") == "Starboard"
  4140. for a in p.get("task", {}).get("answers", []))
  4141. for p in sleeper.start_payloads[1:]) or False,
  4142. timeout=30, what="resume allocation carries the verdict") is not None,
  4143. "the woken daemon's ask allocates the resume — fresh session, notice carried")
  4144. # Barrier: the resume's own working push must commit before the
  4145. # manual done push (a late working write would otherwise race the
  4146. # completion's full-row write).
  4147. check(wait_for(lambda: task_state(auth, sleeping_task).get("status") == "working"
  4148. or False, timeout=15, what="resumed round working") is not None,
  4149. "the resumed round reports working before its completion push")
  4150. # The resumed round runs to completion keyed on the fresh session.
  4151. sleeper.push_results("done", summary="sleep-resumed round complete")
  4152. check(wait_task_done(auth, sleeping_task, timeout=30) is not None,
  4153. "the resumed session continues to completion")
  4154. conn = db()
  4155. rows = conn.execute(
  4156. "select id, outcome, ended_at is not null from sessions where task_id = ?"
  4157. " order by id", (sleeping_task,)).fetchall()
  4158. conn.close()
  4159. check(len(rows) == 2 and rows[0][1] == "resumed" and rows[0][2]
  4160. and rows[1][1] == "done" and rows[1][2],
  4161. "parked session closed 'resumed'; the resumed round ran on a fresh row to done (%s)"
  4162. % (rows,))
  4163. retire_daemon(sleeper, "resume-sleeper")
  4164. print("== phase 2: answer resume — the parked daemon is woken (POST /answer retired) ==")
  4165. # Post Task A every park FREES the daemon: after the blocked push
  4166. # it lands idle and asks (204). The retired POST /answer channel
  4167. # always refuses; the verdict reaches the parked workspace purely
  4168. # through the wake -> ask -> affinity allocation carrying the
  4169. # resume_notice + a fresh session id.
  4170. parked = answerflow_daemon(ask_on_wake=True,
  4171. ask_on_terminal=False)
  4172. register_answerflow(parked, "resume-parked")
  4173. parked_task = create_answerflow_task("Parked resume task")
  4174. ask_status, assignment = parked.ask_now()
  4175. check(ask_status == 200 and int(assignment["task"]["id"]) == parked_task,
  4176. "the daemon's ask claims the task")
  4177. parked_session = assignment.get("session_id")
  4178. parked.state = "blocked"
  4179. check(parked.push_results("blocked", block={
  4180. "question": "Which database?", "type": "question",
  4181. "options": ["SQLite", "Postgres"]}) == 200,
  4182. "the blocked push parks the session mid-round")
  4183. check(wait_for(lambda: task_state(auth, parked_task).get("status") == "blocked"
  4184. or False, timeout=30, what="parked task blocked") is not None,
  4185. "the task parks as blocked")
  4186. check(saddle_card(auth, "resume-parked")["status"] == "idle",
  4187. "the parked session's saddle row reads idle")
  4188. # The freed daemon re-asks (its idle loop) and sleeps on 204.
  4189. ask_status, _ = parked.ask_now()
  4190. check(ask_status == 204,
  4191. "the freed parked daemon asks again and sleeps (204)")
  4192. # The retired channel always refuses — the web never depends on it.
  4193. request = urllib.request.Request(
  4194. "http://127.0.0.1:%d/answer" % parked.port,
  4195. data=json.dumps({"answer": "SQLite", "branch_advanced": False}).encode(),
  4196. method="POST")
  4197. request.add_header("Content-Type", "application/json")
  4198. try:
  4199. urllib.request.urlopen(request, timeout=5)
  4200. refused = False
  4201. except urllib.error.HTTPError as error:
  4202. refused = error.code == 409
  4203. check(refused, "POST /answer always refuses (409) — parks resume via allocation")
  4204. detail = task_state(auth, parked_task)
  4205. db_block = [b for b in detail["blocks"] if b["question"] == "Which database?"][0]
  4206. act(auth, db_block["answer_action"], {"option": "SQLite"})
  4207. check(wait_for(lambda: len(parked.wake_log) > 0 or False,
  4208. timeout=30, what="wake after the answer") is not None,
  4209. "answering the block wakes the parked (idle) affine saddle")
  4210. check(wait_for(lambda: any(
  4211. int(p.get("task", {}).get("id") or 0) == parked_task
  4212. and p.get("session_id") != parked_session
  4213. and p.get("resume_notice") == "Human selected: SQLite"
  4214. for p in parked.start_payloads[1:]) or False,
  4215. timeout=30, what="parked resume allocation") is not None,
  4216. "the parked daemon's ask allocates the resume — fresh session, formatted notice")
  4217. # The hold_state daemon drives its round manually: the resumed
  4218. # round completes on the fresh session row.
  4219. parked.push_results("done", summary="parked round resumed and finished")
  4220. check(wait_task_done(auth, parked_task, timeout=60) is not None,
  4221. "the parked session continues to completion")
  4222. conn = db()
  4223. row = conn.execute("select outcome from sessions where id = ?",
  4224. (parked_session,)).fetchone()
  4225. session_rows = conn.execute(
  4226. "select id, outcome from sessions where task_id = ? order by id",
  4227. (parked_task,)).fetchall()
  4228. conn.close()
  4229. check(row is not None and row[0] == "resumed"
  4230. and len(session_rows) == 2 and session_rows[0] == (parked_session, "resumed"),
  4231. "the parked session closed 'resumed' and the resumed round kept its own row (%s)"
  4232. % (session_rows,))
  4233. retire_daemon(parked, "resume-parked")
  4234. print("== plan 11: plan acceptance — accept / reject / auto-approve ==")
  4235. # A type 'plan' block parks like any other; Accept and
  4236. # Reject-with-feedback drive the same wake -> ask -> allocation
  4237. # resume as any verdict, the stable wording riding the
  4238. # resume_notice. Plan 12: the daemon only SENDS plan blocks on
  4239. # goal runs now (the goal page owns the review); this covers the
  4240. # generic verdict path a goal-run's mirrored block also uses. The
  4241. # auto-approve option is gone.
  4242. planner = answerflow_daemon(ask_on_wake=True, ask_on_terminal=False)
  4243. register_answerflow(planner, "plan-planner")
  4244. def park_on_plan(task_id, markdown):
  4245. planner.state = "blocked"
  4246. check(planner.push_results("blocked", block={
  4247. "question": "Plan submitted for review", "type": "plan",
  4248. "body": markdown}) == 200,
  4249. "the plan push parks the session")
  4250. # Wait for the block row itself (the auto-approve variant is
  4251. # answered — and may resume — before any status poll lands).
  4252. check(wait_for(lambda: any(b["block_type"] == "plan"
  4253. for b in task_state(auth, task_id)["blocks"])
  4254. or False, timeout=30, what="plan block raised") is not None,
  4255. "the plan block reaches the task")
  4256. return [b for b in task_state(auth, task_id)["blocks"]
  4257. if b["block_type"] == "plan"][0]
  4258. # (a) Accept resumes with the approval notice.
  4259. accept_task = create_answerflow_task("Plan accept task")
  4260. ask_status, accept_assignment = planner.ask_now()
  4261. check(ask_status == 200 and int(accept_assignment["task"]["id"]) == accept_task,
  4262. "the planner claims the accept task")
  4263. accept_parked_session = accept_assignment.get("session_id")
  4264. plan_block = park_on_plan(accept_task, "# Steps\n\n1. Wire\n2. Test")
  4265. check(plan_block.get("answered") is not True,
  4266. "the plan block waits for a human verdict")
  4267. act(auth, plan_block["answer_action"],
  4268. {"answer": "Plan approved. Proceed with implementation."})
  4269. check(wait_for(lambda: any(
  4270. int(p.get("task", {}).get("id") or 0) == accept_task
  4271. and p.get("session_id") != accept_parked_session
  4272. and p.get("resume_notice") == "Plan approved. Proceed with implementation."
  4273. for p in planner.start_payloads[1:]) or False,
  4274. timeout=30, what="accept resume allocation") is not None,
  4275. "accept resumes the parked daemon with the approval notice")
  4276. planner.push_results("done", summary="plan accepted and implemented")
  4277. check(wait_task_done(auth, accept_task, timeout=60) is not None,
  4278. "the accepted plan's task completes")
  4279. planner.set_state("idle")
  4280. # (b) Reject-with-feedback loops the feedback notice back.
  4281. reject_task = create_answerflow_task("Plan reject task")
  4282. ask_status, reject_assignment = planner.ask_now()
  4283. check(ask_status == 200 and int(reject_assignment["task"]["id"]) == reject_task,
  4284. "the planner claims the reject task")
  4285. reject_parked_session = reject_assignment.get("session_id")
  4286. plan_block = park_on_plan(reject_task, "# Draft\n\nJust wing it")
  4287. act(auth, plan_block["answer_action"], {"feedback": "Add a test section"})
  4288. reject_block = [b for b in task_state(auth, reject_task)["blocks"]
  4289. if b["block_type"] == "plan"][0]
  4290. check(reject_block.get("answer")
  4291. == "Plan feedback received:\nAdd a test section",
  4292. "reject stores the feedback in the stable wording (%s)"
  4293. % reject_block.get("answer"))
  4294. check(wait_for(lambda: any(
  4295. int(p.get("task", {}).get("id") or 0) == reject_task
  4296. and p.get("session_id") != reject_parked_session
  4297. and p.get("resume_notice") == "Plan feedback received:\nAdd a test section"
  4298. for p in planner.start_payloads[1:]) or False,
  4299. timeout=30, what="reject resume allocation") is not None,
  4300. "reject resumes the parked daemon with the feedback notice")
  4301. planner.push_results("done", summary="plan revised and delivered")
  4302. check(wait_task_done(auth, reject_task, timeout=30) is not None,
  4303. "the revised plan's task completes")
  4304. planner.set_state("idle")
  4305. retire_daemon(planner, "plan-planner")
  4306. print("== phase 2: offline requeue keeps parked-with-answered tasks ==")
  4307. # A daemon dying while its parked task carries an answered
  4308. # verdict: going offline must not requeue the task or close its
  4309. # session — the resume machinery (delivery once the daemon
  4310. # returns, or the affinity allocation on its next ask) needs
  4311. # both. The question park leaves the row idle; the review park
  4312. # keeps it busy@task (`saddle review` blocks the round without
  4313. # a parking state push), exercising the unreachable path's
  4314. # requeue decision both ways.
  4315. stranded = answerflow_daemon()
  4316. register_answerflow(stranded, "resume-stranded")
  4317. stranded_task = create_answerflow_task("Stranded answered task")
  4318. ask_status, _ = stranded.ask_now()
  4319. check(ask_status == 200, "the stranded daemon claims its task")
  4320. stranded.state = "blocked"
  4321. stranded.push_results("blocked", block={
  4322. "question": "Hold or fold?", "type": "question", "options": ["Hold", "Fold"]})
  4323. check(wait_for(lambda: task_state(auth, stranded_task).get("status") == "blocked"
  4324. or False, timeout=30, what="stranded task parked") is not None,
  4325. "the stranded task parks as blocked")
  4326. detail = task_state(auth, stranded_task)
  4327. hold_block = [b for b in detail["blocks"] if b["question"] == "Hold or fold?"][0]
  4328. act(auth, hold_block["answer_action"], {"option": "Hold"})
  4329. stranded.kill() # the daemon dies before the verdict is delivered
  4330. act(auth, saddle_card(auth, "resume-stranded")["refresh"], {})
  4331. check(wait_for(lambda: saddle_card(auth, "resume-stranded")["status"] == "offline"
  4332. or False, timeout=30, what="stranded saddle offline") is not None,
  4333. "the dead daemon's saddle row goes offline")
  4334. # Converted sleep(7): offline ticks run while the task MUST stay
  4335. # parked — a requeue during the window fails loudly.
  4336. check(quiet_window(quiet_seconds(),
  4337. lambda: task_state(auth, stranded_task)["status"] == "blocked",
  4338. "stranded task not requeued"),
  4339. "the parked-with-answered task is not requeued by the offline pass")
  4340. conn = db()
  4341. open_session = conn.execute(
  4342. "select count(*) from sessions where task_id = ? and ended_at is null",
  4343. (stranded_task,)).fetchone()[0]
  4344. conn.close()
  4345. check(open_session == 1,
  4346. "the parked-with-answered task keeps its open session for the resume")
  4347. reviewer = answerflow_daemon(ask_on_terminal=False)
  4348. register_answerflow(reviewer, "resume-reviewer")
  4349. review_task = create_answerflow_task("Review park task")
  4350. ask_status, _ = reviewer.ask_now()
  4351. check(ask_status == 200, "the reviewer claims its task")
  4352. # Post Task A the review park frees the daemon: the blocked push
  4353. # carries the review block and parks the row idle.
  4354. reviewer.state = "blocked"
  4355. check(reviewer.push_results("blocked", block={
  4356. "question": "Review requested", "type": "review",
  4357. "body": "Ready for review: wired and tested."}) == 200,
  4358. "the review park push carries the review block")
  4359. check(wait_for(lambda: task_state(auth, review_task).get("status") == "review_requested"
  4360. or False, timeout=30, what="review park raised") is not None,
  4361. "the review block parks the task as review_requested (row freed)")
  4362. # The verdict lands (nothing delivers it anymore); THEN the daemon
  4363. # dies and the manual refresh offlines it — the parked-with-answered
  4364. # task must keep its session for the eventual resume.
  4365. detail = task_state(auth, review_task)
  4366. verdict_block = [b for b in detail["blocks"]
  4367. if b["block_type"] == "review"][0]
  4368. act(auth, verdict_block["answer_action"],
  4369. {"answer": "Review approved. Continue with the task."})
  4370. reviewer.kill()
  4371. act(auth, saddle_card(auth, "resume-reviewer")["refresh"], {})
  4372. check(wait_for(lambda: saddle_card(auth, "resume-reviewer")["status"] == "offline"
  4373. or False, timeout=30, what="reviewer offline") is not None,
  4374. "the dead reviewer goes offline on the failed probe")
  4375. # Converted sleep(7): offline ticks run while the task MUST stay
  4376. # review-parked — a requeue during the window fails loudly.
  4377. check(quiet_window(quiet_seconds(),
  4378. lambda: task_state(auth, review_task)["status"] == "review_requested",
  4379. "review-parked task not requeued"),
  4380. "the review-parked task with an answered verdict is never requeued")
  4381. conn = db()
  4382. open_session = conn.execute(
  4383. "select count(*) from sessions where task_id = ? and ended_at is null",
  4384. (review_task,)).fetchone()[0]
  4385. conn.close()
  4386. check(open_session == 1,
  4387. "the review-parked task keeps its open session for the resume")
  4388. print("== phase 2: staleness — one probe decides ==")
  4389. # A silent-but-alive runner (long think, nothing to flush): after
  4390. # SADDLE_STALE_S (3s here) of silence it owes ONE exceptional
  4391. # GET /status; the answer keeps it running and the silence
  4392. # episode gets no second probe.
  4393. task_id_tmp = create_queued(auth, {
  4394. "project_id": "1",
  4395. "title": "Silent thinker",
  4396. "priority": "2",
  4397. })
  4398. thinker = task_id_tmp
  4399. check(wait_for(lambda: task_state(auth, thinker).get("status") == "working"
  4400. or False, timeout=60, what="thinker working") is not None,
  4401. "silent thinker reaches working")
  4402. fake.silent = True # the daemon goes quiet mid-round (alive)
  4403. probes_at_start = fake.status_hits
  4404. check(wait_for(lambda: fake.status_hits > probes_at_start or False,
  4405. timeout=30, what="exceptional probe arrives") is not None,
  4406. "a silent runner gets its exceptional GET /status probe")
  4407. # Converted sleep(8)+sleep(6): a quiet window across several
  4408. # ticks in which the probe count MUST NOT move — a second probe
  4409. # (the poll drumbeat this guards against) fails loudly.
  4410. second_window = fake.status_hits
  4411. check(quiet_window(quiet_seconds(),
  4412. lambda: fake.status_hits == second_window,
  4413. "no second staleness probe"),
  4414. "the silence episode is probed exactly once (no poll drumbeat)")
  4415. check(task_state(auth, thinker).get("status") == "working"
  4416. and saddle_card(auth, "fake-saddle")["status"] == "busy",
  4417. "the answered probe keeps the task running (no requeue)")
  4418. # Output flows again: the episode ends, the clock resets.
  4419. fake.silent = False
  4420. fake.push_chunks(["resumed output\r\n"])
  4421. check(wait_task_done(auth, thinker, timeout=60) is not None,
  4422. "the silent thinker completes once output flows again")
  4423. # The daemon vanishing mid-task: silence for the window, the
  4424. # probe fails, the task requeues with an agent comment and the
  4425. # saddle goes offline.
  4426. task_id_tmp = create_queued(auth, {
  4427. "project_id": "1",
  4428. "title": "Vanish victim",
  4429. "priority": "2",
  4430. })
  4431. vanish = task_id_tmp
  4432. check(wait_for(lambda: task_state(auth, vanish).get("status") == "working"
  4433. or False, timeout=60, what="vanish victim working") is not None,
  4434. "vanish victim reaches working")
  4435. fake.kill()
  4436. check(wait_for(lambda: saddle_card(auth, "fake-saddle")["status"] == "offline" or False,
  4437. timeout=60, what="daemon death -> offline") is not None,
  4438. "vanishing daemon drives the saddle offline (failed staleness probe)")
  4439. check(wait_for(lambda: any("unreachable" in c["body"]
  4440. and c.get("is_system")
  4441. for c in task_state(auth, vanish).get("comments", []))
  4442. or False, timeout=30, what="unreachable comment") is not None,
  4443. "the affected task gets an unreachable system row (never an agent comment)")
  4444. check(task_state(auth, vanish)["status"] == "queued",
  4445. "the task requeues after the daemon death")
  4446. card = saddle_card(auth, "fake-saddle")
  4447. check(card.get("health") == "offline",
  4448. "health badge reports offline")
  4449. # The unreachable row flag marks the detection window: a task the
  4450. # web still sees working while its saddle is offline/fenced, before
  4451. # the requeue pass moves it. Controlled window (the real
  4452. # transitions above are atomic with their requeues).
  4453. conn = db()
  4454. conn.execute("insert into tasks (project_id, title, status, priority,"
  4455. " created_at) values (1, 'Unreachable row', 'working', 5,"
  4456. " strftime('%s','now'))")
  4457. unreachable_row = conn.execute("select max(id) from tasks").fetchone()[0]
  4458. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  4459. " values (?, ?, strftime('%s','now'))", (unreachable_row, fake_id))
  4460. conn.commit()
  4461. conn.close()
  4462. row = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  4463. if int(t["id"]) == unreachable_row][0]
  4464. check(row.get("unreachable") is True,
  4465. "queue row shows the unreachable state in the window")
  4466. print("== phase 1: startup migrates the per-saddle token ==")
  4467. # Saddles registered before the flip hold legacy api_tokens rows.
  4468. # On startup every saddle row gets its canonical token: the
  4469. # legacy value it already holds (daemons keep their credential)
  4470. # or a freshly minted one. Fixture: this shard's own racer.
  4471. fake2 = FakeSaddle()
  4472. fake2.ask_on_register = False
  4473. fake2.serve(port=free_port())
  4474. saddles_state = slot_public(auth, "/saddles", "saddles")
  4475. act(auth, saddles_state["register"], {"name": "racer-two",
  4476. "host": "127.0.0.1:%d" % fake2.port})
  4477. racer_two_id = int([s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  4478. if s["name"] == "racer-two"][0]["id"])
  4479. conn = db()
  4480. conn.execute("insert into api_tokens (saddle_id, token, created_at)"
  4481. " values (?, 'saddle-legacy-copied-token', strftime('%s','now'))",
  4482. (racer_two_id,))
  4483. conn.execute("update saddles set token = null where name = 'racer-two'")
  4484. conn.execute("insert into saddles (name, host, status, current_task_id)"
  4485. " values ('tokenless-orphan', '127.0.0.1:1', 'offline', 0)")
  4486. conn.commit()
  4487. conn.close()
  4488. app.terminate()
  4489. app.wait(timeout=10)
  4490. app = start_app()
  4491. auth = login("admin", "adminpass123")
  4492. ctx.app = app # teardown tracks the restarted process
  4493. ctx.auth = auth
  4494. def saddle_row(name):
  4495. conn = db()
  4496. try:
  4497. return conn.execute("select id, token from saddles where name = ?",
  4498. (name,)).fetchone()
  4499. finally:
  4500. conn.close()
  4501. check(wait_for(lambda: saddle_row("tokenless-orphan") is not None
  4502. and (saddle_row("tokenless-orphan")[1] or "").startswith("saddle-")
  4503. or False, timeout=20, what="tokenless row minted") is not None,
  4504. "startup mints a token for a saddle row without one")
  4505. check(wait_for(lambda: saddle_row("racer-two") is not None
  4506. and saddle_row("racer-two")[1] == "saddle-legacy-copied-token"
  4507. or False, timeout=20, what="legacy token copied") is not None,
  4508. "startup copies the legacy api_tokens value onto the row")
  4509. fake2.token = "saddle-legacy-copied-token" # the daemon asks with it
  4510. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-legacy-copied-token")
  4511. check(status in (200, 204),
  4512. "the legacy token still authenticates (copied, not replaced)")
  4513. conn = db()
  4514. conn.execute("delete from saddles where name = 'tokenless-orphan'")
  4515. conn.commit()
  4516. conn.close()
  4517. # The restart wiped the in-memory ask bookkeeping; the fleet's
  4518. # daemons re-establish sleeping with a fresh ask each (the real
  4519. # daemons' idle-awake ask / 15-minute safety self-ask).
  4520. for daemon in (fake2,):
  4521. daemon.ask_now()
  4522. check(True, "fleet re-asks after the restart (sleeping re-established)")
  4523. # =============================================================================
  4524. # Bundle: push — plan 11 task E: real Web Push over VAPID. VAPID
  4525. # persistence, the service worker, subscription CRUD + validation,
  4526. # notify-me prefs, the block/lifecycle dispatch matrix (global vs
  4527. # opted-in), 410 pruning, retry-next-tick delivery and protocol-level
  4528. # payload verification (RFC 8291 decryption + ES256 JWT) against the
  4529. # fake push service.
  4530. # =============================================================================
  4531. def bundle_push(ctx):
  4532. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4533. def subscription_count(endpoint):
  4534. conn = db()
  4535. try:
  4536. return conn.execute(
  4537. "select count(*) from push_subscriptions where endpoint = ?",
  4538. (endpoint,)).fetchone()[0]
  4539. finally:
  4540. conn.close()
  4541. print("== task E: service worker asset ==")
  4542. status, sw = http("GET", "/sw.js", timeout=15)
  4543. check(status == 200 and "addEventListener('push'" in sw
  4544. and "notificationclick" in sw and "clients.openWindow" in sw,
  4545. "the service worker serves at the origin root with push + click routing")
  4546. print("== task E: VAPID keypair generation + persistence ==")
  4547. config = json.load(open(os.path.join(WORK, "web-config.json")))
  4548. vapid = config.get("vapid") or {}
  4549. check(bool(vapid.get("public_key")) and bool(vapid.get("private_key")),
  4550. "the VAPID keypair persists into web-config.json's vapid section")
  4551. vapid_private_key = ec.derive_private_key(
  4552. int.from_bytes(b64url_dec(vapid["private_key"]), "big"), ec.SECP256R1())
  4553. derived_public = vapid_private_key.public_key().public_bytes(
  4554. Encoding.X962, PublicFormat.UncompressedPoint)
  4555. check(b64url_dec(vapid["public_key"]) == derived_public,
  4556. "the persisted public key matches the private scalar (a valid P-256 pair)")
  4557. dash = slot_public(auth, "/", "dashboard")
  4558. check(dash.get("push_vapid_key") == vapid["public_key"],
  4559. "the dashboard exposes the same VAPID key to subscribers")
  4560. check(dash.get("push_subscribed") is False and bool(dash.get("push_subscribe")),
  4561. "the bell starts unsubscribed and carries the subscribe action")
  4562. print("== task E: subscription CRUD + auth validation ==")
  4563. browser = ec.generate_private_key(ec.SECP256R1())
  4564. browser_public = browser.public_key().public_bytes(
  4565. Encoding.X962, PublicFormat.UncompressedPoint)
  4566. browser_auth = os.urandom(16)
  4567. subscribe_fields = {"p256dh": b64url(browser_public), "auth": b64url(browser_auth)}
  4568. valid_endpoint = "http://127.0.0.1:1/x"
  4569. check("absolute http(s)" in (action_notify(act(auth, dash["push_subscribe"],
  4570. {"endpoint": "ftp://example.com/push", **subscribe_fields})) or ""),
  4571. "a non-http endpoint is rejected")
  4572. check("p256dh" in (action_notify(act(auth, dash["push_subscribe"],
  4573. {"endpoint": valid_endpoint, "p256dh": b64url(os.urandom(64)),
  4574. "auth": subscribe_fields["auth"]})) or ""),
  4575. "a malformed p256dh point is rejected")
  4576. check("auth" in (action_notify(act(auth, dash["push_subscribe"],
  4577. {"endpoint": valid_endpoint, "p256dh": subscribe_fields["p256dh"],
  4578. "auth": b64url(os.urandom(15))})) or ""),
  4579. "a malformed auth secret is rejected")
  4580. push = FakePushService()
  4581. push.serve()
  4582. endpoint_main = push.url("/main")
  4583. act(auth, dash["push_subscribe"],
  4584. {"endpoint": endpoint_main, **subscribe_fields})
  4585. conn = db()
  4586. rows = conn.execute("select user_id, p256dh, auth from push_subscriptions"
  4587. " where endpoint = ?", (endpoint_main,)).fetchall()
  4588. admin_id = conn.execute("select id from spry_users where username = 'admin'"
  4589. ).fetchone()[0]
  4590. conn.close()
  4591. check(len(rows) == 1 and rows[0][0] == admin_id,
  4592. "a valid subscription stores against the signed-in user")
  4593. # Re-subscribing the same endpoint replaces (never duplicates).
  4594. rotated_auth = os.urandom(16)
  4595. act(auth, dash["push_subscribe"],
  4596. {"endpoint": endpoint_main, "p256dh": subscribe_fields["p256dh"],
  4597. "auth": b64url(rotated_auth)})
  4598. conn = db()
  4599. rows = conn.execute("select auth from push_subscriptions where endpoint = ?",
  4600. (endpoint_main,)).fetchall()
  4601. conn.close()
  4602. check(len(rows) == 1 and rows[0][0] == b64url(rotated_auth),
  4603. "re-subscribing an endpoint replaces its keys in place")
  4604. print("== task E: notify-me pref persistence ==")
  4605. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4606. {"project_id": "1", "title": "Push pref task", "priority": "5"})
  4607. pref_task = task_id_of("Push pref task")
  4608. act(auth, task_state(auth, pref_task)["toggle_notify"], {})
  4609. conn = db()
  4610. check(conn.execute("select count(*) from task_notify_prefs where task_id = ?"
  4611. " and user_id = ?", (pref_task, admin_id)).fetchone()[0] == 1,
  4612. "Notify me persists a task_notify_prefs row for the user")
  4613. conn.close()
  4614. check(task_state(auth, pref_task).get("notify_me") is True,
  4615. "the task slot reflects notify_me after the toggle")
  4616. act(auth, task_state(auth, pref_task)["toggle_notify"], {})
  4617. conn = db()
  4618. check(conn.execute("select count(*) from task_notify_prefs where task_id = ?",
  4619. (pref_task,)).fetchone()[0] == 0,
  4620. "Don't notify me removes the pref row")
  4621. conn.close()
  4622. check(task_state(auth, pref_task).get("notify_me") is False,
  4623. "the task slot reflects the opt-out")
  4624. print("== task E: dispatch matrix — global blocks vs opted-in lifecycle ==")
  4625. # Two "browsers" for admin (/main, /gone) and one for another user
  4626. # (id 999, rows seeded directly — push targeting is per user).
  4627. endpoint_gone = push.url("/gone")
  4628. push.status_for["/gone"] = 410
  4629. act(auth, dash["push_subscribe"],
  4630. {"endpoint": endpoint_gone, **subscribe_fields})
  4631. other_browser = ec.generate_private_key(ec.SECP256R1())
  4632. other_public = other_browser.public_key().public_bytes(
  4633. Encoding.X962, PublicFormat.UncompressedPoint)
  4634. other_auth = os.urandom(16)
  4635. endpoint_other = push.url("/other")
  4636. conn = db()
  4637. conn.execute("insert into push_subscriptions (user_id, endpoint, p256dh, auth,"
  4638. " created_at) values (999, ?, ?, ?, strftime('%s','now'))",
  4639. (endpoint_other, b64url(other_public), b64url(other_auth)))
  4640. conn.commit()
  4641. conn.close()
  4642. # Task 1: admin opted in via the UI toggle; the other user is not.
  4643. # Baselines are captured BEFORE the enqueue: the first-start push
  4644. # fires at the allocation, the instant the dispatch lands.
  4645. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4646. {"project_id": "1", "title": "Push lifecycle task", "priority": "5"})
  4647. task1 = task_id_of("Push lifecycle task")
  4648. act(auth, task_state(auth, task1)["toggle_notify"], {})
  4649. main_before = len(push.hits("/main"))
  4650. other_before = len(push.hits("/other"))
  4651. gone_before = len(push.hits("/gone"))
  4652. enqueue_task(auth, task1)
  4653. check(wait_for(lambda: fake.running_task == task1 or False, timeout=30,
  4654. what="task 1 assignment") is not None,
  4655. "task 1 dispatches to the fake daemon")
  4656. task1_session = fake.session_id
  4657. check(wait_for(lambda: len(push.hits("/main")) > main_before, timeout=15,
  4658. what="first-start push to the opted-in admin") is not None,
  4659. "first start notifies the opted-in user's subscription")
  4660. check(wait_for(lambda: len(push.hits("/gone")) > gone_before, timeout=15,
  4661. what="first-start push to the gone endpoint") is not None,
  4662. "first start reaches every subscription of the opted-in user")
  4663. check(quiet_window(quiet_seconds(),
  4664. lambda: len(push.hits("/other")) == other_before,
  4665. "no first-start push to the not-opted-in user"),
  4666. "first start never reaches users without the notify pref")
  4667. check(wait_task_done(auth, task1, timeout=60) is not None,
  4668. "task 1 completes")
  4669. _, done_payload = decrypt_webpush(push.hits("/main")[-1], browser,
  4670. browser_public, rotated_auth)
  4671. check(done_payload["title"] == "Push lifecycle task — completed"
  4672. and done_payload["url"] == "/tasks/%d" % task1,
  4673. "completion notifies the opted-in user (decrypted payload)")
  4674. check(len(push.hits("/other")) == other_before,
  4675. "completion stays with the opted-in user only")
  4676. check(wait_for(lambda: subscription_count(endpoint_gone) == 0, timeout=15,
  4677. what="410 endpoint pruned") is not None,
  4678. "a 410 Gone endpoint is pruned from push_subscriptions")
  4679. # Block events go to EVERY push-subscribed user globally.
  4680. main_before = len(push.hits("/main"))
  4681. other_before = len(push.hits("/other"))
  4682. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  4683. {"type": "block", "session_id": task1_session, "data": {
  4684. "question": "Global question for everyone?", "type": "question"}})
  4685. check(wait_for(lambda: len(push.hits("/main")) > main_before
  4686. and len(push.hits("/other")) > other_before, timeout=15,
  4687. what="global block push") is not None,
  4688. "a raised block notifies every push-subscribed user globally")
  4689. block_hit = push.hits("/other")[-1]
  4690. _, payload = decrypt_webpush(block_hit, other_browser, other_public, other_auth)
  4691. check(payload["title"] == "Push lifecycle task — question raised"
  4692. and payload["body"] == "Global question for everyone?"
  4693. and payload["url"] == "/tasks/%d" % task1,
  4694. "the block payload carries task title + kind, question and click URL (%s)"
  4695. % payload)
  4696. ciphertext_len = len(block_hit["body"]) - (21 + 65)
  4697. envelope = block_hit["body"]
  4698. record_size = int.from_bytes(envelope[16:20], "big")
  4699. # rs = plaintext + delimiter (1) + tag (16) == ciphertext-with-tag len.
  4700. check(record_size == ciphertext_len,
  4701. "the RFC 8291 envelope record size covers payload + delimiter + tag")
  4702. claims = verify_vapid(block_hit, vapid["public_key"], vapid["private_key"])
  4703. check(claims.get("aud") == "http://127.0.0.1:%d" % push.port
  4704. and claims.get("sub", "").startswith("mailto:")
  4705. and claims.get("exp", 0) > time.time(),
  4706. "the VAPID JWT verifies: aud = the endpoint origin, mailto sub, future exp")
  4707. check(block_hit["headers"].get("ttl") == "60"
  4708. and block_hit["headers"].get("content-type") == "application/octet-stream",
  4709. "the push POST carries TTL and the encrypted content type")
  4710. # Task 2: only the OTHER user opted in — start + failure reach them
  4711. # alone. Baseline again before the enqueue (first start fires at
  4712. # the allocation).
  4713. fake.fail_next = True
  4714. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4715. {"project_id": "1", "title": "Push failure task", "priority": "5"})
  4716. task2 = task_id_of("Push failure task")
  4717. conn = db()
  4718. conn.execute("insert into task_notify_prefs (task_id, user_id) values (?, 999)",
  4719. (task2,))
  4720. conn.commit()
  4721. conn.close()
  4722. main_before2 = len(push.hits("/main"))
  4723. other_before2 = len(push.hits("/other"))
  4724. enqueue_task(auth, task2)
  4725. check(wait_for(lambda: fake.running_task == task2 or False, timeout=30,
  4726. what="task 2 assignment") is not None,
  4727. "task 2 dispatches (scripted to fail)")
  4728. check(wait_for(lambda: task_state(auth, task2)["status"] == "failed"
  4729. or False, timeout=30, what="task 2 failed") is not None,
  4730. "task 2 fails")
  4731. check(wait_for(lambda: len(push.hits("/other")) >= other_before2 + 2,
  4732. timeout=15, what="opted-in user's started+failed pushes"),
  4733. "the opted-in user gets first start AND failure for the task")
  4734. started_hit = [hit for hit in push.hits("/other")[other_before2:]][0]
  4735. _, started_payload = decrypt_webpush(started_hit, other_browser,
  4736. other_public, other_auth)
  4737. check(started_payload["title"] == "Push failure task — started",
  4738. "the first-start payload names task + kind (%s)" % started_payload)
  4739. _, failure_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4740. other_public, other_auth)
  4741. check(failure_payload["title"] == "Push failure task — failed"
  4742. and failure_payload["url"] == "/tasks/%d" % task2,
  4743. "the failure payload names the task and links its page")
  4744. check(len(push.hits("/main")) == main_before2,
  4745. "an agent failure never reaches users without the pref")
  4746. print("== task E: retry next tick (best-effort delivery) ==")
  4747. endpoint_flaky = push.url("/flaky")
  4748. act(auth, dash["push_subscribe"],
  4749. {"endpoint": endpoint_flaky, **subscribe_fields})
  4750. push.fail_next["/flaky"] = 1
  4751. flaky_before = len(push.hits("/flaky"))
  4752. saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  4753. {"type": "block", "session_id": task1_session, "data": {
  4754. "question": "Flaky delivery question?", "type": "question"}})
  4755. check(wait_for(lambda: len(push.hits("/flaky")) >= flaky_before + 2,
  4756. timeout=20, what="flaky endpoint retried") is not None,
  4757. "a failed send retries on the next dispatcher tick and lands")
  4758. print("== plan 12: goal notifications — blocks/success/failure always ==")
  4759. # Goal blocks, completion approval and failure push to EVERY
  4760. # subscribed user (the mirror on the goal-run task stays quiet).
  4761. def goal_state(goal_id):
  4762. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  4763. push_goal = None
  4764. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4765. "project_id": "1", "title": "Push goal", "brief": "Notifies everyone.",
  4766. "branch_name": "goal/push"})
  4767. conn = db()
  4768. row = conn.execute("select id from goals where title = 'Push goal'").fetchone()
  4769. conn.close()
  4770. push_goal = int(row[0])
  4771. fake.goal_script = [("plan", "# Push plan\n\n1. Ring the bells")]
  4772. main_before = len(push.hits("/main"))
  4773. other_before = len(push.hits("/other"))
  4774. act(auth, goal_state(push_goal)["start"], {})
  4775. check(wait_for(lambda: goal_state(push_goal)["status"] == "plan_review" or False,
  4776. timeout=60, what="push goal enters plan review") is not None,
  4777. "the push goal reaches plan review")
  4778. check(wait_for(lambda: len(push.hits("/main")) > main_before
  4779. and len(push.hits("/other")) > other_before, timeout=15,
  4780. what="goal plan-review push") is not None,
  4781. "a goal plan review notifies every subscribed user globally")
  4782. _, plan_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4783. other_public, other_auth)
  4784. check("Push goal" in plan_payload["title"] and "plan" in plan_payload["title"]
  4785. and plan_payload["url"] == "/goals/%d" % push_goal,
  4786. "the goal block payload carries the goal title + click URL (%s)"
  4787. % plan_payload)
  4788. main_before = len(push.hits("/main"))
  4789. fake.goal_script = [("suspend",)]
  4790. act(auth, goal_state(push_goal)["plan_pending_block"]["answer_action"],
  4791. {"answer": "Plan approved. Proceed with implementation."})
  4792. check(wait_for(lambda: goal_state(push_goal)["status"] == "active" or False,
  4793. timeout=30, what="push goal active") is not None,
  4794. "the push goal activates")
  4795. check(quiet_window(3, lambda: len(push.hits("/main")) == main_before,
  4796. "no push for an internal resume"),
  4797. "the goal agent's own park/resume does not notify (internal)")
  4798. # `saddle failure` in goal context fails the goal — global push.
  4799. fake.goal_script = [("fail", "the harness collapsed")]
  4800. other_before2 = len(push.hits("/other"))
  4801. main_before2 = len(push.hits("/main"))
  4802. conn = db()
  4803. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  4804. " priority, completed_at, created_at) values (1, ?, 'task',"
  4805. " 'Warm', 'done', 5,"
  4806. " strftime('%s','now'),"
  4807. " strftime('%s','now','-30 seconds'))", (push_goal,))
  4808. conn.commit()
  4809. conn.close()
  4810. check(wait_for(lambda: goal_state(push_goal)["status"] == "failed" or False,
  4811. timeout=60, what="goal failure lands") is not None,
  4812. "the goal agent's failure fails the goal")
  4813. check(wait_for(lambda: len(push.hits("/other")) > other_before2
  4814. and len(push.hits("/main")) > main_before2, timeout=15,
  4815. what="goal failure push") is not None,
  4816. "a goal failure notifies every subscribed user globally")
  4817. _, fail_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4818. other_public, other_auth)
  4819. check("Push goal" in fail_payload["title"] and "failed" in fail_payload["title"]
  4820. and fail_payload["url"] == "/goals/%d" % push_goal,
  4821. "the goal failure payload carries the goal title + click URL (%s)"
  4822. % fail_payload)
  4823. # Completion approval pushes "complete" globally (success always).
  4824. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4825. "project_id": "1", "title": "Push done goal", "brief": "Completes.",
  4826. "branch_name": "goal/push-done"})
  4827. conn = db()
  4828. row = conn.execute("select id from goals where title = 'Push done goal'").fetchone()
  4829. conn.close()
  4830. done_goal = int(row[0])
  4831. fake.goal_script = [("plan", "# Done plan")]
  4832. act(auth, goal_state(done_goal)["start"], {})
  4833. check(wait_for(lambda: goal_state(done_goal)["status"] == "plan_review" or False,
  4834. timeout=60, what="done goal plan review") is not None,
  4835. "the done goal reaches plan review")
  4836. fake.goal_script = [("done", "# Completion\n\nShipped.")]
  4837. act(auth, goal_state(done_goal)["plan_pending_block"]["answer_action"],
  4838. {"answer": "Plan approved. Proceed with implementation."})
  4839. check(wait_for(lambda: goal_state(done_goal)["status"] == "completion_review"
  4840. or False, timeout=60, what="done goal completion review") is not None,
  4841. "the approved done goal reaches completion review")
  4842. main_before = len(push.hits("/main"))
  4843. act(auth, goal_state(done_goal)["completion_pending_block"]["answer_action"],
  4844. {"answer": "Review approved. Continue with the task."})
  4845. check(wait_for(lambda: goal_state(done_goal)["status"] == "complete" or False,
  4846. timeout=30, what="done goal completes") is not None,
  4847. "the done goal completes")
  4848. check(wait_for(lambda: len(push.hits("/main")) > main_before, timeout=15,
  4849. what="goal success push") is not None,
  4850. "a goal completion notifies every subscribed user globally")
  4851. _, done_goal_payload = decrypt_webpush(push.hits("/main")[-1], browser,
  4852. browser_public, rotated_auth)
  4853. check("Push done goal" in done_goal_payload["title"]
  4854. and "complete" in done_goal_payload["title"]
  4855. and done_goal_payload["url"] == "/goals/%d" % done_goal,
  4856. "the goal success payload carries the goal title + click URL (%s)"
  4857. % done_goal_payload)
  4858. print("== task E: unsubscribe removes the subscription ==")
  4859. dash = slot_public(auth, "/", "dashboard")
  4860. check(dash.get("push_subscribed") is True,
  4861. "the bell shows subscribed while endpoints exist")
  4862. act(auth, dash["push_unsubscribe"], {"endpoint": endpoint_main})
  4863. check(subscription_count(endpoint_main) == 0,
  4864. "unsubscribing removes the endpoint's row")
  4865. # =============================================================================
  4866. # Bundle: goals — the plan-12 goal lifecycle: creation with branch-name
  4867. # uniqueness, the start → planning → plan review → active flow with
  4868. # revisions, the goal agent's task fan-out through the task CLI
  4869. # callbacks (ownership + creator-only enqueue), the event-driven
  4870. # coalesced resume, pause/resume queueing, the completion review with
  4871. # branch push state, the cancel cascade, and the human tasks'
  4872. # auto-enqueue-after predecessor.
  4873. # =============================================================================
  4874. def bundle_goals(ctx):
  4875. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4876. app = ctx.app
  4877. def goal_state(goal_id):
  4878. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  4879. def create_goal(fields):
  4880. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  4881. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  4882. if g["title"] == fields["title"]]
  4883. return int(rows[0]["id"])
  4884. print("== plan 12: goal creation, validation, lifecycle actions ==")
  4885. goal1 = create_goal({"project_id": "1", "title": "Ship the flange",
  4886. "brief": "Make the flange module production-grade.",
  4887. "branch_name": "goal/flange", "priority": "3"})
  4888. state = goal_state(goal1)
  4889. check(state["status"] == "draft" and state["display"] == "draft"
  4890. and state["branch_name"] == "goal/flange"
  4891. and state["base_branch"] == "main",
  4892. "a goal lands in draft with its branch pair")
  4893. check(state.get("start") is not None and state.get("cancel") is not None
  4894. and state.get("pause") is None,
  4895. "draft offers start + cancel only")
  4896. check(state["run_task_id"] == 0 and state["comments"] == [],
  4897. "a draft goal has no thread yet (the run task owns it)")
  4898. draft_page = http_get_page(auth, "/goals/%d" % goal1)
  4899. check('stm-if="goal.run_task_id &gt; 0" stm-action="goal.comment"' in draft_page
  4900. and "comments open with its run" in draft_page,
  4901. "the draft goal page gates the composer on the run (muted note until then)")
  4902. # Branch-name uniqueness: same name, same involved project → refuse.
  4903. duplicate_directives = act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4904. "project_id": "1", "title": "Clash", "brief": "b", "branch_name": "goal/flange"})
  4905. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  4906. and "goal/flange" in (d.get("message") or "")
  4907. for d in duplicate_directives),
  4908. "a live goal's branch name cannot be reused in an involved project (%s)"
  4909. % [d.get("message") for d in duplicate_directives if d.get("type") == "notify"])
  4910. conn = db()
  4911. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  4912. " values ('other-repo', 'https://example.com/other.git', 'main',"
  4913. " strftime('%s','now'))")
  4914. conn.commit()
  4915. conn.close()
  4916. goal_elsewhere = create_goal({"project_id": "2", "title": "Elsewhere",
  4917. "brief": "b", "branch_name": "goal/flange"})
  4918. check(goal_elsewhere > 0,
  4919. "the same branch name in a disjoint project is fine (one per repo)")
  4920. # Brief validation.
  4921. brief_directives = act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4922. "project_id": "1", "title": "No brief", "brief": " ", "branch_name": "goal/x1"})
  4923. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  4924. and "brief" in (d.get("message") or "").lower()
  4925. for d in brief_directives),
  4926. "an empty brief rejects")
  4927. # Start: planning + the goal-run internal task.
  4928. act(auth, state["start"], {})
  4929. state = goal_state(goal1)
  4930. check(state["status"] == "planning" and state.get("start") is None,
  4931. "start moves the goal to planning")
  4932. conn = db()
  4933. run_row = conn.execute(
  4934. "select id, kind, mode, creator, goal_id, priority, status from tasks"
  4935. " where goal_id = ? and kind = 'goal_run'", (goal1,)).fetchone()
  4936. conn.close()
  4937. check(run_row is not None and run_row[1] == "goal_run"
  4938. and run_row[2] == "orchestrate" and run_row[3] == "goal"
  4939. and run_row[4] == goal1 and run_row[5] == 3
  4940. and run_row[6] in ("queued", "assigned", "working"),
  4941. "start creates the goal-run task (orchestrate, priority 3, creator goal,"
  4942. " queued)")
  4943. run_task = int(run_row[0])
  4944. check(goal_state(goal1)["run_task_id"] == run_task,
  4945. "the goal state carries the run task id")
  4946. check(any(e["kind"] == "started" for e in goal_state(goal1)["events"]),
  4947. "the narrative records the start")
  4948. print("== feedback: goal-agent runs are hidden from every task listing ==")
  4949. # The internal run task never lists anywhere tasks are browsed —
  4950. # only the goal page exposes it (worker tasks stay listed). The
  4951. # plan script is armed BEFORE the first dispatch so this section's
  4952. # waits never consume the round the plan-review flow below needs.
  4953. fake.goal_script = [("plan", "# Plan v1\n\n1. Add tests\n2. Ship")]
  4954. check(wait_for(lambda: task_state(auth, run_task)["status"]
  4955. in ("assigned", "working") or False,
  4956. timeout=60, what="run task dispatches") is not None,
  4957. "the run task reaches its saddle")
  4958. queue_rows = slot_public(auth, "/tasks", "tasks")["tasks"]
  4959. check(all(int(t["id"]) != run_task for t in queue_rows),
  4960. "the tasks queue never lists the goal-agent run task")
  4961. check(all(t["kind"] != "goal_run" for t in queue_rows),
  4962. "no goal_run rows leak into the queue at all")
  4963. project_state = slot_public(auth, "/projects/1", "project")
  4964. check(all(int(t["id"]) != run_task for t in project_state["tasks"]),
  4965. "the project page's task list excludes the run task")
  4966. dashboard = slot_public(auth, "/", "dashboard")
  4967. check(all(int(a["id"]) != run_task for a in dashboard["active_tasks"]),
  4968. "the dashboard's active tasks exclude the run task")
  4969. check(all(int(i["task_id"]) != run_task for i in dashboard["activity"]),
  4970. "the activity timeline never references the run task")
  4971. check(wait_for(lambda: int(next(
  4972. (s for s in slot_public(auth, "/", "dashboard")["saddles"]
  4973. if s["name"] == "fake-saddle"), {})
  4974. .get("current_goal_id") or 0) == goal1 or False,
  4975. timeout=30, what="saddle card links the goal") is not None,
  4976. "a saddle hosting the goal agent reads as supervising the goal")
  4977. fake_dash_card = next(s for s in slot_public(auth, "/", "dashboard")["saddles"]
  4978. if s["name"] == "fake-saddle")
  4979. check(fake_dash_card["current_goal_title"] == "Ship the flange",
  4980. "the supervision link carries the goal title")
  4981. print("== plan 12: the goal agent plans, plan review, revisions ==")
  4982. # (The plan script was armed before the run's first dispatch — see
  4983. # the listing-hiding section above — so the first round submits it.)
  4984. check(wait_for(lambda: goal_state(goal1)["status"] == "plan_review" or False,
  4985. timeout=60, what="goal agent submits its plan") is not None,
  4986. "the goal agent's plan push enters plan review")
  4987. state = goal_state(goal1)
  4988. check(task_state(auth, run_task)["status"] == "blocked",
  4989. "the goal-run task parks on the plan review")
  4990. pending = state.get("plan_pending_block")
  4991. check(pending and "# Plan v1" in (pending.get("body") or ""),
  4992. "the pending plan review carries the submitted markdown")
  4993. check(any(b["block_type"] == "plan" and b["is_plan_review"]
  4994. for b in state["blocks"]),
  4995. "the goal blocks list carries the pending plan block")
  4996. print("== feedback: goal visual identity ==")
  4997. # A goal never reads as a task at a glance: marked nav entry,
  4998. # iconed list page, and the dashboard pile's goal cards carry
  4999. # their own accent styling.
  5000. home_html = http_get_page(auth, "/")
  5001. check('class="nav-goal"' in home_html and "&#127919;" in home_html,
  5002. "the nav carries the marked 🎯 Goals entry beside Tasks")
  5003. check(any(p["item_type"] == "goal" for p in
  5004. slot_public(auth, "/", "dashboard")["pinned"]),
  5005. "the goal's pending block pins onto the dashboard pile")
  5006. check("'card goal-card'" in home_html and 'badge-kind-goal' in home_html,
  5007. "dashboard goal cards carry the distinct goal styling")
  5008. goals_html = http_get_page(auth, "/goals")
  5009. check("&#127919;" in goals_html and "goal-icon" in goals_html,
  5010. "the goals list page carries the goal icon")
  5011. goal_page_html = http_get_page(auth, "/goals/%d" % goal1)
  5012. check('class="card goal-head"' in goal_page_html and "goal-page" in goal_page_html,
  5013. "the goal page carries the goal-accented identity chrome")
  5014. # Reject with feedback: the agent revises.
  5015. fake.goal_script = [("plan", "# Plan v2\n\n1. Add tests\n2. Add docs\n3. Ship")]
  5016. reject_resume_index = len(fake.goal_assignments)
  5017. act(auth, pending["answer_action"], {"answer": "Add documentation please"})
  5018. check(wait_for(lambda: goal_state(goal1)["status"] == "plan_review" or False,
  5019. timeout=60, what="revised plan enters review") is not None,
  5020. "feedback sends the agent back to planning; the revision re-enters review")
  5021. # The rejection resume carried NO context_update (nothing in the
  5022. # instruction context had changed).
  5023. check(all("context_update" not in p
  5024. for p in fake.goal_assignments[reject_resume_index:]),
  5025. "a resume without context changes carries no context_update")
  5026. state = goal_state(goal1)
  5027. revisions = state["plan_revisions"]
  5028. check(len(revisions) == 2
  5029. and revisions[0]["answered"] and "Add documentation please" in revisions[0]["answer"]
  5030. and not revisions[1]["answered"],
  5031. "rejected revisions stay as answered history (historical-blocks data)")
  5032. # Approve: goal.plan = v2, status active, agent resumes and parks.
  5033. fake.goal_script = [("suspend",)]
  5034. pending = state["plan_pending_block"]
  5035. act(auth, pending["answer_action"],
  5036. {"answer": "Plan approved. Proceed with implementation."})
  5037. check(wait_for(lambda: goal_state(goal1)["status"] == "active" or False,
  5038. timeout=60, what="approved plan activates the goal") is not None,
  5039. "approving the plan activates the goal")
  5040. state = goal_state(goal1)
  5041. check("# Plan v2" in state["plan"], "the approved plan markdown is stored on the goal")
  5042. # The approval resume carries the plan delta as a context_update
  5043. # turn (the prompt-cache-friendly replacement for the daemon's
  5044. # old system-prompt refresh).
  5045. check(wait_for(lambda: len(fake.goal_assignments) > 0 and
  5046. "context_update" in fake.goal_assignments[-1] or False,
  5047. timeout=30, what="approval resume carries context_update") is not None,
  5048. "the plan-approval resume carries a context_update turn")
  5049. approval_update = fake.goal_assignments[-1]["context_update"]
  5050. check("Plan approved" in approval_update and "# Plan v2" in approval_update,
  5051. "the context_update summarises the approved plan markdown")
  5052. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5053. or False, timeout=60, what="goal agent parks after approval") is not None,
  5054. "the resumed goal agent parks (saddle suspend)")
  5055. print("== plan 12: task fan-out via the task CLI callbacks ==")
  5056. # The goal agent (parked, open session on its saddle) creates,
  5057. # enqueues and deletes its tasks through /api/saddle/task/*.
  5058. conn = db()
  5059. agent_session = conn.execute(
  5060. "select id from sessions where task_id = ? and ended_at is null",
  5061. (run_task,)).fetchone()[0]
  5062. conn.close()
  5063. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5064. "session_id": agent_session, "title": "Flange tests",
  5065. "mandate": "Write the test suite for the flange module.",
  5066. "mode": "test"})
  5067. check(status == 200 and body.get("ok") is True,
  5068. "task create under the goal succeeds (%s)" % body.get("error"))
  5069. fan_task = int(body["task_id"])
  5070. detail = task_state(auth, fan_task)
  5071. check(detail["status"] == "draft" and detail["mode"] == "test"
  5072. and detail["creator"] == "goal" and detail.get("goal_id") == goal1,
  5073. "the created task is a draft goal task with its mode and creator")
  5074. check(detail["task_branch"] == "task/%d-%d" % (goal1, fan_task)
  5075. and detail["branch_from"] == "goal/flange",
  5076. "goal worker tasks get ephemeral branches cut from the goal branch")
  5077. check(any(e["kind"] == "task-created" and int(e["task_id"]) == fan_task
  5078. for e in goal_state(goal1)["events"]),
  5079. "the narrative records the agent's task creation")
  5080. # Draft until the agent enqueues; humans may not (creator-only).
  5081. check(detail.get("enqueue") is None,
  5082. "the human Enqueue action is not offered for goal tasks (creator-only)")
  5083. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  5084. "session_id": agent_session, "task_id": fan_task})
  5085. check(status == 200 and task_state(auth, fan_task)["status"] == "queued",
  5086. "task enqueue by the goal agent queues the draft")
  5087. # Ownership + shape errors, verbatim for the CLI.
  5088. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  5089. "session_id": agent_session, "task_id": 999999})
  5090. check(status == 400 and "No task exists" in (body.get("error") or ""),
  5091. "enqueue of a missing task errors verbatim")
  5092. create_queued(auth, {"project_id": "1", "title": "Innocent bystander", "priority": "4"})
  5093. bystander = task_id_of("Innocent bystander")
  5094. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  5095. "session_id": agent_session, "task_id": bystander})
  5096. check(status == 400 and "does not belong to your goal" in (body.get("error") or ""),
  5097. "the goal agent cannot touch tasks outside its goal")
  5098. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5099. "session_id": agent_session, "title": "Bad mode", "mandate": "m", "mode": "party"})
  5100. check(status == 400 and "valid modes" in (body.get("error") or ""),
  5101. "an unknown mode rejects with the valid list")
  5102. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5103. "session_id": agent_session, "title": "Bad tag", "mandate": "m",
  5104. "capabilities": ["warp-drive"]})
  5105. check(status == 400 and "warp-drive" in (body.get("error") or "")
  5106. and "valid tags" in (body.get("error") or ""),
  5107. "an unknown capability tag rejects naming the valid set")
  5108. # A plain task's session is not a goal-agent identity.
  5109. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token,
  5110. {"session_id": 999999, "title": "x", "mandate": "m"})
  5111. check(status == 400 and "session" in (body.get("error") or ""),
  5112. "an unknown session_id errors verbatim")
  5113. # Delete: draft + owned.
  5114. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5115. "session_id": agent_session, "title": "Scratch task", "mandate": "m"})
  5116. scratch = int(body["task_id"])
  5117. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  5118. "session_id": agent_session, "task_id": scratch})
  5119. check(status == 200 and not any(
  5120. t["id"] == scratch for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5121. "task delete removes the owned draft")
  5122. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  5123. "session_id": agent_session, "task_id": fan_task})
  5124. check(status == 400 and "draft" in (body.get("error") or ""),
  5125. "deleting a queued task refuses (draft only)")
  5126. print("== plan 12: goal context in the worker assignment + coalesced resume ==")
  5127. # The queued fan-out task dispatches to the daemon with the goal
  5128. # reference + ephemeral branch; its completion schedules the parked
  5129. # goal agent's resume (>= SADDLE_GOAL_RESUME_S after the event).
  5130. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == fan_task
  5131. for p in fake.start_payloads) or False,
  5132. timeout=60, what="fan-out task dispatches") is not None,
  5133. "the goal worker task dispatches")
  5134. fan_payload = [p for p in fake.start_payloads
  5135. if int(p.get("task", {}).get("id") or 0) == fan_task][-1]
  5136. goal_ctx = fan_payload.get("goal") or {}
  5137. check(goal_ctx.get("id") == goal1 and goal_ctx.get("branch") == "goal/flange"
  5138. and goal_ctx.get("base_branch") == "main"
  5139. and "flange module" in goal_ctx.get("brief", "")
  5140. and "# Plan v2" in goal_ctx.get("plan", ""),
  5141. "the worker assignment carries the goal context (read-only brief + plan)")
  5142. check(fan_payload.get("ephemeral_branch") == "task/%d-%d" % (goal1, fan_task)
  5143. and fan_payload.get("kind") == "task" and fan_payload.get("mode") == "test"
  5144. and fan_payload.get("creator") == "goal",
  5145. "the worker assignment carries the ephemeral branch + identity triplet")
  5146. check(wait_task_done(auth, fan_task, timeout=60) is not None,
  5147. "the goal worker task completes")
  5148. check(any(e["kind"] == "task-done" and int(e["task_id"]) == fan_task
  5149. for e in goal_state(goal1)["events"]),
  5150. "the narrative records the task's completion")
  5151. goal_runs_before = len(fake.goal_assignments)
  5152. check(wait_for(lambda: len(fake.goal_assignments) > goal_runs_before or False,
  5153. timeout=30, what="parked goal agent resumes") is not None,
  5154. "the task-terminal event resumes the parked goal agent")
  5155. resume_payload = fake.goal_assignments[-1]
  5156. notice = resume_payload.get("resume_notice") or ""
  5157. check("Task statuses" in notice and "Flange tests" in notice
  5158. and "done" in notice,
  5159. "the resume notice batches ALL plan task statuses")
  5160. check("New completion reports" in notice and "fake daemon finished" in notice,
  5161. "the resume notice carries the new completion report")
  5162. check("context_update" not in resume_payload,
  5163. "a later resume with no context changes omits context_update entirely")
  5164. check(resume_payload.get("kind") == "goal_run"
  5165. and resume_payload.get("mode") == "orchestrate",
  5166. "the resumed goal agent carries its identity triplet")
  5167. # The resumed agent parked again (script): two events at once must
  5168. # coalesce into ONE resume within the window.
  5169. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5170. or False, timeout=60, what="goal agent re-parks") is not None,
  5171. "the resumed goal agent parks again")
  5172. print("== feedback: goal page parity — progress feed, current activity, runs ==")
  5173. # The goal agent's runs feed the page's live surfaces: progress
  5174. # lines (green latest-first feed), the open round's newest
  5175. # activity line and its hosting saddle. Parked runs keep their
  5176. # open session, so fixtures land as rows without disturbing the
  5177. # scripted daemon.
  5178. conn = db()
  5179. open_run_session = conn.execute(
  5180. "select id from sessions where task_id = ? and ended_at is null",
  5181. (run_task,)).fetchone()[0]
  5182. conn.execute(
  5183. "insert into task_progress (task_id, summary, created_at)"
  5184. " values (?, 'Overseeing the flange fan-out', strftime('%s','now'))",
  5185. (run_task,))
  5186. conn.execute(
  5187. "insert into session_commands (session_id, command_text, type, started_at)"
  5188. " values (?, 'git -C demo log --oneline -5', 'command',"
  5189. " strftime('%s','now'))", (open_run_session,))
  5190. conn.commit()
  5191. conn.close()
  5192. # A manual refresh records the daemon's health snapshot (the
  5193. # parked daemon answers /status with its suspended state).
  5194. act(auth, saddle_card(auth, "fake-saddle")["refresh"], {})
  5195. state = goal_state(goal1)
  5196. check(state["progress"] and state["progress"][0]["summary"]
  5197. == "Overseeing the flange fan-out",
  5198. "the goal page carries the agent's live progress feed")
  5199. check(state["current_command"] == "git -C demo log --oneline -5"
  5200. and state["current_command_running"] is True,
  5201. "the current activity shows the open round's running command")
  5202. check(state["agent_saddle"] == "fake-saddle"
  5203. and "fake-saddle" in state["saddle_health"],
  5204. "the assigned agent saddle and its health display")
  5205. check(state["runs"] and state["runs"][0]["saddle_name"] == "fake-saddle"
  5206. and "session_id=" in state["runs"][0]["terminal_url"],
  5207. "the run table carries host saddles and deep-linked terminals")
  5208. goal_page = http_get_page(auth, "/goals/%d" % goal1)
  5209. check('stm-markdown="goal.brief"' in goal_page
  5210. and 'stm-markdown="goal.plan"' in goal_page
  5211. and 'stm-markdown="comment.body"' in goal_page
  5212. and 'stm-markdown="event.text"' in goal_page
  5213. and 'stm-markdown="block.body"' in goal_page,
  5214. "every long-form goal body renders through stm-markdown")
  5215. check('stm-attribute.href="run.terminal_url" target="_blank" rel="noopener"' in goal_page,
  5216. "the run table's terminal links open in a new tab")
  5217. check("progress-latest" in goal_page and "Agent progress" in goal_page,
  5218. "the green progress feed renders on the goal page")
  5219. # Plan revision history keeps its verdicts (approved + rejected).
  5220. revisions = goal_state(goal1)["plan_revisions"]
  5221. check(revisions[0]["answered"] is True and revisions[0]["approved"] is False
  5222. and revisions[1]["approved"] is True,
  5223. "plan revision history badges approved and rejected verdicts")
  5224. print("== plan 12: pause freezes supervision; events coalesce on resume ==")
  5225. state = goal_state(goal1)
  5226. act(auth, state["pause"], {})
  5227. check(goal_state(goal1)["status"] == "paused"
  5228. and goal_state(goal1).get("resume") is not None,
  5229. "an active goal pauses and offers resume")
  5230. # Terminal events under a paused goal queue without waking anybody.
  5231. # (The real completion path — complete_task — records the goal's
  5232. # task-done narrative event; the resume machinery keys on exactly
  5233. # those terminal kinds, never on the agent's own enqueue narrative.)
  5234. conn = db()
  5235. conn.execute("insert into tasks (project_id, goal_id, kind, title, status, priority,"
  5236. " summary, completed_at, created_at) values (1, ?, 'task',"
  5237. " 'Quiet task', 'done', 5, 'finished while paused',"
  5238. " strftime('%s','now'), strftime('%s','now'))", (goal1,))
  5239. quiet_id = conn.execute("select max(id) from tasks").fetchone()[0]
  5240. conn.commit()
  5241. conn.close()
  5242. paused_runs = len(fake.goal_assignments)
  5243. check(quiet_window(quiet_seconds(),
  5244. lambda: len(fake.goal_assignments) == paused_runs,
  5245. "paused goal does not resume"),
  5246. "a paused goal's events queue without scheduling a resume")
  5247. state = goal_state(goal1)
  5248. act(auth, state["resume"], {})
  5249. check(goal_state(goal1)["status"] == "active",
  5250. "resume returns the goal to active")
  5251. check(wait_for(lambda: len(fake.goal_assignments) > paused_runs or False,
  5252. timeout=30, what="queued events flush on resume") is not None,
  5253. "the queued events coalesce into the post-resume wake")
  5254. check("finished while paused" in (fake.goal_assignments[-1].get("resume_notice") or ""),
  5255. "the flushed notice reports the task that finished while paused")
  5256. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5257. or False, timeout=60, what="goal agent parks again") is not None,
  5258. "the goal agent parks again after the flush")
  5259. # The watermark consumed the flushed transition: with nothing new
  5260. # under the goal, no further resume fires (parked stays parked).
  5261. flushed_assignments = len(fake.goal_assignments)
  5262. check(quiet_window(quiet_seconds(),
  5263. lambda: len(fake.goal_assignments) == flushed_assignments,
  5264. "consumed watermark never re-fires"),
  5265. "the consumed watermark never re-fires a resume")
  5266. print("== plan 12: completion review, push state, accept ==")
  5267. # The daemon exposes goal-branch push state on /status; the web
  5268. # caches it on the goal when it probes the goal agent's saddle.
  5269. def status_extra():
  5270. return None
  5271. fake.status_extra = {"goal_branches": [
  5272. {"branch": "goal/flange", "pushed": True},
  5273. {"branch": "goal/other-repo", "pushed": False}]}
  5274. fake_card = saddle_card(auth, "fake-saddle")
  5275. act(auth, fake_card["refresh"], {})
  5276. check(wait_for(lambda: goal_state(goal1).get("push_branches") or False,
  5277. timeout=30, what="push state lands on the goal") is not None,
  5278. "the daemon's /status goal_branches exposure caches on the goal")
  5279. branches = goal_state(goal1)["push_branches"]
  5280. check({(b["branch"], b["pushed"]) for b in branches}
  5281. == {("goal/flange", True), ("goal/other-repo", False)},
  5282. "the push state renders per branch")
  5283. # the daemon's real shape carries repo too — multi-repo rows stay
  5284. # distinguishable as "repo: branch" labels
  5285. fake.status_extra = {"goal_branches": [
  5286. {"repo": "repoa", "branch": "goal/flange", "pushed": True},
  5287. {"repo": "repob", "branch": "goal/flange", "pushed": False}]}
  5288. act(auth, fake_card["refresh"], {})
  5289. check(wait_for(lambda: {b["branch"] for b in goal_state(goal1).get("push_branches") or []}
  5290. >= {"repoa: goal/flange"}, timeout=30,
  5291. what="repo-qualified push state lands") is not None,
  5292. "repo-qualified goal_branches rows render as 'repo: branch'")
  5293. fake.status_extra = None
  5294. # `saddle done` in goal context: the completion review.
  5295. fake.goal_script = [("done", "# Completion\n\nThe flange ships.")]
  5296. # Wake the parked agent: a terminal transition newer than the
  5297. # watermark (the pause-flush consumed everything up to it, so arm
  5298. # one directly with a fresh row).
  5299. conn = db()
  5300. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  5301. " priority, completed_at, created_at) values (1, ?, 'task',"
  5302. " 'Warmup', 'done', 5,"
  5303. " strftime('%s','now'),"
  5304. " strftime('%s','now','-30 seconds'))", (goal1,))
  5305. conn.commit()
  5306. conn.close()
  5307. check(wait_for(lambda: goal_state(goal1)["status"] == "completion_review" or False,
  5308. timeout=60, what="goal agent submits its completion") is not None,
  5309. "`saddle done` in goal context enters completion review")
  5310. state = goal_state(goal1)
  5311. check("# Completion" in state["completion_report"]
  5312. and state["completion_pending"] is True
  5313. and state["completion_pending_block"] is not None
  5314. and state["completion_pending_block"] is not False,
  5315. "the completion review state carries the report + pending block")
  5316. check(task_state(auth, run_task)["status"] == "blocked",
  5317. "the goal-run task parks on the completion review")
  5318. check(state["compare_url"].endswith("/compare/main...goal/flange"),
  5319. "the completion review links the compare view")
  5320. # Reject first: feedback returns the goal to active.
  5321. fake.goal_script = [("suspend",)]
  5322. act(auth, state["completion_pending_block"]["answer_action"],
  5323. {"answer": "Not done — the docs are missing"})
  5324. check(wait_for(lambda: goal_state(goal1)["status"] == "active" or False,
  5325. timeout=30, what="rejected completion reactivates") is not None,
  5326. "rejecting the completion returns the goal to active")
  5327. # Round 2: submit again and accept.
  5328. fake.goal_script = [("done", "# Completion v2\n\nThe flange ships, with docs.")]
  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. " 'Warmup2', '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="resubmitted completion") is not None,
  5339. "the agent resubmits its completion after feedback")
  5340. state = goal_state(goal1)
  5341. act(auth, state["completion_pending_block"]["answer_action"],
  5342. {"answer": "Review approved. Continue with the task."})
  5343. check(wait_for(lambda: goal_state(goal1)["status"] == "complete" or False,
  5344. timeout=30, what="accepted completion completes") is not None,
  5345. "accepting the completion completes the goal")
  5346. state = goal_state(goal1)
  5347. check(state["terminal"] is True and state.get("cancel") is None
  5348. and "# Completion v2" in state["completion_report"],
  5349. "a complete goal is terminal with its report stored")
  5350. check(wait_for(lambda: task_state(auth, run_task)["status"] == "done" or False,
  5351. timeout=30, what="goal run task closes") is not None,
  5352. "approving the completion closes the goal-run task done")
  5353. print("== plan 15 C3: the narrative derives from the recorded shape ==")
  5354. # Content equivalence with the old projection on this run's exact
  5355. # shape: every kind the goal_events projection produced, keyed the
  5356. # same way, plus the watermark and no-ingest guarantees.
  5357. narrative = goal_state(goal1)["events"]
  5358. kinds = [e["kind"] for e in narrative]
  5359. for expected in ("created", "started", "plan-submitted", "plan-rejected",
  5360. "plan-approved", "task-created", "task-done",
  5361. "completion-submitted", "completion-rejected", "goal-approved"):
  5362. check(expected in kinds,
  5363. "the derived narrative carries the %s row" % expected)
  5364. check(all(k != "task-enqueued" and k != "resumed" and k != "retry" for k in kinds),
  5365. "timestamp-less bookkeeping kinds never return")
  5366. stamps = [e["at_display"] for e in narrative if e.get("at_display")]
  5367. check(stamps == sorted(stamps, reverse=True),
  5368. "the narrative reads newest first")
  5369. conn = db()
  5370. no_event_table = conn.execute(
  5371. "select count(*) from sqlite_master where type = 'table'"
  5372. " and name = 'goal_events'").fetchone()[0] == 0
  5373. conn.close()
  5374. check(no_event_table,
  5375. "the goal_events table is gone (no narrative rows on ingest)")
  5376. print("== plan 12: cancel cascades to the goal's tasks ==")
  5377. goal2 = create_goal({"project_id": "1", "title": "Doomed goal",
  5378. "brief": "This goal will be cancelled.",
  5379. "branch_name": "goal/doomed"})
  5380. fake.goal_script = [("suspend",)]
  5381. act(auth, goal_state(goal2)["start"], {})
  5382. conn = db()
  5383. run2 = conn.execute("select id from tasks where goal_id = ? and kind = 'goal_run'",
  5384. (goal2,)).fetchone()[0]
  5385. conn.close()
  5386. check(wait_for(lambda: task_state(auth, run2)["status"] == "suspended" or False,
  5387. timeout=60, what="doomed goal agent parks") is not None,
  5388. "the doomed goal's agent parks")
  5389. conn = db()
  5390. agent_session2 = conn.execute(
  5391. "select id from sessions where task_id = ? and ended_at is null",
  5392. (run2,)).fetchone()[0]
  5393. conn.close()
  5394. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5395. "session_id": agent_session2, "title": "Doomed draft", "mandate": "m"})
  5396. doomed_draft = int(body["task_id"])
  5397. doomed_queued_task = None
  5398. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5399. "session_id": agent_session2, "title": "Doomed runner", "mandate": "m"})
  5400. doomed_runner = int(body["task_id"])
  5401. saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  5402. {"session_id": agent_session2, "task_id": doomed_runner})
  5403. act(auth, goal_state(goal2)["cancel"], {})
  5404. check(goal_state(goal2)["status"] == "cancelled",
  5405. "the goal cancels from active (parked-agent) state")
  5406. check(task_state(auth, run2)["status"] == "failed",
  5407. "the cascade cancels the goal agent's run task")
  5408. check(wait_for(lambda: task_state(auth, doomed_runner)["status"] == "failed"
  5409. or False, timeout=30, what="cascade cancels the queued task") is not None,
  5410. "the cascade cancels the goal's queued task")
  5411. check(not any(t["id"] == doomed_draft
  5412. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5413. "the cascade deletes the goal's draft tasks")
  5414. # A cancelled goal frees its branch name.
  5415. reuse = create_goal({"project_id": "1", "title": "Reused name",
  5416. "brief": "b", "branch_name": "goal/doomed"})
  5417. check(reuse > goal2, "a cancelled goal's branch name is reusable")
  5418. print("== plan 13 B3: goal failure cascades to non-terminal tasks ==")
  5419. # A goal holding a draft, a queued task and a working task: the
  5420. # agent's failure cascades like a cancellation — drafts deleted (no
  5421. # orphan stays dispatchable), queued/working cancelled — and the
  5422. # narrative records the cascade.
  5423. collapse = create_goal({"project_id": "1", "title": "Collapse goal",
  5424. "brief": "Fails with tasks in flight.",
  5425. "branch_name": "goal/collapse"})
  5426. fake.goal_script = [("suspend",)]
  5427. act(auth, goal_state(collapse)["start"], {})
  5428. conn = db()
  5429. run3 = conn.execute("select id from tasks where goal_id = ? and kind = 'goal_run'",
  5430. (collapse,)).fetchone()[0]
  5431. conn.close()
  5432. check(wait_for(lambda: task_state(auth, run3)["status"] == "suspended" or False,
  5433. timeout=60, what="collapse goal agent parks") is not None,
  5434. "the collapse goal's agent parks first")
  5435. conn = db()
  5436. run3_session = conn.execute(
  5437. "select id from sessions where task_id = ? and ended_at is null",
  5438. (run3,)).fetchone()[0]
  5439. conn.close()
  5440. def agent_task(title):
  5441. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5442. "session_id": run3_session, "title": title, "mandate": "m"})
  5443. task_id = int(body["task_id"])
  5444. saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  5445. {"session_id": run3_session, "task_id": task_id})
  5446. return task_id
  5447. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5448. "session_id": run3_session, "title": "Collapse draft", "mandate": "m"})
  5449. collapse_draft = int(body["task_id"]) # stays draft (never enqueued)
  5450. collapse_queued = agent_task("Collapse queued")
  5451. collapse_worker = agent_task("Collapse worker")
  5452. # Both queued tasks race for the one saddle; freeze the daemon the
  5453. # moment the first dispatches so one stays genuinely WORKING (and
  5454. # the other queued) when the goal fails.
  5455. fake.hold_state = True
  5456. def collapse_working():
  5457. for task_id in (collapse_queued, collapse_worker):
  5458. if task_state(auth, task_id)["status"] == "working":
  5459. return task_id
  5460. return False
  5461. running_one = wait_for(collapse_working, timeout=60, what="a collapse task works")
  5462. check(running_one is not None,
  5463. "a collapse task reaches working before the failure")
  5464. queued_one = collapse_worker if running_one == collapse_queued else collapse_queued
  5465. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5466. {"session_id": run3_session, "state": "failed",
  5467. "summary": "the foundation crumbled"})
  5468. check(status == 200 and goal_state(collapse)["status"] == "failed",
  5469. "the agent's failure fails the goal")
  5470. check(task_state(auth, run3)["status"] == "failed",
  5471. "the failure fails the goal agent's run task")
  5472. check(wait_for(lambda: task_state(auth, queued_one)["status"] == "failed"
  5473. and task_state(auth, running_one)["status"] == "failed" or False,
  5474. timeout=30, what="failure cascade settles") is not None,
  5475. "the failure cascade cancels the queued and working tasks")
  5476. check(not any(t["id"] == collapse_draft
  5477. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5478. "the failure cascade deletes the goal's draft tasks")
  5479. state = goal_state(collapse)
  5480. check(any(e["kind"] == "cascade" for e in state["events"]),
  5481. "the narrative records the failure cascade")
  5482. check(state["draft_tasks"] == 0 and state["queued_tasks"] == 0,
  5483. "nothing under the failed goal stays dispatchable (no orphan drafts)")
  5484. check(len([e for e in state["events"] if e["kind"] == "goal-failed"]) == 1,
  5485. "the failing goal records exactly one goal-failed event")
  5486. fake.hold_state = False
  5487. print("== plan 12: auto-enqueue-after for human tasks ==")
  5488. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5489. "project_id": "1", "title": "Predecessor task", "priority": "4"})
  5490. predecessor = task_id_of("Predecessor task")
  5491. enqueue_task(auth, predecessor)
  5492. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5493. "project_id": "1", "title": "Successor task", "priority": "4",
  5494. "enqueue_after_task_id": str(predecessor)})
  5495. successor = task_id_of("Successor task")
  5496. check(task_state(auth, successor)["status"] == "draft"
  5497. and task_state(auth, successor).get("enqueue_after_task_id") == predecessor,
  5498. "a human task can carry an auto-enqueue predecessor")
  5499. check(wait_task_done(auth, predecessor, timeout=60) is not None,
  5500. "the predecessor completes")
  5501. check(wait_for(lambda: task_state(auth, successor)["status"] in
  5502. ("queued", "assigned", "working") or False,
  5503. timeout=30, what="successor auto-enqueues") is not None,
  5504. "the done predecessor auto-enqueues its dependent")
  5505. # Cycle validation refuses a predecessor chain that loops.
  5506. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5507. "project_id": "1", "title": "Cycle A", "priority": "4"})
  5508. cycle_a = task_id_of("Cycle A")
  5509. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5510. "project_id": "1", "title": "Cycle B", "priority": "4",
  5511. "enqueue_after_task_id": str(cycle_a)})
  5512. cycle_b = task_id_of("Cycle B")
  5513. cycle_directives = act(auth, task_state(auth, cycle_a)["update"], {
  5514. "title": "Cycle A", "description": "x", "priority": "4",
  5515. "enqueue_after_task_id": str(cycle_b)})
  5516. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  5517. and "cycle" in (d.get("message") or "").lower()
  5518. for d in cycle_directives),
  5519. "a predecessor cycle rejects with a naming error")
  5520. # A failed predecessor leaves the dependent in draft.
  5521. fake.fail_next = True
  5522. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5523. "project_id": "1", "title": "Failing predecessor", "priority": "1"})
  5524. failing_pred = task_id_of("Failing predecessor")
  5525. enqueue_task(auth, failing_pred)
  5526. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5527. "project_id": "1", "title": "Stranded successor", "priority": "4",
  5528. "enqueue_after_task_id": str(failing_pred)})
  5529. stranded = task_id_of("Stranded successor")
  5530. check(wait_for(lambda: task_state(auth, failing_pred)["status"] == "failed"
  5531. or False, timeout=60, what="failing predecessor fails") is not None,
  5532. "the scripted-failure predecessor fails")
  5533. check(quiet_window(quiet_seconds(),
  5534. lambda: task_state(auth, stranded)["status"] == "draft",
  5535. "failed predecessor leaves the draft"),
  5536. "a failed predecessor leaves its dependent in draft")
  5537. # Successor cleanup: let the queued successor finish so the
  5538. # shard's app shuts down with an empty queue.
  5539. check(wait_task_done(auth, successor, timeout=90) is not None,
  5540. "the auto-enqueued successor completes")
  5541. print("== feedback: context_update carries rule/note deltas on resume ==")
  5542. # A standalone task parks on a question; while it is parked a rule
  5543. # is attached to the project and a note lands; the resuming
  5544. # assignment carries both as the context_update markdown turn.
  5545. probe_id = create_queued(auth, {"project_id": "1", "title": "Context probe",
  5546. "priority": "4"})
  5547. check(wait_for(lambda: fake.running_task == probe_id
  5548. and task_state(auth, probe_id)["status"] == "working" or False,
  5549. timeout=60, what="probe task runs") is not None,
  5550. "the probe task dispatches")
  5551. fake.set_state("blocked")
  5552. fake.push_results("blocked", block={"type": "question",
  5553. "question": "Which database dialect?"})
  5554. check(wait_for(lambda: task_state(auth, probe_id)["status"] == "blocked" or False,
  5555. timeout=60, what="probe task blocks") is not None,
  5556. "the probe task parks on its question")
  5557. detail = task_state(auth, probe_id)
  5558. open_block = [b for b in detail["blocks"] if not b["answered"]][0]
  5559. # Backdate the parked round's start: stamps are second-resolution
  5560. # epochs, and the delta compares strictly-later — the park must
  5561. # span a real interval like an operator's would.
  5562. conn = db()
  5563. conn.execute("update sessions set started_at = strftime('%s','now') - 60"
  5564. " where id = (select min(id) from sessions where task_id = ?)",
  5565. (probe_id,))
  5566. conn.commit()
  5567. conn.close()
  5568. # While parked: a new rule attached to the project + a new note.
  5569. rules_state = slot_public(auth, "/rules", "rules")
  5570. act(auth, rules_state["create"], {
  5571. "name": "Nightly gate", "body": "Every PR must pass the nightly suite before merge."})
  5572. conn = db()
  5573. rule_id = conn.execute("select id from rules where name = 'Nightly gate'").fetchone()[0]
  5574. conn.close()
  5575. act(auth, slot_public(auth, "/projects/1", "project")["attach_rule"],
  5576. {"rule_id": str(rule_id)})
  5577. conn = db()
  5578. conn.execute("insert into project_notes (project_id, body, created_at)"
  5579. " values (1, 'The demo repo moved its CI to nightly builds.',"
  5580. " strftime('%s','now'))")
  5581. conn.commit()
  5582. check(conn.execute("select count(*) from rule_projects where rule_id = ?",
  5583. (rule_id,)).fetchone()[0] == 1,
  5584. "the rule attaches to the project while the task is parked")
  5585. conn.close()
  5586. probe_assignments = len([p for p in fake.start_payloads
  5587. if int(p.get("task", {}).get("id") or 0) == probe_id])
  5588. act(auth, open_block["answer_action"], {"answer": "postgres"})
  5589. check(wait_for(lambda: len([p for p in fake.start_payloads
  5590. if int(p.get("task", {}).get("id") or 0) == probe_id])
  5591. > probe_assignments or False, timeout=60,
  5592. what="probe task resumes") is not None,
  5593. "answering the block resumes the probe task")
  5594. probe_resume = [p for p in fake.start_payloads
  5595. if int(p.get("task", {}).get("id") or 0) == probe_id][-1]
  5596. delta = probe_resume.get("context_update") or ""
  5597. check("Rules changed" in delta and "Nightly gate" in delta
  5598. and "nightly suite" in delta,
  5599. "the resume's context_update summarises the newly attached rule")
  5600. check("New project notes" in delta and "nightly builds" in delta,
  5601. "the resume's context_update summarises the new project note")
  5602. check("Plan approved" not in delta,
  5603. "standalone resumes carry no plan section")
  5604. check(wait_task_done(auth, probe_id, timeout=60) is not None,
  5605. "the probe task completes after its resume")
  5606. # =============================================================================
  5607. # Bundle: replay — plan 13 B1/B2: the daemon-global entry dedup and the
  5608. # idempotent terminal/narrative projections. Replays the live-failure
  5609. # post-mortem shapes directly against the push channels: an outbox
  5610. # redelivery arriving under the WRONG session id after churn (and after
  5611. # a web restart), and repeated failure pushes that must still project
  5612. # exactly once. Includes this shard's one deliberate app restart (the
  5613. # dedup must survive it — it is database state, not memory).
  5614. # =============================================================================
  5615. def bundle_replay(ctx):
  5616. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  5617. app = ctx.app
  5618. def rows_for(session):
  5619. conn = db()
  5620. try:
  5621. return conn.execute(
  5622. "select count(*) from session_commands where session_id = ?",
  5623. (session,)).fetchone()[0]
  5624. finally:
  5625. conn.close()
  5626. def dedup_rows():
  5627. conn = db()
  5628. try:
  5629. return conn.execute("select count(*) from saddle_entry_dedup").fetchone()[0]
  5630. finally:
  5631. conn.close()
  5632. def open_session_on_fake(task_id):
  5633. """A fixture open session row on the shard's saddle (the churn
  5634. shape: a fresh web-side run row the daemon never really drove)."""
  5635. conn = db()
  5636. try:
  5637. conn.execute(
  5638. "insert into sessions (task_id, saddle_id, started_at)"
  5639. " values (?, ?, strftime('%s','now'))", (task_id, fake_id))
  5640. conn.commit()
  5641. return conn.execute(
  5642. "select max(id) from sessions where task_id = ?",
  5643. (task_id,)).fetchone()[0]
  5644. finally:
  5645. conn.close()
  5646. print("== plan 13 B1: entry dedup is daemon-global, not per-session ==")
  5647. # A first task runs to completion; its session is the replay source.
  5648. first = create_queued(auth, {"project_id": "1", "title": "Replay source task",
  5649. "priority": "2"})
  5650. check(wait_task_done(auth, first, timeout=60) is not None,
  5651. "the replay-source task completes")
  5652. conn = db()
  5653. src_session = conn.execute(
  5654. "select max(id) from sessions where task_id = ?", (first,)).fetchone()[0]
  5655. conn.close()
  5656. # The outbox batch: two command entries the daemon already
  5657. # delivered once (their ids landed with the source session).
  5658. burst = [
  5659. {"id": 5001, "command": "make test", "output": "ok", "exit_code": 0,
  5660. "type": "command", "timestamp": "2026-09-11T00:00:00Z"},
  5661. {"id": 5002, "command": "grep -r flange src/", "output": "src/flange.vala",
  5662. "exit_code": 0, "type": "command", "timestamp": "2026-09-11T00:00:01Z"},
  5663. ]
  5664. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5665. {"session_id": src_session, "state": "done",
  5666. "entries": burst})
  5667. check(status == 200 and rows_for(src_session) >= 2,
  5668. "the entries batch stores under its session")
  5669. stored_once = rows_for(src_session)
  5670. dedup_after_first = dedup_rows()
  5671. # Redelivery under the SAME session: consumed, nothing new.
  5672. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5673. {"session_id": src_session, "state": "done",
  5674. "entries": burst})
  5675. check(status == 200 and rows_for(src_session) == stored_once
  5676. and dedup_rows() == dedup_after_first,
  5677. "a same-session redelivery stores nothing new (consumed silently)")
  5678. # Session churn: a brand-new session id on the same saddle replays
  5679. # the SAME entry ids — the post-mortem's mis-keyed outbox send.
  5680. # The entries' ids already populated another session, so the push
  5681. # may not create rows here either.
  5682. conn = db()
  5683. conn.execute(
  5684. "insert into tasks (project_id, title, status, priority, created_at,"
  5685. " completed_at) values (1, 'Churn target task', 'done', 5,"
  5686. " strftime('%s','now'), strftime('%s','now'))")
  5687. conn.commit()
  5688. churn_task = conn.execute(
  5689. "select max(id) from tasks where title = 'Churn target task'").fetchone()[0]
  5690. conn.close()
  5691. churn_session = open_session_on_fake(churn_task)
  5692. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5693. {"session_id": churn_session, "state": "done",
  5694. "entries": burst})
  5695. check(status == 200 and rows_for(churn_session) == 0,
  5696. "replay-under-wrong-session stores nothing new (daemon-global dedup)")
  5697. check(dedup_rows() == dedup_after_first,
  5698. "the consumed redelivery claims no fresh dedup rows")
  5699. # A fresh entry id under the churned session DOES store — the dedup
  5700. # keys on the entry id, never on the session.
  5701. fresh = [{"id": 5003, "command": "git status", "output": "clean",
  5702. "exit_code": 0, "type": "command", "timestamp": "2026-09-11T00:00:02Z"}]
  5703. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5704. {"session_id": churn_session, "state": "done",
  5705. "entries": fresh})
  5706. check(status == 200 and rows_for(churn_session) == 1
  5707. and dedup_rows() == dedup_after_first + 1,
  5708. "a fresh entry id stores under any session of its saddle")
  5709. # Web restart: the dedup survives (database state, not memory).
  5710. app.terminate()
  5711. app.wait(timeout=10)
  5712. app = start_app()
  5713. auth = login("admin", "adminpass123")
  5714. ctx.app = app # teardown tracks the restarted process
  5715. ctx.auth = auth
  5716. # The restart wiped the in-memory ask bookkeeping; the daemon
  5717. # re-establishes sleeping with a fresh ask (the real daemon's
  5718. # idle-awake ask / 15-minute safety self-ask).
  5719. fake.ask_now()
  5720. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5721. {"session_id": churn_session, "state": "done",
  5722. "entries": burst + fresh})
  5723. check(status == 200 and rows_for(churn_session) == 1
  5724. and rows_for(src_session) == stored_once,
  5725. "a post-restart redelivery still stores nothing (dedup is persistent)")
  5726. print("== plan 13 B2: duplicate failed entries project once (task) ==")
  5727. # The post-mortem's honest burst: the same failure entry redelivered
  5728. # under a churned session AND a second, DISTINCT failure entry id
  5729. # in the same session — one transition, one comment, ever.
  5730. def agent_comments(task_id, body=None):
  5731. conn = db()
  5732. try:
  5733. if body is None:
  5734. return conn.execute(
  5735. "select count(*) from task_comments"
  5736. " where task_id = ? and author = 'agent'",
  5737. (task_id,)).fetchone()[0]
  5738. return conn.execute(
  5739. "select count(*) from task_comments"
  5740. " where task_id = ? and author = 'agent' and body = ?",
  5741. (task_id, body)).fetchone()[0]
  5742. finally:
  5743. conn.close()
  5744. conn = db()
  5745. conn.execute(
  5746. "insert into tasks (project_id, title, status, priority, created_at)"
  5747. " values (1, 'Burst failure task', 'working', 5, strftime('%s','now'))")
  5748. conn.commit()
  5749. burst_task = conn.execute(
  5750. "select max(id) from tasks where title = 'Burst failure task'").fetchone()[0]
  5751. conn.close()
  5752. burst_session = open_session_on_fake(burst_task)
  5753. first_fail = [{"id": 6001, "command": "saddle failure",
  5754. "output": "bash -n rejected the script", "exit_code": 1,
  5755. "type": "failed", "timestamp": "2026-09-11T00:01:00Z"}]
  5756. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5757. {"session_id": burst_session, "state": "failed",
  5758. "entries": first_fail,
  5759. "summary": "bash -n rejected the script"})
  5760. check(status == 200
  5761. and task_state(auth, burst_task)["status"] == "failed",
  5762. "the failure entry + state pair fails the task")
  5763. check(agent_comments(burst_task, "bash -n rejected the script") == 1,
  5764. "the entry path and the state path together leave one failure comment")
  5765. # The burst: a DISTINCT failure entry id in the same session, plus
  5766. # both ids redelivered under a churned session — nothing re-runs.
  5767. second_fail = [{"id": 6002, "command": "saddle failure",
  5768. "output": "bash -n rejected the script", "exit_code": 1,
  5769. "type": "failed", "timestamp": "2026-09-11T00:01:01Z"}]
  5770. churned_burst = open_session_on_fake(burst_task)
  5771. for target in (burst_session, churned_burst):
  5772. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5773. {"session_id": target, "state": "failed",
  5774. "entries": first_fail + second_fail,
  5775. "summary": "bash -n rejected the script"})
  5776. check(status == 200,
  5777. "the burst push under %s is consumed, not rejected" % (
  5778. "its session" if target == burst_session else "a churned session"))
  5779. check(task_state(auth, burst_task)["status"] == "failed"
  5780. and agent_comments(burst_task) == 1,
  5781. "duplicate failed entries leave one transition and one comment")
  5782. print("== plan 13 B2: goal failure projects once ==")
  5783. # Goal context: `saddle failure` fails the goal ONCE — the 115
  5784. # goal-failed events of the live failure are structurally gone.
  5785. def goal_state(goal_id):
  5786. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  5787. def goal_failed_events(goal_id):
  5788. # Plan 15 C3: the narrative derives at read time — the
  5789. # failed-goal row IS the goal-failed record (one row, ever).
  5790. return len([e for e in goal_state(goal_id)["events"]
  5791. if e["kind"] == "goal-failed"])
  5792. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  5793. "project_id": "1", "title": "Burst goal", "brief": "Fails honestly.",
  5794. "branch_name": "goal/burst"})
  5795. conn = db()
  5796. burst_goal = conn.execute(
  5797. "select id from goals where title = 'Burst goal'").fetchone()[0]
  5798. conn.close()
  5799. fake.goal_script = [("suspend",)]
  5800. act(auth, goal_state(burst_goal)["start"], {})
  5801. conn = db()
  5802. run_task = conn.execute(
  5803. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  5804. (burst_goal,)).fetchone()[0]
  5805. conn.close()
  5806. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5807. or False, timeout=60, what="burst goal agent parks") is not None,
  5808. "the burst goal's agent parks first")
  5809. conn = db()
  5810. run_session = conn.execute(
  5811. "select id from sessions where task_id = ? and ended_at is null",
  5812. (run_task,)).fetchone()[0]
  5813. conn.close()
  5814. goal_fail = [{"id": 7001, "command": "saddle failure",
  5815. "output": "the harness collapsed", "exit_code": 1,
  5816. "type": "failed", "timestamp": "2026-09-11T00:02:00Z"},
  5817. {"id": 7002, "command": "saddle failure",
  5818. "output": "the harness collapsed", "exit_code": 1,
  5819. "type": "failed", "timestamp": "2026-09-11T00:02:01Z"}]
  5820. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5821. {"session_id": run_session, "state": "failed",
  5822. "entries": goal_fail, "summary": "the harness collapsed"})
  5823. check(status == 200 and goal_state(burst_goal)["status"] == "failed",
  5824. "the goal agent's failure fails the goal")
  5825. check(goal_failed_events(burst_goal) == 1,
  5826. "a two-entry failure burst records exactly one goal-failed event")
  5827. # Redeliveries — same ids under the run's session AND under a
  5828. # churned session — plus the bare failed state again: still one.
  5829. churned_run = open_session_on_fake(run_task)
  5830. for target in (run_session, churned_run):
  5831. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5832. {"session_id": target, "state": "failed",
  5833. "entries": goal_fail,
  5834. "summary": "the harness collapsed"})
  5835. check(status == 200, "the goal-failure redelivery under %s is consumed"
  5836. % ("its session" if target == run_session else "a churned session"))
  5837. check(goal_state(burst_goal)["status"] == "failed"
  5838. and goal_failed_events(burst_goal) == 1,
  5839. "redelivered failures never re-run the goal failure (one event, ever)")
  5840. check(task_state(auth, run_task)["status"] == "failed",
  5841. "the goal-run task stays failed after the replays")
  5842. conn = db()
  5843. burst_blocks = conn.execute(
  5844. "select count(*) from task_blocks where task_id = ?", (run_task,)
  5845. ).fetchone()[0]
  5846. conn.close()
  5847. check(burst_blocks == 0,
  5848. "the goal-failed path raises ZERO blocks (nothing pins the pile)")
  5849. print("== plan 13 B4: the comment projection stores the body ==")
  5850. # The heredoc shape: the command is the pipe invocation, the OUTPUT
  5851. # is the body. The projections must carry the body — the command
  5852. # echo never becomes comment text, and the literal `saddle
  5853. # comment` string never renders outside the terminal.
  5854. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  5855. "project_id": "1", "title": "Comment goal", "brief": "Reports cleanly.",
  5856. "branch_name": "goal/comment"})
  5857. conn = db()
  5858. comment_goal = conn.execute(
  5859. "select id from goals where title = 'Comment goal'").fetchone()[0]
  5860. conn.close()
  5861. fake.goal_script = [("suspend",)]
  5862. act(auth, goal_state(comment_goal)["start"], {})
  5863. conn = db()
  5864. comment_run = conn.execute(
  5865. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  5866. (comment_goal,)).fetchone()[0]
  5867. conn.close()
  5868. check(wait_for(lambda: task_state(auth, comment_run)["status"] == "suspended"
  5869. or False, timeout=60, what="comment goal agent parks") is not None,
  5870. "the comment goal's agent parks")
  5871. conn = db()
  5872. comment_session = conn.execute(
  5873. "select id from sessions where task_id = ? and ended_at is null",
  5874. (comment_run,)).fetchone()[0]
  5875. conn.close()
  5876. comment_body = "The flange weld holds. First sentence carries the information."
  5877. comment_entry = [{"id": 8001, "command": "cat << 'EOF' | saddle comment",
  5878. "output": comment_body, "exit_code": 0, "type": "comment",
  5879. "timestamp": "2026-09-11T00:03:00Z"}]
  5880. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5881. {"session_id": comment_session, "state": "suspended",
  5882. "entries": comment_entry})
  5883. check(status == 200, "the comment entry push is accepted")
  5884. conn = db()
  5885. task_comment_bodies = [r[0] for r in conn.execute(
  5886. "select body from task_comments where task_id = ?", (comment_run,))]
  5887. tables = {r[0] for r in conn.execute(
  5888. "select name from sqlite_master where type = 'table'").fetchall()}
  5889. conn.close()
  5890. check(task_comment_bodies == [comment_body],
  5891. "the run task's comment stores the body, not the command echo")
  5892. check("goal_comments" not in tables,
  5893. "the goal_comments table is gone (the run task's rows are the thread)")
  5894. narrative_comments = [e["text"] for e in goal_state(comment_goal)["events"]
  5895. if e["kind"] == "comment"]
  5896. check(len(narrative_comments) == 1
  5897. and narrative_comments[0].startswith("The flange weld holds.")
  5898. and "saddle comment" not in narrative_comments[0]
  5899. and "EOF" not in narrative_comments[0],
  5900. "the derived narrative's comment rows carry the body text")
  5901. state = goal_state(comment_goal)
  5902. check(state["current_command"] == comment_body,
  5903. "the goal page's current-activity line shows the comment body")
  5904. check(state["comments"] and state["comments"][0]["body"] == comment_body
  5905. and any(e["kind"] == "comment"
  5906. and e["text"].startswith("The flange weld holds.")
  5907. for e in state["events"]),
  5908. "the goal slot carries the body in its comments and narrative")
  5909. page = http_get_page(auth, "/goals/%d" % comment_goal)
  5910. check("saddle comment" not in page,
  5911. "the rendered goal page never shows the command echo")
  5912. check("event.kind == 'comment' ? ' footnote'" in page,
  5913. "the narrative's comment events render with footnote styling")
  5914. check(page.index('stm-markdown="comment.body"')
  5915. < page.index('stm-text="comment.quote"'),
  5916. "the comment card shows the body before the quote")
  5917. # Drain: nothing queued remains for the shard's shutdown.
  5918. check(queued_count() == 0, "the replay shard drains its queue")
  5919. def bundle_goalui(ctx):
  5920. """Plan 14 workstream B + plan 15 C1: the goal supervision surface.
  5921. B1 — goal-run control parity (Retry supervision / Requeue-to-resume
  5922. on the status head, the /tasks/<goal-run-id> redirect, no
  5923. notify-me toggle), B2 — the plan-review remarks queue, B4 —
  5924. sessions.resume_notice + the terminal dropdown/resume panel, B5 —
  5925. page order, effective rules and per-task capability badges, B6 —
  5926. narrative footnote weights. C1 — the single-row block world: the
  5927. goal's blocks ARE the run task's rows (answered from every
  5928. surface through one path; no dual rows, no stragglers, at most
  5929. one review-kind block per verdict path).
  5930. """
  5931. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  5932. def goal_state(goal_id):
  5933. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  5934. def run_task_of(goal_id):
  5935. conn = db()
  5936. try:
  5937. return int(conn.execute(
  5938. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  5939. (goal_id,)).fetchone()[0])
  5940. finally:
  5941. conn.close()
  5942. def wait_run(status, timeout=60, what="run status"):
  5943. return wait_for(lambda: task_state(auth, run_task_of(goal))["status"] == status
  5944. or False, timeout=timeout, what=what)
  5945. def pile_questions():
  5946. return [b.get("question") for b in
  5947. slot_public(auth, "/", "dashboard")["pinned"]
  5948. if b.get("item_type") == "goal"]
  5949. def open_session(task_id):
  5950. conn = db()
  5951. try:
  5952. row = conn.execute(
  5953. "select id from sessions where task_id = ? and ended_at is null",
  5954. (task_id,)).fetchone()
  5955. return int(row[0]) if row else None
  5956. finally:
  5957. conn.close()
  5958. print("== B1: the goal-run task page redirects to the goal ==")
  5959. fake.goal_script = [("plan", "# Remarks plan\n\n## Steps\n\n1. First move")]
  5960. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  5961. "project_id": "1", "title": "Goalui goal",
  5962. "brief": "Drive the plan-14 goal surface end to end.",
  5963. "branch_name": "goal/goalui"})
  5964. conn = db()
  5965. goal = conn.execute("select id from goals where title = 'Goalui goal'"
  5966. ).fetchone()[0]
  5967. conn.close()
  5968. act(auth, goal_state(goal)["start"], {})
  5969. wait_run("blocked", what="goalui goal agent parks on its plan") # plan review parks blocked
  5970. run_task = run_task_of(goal)
  5971. frames = directives("/tasks/%d" % run_task, auth)
  5972. navigations = [d for d in frames if d.get("type") == "navigate"]
  5973. check(any(d.get("uri") == "/goals/%d" % goal for d in navigations),
  5974. "the goal-run task page redirects to /goals/<id> (navigate directive)")
  5975. check(slot_public(auth, "/tasks/%d" % run_task, "task")["id"] == run_task,
  5976. "the redirect still hydrates the task slot (sealed refresh + API readers)")
  5977. status, page = http("GET", "/tasks/%d" % run_task, headers={
  5978. "X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}, timeout=15)
  5979. check(status == 200, "the compiled goal-run page serves")
  5980. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5981. "project_id": "1", "title": "Goalui worker", "priority": "4",
  5982. "description": "A plain worker under no goal."})
  5983. conn = db()
  5984. worker = conn.execute("select id from tasks where title = 'Goalui worker'"
  5985. ).fetchone()[0]
  5986. conn.close()
  5987. check(not [d for d in directives("/tasks/%d" % worker, auth)
  5988. if d.get("type") == "navigate"],
  5989. "worker task pages render normally (no redirect)")
  5990. state = goal_state(goal)
  5991. check("toggle_notify" not in state and state.get("notify") is None,
  5992. "no notify-me toggle on the goal (goals notify unconditionally)")
  5993. goal_page = http_get_page(auth, "/goals/%d" % goal)
  5994. check("Notify me" not in goal_page and "toggle-notify" not in goal_page,
  5995. "the goal page template ships no notify control")
  5996. check(state["branch_name"] == "goal/goalui" and state["base_branch"] == "main"
  5997. and isinstance(state["push_branches"], list)
  5998. and state["priority"] == 3
  5999. and len(state["started_display"]) > 0
  6000. and len(state["agent_saddle"]) > 0,
  6001. "the status head carries the full field set (branch pair, chips list,"
  6002. " priority, timestamps, agent saddle)")
  6003. check("Retry supervision" in goal_page and "Requeue to resume" in goal_page,
  6004. "the status head ships the run-control parity buttons")
  6005. check("status-corner" not in goal_page and "goal complete" not in goal_page
  6006. and goal_page.count("badge-yeehaw") == 1,
  6007. "yeehaw is rows-only (no goal-head corner badge; the row badge remains)")
  6008. print("== B2: the plan-review remarks queue ==")
  6009. check(goal_state(goal)["status"] == "plan_review"
  6010. and goal_state(goal)["plan_pending_block"] is not None,
  6011. "the goal sits in plan review with a pending block")
  6012. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6013. review_at = goal_page.index("data-plan-review")
  6014. check(review_at > 0, "the plan review region is marked for the remarks queue")
  6015. check(goal_page.index('data-block-id="goal.plan_pending_block.id"') > 0,
  6016. "the queue keys on the pending goal block id")
  6017. body_at = goal_page.index('data-plan-body')
  6018. remarks_at = goal_page.index("data-plan-remarks")
  6019. check(body_at < remarks_at,
  6020. "the remarks queue renders at the bottom of the plan body")
  6021. for marker in ("data-plan-accept", "data-plan-toggle", "data-plan-submit",
  6022. "data-plan-remove", "plan-popover", "remarksByBlock"):
  6023. check(marker in goal_page, "the remarks queue ships %s" % marker)
  6024. check("(index + 1) + '. '" in goal_page,
  6025. "the rejection payload numbers every queued remark")
  6026. check("rejectOpenByBlock" in goal_page and "statum.afterEvaluate(syncPlanRemarks)" in goal_page,
  6027. "the queue survives pulse refreshes (maps outside statum re-renders)")
  6028. # The rejection payload exactly as the client composes it: the
  6029. # stable verdict wording, then each remark NUMBERED in queue order
  6030. # with its quote prefixed like a comment.
  6031. payload = ("Plan feedback received:\n\n"
  6032. "> ## Steps\n\n1. First move\n\n"
  6033. "1. Add a rollback step\n\n"
  6034. "2. Name the owner of the migration")
  6035. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  6036. {"answer": payload})
  6037. state = goal_state(goal)
  6038. check(state["status"] == "planning",
  6039. "the remarks rejection returns the agent to planning")
  6040. rejected = [r for r in state["plan_revisions"] if r.get("answered")]
  6041. check(any(r["answer"] == payload for r in rejected),
  6042. "the rejection carries the remarks verbatim, in order")
  6043. check(payload.index("1. Add a rollback step") < payload.index("2. Name the owner"),
  6044. "the numbering is queue-ordered")
  6045. print("== B4: resume_notice lands on the resumed session row ==")
  6046. fake.goal_script = [("question", "Which datastore?", ["SQLite", "Redis"])]
  6047. check(wait_for(lambda: goal_state(goal)["status"] == "planning" or False,
  6048. timeout=30, what="rejection observed") is not None,
  6049. "the agent revises")
  6050. # The parked plan agent resumes with the verdict; the next round
  6051. # raises the scripted question.
  6052. check(wait_for(lambda: any(b["question"] == "Which datastore?"
  6053. and not b.get("answered")
  6054. for b in goal_state(goal)["blocks"]) or False,
  6055. timeout=60, what="question raised") is not None,
  6056. "the resumed agent raises its question")
  6057. conn = db()
  6058. notices = dict(conn.execute(
  6059. "select id, resume_notice from sessions where task_id = ?", (run_task,)
  6060. ).fetchall())
  6061. conn.close()
  6062. resumed_ids = [i for i, text in notices.items() if text]
  6063. fresh_ids = [i for i, text in notices.items() if not text]
  6064. check(len(resumed_ids) >= 1 and any("Plan feedback received" in notices[i]
  6065. for i in resumed_ids),
  6066. "the resumed session stores the notice it was allocated")
  6067. check(min(notices) in fresh_ids,
  6068. "session 1 (the fresh opening round) carries no resume notice")
  6069. print("== C1: the single run-task row IS the goal's block ==")
  6070. check("Which datastore?" in pile_questions(),
  6071. "the open goal question pins onto the dashboard pile")
  6072. goal_rows = [b for b in goal_state(goal)["blocks"]
  6073. if b["question"] == "Which datastore?"]
  6074. run_rows = [b for b in task_state(auth, run_task)["blocks"]
  6075. if b["question"] == "Which datastore?"]
  6076. check(len(run_rows) == 1 and len(goal_rows) == 1
  6077. and int(run_rows[0]["id"]) == int(goal_rows[0]["id"]),
  6078. "the goal page and the run task read the SAME single row")
  6079. pile_card = [b for b in slot_public(auth, "/", "dashboard")["pinned"]
  6080. if b.get("question") == "Which datastore?"][0]
  6081. check(pile_card.get("item_type") == "goal"
  6082. and int(pile_card.get("goal_id") or 0) == goal
  6083. and int(pile_card.get("id") or 0) == int(run_rows[0]["id"])
  6084. and pile_card.get("goal_title") == "Goalui goal",
  6085. "the pile card is the run-task row styled as a goal item")
  6086. act(auth, [b for b in goal_state(goal)["blocks"]
  6087. if b["question"] == "Which datastore?" and not b.get("answered")]
  6088. [0]["answer_action"], {"option": "SQLite"})
  6089. conn = db()
  6090. unanswered = conn.execute(
  6091. "select count(*) from task_blocks where question = 'Which datastore?'"
  6092. " and answer is null").fetchone()[0]
  6093. conn.close()
  6094. check(unanswered == 0, "answering from the goal page closes the single row")
  6095. check("Which datastore?" not in pile_questions(),
  6096. "the answered row no longer pins the dashboard pile")
  6097. # The task-page deep link (the AnswerBlockAction API surface)
  6098. # answers the SAME row through the one goal path — there is no
  6099. # second row to sweep and no stale copy can survive.
  6100. conn = db()
  6101. conn.execute("insert into task_blocks (task_id, type, question, created_at)"
  6102. " values (?, 'question', 'Deep link probe?',"
  6103. " strftime('%s','now'))", (run_task,))
  6104. conn.commit()
  6105. conn.close()
  6106. check("Deep link probe?" in pile_questions(),
  6107. "the fixture row pins like any goal question")
  6108. deep_block = [b for b in task_state(auth, run_task)["blocks"]
  6109. if b["question"] == "Deep link probe?" and not b.get("answered")][0]
  6110. act(auth, deep_block["answer_action"], {"answer": "Answered via the deep link"})
  6111. conn = db()
  6112. answered_row = conn.execute(
  6113. "select answer from task_blocks where question = 'Deep link probe?'"
  6114. ).fetchone()[0]
  6115. tables = {r[0] for r in conn.execute(
  6116. "select name from sqlite_master where type = 'table'").fetchall()}
  6117. conn.close()
  6118. check(answered_row == "Answered via the deep link",
  6119. "the task-page deep link answers the same single row (the API path)")
  6120. check("Deep link probe?" not in pile_questions(),
  6121. "the deep-link answer closes the pile card too")
  6122. check("goal_blocks" not in tables,
  6123. "the goal_blocks table is gone (run-task blocks are canonical)")
  6124. print("== B4: the terminal session dropdown + resume-info panel ==")
  6125. fake.goal_script = [("suspend",)]
  6126. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6127. or False, timeout=60, what="agent parks suspended") is not None,
  6128. "the agent parks suspended for the requeue scenario")
  6129. terminal = slot_public(auth, "/tasks/%d/terminal" % run_task, "terminal")
  6130. ids = [int(s["id"]) for s in terminal["sessions"]]
  6131. check(ids == sorted(ids, reverse=True),
  6132. "the session dropdown lists newest-first")
  6133. check(int(terminal["session_id"]) == ids[0],
  6134. "the terminal still defaults to the latest session")
  6135. labels = {int(s["id"]): s["label"] for s in terminal["sessions"]}
  6136. check(all(label.startswith("Session #") for label in labels.values()),
  6137. "dropdown labels read 'Session #N — started <time>'")
  6138. # Recompute at the check point: the C1 answers above each
  6139. # resumed the agent too, so the earlier snapshot would go stale.
  6140. conn = db()
  6141. resumed_ids = [int(i) for (i, text) in conn.execute(
  6142. "select id, resume_notice from sessions where task_id = ?",
  6143. (run_task,)).fetchall() if text]
  6144. conn.close()
  6145. resumed_markers = [i for i in ids if "[resumed]" in labels[i]]
  6146. check(set(resumed_markers) == set(resumed_ids),
  6147. "the [resumed] marker rides exactly the notice-carrying sessions")
  6148. notices_by_id = {int(s["id"]): s.get("notice") or "" for s in terminal["sessions"]}
  6149. check("Opening brief" in notices_by_id[min(ids)]
  6150. and "Drive the plan-14 goal surface" in notices_by_id[min(ids)],
  6151. "session 1's panel shows the opening-brief framing (from the goal brief)")
  6152. check(any("Plan feedback received" in (notices_by_id[i] or "") for i in resumed_ids),
  6153. "a resumed session's panel shows the stored resume notice")
  6154. terminal_page = http_get_page(auth, "/tasks/%d/terminal" % run_task)
  6155. check('id="session-select"' in terminal_page
  6156. and "window.terminalPickSession" in terminal_page,
  6157. "the session picker is an options dropdown")
  6158. check('stm-markdown="window.terminalSessionNotice(terminal)"' in terminal_page,
  6159. "the panel renders the selected session's notice as markdown")
  6160. check("No opening brief or resume notice recorded" in terminal_page,
  6161. "the panel ships its graceful empty state")
  6162. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6163. check("resume-notice-panel" in css and "max-height: 200px" in css,
  6164. "the panel is a 200px vertical-scroll strip (stylesheet)")
  6165. print("== B1: requeue-to-resume from the goal head ==")
  6166. conn = db()
  6167. conn.execute("update saddles set status = 'offline' where id = ?", (fake_id,))
  6168. conn.commit()
  6169. conn.close()
  6170. check(wait_for(lambda: goal_state(goal).get("requeue_run") is not None
  6171. or False, timeout=30, what="requeue offered") is not None,
  6172. "a parked run on a dead saddle offers Requeue-to-resume")
  6173. state = goal_state(goal)
  6174. check(state.get("retry_run") is None,
  6175. "an active goal offers no Retry supervision")
  6176. open_before = open_session(run_task)
  6177. act(auth, state["requeue_run"], {})
  6178. check(task_state(auth, run_task)["status"] == "queued",
  6179. "the requeue returns the run to the queue")
  6180. check(wait_for(lambda: open_session(run_task) is None or False,
  6181. timeout=30, what="parked session closed") is not None,
  6182. "the requeue closed the parked session (restore-on-dispatch)")
  6183. conn = db()
  6184. conn.execute("update saddles set status = 'idle' where id = ?", (fake_id,))
  6185. conn.commit()
  6186. conn.close()
  6187. fake.goal_script = [("suspend",)]
  6188. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6189. or False, timeout=60, what="requeued run re-dispatches") is not None,
  6190. "the requeued run re-dispatches and re-parks")
  6191. fresh_session = open_session(run_task)
  6192. conn = db()
  6193. fresh_notice = conn.execute(
  6194. "select resume_notice from sessions where id = ?", (fresh_session,)
  6195. ).fetchone()[0]
  6196. conn.close()
  6197. check(fresh_notice is None,
  6198. "a requeue's fresh session carries no resume notice (empty panel state)")
  6199. print("== B1: Retry supervision revives a failed goal ==")
  6200. fake.push_results("failed", summary="the supervision collapsed (scripted)")
  6201. check(wait_for(lambda: goal_state(goal)["status"] == "failed" or False,
  6202. timeout=30, what="goal fails") is not None,
  6203. "the run's failure fails the goal")
  6204. check(wait_for(lambda: goal_state(goal).get("retry_run") is not None
  6205. or False, timeout=30, what="retry offered") is not None,
  6206. "a failed goal offers Retry supervision")
  6207. fake.goal_script = [("suspend",)]
  6208. act(auth, goal_state(goal)["retry_run"], {})
  6209. state = goal_state(goal)
  6210. check(state["status"] == "active",
  6211. "the retry revives supervision (goal back to active)")
  6212. check(task_state(auth, run_task)["status"] in ("queued", "assigned", "working",
  6213. "suspended", "blocked"),
  6214. "the retry re-offered the run task")
  6215. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6216. or False, timeout=60, what="retried supervision parks") is not None,
  6217. "the retried supervision dispatches and parks again")
  6218. state = goal_state(goal)
  6219. check(any(e["kind"] == "system" and "Supervision retried" in e["text"]
  6220. for e in state["events"]),
  6221. "the narrative records the supervision retry (a system row)")
  6222. print("== B5: order, effective rules, capability badges ==")
  6223. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6224. markers = [
  6225. ('class="card goal-head"', "status head"),
  6226. ("Agent progress", "progress"),
  6227. ("Current activity", "activity"),
  6228. ("Goal agent blocks", "attention blocks"),
  6229. ("<h3>Tasks</h3>", "tasks"),
  6230. ("Initial brief", "brief"),
  6231. ("Involved projects", "projects"),
  6232. ("<h3>Rules</h3>", "rules"),
  6233. ("<h3>Plan</h3>", "plan"),
  6234. ("Supervision narrative", "narrative"),
  6235. ("<h3>Comments</h3>", "comments"),
  6236. ("Goal agent runs", "runs"),
  6237. ]
  6238. positions = []
  6239. for marker, _ in markers:
  6240. check(marker in goal_page, "the goal page ships the %s section" % _)
  6241. positions.append(goal_page.index(marker))
  6242. check(positions == sorted(positions),
  6243. "the page reads status → attention → tasks → brief → rules → plan →"
  6244. " narrative → comments → runs (in order)")
  6245. rules_state = slot_public(auth, "/rules", "rules")
  6246. act(auth, rules_state["create"], {"name": "goalui-primary", "body": "Primary rule"})
  6247. act(auth, rules_state["create"], {"name": "goalui-codev", "body": "Co-dev rule"})
  6248. act(auth, rules_state["create"], {"name": "goalui-ref", "body": "Reference rule"})
  6249. conn = db()
  6250. rule_ids = {name: int(conn.execute("select id from rules where name = ?",
  6251. (name,)).fetchone()[0])
  6252. for name in ("goalui-primary", "goalui-codev", "goalui-ref")}
  6253. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  6254. " values (?, 1, strftime('%s','now'))", (rule_ids["goalui-primary"],))
  6255. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  6256. " values ('goalui-codev-project', 'https://example.com/g.git',"
  6257. " 'main', strftime('%s','now'))")
  6258. codev_project = conn.execute(
  6259. "select id from projects where name = 'goalui-codev-project'").fetchone()[0]
  6260. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  6261. " values ('goalui-ref-project', 'https://example.com/r.git',"
  6262. " 'main', strftime('%s','now'))")
  6263. ref_project = conn.execute(
  6264. "select id from projects where name = 'goalui-ref-project'").fetchone()[0]
  6265. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  6266. " values (?, ?, strftime('%s','now'))",
  6267. (rule_ids["goalui-codev"], codev_project))
  6268. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  6269. " values (?, ?, strftime('%s','now'))",
  6270. (rule_ids["goalui-ref"], ref_project))
  6271. conn.commit()
  6272. conn.close()
  6273. act(auth, goal_state(goal)["add_link"], {"linked_project_id": str(codev_project),
  6274. "relationship": "co-developed"})
  6275. act(auth, goal_state(goal)["add_link"], {"linked_project_id": str(ref_project),
  6276. "relationship": "reference"})
  6277. rule_names = [r["name"] for r in goal_state(goal)["rules"]]
  6278. check(rule_names == ["goalui-primary", "goalui-codev"],
  6279. "the Rules section lists the goal's effective set (primary then"
  6280. " co-developed; reference contributes nothing)")
  6281. act(auth, slot_public(auth, "/saddles", "saddles")["create_capability"],
  6282. {"name": "goalui-capability"})
  6283. conn = db()
  6284. capability = conn.execute(
  6285. "select id from capabilities where name = 'goalui-capability'"
  6286. ).fetchone()[0]
  6287. # The early redirect-fixture worker joins the goal (a fanned
  6288. # worker's shape) so its row carries the badge too.
  6289. conn.execute("update tasks set goal_id = ? where id = ?", (goal, worker))
  6290. conn.execute("insert into task_capabilities (task_id, capability_id)"
  6291. " values (?, ?)", (worker, capability))
  6292. conn.commit()
  6293. conn.close()
  6294. goal_worker = {"id": worker, "caps": None}
  6295. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  6296. "project_id": "1", "title": "Goalui fanned worker", "priority": "4",
  6297. "description": "A worker the agent fanned out."})
  6298. conn = db()
  6299. fanned = conn.execute(
  6300. "select id from tasks where title = 'Goalui fanned worker'").fetchone()[0]
  6301. conn.execute("update tasks set goal_id = ? where id = ?", (goal, fanned))
  6302. conn.execute("insert into task_capabilities (task_id, capability_id)"
  6303. " values (?, ?)", (fanned, capability))
  6304. conn.commit()
  6305. conn.close()
  6306. rows = {int(t["id"]): t for t in goal_state(goal)["goal_tasks"]}
  6307. check(rows[fanned].get("capabilities") == ["goalui-capability"]
  6308. and rows[worker].get("capabilities") == ["goalui-capability"],
  6309. "task rows carry their required capability tags")
  6310. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6311. check('stm-for-capability-in="goal_task.capabilities"' in goal_page
  6312. and "badge-capability" in goal_page,
  6313. "the task rows render capability badges")
  6314. print("== B6: narrative weights — events full, comments footnote ==")
  6315. # An AGENT comment projects the narrative's comment event (human
  6316. # comments only thread) — pushed through the entries channel while
  6317. # parked, so the suspended state stays put.
  6318. fake.push_results("suspended", entries=[{
  6319. "id": 9001, "command": "saddle comment", "output": "An agent aside.",
  6320. "exit_code": 0, "type": "comment", "timestamp": "2026-09-12T00:00:00Z"}])
  6321. check(wait_for(lambda: any(e["kind"] == "comment"
  6322. for e in goal_state(goal)["events"]) or False,
  6323. timeout=15, what="comment event lands") is not None,
  6324. "an agent comment lands as a narrative event")
  6325. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6326. check("stm-attribute.class=\"'goal-event' + (event.kind == 'comment'"
  6327. " ? ' footnote' : '')\"" in goal_page.replace("\n", " ").replace(" ", " ")
  6328. or "'goal-event' + (event.kind == 'comment' ? ' footnote' : '')" in goal_page,
  6329. "the WHOLE comment event row carries .footnote (badge included)")
  6330. check("'badge badge-goal-' + event.kind" in goal_page,
  6331. "non-comment events keep their full-weight kind badges")
  6332. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6333. check(".goal-event.footnote" in css and ".footnote {" in css,
  6334. "the stylesheet ships the footnote row weight beside the utility")
  6335. print("== C2: system rows render distinctly on the ONE thread ==")
  6336. run_comments = task_state(auth, run_task)["comments"]
  6337. system_rows = [c for c in run_comments if c.get("is_system")]
  6338. check(system_rows and all(c["author"] == "system" for c in system_rows)
  6339. and not any(c.get("from_agent") for c in system_rows),
  6340. "the harness bookkeeping rows are authored 'system' (never agent)")
  6341. goal_thread = goal_state(goal)["comments"]
  6342. check(any(c.get("is_system") for c in goal_thread),
  6343. "the goal page reads the same thread (the system rows included)")
  6344. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6345. check(".comment.system" in css and ".system-label" in css,
  6346. "the stylesheet ships the distinct system-event styling")
  6347. page = http_get_page(auth, "/goals/%d" % goal)
  6348. check("comment.is_system" in page and "system-label" in page,
  6349. "the goal page renders system rows with the labelled muted style")
  6350. task_page = http_get_page(auth, "/tasks/%d" % worker)
  6351. check("comment.is_system" in task_page and "system-label" in task_page,
  6352. "the task page renders system rows with the same style")
  6353. print("== C1: one review block per verdict path (F6) ==")
  6354. # The daemon's honest round pushes the ENTRY and the STATE
  6355. # together — the done pair must raise exactly ONE completion
  6356. # block, and a redelivered pair nothing more.
  6357. fake.goal_script = [("done", "# Completion\n\nOne block only.")]
  6358. conn = db()
  6359. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  6360. " priority, completed_at, created_at) values (1, ?, 'task',"
  6361. " 'Warmup', 'done', 5,"
  6362. " strftime('%s','now'),"
  6363. " strftime('%s','now','-30 seconds'))", (goal,))
  6364. conn.commit()
  6365. conn.close()
  6366. check(wait_for(lambda: goal_state(goal)["status"] == "completion_review" or False,
  6367. timeout=60, what="goalui completion review opens") is not None,
  6368. "the scripted done round enters completion review")
  6369. def completion_block_count():
  6370. conn = db()
  6371. try:
  6372. return conn.execute(
  6373. "select count(*) from task_blocks where task_id = ?"
  6374. " and type = 'completion'", (run_task,)).fetchone()[0]
  6375. finally:
  6376. conn.close()
  6377. check(completion_block_count() == 1,
  6378. "the done state raises exactly ONE completion block")
  6379. # The burst shape: the done ENTRY and the done STATE in one push
  6380. # (fresh entry ids), then the whole pair redelivered — the
  6381. # pending-report idempotency leaves the one row alone.
  6382. conn = db()
  6383. burst_session = conn.execute(
  6384. "select id from sessions where task_id = ? and ended_at is null",
  6385. (run_task,)).fetchone()[0]
  6386. conn.close()
  6387. done_pair = [{"id": 9401, "command": "saddle done",
  6388. "output": "# Completion\n\nOne block only.", "exit_code": 0,
  6389. "type": "done", "timestamp": "2026-09-12T00:00:00Z"}]
  6390. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6391. {"session_id": burst_session, "state": "done",
  6392. "entries": done_pair,
  6393. "summary": "# Completion\n\nOne block only."})
  6394. check(status == 200 and completion_block_count() == 1,
  6395. "the done entry + state pair raises nothing more (one block, ever)")
  6396. state = goal_state(goal)
  6397. act(auth, state["completion_pending_block"]["answer_action"],
  6398. {"answer": "Review approved. Continue with the task."})
  6399. check(wait_for(lambda: goal_state(goal)["status"] == "complete" or False,
  6400. timeout=30, what="goalui goal completes") is not None,
  6401. "accepting the completion completes the goal")
  6402. check(completion_block_count() == 1,
  6403. "the accept path leaves exactly one review-kind block behind")
  6404. conn = db()
  6405. stragglers = conn.execute(
  6406. "select count(*) from task_blocks where task_id = ? and answer is null",
  6407. (run_task,)).fetchone()[0]
  6408. conn.close()
  6409. check(stragglers == 0,
  6410. "no unanswered straggler rows survive the completion")
  6411. BUNDLES_ORDER = ("pages", "dispatch", "subtasks", "lineage",
  6412. "allocation", "lifecycle", "answers", "push", "goals",
  6413. "replay", "goalui")
  6414. def run_bundle(name):
  6415. """Runs one shard to completion; returns a failure count."""
  6416. started = time.monotonic()
  6417. ctx = start_bundle(name)
  6418. runner = globals()["bundle_" + name]
  6419. try:
  6420. runner(ctx)
  6421. finally:
  6422. # Exit-code diagnostic: distinguishes a crashed app (negative
  6423. # returncode, e.g. -11 SIGSEGV) from a clean shutdown. When
  6424. # tearing down mid-exception, also capture the still-alive
  6425. # app's stacks before killing it (a wedged-but-alive server
  6426. # otherwise leaves no evidence).
  6427. print("(app returncode at teardown: %s)" % ctx.app.poll())
  6428. if ctx.app.poll() is None and sys.exc_info()[0] is not None:
  6429. dump_app_stacks(ctx.app.pid)
  6430. ctx.fake.kill()
  6431. try:
  6432. ctx.app.terminate()
  6433. try:
  6434. ctx.app.wait(timeout=5)
  6435. except subprocess.TimeoutExpired:
  6436. ctx.app.kill()
  6437. check(ctx.app.poll() in (0, -15),
  6438. "bundle %s app shut down cleanly (exit %s)"
  6439. % (name, ctx.app.poll()))
  6440. except OSError:
  6441. pass
  6442. print("%d passed, %d failed" % (passes, failures))
  6443. print("[bundle %s] %.1fs" % (name, time.monotonic() - started))
  6444. return failures
  6445. def run_all_parallel():
  6446. """The default meson entry: one subprocess per bundle (each with its
  6447. own app, daemons and database), verdicts aggregated into one exit
  6448. code and one combined check-count summary."""
  6449. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  6450. log_dir = os.path.join(os.path.dirname(base) or "/tmp/kilo",
  6451. "webstack-shards")
  6452. os.makedirs(log_dir, exist_ok=True)
  6453. procs = {}
  6454. started = time.monotonic()
  6455. for name in BUNDLES_ORDER:
  6456. out_path = os.path.join(log_dir, "bundle-%s.log" % name)
  6457. handle = open(out_path, "w")
  6458. procs[name] = (subprocess.Popen(
  6459. [sys.executable, "-u", os.path.abspath(__file__), APP,
  6460. "--bundle", name],
  6461. stdout=handle, stderr=subprocess.STDOUT), handle, out_path)
  6462. total_pass = total_fail = 0
  6463. broken = []
  6464. for name, (proc, handle, out_path) in procs.items():
  6465. try:
  6466. proc.wait(timeout=SHARD_TIMEOUT_S)
  6467. except subprocess.TimeoutExpired:
  6468. proc.kill()
  6469. proc.wait()
  6470. handle.close()
  6471. text = open(out_path).read()
  6472. match = re.search(r"(\d+) passed, (\d+) failed", text)
  6473. took = re.search(r"\[bundle %s\] ([0-9.]+)s" % name, text)
  6474. bundle_pass = int(match.group(1)) if match else 0
  6475. bundle_fail = int(match.group(2)) if match else -1
  6476. total_pass += max(bundle_pass, 0)
  6477. total_fail += max(bundle_fail, 0)
  6478. status = "ok"
  6479. if proc.returncode != 0 or bundle_fail != 0 or match is None:
  6480. status = "BROKEN (exit %s)" % proc.returncode
  6481. broken.append(name)
  6482. print("[shard %-10s] %6ss %3d passed %3d failed %s"
  6483. % (name, took.group(1) if took else "?",
  6484. bundle_pass, bundle_fail, status))
  6485. if status != "ok":
  6486. tail = "\n".join(text.rstrip().split("\n")[-60:])
  6487. print("--- web-stack/%s tail (full log: %s) ---" % (name, out_path))
  6488. print(tail)
  6489. print("--- end web-stack/%s tail ---" % name)
  6490. print("shards wall: %.1fs (logs under %s)" % (time.monotonic() - started, log_dir))
  6491. print("ALL SHARDS: %d passed, %d failed%s"
  6492. % (total_pass, total_fail,
  6493. "" if not broken else " BROKEN: " + ", ".join(broken)))
  6494. return 1 if broken or total_fail else 0
  6495. def main():
  6496. if not os.path.exists(APP):
  6497. raise SystemExit("app binary not found at %s (build first)" % APP)
  6498. argv = sys.argv[2:]
  6499. if "--bundle" in argv:
  6500. sys.exit(1 if run_bundle(argv[argv.index("--bundle") + 1]) else 0)
  6501. if os.environ.get("WEBSTACK_SEQUENTIAL"):
  6502. # Debug path: every bundle in-process, one after another.
  6503. for name in BUNDLES_ORDER:
  6504. if run_bundle(name):
  6505. return 1
  6506. return 0
  6507. return run_all_parallel()
  6508. if __name__ == "__main__":
  6509. sys.exit(main())