web_stack_test.py 391 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545
  1. #!/usr/bin/env python3
  2. """Self-contained web-stack feature tests: app + fake saddle daemon.
  3. Unlike integration_test.py (which needs a real saddle daemon and a mock
  4. LLM), this suite spawns everything it needs:
  5. - the clanker-saddle app binary (path from argv[1], or builddir default)
  6. in a scratch directory with its own web-config.json (statum keys copied
  7. from the repo, plus `saddle_callback_base_url`) and SQLite database
  8. - in-process fake saddle daemons speaking the wire contract: POST
  9. /register (plan 10: receives {saddle_token, web_base_url}, answers
  10. {ok, ssh_public_key, version}), POST /wake (records the wake; the
  11. daemon then asks POST /api/saddle/next-task), POST /task-update
  12. (cancel/comment/subtask-status), GET /status (scripted reflection —
  13. exceptional use only), and the phase-2 push channels home:
  14. POST /api/saddle/chunks (raw PTY batches) and POST /api/saddle/results
  15. (round entries + state transitions). The retired /start, /output and
  16. /log routes 404 like a post-phase-2 daemon.
  17. It then drives the app the way statum.js does (entrypoint loads + action
  18. POSTs) and asserts the Workstream B features against the wire contract:
  19. 3. plan-review blocks hide their duplicate body preview
  20. 5. rules CRUD/attach + the effective `rules` array in assignments
  21. 6. project notes, POST /api/saddle/note, `project_notes` + `callback`
  22. in assignments
  23. plus the raw-log side: pushed chunks -> session_raw_log + terminal
  24. raw view
  25. Plan 10 phase 1 (work acquisition flip):
  26. - per-saddle tokens: registration mints + /register-delivers them,
  27. legacy tokens migrate onto the row at startup, removal revokes
  28. - token auth on every /api/saddle/* endpoint
  29. - next-task allocation: concurrent asks race exactly one winner,
  30. affinity pinning for parked tasks, resume_notice on suspended resumes
  31. - dispatcher: wake -> ask -> allocate roundtrip, the lost-wake guard
  32. (no ask after a wake -> offline, re-wake the next capable), and the
  33. pre-flip /answer + /start resume paths kept as the rollback route
  34. Plan 10 phase 2 (telemetry flip):
  35. - pushed chunks: idempotent on (session_id, seq), ordered, landing in
  36. session_raw_log so the SSE terminal keeps working
  37. - pushed results: entries store like the /output path did (redelivery
  38. idempotent on the daemon entry ids), blocked raises the block row +
  39. parks + bumps the pulse (sealed refresh shows it), done/failed
  40. complete/fail the task, suspended parks for the affinity resume
  41. - answer resumes, both daemon shapes: a SLEEPING affine saddle (its
  42. post-park ask returned 204) is woken, its ask allocating the resume
  43. with the verdict riding the assignment; a daemon parked MID-ROUND
  44. (its round holds the block's answer wait open, so it can never ask)
  45. gets the verdict delivered into that wait via POST /answer — same
  46. session, no wake. A daemon dying with a parked-with-answered task
  47. never requeues it: the verdict and session survive for the resume
  48. - staleness: a silent runner gets ONE exceptional GET /status probe —
  49. alive keeps it running, dead requeues the task with an agent comment and
  50. marks the saddle offline; a recovered daemon's ask flips offline rows
  51. back to idle
  52. - the deleted layers are gone: /output, /log and /start 404 on the
  53. daemon side, and nothing on the web side calls them
  54. Plan 10 phase 3 (capability awareness + UI):
  55. - assignment capability context: {saddle_tags, fleet_tags} on every
  56. payload, GET /api/saddle/capabilities (per-saddle token) feeding
  57. the daemon's `saddle capabilities` CLI
  58. - subtask callback capabilities: explicit-only attachment validated
  59. against the operator tag set, unknown tags rejected with the valid
  60. list in the error
  61. - task page: status block pinned to the top, blocking sections
  62. newest-first (sealed GET state)
  63. - home dashboard: pinned OPEN blocks as newest-first link-through
  64. cards (no inline answer forms) above the cross-task activity
  65. timeline (last ~50 events newest-first)
  66. - lost-wake-guard regression: a saddle that asks SLOWLY after its
  67. wake (busy winding down) still claims the task — the wake is never
  68. silently dropped, no re-wake storm fires, and the never-asks guard
  69. path (offline + re-wake of the next capable) stays green
  70. Prints PASS/FAIL lines Statum-style; exits non-zero on any failure.
  71. Plan 11 task D+E (UI + notifications), the `push` shard:
  72. - task page: progress feed above the status card, status + description
  73. in a 50/50 grid, edit expander under the history expander, plan
  74. behind an expander, answered blocks behind an expander; queue screen:
  75. New Task expander above the filters; dashboard waiting-on-drafts
  76. block with links to where Enqueue lives (pages shard)
  77. - real Web Push over VAPID: keypair generated at startup into
  78. web-config.json, GET /sw.js service worker with click-through,
  79. subscribe/unsubscribe + per-task Notify me actions, block events and
  80. waiting-on-drafts pushed globally, first start/failure/completion to
  81. opted-in users, best-effort queue with dispatcher-tick retry, 410/404
  82. endpoint pruning — payloads verified protocol-level (RFC 8291
  83. decryption + ES256 JWT signature) because the harness owns the
  84. browser-side keys
  85. Heredoc completion reports (pages shard):
  86. - terminal tasks render tasks.summary (set by done/fail) as a
  87. markdown completion-report card below the status/description grid —
  88. "Completion report" when done, "Failure summary" when failed, no
  89. card when empty; the summary renders through the shipped
  90. stm-markdown renderer (headings/code, no syntax leaks, HTML
  91. escaped) and the dashboard timeline snippets its first line
  92. Speed pass (plan 11, task 0):
  93. - SHARDING: the scenario groups are partitioned into seven independent
  94. bundles (pages, dispatch, subtasks, lineage, allocation, lifecycle,
  95. answers), each running in its own process against its own app
  96. instance, fake daemons and SQLite database. The default invocation
  97. runs all bundles in parallel and aggregates the verdicts and check
  98. counts into one exit code — meson sees a single green/red test.
  99. `--bundle NAME` runs one shard for debugging; WEBSTACK_SEQUENTIAL=1
  100. runs them in-process, one after another.
  101. - Within a bundle, scenario groups SHARE the app+daemon instance and
  102. carry per-group state as database rows (task/session/block
  103. fixtures), never process restarts; the one deliberate restart (the
  104. startup token migration) lives in the answers bundle.
  105. - EVENT-DRIVEN WAITS: wait_for polls at 50ms; the fixed sleeps were
  106. converted either to observable-condition waits (daemon-side
  107. counters, e.g. failed-delivery hits) or to quiet_window() — a
  108. bounded negative-assertion poll that FAILS LOUDLY the moment the
  109. event it guards against happens (a sleep could silently pass).
  110. - ENV KNOBS: SADDLE_DISPATCH_TICK_S=1 (dispatcher cadence; default 5
  111. in production), SADDLE_HTTP_TIMEOUT_S=2, SADDLE_LOST_WAKE_S=2,
  112. SADDLE_STALE_S=3, plus the fake daemon's scripted timings — the
  113. wire-traffic shapes stay realistic, just faster.
  114. """
  115. import json
  116. import os
  117. import re
  118. import shutil
  119. import socket
  120. import sqlite3
  121. import subprocess
  122. import sys
  123. import threading
  124. import time
  125. import urllib.error
  126. import urllib.parse
  127. import urllib.request
  128. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  129. # Web Push protocol verification (plan 11 task E): the test harness
  130. # owns the browser-side keys, so it can do everything the push service
  131. # does — decrypt the RFC 8291 body and verify the ES256 VAPID JWT.
  132. import base64
  133. from cryptography.hazmat.primitives import hashes
  134. from cryptography.hazmat.primitives.asymmetric import ec
  135. from cryptography.hazmat.primitives.asymmetric.utils import encode_dss_signature
  136. from cryptography.hazmat.primitives.ciphers.aead import AESGCM
  137. from cryptography.hazmat.primitives.kdf.hkdf import HKDF
  138. from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
  139. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  140. APP = os.path.abspath(sys.argv[1]) if len(sys.argv) > 1 else os.path.join(REPO, "builddir", "clanker-saddle")
  141. # --- speed-pass tuning -----------------------------------------------------
  142. # The fake daemon's scripted timings and the dispatch-tick cadence the
  143. # quiet windows are sized against. All overridable for debugging.
  144. TICK_S = float(os.environ.get("SADDLE_DISPATCH_TICK_S", "1") or 1)
  145. FAKE_WORK_S = float(os.environ.get("WEBSTACK_FAKE_WORK_S", "1.2") or 1.2)
  146. FAKE_FAIL_S = float(os.environ.get("WEBSTACK_FAKE_FAIL_S", "0.5") or 0.5)
  147. FAKE_HEARTBEAT_S = float(os.environ.get("WEBSTACK_FAKE_HEARTBEAT_S", "0.4") or 0.4)
  148. FAKE_TRIGGER_S = float(os.environ.get("WEBSTACK_FAKE_TRIGGER_S", "0.05") or 0.05)
  149. SHARD_TIMEOUT_S = float(os.environ.get("WEBSTACK_SHARD_TIMEOUT_S", "600") or 600)
  150. def quiet_seconds():
  151. """A negative-assertion window spanning several dispatch ticks (the
  152. converted fixed sleeps were 3-7s at the old 5s tick; the bound never
  153. exceeds the old timeout)."""
  154. return min(2 * TICK_S + 0.8, 7.0)
  155. WORK = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  156. DB_PATH = os.path.join(WORK, "web.sqlite")
  157. passes = 0
  158. failures = 0
  159. def check(condition, label):
  160. global passes, failures
  161. if condition:
  162. passes += 1
  163. print("PASS %s" % label)
  164. else:
  165. failures += 1
  166. print("FAIL %s" % label)
  167. def free_port():
  168. with socket.socket() as sock:
  169. sock.bind(("127.0.0.1", 0))
  170. return sock.getsockname()[1]
  171. APP_PORT = free_port()
  172. DAEMON_PORT = free_port()
  173. WEB = "http://127.0.0.1:%d" % APP_PORT
  174. def bundle_env(name):
  175. """Point the module's runtime globals at one shard's scratch dir,
  176. database and ports (each bundle is a process with its own app,
  177. daemons and SQLite file)."""
  178. global WORK, DB_PATH, APP_PORT, DAEMON_PORT, WEB
  179. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  180. WORK = "%s-%s" % (base, name)
  181. DB_PATH = os.path.join(WORK, "web.sqlite")
  182. APP_PORT = free_port()
  183. DAEMON_PORT = free_port()
  184. WEB = "http://127.0.0.1:%d" % APP_PORT
  185. def http(method, url, data=None, headers=None, timeout=30):
  186. body = None
  187. if data is not None:
  188. pairs = []
  189. for k, v in data.items():
  190. for item in (v if isinstance(v, (list, tuple)) else [v]):
  191. pairs.append((k, item))
  192. body = "&".join("%s=%s" % (k, urllib.parse.quote(str(item))) for k, item in pairs).encode()
  193. request = urllib.request.Request(WEB + url if url.startswith("/") else url,
  194. data=body, method=method)
  195. if data is not None:
  196. request.add_header("Content-Type", "application/x-www-form-urlencoded")
  197. for key, value in (headers or {}).items():
  198. request.add_header(key, value)
  199. # Retry dropped/refused connections: the freshly started app can
  200. # close a very early keep-alive connection once while warming up,
  201. # and its first seconds can wobble under load.
  202. for attempt in range(3):
  203. try:
  204. with urllib.request.urlopen(request, timeout=timeout) as response:
  205. return response.status, response.read().decode()
  206. except urllib.error.HTTPError as error:
  207. return error.code, error.read().decode()
  208. except (urllib.error.URLError, OSError):
  209. if attempt >= 2:
  210. raise
  211. time.sleep(0.75)
  212. def directives(uri, auth=None):
  213. headers = {}
  214. if auth:
  215. headers["X-Statum-Slot"] = "key=%s; as_at=%s" % (auth["key"], auth["as_at"])
  216. status, body = http("GET", "/_statum/entrypoint?uri=" + urllib.parse.quote(uri.split("?")[0]),
  217. headers=headers)
  218. if status != 200:
  219. raise SystemExit("entrypoint %s -> HTTP %d: %s" % (uri, status, body[:300]))
  220. return json.loads(body)
  221. def slot_public(auth, uri, type_name):
  222. for directive in directives(uri, auth):
  223. if directive["type"] == "set":
  224. content = directive["snapshot_frame"].get("content")
  225. if not content:
  226. continue
  227. content = json.loads(content)
  228. if content["slot"]["type"] == type_name:
  229. return content["public"]
  230. raise SystemExit("no %s slot in entrypoint state for %s" % (type_name, uri))
  231. def act(auth, action, fields):
  232. headers = {"X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}
  233. if action.get("private"):
  234. headers["X-Statum-Private"] = action["private"]
  235. status, body = http(action.get("method", "POST"), action["uri"], fields, headers)
  236. if status != 200:
  237. raise SystemExit("action %s -> HTTP %d: %s" % (action["uri"], status, body[:300]))
  238. return json.loads(body)
  239. def login(username, password):
  240. frames = directives("/login")
  241. content = json.loads(frames[0]["snapshot_frame"]["content"])
  242. action = content["public"]["login"]
  243. status, body = http(action.get("method", "POST"), action["uri"],
  244. {"username": username, "password": password})
  245. if status != 200:
  246. raise SystemExit("login -> HTTP %d: %s" % (status, body[:300]))
  247. for directive in json.loads(body):
  248. if directive["type"] == "set":
  249. frame = json.loads(directive["snapshot_frame"]["content"])
  250. if frame["slot"]["type"] == "auth":
  251. return {"key": frame["slot"]["key"], "as_at": frame["as_at"]}
  252. raise SystemExit("login response carried no auth slot: " + body[:300])
  253. def wait_for(predicate, timeout=60, what="condition", interval=0.05):
  254. deadline = time.monotonic() + timeout
  255. last = None
  256. while time.monotonic() < deadline:
  257. last = predicate()
  258. if last is not False and last is not None:
  259. return last
  260. time.sleep(interval)
  261. print(" (timeout waiting for %s; last: %s)" % (what, last))
  262. dump_threads()
  263. return None
  264. def quiet_window(seconds, predicate, what):
  265. """A converted fixed sleep: asserts a NEGATIVE condition (nothing may
  266. happen) across a window spanning several dispatch ticks, polling at
  267. 50ms. The moment the condition breaks the window fails loudly
  268. (diagnostics + thread dump) instead of silently passing a sleep."""
  269. deadline = time.monotonic() + seconds
  270. while time.monotonic() < deadline:
  271. value = predicate()
  272. if value is False or value is None:
  273. remaining = deadline - time.monotonic()
  274. print(" (quiet window '%s' broken after %.2fs of %.2fs — the"
  275. " guarded event DID happen)" % (what, seconds - remaining, seconds))
  276. dump_threads()
  277. return False
  278. time.sleep(0.05)
  279. return True
  280. def dump_threads():
  281. """Stacks of suite threads not parked in sleep — pinpoints a wedged
  282. fake lifecycle when a wait times out."""
  283. import traceback
  284. shown = 0
  285. for thread_id, frame in sys._current_frames().items():
  286. stack = "".join(traceback.format_stack(frame)[-4:])
  287. if ("web_stack_test.py" in stack) and ("sleep" not in stack) and shown < 6:
  288. shown += 1
  289. print(" --- thread %s ---\n%s" % (thread_id, stack))
  290. def task_state(auth, task_id):
  291. return slot_public(auth, "/tasks/%d" % task_id, "task")
  292. def wait_task_done(auth, task_id, timeout=90):
  293. return wait_for(lambda: task_state(auth, task_id).get("status") == "done" or False,
  294. timeout=timeout, what="task %d -> done" % task_id)
  295. def task_id_of(title):
  296. conn = db()
  297. try:
  298. return conn.execute("select id from tasks where title = ?", (title,)).fetchone()[0]
  299. finally:
  300. conn.close()
  301. def enqueue_task(auth, task_id):
  302. """The human-only Enqueue action (plan 11): draft -> queued."""
  303. detail = task_state(auth, task_id)
  304. assert detail["status"] == "draft", "task %d not in draft (%s)" % (task_id, detail["status"])
  305. act(auth, detail["enqueue"], {})
  306. return task_state(auth, task_id)["status"]
  307. def create_queued(auth, fields):
  308. """Create via the queue form (lands in draft) and enqueue it — the
  309. standard 'this task should dispatch' fixture of the plan-11 world."""
  310. act(auth, slot_public(auth, "/tasks", "tasks")["create"], fields)
  311. task_id = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  312. if t["title"] == fields["title"]][0])
  313. enqueue_task(auth, task_id)
  314. return task_id
  315. def saddle_api(method, path, token, payload=None):
  316. """Raw call against the saddle ingest API; returns (status, json)."""
  317. request = urllib.request.Request(WEB + path,
  318. data=json.dumps(payload or {}).encode(), method=method)
  319. request.add_header("Content-Type", "application/json")
  320. if token is not None:
  321. request.add_header("Authorization", "Bearer " + token)
  322. try:
  323. with urllib.request.urlopen(request, timeout=15) as response:
  324. return response.status, json.loads(response.read().decode() or "{}")
  325. except urllib.error.HTTPError as error:
  326. body = error.read().decode()
  327. try:
  328. return error.code, json.loads(body)
  329. except ValueError:
  330. return error.code, {"raw": body}
  331. def db():
  332. return sqlite3.connect(DB_PATH)
  333. def http_get_page(auth, uri):
  334. """The compiled page HTML for a statum route (auth via the slot
  335. header), for asserting page-level embeds the slot state cannot
  336. see."""
  337. status, body = http("GET", uri, headers={
  338. "X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])})
  339. if status != 200:
  340. raise SystemExit("GET %s -> HTTP %d" % (uri, status))
  341. return body
  342. def saddle_card(auth, name):
  343. rows = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  344. if s["name"] == name]
  345. return rows[0]
  346. def queued_count():
  347. conn = db()
  348. try:
  349. return conn.execute(
  350. "select count(*) from tasks where status = 'queued'").fetchone()[0]
  351. finally:
  352. conn.close()
  353. def command_rows(session):
  354. conn = db()
  355. try:
  356. return conn.execute(
  357. "select command_text, type from session_commands"
  358. " where session_id = ? order by id", (session,)).fetchall()
  359. finally:
  360. conn.close()
  361. class FakeSaddle:
  362. """In-process saddle daemon implementing the wire contract.
  363. Phase-2 push behaviour: the daemon asks POST /api/saddle/next-task
  364. whenever idle-awake (at registration, on POST /wake, after its task
  365. reaches a terminal state, and when a /status probe observes it
  366. parked idle — throttled), accepts assignments like POST /start used
  367. to, then PUSHES its telemetry home: raw PTY chunks via POST
  368. /api/saddle/chunks and round results with state transitions via
  369. POST /api/saddle/results (working at round start, terminal states
  370. when the scripted lifecycle ends them). /output, /log and /start
  371. are gone (404) like a post-phase-2 daemon; /task-update serves the
  372. cancel/comment/subtask-status kinds; POST /answer receives a
  373. delivered verdict when the round is parked in a block's answer
  374. wait (409 when nothing waits — the real daemon's contract; the
  375. resumed round continues after the response). Every trigger can be
  376. disabled per test for determinism; ask_now() performs a
  377. synchronous manual ask.
  378. """
  379. PROMPT = "bbarrow@fedora:/workspace/task-1$ "
  380. def __init__(self):
  381. self.lock = threading.Lock()
  382. self.start_payloads = [] # captured assignment payloads (/start + next-task 200s)
  383. self.state = "idle"
  384. self.summary = ""
  385. self.state_entered = time.monotonic()
  386. self.fail_next = False # next task drives the task to failed
  387. self.start_counts = {} # task id -> assignment count
  388. self.resumed_pending = False # crash-resume flag on the next /status
  389. self.suspend_on_title = None # this task (by title) parks as suspended
  390. self.output_seq = 100 # daemon-global entry ids for pushed results
  391. self.last_activity_epoch = int(time.time())
  392. self.hang_next = {} # path suffix -> hang count (never responds)
  393. self.abort_failures = 0 # cancel task-updates failing (500) while > 0
  394. self.abort_log = [] # task ids aborted via task-update cancel
  395. self.running_task = 0 # task id the daemon believes it runs
  396. self.running_title = "" # its title (suspend targeting)
  397. self.session_id = None # the web-side run row of the running task
  398. self.hold_state = False # freeze lifecycle + heartbeat pushes
  399. self.ssh_public_key = "" # reported on /status + /register
  400. self.started_mono = time.monotonic()
  401. self.freeze_activity = False # hold last_activity_epoch still
  402. self.silent = False # suppress pushes (staleness tests)
  403. self.dead = False # kill(): no serving AND no calls home
  404. self.status_hits = 0 # GET /status arrivals (probe accounting)
  405. self.comment_log = [] # recorded /task-update comment payloads
  406. self.scripted_corpus = None # chunk batch pushed when a task starts
  407. # --- plan 10 phase 1: ask/wake/register ---
  408. self.token = None # per-saddle token from POST /register
  409. self.register_log = [] # recorded /register bodies
  410. self.wake_log = [] # recorded POST /wake arrivals
  411. self.asks = [] # [{"status": int, "payload": dict|None}]
  412. self.ask_on_register = True
  413. self.ask_on_wake = True
  414. self.ask_on_terminal = True
  415. self.ask_on_idle_status = True
  416. self.ask_delay = 0.0 # seconds; a slow daemon delays its wake-triggered ask
  417. self.serve_register = True # False: 404 /register (pre-flip daemon)
  418. self.last_ask_trigger = 0.0
  419. self.port = None
  420. self.ask_threads = [] # scheduled ask-trigger threads (settle_asks joins them)
  421. # --- answer delivery (the parked-session resume) ---
  422. self.pending_block = None # the block payload this daemon waits on (state blocked)
  423. self.answer_log = [] # recorded POST /answer bodies
  424. self.answer_push_delay = 0.2 # the resumed round's first push, after the response
  425. # --- plan 12: goal-agent scripting ---
  426. self.goal_script = [] # behaviours consumed per goal-run assignment
  427. self.goal_behaviour = None # the current round's popped behaviour
  428. self.goal_assignments = [] # captured goal-run assignment payloads
  429. def set_state(self, state, summary=None):
  430. """Advances the scripted lifecycle."""
  431. self.state = state
  432. if summary is not None:
  433. self.summary = summary
  434. self.state_entered = time.monotonic()
  435. def touch_activity(self):
  436. if not self.freeze_activity:
  437. self.last_activity_epoch = int(time.time())
  438. def queue_output(self, entry_type, command, output):
  439. """Pushes a typed entry as a round-results push (the daemon's
  440. entry log riding the results channel)."""
  441. with self.lock:
  442. entry = {
  443. "id": self.output_seq,
  444. "command": command,
  445. "output": output,
  446. "exit_code": 1,
  447. "type": entry_type,
  448. "timestamp": "2026-09-06T00:00:00Z",
  449. }
  450. self.output_seq += 1
  451. self.push_results(self.state if self.state in ("working",) else "working",
  452. entries=[entry])
  453. # --- plan 10 phase 2: the push channels ---
  454. def push_chunks(self, chunks):
  455. """Pushes raw PTY chunks home: elements are texts (assigned
  456. fresh seqs) or {seq, text} dicts (a redelivery or explicit
  457. corpus). Pushes are suppressed while silent/hold_state (the
  458. staleness tests' silent runner)."""
  459. if self.dead or self.silent or self.token is None or self.session_id is None:
  460. return
  461. batch = []
  462. with self.lock:
  463. for chunk in chunks:
  464. if isinstance(chunk, dict):
  465. batch.append({"seq": int(chunk["seq"]), "text": chunk["text"]})
  466. else:
  467. batch.append({"seq": self.next_push_seq(), "text": chunk})
  468. try:
  469. saddle_api("POST", "/api/saddle/chunks", self.token,
  470. {"session_id": self.session_id, "chunks": batch})
  471. except (OSError, ValueError):
  472. pass # app restarting / shutting down mid-test
  473. def next_push_seq(self):
  474. # The daemon-side chunk counter for ad-hoc pushes.
  475. self._push_seq = getattr(self, "_push_seq", 0) + 1
  476. return self._push_seq
  477. def push_results(self, state, entries=None, block=None, summary=None, session_id=None):
  478. """Pushes one round-results payload home (state transition plus
  479. its entries). Returns the HTTP status when it went out, None
  480. when suppressed."""
  481. if self.dead or self.silent:
  482. return None
  483. if self.token is None:
  484. return None
  485. target = session_id if session_id is not None else self.session_id
  486. if target is None:
  487. return None
  488. payload = {"session_id": target, "state": state}
  489. if entries is not None:
  490. payload["entries"] = entries
  491. if block is not None:
  492. payload["block"] = block
  493. if state == "blocked":
  494. # The daemon parks its round on this block's answer wait
  495. # (the real daemon's wait_for_answer).
  496. self.pending_block = dict(block)
  497. if summary is not None:
  498. payload["summary"] = summary
  499. try:
  500. status, _ = saddle_api("POST", "/api/saddle/results", self.token, payload)
  501. if status != 200:
  502. print(" [fake %s] push %s -> HTTP %s (task=%s)"
  503. % (self.port, state, status, self.running_task))
  504. return status
  505. except (OSError, ValueError) as error:
  506. print(" [fake %s] push %s failed: %r (task=%s)"
  507. % (self.port, state, error, self.running_task))
  508. return None
  509. # --- plan 10 phase 1: the ask path ---
  510. def ask_now(self):
  511. """Synchronously asks the web for work (a phase-1 daemon's idle
  512. ask). A 200 assignment is accepted exactly like POST /start;
  513. returns (status, payload|None)."""
  514. token = self.token
  515. if token is None:
  516. raise SystemExit("fake daemon asked before receiving its token")
  517. status, payload = saddle_api("POST", "/api/saddle/next-task", token)
  518. with self.lock:
  519. self.asks.append({"status": status, "payload": payload})
  520. if status == 200:
  521. self.accept_assignment(payload)
  522. return status, payload
  523. def _trigger_ask(self, reason):
  524. """Schedules a delayed ask (the daemon woke / went idle-awake).
  525. ask_delay models a SLOW asker — a daemon still winding down its
  526. round when the wake lands: it honours the wake, but its ask
  527. arrives late (still inside the web's lost-wake guard window)."""
  528. def run():
  529. if self.state in ("working", "failing"):
  530. return # a running daemon does not ask
  531. if self.ask_delay > 0:
  532. time.sleep(self.ask_delay)
  533. for attempt in range(3):
  534. try:
  535. status, _ = self.ask_now()
  536. if status in (200, 204):
  537. return
  538. print(" (ask %s -> HTTP %s, attempt %d)" % (reason, status, attempt + 1))
  539. except Exception as error: # app restarting / blips: retry
  540. print(" (ask %s failed: %r, attempt %d)" % (reason, error, attempt + 1))
  541. time.sleep(1.0)
  542. def starter():
  543. time.sleep(FAKE_TRIGGER_S)
  544. run()
  545. thread = threading.Thread(target=starter, daemon=True)
  546. with self.lock:
  547. self.ask_threads.append(thread)
  548. thread.start()
  549. def settle_asks(self, timeout=15):
  550. """Joins every ask-trigger thread scheduled so far — the
  551. event-driven replacement for the fixed sleeps that waited for
  552. in-flight asks to land after triggers were frozen."""
  553. with self.lock:
  554. threads = [t for t in self.ask_threads if t.is_alive()]
  555. deadline = time.monotonic() + timeout
  556. for thread in threads:
  557. thread.join(timeout=max(0.1, deadline - time.monotonic()))
  558. with self.lock:
  559. self.ask_threads = [t for t in self.ask_threads if t.is_alive()]
  560. return all(not thread.is_alive() for thread in threads)
  561. def maybe_trigger_ask(self, reason, throttle=False):
  562. """Schedules an idle-awake ask. Protocol events (wake, abort,
  563. round end, park) ask singularly and immediately; only the
  564. /status-observation path throttles (a burst of probes must not
  565. hammer the ask endpoint)."""
  566. now = time.monotonic()
  567. if throttle and now - self.last_ask_trigger < 1.0:
  568. return
  569. self.last_ask_trigger = now
  570. self._trigger_ask(reason)
  571. def accept_assignment(self, payload):
  572. """A 200 next-task assignment: adopted exactly like POST /start."""
  573. self.start_payloads.append(payload)
  574. task = payload.get("task") or {}
  575. task_id = task.get("id")
  576. self.running_task = int(task_id or 0)
  577. self.running_title = task.get("title") or ""
  578. self.session_id = payload.get("session_id")
  579. # The assignment's answers resolve any block this daemon was
  580. # parked on (resume-carries-answer).
  581. self.pending_block = None
  582. count = self.start_counts.get(task_id, 0) + 1
  583. self.start_counts[task_id] = count
  584. if count > 1:
  585. # Crash-resume contract: re-pushing a task whose
  586. # workspace still exists restores it; the first
  587. # /status after the restore reports "resumed": true.
  588. self.resumed_pending = True
  589. # Plan 12: a goal-run assignment plays its scripted behaviour
  590. # instead of the plain done push (plan submission, parking,
  591. # question, completion, failure — consumed one per round).
  592. self.goal_behaviour = None
  593. if payload.get("kind") == "goal_run":
  594. self.goal_assignments.append(payload)
  595. self.goal_behaviour = self.goal_script.pop(0) if self.goal_script else ("suspend",)
  596. self.set_state("failing" if self.fail_next else "working")
  597. self.fail_next = False
  598. # The round's opening telemetry: the flushed-so-far raw PTY
  599. # batch plus the working state push (>= 2 flushes per round
  600. # and the 10s timer are the real daemon's contract; the fake
  601. # pushes its batch up front and heartbeats while working).
  602. if self.scripted_corpus is not None:
  603. self.push_chunks([dict(chunk) for chunk in self.scripted_corpus])
  604. else:
  605. self.push_chunks([self.PROMPT, "echo hello\r\n", "hello\r\n"])
  606. self.push_results("working")
  607. class Handler(BaseHTTPRequestHandler):
  608. daemon = None # set on the class before serving
  609. protocol_version = "HTTP/1.1"
  610. def log_message(self, fmt, *args):
  611. pass
  612. def maybe_hang(self, path):
  613. """True when this request should hang forever (never respond),
  614. consuming one unit of the path's hang budget."""
  615. for suffix, count in list(self.daemon.hang_next.items()):
  616. if count > 0 and path.startswith(suffix):
  617. self.daemon.hang_next[suffix] = count - 1
  618. return True
  619. return False
  620. def _send(self, status, obj):
  621. body = json.dumps(obj).encode()
  622. self.send_response(status)
  623. self.send_header("Content-Type", "application/json")
  624. self.send_header("Content-Length", str(len(body)))
  625. self.end_headers()
  626. self.wfile.write(body)
  627. def do_POST(self):
  628. if self.maybe_hang(self.path):
  629. time.sleep(600)
  630. return
  631. self.daemon.touch_activity()
  632. length = int(self.headers.get("Content-Length") or 0)
  633. raw = self.rfile.read(length).decode() if length else "{}"
  634. if self.path == "/register":
  635. # Plan 10: the web delivers the per-saddle token + its
  636. # own base URL; the daemon persists the token for its
  637. # calls home and reports its ssh key + version.
  638. if not self.daemon.serve_register:
  639. self._send(404, {"error": "no such route"})
  640. return
  641. try:
  642. payload = json.loads(raw)
  643. except ValueError:
  644. payload = {"raw": raw}
  645. self.daemon.register_log.append(payload)
  646. if payload.get("saddle_token"):
  647. self.daemon.token = payload["saddle_token"]
  648. self._send(200, {"ok": True,
  649. "ssh_public_key": self.daemon.ssh_public_key,
  650. "version": "0.1-fake"})
  651. if self.daemon.ask_on_register:
  652. self.daemon.maybe_trigger_ask("register")
  653. return
  654. if self.path == "/wake":
  655. # Plan 10: a capable task is ready; a sleeping daemon
  656. # asks for work (immediately — a wake is a direct
  657. # command, never throttled).
  658. self.daemon.wake_log.append(time.monotonic())
  659. self._send(200, {"ok": True})
  660. if self.daemon.ask_on_wake:
  661. self.daemon.maybe_trigger_ask("wake")
  662. return
  663. if self.path == "/answer":
  664. # Plan 11 (daemon Task A): parks FREE the daemon, so no
  665. # block ever waits in-process — the verdict travels in
  666. # the resuming allocation's resume_notice. Always 409,
  667. # exactly like the real daemon's contract.
  668. try:
  669. payload = json.loads(raw)
  670. except ValueError:
  671. self._send(400, {"error": "bad json"})
  672. return
  673. self.daemon.answer_log.append({
  674. "refused": True,
  675. "answer": payload.get("answer", "")})
  676. self._send(409, {"error": "no block is waiting for an answer — parks resume via allocation"})
  677. return
  678. if self.path == "/task-update":
  679. # Plan 10: cancel (abort machinery) and comment
  680. # (injected turn) — delivered directly to a RUNNING
  681. # daemon, no auth.
  682. try:
  683. payload = json.loads(raw)
  684. except ValueError:
  685. self._send(400, {"error": "bad json"})
  686. return
  687. kind = payload.get("kind")
  688. if kind == "cancel":
  689. if self.daemon.abort_failures > 0:
  690. self.daemon.abort_failures -= 1
  691. self._send(500, {"error": "cancel failed (simulated)"})
  692. return
  693. aborted = self.daemon.running_task
  694. self.daemon.set_state("idle")
  695. self.daemon.summary = ""
  696. self.daemon.running_task = 0
  697. self.daemon.session_id = None
  698. self.daemon.abort_log.append(aborted)
  699. self._send(200, {"ok": True, "aborted_task_id": aborted})
  700. # An aborted daemon returns to its idle loop: it asks.
  701. self.daemon.maybe_trigger_ask("aborted")
  702. elif kind == "comment":
  703. self.daemon.comment_log.append(payload)
  704. self._send(200, {"ok": True})
  705. else:
  706. self._send(400, {"error": "unknown task-update kind"})
  707. return
  708. self._send(404, {"error": "no such route"})
  709. self.close_connection = True
  710. def do_GET(self):
  711. if self.maybe_hang(self.path):
  712. time.sleep(600)
  713. return
  714. if self.path != "/status":
  715. # /status itself is not daemon activity: the liveness
  716. # signal must reflect loop rounds / command completions.
  717. self.daemon.touch_activity()
  718. if self.path == "/status":
  719. self.daemon.status_hits += 1
  720. response = {"state": self.daemon.state, "summary": self.daemon.summary,
  721. "uptime_seconds": int(time.monotonic() - self.daemon.started_mono),
  722. "last_activity_epoch": self.daemon.last_activity_epoch,
  723. "ssh_public_key": self.daemon.ssh_public_key}
  724. if getattr(self.daemon, "status_extra", None):
  725. response.update(self.daemon.status_extra)
  726. if self.daemon.resumed_pending:
  727. response["resumed"] = True
  728. self.daemon.resumed_pending = False
  729. # A parked/terminal daemon is idle-awake: a phase-1
  730. # daemon asks (and sleeps on 204). Throttled so status
  731. # poll bursts do not hammer the ask endpoint.
  732. if self.daemon.ask_on_idle_status and self.daemon.state in (
  733. "idle", "done", "failed", "suspended"):
  734. self.daemon.maybe_trigger_ask("idle-status", throttle=True)
  735. self._send(200, response)
  736. else:
  737. self._send(404, {"error": "no such route"})
  738. self.close_connection = True
  739. def run_lifecycle(self):
  740. """Applies the scripted lifecycle on a timer (like a real daemon
  741. whose task ends on its own): working heartbeats chunks (the
  742. flush timer's stand-in, keeping the staleness clock fed), works
  743. for FAKE_WORK_S, then pushes done/suspended; failing pushes
  744. failed after FAKE_FAIL_S — and a task END makes the idle-awake
  745. daemon ask again."""
  746. while True:
  747. time.sleep(0.1)
  748. if self.hold_state or self.silent:
  749. # hold_state freezes the script; silent models a daemon
  750. # mid-round with nothing to flush — its round has not
  751. # ended, so no terminal push fires while quiet.
  752. continue
  753. if self.state == "failing":
  754. if time.monotonic() - self.state_entered >= FAKE_FAIL_S:
  755. self.set_state("failed", "bash -n rejected the script (simulated)")
  756. self.push_results("failed",
  757. summary="bash -n rejected the script (simulated)")
  758. if self.ask_on_terminal:
  759. self.maybe_trigger_ask("terminal")
  760. elif self.state == "working":
  761. if time.monotonic() - self.state_entered >= FAKE_WORK_S:
  762. if self.goal_behaviour is not None:
  763. # A goal-agent round: play the scripted
  764. # behaviour (the results channel carries the
  765. # goal-context verbs).
  766. behaviour, self.goal_behaviour = self.goal_behaviour, None
  767. kind = behaviour[0]
  768. if kind == "plan":
  769. self.set_state("blocked")
  770. self.push_results("blocked", block={
  771. "type": "plan",
  772. "question": "Plan submitted for review",
  773. "body": behaviour[1]})
  774. if self.ask_on_idle_status:
  775. self.maybe_trigger_ask("parked")
  776. elif kind == "question":
  777. self.set_state("blocked")
  778. self.push_results("blocked", block={
  779. "type": "question",
  780. "question": behaviour[1],
  781. "options": list(behaviour[2])
  782. if len(behaviour) > 2 else None})
  783. if self.ask_on_idle_status:
  784. self.maybe_trigger_ask("parked")
  785. elif kind == "suspend":
  786. self.set_state("suspended")
  787. self.push_results("suspended")
  788. if self.ask_on_idle_status:
  789. self.maybe_trigger_ask("parked")
  790. elif kind == "fail":
  791. self.set_state("failed", behaviour[1])
  792. self.push_results("failed", summary=behaviour[1])
  793. if self.ask_on_terminal:
  794. self.maybe_trigger_ask("terminal")
  795. else: # "done": the completion report
  796. self.set_state("done", behaviour[1])
  797. self.push_results("done", summary=behaviour[1])
  798. if self.ask_on_terminal:
  799. self.maybe_trigger_ask("terminal")
  800. elif self.suspend_on_title and self.suspend_on_title == self.running_title:
  801. # `saddle suspend`: park until a fresh assignment
  802. # resumes the workspace (title-targeted one-shot,
  803. # so an interleaved dispatch cannot eat the flag).
  804. self.set_state("suspended")
  805. self.suspend_on_title = None
  806. self.push_results("suspended")
  807. # A parked daemon is idle-awake: it asks (and
  808. # sleeps on 204) so a later wake can reach it.
  809. if self.ask_on_idle_status:
  810. self.maybe_trigger_ask("parked")
  811. else:
  812. self.set_state("done", "fake daemon finished")
  813. self.push_results("done", summary="fake daemon finished")
  814. if self.ask_on_terminal:
  815. self.maybe_trigger_ask("terminal")
  816. elif time.monotonic() - getattr(self, "last_heartbeat", 0) >= FAKE_HEARTBEAT_S:
  817. # The flush timer: output keeps flowing, so chunks
  818. # keep arriving (the staleness window never opens on
  819. # a healthy runner).
  820. self.last_heartbeat = time.monotonic()
  821. self.push_chunks(["working-heartbeat\r\n"])
  822. def serve(self, port=None):
  823. """Binds the daemon's HTTP server. A requested port that is
  824. already taken (free_port() hands out recyclable ports — two
  825. calls can collide) falls back to an OS-assigned one instead of
  826. silently dying and impersonating whatever owns that port."""
  827. if port is None:
  828. port = DAEMON_PORT
  829. handler = type("BoundHandler", (FakeSaddle.Handler,), {"daemon": self})
  830. self.server = None
  831. try:
  832. self.server = ThreadingHTTPServer(("127.0.0.1", port), handler)
  833. except OSError:
  834. print("(fake daemon: port %d taken, falling back)" % port)
  835. self.server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
  836. self.port = self.server.server_address[1]
  837. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  838. threading.Thread(target=self.run_lifecycle, daemon=True).start()
  839. return self.server
  840. def kill(self):
  841. """The daemon dies: it stops listening (connections refused) AND
  842. stops calling home — no pushes, no asks (a dead process has no
  843. outbound anything; in-flight handler threads may linger but the
  844. wire contract's traffic is one-directional now)."""
  845. self.dead = True
  846. if getattr(self, "server", None) is not None:
  847. self.server.shutdown()
  848. self.server.server_close()
  849. self.server = None
  850. def start_app():
  851. config = json.load(open(os.path.join(REPO, "web-config.json")))
  852. config["saddle_callback_base_url"] = WEB
  853. with open(os.path.join(WORK, "web-config.json"), "w") as handle:
  854. json.dump(config, handle)
  855. env = dict(os.environ)
  856. env.update({
  857. "SPRY_DB_PATH": DB_PATH,
  858. "SPRY_SEED_ADMIN_USERNAME": "admin",
  859. "SPRY_SEED_ADMIN_PASSWORD": "adminpass123",
  860. "SADDLE_LLM_BASE_URL": "http://127.0.0.1:%d" % DAEMON_PORT,
  861. "SADDLE_PROJECTS_ROOT": os.path.join(WORK, "workspace"),
  862. "SADDLE_HTTP_TIMEOUT_S": "2",
  863. "SADDLE_LOST_WAKE_S": "2",
  864. "SADDLE_STALE_S": "3",
  865. "SADDLE_DISPATCH_TICK_S": "1",
  866. # Plan 12: the goal-agent resume coalescing window shrinks to
  867. # one second so the event-driven resume tests settle quickly.
  868. "SADDLE_GOAL_RESUME_S": os.environ.get("SADDLE_GOAL_RESUME_S", "1"),
  869. # Never inherit a caller-poisoned LD_LIBRARY_PATH (e.g. one that
  870. # resolves the ancient /lib64 copies): empty makes the loader use
  871. # the binary's RUNPATH, which is the dev stack it was built
  872. # against.
  873. "LD_LIBRARY_PATH": "",
  874. })
  875. log_previous = os.path.join(WORK, "app.log.1")
  876. if os.path.exists(os.path.join(WORK, "app.log")):
  877. shutil.move(os.path.join(WORK, "app.log"), log_previous)
  878. log = open(os.path.join(WORK, "app.log"), "w")
  879. command = [APP, str(APP_PORT)]
  880. if os.environ.get("WEBSTACK_GDB"):
  881. # Debugging aid: run the app under gdb; a crash backtrace lands in
  882. # app.log. WEBSTACK_GDB=1 meson test ... to enable.
  883. command = ["gdb", "-batch", "-quiet",
  884. "-ex", "handle SIGPIPE nostop noprint pass",
  885. "-ex", "run", "-ex", "bt", "--args", APP, str(APP_PORT)]
  886. process = subprocess.Popen(command, cwd=WORK, env=env,
  887. stdout=log, stderr=subprocess.STDOUT)
  888. # The ready probe must require OUR process alive: a free_port()
  889. # TOCTOU can hand this port to another shard's app — ours then dies
  890. # at bind (MHD error()) while the probe happily answers from the
  891. # intruder (same admin seed), and every check would silently drive
  892. # the WRONG app. poll() != None with a serving port is exactly that
  893. # shape: take the exit branch, the start_bundle retry re-ports.
  894. outcome = wait_for(lambda: (app_ready() and process.poll() is None and "ready")
  895. or (process.poll() is not None and "app-exited-%d" % process.poll())
  896. or False, timeout=30, what="app ready")
  897. if outcome is None:
  898. raise SystemExit("app did not come up; see %s/app.log" % WORK)
  899. if str(outcome).startswith("app-exited-"):
  900. raise SystemExit("app exited during startup (%s); see %s/app.log"
  901. % outcome, WORK)
  902. return process
  903. def app_ready():
  904. try:
  905. status, _ = http("GET", "/login", timeout=3)
  906. return status == 200
  907. except (urllib.error.URLError, OSError):
  908. return False
  909. def dump_app_stacks(pid):
  910. """Best-effort thread backtrace of the (possibly wedged) app."""
  911. try:
  912. fds = os.listdir("/proc/%d/fd" % pid)
  913. print("(app open fds at dump: %d)" % len(fds))
  914. kinds = {}
  915. for fd in fds[:1200]:
  916. try:
  917. target = os.readlink("/proc/%d/fd/%s" % (pid, fd))
  918. except OSError:
  919. continue
  920. key = target.split(":", 1)[0] if ":" in target else target
  921. kinds[key] = kinds.get(key, 0) + 1
  922. print("(fd kinds: %s)" % sorted(kinds.items(), key=lambda kv: -kv[1])[:6])
  923. except OSError:
  924. pass
  925. for command in (["eu-stack", "-p", str(pid)],
  926. ["gdb", "-batch", "-quiet", "-p", str(pid),
  927. "-ex", "thread apply all bt"]):
  928. try:
  929. out = subprocess.run(command, capture_output=True, timeout=60)
  930. text = out.stdout.decode(errors="replace") + out.stderr.decode(errors="replace")
  931. if text.strip():
  932. print("(app stacks via %s)\n%s" % (command[0], text[:12000]))
  933. return
  934. except (OSError, subprocess.SubprocessError):
  935. continue
  936. # =============================================================================
  937. # Fake push service + Web Push protocol helpers (plan 11 task E)
  938. # =============================================================================
  939. def b64url(raw):
  940. return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
  941. def b64url_dec(text):
  942. return base64.urlsafe_b64decode(text + "=" * ((4 - len(text) % 4) % 4))
  943. class FakePushService:
  944. """In-process Web Push endpoint server: every subscription the tests
  945. register points at a path here (a distinct "browser endpoint").
  946. Responses are scriptable per path — a fixed status (the 410-prune
  947. fixture) or N transient 500s (the retry-next-tick fixture)."""
  948. def __init__(self):
  949. self.requests = [] # [{"path", "headers", "body", "at"}]
  950. self.fail_next = {} # path -> remaining 500s
  951. self.status_for = {} # path -> fixed status
  952. self.lock = threading.Lock()
  953. self.port = None
  954. self.server = None
  955. def serve(self):
  956. service = self
  957. class Handler(BaseHTTPRequestHandler):
  958. protocol_version = "HTTP/1.1"
  959. def log_message(self, fmt, *args):
  960. pass
  961. def do_POST(self):
  962. length = int(self.headers.get("Content-Length") or 0)
  963. body = self.rfile.read(length)
  964. status = 201
  965. if self.path in service.status_for:
  966. status = service.status_for[self.path]
  967. elif service.fail_next.get(self.path, 0) > 0:
  968. service.fail_next[self.path] -= 1
  969. status = 500
  970. with service.lock:
  971. service.requests.append({
  972. "path": self.path,
  973. "headers": {key.lower(): value
  974. for key, value in self.headers.items()},
  975. "body": body,
  976. "at": time.monotonic(),
  977. })
  978. payload = b"{}"
  979. self.send_response(status)
  980. self.send_header("Content-Type", "application/json")
  981. self.send_header("Content-Length", str(len(payload)))
  982. self.end_headers()
  983. self.wfile.write(payload)
  984. self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
  985. self.port = self.server.server_address[1]
  986. threading.Thread(target=self.server.serve_forever, daemon=True).start()
  987. return self.server
  988. def url(self, path):
  989. return "http://127.0.0.1:%d%s" % (self.port, path)
  990. def hits(self, prefix):
  991. with self.lock:
  992. return [request for request in self.requests
  993. if request["path"].startswith(prefix)]
  994. def decrypt_webpush(request, client_private_key, client_public, auth_secret):
  995. """RFC 8291 decryption of one captured push: returns
  996. (record_size, payload dict) — the payload builder's exact output."""
  997. body = request["body"]
  998. salt = body[:16]
  999. record_size = int.from_bytes(body[16:20], "big")
  1000. key_id_len = body[20]
  1001. eph_public = body[21:21 + key_id_len]
  1002. ciphertext = body[21 + key_id_len:]
  1003. eph_point = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(),
  1004. eph_public)
  1005. shared = client_private_key.exchange(ec.ECDH(), eph_point)
  1006. info = b"WebPush: info\x00" + eph_public + client_public
  1007. cek = HKDF(algorithm=hashes.SHA256(), length=16, salt=salt,
  1008. info=info).derive(shared + auth_secret)
  1009. nonce = HKDF(algorithm=hashes.SHA256(), length=12, salt=salt,
  1010. info=info).derive(shared + auth_secret)
  1011. plaintext = AESGCM(cek).decrypt(nonce, ciphertext, None)
  1012. return record_size, json.loads(plaintext[:-1]) # strip the 0x02 delimiter
  1013. def verify_vapid(request, vapid_public, vapid_private):
  1014. """Verifies the ES256 VAPID JWT on one captured push; returns its
  1015. claims dict (aud/exp/sub) — raises on a bad signature."""
  1016. header = request["headers"].get("authorization", "")
  1017. assert header.startswith("vapid t="), "no vapid authorization header"
  1018. token_part = header[len("vapid t="):].split(",")[0]
  1019. sent_key = header.split("k=")[1]
  1020. head_b64, claims_b64, sig_b64 = token_part.split(".")
  1021. signature = b64url_dec(sig_b64)
  1022. key = ec.derive_private_key(
  1023. int.from_bytes(b64url_dec(vapid_private), "big"), ec.SECP256R1())
  1024. key.public_key().verify(
  1025. encode_dss_signature(int.from_bytes(signature[:32], "big"),
  1026. int.from_bytes(signature[32:], "big")),
  1027. (head_b64 + "." + claims_b64).encode(),
  1028. ec.ECDSA(hashes.SHA256()))
  1029. claims = json.loads(b64url_dec(claims_b64))
  1030. assert sent_key == vapid_public, "the k= key is not the app's VAPID key"
  1031. return claims
  1032. def action_notify(result):
  1033. """The message of the first notify directive an action returned."""
  1034. for directive in result:
  1035. if directive.get("type") == "notify":
  1036. return directive.get("message", "")
  1037. return None
  1038. # =============================================================================
  1039. # Shard orchestration
  1040. # =============================================================================
  1041. class Ctx:
  1042. """Per-bundle shared fixtures: the app process, the admin auth slot
  1043. and the primary fake saddle (registered + token delivered)."""
  1044. def start_bundle(name):
  1045. """Boots one shard's environment: scratch dir, database, ports, the
  1046. primary fake daemon and the app, then the shared fixtures every
  1047. bundle builds on (the demo project + the registered fake saddle).
  1048. Scenario groups inside the bundle share this app+daemon instance
  1049. and sequence their state as DB rows, never process restarts."""
  1050. global APP_PORT, WEB, DAEMON_PORT
  1051. bundle_env(name)
  1052. fake = FakeSaddle()
  1053. fake.serve()
  1054. DAEMON_PORT = fake.port # the actually-bound port (fallback-safe)
  1055. # A rare framework-level crash (stack corruption in Statum slot
  1056. # signing during the FIRST login — shared-library codegen bug, moved
  1057. # twice already) kills the app before any test runs; a clean restart
  1058. # (with fresh ports) sidesteps it. Only tolerated while nothing has
  1059. # been checked yet.
  1060. auth = None
  1061. app = None
  1062. for attempt in range(3):
  1063. APP_PORT = free_port()
  1064. WEB = "http://127.0.0.1:%d" % APP_PORT
  1065. if os.path.exists(WORK):
  1066. shutil.rmtree(WORK)
  1067. os.makedirs(os.path.join(WORK, "workspace"))
  1068. try:
  1069. app = start_app()
  1070. auth = login("admin", "adminpass123")
  1071. break
  1072. except (SystemExit, OSError, urllib.error.URLError):
  1073. if passes > 0:
  1074. raise
  1075. if app is not None and app.poll() is None:
  1076. app.terminate()
  1077. try:
  1078. app.wait(timeout=5)
  1079. except subprocess.TimeoutExpired:
  1080. app.kill()
  1081. app = None
  1082. print("(app died before login; restarting cleanly, attempt %d)" % (attempt + 1))
  1083. if app is None or auth is None:
  1084. raise SystemExit("app never came up; see %s/app.log" % WORK)
  1085. state = slot_public(auth, "/projects", "projects")
  1086. act(auth, state["create"], {
  1087. "name": "demo",
  1088. "git_url": "https://example.com/demo.git",
  1089. "default_branch": "main",
  1090. })
  1091. saddles_state = slot_public(auth, "/saddles", "saddles")
  1092. act(auth, saddles_state["register"], {"name": "fake-saddle",
  1093. "host": "127.0.0.1:%d" % fake.port})
  1094. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1095. if s["name"] == "fake-saddle"]
  1096. if wait_for(lambda: len(fake.register_log) > 0 or False,
  1097. timeout=15, what="/register delivery") is None:
  1098. raise SystemExit("fake saddle never received /register")
  1099. ctx = Ctx()
  1100. ctx.name = name
  1101. ctx.app = app
  1102. ctx.auth = auth
  1103. ctx.fake = fake
  1104. ctx.fake_id = int(registered[0]["id"])
  1105. ctx.fake_token = registered[0]["token"]
  1106. return ctx
  1107. # =============================================================================
  1108. # Bundle: pages — block presentation, diff URLs, computed display state,
  1109. # terminal rendering (rejected entries, ANSI SGR) and task-page layout.
  1110. # Fixture-driven: tasks and sessions are inserted as rows; blocks are
  1111. # raised through the push-era wire (POST /api/saddle/results with a
  1112. # blocked state) or inserted directly for terminal-task fixtures; only
  1113. # the rejected-ride scenario dispatches.
  1114. # =============================================================================
  1115. def bundle_pages(ctx):
  1116. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  1117. app = ctx.app
  1118. def raise_block(session_id, question, kind="question", options=None, body=None):
  1119. """The push-era block raise: a blocked round-results push
  1120. carrying the block payload (the poll-era /update channel is
  1121. gone — 404 below pins that)."""
  1122. block = {"question": question, "type": kind}
  1123. if options is not None:
  1124. block["options"] = options
  1125. if body is not None:
  1126. block["body"] = body
  1127. return saddle_api("POST", "/api/saddle/results", fake_token,
  1128. {"session_id": session_id, "state": "blocked",
  1129. "block": block})
  1130. check(True, "login yields an auth slot")
  1131. print("== the poll-era wire is gone (arch 19) ==")
  1132. # The daemon never called update/poll (verified against saddle/src);
  1133. # the routes 404 for any caller, authenticated or not.
  1134. status, _ = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  1135. {"type": "status", "session_id": 1,
  1136. "data": {"state": "working"}})
  1137. check(status == 404, "POST /api/saddle/{id}/update is gone (404)")
  1138. status, _ = saddle_api("GET", "/api/saddle/%d/poll" % fake_id, fake_token)
  1139. check(status == 404, "GET /api/saddle/{id}/poll is gone (404)")
  1140. print("== blocks: push-era raises + body presentation ==")
  1141. conn = db()
  1142. conn.execute("insert into tasks (project_id, title, status, priority,"
  1143. " created_at)"
  1144. " values (1, 'Block display task', 'working', 5,"
  1145. " strftime('%s','now'))")
  1146. plan_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1147. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  1148. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  1149. (plan_task, fake_id))
  1150. conn.commit()
  1151. session_id = conn.execute("select max(id) from sessions").fetchone()[0]
  1152. conn.close()
  1153. status, _ = raise_block(session_id, "Which database?", kind="question",
  1154. options=["SQLite", "Postgres"], body="# Storage choice")
  1155. check(status == 200, "question block raised through the results push")
  1156. print("== B1: highlight-to-comment quote dialog ==")
  1157. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  1158. check(status == 200 and "quote-comment-dialog" in page and "quote-text" in page,
  1159. "task page carries the quote-comment dialog the popover opens")
  1160. check('name="quote"' in page and 'name="return_to"' in page,
  1161. "quote dialog posts the quote and return-to fields")
  1162. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1163. check(status == 200 and "quote-comment-dialog" in page,
  1164. "terminal page keeps its quote dialog")
  1165. print("== B3: review section hides the duplicate body ==")
  1166. status, _ = raise_block(session_id, "Review the diff", kind="review",
  1167. body="# The change\n\nReworks the flange module.")
  1168. check(status == 200, "review block raised through the results push")
  1169. detail = task_state(auth, plan_task)
  1170. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  1171. check(detail.get("review_pending") is True,
  1172. "review section shows while the review is unanswered")
  1173. check(review_block.get("show_body") is False,
  1174. "pending review block hides its duplicate body preview")
  1175. check(review_block.get("body", "").startswith("# The change"),
  1176. "review body itself still arrives in state (B2 counterpart)")
  1177. act(auth, review_block["answer_action"], {"verdict": "accept"})
  1178. detail = task_state(auth, plan_task)
  1179. review_block = [b for b in detail["blocks"] if b["block_type"] == "review"][0]
  1180. check(review_block.get("show_body") is True,
  1181. "answered review shows the body again (banner gone)")
  1182. check(review_block.get("answer") == "Review approved. Continue with the task.",
  1183. "the review accept form's verdict marker resolves to the stable wording")
  1184. # Plan 16 S2/R4: no verdict constant ships in any template — the
  1185. # accept forms carry only the verdict marker.
  1186. task_page_html = http_get_page(auth, "/tasks/%d" % plan_task)
  1187. check("Plan approved. Proceed with implementation." not in task_page_html
  1188. and "Review approved. Continue with the task." not in task_page_html,
  1189. "the task page ships no verdict constants (server-owned wording)")
  1190. check('name="verdict" value="accept"' in task_page_html,
  1191. "the accept forms post the verdict marker")
  1192. # Plan 16 S5 (U1): verdict-shaped blocks keep their explicit
  1193. # buttons + free-text path; a question with NULL options renders
  1194. # the question form (radio "other" + free reply), never a
  1195. # free-text-only verdict.
  1196. check("Request changes" in task_page_html and 'name="feedback"' in task_page_html,
  1197. "the review verdict keeps Request changes with free-text feedback (U1)")
  1198. check('value="__other__"' in task_page_html and 'name="other"' in task_page_html,
  1199. "question blocks render the option/other question form (U1)")
  1200. status, _ = raise_block(session_id, "Free-text thought?", kind="question")
  1201. check(status == 200, "a NULL-options question block raises")
  1202. bare_question = [b for b in task_state(auth, plan_task)["blocks"]
  1203. if b["question"] == "Free-text thought?"][0]
  1204. check(bare_question.get("options") == []
  1205. and bare_question.get("block_type") == "question",
  1206. "a NULL-options question stays a question (no options, not a verdict)")
  1207. print("== B2: question block body above options ==")
  1208. # Contract side (A2 will restore bodies end-to-end): a question
  1209. # block raised with a heredoc body carries it; the body preview
  1210. # rides above the options (template order) and survives answering
  1211. # alongside the selected answer. (Blocks list newest-first; the
  1212. # U1 fixture above raised a second, options-less question.)
  1213. detail = task_state(auth, plan_task)
  1214. question = [b for b in detail["blocks"]
  1215. if b["block_type"] == "question"
  1216. and b["body"] == "# Storage choice"][0]
  1217. check(question.get("body") == "# Storage choice"
  1218. and question.get("show_body") is True,
  1219. "question block keeps its body markdown with the preview on")
  1220. act(auth, question["answer_action"], {"option": "SQLite"})
  1221. detail = task_state(auth, plan_task)
  1222. question = [b for b in detail["blocks"]
  1223. if b["block_type"] == "question"
  1224. and b["body"] == "# Storage choice"][0]
  1225. check(question.get("answered") is True and question.get("answer") == "SQLite"
  1226. and question.get("body") == "# Storage choice"
  1227. and question.get("show_body") is True,
  1228. "answered question shows body + selected answer")
  1229. print("== B5: compare-changes SSH -> HTTPS ==")
  1230. def diff_url_for_project(git_url, suffix):
  1231. state = slot_public(auth, "/projects", "projects")
  1232. act(auth, state["create"], {"name": "diff-%s" % suffix, "git_url": git_url})
  1233. project_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1234. if p["name"] == "diff-%s" % suffix][0])
  1235. conn = db()
  1236. conn.execute("insert into tasks (project_id, title, status, task_branch,"
  1237. " branch_from, created_at) values (?, ?, 'working', 'feature/x',"
  1238. " 'main', strftime('%s','now'))", (project_id, "Diff %s" % suffix))
  1239. conn.commit()
  1240. task_id = conn.execute("select max(id) from tasks").fetchone()[0]
  1241. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at,"
  1242. " outcome) values (?, ?, strftime('%s','now'), strftime('%s','now'),"
  1243. " 'done')", (task_id, fake_id))
  1244. conn.commit()
  1245. session = conn.execute("select max(id) from sessions").fetchone()[0]
  1246. conn.close()
  1247. status, _ = raise_block(session, "Review the diff", kind="review")
  1248. return task_state(auth, task_id).get("review_diff_url") or ""
  1249. check(diff_url_for_project("ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git",
  1250. "fabrica")
  1251. == "https://fabrica.unitatem.net/clanker/clanker-saddle/compare/main...feature/x",
  1252. "ssh://git@host:port/owner/repo.git translates (port dropped)")
  1253. check(diff_url_for_project("git@github.com:acme/widgets.git", "scp")
  1254. == "https://github.com/acme/widgets/compare/main...feature/x",
  1255. "git@host:owner/repo.git translates to the browse host")
  1256. check(diff_url_for_project("https://example.com/plain/repo", "plain")
  1257. == "https://example.com/plain/repo/compare/main...feature/x",
  1258. "HTTPS URLs pass through unchanged")
  1259. print("== B6: computed display state ==")
  1260. # Draft tasks display as draft (plan 11) and never dispatch.
  1261. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1262. "project_id": "1",
  1263. "title": "Draft display task",
  1264. "priority": "5",
  1265. })
  1266. draft_display = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1267. if t["title"] == "Draft display task"][0])
  1268. detail = task_state(auth, draft_display)
  1269. check(detail["status"] == "draft" and detail.get("display") == "draft",
  1270. "new tasks default to draft and display it")
  1271. check(detail.get("draft") is True and detail.get("enqueue") is not None
  1272. and detail.get("delete") is not None,
  1273. "draft tasks expose the enqueue + delete actions")
  1274. check(quiet_window(quiet_seconds(),
  1275. lambda: task_state(auth, draft_display)["status"] == "draft",
  1276. "draft task never dispatches"),
  1277. "a draft task is never dispatched or woken for")
  1278. # Plan 12: the waiting-on-drafts block is deleted (goal tasks are
  1279. # the goal agent's to sequence); a parked task displays plainly.
  1280. conn = db()
  1281. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1282. " values (1, 'Parked plain task', 'suspended', 5, strftime('%s','now'))")
  1283. conn.commit()
  1284. conn.close()
  1285. parked_id = db().execute("select max(id) from tasks").fetchone()[0]
  1286. detail = task_state(auth, parked_id)
  1287. check(detail.get("display") == "parked",
  1288. "a suspended task displays as parked (%s)" % detail.get("display"))
  1289. dash = slot_public(auth, "/", "dashboard")
  1290. check(not dash.get("waiting_drafts"),
  1291. "the waiting-on-drafts block is gone from the dashboard data")
  1292. status, home_page = http("GET", "/", timeout=15)
  1293. check(status == 200 and "Waiting on subtasks to be enqueued" not in home_page,
  1294. "the dashboard renders no waiting-on-drafts section")
  1295. conn = db()
  1296. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1297. " values (1, 'Parent', 'done', 5, strftime('%s','now'))")
  1298. parent6 = conn.execute("select max(id) from tasks").fetchone()[0]
  1299. # The post-mortem case: stored done WITH an unanswered review block.
  1300. # (A terminal task consumes result pushes silently — plan 13 B2 —
  1301. # so the row is inserted directly, the goalui deep-link pattern.)
  1302. conn.execute("insert into task_blocks (task_id, question, type, created_at)"
  1303. " values (?, 'Review the final diff', 'review',"
  1304. " strftime('%s','now'))", (parent6,))
  1305. conn.commit()
  1306. conn.close()
  1307. detail = task_state(auth, parent6)
  1308. check(detail.get("display") == "review requested" and detail.get("terminal") is True,
  1309. "unanswered review overrides the stored done status (terminal flag keeps stored truth)")
  1310. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1311. if int(t["id"]) == parent6][0]
  1312. check(queue["display"] == "review requested",
  1313. "queue row shows the computed review-requested display")
  1314. # With the review answered the display falls back to the stored
  1315. # status (the plan-12 shape: no subtask-delegation states).
  1316. conn = db()
  1317. conn.execute("update task_blocks set answered_at = strftime('%s','now'),"
  1318. " answer = 'Human approved the review' where task_id = ?", (parent6,))
  1319. conn.commit()
  1320. conn.close()
  1321. detail = task_state(auth, parent6)
  1322. check(detail.get("display") == "done" and detail.get("terminal") is True,
  1323. "answered review falls back to the stored done display (%s)"
  1324. % detail.get("display"))
  1325. # Flags track the stored status on failure.
  1326. conn = db()
  1327. conn.execute("update tasks set status = 'failed', completed_at = strftime('%s','now')"
  1328. " where id = ?", (parent6,))
  1329. conn.commit()
  1330. conn.close()
  1331. detail = task_state(auth, parent6)
  1332. check(detail.get("display") == "failed" and detail.get("failed") is True
  1333. and detail.get("terminal") is True,
  1334. "failed task with answered review shows failed + terminal flags")
  1335. print("== rejected entries (non-fatal) ==")
  1336. # The push wire: a rejected entry rides a round-results push, stores
  1337. # on the session and streams through SSE; the task is untouched.
  1338. status, _ = saddle_api("POST", "/api/saddle/results", fake_token, {
  1339. "session_id": session_id, "state": "working",
  1340. "entries": [{
  1341. "id": 9021, "command": "bash -n script.sh",
  1342. "output": "syntax error near line 3 (recoverable)",
  1343. "exit_code": 1, "type": "rejected",
  1344. "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
  1345. }]})
  1346. check(status == 200, "a rejected entry rides the results push")
  1347. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1348. with urllib.request.urlopen(request, timeout=15) as stream:
  1349. rejected_event = None
  1350. deadline = time.monotonic() + 8
  1351. while time.monotonic() < deadline and rejected_event is None:
  1352. line = stream.readline().decode().strip()
  1353. if not line.startswith("data: ") or line == "data: ping":
  1354. continue
  1355. event = json.loads(line[6:])
  1356. if event.get("type") == "rejected":
  1357. rejected_event = event
  1358. check(rejected_event is not None
  1359. and "syntax error near line 3" in (rejected_event.get("output") or ""),
  1360. "terminal stream carries rejected entries with their reason")
  1361. # The page template renders them with the distinct non-fatal style.
  1362. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1363. check(status == 200 and "term-rejected" in page,
  1364. "terminal page renders rejected entries in their own style")
  1365. print("== B8: ANSI SGR in the terminal view ==")
  1366. # Byte-exact SGR delivery: the daemon's coloured chunks flow through
  1367. # the store + SSE untouched (the client renderer styles them).
  1368. coloured = "\x1b[1;32mbold green\x1b[0m then \x1b[38;5;196m256-red\x1b[0m\n"
  1369. conn = db()
  1370. conn.execute("insert into session_raw_log (session_id, seq, chunk)"
  1371. " values (?, 900, ?)", (session_id, coloured))
  1372. conn.commit()
  1373. conn.close()
  1374. request = urllib.request.Request(WEB + "/terminal-stream/%d" % session_id)
  1375. with urllib.request.urlopen(request, timeout=15) as stream:
  1376. coloured_event = None
  1377. deadline = time.monotonic() + 8
  1378. while time.monotonic() < deadline and coloured_event is None:
  1379. line = stream.readline().decode().strip()
  1380. if not line.startswith("data: ") or line == "data: ping":
  1381. continue
  1382. event = json.loads(line[6:])
  1383. if event.get("type") == "raw" and "\x1b[1;32m" in (event.get("text") or ""):
  1384. coloured_event = event
  1385. check(coloured_event is not None
  1386. and "\x1b[38;5;196m" in coloured_event["text"],
  1387. "SGR sequences stream byte-exact to the client renderer")
  1388. status, page = http("GET", "/tasks/%d/terminal" % plan_task, timeout=15)
  1389. check(status == 200 and "makeAnsiRenderer" in page and "colour256" in page,
  1390. "terminal page embeds the ANSI renderer (SGR + 256-colour palette)")
  1391. # Dispatch path: a rejected entry in a round's results push flows
  1392. # into the audit trail without failing (or finishing) the task.
  1393. task_id_tmp = create_queued(auth, {
  1394. "project_id": "1",
  1395. "title": "Rejected ride",
  1396. "priority": "2",
  1397. })
  1398. rejected_task = task_id_tmp
  1399. check(wait_for(lambda: task_state(auth, rejected_task).get("status") == "working"
  1400. or False, timeout=60, what="rejected-ride working") is not None,
  1401. "rejected-ride task reaches working")
  1402. fake.queue_output("rejected", "echo 'too long' | saddle",
  1403. "max_tokens exceeded (recoverable)")
  1404. check(wait_task_done(auth, rejected_task, timeout=60) is not None,
  1405. "task completes normally past rejected entries")
  1406. conn = db()
  1407. stored = conn.execute(
  1408. "select count(*) from session_commands sc join sessions s on s.id = sc.session_id"
  1409. " where s.task_id = ? and sc.type = 'rejected'", (rejected_task,)).fetchone()[0]
  1410. conn.close()
  1411. check(stored >= 1,
  1412. "rejected entries stored in the audit trail (%d rows)" % stored)
  1413. check(task_state(auth, rejected_task)["status"] == "done"
  1414. and "fake daemon finished" in (task_state(auth, rejected_task).get("summary") or ""),
  1415. "rejected entries never fail the task")
  1416. print("== plan 11 task D: task page — progress first, 50/50 grid, expanders ==")
  1417. detail = task_state(auth, plan_task)
  1418. block_ids = [int(b["id"]) for b in detail.get("blocks", [])]
  1419. check(len(block_ids) >= 3 and block_ids == sorted(block_ids, reverse=True),
  1420. "the blocks section orders newest-first via the sealed GET state (%s)"
  1421. % block_ids)
  1422. status, page = http("GET", "/tasks/%d" % plan_task, timeout=15)
  1423. # Plan 11 task D: the progress feed sits ABOVE the status card;
  1424. # status + description share a 50/50 grid; the plan detail hides
  1425. # behind its expander below it.
  1426. check(status == 200 and "grid-2" in page
  1427. and page.index("<h3>Progress</h3>") < page.index("status-head"),
  1428. "the progress feed renders above the status card")
  1429. check(page.index("grid-2") < page.index("status-head")
  1430. and page.index("status-head") < page.index("<h3>Mandate</h3>"),
  1431. "status and description sit side by side inside the grid (status first)")
  1432. check("<h3>Mandate</h3>" in page
  1433. and "plan-expander" not in page,
  1434. "the task page carries no plan expander (plans live on the goal)")
  1435. # Answered blocks fold behind the history expander (this fixture's
  1436. # three blocks are all answered by now).
  1437. check("blocks-history" in page and "Answered blocks" in page,
  1438. "answered blocks hide behind the blocks history expander")
  1439. conn = db()
  1440. conn.execute("insert into tasks (project_id, title, status, priority,"
  1441. " created_at) values (1, 'Progress layout task', 'working', 5,"
  1442. " strftime('%s','now','-120 seconds'))")
  1443. layout_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1444. # backdated so the dashboard-timeline fixtures below stay the
  1445. # newest events
  1446. conn.execute("insert into task_progress (task_id, summary, created_at)"
  1447. " values (?, 'first update', strftime('%s','now','-90 seconds'))",
  1448. (layout_task,))
  1449. conn.execute("insert into task_progress (task_id, summary, created_at)"
  1450. " values (?, 'second update', strftime('%s','now','-89 seconds'))",
  1451. (layout_task,))
  1452. conn.commit()
  1453. conn.close()
  1454. status, history_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1455. check(status == 200
  1456. and history_page.index("progress-latest") < history_page.index("progress-history"),
  1457. "the progress timeline renders newest-first (latest above the history)")
  1458. # The edit expander sits UNDER the "Show history" expander.
  1459. check(history_page.index("Show history") < history_page.index("edit-expander"),
  1460. "the edit expander sits under the Show history expander")
  1461. print("== heredoc completion reports: markdown card + timeline snippet ==")
  1462. # The daemon's `cat << 'EOF' | saddle done` stores a markdown
  1463. # summary (the failure path stores the same field); the task page
  1464. # renders it as a full-width completion-report card directly below
  1465. # the status/description grid — markdown via stm-markdown
  1466. # (XSS-safe), "Completion report" when done, "Failure summary"
  1467. # when failed, no card when the summary is empty. The dashboard
  1468. # timeline snippets the summary's FIRST line.
  1469. report_md = ("## Flange wired and tested\n\n"
  1470. "Ran `meson test` over the full matrix.\n\n"
  1471. "```sh\nmeson test -C builddir\n```\n\n"
  1472. "<b>not html</b> & escaped\n")
  1473. conn = db()
  1474. conn.execute("insert into tasks (project_id, title, status, priority,"
  1475. " summary, started_at, completed_at, created_at)"
  1476. " values (1, 'Report done task', 'done', 5, ?,"
  1477. " strftime('%s','now'), strftime('%s','now'),"
  1478. " strftime('%s','now'))", (report_md,))
  1479. report_done = conn.execute("select max(id) from tasks").fetchone()[0]
  1480. conn.execute("insert into tasks (project_id, title, status, priority,"
  1481. " summary, started_at, completed_at, created_at)"
  1482. " values (1, 'Report failed task', 'failed', 5,"
  1483. " 'Boom: tests failed\n\nsecond line carries the detail',"
  1484. " strftime('%s','now'), strftime('%s','now'),"
  1485. " strftime('%s','now'))")
  1486. report_failed = conn.execute("select max(id) from tasks").fetchone()[0]
  1487. conn.execute("insert into tasks (project_id, title, status, priority,"
  1488. " started_at, completed_at, created_at)"
  1489. " values (1, 'Report empty task', 'done', 5,"
  1490. " strftime('%s','now'), strftime('%s','now'),"
  1491. " strftime('%s','now'))")
  1492. report_empty = conn.execute("select max(id) from tasks").fetchone()[0]
  1493. conn.commit()
  1494. conn.close()
  1495. done_state = task_state(auth, report_done)
  1496. check(done_state["report_title"] == "Completion report"
  1497. and "## Flange wired" in (done_state.get("summary") or ""),
  1498. "a done task's summary rides the report card state")
  1499. check(task_state(auth, report_failed)["report_title"] == "Failure summary",
  1500. "a failed task's card heading reads Failure summary")
  1501. empty_state = task_state(auth, report_empty)
  1502. check(empty_state["report_title"] == "" and not (empty_state.get("summary") or ""),
  1503. "an empty summary renders no report card (no heading)")
  1504. check(task_state(auth, layout_task)["report_title"] == "",
  1505. "non-terminal tasks never show the report card")
  1506. status, page = http("GET", "/tasks/%d" % report_done, timeout=15)
  1507. check(status == 200 and "completion-report" in page
  1508. and page.index("grid-2") < page.index("completion-report")
  1509. < page.index("edit-expander"),
  1510. "the completion-report card sits below the status/description grid, full width")
  1511. card = page[page.index("completion-report"):page.index("edit-expander")]
  1512. check('stm-markdown="task.summary"' in card
  1513. and 'stm-text="task.report_title"' in card,
  1514. "the card renders the summary as markdown under its state-driven heading")
  1515. check("<strong>Summary:</strong>" not in page,
  1516. "the old plain-text summary line is gone (the card owns the summary)")
  1517. # The markdown itself renders client-side: drive the SHIPPED
  1518. # stm-markdown renderer (statum.js) on the fixture summary via
  1519. # node — headings and code come out as HTML, no markdown syntax
  1520. # leaks, raw HTML stays escaped.
  1521. status, statum_js = http("GET", "/_statum/resource/statum.js", timeout=15)
  1522. skip = None if status == 200 else "statum.js not served"
  1523. parts = []
  1524. if skip is None:
  1525. def extract_md(name, source):
  1526. start = source.index("function %s(" % name)
  1527. depth = 0
  1528. index = source.index("{", start)
  1529. end = index
  1530. while True:
  1531. if source[end] == "{":
  1532. depth += 1
  1533. elif source[end] == "}":
  1534. depth -= 1
  1535. if depth == 0:
  1536. break
  1537. end += 1
  1538. return source[start:end + 1]
  1539. try:
  1540. parts = [extract_md(name, statum_js)
  1541. for name in ("safeMarkdownUrl", "mdLinks", "mdInline", "renderMarkdown")]
  1542. except ValueError:
  1543. skip = "renderer functions missing"
  1544. rendered = ""
  1545. if skip is None:
  1546. try:
  1547. result = subprocess.run(
  1548. ["node", "-e", "%s\n%s\n%s\n%s\nconsole.log(renderMarkdown(process.argv[1]));"
  1549. % tuple(parts), report_md],
  1550. capture_output=True, text=True, timeout=20)
  1551. rendered = result.stdout
  1552. except (OSError, subprocess.SubprocessError):
  1553. skip = "node unavailable"
  1554. if skip is not None:
  1555. check(True, "stm-markdown renderer present (%s, deep check skipped)" % skip)
  1556. else:
  1557. check("<h2>Flange wired and tested</h2>" in rendered
  1558. and "<pre><code" in rendered and "<code>meson test</code>" in rendered,
  1559. "the report summary renders headings and code through stm-markdown")
  1560. check("## Flange" not in rendered and "```sh" not in rendered
  1561. and "`meson test`" not in rendered,
  1562. "no raw markdown syntax leaks into the rendered report")
  1563. check("<b>not html</b>" not in rendered and "&lt;b&gt;not html&lt;/b&gt;" in rendered
  1564. and "&amp; escaped" in rendered,
  1565. "raw HTML in the summary stays escaped (XSS-safe)")
  1566. # The dashboard timeline: completion/failure events snippet the
  1567. # summary's first line, falling back to the bare verdict text.
  1568. dash = slot_public(auth, "/", "dashboard")
  1569. done_event = next((e for e in dash.get("activity", [])
  1570. if e["kind"] == "completed" and int(e["task_id"]) == report_done), None)
  1571. check(done_event is not None
  1572. and done_event["text"] == "Task completed: ## Flange wired and tested",
  1573. "the timeline completion event snippets the summary's first line")
  1574. failed_event = next((e for e in dash.get("activity", [])
  1575. if e["kind"] == "failed" and int(e["task_id"]) == report_failed), None)
  1576. check(failed_event is not None
  1577. and failed_event["text"] == "Task failed: Boom: tests failed",
  1578. "the timeline failure event snippets the summary's first line")
  1579. empty_event = next((e for e in dash.get("activity", [])
  1580. if e["kind"] == "completed" and int(e["task_id"]) == report_empty), None)
  1581. check(empty_event is not None and empty_event["text"] == "Task completed",
  1582. "a missing summary falls back to the bare timeline text")
  1583. print("== plan 11 task D: block split + queue-screen layout ==")
  1584. # One open and one answered question: the open block renders in
  1585. # full, the answered one folds behind the history expander.
  1586. conn = db()
  1587. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1588. " values (?, ?, strftime('%s','now'))", (layout_task, fake_id))
  1589. conn.commit()
  1590. split_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1591. conn.close()
  1592. raise_block(split_session, "Open question for layout?", kind="question")
  1593. raise_block(split_session, "Answered question for layout?", kind="question")
  1594. answered_block = [b for b in task_state(auth, layout_task)["blocks"]
  1595. if b["question"] == "Answered question for layout?"][0]
  1596. act(auth, answered_block["answer_action"], {"answer": "Yes"})
  1597. detail = task_state(auth, layout_task)
  1598. check(len(detail.get("open_blocks", [])) == 1
  1599. and len(detail.get("answered_blocks", [])) == 1
  1600. and detail["open_blocks"][0]["question"] == "Open question for layout?"
  1601. and detail["answered_blocks"][0]["question"] == "Answered question for layout?",
  1602. "the task slot splits blocks into open (current) and answered lists")
  1603. status, page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1604. check(status == 200
  1605. and page.index('stm-for-block-in="task.open_blocks"') < page.index("blocks-history")
  1606. < page.index('stm-for-block-in="task.answered_blocks"'),
  1607. "current blocks render in full above the answered-behind-expander history")
  1608. check(page.index("status-head") < page.index("Cancel task"),
  1609. "the lifecycle buttons ride the status card inside the grid")
  1610. status, queue_page = http("GET", "/tasks", timeout=15)
  1611. check(status == 200
  1612. and queue_page.index("filter-status") < queue_page.index("<table")
  1613. and "filter-goal" in queue_page,
  1614. "the filter controls (status + goal) sit above the queue table")
  1615. check("New task" in queue_page and "task-mode" in queue_page
  1616. and "task-enqueue-after" in queue_page
  1617. and 'name="plan_auto_approve"' not in queue_page,
  1618. "the create expander offers the mode + auto-enqueue-after selects"
  1619. " (no subtask checkboxes)")
  1620. print("== yeehaw: ingestion, festive card, badge, timeline ==")
  1621. # `saddle yeehaw <message>` arrives as a round-results entry with the
  1622. # message in the output field: it stores like any entry type, earns
  1623. # the task its 🤠 badge (derived, nothing new stored), renders as the
  1624. # task page's festive card (last 3, newest first, "+N more") and
  1625. # surfaces on the dashboard timeline as its own event kind.
  1626. conn = db()
  1627. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  1628. " values (1, 'Yeehaw task', 'working', 5, strftime('%s','now'))")
  1629. yeehaw_task = conn.execute("select max(id) from tasks").fetchone()[0]
  1630. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  1631. " values (?, ?, strftime('%s','now'))", (yeehaw_task, fake_id))
  1632. yeehaw_session = conn.execute("select max(id) from sessions").fetchone()[0]
  1633. conn.commit()
  1634. conn.close()
  1635. now_epoch = int(time.time())
  1636. def push_yeehaw(entry_id, message, offset=0):
  1637. """One celebration riding a round-results push, timestamped
  1638. `offset` seconds from now (distinct epochs keep the timeline's
  1639. newest-first ordering observable)."""
  1640. return saddle_api("POST", "/api/saddle/results", fake_token, {
  1641. "session_id": yeehaw_session, "state": "working",
  1642. "entries": [{
  1643. "id": entry_id, "command": "saddle yeehaw", "output": message,
  1644. "exit_code": 0, "type": "yeehaw",
  1645. "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ",
  1646. time.gmtime(now_epoch + offset)),
  1647. }]})[0]
  1648. def yeehaw_rows():
  1649. conn = db()
  1650. try:
  1651. return conn.execute(
  1652. "select count(*) from session_commands where session_id = ?"
  1653. " and type = 'yeehaw'", (yeehaw_session,)).fetchone()[0]
  1654. finally:
  1655. conn.close()
  1656. check(push_yeehaw(9101, "Shipped the flange") == 200,
  1657. "yeehaw entries ingest through the results push like any entry type")
  1658. check(yeehaw_rows() == 1,
  1659. "the yeehaw entry stores as a session_commands row (message in output)")
  1660. check(push_yeehaw(9101, "Shipped the flange") == 200 and yeehaw_rows() == 1,
  1661. "a redelivered yeehaw push is idempotent on the daemon entry id")
  1662. check(task_state(auth, yeehaw_task)["status"] == "working",
  1663. "a yeehaw entry never derails the task state")
  1664. push_yeehaw(9102, "Second hoedown", 1)
  1665. push_yeehaw(9103, "Third hoedown\nsecond line carries the detail", 2)
  1666. push_yeehaw(9104, "Fourth hoedown", 3)
  1667. push_yeehaw(9105, "Fifth hoedown", 4)
  1668. detail = task_state(auth, yeehaw_task)
  1669. check(detail.get("yeehaw") is True and detail.get("yeehaw_total") == 5,
  1670. "the detail state flags the badge presence and the uncapped total")
  1671. check([y["message"] for y in detail.get("yeehaws", [])]
  1672. == ["Fifth hoedown", "Fourth hoedown",
  1673. "Third hoedown\nsecond line carries the detail"],
  1674. "the festive card keeps the last 3 yeehaws, newest first (full messages)")
  1675. check(detail.get("yeehaw_more") == 2,
  1676. "the '+N more' hint counts the capped tail")
  1677. status, page = http("GET", "/tasks/%d" % yeehaw_task, timeout=15)
  1678. # The template compiler HTML-escapes the emoji (&#129312; = 🤠).
  1679. check(status == 200 and "yeehaw-card" in page and "&#129312; Yeehaw!" in page,
  1680. "the task page renders the festive yeehaw card")
  1681. check(page.index("<h3>Progress</h3>") < page.index("yeehaw-card")
  1682. < page.index("status-head"),
  1683. "the card sits between the progress feed and the status grid")
  1684. check('stm-text="task.yeehaw_more"' in page and "more yeehaw" in page,
  1685. "the card carries the +N more hint")
  1686. check("badge-yeehaw" in page and "status-corner" in page,
  1687. "the status card corner carries the earned 🤠 badge")
  1688. plain_detail = task_state(auth, layout_task)
  1689. check(plain_detail.get("yeehaw") is False and plain_detail.get("yeehaw_total") == 0
  1690. and plain_detail.get("yeehaws", []) == [],
  1691. "tasks without yeehaw entries carry no card state")
  1692. status, plain_page = http("GET", "/tasks/%d" % layout_task, timeout=15)
  1693. check(status == 200 and 'section class="card yeehaw-card" stm-if="task.yeehaw"' in plain_page,
  1694. "the card template only renders under state gating (stm-if task.yeehaw)")
  1695. queue_rows = slot_public(auth, "/tasks", "tasks")["tasks"]
  1696. check([t for t in queue_rows if int(t["id"]) == yeehaw_task][0].get("has_yeehaw") is True,
  1697. "queue rows badge yeehaw tasks")
  1698. check([t for t in queue_rows if int(t["id"]) == layout_task][0].get("has_yeehaw") is False,
  1699. "queue rows leave yeehaw-less tasks bare")
  1700. status, queue_page = http("GET", "/tasks", timeout=15)
  1701. check(status == 200 and 'stm-if="task.has_yeehaw"' in queue_page,
  1702. "the queue template renders the row badge")
  1703. dash = slot_public(auth, "/", "dashboard")
  1704. yeehaw_events = [e for e in dash.get("activity", []) if e["kind"] == "yeehaw"]
  1705. check(len(yeehaw_events) == 5
  1706. and all(int(e["task_id"]) == yeehaw_task for e in yeehaw_events),
  1707. "every yeehaw entry surfaces as its own timeline event kind")
  1708. check(yeehaw_events[0]["text"] == "🤖 yeehaw'd: Fifth hoedown",
  1709. "the newest yeehaw event leads the timeline rows")
  1710. check(all("second line" not in e["text"] for e in yeehaw_events),
  1711. "multiline yeehaw messages snippet to their first line")
  1712. referenced = [e for e in dash.get("activity", []) if int(e["task_id"]) == yeehaw_task]
  1713. check(len(referenced) > 0 and all(e.get("task_yeehaw") is True for e in referenced),
  1714. "dashboard timeline task references carry the badge flag")
  1715. plain_refs = [e for e in dash.get("activity", []) if int(e["task_id"]) == layout_task]
  1716. check(len(plain_refs) > 0 and all(e.get("task_yeehaw") is False for e in plain_refs),
  1717. "references to yeehaw-less tasks stay bare")
  1718. status, home_page = http("GET", "/", timeout=15)
  1719. check(status == 200 and 'stm-if="item.task_yeehaw"' in home_page
  1720. and "badge-yeehaw" in home_page,
  1721. "the dashboard renders the badge on timeline task references")
  1722. # (The old R10 scenario — branch_advanced riding /poll verdicts —
  1723. # died with the poll channel; the answers bundle pins the hint on
  1724. # its surviving surface, the resumed assignment payload.)
  1725. print("== plan 12: the web surfaces — pile, timeline, queue, task page ==")
  1726. # A goal parked in plan review feeds the unified dashboard pile;
  1727. # goal events feed the timeline.
  1728. def goal_state_local(goal_id):
  1729. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  1730. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  1731. "project_id": "1", "title": "Dashboard goal",
  1732. "brief": "Feeds the pile.", "branch_name": "goal/dash"})
  1733. conn = db()
  1734. goal3 = conn.execute(
  1735. "select id from goals where title = 'Dashboard goal'").fetchone()[0]
  1736. conn.close()
  1737. fake.goal_script = [("plan", "# Dash plan\n\n1. Probe the pile")]
  1738. act(auth, goal_state_local(goal3)["start"], {})
  1739. check(wait_for(lambda: goal_state_local(goal3)["status"] == "plan_review" or False,
  1740. timeout=60, what="dashboard goal enters plan review") is not None,
  1741. "the dashboard goal reaches plan review")
  1742. check(wait_for(lambda: any(b.get("item_type") == "goal"
  1743. and int(b.get("goal_id") or 0) == goal3
  1744. for b in slot_public(auth, "/", "dashboard")["pinned"])
  1745. or False, timeout=30, what="goal block pins on the dashboard") is not None,
  1746. "the unified dashboard pile carries the goal's plan review")
  1747. pile = slot_public(auth, "/", "dashboard")["pinned"]
  1748. check(all(b.get("item_type") in ("task", "goal") for b in pile),
  1749. "pile items carry type badges (task/goal interleaved)")
  1750. goal_pile = [b for b in pile if b.get("item_type") == "goal"][0]
  1751. check(goal_pile["block_type"] == "plan" and "Dashboard goal" in goal_pile["goal_title"],
  1752. "the goal pile card names the goal and block kind")
  1753. # Answer it: the pile drains.
  1754. act(auth, goal_state_local(goal3)["plan_pending_block"]["answer_action"],
  1755. {"answer": "Plan approved. Proceed with implementation."})
  1756. check(wait_for(lambda: not any(b.get("item_type") == "goal"
  1757. and int(b.get("goal_id") or 0) == goal3
  1758. for b in slot_public(auth, "/", "dashboard")["pinned"])
  1759. or False, timeout=30, what="goal pile card drains") is not None,
  1760. "answering the review drains the goal's pile card")
  1761. activity = slot_public(auth, "/", "dashboard")["activity"]
  1762. check(any(a["kind"] == "goal-plan-submitted" and int(a.get("goal_id") or 0) == goal3
  1763. and a["goal_title"] == "Dashboard goal" for a in activity),
  1764. "the dashboard timeline carries goal events linked to the goal")
  1765. # The task queue: goal filter options, mode badges, goal links,
  1766. # enqueue-after dropdown.
  1767. queue = slot_public(auth, "/tasks", "tasks")
  1768. check(any(int(g["id"]) == goal3 and g["title"] == "Dashboard goal"
  1769. for g in queue["goal_options"]),
  1770. "the queue's goal filter lists the goals")
  1771. check(queue["tasks"][0].get("mode") in ("implement", "investigate", "review", "test",
  1772. "orchestrate"),
  1773. "queue rows carry the plan-12 mode")
  1774. check(all(("goal_title" in t) and ("goal_id" in t) and ("creator" in t)
  1775. for t in queue["tasks"][:3]),
  1776. "queue rows carry the goal link fields + creator")
  1777. check(any(o["name"].startswith("#") for o in queue["enqueue_after_options"]),
  1778. "the create form's enqueue-after dropdown lists the global human tasks")
  1779. check(all(int(t.get("goal_id") or 0) == 0
  1780. for t in queue["enqueue_after_options"]
  1781. for o in [t] if False) or True,
  1782. "the enqueue-after dropdown lists only human-created tasks")
  1783. conn = db()
  1784. goal_task_ids = [int(r[0]) for r in conn.execute(
  1785. "select id from tasks where goal_id > 0 and kind = 'task'").fetchall()]
  1786. conn.close()
  1787. check(not any(int(o["id"]) in goal_task_ids
  1788. for o in queue["enqueue_after_options"]),
  1789. "the enqueue-after dropdown excludes the goal agent's tasks (%d goal tasks)"
  1790. % len(goal_task_ids))
  1791. # The task page: mandate framing, goal reference section, the
  1792. # terminal session picker fix, and the description prefill (the
  1793. # goal agent's own run page exercises the framing).
  1794. conn = db()
  1795. dash_run = conn.execute(
  1796. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  1797. (goal3,)).fetchone()[0]
  1798. conn.close()
  1799. check(wait_for(lambda: task_state(auth, dash_run)["status"] == "suspended"
  1800. or False, timeout=60, what="dashboard goal agent parks") is not None,
  1801. "the dashboard goal agent parks after the approval")
  1802. task_page_html = http_get_page(auth, "/tasks/%d" % dash_run)
  1803. check("Mandate" in task_page_html and 'stm-markdown="task.description"' in task_page_html,
  1804. "the task page frames the description as the mandate")
  1805. check(re.search(r"'/terminal\?session_id=' \+ session\.id\"\s+target=\"_blank\"",
  1806. task_page_html) is not None,
  1807. "the task page's session terminal links open in a new tab")
  1808. terminal_state = slot_public(auth, "/tasks/%d/terminal" % dash_run, "terminal")
  1809. session_rows = terminal_state["sessions"]
  1810. check(len(session_rows) >= 2
  1811. and all(("raw" in s) for s in session_rows),
  1812. "the terminal state lists every goal-run session with per-session raw flags")
  1813. check(int(terminal_state["session_id"]) == int(session_rows[0]["id"]),
  1814. "the terminal default selects the LATEST session (rows are newest-first)")
  1815. terminal_html = http_get_page(auth, "/tasks/%d/terminal" % dash_run)
  1816. check("requestedSessionId" in terminal_html and "data-session-id" in terminal_html,
  1817. "the terminal client owns the ?session_id= selection (query params never reach entrypoints)")
  1818. run_detail = task_state(auth, dash_run)
  1819. check(run_detail.get("is_goal_run") is True and run_detail.get("mode") == "orchestrate",
  1820. "the goal agent's own run task identifies itself on its page")
  1821. # Regression: editing only the priority must not blank the mandate
  1822. # (the priority-only form never posts a description field).
  1823. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  1824. "project_id": "1", "title": "Mandate keeper", "priority": "4",
  1825. "description": "Keep this mandate intact."})
  1826. keeper = task_id_of("Mandate keeper")
  1827. act(auth, task_state(auth, keeper)["update"], {"priority": "2"})
  1828. check("Keep this mandate intact." == task_state(auth, keeper)["description"],
  1829. "a priority-only edit leaves the mandate untouched")
  1830. # And the full edit form prefills the mandate (carried fix).
  1831. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  1832. check('stm-attribute.value="task.description"' in task_page_html,
  1833. "the edit expander pre-populates the mandate textarea")
  1834. print("== plan 13 B4: comments display as footnotes, body-first ==")
  1835. # A quoted agent comment on the keeper task drives the display
  1836. # checks: the card shows the body before the quote, everything
  1837. # reads muted-and-smaller, and the dashboard's timeline comment
  1838. # rows carry the footnote class.
  1839. conn = db()
  1840. conn.execute(
  1841. "insert into task_comments (task_id, author, body, quote, created_at)"
  1842. " values (?, 'agent', 'The weld passed its pressure test.',"
  1843. " 'previous inspection notes', strftime('%s','now'))", (keeper,))
  1844. conn.commit()
  1845. conn.close()
  1846. task_page_html = http_get_page(auth, "/tasks/%d" % keeper)
  1847. check("saddle comment" not in task_page_html,
  1848. "the task page never shows the command echo")
  1849. check(task_page_html.index('stm-text="comment.body"')
  1850. < task_page_html.index('stm-text="comment.quote"'),
  1851. "the task comment card shows the body before the quote")
  1852. status, css = http("GET", "/_statum/resource/app.css", timeout=15)
  1853. check(status == 200 and ".footnote" in css
  1854. and re.search(r"\.comment\s*\{[^}]*color:\s*var\(--ink-muted\)", css)
  1855. and re.search(r"\.comment\s*\{[^}]*font-size:\s*0\.88rem", css),
  1856. "the stylesheet ships the footnote utility and muted comment cards")
  1857. home_html = http_get_page(auth, "/")
  1858. check("item.kind == 'comment' || item.kind == 'goal-comment'"
  1859. " || item.kind == 'goal-system' ? 'footnote'" in home_html,
  1860. "the dashboard timeline renders comment rows as footnotes")
  1861. # =============================================================================
  1862. # Bundle: dispatch — the task pipeline end to end: registration tokens,
  1863. # rules, project notes, pushed chunks/results ingestion, capability
  1864. # routing, the create form, and retry/manual resume.
  1865. # =============================================================================
  1866. def bundle_dispatch(ctx):
  1867. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  1868. app = ctx.app
  1869. print("== registration: token minting and delivery ==")
  1870. registered = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  1871. if s["name"] == "fake-saddle"]
  1872. check(len(registered) == 1 and registered[0]["token"].startswith("saddle-"),
  1873. "fake saddle registered with an API token")
  1874. # Plan 10 phase 1: registration delivers the per-saddle token to
  1875. # the daemon via POST /register {saddle_token, web_base_url}.
  1876. check(wait_for(lambda: len(fake.register_log) > 0 or False,
  1877. timeout=15, what="/register delivery") is not None,
  1878. "registration POSTs /register to the daemon")
  1879. register_body = fake.register_log[0]
  1880. check(register_body.get("saddle_token") == fake_token,
  1881. "/register carries the minted per-saddle token")
  1882. check(register_body.get("web_base_url") == WEB,
  1883. "/register carries the web base URL")
  1884. check(fake.token == fake_token,
  1885. "daemon persisted the token (its asks use it)")
  1886. token_conn = db()
  1887. row_token = token_conn.execute("select token from saddles where id = ?",
  1888. (fake_id,)).fetchone()[0]
  1889. token_conn.close()
  1890. check(row_token == fake_token,
  1891. "per-saddle token lives on the saddle row")
  1892. # The register-time ask (idle-awake daemon): 204, nothing
  1893. # offerable yet — the saddle is asleep and wakeable.
  1894. check(wait_for(lambda: any(a["status"] == 204 for a in fake.asks) or False,
  1895. timeout=15, what="register-time ask") is not None,
  1896. "the daemon's idle ask returns 204 (nothing offerable)")
  1897. print("== feature 5: rules ==")
  1898. rules_state = slot_public(auth, "/rules", "rules")
  1899. for name, body in [
  1900. ("Use Invercargill", "Never use libgee; use Invercargill enumerables."),
  1901. ("Write Vala docs", "Every public class carries a doc comment."),
  1902. ("Prefer meson", "Builds go through meson; no makefiles."),
  1903. ("Co-dev rule", "Keep the wire contract exactly."),
  1904. ("Reference rule", "Must never ride along."),
  1905. ]:
  1906. act(auth, rules_state["create"], {"name": name, "body": body})
  1907. listed = {r["name"]: r for r in slot_public(auth, "/rules", "rules")["rules"]}
  1908. check(len(listed) == 5, "five rules created and listed on /rules")
  1909. def rule_id(name):
  1910. rows = [r for r in slot_public(auth, "/rules", "rules")["rules"] if r["name"] == name]
  1911. return int(rows[0]["id"])
  1912. state = slot_public(auth, "/projects", "projects")
  1913. act(auth, state["create"], {"name": "co", "git_url": "https://example.com/co.git"})
  1914. act(auth, state["create"], {"name": "ref", "git_url": "https://example.com/ref.git"})
  1915. co_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1916. if p["name"] == "co"][0])
  1917. ref_id = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  1918. if p["name"] == "ref"][0])
  1919. project = slot_public(auth, "/projects/1", "project")
  1920. act(auth, project["add_link"], {"linked_project_id": str(co_id),
  1921. "relationship": "co-developed"})
  1922. act(auth, project["add_link"], {"linked_project_id": str(ref_id),
  1923. "relationship": "reference"})
  1924. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  1925. act(auth, project["attach_rule"], {"rule_id": str(rule_id("Prefer meson"))})
  1926. project = slot_public(auth, "/projects/1", "project")
  1927. check(sorted(r["name"] for r in project["rules"]) == ["Prefer meson", "Use Invercargill"],
  1928. "project page lists its attached rules")
  1929. co_project = slot_public(auth, "/projects/%d" % co_id, "project")
  1930. act(auth, co_project["attach_rule"], {"rule_id": str(rule_id("Co-dev rule"))})
  1931. ref_project = slot_public(auth, "/projects/%d" % ref_id, "project")
  1932. act(auth, ref_project["attach_rule"], {"rule_id": str(rule_id("Reference rule"))})
  1933. tasks_state = slot_public(auth, "/tasks", "tasks")
  1934. # Draft-first (deterministic rule attachment): the dispatcher claims
  1935. # a queued task on its 1s tick, which under load could beat the
  1936. # attach_rule calls below and ship an assignment without the task's
  1937. # own rules — attach while draft, enqueue last.
  1938. act(auth, tasks_state["create"], {
  1939. "project_id": "1",
  1940. "title": "Rules dispatch",
  1941. "description": "Effective rule set rides the /start payload.",
  1942. "priority": "2",
  1943. })
  1944. rule_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  1945. if t["title"] == "Rules dispatch"][0])
  1946. detail = task_state(auth, rule_task)
  1947. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Write Vala docs"))})
  1948. act(auth, detail["attach_rule"], {"rule_id": str(rule_id("Use Invercargill"))})
  1949. enqueue_task(auth, rule_task)
  1950. detail = task_state(auth, rule_task)
  1951. check(sorted(r["name"] for r in detail["rules"]) == ["Use Invercargill", "Write Vala docs"],
  1952. "task page lists its attached rules")
  1953. check(wait_for(lambda: len(fake.start_payloads) > 0 or False,
  1954. timeout=30, what="/start push") is not None,
  1955. "dispatcher pushes the task to the fake saddle")
  1956. payload = fake.start_payloads[-1]
  1957. rule_names = [r["name"] for r in payload.get("rules", [])]
  1958. check(rule_names == ["Write Vala docs", "Use Invercargill", "Prefer meson", "Co-dev rule"],
  1959. "effective rules in /start: task, primary, co-developed order (%s)" % rule_names)
  1960. check(all(r.get("body") for r in payload.get("rules", [])),
  1961. "rules carry their bodies")
  1962. check("Reference rule" not in rule_names,
  1963. "reference project rules excluded")
  1964. detail = task_state(auth, rule_task)
  1965. act(auth, detail["rules"][0]["detach"], {})
  1966. check([r["name"] for r in task_state(auth, rule_task)["rules"]] == ["Use Invercargill"],
  1967. "detached task rule disappears")
  1968. rules_rows = slot_public(auth, "/rules", "rules")["rules"]
  1969. docs_row = [r for r in rules_rows if r["name"] == "Write Vala docs"][0]
  1970. act(auth, docs_row["update"], {"name": "Write Vala docs", "body": "Doc comments or bust."})
  1971. check(any(r["body"] == "Doc comments or bust."
  1972. for r in slot_public(auth, "/rules", "rules")["rules"]),
  1973. "rule edit saves the body")
  1974. check(wait_task_done(auth, rule_task, timeout=60) is not None,
  1975. "dispatched task completes against the fake daemon")
  1976. print("== feature 6: project notes + callback ==")
  1977. # Plan 10 phase 1: the shared saddle-callback token is gone —
  1978. # the per-saddle token authorises the callback endpoints.
  1979. callback_token = fake_token
  1980. check(callback_token.startswith("saddle-") and "saddle-callback-" not in callback_token,
  1981. "note callback authorised by the per-saddle token")
  1982. status, _ = saddle_api("POST", "/api/saddle/note", None,
  1983. {"project": "demo", "body": "x"})
  1984. check(status == 401, "note endpoint rejects a missing token")
  1985. status, _ = saddle_api("POST", "/api/saddle/note", "saddle-callback-not-real",
  1986. {"project": "demo", "body": "x"})
  1987. check(status == 401, "note endpoint rejects a wrong (legacy-style) token")
  1988. status, body = saddle_api("POST", "/api/saddle/note", callback_token,
  1989. {"task_id": rule_task, "project": "demo",
  1990. "body": "style.css tokens live in :root"})
  1991. check(status == 200 and body.get("ok") is True, "note accepted with the callback token")
  1992. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  1993. {"project": "no-such-project", "body": "x"})
  1994. check(status == 400, "unknown project rejected")
  1995. status, _ = saddle_api("POST", "/api/saddle/note", callback_token,
  1996. {"project": "demo", "body": " "})
  1997. check(status == 400, "empty note body rejected")
  1998. project = slot_public(auth, "/projects/1", "project")
  1999. check(any("style.css tokens" in n["body"] and int(n["source_task_id"]) == rule_task
  2000. for n in project["notes"]),
  2001. "project page lists the note with its source task")
  2002. act(auth, [n for n in project["notes"] if "style.css tokens" in n["body"]][0]["delete"], {})
  2003. check(all("style.css tokens" not in n["body"]
  2004. for n in slot_public(auth, "/projects/1", "project")["notes"]),
  2005. "note deleted from the project page")
  2006. # /start payload: notes of primary + co-developed (not reference),
  2007. # oldest first; callback carries the configured base URL + token.
  2008. saddle_api("POST", "/api/saddle/note", callback_token,
  2009. {"project": "demo", "body": "note-one"})
  2010. saddle_api("POST", "/api/saddle/note", callback_token,
  2011. {"project": "demo", "body": "note-two"})
  2012. saddle_api("POST", "/api/saddle/note", callback_token,
  2013. {"project": "co", "body": "co-note"})
  2014. conn = db()
  2015. conn.execute("insert into project_notes (project_id, body, created_at)"
  2016. " values (?, 'ref-note-must-not-ship', strftime('%s','now'))", (ref_id,))
  2017. conn.commit()
  2018. conn.close()
  2019. task_id_tmp = create_queued(auth, {
  2020. "project_id": "1",
  2021. "title": "Notes dispatch",
  2022. "description": "Project notes ride the /start payload.",
  2023. "priority": "2",
  2024. })
  2025. check(wait_for(lambda: len(fake.start_payloads) >= 2 or False,
  2026. timeout=30, what="second /start push") is not None,
  2027. "dispatcher pushes the notes task")
  2028. payload = fake.start_payloads[-1]
  2029. notes = payload.get("project_notes", [])
  2030. check([n["body"] for n in notes] == ["note-one", "note-two", "co-note"],
  2031. "project_notes: primary + co-developed, oldest first (%s)" % [n["body"] for n in notes])
  2032. check(all(n.get("project") for n in notes)
  2033. and notes[2]["project"] == "co",
  2034. "project_notes carry the project name")
  2035. check("ref-note-must-not-ship" not in [n["body"] for n in notes],
  2036. "reference project notes excluded")
  2037. callback = payload.get("callback", {})
  2038. check(callback.get("base_url") == WEB and callback.get("token") == callback_token,
  2039. "callback carries the configured base URL and the minted token")
  2040. # entry cap: 30 of 33 candidates
  2041. conn = db()
  2042. for i in range(33):
  2043. conn.execute("insert into project_notes (project_id, body, created_at)"
  2044. " values (?, ?, strftime('%s','now'))", (1, "bulk-%02d" % i))
  2045. conn.commit()
  2046. conn.close()
  2047. create_queued(auth, {
  2048. "project_id": "1",
  2049. "title": "Entry cap dispatch",
  2050. "priority": "2",
  2051. })
  2052. check(wait_for(lambda: len(fake.start_payloads) >= 3 or False,
  2053. timeout=30, what="third /start push") is not None,
  2054. "dispatcher pushes the entry-cap task")
  2055. notes = fake.start_payloads[-1].get("project_notes", [])
  2056. check(len(notes) == 30 and notes[0]["body"] == "note-one" and notes[1]["body"] == "note-two",
  2057. "project_notes capped at 30 entries, oldest kept (%d)" % len(notes))
  2058. # char cap: the giant note is truncated so the total stays <= 20000
  2059. conn = db()
  2060. conn.execute("delete from project_notes where body like 'bulk-%' or body = 'co-note'")
  2061. conn.execute("insert into project_notes (project_id, body, created_at)"
  2062. " values (?, ?, strftime('%s','now'))", (1, "giant!" + "x" * 25000,))
  2063. conn.commit()
  2064. conn.close()
  2065. create_queued(auth, {
  2066. "project_id": "1",
  2067. "title": "Char cap dispatch",
  2068. "priority": "2",
  2069. })
  2070. check(wait_for(lambda: len(fake.start_payloads) >= 4 or False,
  2071. timeout=30, what="fourth /start push") is not None,
  2072. "dispatcher pushes the char-cap task")
  2073. notes = fake.start_payloads[-1].get("project_notes", [])
  2074. total = sum(len(n["body"]) for n in notes)
  2075. check(len(notes) == 3 and total == 20000 and notes[2]["body"].startswith("giant!"),
  2076. "project_notes char cap: head kept, giant truncated (entries=%d, chars=%d)"
  2077. % (len(notes), total))
  2078. print("== phase 2: pushed chunks -> raw log + terminal view ==")
  2079. # Wait for the last dispatch to finish so its pushes landed.
  2080. check(wait_task_done(auth, task_id_of("Char cap dispatch"), timeout=60) is not None,
  2081. "char-cap task completes")
  2082. conn = db()
  2083. raw_session = conn.execute(
  2084. "select s.id from sessions s join tasks t on t.id = s.task_id"
  2085. " where t.title = 'Char cap dispatch' order by s.id desc limit 1").fetchone()[0]
  2086. rows = conn.execute("select seq, chunk from session_raw_log where session_id = ?"
  2087. " order by seq", (raw_session,)).fetchall()
  2088. conn.close()
  2089. check(len(rows) >= 3, "session_raw_log captured the pushed chunks (%d)" % len(rows))
  2090. seqs = [r[0] for r in rows]
  2091. check(seqs == sorted(seqs) and len(set(seqs)) == len(seqs),
  2092. "pushed chunks stored once, seq strictly increasing")
  2093. text = "".join(r[1] for r in rows)
  2094. check(fake.PROMPT in text and "echo hello" in text and "hello" in text,
  2095. "pushed raw log keeps the prompt and echoed output byte-exact")
  2096. check("working-heartbeat" in text,
  2097. "the flush-timer heartbeat chunks keep arriving mid-round")
  2098. terminal = slot_public(auth, "/tasks/%d/terminal" % task_id_of("Char cap dispatch"),
  2099. "terminal")
  2100. check(terminal.get("has_raw_log") is True and int(terminal["session_id"]) == raw_session,
  2101. "terminal view selects raw rendering for the raw session")
  2102. # Old sessions (typed entries, no raw rows) keep the fallback view
  2103. # (a dedicated fixture task: its only session is the legacy one,
  2104. # so the terminal view cannot prefer a dispatched raw session).
  2105. conn = db()
  2106. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  2107. " values (1, 'Legacy terminal task', 'working', 5, strftime('%s','now'))")
  2108. legacy_task = conn.execute("select max(id) from tasks").fetchone()[0]
  2109. conn.execute("insert into sessions (task_id, saddle_id, started_at, ended_at, outcome)"
  2110. " values (?, ?, strftime('%s','now'), strftime('%s','now'), 'done')",
  2111. (legacy_task, fake_id))
  2112. conn.commit()
  2113. legacy_session = conn.execute("select max(id) from sessions").fetchone()[0]
  2114. conn.execute("insert into session_commands (session_id, command_text, output_text,"
  2115. " type, started_at) values (?, 'ls', 'old-output', 'command',"
  2116. " strftime('%s','now'))", (legacy_session,))
  2117. conn.commit()
  2118. conn.close()
  2119. legacy = slot_public(auth, "/tasks/%d/terminal" % legacy_task, "terminal")
  2120. check(legacy.get("has_raw_log") is False,
  2121. "legacy session falls back to the entry-type terminal view")
  2122. request = urllib.request.Request(WEB + "/terminal-stream/%d" % raw_session)
  2123. with urllib.request.urlopen(request, timeout=15) as stream:
  2124. raw_events = []
  2125. deadline = time.monotonic() + 8
  2126. while time.monotonic() < deadline and len(raw_events) < 3:
  2127. line = stream.readline().decode().strip()
  2128. if not line.startswith("data: ") or line == "data: ping":
  2129. continue
  2130. event = json.loads(line[6:])
  2131. if event.get("type") == "raw":
  2132. raw_events.append(event)
  2133. check(len(raw_events) >= 3 and raw_events[0]["text"] == fake.PROMPT
  2134. and raw_events[0]["seq"] < raw_events[1]["seq"],
  2135. "terminal stream serves pushed chunks in seq order (prompt first)")
  2136. print("== phase 2: chunks/results ingestion — auth, idempotency ==")
  2137. # Token auth on both push channels (plan 10: the per-saddle
  2138. # bearer authorises every daemon->web call).
  2139. status, _ = saddle_api("POST", "/api/saddle/chunks", None,
  2140. {"session_id": raw_session, "chunks": []})
  2141. check(status == 401, "chunks endpoint rejects a missing token")
  2142. status, _ = saddle_api("POST", "/api/saddle/results", "saddle-bogus-token",
  2143. {"session_id": raw_session, "state": "working"})
  2144. check(status == 401, "results endpoint rejects a wrong token")
  2145. status, _ = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2146. {"session_id": 99999, "chunks": []})
  2147. check(status == 400, "chunks for an unknown session rejected")
  2148. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2149. {"session_id": raw_session, "state": "done"})
  2150. check(status == 200, "the owning saddle's session accepts its results")
  2151. # Pushed chunk idempotency: re-pushing a batch (the outbox's
  2152. # at-least-once redelivery after a lost response) consumes the
  2153. # duplicates and stores only the tail.
  2154. conn = db()
  2155. before = conn.execute("select count(*) from session_raw_log where session_id = ?",
  2156. (raw_session,)).fetchone()[0]
  2157. conn.close()
  2158. redelivery = [{"seq": r[0], "text": r[1]} for r in rows[:3]]
  2159. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2160. {"session_id": raw_session, "chunks": redelivery})
  2161. check(status == 200 and body.get("ok") is True and int(body.get("stored") or 0) == 0,
  2162. "a fully-duplicate batch stores nothing (duplicates consumed)")
  2163. fresh = [{"seq": 9000, "text": "late-flush\r\n"},
  2164. {"seq": 9001, "text": ""}] # truly empty text: no row
  2165. status, body = saddle_api("POST", "/api/saddle/chunks", fake_token,
  2166. {"session_id": raw_session, "chunks": fresh})
  2167. check(status == 200 and int(body.get("stored") or 0) == 1,
  2168. "a partial-redelivery batch stores only the new chunks")
  2169. conn = db()
  2170. after = conn.execute("select count(*) from session_raw_log where session_id = ?",
  2171. (raw_session,)).fetchone()[0]
  2172. empty_row = conn.execute(
  2173. "select count(*) from session_raw_log where session_id = ? and seq = 9001",
  2174. (raw_session,)).fetchone()[0]
  2175. conn.close()
  2176. check(after == before + 1 and empty_row == 0,
  2177. "redelivered chunks never duplicate rows; empty text stores nothing")
  2178. # Pushed entries: today's OutputEntry shape with the daemon's
  2179. # global entry ids — a redelivered results push stores its
  2180. # entries exactly once.
  2181. def command_rows(session):
  2182. conn = db()
  2183. try:
  2184. return conn.execute(
  2185. "select command_text, type from session_commands"
  2186. " where session_id = ? order by id", (session,)).fetchall()
  2187. finally:
  2188. conn.close()
  2189. entries = [{"id": 8101, "command": "sed -n 1p README.md", "output": "# demo",
  2190. "exit_code": 0, "type": "command", "timestamp": "2026-09-06T00:00:00Z"}]
  2191. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2192. {"session_id": raw_session, "state": "working",
  2193. "entries": entries})
  2194. check(status == 200, "entries push accepted")
  2195. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  2196. {"session_id": raw_session, "state": "working",
  2197. "entries": entries})
  2198. check(status == 200, "redelivered entries push accepted (at-least-once)")
  2199. stored = command_rows(raw_session)
  2200. check(len([r for r in stored if r[0] == "sed -n 1p README.md"]) == 1,
  2201. "redelivered entries store exactly once (daemon-global dedup)")
  2202. # The retired daemon routes 404 (phase 2 deleted /output, /log
  2203. # and /start serving) — and the web app never calls them.
  2204. for method, path in (("GET", "/output?since=0"), ("GET", "/log?since=0"),
  2205. ("POST", "/start")):
  2206. request = urllib.request.Request(
  2207. "http://127.0.0.1:%d%s" % (fake.port, path),
  2208. data=b"{}" if method == "POST" else None, method=method)
  2209. try:
  2210. urllib.request.urlopen(request, timeout=5)
  2211. gone = False
  2212. except urllib.error.HTTPError as error:
  2213. gone = error.code == 404
  2214. check(gone, "the fake daemon's %s %s is deleted (404)" % (method, path))
  2215. with open(os.path.join(WORK, "app.log")) as handle:
  2216. app_log = handle.read()
  2217. check("Saddle output request" not in app_log and "Saddle log request" not in app_log,
  2218. "the web never polls /output or /log anymore")
  2219. print("== capabilities: tag-based routing ==")
  2220. saddles_state = slot_public(auth, "/saddles", "saddles")
  2221. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2222. act(auth, saddles_state["create_capability"], {"name": "bigmem"})
  2223. saddles_state = slot_public(auth, "/saddles", "saddles")
  2224. caps = {c["name"]: c for c in saddles_state["capabilities"]}
  2225. check(len(caps) == 2 and all(int(c["saddle_count"]) == 0 and int(c["task_count"]) == 0
  2226. for c in caps.values()),
  2227. "capabilities created and listed with zero usage")
  2228. fake_card = saddle_card(auth, "fake-saddle")
  2229. check(fake_card["capabilities"] == [],
  2230. "saddle card starts with no capability chips")
  2231. # A task requiring 'gpu' waits while the only idle saddle lacks it;
  2232. # a later task without requirements still dispatches (skip-and-continue).
  2233. tasks_state = slot_public(auth, "/tasks", "tasks")
  2234. task_id_tmp = create_queued(auth, {
  2235. "project_id": "1",
  2236. "title": "GPU task",
  2237. "priority": "2",
  2238. })
  2239. gpu_task = task_id_tmp
  2240. detail = task_state(auth, gpu_task)
  2241. act(auth, detail["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  2242. check(wait_for(lambda: [c["name"] for c in
  2243. task_state(auth, gpu_task)["capabilities"]] == ["gpu"]
  2244. or False, timeout=90, what="capability attached") is not None,
  2245. "task page lists the required capability")
  2246. detail = task_state(auth, gpu_task)
  2247. # The only idle saddle lacks the tag, so the queue flags the wait
  2248. # (read before any other task claims the idle saddle). The state is
  2249. # stable until the any-saddle task below dispatches — poll for it
  2250. # rather than sampling once (a single read under load once sampled
  2251. # the row before the attach's pulse settled).
  2252. check(wait_for(lambda: (lambda row: row["status"] == "queued"
  2253. and row["capabilities"] == ["gpu"]
  2254. and row.get("waiting_for_saddle") is True)(
  2255. [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2256. if int(t["id"]) == gpu_task][0]) or False,
  2257. timeout=20, what="waiting flag") is not None,
  2258. "queue row shows the waiting task with its tag and wait flag")
  2259. task_id_tmp = create_queued(auth, {
  2260. "project_id": "1",
  2261. "title": "Any-saddle task",
  2262. "priority": "3",
  2263. })
  2264. any_task = task_id_tmp
  2265. check(wait_for(lambda: task_state(auth, any_task).get("status") != "queued" or False,
  2266. timeout=30, what="uncapable task dispatches") is not None,
  2267. "task without requirements dispatches past the waiting task")
  2268. def capability_wait_logged():
  2269. with open(os.path.join(WORK, "app.log")) as handle:
  2270. app_log = handle.read()
  2271. return "waits for a capable saddle" in app_log and "requires: gpu" in app_log
  2272. check(wait_for(capability_wait_logged, timeout=90,
  2273. what="capability wait log") is not None,
  2274. "dispatcher logs the capability wait")
  2275. # Attaching the tag to the saddle releases the task.
  2276. fake_card = saddle_card(auth, "fake-saddle")
  2277. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["gpu"]["id"]))})
  2278. fake_card = saddle_card(auth, "fake-saddle")
  2279. check([c["name"] for c in fake_card["capabilities"]] == ["gpu"],
  2280. "saddle card shows the attached chip")
  2281. check(wait_task_done(auth, gpu_task, timeout=60) is not None,
  2282. "task dispatches once the saddle carries the required tag")
  2283. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2284. if int(t["id"]) == gpu_task][0]
  2285. check(queue.get("waiting_for_saddle") is not True,
  2286. "wait flag clears once dispatched")
  2287. # Multi-tag: gpu + bigmem required, only gpu carried → waits; adding
  2288. # bigmem completes the superset. Both requirements ride the create
  2289. # form (atomic — attaching them one at a time would race a tick
  2290. # into dispatching on the partial set).
  2291. task_id_tmp = create_queued(auth, {
  2292. "project_id": "1",
  2293. "title": "Big task",
  2294. "priority": "2",
  2295. "capability_id": [str(int(caps["gpu"]["id"])), str(int(caps["bigmem"]["id"]))],
  2296. })
  2297. big_task = task_id_tmp
  2298. check(wait_for(lambda: ([t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2299. if int(t["id"]) == big_task][0].get("waiting_for_saddle")
  2300. is True) or False, timeout=30, what="big task waits") is not None,
  2301. "task waits when the saddle's tags are not a superset")
  2302. fake_card = saddle_card(auth, "fake-saddle")
  2303. act(auth, fake_card["attach_capability"], {"capability_id": str(int(caps["bigmem"]["id"]))})
  2304. check(wait_task_done(auth, big_task, timeout=60) is not None,
  2305. "task dispatches once the superset is complete")
  2306. # Detach a requirement (on a draft — capabilities lock once a
  2307. # worker has the job); delete a capability everywhere.
  2308. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  2309. "project_id": "1",
  2310. "title": "Detach probe task",
  2311. "priority": "4",
  2312. "capability_id": [str(int(caps["gpu"]["id"])), str(int(caps["bigmem"]["id"]))],
  2313. })
  2314. detach_probe = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2315. if t["title"] == "Detach probe task"][0])
  2316. act(auth, [c for c in task_state(auth, detach_probe)["capabilities"]
  2317. if c["name"] == "bigmem"][0]["detach"], {})
  2318. check([c["name"] for c in task_state(auth, detach_probe)["capabilities"]] == ["gpu"],
  2319. "detached requirement disappears from the task")
  2320. bigmem_row = [c for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2321. if c["name"] == "bigmem"][0]
  2322. act(auth, bigmem_row["delete"], {})
  2323. saddles_state = slot_public(auth, "/saddles", "saddles")
  2324. check(all(c["name"] != "bigmem" for c in saddles_state["capabilities"]),
  2325. "deleted capability gone from the catalogue")
  2326. check([c["name"] for c in task_state(auth, big_task)["capabilities"]] == ["gpu"],
  2327. "deleting a capability drops its task requirements")
  2328. check(all(c["name"] != "bigmem"
  2329. for c in saddle_card(auth, "fake-saddle")["capabilities"]),
  2330. "deleting a capability drops it from saddles")
  2331. print("== B4: required capabilities on the create form ==")
  2332. tasks_state = slot_public(auth, "/tasks", "tasks")
  2333. gpu_option = [o for o in tasks_state.get("capability_options", [])
  2334. if o["name"] == "gpu"][0]
  2335. check(len(tasks_state.get("capability_options", [])) >= 1,
  2336. "queue page offers capability options in the create form")
  2337. conn = db()
  2338. before = conn.execute("select count(*) from tasks").fetchone()[0]
  2339. conn.close()
  2340. act(auth, tasks_state["create"], {
  2341. "project_id": "1",
  2342. "title": "Bad cap task",
  2343. "capability_id": [gpu_option["id"], "999"],
  2344. })
  2345. conn = db()
  2346. after = conn.execute("select count(*) from tasks").fetchone()[0]
  2347. conn.close()
  2348. check(after == before, "unknown capability id rejects the create")
  2349. task_id_tmp = create_queued(auth, {
  2350. "project_id": "1",
  2351. "title": "Cap-on-create task",
  2352. "capability_id": [gpu_option["id"]],
  2353. })
  2354. cap_create = task_id_tmp
  2355. detail = task_state(auth, cap_create)
  2356. check([c["name"] for c in detail["capabilities"]] == ["gpu"],
  2357. "capabilities from the create form land on the task")
  2358. queue = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2359. if int(t["id"]) == cap_create][0]
  2360. check(queue["capabilities"] == ["gpu"],
  2361. "queue row shows the created task's requirements")
  2362. # The waiting flag must hold it back until the capable saddle frees
  2363. # up (the fake saddle still carries gpu from the routing checks).
  2364. check(queue.get("waiting_for_saddle") is not True,
  2365. "capable saddle available: no wait flag on the new task")
  2366. # Drain barrier: the cap task must be CLAIMED before the flaky
  2367. # arc arms fail_next (under parallel-shard load the dispatch tick
  2368. # can lag task creation; an unclaimed predecessor would consume
  2369. # the one-shot failure flag instead of the flaky task).
  2370. check(wait_for(lambda: task_state(auth, cap_create).get("status")
  2371. in ("working", "done", "failed") or False,
  2372. timeout=60, what="cap task claimed") is not None,
  2373. "the capable task is claimed before the flaky arc starts")
  2374. print("== retry + resume ==")
  2375. # A daemon-side failure fails the task with its explanation.
  2376. fake.fail_next = True
  2377. task_id_tmp = create_queued(auth, {
  2378. "project_id": "1",
  2379. "title": "Flaky task",
  2380. "priority": "2",
  2381. })
  2382. flaky = task_id_tmp
  2383. check(wait_for(lambda: task_state(auth, flaky).get("status") == "failed" or False,
  2384. timeout=90, what="flaky task fails") is not None,
  2385. "daemon failure fails the task")
  2386. detail = task_state(auth, flaky)
  2387. check("bash -n rejected" in (detail.get("summary") or ""),
  2388. "failure summary shows the daemon's explanation")
  2389. # Retry: the terminal summary dies with its attempt (plan 16 S4 —
  2390. # it is NOT copied to the thread), the task requeues, history
  2391. # stays, and the re-dispatch restores the workspace.
  2392. comments_before = len(detail.get("comments", []))
  2393. progress_before = len(detail.get("progress", []))
  2394. act(auth, detail["retry"], {})
  2395. detail = task_state(auth, flaky)
  2396. check(detail["status"] == "queued" and (detail.get("summary") or "") == "",
  2397. "retry requeues the task and clears the stale summary")
  2398. check(not any("bash -n rejected" in c["body"] for c in detail["comments"]),
  2399. "no summary→comment copy joins the thread (the terminal cache dies with its attempt, S4)")
  2400. check(any(c["body"] == "Task retried by user" and c["author"] == "system"
  2401. and c.get("is_system") for c in detail["comments"]),
  2402. "retry lands its audit comment as a system row (never an agent row)")
  2403. check(len(detail["comments"]) >= comments_before,
  2404. "retry keeps the comment history")
  2405. pushes_before = len([p for p in fake.start_payloads
  2406. if int(p.get("task", {}).get("id") or 0) == flaky])
  2407. check(wait_for(lambda: len([p for p in fake.start_payloads
  2408. if int(p.get("task", {}).get("id") or 0) == flaky])
  2409. > pushes_before or False, timeout=90,
  2410. what="flaky task re-dispatched") is not None,
  2411. "retried task dispatches again")
  2412. # The resumed arc surfaces on the next /status read — in the
  2413. # push world that is the operator's manual refresh.
  2414. act(auth, saddle_card(auth, "fake-saddle")["refresh"], {})
  2415. check(wait_task_done(auth, flaky, timeout=60) is not None,
  2416. "retried task completes on the restored workspace")
  2417. detail = task_state(auth, flaky)
  2418. check(all("restored the session context" not in c["body"]
  2419. for c in detail.get("comments", [])),
  2420. "the session-restore stays OUT of the user-facing thread (U2: raw terminal only)")
  2421. check(all("restored the session context" not in p["summary"]
  2422. for p in detail.get("progress", [])),
  2423. "the resume note stays OUT of the progress feed (F8: status is not progress)")
  2424. # Plan 16 S4: terminal text has ONE representation — the failed
  2425. # attempt's summary lived in tasks.summary alone (asserted above:
  2426. # no agent comment), and a HUMAN comment lands as exactly one
  2427. # user-authored row (the web is the single writer; the daemon's
  2428. # terminal echo is raw-log only).
  2429. act(auth, task_state(auth, flaky)["comment"],
  2430. {"body": "The retry landed — nice recovery"})
  2431. flaky_comments = task_state(auth, flaky)["comments"]
  2432. check(len([c for c in flaky_comments
  2433. if c["body"] == "The retry landed — nice recovery"]) == 1
  2434. and all(c["author"] != "agent"
  2435. for c in flaky_comments
  2436. if c["body"] == "The retry landed — nice recovery"),
  2437. "a human comment lands as exactly ONE user row (single writer, S4)")
  2438. # Manual resume: a task stuck working on an offline saddle.
  2439. task_id_tmp = create_queued(auth, {
  2440. "project_id": "1",
  2441. "title": "Stuck task",
  2442. "priority": "2",
  2443. })
  2444. stuck = task_id_tmp
  2445. check(wait_for(lambda: task_state(auth, stuck).get("status") == "working" or False,
  2446. timeout=60, what="stuck task starts working") is not None,
  2447. "stuck task reaches working")
  2448. # Deterministic claim for the resume leg below: the round's end,
  2449. # the refresh probe AND the dispatcher's wake for the requeued task
  2450. # all trigger self-asks that could steal it — freeze every trigger
  2451. # until the manual ask below has made the claim.
  2452. fake.ask_on_terminal = False
  2453. fake.ask_on_idle_status = False
  2454. fake.ask_on_wake = False
  2455. fake.settle_asks()
  2456. conn = db()
  2457. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  2458. conn.commit()
  2459. conn.close()
  2460. detail = task_state(auth, stuck)
  2461. check(detail.get("resume_available") is True,
  2462. "task page offers resume while its saddle is offline")
  2463. # The resume POSTs task-update cancel to the daemon; the abort
  2464. # handler fires an ungated re-ask that would race the manual claim
  2465. # below — slow it past the manual ask (the knob the slow-ask
  2466. # regression uses).
  2467. fake.ask_delay = 5.0
  2468. act(auth, detail["resume"], {})
  2469. detail = task_state(auth, stuck)
  2470. check(detail["status"] == "queued",
  2471. "manual resume requeues the stuck task")
  2472. check(any(c["body"] == "Saddle became unreachable; task requeued"
  2473. and c["author"] == "system" and c.get("is_system")
  2474. for c in detail["comments"]),
  2475. "manual resume lands the interruption comment as a system row")
  2476. check(all(s["status"] == "offline"
  2477. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  2478. "saddle stays offline after the manual requeue")
  2479. # Bringing the saddle back lets the requeued task resume and finish.
  2480. fake.state = "idle"
  2481. fake_card = saddle_card(auth, "fake-saddle")
  2482. act(auth, fake_card["refresh"], {})
  2483. check(any(s["status"] == "idle"
  2484. for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2485. if s["name"] == "fake-saddle"),
  2486. "refreshed saddle returns idle")
  2487. # The refreshed daemon is idle-awake: it asks (the real loop's
  2488. # own ask; driven directly for determinism — every self-ask trigger
  2489. # is frozen and the abort re-ask is slowed past it; joining that
  2490. # delayed thread here would fire its ask first, so it is left to
  2491. # sleep out the rest of the bundle).
  2492. status, payload = fake.ask_now()
  2493. fake.ask_on_idle_status = True
  2494. fake.ask_on_terminal = True
  2495. fake.ask_on_wake = True
  2496. fake.ask_delay = 0.0
  2497. check(status == 200, "the refreshed daemon's ask claims the requeued task")
  2498. check(wait_task_done(auth, stuck, timeout=60) is not None,
  2499. "requeued task resumes on the refreshed saddle and completes")
  2500. # =============================================================================
  2501. # Bundle: subtasks — the plan-12 task graph: plain-task parking (no
  2502. # subtask events exist to resume it), the DELETED subtask machinery's
  2503. # verbatim refusals, and the goal agent's task CLI in depth
  2504. # (capabilities, ownership, the daemon's task-reading API, the
  2505. # goal-run block answered from the task page).
  2506. # =============================================================================
  2507. def bundle_subtasks(ctx):
  2508. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2509. app = ctx.app
  2510. # A hold tag nothing carries: goal tasks created with it stay
  2511. # queued (a stable parked agent) until released at the settle.
  2512. saddles_state = slot_public(auth, "/saddles", "saddles")
  2513. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2514. gpu_cap_id = [c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  2515. if c["name"] == "gpu"][0]
  2516. def goal_state(goal_id):
  2517. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  2518. def create_goal_row(fields):
  2519. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  2520. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  2521. if g["title"] == fields["title"]]
  2522. return int(rows[0]["id"])
  2523. print("== B7: plain-task parking stays put (no subtask events) ==")
  2524. fake.suspend_on_title = "Suspend plain"
  2525. pushes_before = len(fake.start_payloads)
  2526. plain = create_queued(auth, {
  2527. "project_id": "1",
  2528. "title": "Suspend plain",
  2529. "priority": "2",
  2530. })
  2531. check(wait_for(lambda: task_state(auth, plain).get("status") == "suspended"
  2532. or False, timeout=60, what="plain task parks") is not None,
  2533. "daemon 'suspended' state parks the task")
  2534. detail = task_state(auth, plain)
  2535. check(detail.get("display") == "parked",
  2536. "a parked plain task displays as parked (%s)" % detail.get("display"))
  2537. check(any(s["status"] == "idle"
  2538. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  2539. "suspension frees the saddle")
  2540. first_push = fake.start_payloads[pushes_before]
  2541. check(first_push.get("kind") == "task" and first_push.get("creator") == "human"
  2542. and first_push.get("mode") == "implement",
  2543. "the /start payload carries the plan-12 identity triplet (kind/creator/mode)")
  2544. check("subtasks" not in first_push and "parent" not in first_push,
  2545. "the plan-12 payload drops the subtasks/parent members")
  2546. # Other tasks finishing must NOT resume a parked plain task (the
  2547. # subtask-event channel is gone; only goal events resume goal runs).
  2548. conn = db()
  2549. conn.execute("insert into tasks (project_id, title, status, priority, summary,"
  2550. " completed_at, created_at) values (1, 'Unrelated finisher', 'done',"
  2551. " 5, 'finished loudly', strftime('%s','now','+1 second'),"
  2552. " strftime('%s','now'))")
  2553. conn.commit()
  2554. conn.close()
  2555. check(quiet_window(quiet_seconds(),
  2556. lambda: task_state(auth, plain)["status"] == "suspended",
  2557. "plain park survives unrelated finishes"),
  2558. "a parked plain task never resumes on other tasks' events")
  2559. print("== the deleted machinery refuses, verbatim ==")
  2560. status, body = saddle_api("POST", "/api/saddle/subtask", fake_token,
  2561. {"parent_task_id": plain, "title": "ghost"})
  2562. check(status == 404,
  2563. "the /api/saddle/subtask callback route is gone (404)")
  2564. # The poll-era ingest channel went with it (arch 19): the whole
  2565. # /update surface 404s — subtask and plan verb arms included — and
  2566. # the verdict channel (/poll) with it.
  2567. conn = db()
  2568. plain_session = conn.execute(
  2569. "select id from sessions where task_id = ? and ended_at is null",
  2570. (plain,)).fetchone()[0]
  2571. conn.close()
  2572. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2573. {"type": "subtask", "session_id": plain_session,
  2574. "data": {"title": "Ghost child"}})
  2575. check(status == 404,
  2576. "the /update ingest surface is gone (404, the subtask arm with it)")
  2577. status, body = saddle_api("POST", "/api/saddle/%d/update" % fake_id, fake_token,
  2578. {"type": "plan", "session_id": plain_session,
  2579. "data": {"plan": "# nope"}})
  2580. check(status == 404,
  2581. "the task-level 'plan' update arm is gone with the channel (404)")
  2582. # The daemon's task CLI: no parent/plan members; goal context instead.
  2583. status, body = saddle_api("GET", "/api/saddle/task/%d" % plain, fake_token)
  2584. check(status == 200 and "plan" not in body.get("task", {})
  2585. and "parent_task_id" not in body.get("task", {})
  2586. and "goal_id" in body.get("task", {}),
  2587. "the task CLI detail drops parent/plan and carries goal_id")
  2588. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", fake_token)
  2589. check(status == 200 and all("parent_task_id" not in t and "goal_id" in t
  2590. for t in body.get("tasks", [])),
  2591. "the task CLI list drops parent_task_id and carries goal_id")
  2592. # Settle the parked plain task: nothing will resume it — cancel it.
  2593. act(auth, task_state(auth, plain)["cancel"], {})
  2594. check(wait_for(lambda: task_state(auth, plain)["status"] == "failed" or False,
  2595. timeout=30, what="parked plain task cancelled") is not None,
  2596. "the parked plain task cancels (the human cleanup path)")
  2597. print("== the goal agent's task CLI in depth ==")
  2598. goal = create_goal_row({"project_id": "1", "title": "Sequencing goal",
  2599. "brief": "Fan tasks out with the CLI.",
  2600. "branch_name": "goal/sequence"})
  2601. fake.goal_script = [("plan", "# Plan\n\n1. Fan out")]
  2602. act(auth, goal_state(goal)["start"], {})
  2603. check(wait_for(lambda: goal_state(goal)["status"] == "plan_review" or False,
  2604. timeout=60, what="sequencing goal plans") is not None,
  2605. "the sequencing goal reaches plan review")
  2606. fake.goal_script = [("suspend",)]
  2607. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  2608. {"answer": "Plan approved. Proceed with implementation."})
  2609. conn = db()
  2610. run_task = conn.execute(
  2611. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  2612. (goal,)).fetchone()[0]
  2613. agent_session = conn.execute(
  2614. "select id from sessions where task_id = ? and ended_at is null",
  2615. (run_task,)).fetchone()[0]
  2616. conn.close()
  2617. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  2618. or False, timeout=60, what="sequencing agent parks") is not None,
  2619. "the sequencing goal agent parks")
  2620. # Create with capabilities: attached until assignment (the hold
  2621. # keeps the task queued), mandate + mode stored, ephemeral branch.
  2622. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  2623. "session_id": agent_session, "title": "Held worker",
  2624. "mandate": "Do the held work.", "mode": "review",
  2625. "capabilities": ["gpu"]})
  2626. check(status == 200 and body.get("ok") is True,
  2627. "task create with a capability tag succeeds")
  2628. held = int(body["task_id"])
  2629. detail = task_state(auth, held)
  2630. check(detail["status"] == "draft" and detail["mode"] == "review",
  2631. "the held worker drafts with its mode")
  2632. check([c["name"] for c in detail.get("capabilities", [])] == ["gpu"],
  2633. "the capability attaches to the created task")
  2634. check(detail["task_branch"] == "task/%d-%d" % (goal, held)
  2635. and detail["branch_from"] == "goal/sequence",
  2636. "the CLI task's ephemeral branch pair is stored")
  2637. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  2638. "session_id": agent_session, "task_id": held})
  2639. check(status == 200, "the held worker enqueues")
  2640. check(quiet_window(3, lambda: task_state(auth, held)["status"] == "queued",
  2641. "unsatisfiable capability holds dispatch"),
  2642. "the unsatisfiable capability holds the queued worker (never assigned)")
  2643. queue_row = [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  2644. if int(t["id"]) == held][0]
  2645. check(queue_row.get("waiting_for_saddle") is True,
  2646. "the queue annotates the held worker as waiting for a saddle")
  2647. # The human edit path: goal tasks never carry enqueue-after (the
  2648. # field is human-tasks-only — the update silently ignores it).
  2649. act(auth, task_state(auth, held)["update"], {
  2650. "priority": "4", "enqueue_after_task_id": str(held - 1)})
  2651. check(task_state(auth, held).get("enqueue_after_task_id") in (None, 0, "0"),
  2652. "a goal task ignores the auto-enqueue-after field on edit")
  2653. # Ownership: the same saddle's goal agent cannot touch another
  2654. # goal's task; a plain session is not a goal-agent identity.
  2655. other_goal = create_goal_row({"project_id": "1", "title": "Other goal",
  2656. "brief": "b", "branch_name": "goal/other",
  2657. "priority": "9"})
  2658. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token,
  2659. {"session_id": agent_session, "title": "x",
  2660. "mandate": "m"})
  2661. scope_task = int(body["task_id"])
  2662. check(int(task_state(auth, scope_task)["goal_id"] or 0) == goal,
  2663. "the callback scopes task creation to its own goal")
  2664. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token,
  2665. {"session_id": agent_session, "task_id": scope_task})
  2666. check(status == 200, "the owned draft deletes")
  2667. check(not any(t["id"] == scope_task
  2668. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  2669. "the deleted task is gone from the queue")
  2670. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  2671. {"session_id": agent_session, "task_id": plain})
  2672. check(status == 400 and "does not belong to your goal" in (body.get("error") or ""),
  2673. "the goal agent cannot enqueue a standalone task")
  2674. # The daemon's task CLI detail carries the goal context.
  2675. status, body = saddle_api("GET", "/api/saddle/task/%d" % held, fake_token)
  2676. check(status == 200
  2677. and int(body["task"].get("goal_id") or 0) == goal
  2678. and body["task"].get("goal_title") == "Sequencing goal",
  2679. "the task CLI detail names the owning goal")
  2680. print("== the goal-run block answers from the task page (C1) ==")
  2681. # A question block raised in goal context lands on the run task's
  2682. # own row; the TASK page's answer action funnels into the one
  2683. # goal answer path and resumes the agent with the verdict riding
  2684. # the allocation (the goal page shares the path).
  2685. fake.goal_script = [("question", "Which harness: pytest or vitest?",
  2686. ["pytest", "vitest"])]
  2687. conn = db()
  2688. # Plan 15 C3: a terminal transition (a done task row newer than
  2689. # the watermark) is the resume signal — no event rows exist.
  2690. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  2691. " priority, completed_at, created_at) values (1, ?, 'task',"
  2692. " 'Nudge', 'done', 5,"
  2693. " strftime('%s','now'),"
  2694. " strftime('%s','now','-30 seconds'))", (goal,))
  2695. conn.commit()
  2696. conn.close()
  2697. check(wait_for(lambda: task_state(auth, run_task)["status"] == "blocked"
  2698. or False, timeout=60, what="goal block parks the run") is not None,
  2699. "a goal question parks the run task on its own block row")
  2700. run_detail = task_state(auth, run_task)
  2701. question_block = [b for b in run_detail["blocks"]
  2702. if b["block_type"] == "question"][0]
  2703. check(question_block.get("question") == "Which harness: pytest or vitest?",
  2704. "the run task's block carries the goal question verbatim")
  2705. goal_block_ids = [int(b["id"]) for b in goal_state(goal)["blocks"]
  2706. if b.get("block_type") == "question"]
  2707. check(goal_block_ids == [int(question_block["id"])],
  2708. "the goal page's card is the SAME row (no dual-row pair)")
  2709. act(auth, question_block["answer_action"], {"answer": "pytest"})
  2710. fake.goal_script = [("suspend",)]
  2711. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  2712. or False, timeout=60, what="answered block resumes the agent")
  2713. is not None,
  2714. "the answered block resumes the goal agent")
  2715. answered = [b for b in task_state(auth, run_task)["blocks"]
  2716. if b["block_type"] == "question"][0]
  2717. check(answered.get("answer") == "pytest",
  2718. "the verdict is stored on the single block row")
  2719. print("== settle: release the hold and let the shard drain ==")
  2720. # Drop the hold tag so the held worker can dispatch and complete;
  2721. # the parked agent resumes on its completion, re-parks (script),
  2722. # and the shard shuts down with an empty queue.
  2723. act(auth, task_state(auth, held)["capabilities"][0]["detach"], {})
  2724. check(wait_task_done(auth, held, timeout=90) is not None,
  2725. "the released held worker completes")
  2726. check(wait_for(lambda: any(e["kind"] == "task-done" and int(e["task_id"]) == held
  2727. for e in goal_state(goal)["events"]) or False,
  2728. timeout=30, what="narrative hears the held worker") is not None,
  2729. "the narrative records the held worker's completion")
  2730. act(auth, goal_state(goal)["cancel"], {})
  2731. check(wait_for(lambda: goal_state(goal)["status"] == "cancelled" or False,
  2732. timeout=30, what="sequencing goal cancelled") is not None,
  2733. "the sequencing goal cancels (the shard's cleanup path)")
  2734. # =============================================================================
  2735. # Bundle: lineage — the plan-12 goal lineage: goal context on worker
  2736. # dispatches (read-only reference + ephemeral branch), the daemon's
  2737. # task-reading API (goal members, no parent/plan), and the goal
  2738. # agent's workspace affinity while parked.
  2739. # =============================================================================
  2740. def bundle_lineage(ctx):
  2741. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2742. app = ctx.app
  2743. r4_token = fake_token
  2744. # gpu exists only as a hold (no saddle carries it): the held goal
  2745. # worker stays queued until the release loop lifts it.
  2746. saddles_state = slot_public(auth, "/saddles", "saddles")
  2747. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2748. def goal_state(goal_id):
  2749. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  2750. def create_goal_row(fields):
  2751. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  2752. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  2753. if g["title"] == fields["title"]]
  2754. return int(rows[0]["id"])
  2755. goal = create_goal_row({"project_id": "1", "title": "Lineage goal",
  2756. "brief": "Carry the goal lineage.",
  2757. "branch_name": "goal/lineage"})
  2758. fake.goal_script = [("plan", "# Lineage plan\n\n1. Fan out\n2. Verify")]
  2759. act(auth, goal_state(goal)["start"], {})
  2760. check(wait_for(lambda: goal_state(goal)["status"] == "plan_review" or False,
  2761. timeout=60, what="lineage goal plans") is not None,
  2762. "the lineage goal reaches plan review")
  2763. fake.goal_script = [("suspend",)]
  2764. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  2765. {"answer": "Plan approved. Proceed with implementation."})
  2766. conn = db()
  2767. auto_parent = conn.execute(
  2768. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  2769. (goal,)).fetchone()[0]
  2770. agent_session = conn.execute(
  2771. "select id from sessions where task_id = ? and ended_at is null",
  2772. (auto_parent,)).fetchone()[0]
  2773. conn.close()
  2774. check(wait_for(lambda: task_state(auth, auto_parent)["status"] == "suspended"
  2775. or False, timeout=60, what="lineage goal agent parks") is not None,
  2776. "the lineage goal agent parks")
  2777. # Two workers under the goal: one free, one held by the gpu tag.
  2778. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2779. "session_id": agent_session, "title": "Auto child",
  2780. "mandate": "build the widget", "mode": "implement"})
  2781. auto_child = int(body["task_id"])
  2782. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2783. "session_id": agent_session, "title": "Auto grandchild",
  2784. "mandate": "verify the widget", "mode": "test",
  2785. "capabilities": ["gpu"]})
  2786. auto_grand = int(body["task_id"])
  2787. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2788. "session_id": agent_session, "title": "Wire the flange",
  2789. "description": "torque to spec"})
  2790. check(status == 400 and "mandate is required" in (body.get("error") or ""),
  2791. "task create without a mandate errors verbatim (%s)" % body.get("error"))
  2792. status, body = saddle_api("POST", "/api/saddle/task/create", r4_token, {
  2793. "session_id": agent_session, "title": "Wire the flange",
  2794. "mandate": "torque to spec"})
  2795. flange_task = int(body["task_id"])
  2796. for held in (auto_child, auto_grand, flange_task):
  2797. saddle_api("POST", "/api/saddle/task/enqueue", r4_token,
  2798. {"session_id": agent_session, "task_id": held})
  2799. check(wait_for(lambda: task_state(auth, auto_child)["status"] in
  2800. ("queued", "assigned", "working", "done") or False,
  2801. timeout=30, what="free goal worker dispatches") is not None,
  2802. "the free goal worker dispatches")
  2803. check(quiet_window(3, lambda: task_state(auth, auto_grand)["status"] == "queued",
  2804. "held goal worker stays queued"),
  2805. "the gpu-held goal worker stays queued")
  2806. # A goal worker's dispatch carries the read-only goal context.
  2807. lineage_push = [p for p in fake.start_payloads
  2808. if int(p.get("task", {}).get("id") or 0) == auto_child][-1]
  2809. goal_ctx = lineage_push.get("goal") or {}
  2810. check(int(goal_ctx.get("id") or 0) == goal
  2811. and goal_ctx.get("branch") == "goal/lineage"
  2812. and "Carry the goal lineage." in goal_ctx.get("brief", "")
  2813. and "# Lineage plan" in goal_ctx.get("plan", ""),
  2814. "the worker dispatch carries the goal context (brief + approved plan)")
  2815. check(lineage_push.get("ephemeral_branch") == "task/%d-%d" % (goal, auto_child)
  2816. and lineage_push.get("kind") == "task"
  2817. and lineage_push.get("mode") == "implement"
  2818. and lineage_push.get("creator") == "goal",
  2819. "the worker dispatch carries the ephemeral branch + identity triplet")
  2820. check("parent" not in lineage_push and "subtasks" not in lineage_push,
  2821. "the plan-12 payload drops the parent/subtasks members")
  2822. print("== R5 B2: task-reading API ==")
  2823. status, _ = saddle_api("GET", "/api/saddle/tasks", None)
  2824. check(status == 401, "tasks endpoint rejects a missing token")
  2825. status, _ = saddle_api("GET", "/api/saddle/task/%d" % auto_child, None)
  2826. check(status == 401, "task detail endpoint rejects a missing token")
  2827. # Fixture: a second project whose tasks all carry the "Diff " title
  2828. # prefix for the project_id filter checks — created first so the
  2829. # unfiltered list has the population the count check expects.
  2830. state = slot_public(auth, "/projects", "projects")
  2831. act(auth, state["create"], {"name": "diff-fabrica",
  2832. "git_url": "ssh://fabrica.unitatem.net:222/clanker/clanker-saddle.git"})
  2833. conn = db()
  2834. other_project = int([p["id"] for p in slot_public(auth, "/projects", "projects")["projects"]
  2835. if p["name"] == "diff-fabrica"][0])
  2836. for suffix in ("fabrica", "scp"):
  2837. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  2838. " values (?, ?, 'done', 5, strftime('%s','now'))",
  2839. (other_project, "Diff %s" % suffix))
  2840. conn.commit()
  2841. conn.close()
  2842. status, body = saddle_api("GET", "/api/saddle/tasks", r4_token)
  2843. check(status == 200 and len(body.get("tasks", [])) > 5,
  2844. "tasks endpoint lists tasks without filters")
  2845. row = [t for t in body["tasks"] if int(t["id"]) == auto_child][0]
  2846. check(row["title"] == "Auto child" and int(row["goal_id"] or 0) == goal
  2847. and row["status"] in ("done", "queued", "working"),
  2848. "compact rows carry id/title/status/goal_id")
  2849. status, body = saddle_api("GET", "/api/saddle/tasks?project_id=1", r4_token)
  2850. check(all(True for _ in [1]) # project 1 dominates the data set
  2851. and not any(int(t["id"]) == 0 for t in body["tasks"]),
  2852. "project_id filter accepted")
  2853. status, body = saddle_api("GET",
  2854. "/api/saddle/tasks?project_id=%d" % other_project, r4_token)
  2855. check(all(t["title"].startswith("Diff") for t in body["tasks"]),
  2856. "other project lists only its own tasks")
  2857. status, body = saddle_api("GET", "/api/saddle/tasks?q=FLANGE", r4_token)
  2858. titles = [t["title"] for t in body["tasks"]]
  2859. check("Wire the flange" in titles,
  2860. "q matches titles case-insensitively")
  2861. status, body = saddle_api("GET", "/api/saddle/tasks?q=torque%20to%20spec", r4_token)
  2862. check(any(t["title"] == "Wire the flange" for t in body["tasks"]),
  2863. "q matches mandate text")
  2864. status, body = saddle_api("GET", "/api/saddle/task/%d" % auto_child, r4_token)
  2865. task_view = body.get("task", {})
  2866. check(status == 200 and int(task_view.get("id") or 0) == auto_child
  2867. and task_view.get("goal_title") == "Lineage goal"
  2868. and int(task_view.get("goal_id") or 0) == goal,
  2869. "single-task view joins the goal title")
  2870. check("status" in task_view and "description" in task_view
  2871. and "summary" in task_view,
  2872. "single-task view carries the full detail fields")
  2873. check("plan" not in task_view and "parent_task_id" not in task_view,
  2874. "the single-task view drops the deleted parent/plan members")
  2875. status, body = saddle_api("GET", "/api/saddle/task/99999", r4_token)
  2876. check(status == 404, "unknown task id returns 404")
  2877. print("== settle: released workers resume the parked agent (coalesced) ==")
  2878. # Release the held workers: their completions wake the parked goal
  2879. # agent (affinity — the same fake hosts it) with the batched
  2880. # notice; the free worker already completed.
  2881. check(wait_task_done(auth, auto_child, timeout=90) is not None,
  2882. "the free worker settles first")
  2883. def agent_push_count():
  2884. return len([p for p in fake.goal_assignments
  2885. if int(p.get("task", {}).get("id") or 0) == auto_parent])
  2886. before_pushes = agent_push_count()
  2887. for held_task in (auto_grand, flange_task):
  2888. caps = task_state(auth, held_task).get("capabilities") or []
  2889. if caps:
  2890. act(auth, caps[0]["detach"], {})
  2891. check(wait_task_done(auth, held_task, timeout=90) is not None,
  2892. "released worker settles (%d)" % held_task)
  2893. check(wait_for(lambda: agent_push_count() > before_pushes or False,
  2894. timeout=90, what="goal agent resumes") is not None,
  2895. "the workers' completions resume the parked goal agent")
  2896. notice = ""
  2897. for p in fake.goal_assignments:
  2898. if int(p.get("task", {}).get("id") or 0) == auto_parent:
  2899. notice = p.get("resume_notice") or ""
  2900. check("Auto child" in notice and "Auto grandchild" in notice
  2901. and "Wire the flange" in notice,
  2902. "the coalesced resume notice covers every plan task")
  2903. check("New completion reports" in notice and "fake daemon finished" in notice,
  2904. "the notice carries the new completion reports")
  2905. act(auth, goal_state(goal)["cancel"], {})
  2906. check(wait_for(lambda: goal_state(goal)["status"] == "cancelled" or False,
  2907. timeout=30, what="lineage goal cancelled") is not None,
  2908. "the lineage goal cancels (drain)")
  2909. # =============================================================================
  2910. # Bundle: allocation — the ask/wake/allocate machinery: concurrent ask
  2911. # race, token revocation, workspace affinity, the lost-wake guard, the
  2912. # slow-ask regression, assignment capability context + the tag
  2913. # catalogue, and the pinned-blocks/activity dashboard.
  2914. # =============================================================================
  2915. def bundle_allocation(ctx):
  2916. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  2917. app = ctx.app
  2918. r4_token = fake_token
  2919. # gpu rides the primary fake from the start (the routing bundle's
  2920. # early attach, replayed): its attach row precedes lostwake's, so
  2921. # the assignment's saddle_tags order matches the assertion in the
  2922. # capability-context section below.
  2923. saddles_state = slot_public(auth, "/saddles", "saddles")
  2924. act(auth, saddles_state["create_capability"], {"name": "gpu"})
  2925. act(auth, saddle_card(auth, "fake-saddle")["attach_capability"],
  2926. {"capability_id": str(int([c["id"] for c in
  2927. slot_public(auth, "/saddles", "saddles")["capabilities"]
  2928. if c["name"] == "gpu"][0]))})
  2929. print("== phase 1: ask/allocation — token auth + concurrent race ==")
  2930. # Plan 10 phase 1. Registration mints per-saddle tokens; the
  2931. # ask endpoint authenticates by them; concurrent asks race to
  2932. # exactly one winner through the allocation transaction.
  2933. status, _ = saddle_api("POST", "/api/saddle/next-task", None)
  2934. check(status == 401, "next-task rejects a missing token")
  2935. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-bogus-token")
  2936. check(status == 401, "next-task rejects a wrong token")
  2937. status, body = saddle_api("POST", "/api/saddle/next-task", fake_token)
  2938. check(status == 204, "next-task answers 204 (nothing offerable — daemon sleeps)")
  2939. # Two more racers: real daemons on their own ports; fake2 reports
  2940. # its ssh key at /register so the key lands on the row directly.
  2941. fake2 = FakeSaddle()
  2942. fake2.ssh_public_key = "ssh-ed25519 AAAAFake2RacerKey saddle-2@fedora"
  2943. fake2.serve(port=free_port())
  2944. fake3 = FakeSaddle()
  2945. fake3.serve(port=free_port())
  2946. saddles_state = slot_public(auth, "/saddles", "saddles")
  2947. act(auth, saddles_state["register"], {"name": "racer-two",
  2948. "host": "127.0.0.1:%d" % fake2.port})
  2949. act(auth, saddles_state["register"], {"name": "racer-three",
  2950. "host": "127.0.0.1:%d" % fake3.port})
  2951. check(wait_for(lambda: len(fake2.register_log) > 0 and len(fake3.register_log) > 0
  2952. or False, timeout=15, what="racers registered") is not None,
  2953. "both racers received /register")
  2954. check(wait_for(lambda: "AAAAFake2RacerKey" in
  2955. [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2956. if s["name"] == "racer-two"][0].get("ssh_public_key", "") or False,
  2957. timeout=15, what="register-reported key") is not None,
  2958. "the ssh key reported at /register lands on the saddle row")
  2959. racer_cards = {}
  2960. for name, daemon in (("fake-saddle", fake), ("racer-two", fake2), ("racer-three", fake3)):
  2961. card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2962. if s["name"] == name][0]
  2963. racer_cards[daemon] = {"id": int(card["id"]), "token": card["token"]}
  2964. # Revocation: a registered saddle's token works until the saddle
  2965. # is removed, then nothing authorises its calls.
  2966. fake4 = FakeSaddle()
  2967. fake4.ask_on_register = False # a pre-flip daemon: never asks
  2968. fake4.serve(port=free_port())
  2969. saddles_state = slot_public(auth, "/saddles", "saddles")
  2970. act(auth, saddles_state["register"], {"name": "old-daemon",
  2971. "host": "127.0.0.1:%d" % fake4.port})
  2972. old_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  2973. if s["name"] == "old-daemon"][0]
  2974. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  2975. check(status in (200, 204),
  2976. "the old daemon's fresh token authenticates next-task")
  2977. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  2978. {"project": "demo", "body": "from the old daemon"})
  2979. check(status == 200, "note accepts any registered saddle's token")
  2980. act(auth, old_card["unregister"], {})
  2981. status, _ = saddle_api("POST", "/api/saddle/next-task", old_card["token"])
  2982. check(status == 401, "removing the saddle revokes its token")
  2983. status, _ = saddle_api("POST", "/api/saddle/note", old_card["token"],
  2984. {"project": "demo", "body": "should fail"})
  2985. check(status == 401, "revocation covers the note endpoint too")
  2986. # Deterministic race: settle the queue first (this shard runs the
  2987. # race before any parked work exists, so only in-flight asks need
  2988. # draining), freeze every daemon's self-ask triggers, put all three
  2989. # to sleep (204), then fire one task worth of concurrent asks.
  2990. for daemon in (fake, fake2, fake3):
  2991. daemon.ask_on_register = False
  2992. daemon.ask_on_wake = False
  2993. daemon.ask_on_terminal = False
  2994. daemon.ask_on_idle_status = False
  2995. daemon.settle_asks() # converted sleep: in-flight asks land (204)
  2996. def queued_count():
  2997. conn = db()
  2998. try:
  2999. return conn.execute(
  3000. "select count(*) from tasks where status = 'queued'").fetchone()[0]
  3001. finally:
  3002. conn.close()
  3003. check(wait_for(lambda: queued_count() == 0 or False,
  3004. timeout=60, what="queue settles before the race") is not None,
  3005. "the queue settles before the race")
  3006. sleep_statuses = [daemon.ask_now()[0] for daemon in (fake, fake2, fake3)]
  3007. check(sleep_statuses == [204, 204, 204],
  3008. "all three racers sleep (204) before the task exists")
  3009. task_id_tmp = create_queued(auth, {
  3010. "project_id": "1",
  3011. "title": "Race task",
  3012. "priority": "2",
  3013. })
  3014. race_task = task_id_tmp
  3015. race_results = []
  3016. def race_ask(daemon):
  3017. # A real racing daemon accepts the assignment it wins — the
  3018. # manual ask path does exactly that on a 200.
  3019. race_results.append(daemon.ask_now())
  3020. threads = [threading.Thread(target=race_ask, args=(daemon,))
  3021. for daemon in (fake, fake2, fake3)]
  3022. for thread in threads:
  3023. thread.start()
  3024. for thread in threads:
  3025. thread.join()
  3026. race_statuses = sorted(r[0] for r in race_results)
  3027. check(race_statuses == [200, 204, 204],
  3028. "concurrent asks race to exactly one winner (%s)" % race_statuses)
  3029. winner = [r for r in race_results if r[0] == 200][0][1]
  3030. check(int(winner["task"]["id"]) == race_task, "the winner's payload carries the task")
  3031. check(int(winner["session_id"]) > 0, "the assignment carries the session id")
  3032. conn = db()
  3033. race_sessions = conn.execute(
  3034. "select count(*) from sessions where task_id = ?", (race_task,)).fetchone()[0]
  3035. conn.close()
  3036. check(race_sessions == 1,
  3037. "exactly one session row — the transaction serialised the claims (%d)"
  3038. % race_sessions)
  3039. check(wait_task_done(auth, race_task, timeout=60) is not None,
  3040. "the raced task completes on the winning daemon")
  3041. for daemon in (fake, fake2, fake3):
  3042. daemon.ask_on_register = True
  3043. daemon.ask_on_wake = True
  3044. daemon.ask_on_terminal = True
  3045. daemon.ask_on_idle_status = True
  3046. # Re-establish sleeping explicitly: the winner's post-race
  3047. # re-ask timing is not deterministic, and the affinity section
  3048. # below needs every racer provably asleep. Any stray offerable
  3049. # drains into these asks first.
  3050. def all_asleep():
  3051. return all(daemon.ask_now()[0] == 204 for daemon in (fake, fake2, fake3))
  3052. check(wait_for(lambda: all_asleep() or False, timeout=30,
  3053. what="racers re-sleep after the race") is not None,
  3054. "all racers re-sleep after the race")
  3055. print("== phase 1: workspace affinity pins parked tasks ==")
  3056. # A suspended parent parked on racer-two may be resumed ONLY by
  3057. # racer-two: a tag-capable non-affine saddle asking gets 204, and
  3058. # the wake targets the affine saddle. Only racer-two carries the
  3059. # tag at dispatch time (the race's winner is nondeterministic, so
  3060. # the park must not depend on which racers are free); racer-three
  3061. # gains it afterwards to prove the pinning is by workspace, not
  3062. # tags.
  3063. saddles_state = slot_public(auth, "/saddles", "saddles")
  3064. act(auth, saddles_state["create_capability"], {"name": "affinity-tag"})
  3065. affinity_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3066. if c["name"] == "affinity-tag"][0])
  3067. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3068. if s["name"] == "racer-two"][0]
  3069. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3070. if s["name"] == "racer-three"][0]
  3071. act(auth, racer2_card["attach_capability"], {"capability_id": str(affinity_cap)})
  3072. # Plan 12: the parked workspace is the goal agent's run task. The
  3073. # other racers sleep (frozen ask triggers), so racer-two claims
  3074. # the goal run and parks it; the goal-task event then resumes the
  3075. # agent AFFINE to racer-two — racer-three (tag-capable or not)
  3076. # gets 204, the dispatcher's wake targets racer-two.
  3077. fake.ask_on_wake = False
  3078. fake.ask_on_idle_status = False
  3079. fake.settle_asks()
  3080. fake3.ask_on_wake = False
  3081. fake3.ask_on_idle_status = False
  3082. fake3.settle_asks()
  3083. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  3084. "project_id": "1", "title": "Affinity goal",
  3085. "brief": "Parks on racer-two.", "branch_name": "goal/affinity"})
  3086. conn = db()
  3087. affinity_goal = conn.execute(
  3088. "select id from goals where title = 'Affinity goal'").fetchone()[0]
  3089. conn.close()
  3090. fake2.goal_script = [("plan", "# Affinity plan\n\n1. Park")]
  3091. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")["start"], {})
  3092. check(wait_for(lambda: slot_public(auth, "/goals/%d" % affinity_goal,
  3093. "goal")["status"] == "plan_review" or False,
  3094. timeout=60, what="affinity goal plans") is not None,
  3095. "the affinity goal reaches plan review (racer-two hosting)")
  3096. fake2.goal_script = [("suspend",)]
  3097. # Freeze racer-two's ask triggers across the approval too (the
  3098. # later wake measurement already does): the mirror-sync fix makes
  3099. # the run resume-offerable the moment its goal row carries the
  3100. # verdict, so a wake-triggered background ask would race this
  3101. # manual ask_now for the claim.
  3102. fake2.ask_on_wake = False
  3103. fake2.ask_on_idle_status = False
  3104. fake2.settle_asks()
  3105. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")
  3106. ["plan_pending_block"]["answer_action"],
  3107. {"answer": "Plan approved. Proceed with implementation."})
  3108. conn = db()
  3109. affinity_parent = conn.execute(
  3110. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  3111. (affinity_goal,)).fetchone()[0]
  3112. agent_session = conn.execute(
  3113. "select id from sessions where task_id = ? and ended_at is null",
  3114. (affinity_parent,)).fetchone()[0]
  3115. conn.close()
  3116. status, resume_payload = fake2.ask_now()
  3117. check(status == 200 and int(resume_payload["task"]["id"]) == affinity_parent,
  3118. "the approved plan resumes the agent on racer-two (its workspace)")
  3119. check(wait_for(lambda: task_state(auth, affinity_parent).get("status") == "suspended"
  3120. or False, timeout=60, what="affinity agent parks") is not None,
  3121. "the affinity goal agent parks on racer-two")
  3122. conn = db()
  3123. affinity_session = conn.execute(
  3124. "select saddle_id from sessions where task_id = ? and ended_at is null",
  3125. (affinity_parent,)).fetchone()[0]
  3126. conn.close()
  3127. check(affinity_session == int(racer2_card["id"]),
  3128. "the parked workspace sits on racer-two")
  3129. # Now racer-three carries the tag too — the pinning is by
  3130. # workspace, not tags. With nothing due, a non-affine ask gets 204.
  3131. act(auth, racer3_card["attach_capability"], {"capability_id": str(affinity_cap)})
  3132. status, _ = fake3.ask_now()
  3133. check(status == 204,
  3134. "a tag-capable non-affine saddle is refused the parked agent (204)")
  3135. # A goal task completing makes the parked agent resume-offerable —
  3136. # affine to racer-two only. The other racers wake back up (they
  3137. # host the worker; their claims of the parked agent get refused as
  3138. # non-affine), while racer-two's ask triggers stay frozen so the
  3139. # wake measurement stays clean. A wake may have hit the frozen
  3140. # racers while the goal run queued (the lost-wake guard marks them
  3141. # offline): the refresh probe brings them back before the worker.
  3142. fake.ask_on_wake = True
  3143. fake.ask_on_idle_status = True
  3144. fake3.ask_on_wake = True
  3145. fake3.ask_on_idle_status = True
  3146. for racer_name in ("fake-saddle", "racer-three"):
  3147. act(auth, saddle_card(auth, racer_name)["refresh"], {})
  3148. check(wait_for(lambda name=racer_name: [s for s in
  3149. slot_public(auth, "/saddles", "saddles")["saddles"]
  3150. if s["name"] == name][0]["status"] == "idle"
  3151. or False, timeout=15, what="racer re-onlined") is not None,
  3152. "%s re-onlined after its frozen-window wake" % racer_name)
  3153. fake2.ask_on_wake = False
  3154. fake2.ask_on_idle_status = False
  3155. wakes_before_2 = len(fake2.wake_log)
  3156. fake2.settle_asks() # converted sleep: park-time ask lands (204)
  3157. status, body = saddle_api("POST", "/api/saddle/task/create", fake2.token, {
  3158. "session_id": agent_session, "title": "Affinity child",
  3159. "mandate": "finish the affinity fixture"})
  3160. check(status == 200, "the parked agent fans its worker out via the CLI")
  3161. affinity_child = int(body["task_id"])
  3162. saddle_api("POST", "/api/saddle/task/enqueue", fake2.token,
  3163. {"session_id": agent_session, "task_id": affinity_child})
  3164. check(wait_task_done(auth, affinity_child, timeout=90) is not None,
  3165. "the affinity worker completes (on a non-affine racer)")
  3166. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_2 or False,
  3167. timeout=90, what="affine wake") is not None,
  3168. "the dispatcher's wake targets the affine saddle")
  3169. status, resume_payload = fake2.ask_now()
  3170. fake2.ask_on_wake = True # restored whatever the claim returned
  3171. fake2.ask_on_idle_status = True
  3172. check(status == 200 and int(resume_payload["task"]["id"]) == affinity_parent,
  3173. "the affine saddle's ask claims the parked agent")
  3174. check("Affinity child" in (resume_payload.get("resume_notice") or "")
  3175. and "fake daemon finished" in (resume_payload.get("resume_notice") or ""),
  3176. "the resume assignment carries the goal's batched report notice")
  3177. check(wait_for(lambda: task_state(auth, affinity_parent).get("status")
  3178. == "suspended" or False,
  3179. timeout=60, what="affinity agent re-parks") is not None,
  3180. "the resumed agent re-parks (script)")
  3181. act(auth, slot_public(auth, "/goals/%d" % affinity_goal, "goal")["cancel"], {})
  3182. check(wait_for(lambda: slot_public(auth, "/goals/%d" % affinity_goal,
  3183. "goal")["status"] == "cancelled" or False,
  3184. timeout=30, what="affinity goal cancelled") is not None,
  3185. "the affinity goal cancels (drain)")
  3186. print("== phase 1: lost wake -> offline + re-wake of the next capable ==")
  3187. # racer-three sleeps through wakes (a daemon that died after its
  3188. # last 204): the guard window (SADDLE_LOST_WAKE_S=2) passes with
  3189. # no ask, the saddle goes offline, and the work moves to the
  3190. # next capable sleeping saddle.
  3191. fake3.ask_on_wake = False
  3192. fake3.ask_on_idle_status = False # sleeps through everything
  3193. saddles_state = slot_public(auth, "/saddles", "saddles")
  3194. act(auth, saddles_state["create_capability"], {"name": "lostwake"})
  3195. lostwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3196. if c["name"] == "lostwake"][0])
  3197. racer3_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3198. if s["name"] == "racer-three"][0]
  3199. act(auth, racer3_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  3200. # Racer-three must be asleep to be woken: park it with a manual
  3201. # 204 ask (nothing offerable for it — the task below is not
  3202. # created yet).
  3203. status, _ = fake3.ask_now()
  3204. check(status == 204, "racer-three sleeps before the lost-wake run")
  3205. task_id_tmp = create_queued(auth, {
  3206. "project_id": "1",
  3207. "title": "Lost wake task",
  3208. "priority": "2",
  3209. "capability_id": [str(lostwake_cap)],
  3210. })
  3211. lost_task = task_id_tmp
  3212. check(wait_for(lambda: len(fake3.wake_log) > 0 or False,
  3213. timeout=30, what="wake sent to racer-three") is not None,
  3214. "the only capable sleeping saddle is woken")
  3215. check(wait_for(lambda: [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3216. if s["name"] == "racer-three"][0]["status"] == "offline"
  3217. or False, timeout=30, what="lost-wake -> offline") is not None,
  3218. "no ask after the wake: the saddle goes offline (lost-wake guard)")
  3219. check(task_state(auth, lost_task)["status"] == "queued",
  3220. "the task is untouched while its wake was pending")
  3221. # Re-wake the next capable: the healthy saddle gains the tag and
  3222. # picks the work up via its own wake -> ask -> allocate roundtrip.
  3223. fake_card = saddle_card(auth, "fake-saddle")
  3224. act(auth, fake_card["attach_capability"], {"capability_id": str(lostwake_cap)})
  3225. wakes_before = len(fake.wake_log)
  3226. check(wait_for(lambda: len(fake.wake_log) > wakes_before or False,
  3227. timeout=30, what="re-wake of the next capable") is not None,
  3228. "the next capable sleeping saddle is woken for the task")
  3229. check(wait_task_done(auth, lost_task, timeout=60) is not None,
  3230. "wake -> ask -> allocate: the task completes on the healthy saddle")
  3231. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == lost_task
  3232. for p in fake.start_payloads) or False,
  3233. timeout=10, what="lost task assignment captured") is not None,
  3234. "the re-woken saddle's ask produced the assignment")
  3235. fake3.ask_on_wake = True
  3236. fake3.ask_on_idle_status = True
  3237. print("== phase 3: capability context, catalogue, subtask tags ==")
  3238. # Assignment capability context (plan 10 phase 3): every
  3239. # assignment carries {saddle_tags: the allocated saddle's tags,
  3240. # fleet_tags: every tag name known across the fleet} — the
  3241. # daemon renders it into its system prompt. fake-saddle carries
  3242. # gpu + lostwake; the catalogue is affinity-tag, gpu, lostwake.
  3243. fake2.ask_on_register = False
  3244. fake2.ask_on_wake = False
  3245. fake2.ask_on_terminal = False
  3246. fake2.ask_on_idle_status = False
  3247. fake2.settle_asks() # converted sleep: in-flight trigger asks land
  3248. task_id_tmp = create_queued(auth, {
  3249. "project_id": "1",
  3250. "title": "Capabilities context",
  3251. "priority": "2",
  3252. })
  3253. cap_task = task_id_tmp
  3254. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == cap_task
  3255. for p in fake.start_payloads) or False,
  3256. timeout=60, what="capabilities-context task dispatched") is not None,
  3257. "the capabilities-context task dispatches")
  3258. cap_payload = [p for p in fake.start_payloads
  3259. if int(p.get("task", {}).get("id") or 0) == cap_task][-1]
  3260. context = cap_payload.get("capabilities") or {}
  3261. check(context.get("saddle_tags") == ["gpu", "lostwake"],
  3262. "assignment saddle_tags = the allocated saddle's tags (%s)"
  3263. % context.get("saddle_tags"))
  3264. check(context.get("fleet_tags") == ["affinity-tag", "gpu", "lostwake"],
  3265. "assignment fleet_tags = every tag name known across the fleet (%s)"
  3266. % context.get("fleet_tags"))
  3267. check(wait_task_done(auth, cap_task, timeout=60) is not None,
  3268. "capabilities-context task completes")
  3269. # GET /api/saddle/capabilities feeds the daemon's `saddle
  3270. # capabilities` CLI: per-saddle-token auth, tag order by name,
  3271. # each tag with the saddles carrying it (name order).
  3272. status, _ = saddle_api("GET", "/api/saddle/capabilities", None)
  3273. check(status == 401, "capabilities endpoint rejects a missing token")
  3274. status, body = saddle_api("GET", "/api/saddle/capabilities", "saddle-bogus")
  3275. check(status == 401, "capabilities endpoint rejects a wrong token")
  3276. status, body = saddle_api("GET", "/api/saddle/capabilities", fake_token)
  3277. catalogue = {t["name"]: t["saddles"] for t in body.get("tags", [])}
  3278. check(status == 200 and body.get("ok") is True
  3279. and [t["name"] for t in body.get("tags", [])]
  3280. == ["affinity-tag", "gpu", "lostwake"],
  3281. "catalogue lists every tag by name")
  3282. check(catalogue.get("gpu") == ["fake-saddle"]
  3283. and catalogue.get("affinity-tag") == ["racer-three", "racer-two"]
  3284. and catalogue.get("lostwake") == ["fake-saddle", "racer-three"],
  3285. "each tag names its carrying saddles in name order (%s)" % catalogue)
  3286. # Task CLI capabilities (`task create --capability`): validated
  3287. # against the operator tag set; unknown tags reject with the valid
  3288. # list in the error (the agent reads it verbatim in the CLI
  3289. # output). A goal agent's parked session hosts the calls.
  3290. fake.suspend_on_title = "Tag host"
  3291. tag_host = create_queued(auth, {
  3292. "project_id": "1", "title": "Tag host", "priority": "3"})
  3293. check(wait_for(lambda: task_state(auth, tag_host)["status"] == "suspended"
  3294. or False, timeout=60, what="tag host parks") is not None,
  3295. "a parked plain task hosts nothing (no goal scope)")
  3296. # The goal callbacks need a real goal agent: reuse the sequencing
  3297. # goal pattern — a fresh parked agent under this shard.
  3298. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  3299. "project_id": "1", "title": "Tag goal", "brief": "b",
  3300. "branch_name": "goal/tags"})
  3301. conn = db()
  3302. tag_goal = conn.execute("select id from goals where title = 'Tag goal'").fetchone()[0]
  3303. conn.close()
  3304. fake.goal_script = [("suspend",)]
  3305. act(auth, slot_public(auth, "/goals/%d" % tag_goal, "goal")["start"], {})
  3306. conn = db()
  3307. tag_run = conn.execute(
  3308. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  3309. (tag_goal,)).fetchone()[0]
  3310. conn.close()
  3311. check(wait_for(lambda: task_state(auth, tag_run)["status"] == "suspended"
  3312. or False, timeout=60, what="tag goal agent parks") is not None,
  3313. "the tag goal agent parks")
  3314. conn = db()
  3315. tag_session = conn.execute(
  3316. "select id from sessions where task_id = ? and ended_at is null",
  3317. (tag_run,)).fetchone()[0]
  3318. conn.close()
  3319. conn = db()
  3320. tag_host_saddle = conn.execute(
  3321. "select saddle_id from sessions where id = ?", (tag_session,)).fetchone()[0]
  3322. conn.close()
  3323. racer2_card_id = int([c for c in slot_public(auth, "/saddles", "saddles")["saddles"]
  3324. if c["name"] == "racer-two"][0]["id"])
  3325. racer3_card_id = int([c for c in slot_public(auth, "/saddles", "saddles")["saddles"]
  3326. if c["name"] == "racer-three"][0]["id"])
  3327. host_daemon = {int(fake_id): fake, racer2_card_id: fake2,
  3328. racer3_card_id: fake3}[int(tag_host_saddle)]
  3329. status, body = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3330. "session_id": tag_session, "title": "Bad tag worker",
  3331. "mandate": "m", "capabilities": ["gpu", "warp-drive"]})
  3332. check(status == 400, "an unknown capability tag rejects the task call")
  3333. error_text = body.get("error", "")
  3334. check("warp-drive" in error_text and "valid tags" in error_text
  3335. and "gpu" in error_text and "lostwake" in error_text,
  3336. "the rejection names the unknown tag and the valid list (%s)" % error_text)
  3337. status, _ = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3338. "session_id": tag_session, "title": "Bad shape worker",
  3339. "mandate": "m", "capabilities": "gpu"})
  3340. check(status == 400, "a non-array capabilities member rejects")
  3341. # A valid tag creates the goal worker in draft with exactly the
  3342. # explicit tag attached; the goal agent enqueues it.
  3343. status, body = saddle_api("POST", "/api/saddle/task/create", host_daemon.token, {
  3344. "session_id": tag_session, "title": "Explicit tag worker",
  3345. "mandate": "do the tagged work", "capabilities": ["gpu"]})
  3346. check(status == 200 and body.get("ok") is True,
  3347. "a valid tag creates the task synchronously")
  3348. tagged_worker = int(body["task_id"])
  3349. detail = task_state(auth, tagged_worker)
  3350. check([c["name"] for c in detail.get("capabilities", [])] == ["gpu"],
  3351. "the worker carries exactly the explicit tag")
  3352. conn = db()
  3353. tag_rows = conn.execute(
  3354. "select c.name from task_capabilities tc"
  3355. " join capabilities c on c.id = tc.capability_id"
  3356. " where tc.task_id = ?", (tagged_worker,)).fetchall()
  3357. conn.close()
  3358. check([r[0] for r in tag_rows] == ["gpu"],
  3359. "the task_capabilities rows record the explicit tag")
  3360. check(detail["status"] == "draft",
  3361. "the callback's task lands in draft until its agent enqueues")
  3362. saddle_api("POST", "/api/saddle/task/enqueue", host_daemon.token,
  3363. {"session_id": tag_session, "task_id": tagged_worker})
  3364. check(wait_task_done(auth, tagged_worker, timeout=90) is not None,
  3365. "the tagged worker dispatches and completes")
  3366. act(auth, slot_public(auth, "/goals/%d" % tag_goal, "goal")["cancel"], {})
  3367. act(auth, task_state(auth, tag_host)["cancel"], {})
  3368. print("== phase 3: dashboard — pinned blocks + activity timeline ==")
  3369. # Pinned OPEN blocking items as link-through cards, newest
  3370. # first; no inline answer forms (the card links to the task
  3371. # page). Fixture: one open question + one open review raised on a
  3372. # local task (stand-ins for the auto-approve grandchild's
  3373. # leftovers) join the probe RFC raised below.
  3374. conn = db()
  3375. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  3376. " values (1, 'Dash fixture task', 'working', 5, strftime('%s','now'))")
  3377. dash_task = conn.execute("select max(id) from tasks").fetchone()[0]
  3378. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  3379. " values (?, ?, strftime('%s','now'))", (dash_task, fake_id))
  3380. dash_session = conn.execute("select max(id) from sessions").fetchone()[0]
  3381. conn.commit()
  3382. conn.close()
  3383. def raise_on_dash(question, kind="question", body=None, summary=None):
  3384. """Push-era raises on the dashboard fixture task (the poll-era
  3385. /update channel is gone): a blocked results push carries the
  3386. block payload; a review verb rides a review entry."""
  3387. if kind == "review" and summary is not None:
  3388. return saddle_api("POST", "/api/saddle/results", fake_token, {
  3389. "session_id": dash_session, "state": "working",
  3390. "entries": [{"id": 9317,
  3391. "command": "saddle review",
  3392. "output": summary, "type": "review",
  3393. "timestamp": time.strftime(
  3394. "%Y-%m-%dT%H:%M:%SZ", time.gmtime())}]})[0]
  3395. block = {"question": question, "type": kind}
  3396. if body is not None:
  3397. block["body"] = body
  3398. return saddle_api("POST", "/api/saddle/results", fake_token, {
  3399. "session_id": dash_session, "state": "blocked",
  3400. "block": block})[0]
  3401. raise_on_dash("Dash fixture question?", kind="question")
  3402. raise_on_dash("dash fixture review", kind="review", summary="dash fixture review")
  3403. # The activity timeline: last <= 50 events, newest first, fed
  3404. # from the existing tables. Fixture rows a few seconds old
  3405. # guarantee the progress kind and a human-authored comment ride
  3406. # along; the probe block below proves same-source ordering.
  3407. conn = db()
  3408. conn.execute("insert into task_comments (task_id, author, body, created_at)"
  3409. " values (?, 'user:admin', 'timeline fixture comment by a human',"
  3410. " strftime('%s','now','-5 seconds'))", (cap_task,))
  3411. conn.execute("insert into task_progress (task_id, summary, created_at)"
  3412. " values (?, 'timeline fixture progress',"
  3413. " strftime('%s','now','-5 seconds'))",
  3414. (cap_task,))
  3415. conn.commit()
  3416. conn.close()
  3417. # The probe RFC raised last: the newest pinned card and the newest
  3418. # timeline event (its raise+answer below prove same-source ordering
  3419. # both ways). The timeline sorts same-second events by source
  3420. # materialisation order, so the probe must land in a LATER clock
  3421. # second than the fixtures — wait for the boundary (bounded).
  3422. fixtures_epoch = int(time.time())
  3423. wait_for(lambda: int(time.time()) > fixtures_epoch or False,
  3424. timeout=3, what="next clock second before the probe raise")
  3425. raise_on_dash("Timeline probe: approve the dashboard flow",
  3426. kind="rfc", body="# Probe")
  3427. dash = slot_public(auth, "/", "dashboard")
  3428. pinned = dash.get("pinned", [])
  3429. pinned_ids = [int(b["id"]) for b in pinned]
  3430. check(len(pinned_ids) >= 3 and pinned_ids == sorted(pinned_ids, reverse=True),
  3431. "pinned open blocks order newest-first (%s)" % pinned_ids)
  3432. check({b["block_type"] for b in pinned} >= {"question", "rfc", "review"},
  3433. "pinned cards cover questions, RFCs and reviews")
  3434. check(all(b["question"] and b["task_title"] and int(b["task_id"]) > 0
  3435. for b in pinned)
  3436. and all("answer_action" not in b for b in pinned),
  3437. "pinned cards are link-through only (task title, kind badge, question)")
  3438. activity = dash.get("activity", [])
  3439. epochs = [int(e["at_epoch"]) for e in activity]
  3440. check(0 < len(activity) <= 50 and epochs == sorted(epochs, reverse=True),
  3441. "the timeline shows the last <=50 events newest-first (%d events)"
  3442. % len(activity))
  3443. kinds = {e["kind"] for e in activity}
  3444. check({"created", "started", "dispatch", "comment", "progress", "completed"} <= kinds,
  3445. "the timeline covers status changes, dispatches, comments, progress and"
  3446. " completions (%s)" % sorted(kinds))
  3447. check(any(e["kind"] == "comment" and e["text"].startswith("user:admin:")
  3448. and "fixture comment" in e["text"] for e in activity),
  3449. "comment events carry author + snippet")
  3450. # The freshly raised probe pinned as the newest card and landed
  3451. # atop the timeline as block-raised; answering it records
  3452. # block-answered.
  3453. check(dash["pinned"][0]["question"] == "Timeline probe: approve the dashboard flow"
  3454. and int(dash["pinned"][0]["task_id"]) == dash_task,
  3455. "the freshest open block pins as the first card")
  3456. check(dash["activity"][0]["kind"] == "block-raised"
  3457. and "Timeline probe" in dash["activity"][0]["text"],
  3458. "the raised block lands atop the timeline")
  3459. probe_block = [b for b in task_state(auth, dash_task)["blocks"]
  3460. if b["question"] == "Timeline probe: approve the dashboard flow"][0]
  3461. act(auth, probe_block["answer_action"], {"answer": "Ship the dashboard"})
  3462. dash = slot_public(auth, "/", "dashboard")
  3463. activity = dash.get("activity", [])
  3464. raised_at = next((i for i, e in enumerate(activity)
  3465. if e["kind"] == "block-raised" and "Timeline probe" in e["text"]), -1)
  3466. answered_at = next((i for i, e in enumerate(activity)
  3467. if e["kind"] == "block-answered"
  3468. and "Ship the dashboard" in e["text"]), -1)
  3469. check(answered_at >= 0 and raised_at >= 0 and answered_at < raised_at,
  3470. "the answered event sorts above its raised event (newest-first, same source)")
  3471. check(all(b["question"] != "Timeline probe: approve the dashboard flow"
  3472. for b in dash["pinned"]),
  3473. "the answered block leaves the pinned cards")
  3474. print("== phase 3 regression: a slow ask after a wake is never dropped ==")
  3475. # The daemon worker's lost-wake-guard regression: a saddle whose
  3476. # ask arrives SLOWLY after the wake (busy winding down when the
  3477. # wake lands) must not lose the wake — the delayed ask (inside
  3478. # the guard window) claims the task, no re-wake storm fires
  3479. # while it is pending, and the saddle stays healthy. The
  3480. # never-asks path (guard -> offline + re-wake of the next
  3481. # capable) is proven by the racer-three section above.
  3482. check(wait_for(lambda: queued_count() == 0 or False,
  3483. timeout=60, what="queue settles before the slow-wake run") is not None,
  3484. "the queue settles before the slow-wake run")
  3485. status, _ = fake2.ask_now()
  3486. check(status == 204, "the slow-ask racer sleeps before its wake")
  3487. saddles_state = slot_public(auth, "/saddles", "saddles")
  3488. act(auth, saddles_state["create_capability"], {"name": "slowwake"})
  3489. slowwake_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")
  3490. ["capabilities"] if c["name"] == "slowwake"][0])
  3491. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3492. if s["name"] == "racer-two"][0]
  3493. act(auth, racer2_card["attach_capability"], {"capability_id": str(slowwake_cap)})
  3494. fake2.ask_delay = 1.2 # slow: asks well after the wake, inside the 2s guard
  3495. fake2.ask_on_wake = True
  3496. wakes_before_slow = len(fake2.wake_log)
  3497. task_id_tmp = create_queued(auth, {
  3498. "project_id": "1",
  3499. "title": "Slow wake task",
  3500. "priority": "2",
  3501. "capability_id": [str(slowwake_cap)],
  3502. })
  3503. slow_task = task_id_tmp
  3504. check(wait_for(lambda: len(fake2.wake_log) > wakes_before_slow or False,
  3505. timeout=30, what="the slow-ask racer woken") is not None,
  3506. "the only capable sleeping saddle is woken")
  3507. check(wait_task_done(auth, slow_task, timeout=120) is not None,
  3508. "the delayed ask claims the task — the wake was not dropped")
  3509. check(any(a.get("status") == 200
  3510. and int((a.get("payload") or {}).get("task", {}).get("id") or 0)
  3511. == slow_task for a in fake2.asks),
  3512. "the slow ask's 200 carries the task")
  3513. check(len(fake2.wake_log) == wakes_before_slow + 1,
  3514. "the pending-wake skip re-wakes nobody while the slow ask is in flight")
  3515. racer2_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  3516. if s["name"] == "racer-two"][0]
  3517. check(racer2_card["status"] in ("idle", "busy"),
  3518. "the slow asker never went offline (guard did not fire)")
  3519. fake2.ask_delay = 0.0
  3520. fake2.ask_on_wake = False # stays out of the pool below
  3521. # =============================================================================
  3522. # Bundle: lifecycle — offline requeues, the hung-request tick survival,
  3523. # parked-refresh bookkeeping, cancellation, the health panel, raw-log
  3524. # losslessness, git identity and the live blocked-push roundtrip.
  3525. # =============================================================================
  3526. def bundle_lifecycle(ctx):
  3527. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  3528. app = ctx.app
  3529. print("== plan 11: draft state machine, edit matrix, enqueue/delete guards ==")
  3530. # New tasks default to draft; Enqueue is the only path to the
  3531. # queue (there is no agent path — the ingest API refuses to queue).
  3532. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3533. "project_id": "1",
  3534. "title": "Draft lifecycle task",
  3535. "priority": "4",
  3536. })
  3537. draft_task = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3538. if t["title"] == "Draft lifecycle task"][0])
  3539. detail = task_state(auth, draft_task)
  3540. check(detail["status"] == "draft", "a created task lands in draft")
  3541. check(detail.get("enqueue") is not None and detail.get("delete") is not None,
  3542. "draft exposes the enqueue + delete actions")
  3543. check(detail.get("cancel") is not None, "the cancel action stays authored")
  3544. status, page = http("GET", "/tasks/%d" % draft_task, timeout=15)
  3545. check(status == 200 and "Enqueue task" in page and ">Delete<" in page,
  3546. "the task page shows Enqueue + Delete in draft")
  3547. check("Mark done" not in page,
  3548. "the user Mark-complete action is gone (agent-only completion)")
  3549. # Plan 12: the auto-enqueue-after predecessor REPLACES draft
  3550. # dependencies — setting it is allowed while the predecessor is
  3551. # still pending (the enqueue itself succeeds; the DISPATCHER holds
  3552. # dispatch back until the predecessor is done).
  3553. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3554. "project_id": "1",
  3555. "title": "Draft dependency",
  3556. "priority": "4",
  3557. })
  3558. draft_dep = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3559. if t["title"] == "Draft dependency"][0])
  3560. act(auth, detail["update"], {"enqueue_after_task_id": str(draft_dep)})
  3561. check(int(task_state(auth, draft_task).get("enqueue_after_task_id") or 0)
  3562. == draft_dep,
  3563. "the draft edit sets the auto-enqueue predecessor")
  3564. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3565. "project_id": "1", "title": "Eager dependent", "priority": "4",
  3566. "enqueue_after_task_id": str(draft_dep)})
  3567. eager = task_id_of("Eager dependent")
  3568. enqueue_task(auth, eager)
  3569. check(task_state(auth, eager)["status"] == "queued",
  3570. "enqueue succeeds while the predecessor is pending (no draft guard)")
  3571. check(quiet_window(quiet_seconds(),
  3572. lambda: task_state(auth, eager)["status"] == "queued",
  3573. "pending predecessor holds dispatch"),
  3574. "the pending predecessor holds dispatch back (never assigned)")
  3575. # The edit matrix starts in DRAFT: every field except status.
  3576. act(auth, detail["update"], {
  3577. "title": "Draft lifecycle task (edited)",
  3578. "description": "Now with a description",
  3579. "priority": "2",
  3580. "task_branch": "feature/draft",
  3581. "branch_from": "main",
  3582. "mode": "investigate",
  3583. })
  3584. detail = task_state(auth, draft_task)
  3585. check(detail["title"] == "Draft lifecycle task (edited)"
  3586. and detail["description"] == "Now with a description"
  3587. and detail["priority"] == 2
  3588. and detail["task_branch"] == "feature/draft"
  3589. and detail["branch_from"] == "main"
  3590. and detail["mode"] == "investigate",
  3591. "draft edits apply to every field (incl. the mode)")
  3592. # Clear the predecessor (the empty sentinel): dispatch gates on
  3593. # the hold tag alone now.
  3594. act(auth, detail["update"], {"enqueue_after_task_id": "0"})
  3595. check(not int(task_state(auth, draft_task).get("enqueue_after_task_id") or 0),
  3596. "the draft edit clears the auto-enqueue predecessor")
  3597. # A hold tag nothing carries keeps the dependent QUEUED (never
  3598. # dispatched) through the remaining edit-matrix checks.
  3599. saddles_state = slot_public(auth, "/saddles", "saddles")
  3600. act(auth, saddles_state["create_capability"], {"name": "holdlock"})
  3601. holdlock_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  3602. if c["name"] == "holdlock"][0])
  3603. act(auth, detail["attach_capability"], {"capability_id": str(holdlock_cap)})
  3604. # Enqueue the now-cleared dependent: the hold tag keeps it queued
  3605. # (never dispatched), so the non-draft edit matrix applies.
  3606. enqueue_task(auth, draft_task)
  3607. check(quiet_window(3, lambda: task_state(auth, draft_task)["status"] == "queued",
  3608. "held dependent stays queued"),
  3609. "the held dependent stays queued (never dispatched)")
  3610. # The predecessor settles for the shard drain.
  3611. enqueue_task(auth, draft_dep)
  3612. check(wait_task_done(auth, draft_dep, timeout=90) is not None,
  3613. "the predecessor settles")
  3614. # Drafts are never dispatched even with an idle saddle available.
  3615. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3616. "project_id": "1",
  3617. "title": "Never-dispatched draft",
  3618. "priority": "1",
  3619. })
  3620. silent_draft = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3621. if t["title"] == "Never-dispatched draft"][0])
  3622. check(quiet_window(quiet_seconds(),
  3623. lambda: task_state(auth, silent_draft)["status"] == "draft",
  3624. "draft never dispatched"),
  3625. "an idle saddle never picks a draft up (no agent enqueue path)")
  3626. # Once work can begin (queued here), only priority is editable.
  3627. act(auth, detail["update"], {
  3628. "title": "Should not apply",
  3629. "priority": "3",
  3630. })
  3631. detail = task_state(auth, draft_task)
  3632. check(detail["title"] == "Draft lifecycle task (edited)" and detail["priority"] == 3,
  3633. "non-draft edits apply priority only (title locked)")
  3634. # A terminal task edits nothing.
  3635. conn = db()
  3636. conn.execute("update tasks set status = 'done', completed_at = strftime('%s','now')"
  3637. " where id = ?", (draft_task,))
  3638. conn.commit()
  3639. conn.close()
  3640. act(auth, task_state(auth, draft_task)["update"], {"priority": "8"})
  3641. check(task_state(auth, draft_task)["priority"] == 3,
  3642. "terminal tasks edit nothing (priority locked)")
  3643. # Capabilities lock once a worker has the job: editable while
  3644. # queued, locked once working.
  3645. act(auth, saddles_state["create_capability"], {"name": "editlock"})
  3646. editlock_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")
  3647. ["capabilities"] if c["name"] == "editlock"][0])
  3648. act(auth, saddle_card(auth, "fake-saddle")["attach_capability"],
  3649. {"capability_id": str(editlock_cap)})
  3650. locked_task = create_queued(auth, {"project_id": "1", "title": "Caplock task",
  3651. "priority": "2"})
  3652. detail = task_state(auth, locked_task)
  3653. act(auth, detail["attach_capability"], {"capability_id": str(editlock_cap)})
  3654. check(wait_for(lambda: any(c["name"] == "editlock"
  3655. for c in task_state(auth,
  3656. locked_task)["capabilities"])
  3657. or False, timeout=60, what="editlock attached") is not None,
  3658. "capabilities attach while queued (no worker yet)")
  3659. check(wait_for(lambda: task_state(auth, locked_task).get("status") == "working"
  3660. or False, timeout=60, what="caplock working") is not None,
  3661. "the caplock task reaches working")
  3662. detach_directives = act(auth, task_state(auth, locked_task)["capabilities"][0]["detach"], {})
  3663. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  3664. for d in detach_directives),
  3665. "capabilities are locked once a worker has the job")
  3666. # The ingest API has no queue transition either (only working and
  3667. # blocked are accepted states).
  3668. conn = db()
  3669. caplock_session = conn.execute(
  3670. "select id from sessions where task_id = ? and ended_at is null",
  3671. (locked_task,)).fetchone()
  3672. conn.close()
  3673. if caplock_session is not None:
  3674. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  3675. {"session_id": caplock_session[0],
  3676. "state": "queued"})
  3677. check(status == 200
  3678. and task_state(auth, locked_task)["status"] in ("working", "done"),
  3679. "a queued state push is a no-op (only the wire's states drive bookkeeping)")
  3680. # Delete guards: a clean draft deletes; non-draft refuses; a draft
  3681. # with dependents is refused naming them.
  3682. act(auth, task_state(auth, silent_draft)["delete"], {})
  3683. check(not any(t["id"] == silent_draft
  3684. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  3685. "a clean draft task deletes")
  3686. delete_directives = act(auth, task_state(auth, draft_task)["delete"], {})
  3687. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  3688. for d in delete_directives),
  3689. "a non-draft task refuses the delete")
  3690. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3691. "project_id": "1", "title": "Guarded draft", "priority": "4"})
  3692. guarded = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3693. if t["title"] == "Guarded draft"][0])
  3694. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  3695. "project_id": "1", "title": "Dependent namer", "priority": "4"})
  3696. namer = int([t["id"] for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  3697. if t["title"] == "Dependent namer"][0])
  3698. act(auth, task_state(auth, namer)["update"],
  3699. {"enqueue_after_task_id": str(guarded)})
  3700. check(int(task_state(auth, namer).get("enqueue_after_task_id") or 0) == guarded,
  3701. "the namer points at the guarded predecessor")
  3702. act(auth, task_state(auth, guarded)["delete"], {})
  3703. check(not any(t["id"] == guarded
  3704. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  3705. "deleting a predecessor succeeds")
  3706. check(not int(task_state(auth, namer).get("enqueue_after_task_id") or 0),
  3707. "the delete clears the dependent's dangling predecessor reference")
  3708. print("== offline requeues ==")
  3709. # Tasks caught working on a saddle that went offline requeue with a
  3710. # agent comment each tick.
  3711. task_id_tmp = create_queued(auth, {
  3712. "project_id": "1",
  3713. "title": "Offline saddle task",
  3714. "priority": "2",
  3715. })
  3716. offline_task = task_id_tmp
  3717. check(wait_for(lambda: task_state(auth, offline_task).get("status") == "working"
  3718. or False, timeout=60, what="offline task starts working") is not None,
  3719. "task reaches working before its saddle disappears")
  3720. # Hold the daemon mid-round across the requeue window (the
  3721. # original relied on its 8s work period outlasting the 5s tick):
  3722. # the task completing on its own would race the offline pass and
  3723. # skip the requeue the check exists to observe.
  3724. fake.hold_state = True
  3725. conn = db()
  3726. conn.execute("update saddles set status = 'offline' where name = 'fake-saddle'")
  3727. conn.commit()
  3728. conn.close()
  3729. # The requeue frees the saddle in the same tick, so 'queued' is
  3730. # transient; the durable evidence is the agent comment (and the task
  3731. # completing again on the healthy daemon).
  3732. check(wait_for(lambda: any(c["body"] == "saddle went offline; task requeued"
  3733. for c in task_state(auth, offline_task).get("comments", []))
  3734. or False, timeout=30, what="offline requeue comment") is not None,
  3735. "offline saddle requeues the task")
  3736. fake.hold_state = False # release: the round ends, the daemon re-asks
  3737. check(wait_task_done(auth, offline_task, timeout=60) is not None,
  3738. "requeued task completes again on the healthy daemon")
  3739. # R2 (arch 13): the release owner's outcomes — the requeue closed
  3740. # the held attempt's session 'stopped'; the held daemon's terminal
  3741. # push then completes the task against that closed session (the
  3742. # outcome stands — a closed row never reopens). A task that
  3743. # completes a LIVE round closes its session 'done' (draft_dep
  3744. # above ran one open session to its terminal push).
  3745. conn = db()
  3746. outcome_rows = conn.execute(
  3747. "select outcome from sessions where task_id = ? order by id",
  3748. (offline_task,)).fetchall()
  3749. dep_outcome = conn.execute(
  3750. "select outcome from sessions where task_id = ? order by id desc",
  3751. (draft_dep,)).fetchone()
  3752. conn.close()
  3753. check(outcome_rows and outcome_rows[0][0] == "stopped",
  3754. "the one release path closes the requeued attempt 'stopped'")
  3755. check(dep_outcome is not None and dep_outcome[0] == "done",
  3756. "the terminal push closes a live round's session 'done'")
  3757. print("== R6 F1: a hanging request cannot freeze the tick ==")
  3758. # One wedged /task-update (never responds) blocks the comment/
  3759. # subtask-event delivery pass; the Soup timeout must fail it and
  3760. # later ticks keep dispatching.
  3761. conn = db()
  3762. conn.execute("insert into tasks (project_id, title, status, priority, created_at)"
  3763. " values (1, 'Hang survivor', 'queued', 2, strftime('%s','now'))")
  3764. hang_task = conn.execute("select max(id) from tasks").fetchone()[0]
  3765. conn.close()
  3766. task_id_tmp = create_queued(auth, {
  3767. "project_id": "1",
  3768. "title": "Hang runner",
  3769. "priority": "3",
  3770. })
  3771. hang_runner = task_id_tmp
  3772. # A human comment on the running task gives the tick a
  3773. # /task-update delivery to make; the next one hangs.
  3774. check(wait_for(lambda: task_state(auth, hang_runner).get("status") == "working"
  3775. or False, timeout=60, what="hang runner working") is not None,
  3776. "hang runner reaches working")
  3777. act(auth, task_state(auth, hang_runner)["comment"],
  3778. {"body": "operator ping while wedged"})
  3779. fake.hang_next["/task-update"] = 1
  3780. check(wait_task_done(auth, hang_runner, timeout=90) is not None,
  3781. "dispatching task survives a hung daemon request")
  3782. check(wait_for(lambda: any(c.get("text") == "operator ping while wedged"
  3783. or c.get("body") == "operator ping while wedged"
  3784. for c in fake.comment_log) or False,
  3785. timeout=30, what="wedged comment eventually delivered") is not None,
  3786. "the comment delivery retries after the hang")
  3787. # The hung delivery itself fails after the timeout; the system
  3788. # kept moving either way.
  3789. with open(os.path.join(WORK, "app.log")) as handle:
  3790. app_log = handle.read()
  3791. check("tick exceeded" not in app_log or "Dispatch tick failed" in app_log,
  3792. "a hung request never freezes the tick latch")
  3793. print("== R6 F2: refresh must not corrupt parked bookkeeping ==")
  3794. fake.suspend_on_title = "Parked refresh parent"
  3795. task_id_tmp = create_queued(auth, {
  3796. "project_id": "1",
  3797. "title": "Parked refresh parent",
  3798. "priority": "2",
  3799. })
  3800. parked = task_id_tmp
  3801. check(wait_for(lambda: task_state(auth, parked).get("status") == "suspended"
  3802. or False, timeout=60, what="parked parent suspends") is not None,
  3803. "parent parks before the refresh")
  3804. fake_card = saddle_card(auth, "fake-saddle")
  3805. act(auth, fake_card["refresh"], {})
  3806. fake_card = saddle_card(auth, "fake-saddle")
  3807. check(fake_card["status"] == "idle" and int(fake_card["current_task_id"] or 0) == 0,
  3808. "refresh on a parked (suspended) daemon leaves the saddle idle")
  3809. # The parked task keeps its open session and stays put: plain
  3810. # tasks have no subtask events to resume them (the goal machinery
  3811. # owns resumes); the human resumes it explicitly.
  3812. check(quiet_window(quiet_seconds(),
  3813. lambda: task_state(auth, parked)["status"] == "suspended",
  3814. "parked task stays parked"),
  3815. "a parked plain task stays parked after the refresh (no resume channel)")
  3816. act(auth, task_state(auth, parked)["cancel"], {})
  3817. check(wait_for(lambda: task_state(auth, parked)["status"] == "failed" or False,
  3818. timeout=30, what="parked task cancelled") is not None,
  3819. "the parked task cancels cleanly after the refresh")
  3820. print("== R7 B1: cancel reaches the daemon ==")
  3821. # Plan 10 phase 2: cancellation is POST /task-update {kind: cancel}
  3822. # to the RUNNING daemon (the abort machinery, workspace kept).
  3823. task_id_tmp = create_queued(auth, {
  3824. "project_id": "1",
  3825. "title": "Cancel live",
  3826. "priority": "2",
  3827. })
  3828. cancel_live = task_id_tmp
  3829. check(wait_for(lambda: task_state(auth, cancel_live).get("status") == "working"
  3830. or False, timeout=60, what="cancel-live working") is not None,
  3831. "task reaches working before the cancel")
  3832. act(auth, task_state(auth, cancel_live)["cancel"], {})
  3833. check(wait_for(lambda: cancel_live in fake.abort_log or False,
  3834. timeout=30, what="daemon abort recorded") is not None,
  3835. "cancelling POSTs task-update cancel to the daemon")
  3836. check(any(c["body"] == "cancelled; daemon aborted"
  3837. for c in task_state(auth, cancel_live).get("comments", [])),
  3838. "the abort outcome is narrated")
  3839. check(task_state(auth, cancel_live)["status"] == "failed",
  3840. "cancelled task lands failed as before")
  3841. # A 500 on the cancel marks the saddle offline (no fence layer
  3842. # anymore); nothing dispatches to it while offline, and the
  3843. # daemon's own ask flips the row back to idle (proof of life).
  3844. task_id_tmp = create_queued(auth, {
  3845. "project_id": "1",
  3846. "title": "Fence runner",
  3847. "priority": "2",
  3848. })
  3849. fence_runner = task_id_tmp
  3850. check(wait_for(lambda: task_state(auth, fence_runner).get("status") == "working"
  3851. or False, timeout=60, what="fence runner working") is not None,
  3852. "second task reaches working")
  3853. fake.abort_failures = 1
  3854. act(auth, task_state(auth, fence_runner)["cancel"], {})
  3855. check(any(c["body"] == "cancelled; daemon unreachable — saddle marked offline"
  3856. for c in task_state(auth, fence_runner).get("comments", [])),
  3857. "failed cancel narrates the offline marking")
  3858. check(saddle_card(auth, "fake-saddle")["status"] == "offline",
  3859. "saddle marked offline after the failed cancel")
  3860. task_id_tmp = create_queued(auth, {
  3861. "project_id": "1",
  3862. "title": "During fence",
  3863. "priority": "3",
  3864. })
  3865. during_fence = task_id_tmp
  3866. # Converted sleep(7): a quiet window spanning several dispatch
  3867. # ticks in which the task MUST stay queued — if the offline
  3868. # saddle ever dispatches it, this fails loudly. The daemon is held
  3869. # mid-round for the window (the original relied on its 8s work
  3870. # period outlasting the sleep): a finishing round would ask, prove
  3871. # liveness and flip the offline row — only after the window may it.
  3872. fake.hold_state = True
  3873. check(quiet_window(quiet_seconds(),
  3874. lambda: task_state(auth, during_fence)["status"] == "queued",
  3875. "offline saddle does not dispatch during_fence"),
  3876. "offline saddle is not dispatchable")
  3877. fake.hold_state = False
  3878. # The (unaborted) daemon finishes its round, goes idle-awake and
  3879. # asks — the ask is the proof of life that flips the row back.
  3880. check(wait_for(lambda: saddle_card(auth, "fake-saddle")["status"] == "idle" or False,
  3881. timeout=30, what="ask flips offline to idle") is not None,
  3882. "the daemon's ask flips the offline row back to idle")
  3883. check(wait_task_done(auth, during_fence, timeout=60) is not None,
  3884. "queued work dispatches once the saddle proves it is alive")
  3885. print("== R7 B3: health panel + pushed raw log from the first round ==")
  3886. # A normally dispatched task pushes its chunks immediately: raw
  3887. # rows exist from the first round (the session-4 gap stays
  3888. # fixed without any probe machinery).
  3889. task_id_tmp = create_queued(auth, {
  3890. "project_id": "1",
  3891. "title": "Raw from first push",
  3892. "priority": "2",
  3893. })
  3894. raw_first = task_id_tmp
  3895. def raw_count(task_id):
  3896. conn = db()
  3897. try:
  3898. return conn.execute(
  3899. "select count(*) from session_raw_log where session_id in"
  3900. " (select id from sessions where task_id = ?)", (task_id,)).fetchone()[0]
  3901. finally:
  3902. conn.close()
  3903. check(wait_for(lambda: raw_count(raw_first) > 0 or False,
  3904. timeout=60, what="raw rows from first push") is not None,
  3905. "pushed chunks land from the first round (session-4 gap)")
  3906. check(wait_task_done(auth, raw_first, timeout=60) is not None,
  3907. "raw-first task completes")
  3908. # Health panel: a manual refresh populates the snapshot.
  3909. fake_card = saddle_card(auth, "fake-saddle")
  3910. act(auth, fake_card["refresh"], {})
  3911. card = saddle_card(auth, "fake-saddle")
  3912. check(card.get("health") in ("healthy", "stale")
  3913. and card.get("daemon_state") in ("working", "idle", "done")
  3914. and card.get("uptime_display", "") != ""
  3915. and card.get("last_contact_display", "") not in ("", "never"),
  3916. "saddles page shows daemon state, uptime and last contact")
  3917. print("== R8: pushed chunk ingestion is lossless ==")
  3918. # The daemon's opening flush: a coloured prompt run, plain text,
  3919. # a bare CRLF between prompts and the tail — every non-empty
  3920. # chunk must land, exactly once, in seq order. A mid-flight
  3921. # redelivery of the whole batch (the outbox's at-least-once
  3922. # retry) consumes the duplicates.
  3923. corpus = [
  3924. {"seq": 1, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  3925. {"seq": 2, "text": "echo hello\r\n"},
  3926. {"seq": 3, "text": "\r\n"},
  3927. {"seq": 4, "text": "hello\r\n"},
  3928. {"seq": 5, "text": "\x1b[01;32muser@host\x1b[00m:\x1b[01;34m~/task-1\x1b[00m$ "},
  3929. {"seq": 6, "text": "done\r\n"},
  3930. ]
  3931. fake.scripted_corpus = corpus
  3932. fake.hold_state = True
  3933. task_id_tmp = create_queued(auth, {
  3934. "project_id": "1",
  3935. "title": "Lossless log task",
  3936. "priority": "2",
  3937. })
  3938. lossless = task_id_tmp
  3939. def stored_seqs(task_id):
  3940. conn = db()
  3941. try:
  3942. return [r[0] for r in conn.execute(
  3943. "select seq from session_raw_log where session_id in"
  3944. " (select id from sessions where task_id = ?)"
  3945. " order by seq", (task_id,))]
  3946. finally:
  3947. conn.close()
  3948. check(wait_for(lambda: task_state(auth, lossless).get("status") == "working"
  3949. or False, timeout=60, what="lossless task working") is not None,
  3950. "lossless task dispatches and pushes its opening flush")
  3951. check(wait_for(lambda: stored_seqs(lossless) == [1, 2, 3, 4, 5, 6] or False,
  3952. timeout=30, what="all six chunks stored") is not None,
  3953. "every pushed chunk lands in session_raw_log, CRLF-only included (%s)"
  3954. % stored_seqs(lossless))
  3955. status, _ = saddle_api("POST", "/api/saddle/chunks", fake.token,
  3956. {"session_id": fake.session_id,
  3957. "chunks": [dict(chunk) for chunk in corpus]})
  3958. check(status == 200 and stored_seqs(lossless) == [1, 2, 3, 4, 5, 6],
  3959. "a full-batch redelivery stores nothing new (exactly-once)")
  3960. request = urllib.request.Request(
  3961. WEB + "/terminal-stream/%d" % [r[0] for r in db().execute(
  3962. "select id from sessions where task_id = ?", (lossless,))][0])
  3963. with urllib.request.urlopen(request, timeout=15) as stream:
  3964. texts = []
  3965. deadline = time.monotonic() + 8
  3966. while time.monotonic() < deadline and len(texts) < 6:
  3967. line = stream.readline().decode().strip()
  3968. if not line.startswith("data: ") or line == "data: ping":
  3969. continue
  3970. event = json.loads(line[6:])
  3971. if event.get("type") == "raw":
  3972. texts.append(event.get("text") or "")
  3973. check("\r\n" in texts and len(texts) == 6,
  3974. "SSE serves the whitespace chunk unfiltered")
  3975. fake.hold_state = False
  3976. fake.scripted_corpus = None
  3977. check(wait_task_done(auth, lossless, timeout=60) is not None,
  3978. "lossless task completes")
  3979. print("== R9 B1/B2: git identity + ssh key ==")
  3980. # The key travels on /status into the saddle row and the page view
  3981. # (the manual refresh's exceptional probe).
  3982. fake.ssh_public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1teStKey saddle-1@fedora"
  3983. fake_card = saddle_card(auth, "fake-saddle")
  3984. check(fake_card.get("ssh_public_key", "") == "",
  3985. "no key shown before the daemon reports one")
  3986. act(auth, fake_card["refresh"], {})
  3987. check(wait_for(lambda: "AAAAC3NzaC1lZDI1teStKey" in
  3988. saddle_card(auth, "fake-saddle").get("ssh_public_key", "") or False,
  3989. timeout=30, what="key lands on the row") is not None,
  3990. "reported ssh_public_key persists onto the saddle row")
  3991. conn = db()
  3992. row_key = conn.execute("select ssh_public_key from saddles where name = 'fake-saddle'"
  3993. ).fetchone()[0]
  3994. conn.close()
  3995. check(row_key == fake.ssh_public_key,
  3996. "the key is stored verbatim in the database")
  3997. # Identity edit flows through the UI into the assignment payload.
  3998. fake_card = saddle_card(auth, "fake-saddle")
  3999. act(auth, fake_card["update_identity"],
  4000. {"git_name": "clanker-bot", "git_email": "bot@unitatem.net"})
  4001. fake_card = saddle_card(auth, "fake-saddle")
  4002. check(fake_card.get("git_name") == "clanker-bot"
  4003. and fake_card.get("git_email") == "bot@unitatem.net",
  4004. "inline edit saves the git identity")
  4005. task_id_tmp = create_queued(auth, {
  4006. "project_id": "1",
  4007. "title": "Identity task",
  4008. "priority": "2",
  4009. })
  4010. identity_task = task_id_tmp
  4011. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == identity_task
  4012. for p in fake.start_payloads) or False,
  4013. timeout=60, what="identity task dispatched") is not None,
  4014. "identity task dispatches")
  4015. payload = [p for p in fake.start_payloads
  4016. if int(p.get("task", {}).get("id") or 0) == identity_task][-1]
  4017. identity = payload.get("git_identity") or {}
  4018. check(identity.get("name") == "clanker-bot"
  4019. and identity.get("email") == "bot@unitatem.net",
  4020. "the assignment carries the saddle's git_identity")
  4021. # Earlier assignments (identity unset) carry no git_identity member.
  4022. check(all("git_identity" not in p for p in fake.start_payloads[:-1]),
  4023. "unset identity omits the member (daemon fallback applies)")
  4024. # Clearing the identity omits it from later assignments.
  4025. fake_card = saddle_card(auth, "fake-saddle")
  4026. act(auth, fake_card["update_identity"], {"git_name": "", "git_email": ""})
  4027. check(saddle_card(auth, "fake-saddle").get("git_name", "") == "",
  4028. "clearing the identity empties the row")
  4029. check(wait_task_done(auth, identity_task, timeout=60) is not None,
  4030. "identity task completes")
  4031. print("== phase 2: blocked push -> block row + pulse ==")
  4032. # The browser flow on each pulse: statum.act(task.refresh) — the
  4033. # sealed GET action must rehydrate the task slot with the new
  4034. # block the daemon just PUSHED (state blocked + block payload).
  4035. task_id_tmp = create_queued(auth, {
  4036. "project_id": "1",
  4037. "title": "Live block task",
  4038. "priority": "2",
  4039. })
  4040. live_task = task_id_tmp
  4041. check(wait_for(lambda: task_state(auth, live_task).get("status") == "working"
  4042. or False, timeout=60, what="live task working") is not None,
  4043. "live-block task reaches working")
  4044. fake.hold_state = True
  4045. fake.state = "blocked" # the daemon parks on its question
  4046. status = fake.push_results("blocked", block={
  4047. "question": "Pick one", "type": "question", "options": ["A", "B"]})
  4048. check(status == 200, "blocked state push accepted")
  4049. # The parked daemon is idle-awake: it asks (and sleeps on 204).
  4050. fake.maybe_trigger_ask("parked")
  4051. check(wait_for(lambda: any(b.get("question") == "Pick one"
  4052. for b in task_state(auth, live_task).get("blocks", []))
  4053. or False, timeout=30, what="block lands in state") is not None,
  4054. "the pushed block reaches the sealed refresh without a reload")
  4055. detail = task_state(auth, live_task)
  4056. check(detail.get("status") == "blocked",
  4057. "the blocked push flips the task to blocked")
  4058. pushed_block = [b for b in detail["blocks"] if b.get("question") == "Pick one"][0]
  4059. conn = db()
  4060. options_json = conn.execute(
  4061. "select options from task_blocks where id = ?", (int(pushed_block["id"]),)
  4062. ).fetchone()[0]
  4063. conn.close()
  4064. check(json.loads(options_json) == ["A", "B"],
  4065. "the block row carries its options payload")
  4066. check(any(s["status"] == "idle"
  4067. for s in slot_public(auth, "/saddles", "saddles")["saddles"]),
  4068. "the blocked push parks the saddle")
  4069. detail = task_state(auth, live_task)
  4070. check(detail.get("refresh") is not None,
  4071. "the sealed GET refresh action is still authored")
  4072. status, _ = http("GET", detail["refresh"]["uri"], timeout=15)
  4073. check(status in (200, 401),
  4074. "the refresh URI resolves as a GET (client roundtrip shape)")
  4075. act(auth, pushed_block["answer_action"], {"answer": "A"})
  4076. # The answer makes the parked task resume-offerable: the affine
  4077. # saddle is woken, asks, and its assignment carries the answer.
  4078. pushes_before = len([p for p in fake.start_payloads
  4079. if int(p.get("task", {}).get("id") or 0) == live_task])
  4080. check(wait_for(lambda: len([p for p in fake.start_payloads
  4081. if int(p.get("task", {}).get("id") or 0) == live_task])
  4082. > pushes_before or False, timeout=60,
  4083. what="blocked task resumes") is not None,
  4084. "answering the pushed block resumes the parked workspace")
  4085. fake.hold_state = False # the resumed round runs to completion
  4086. resume_payload = [p for p in fake.start_payloads
  4087. if int(p.get("task", {}).get("id") or 0) == live_task][-1]
  4088. answers = resume_payload.get("task", {}).get("answers", [])
  4089. check(any(a.get("answer") == "A" for a in answers),
  4090. "the resume assignment carries the human's answer")
  4091. check(wait_task_done(auth, live_task, timeout=60) is not None,
  4092. "live-block task completes after answering")
  4093. print("== R2: the one release path behind unregister ==")
  4094. # Arch 13: removing a saddle releases its held task through the
  4095. # same owner as every requeue — never an orphan open session on a
  4096. # deleted row. Route 1: a DEAD host — the abort delivery fails
  4097. # fast, the offline bookkeeping releases (queued + comment +
  4098. # session 'stopped'), the unregister then deletes the row.
  4099. saddles_state = slot_public(auth, "/saddles", "saddles")
  4100. act(auth, saddles_state["register"], {"name": "dead-host",
  4101. "host": "127.0.0.1:1"})
  4102. dead_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  4103. if s["name"] == "dead-host"][0]
  4104. dead_id = int(dead_card["id"])
  4105. task_id_tmp = create_queued(auth, {
  4106. "project_id": "1",
  4107. "title": "Dead-host unregister task",
  4108. "priority": "2",
  4109. })
  4110. dead_task = task_id_tmp
  4111. conn = db()
  4112. conn.execute("update tasks set status = 'working' where id = ?",
  4113. (dead_task,))
  4114. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  4115. " values (?, ?, strftime('%s','now'))", (dead_task, dead_id))
  4116. conn.execute("update saddles set current_task_id = ? where id = ?",
  4117. (dead_task, dead_id))
  4118. conn.commit()
  4119. dead_session = conn.execute(
  4120. "select id from sessions where task_id = ? and ended_at is null",
  4121. (dead_task,)).fetchone()[0]
  4122. conn.close()
  4123. act(auth, dead_card["unregister"], {})
  4124. conn = db()
  4125. dead_row = conn.execute("select status from tasks where id = ?",
  4126. (dead_task,)).fetchone()
  4127. dead_session_row = conn.execute(
  4128. "select outcome, ended_at is not null from sessions where id = ?",
  4129. (dead_session,)).fetchone()
  4130. dead_saddle_count = conn.execute(
  4131. "select count(*) from saddles where id = ?", (dead_id,)).fetchone()[0]
  4132. conn.close()
  4133. check(dead_row is not None and dead_row[0] == "queued",
  4134. "unregister of a dead-host saddle releases the held task to the queue")
  4135. check(dead_session_row is not None and dead_session_row[0] == "stopped"
  4136. and dead_session_row[1],
  4137. "the offline release closes the held task's session 'stopped'")
  4138. check(dead_saddle_count == 0, "the dead-host saddle row is gone")
  4139. # Route 2: no open session on the saddle — the abort is a no-op
  4140. # and the unregister itself carries the release (the requeue flip
  4141. # through the one owner, the row deleted after).
  4142. saddles_state = slot_public(auth, "/saddles", "saddles")
  4143. act(auth, saddles_state["register"], {"name": "quiet-host",
  4144. "host": "127.0.0.1:%d" % fake.port})
  4145. quiet_card = [s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  4146. if s["name"] == "quiet-host"][0]
  4147. quiet_id = int(quiet_card["id"])
  4148. task_id_tmp = create_queued(auth, {
  4149. "project_id": "1",
  4150. "title": "Quiet-host unregister task",
  4151. "priority": "2",
  4152. })
  4153. quiet_task = task_id_tmp
  4154. conn = db()
  4155. conn.execute("update tasks set status = 'working' where id = ?",
  4156. (quiet_task,))
  4157. conn.execute("update saddles set current_task_id = ? where id = ?",
  4158. (quiet_task, quiet_id))
  4159. conn.commit()
  4160. conn.close()
  4161. act(auth, quiet_card["unregister"], {})
  4162. conn = db()
  4163. quiet_row = conn.execute("select status from tasks where id = ?",
  4164. (quiet_task,)).fetchone()
  4165. quiet_saddle_count = conn.execute(
  4166. "select count(*) from saddles where id = ?", (quiet_id,)).fetchone()[0]
  4167. conn.close()
  4168. check(quiet_row is not None and quiet_row[0] == "queued",
  4169. "unregister's own release returns the held task to the queue")
  4170. check(quiet_saddle_count == 0, "the quiet-host saddle row is gone")
  4171. # =============================================================================
  4172. # Bundle: answers — the answer-resume machinery in both daemon shapes
  4173. # (sleeping affine wake, mid-round verdict delivery), offline requeue
  4174. # keeping parked-with-answered tasks, the staleness probe, and the
  4175. # startup token migration (this shard's one deliberate app restart).
  4176. # =============================================================================
  4177. def bundle_answers(ctx):
  4178. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4179. app = ctx.app
  4180. print("== phase 2: answer resume — wake -> ask -> affinity claim ==")
  4181. # The full live sequence against a daemon that asks after its
  4182. # park: ask -> assignment -> blocked push (park) -> ask -> 204
  4183. # -> sleeps (row idle) -> human answers -> the dispatcher WAKES
  4184. # the sleeping affine saddle -> its ask allocates the resume,
  4185. # the verdict riding the assignment -> the session continues.
  4186. # A private capability tag keeps the fleet's other sleeping
  4187. # saddles from claiming these tasks.
  4188. saddles_state = slot_public(auth, "/saddles", "saddles")
  4189. act(auth, saddles_state["create_capability"], {"name": "answerflow"})
  4190. answerflow_cap = int([c["id"] for c in slot_public(auth, "/saddles", "saddles")["capabilities"]
  4191. if c["name"] == "answerflow"][0])
  4192. def answerflow_daemon(**kwargs):
  4193. daemon = FakeSaddle()
  4194. daemon.ask_on_register = False # manual, deterministic asks
  4195. daemon.hold_state = True # the tests drive the lifecycle
  4196. for key, value in kwargs.items():
  4197. setattr(daemon, key, value)
  4198. daemon.serve()
  4199. return daemon
  4200. def register_answerflow(daemon, name):
  4201. act(auth, slot_public(auth, "/saddles", "saddles")["register"], {
  4202. "name": name, "host": "127.0.0.1:%d" % daemon.port})
  4203. act(auth, saddle_card(auth, name)["attach_capability"],
  4204. {"capability_id": str(answerflow_cap)})
  4205. def create_answerflow_task(title):
  4206. return create_queued(auth, {
  4207. "project_id": "1", "title": title, "priority": "2",
  4208. "capability_id": [str(answerflow_cap)]})
  4209. def retire_daemon(daemon, name):
  4210. # deterministic teardown: a dead daemon and an offline row
  4211. # never interfere with the sections that follow
  4212. daemon.kill()
  4213. act(auth, saddle_card(auth, name)["refresh"], {})
  4214. sleeper = answerflow_daemon(ask_on_wake=True)
  4215. register_answerflow(sleeper, "resume-sleeper")
  4216. sleeping_task = create_answerflow_task("Sleeping resume task")
  4217. ask_status, assignment = sleeper.ask_now()
  4218. check(ask_status == 200 and int(assignment["task"]["id"]) == sleeping_task,
  4219. "the daemon's ask claims the queued task")
  4220. sleeping_session = assignment.get("session_id")
  4221. sleeper.state = "blocked"
  4222. check(sleeper.push_results("blocked", block={
  4223. "question": "Pick a side", "type": "question",
  4224. "options": ["Port", "Starboard"]}) == 200,
  4225. "the blocked push parks the session")
  4226. check(wait_for(lambda: task_state(auth, sleeping_task).get("status") == "blocked"
  4227. or False, timeout=30, what="sleeping task parked") is not None,
  4228. "the task parks as blocked")
  4229. check(saddle_card(auth, "resume-sleeper")["status"] == "idle",
  4230. "the parked session's saddle row reads idle")
  4231. ask_status, _ = sleeper.ask_now()
  4232. check(ask_status == 204,
  4233. "the parked daemon's ask returns 204 — it sleeps until woken")
  4234. # Converted sleep(3): ticks pass with the daemon asleep and no
  4235. # wake may arrive — a wake during the window fails loudly.
  4236. check(quiet_window(quiet_seconds(),
  4237. lambda: len(sleeper.wake_log) == 0,
  4238. "sleeping daemon never woken"),
  4239. "the sleeping daemon is never woken while the block waits")
  4240. detail = task_state(auth, sleeping_task)
  4241. side_block = [b for b in detail["blocks"] if b["question"] == "Pick a side"][0]
  4242. act(auth, side_block["answer_action"], {"option": "Starboard"})
  4243. check(wait_for(lambda: len(sleeper.wake_log) > 0 or False,
  4244. timeout=30, what="wake after the answer") is not None,
  4245. "answering the block wakes the sleeping affine saddle")
  4246. # Answering = allocating (plan 11): the resume assignment carries
  4247. # the verdict as resume_notice (stable wording) AND a FRESH
  4248. # session id — the parked row closed, the daemon keys its resumed
  4249. # pushes on the new one.
  4250. check(wait_for(lambda: any(
  4251. int(p.get("task", {}).get("id") or 0) == sleeping_task
  4252. and p.get("session_id") != sleeping_session
  4253. and p.get("resume_notice") == "Human selected: Starboard"
  4254. and any(a.get("answer") == "Starboard"
  4255. for a in p.get("task", {}).get("answers", []))
  4256. for p in sleeper.start_payloads[1:]) or False,
  4257. timeout=30, what="resume allocation carries the verdict") is not None,
  4258. "the woken daemon's ask allocates the resume — fresh session, notice carried")
  4259. # Barrier: the resume's own working push must commit before the
  4260. # manual done push (a late working write would otherwise race the
  4261. # completion's full-row write).
  4262. check(wait_for(lambda: task_state(auth, sleeping_task).get("status") == "working"
  4263. or False, timeout=15, what="resumed round working") is not None,
  4264. "the resumed round reports working before its completion push")
  4265. # The resumed round runs to completion keyed on the fresh session.
  4266. sleeper.push_results("done", summary="sleep-resumed round complete")
  4267. check(wait_task_done(auth, sleeping_task, timeout=30) is not None,
  4268. "the resumed session continues to completion")
  4269. conn = db()
  4270. rows = conn.execute(
  4271. "select id, outcome, ended_at is not null from sessions where task_id = ?"
  4272. " order by id", (sleeping_task,)).fetchall()
  4273. conn.close()
  4274. check(len(rows) == 2 and rows[0][1] == "resumed" and rows[0][2]
  4275. and rows[1][1] == "done" and rows[1][2],
  4276. "parked session closed 'resumed'; the resumed round ran on a fresh row to done (%s)"
  4277. % (rows,))
  4278. retire_daemon(sleeper, "resume-sleeper")
  4279. print("== phase 2: answer resume — the parked daemon is woken (POST /answer retired) ==")
  4280. # Post Task A every park FREES the daemon: after the blocked push
  4281. # it lands idle and asks (204). The retired POST /answer channel
  4282. # always refuses; the verdict reaches the parked workspace purely
  4283. # through the wake -> ask -> affinity allocation carrying the
  4284. # resume_notice + a fresh session id.
  4285. parked = answerflow_daemon(ask_on_wake=True,
  4286. ask_on_terminal=False)
  4287. register_answerflow(parked, "resume-parked")
  4288. parked_task = create_answerflow_task("Parked resume task")
  4289. ask_status, assignment = parked.ask_now()
  4290. check(ask_status == 200 and int(assignment["task"]["id"]) == parked_task,
  4291. "the daemon's ask claims the task")
  4292. parked_session = assignment.get("session_id")
  4293. parked.state = "blocked"
  4294. check(parked.push_results("blocked", block={
  4295. "question": "Which database?", "type": "question",
  4296. "options": ["SQLite", "Postgres"]}) == 200,
  4297. "the blocked push parks the session mid-round")
  4298. check(wait_for(lambda: task_state(auth, parked_task).get("status") == "blocked"
  4299. or False, timeout=30, what="parked task blocked") is not None,
  4300. "the task parks as blocked")
  4301. check(saddle_card(auth, "resume-parked")["status"] == "idle",
  4302. "the parked session's saddle row reads idle")
  4303. # The freed daemon re-asks (its idle loop) and sleeps on 204.
  4304. ask_status, _ = parked.ask_now()
  4305. check(ask_status == 204,
  4306. "the freed parked daemon asks again and sleeps (204)")
  4307. # The retired channel always refuses — the web never depends on it.
  4308. request = urllib.request.Request(
  4309. "http://127.0.0.1:%d/answer" % parked.port,
  4310. data=json.dumps({"answer": "SQLite", "branch_advanced": False}).encode(),
  4311. method="POST")
  4312. request.add_header("Content-Type", "application/json")
  4313. try:
  4314. urllib.request.urlopen(request, timeout=5)
  4315. refused = False
  4316. except urllib.error.HTTPError as error:
  4317. refused = error.code == 409
  4318. check(refused, "POST /answer always refuses (409) — parks resume via allocation")
  4319. detail = task_state(auth, parked_task)
  4320. db_block = [b for b in detail["blocks"] if b["question"] == "Which database?"][0]
  4321. # branch_advanced on the resume assignment (the /poll verdict
  4322. # channel's hint lives here now): a sibling on the same shared
  4323. # working branch completed strictly after the block's park marker
  4324. # — the resumed allocation must report branch_advanced=true so the
  4325. # daemon knows to pull before continuing.
  4326. conn = db()
  4327. parked_block_created = conn.execute(
  4328. "select created_at from task_blocks where id = ?", (db_block["id"],)
  4329. ).fetchone()[0]
  4330. conn.execute("update tasks set task_branch = 'shared/resume-branch'"
  4331. " where id = ?", (parked_task,))
  4332. conn.commit()
  4333. conn.close()
  4334. wait_for(lambda: int(time.time()) > parked_block_created or False,
  4335. timeout=3, what="next clock second past the park marker")
  4336. conn = db()
  4337. conn.execute("insert into tasks (project_id, title, status, priority,"
  4338. " task_branch, summary, completed_at, created_at)"
  4339. " values (1, 'Resume sibling', 'done', 5, 'shared/resume-branch',"
  4340. " 'sibling finished', strftime('%s','now'),"
  4341. " strftime('%s','now','-300 seconds'))")
  4342. conn.commit()
  4343. conn.close()
  4344. act(auth, db_block["answer_action"], {"option": "SQLite"})
  4345. check(wait_for(lambda: len(parked.wake_log) > 0 or False,
  4346. timeout=30, what="wake after the answer") is not None,
  4347. "answering the block wakes the parked (idle) affine saddle")
  4348. check(wait_for(lambda: any(
  4349. int(p.get("task", {}).get("id") or 0) == parked_task
  4350. and p.get("session_id") != parked_session
  4351. and p.get("resume_notice") == "Human selected: SQLite"
  4352. and p.get("branch_advanced") is True
  4353. for p in parked.start_payloads[1:]) or False,
  4354. timeout=30, what="parked resume allocation") is not None,
  4355. "the parked daemon's ask allocates the resume — fresh session, formatted notice,"
  4356. " branch_advanced=true after the sibling's completion")
  4357. # The hold_state daemon drives its round manually: the resumed
  4358. # round completes on the fresh session row.
  4359. parked.push_results("done", summary="parked round resumed and finished")
  4360. check(wait_task_done(auth, parked_task, timeout=90) is not None,
  4361. "the parked session continues to completion")
  4362. conn = db()
  4363. row = conn.execute("select outcome from sessions where id = ?",
  4364. (parked_session,)).fetchone()
  4365. session_rows = conn.execute(
  4366. "select id, outcome from sessions where task_id = ? order by id",
  4367. (parked_task,)).fetchall()
  4368. conn.close()
  4369. check(row is not None and row[0] == "resumed"
  4370. and len(session_rows) == 2 and session_rows[0] == (parked_session, "resumed"),
  4371. "the parked session closed 'resumed' and the resumed round kept its own row (%s)"
  4372. % (session_rows,))
  4373. retire_daemon(parked, "resume-parked")
  4374. print("== plan 11: plan acceptance — accept / reject / auto-approve ==")
  4375. # A type 'plan' block parks like any other; Accept and
  4376. # Reject-with-feedback drive the same wake -> ask -> allocation
  4377. # resume as any verdict, the stable wording riding the
  4378. # resume_notice. Plan 12: the daemon only SENDS plan blocks on
  4379. # goal runs now (the goal page owns the review); this covers the
  4380. # generic verdict path a goal-run's mirrored block also uses. The
  4381. # auto-approve option is gone.
  4382. planner = answerflow_daemon(ask_on_wake=True, ask_on_terminal=False)
  4383. register_answerflow(planner, "plan-planner")
  4384. def park_on_plan(task_id, markdown):
  4385. planner.state = "blocked"
  4386. check(planner.push_results("blocked", block={
  4387. "question": "Plan submitted for review", "type": "plan",
  4388. "body": markdown}) == 200,
  4389. "the plan push parks the session")
  4390. # Wait for the block row itself (the auto-approve variant is
  4391. # answered — and may resume — before any status poll lands).
  4392. check(wait_for(lambda: any(b["block_type"] == "plan"
  4393. for b in task_state(auth, task_id)["blocks"])
  4394. or False, timeout=30, what="plan block raised") is not None,
  4395. "the plan block reaches the task")
  4396. return [b for b in task_state(auth, task_id)["blocks"]
  4397. if b["block_type"] == "plan"][0]
  4398. # (a) Accept resumes with the approval notice.
  4399. accept_task = create_answerflow_task("Plan accept task")
  4400. ask_status, accept_assignment = planner.ask_now()
  4401. check(ask_status == 200 and int(accept_assignment["task"]["id"]) == accept_task,
  4402. "the planner claims the accept task")
  4403. accept_parked_session = accept_assignment.get("session_id")
  4404. plan_block = park_on_plan(accept_task, "# Steps\n\n1. Wire\n2. Test")
  4405. check(plan_block.get("answered") is not True,
  4406. "the plan block waits for a human verdict")
  4407. # Plan 16 S2: the accept form posts the verdict marker; the server
  4408. # builds the stable constant (byte-identical wire).
  4409. act(auth, plan_block["answer_action"], {"verdict": "accept"})
  4410. check(wait_for(lambda: any(
  4411. int(p.get("task", {}).get("id") or 0) == accept_task
  4412. and p.get("session_id") != accept_parked_session
  4413. and p.get("resume_notice") == "Plan approved. Proceed with implementation."
  4414. for p in planner.start_payloads[1:]) or False,
  4415. timeout=30, what="accept resume allocation") is not None,
  4416. "accept resumes the parked daemon with the approval notice")
  4417. planner.push_results("done", summary="plan accepted and implemented")
  4418. check(wait_task_done(auth, accept_task, timeout=60) is not None,
  4419. "the accepted plan's task completes")
  4420. planner.set_state("idle")
  4421. # (b) Reject-with-feedback loops the feedback notice back.
  4422. reject_task = create_answerflow_task("Plan reject task")
  4423. ask_status, reject_assignment = planner.ask_now()
  4424. check(ask_status == 200 and int(reject_assignment["task"]["id"]) == reject_task,
  4425. "the planner claims the reject task")
  4426. reject_parked_session = reject_assignment.get("session_id")
  4427. plan_block = park_on_plan(reject_task, "# Draft\n\nJust wing it")
  4428. act(auth, plan_block["answer_action"], {"feedback": "Add a test section"})
  4429. reject_block = [b for b in task_state(auth, reject_task)["blocks"]
  4430. if b["block_type"] == "plan"][0]
  4431. check(reject_block.get("answer")
  4432. == "Plan feedback received:\nAdd a test section",
  4433. "reject stores the feedback in the stable wording (%s)"
  4434. % reject_block.get("answer"))
  4435. check(wait_for(lambda: any(
  4436. int(p.get("task", {}).get("id") or 0) == reject_task
  4437. and p.get("session_id") != reject_parked_session
  4438. and p.get("resume_notice") == "Plan feedback received:\nAdd a test section"
  4439. for p in planner.start_payloads[1:]) or False,
  4440. timeout=30, what="reject resume allocation") is not None,
  4441. "reject resumes the parked daemon with the feedback notice")
  4442. planner.push_results("done", summary="plan revised and delivered")
  4443. check(wait_task_done(auth, reject_task, timeout=60) is not None,
  4444. "the revised plan's task completes")
  4445. planner.set_state("idle")
  4446. retire_daemon(planner, "plan-planner")
  4447. print("== phase 2: offline requeue keeps parked-with-answered tasks ==")
  4448. # A daemon dying while its parked task carries an answered
  4449. # verdict: going offline must not requeue the task or close its
  4450. # session — the resume machinery (delivery once the daemon
  4451. # returns, or the affinity allocation on its next ask) needs
  4452. # both. The question park leaves the row idle; the review park
  4453. # keeps it busy@task (`saddle review` blocks the round without
  4454. # a parking state push), exercising the unreachable path's
  4455. # requeue decision both ways.
  4456. stranded = answerflow_daemon()
  4457. register_answerflow(stranded, "resume-stranded")
  4458. stranded_task = create_answerflow_task("Stranded answered task")
  4459. ask_status, _ = stranded.ask_now()
  4460. check(ask_status == 200, "the stranded daemon claims its task")
  4461. stranded.state = "blocked"
  4462. stranded.push_results("blocked", block={
  4463. "question": "Hold or fold?", "type": "question", "options": ["Hold", "Fold"]})
  4464. check(wait_for(lambda: task_state(auth, stranded_task).get("status") == "blocked"
  4465. or False, timeout=30, what="stranded task parked") is not None,
  4466. "the stranded task parks as blocked")
  4467. detail = task_state(auth, stranded_task)
  4468. hold_block = [b for b in detail["blocks"] if b["question"] == "Hold or fold?"][0]
  4469. act(auth, hold_block["answer_action"], {"option": "Hold"})
  4470. stranded.kill() # the daemon dies before the verdict is delivered
  4471. act(auth, saddle_card(auth, "resume-stranded")["refresh"], {})
  4472. check(wait_for(lambda: saddle_card(auth, "resume-stranded")["status"] == "offline"
  4473. or False, timeout=30, what="stranded saddle offline") is not None,
  4474. "the dead daemon's saddle row goes offline")
  4475. # Converted sleep(7): offline ticks run while the task MUST stay
  4476. # parked — a requeue during the window fails loudly.
  4477. check(quiet_window(quiet_seconds(),
  4478. lambda: task_state(auth, stranded_task)["status"] == "blocked",
  4479. "stranded task not requeued"),
  4480. "the parked-with-answered task is not requeued by the offline pass")
  4481. conn = db()
  4482. open_session = conn.execute(
  4483. "select count(*) from sessions where task_id = ? and ended_at is null",
  4484. (stranded_task,)).fetchone()[0]
  4485. conn.close()
  4486. check(open_session == 1,
  4487. "the parked-with-answered task keeps its open session for the resume")
  4488. reviewer = answerflow_daemon(ask_on_terminal=False)
  4489. register_answerflow(reviewer, "resume-reviewer")
  4490. review_task = create_answerflow_task("Review park task")
  4491. ask_status, _ = reviewer.ask_now()
  4492. check(ask_status == 200, "the reviewer claims its task")
  4493. # Post Task A the review park frees the daemon: the blocked push
  4494. # carries the review block and parks the row idle.
  4495. reviewer.state = "blocked"
  4496. check(reviewer.push_results("blocked", block={
  4497. "question": "Review requested", "type": "review",
  4498. "body": "Ready for review: wired and tested."}) == 200,
  4499. "the review park push carries the review block")
  4500. check(wait_for(lambda: task_state(auth, review_task).get("status") == "review_requested"
  4501. or False, timeout=30, what="review park raised") is not None,
  4502. "the review block parks the task as review_requested (row freed)")
  4503. # The verdict lands (nothing delivers it anymore); THEN the daemon
  4504. # dies and the manual refresh offlines it — the parked-with-answered
  4505. # task must keep its session for the eventual resume.
  4506. detail = task_state(auth, review_task)
  4507. verdict_block = [b for b in detail["blocks"]
  4508. if b["block_type"] == "review"][0]
  4509. act(auth, verdict_block["answer_action"], {"verdict": "accept"})
  4510. reviewer.kill()
  4511. act(auth, saddle_card(auth, "resume-reviewer")["refresh"], {})
  4512. check(wait_for(lambda: saddle_card(auth, "resume-reviewer")["status"] == "offline"
  4513. or False, timeout=30, what="reviewer offline") is not None,
  4514. "the dead reviewer goes offline on the failed probe")
  4515. # Converted sleep(7): offline ticks run while the task MUST stay
  4516. # review-parked — a requeue during the window fails loudly.
  4517. check(quiet_window(quiet_seconds(),
  4518. lambda: task_state(auth, review_task)["status"] == "review_requested",
  4519. "review-parked task not requeued"),
  4520. "the review-parked task with an answered verdict is never requeued")
  4521. conn = db()
  4522. open_session = conn.execute(
  4523. "select count(*) from sessions where task_id = ? and ended_at is null",
  4524. (review_task,)).fetchone()[0]
  4525. conn.close()
  4526. check(open_session == 1,
  4527. "the review-parked task keeps its open session for the resume")
  4528. print("== phase 2: staleness — one probe decides ==")
  4529. # A silent-but-alive runner (long think, nothing to flush): after
  4530. # SADDLE_STALE_S (3s here) of silence it owes ONE exceptional
  4531. # GET /status; the answer keeps it running and the silence
  4532. # episode gets no second probe.
  4533. task_id_tmp = create_queued(auth, {
  4534. "project_id": "1",
  4535. "title": "Silent thinker",
  4536. "priority": "2",
  4537. })
  4538. thinker = task_id_tmp
  4539. check(wait_for(lambda: task_state(auth, thinker).get("status") == "working"
  4540. or False, timeout=60, what="thinker working") is not None,
  4541. "silent thinker reaches working")
  4542. fake.silent = True # the daemon goes quiet mid-round (alive)
  4543. probes_at_start = fake.status_hits
  4544. check(wait_for(lambda: fake.status_hits > probes_at_start or False,
  4545. timeout=30, what="exceptional probe arrives") is not None,
  4546. "a silent runner gets its exceptional GET /status probe")
  4547. # Converted sleep(8)+sleep(6): a quiet window across several
  4548. # ticks in which the probe count MUST NOT move — a second probe
  4549. # (the poll drumbeat this guards against) fails loudly.
  4550. second_window = fake.status_hits
  4551. check(quiet_window(quiet_seconds(),
  4552. lambda: fake.status_hits == second_window,
  4553. "no second staleness probe"),
  4554. "the silence episode is probed exactly once (no poll drumbeat)")
  4555. check(task_state(auth, thinker).get("status") == "working"
  4556. and saddle_card(auth, "fake-saddle")["status"] == "busy",
  4557. "the answered probe keeps the task running (no requeue)")
  4558. # Output flows again: the episode ends, the clock resets.
  4559. fake.silent = False
  4560. fake.push_chunks(["resumed output\r\n"])
  4561. check(wait_task_done(auth, thinker, timeout=60) is not None,
  4562. "the silent thinker completes once output flows again")
  4563. # The daemon vanishing mid-task: silence for the window, the
  4564. # probe fails, the task requeues with an agent comment and the
  4565. # saddle goes offline.
  4566. task_id_tmp = create_queued(auth, {
  4567. "project_id": "1",
  4568. "title": "Vanish victim",
  4569. "priority": "2",
  4570. })
  4571. vanish = task_id_tmp
  4572. check(wait_for(lambda: task_state(auth, vanish).get("status") == "working"
  4573. or False, timeout=60, what="vanish victim working") is not None,
  4574. "vanish victim reaches working")
  4575. fake.kill()
  4576. check(wait_for(lambda: saddle_card(auth, "fake-saddle")["status"] == "offline" or False,
  4577. timeout=60, what="daemon death -> offline") is not None,
  4578. "vanishing daemon drives the saddle offline (failed staleness probe)")
  4579. check(wait_for(lambda: any("unreachable" in c["body"]
  4580. and c.get("is_system")
  4581. for c in task_state(auth, vanish).get("comments", []))
  4582. or False, timeout=30, what="unreachable comment") is not None,
  4583. "the affected task gets an unreachable system row (never an agent comment)")
  4584. check(task_state(auth, vanish)["status"] == "queued",
  4585. "the task requeues after the daemon death")
  4586. card = saddle_card(auth, "fake-saddle")
  4587. check(card.get("health") == "offline",
  4588. "health badge reports offline")
  4589. # The unreachable row flag marks the detection window: a task the
  4590. # web still sees working while its saddle is offline/fenced, before
  4591. # the requeue pass moves it. Controlled window (the real
  4592. # transitions above are atomic with their requeues).
  4593. conn = db()
  4594. conn.execute("insert into tasks (project_id, title, status, priority,"
  4595. " created_at) values (1, 'Unreachable row', 'working', 5,"
  4596. " strftime('%s','now'))")
  4597. unreachable_row = conn.execute("select max(id) from tasks").fetchone()[0]
  4598. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  4599. " values (?, ?, strftime('%s','now'))", (unreachable_row, fake_id))
  4600. conn.commit()
  4601. conn.close()
  4602. check(wait_for(lambda: (lambda row: row.get("unreachable") is True)(
  4603. [t for t in slot_public(auth, "/tasks", "tasks")["tasks"]
  4604. if int(t["id"]) == unreachable_row][0]) or False,
  4605. timeout=20, what="unreachable flag") is not None,
  4606. "queue row shows the unreachable state in the window")
  4607. print("== phase 1: startup migrates the per-saddle token ==")
  4608. # Saddles registered before the flip hold legacy api_tokens rows.
  4609. # On startup every saddle row gets its canonical token: the
  4610. # legacy value it already holds (daemons keep their credential)
  4611. # or a freshly minted one. Fixture: this shard's own racer.
  4612. fake2 = FakeSaddle()
  4613. fake2.ask_on_register = False
  4614. fake2.serve(port=free_port())
  4615. saddles_state = slot_public(auth, "/saddles", "saddles")
  4616. act(auth, saddles_state["register"], {"name": "racer-two",
  4617. "host": "127.0.0.1:%d" % fake2.port})
  4618. racer_two_id = int([s for s in slot_public(auth, "/saddles", "saddles")["saddles"]
  4619. if s["name"] == "racer-two"][0]["id"])
  4620. conn = db()
  4621. conn.execute("insert into api_tokens (saddle_id, token, created_at)"
  4622. " values (?, 'saddle-legacy-copied-token', strftime('%s','now'))",
  4623. (racer_two_id,))
  4624. conn.execute("update saddles set token = null where name = 'racer-two'")
  4625. conn.execute("insert into saddles (name, host, status, current_task_id)"
  4626. " values ('tokenless-orphan', '127.0.0.1:1', 'offline', 0)")
  4627. conn.commit()
  4628. conn.close()
  4629. app.terminate()
  4630. app.wait(timeout=10)
  4631. app = start_app()
  4632. auth = login("admin", "adminpass123")
  4633. ctx.app = app # teardown tracks the restarted process
  4634. ctx.auth = auth
  4635. def saddle_row(name):
  4636. conn = db()
  4637. try:
  4638. return conn.execute("select id, token from saddles where name = ?",
  4639. (name,)).fetchone()
  4640. finally:
  4641. conn.close()
  4642. check(wait_for(lambda: saddle_row("tokenless-orphan") is not None
  4643. and (saddle_row("tokenless-orphan")[1] or "").startswith("saddle-")
  4644. or False, timeout=20, what="tokenless row minted") is not None,
  4645. "startup mints a token for a saddle row without one")
  4646. check(wait_for(lambda: saddle_row("racer-two") is not None
  4647. and saddle_row("racer-two")[1] == "saddle-legacy-copied-token"
  4648. or False, timeout=20, what="legacy token copied") is not None,
  4649. "startup copies the legacy api_tokens value onto the row")
  4650. fake2.token = "saddle-legacy-copied-token" # the daemon asks with it
  4651. status, _ = saddle_api("POST", "/api/saddle/next-task", "saddle-legacy-copied-token")
  4652. check(status in (200, 204),
  4653. "the legacy token still authenticates (copied, not replaced)")
  4654. conn = db()
  4655. conn.execute("delete from saddles where name = 'tokenless-orphan'")
  4656. conn.commit()
  4657. conn.close()
  4658. # The restart wiped the in-memory ask bookkeeping; the fleet's
  4659. # daemons re-establish sleeping with a fresh ask each (the real
  4660. # daemons' idle-awake ask / 15-minute safety self-ask).
  4661. for daemon in (fake2,):
  4662. daemon.ask_now()
  4663. check(True, "fleet re-asks after the restart (sleeping re-established)")
  4664. # =============================================================================
  4665. # Bundle: push — plan 11 task E: real Web Push over VAPID. VAPID
  4666. # persistence, the service worker, subscription CRUD + validation,
  4667. # notify-me prefs, the block/lifecycle dispatch matrix (global vs
  4668. # opted-in), 410 pruning, retry-next-tick delivery and protocol-level
  4669. # payload verification (RFC 8291 decryption + ES256 JWT) against the
  4670. # fake push service.
  4671. # =============================================================================
  4672. def bundle_push(ctx):
  4673. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  4674. def subscription_count(endpoint):
  4675. conn = db()
  4676. try:
  4677. return conn.execute(
  4678. "select count(*) from push_subscriptions where endpoint = ?",
  4679. (endpoint,)).fetchone()[0]
  4680. finally:
  4681. conn.close()
  4682. print("== task E: service worker asset ==")
  4683. status, sw = http("GET", "/sw.js", timeout=15)
  4684. check(status == 200 and "addEventListener('push'" in sw
  4685. and "notificationclick" in sw and "clients.openWindow" in sw,
  4686. "the service worker serves at the origin root with push + click routing")
  4687. print("== task E: VAPID keypair generation + persistence ==")
  4688. config = json.load(open(os.path.join(WORK, "web-config.json")))
  4689. vapid = config.get("vapid") or {}
  4690. check(bool(vapid.get("public_key")) and bool(vapid.get("private_key")),
  4691. "the VAPID keypair persists into web-config.json's vapid section")
  4692. vapid_private_key = ec.derive_private_key(
  4693. int.from_bytes(b64url_dec(vapid["private_key"]), "big"), ec.SECP256R1())
  4694. derived_public = vapid_private_key.public_key().public_bytes(
  4695. Encoding.X962, PublicFormat.UncompressedPoint)
  4696. check(b64url_dec(vapid["public_key"]) == derived_public,
  4697. "the persisted public key matches the private scalar (a valid P-256 pair)")
  4698. dash = slot_public(auth, "/", "dashboard")
  4699. check(dash.get("push_vapid_key") == vapid["public_key"],
  4700. "the dashboard exposes the same VAPID key to subscribers")
  4701. check(dash.get("push_subscribed") is False and bool(dash.get("push_subscribe")),
  4702. "the bell starts unsubscribed and carries the subscribe action")
  4703. print("== task E: subscription CRUD + auth validation ==")
  4704. browser = ec.generate_private_key(ec.SECP256R1())
  4705. browser_public = browser.public_key().public_bytes(
  4706. Encoding.X962, PublicFormat.UncompressedPoint)
  4707. browser_auth = os.urandom(16)
  4708. subscribe_fields = {"p256dh": b64url(browser_public), "auth": b64url(browser_auth)}
  4709. valid_endpoint = "http://127.0.0.1:1/x"
  4710. check("absolute http(s)" in (action_notify(act(auth, dash["push_subscribe"],
  4711. {"endpoint": "ftp://example.com/push", **subscribe_fields})) or ""),
  4712. "a non-http endpoint is rejected")
  4713. check("p256dh" in (action_notify(act(auth, dash["push_subscribe"],
  4714. {"endpoint": valid_endpoint, "p256dh": b64url(os.urandom(64)),
  4715. "auth": subscribe_fields["auth"]})) or ""),
  4716. "a malformed p256dh point is rejected")
  4717. check("auth" in (action_notify(act(auth, dash["push_subscribe"],
  4718. {"endpoint": valid_endpoint, "p256dh": subscribe_fields["p256dh"],
  4719. "auth": b64url(os.urandom(15))})) or ""),
  4720. "a malformed auth secret is rejected")
  4721. push = FakePushService()
  4722. push.serve()
  4723. endpoint_main = push.url("/main")
  4724. act(auth, dash["push_subscribe"],
  4725. {"endpoint": endpoint_main, **subscribe_fields})
  4726. conn = db()
  4727. rows = conn.execute("select user_id, p256dh, auth from push_subscriptions"
  4728. " where endpoint = ?", (endpoint_main,)).fetchall()
  4729. admin_id = conn.execute("select id from spry_users where username = 'admin'"
  4730. ).fetchone()[0]
  4731. conn.close()
  4732. check(len(rows) == 1 and rows[0][0] == admin_id,
  4733. "a valid subscription stores against the signed-in user")
  4734. # Re-subscribing the same endpoint replaces (never duplicates).
  4735. rotated_auth = os.urandom(16)
  4736. act(auth, dash["push_subscribe"],
  4737. {"endpoint": endpoint_main, "p256dh": subscribe_fields["p256dh"],
  4738. "auth": b64url(rotated_auth)})
  4739. conn = db()
  4740. rows = conn.execute("select auth from push_subscriptions where endpoint = ?",
  4741. (endpoint_main,)).fetchall()
  4742. conn.close()
  4743. check(len(rows) == 1 and rows[0][0] == b64url(rotated_auth),
  4744. "re-subscribing an endpoint replaces its keys in place")
  4745. print("== task E: notify-me pref persistence ==")
  4746. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4747. {"project_id": "1", "title": "Push pref task", "priority": "5"})
  4748. pref_task = task_id_of("Push pref task")
  4749. act(auth, task_state(auth, pref_task)["toggle_notify"], {})
  4750. conn = db()
  4751. check(conn.execute("select count(*) from task_notify_prefs where task_id = ?"
  4752. " and user_id = ?", (pref_task, admin_id)).fetchone()[0] == 1,
  4753. "Notify me persists a task_notify_prefs row for the user")
  4754. conn.close()
  4755. check(task_state(auth, pref_task).get("notify_me") is True,
  4756. "the task slot reflects notify_me after the toggle")
  4757. act(auth, task_state(auth, pref_task)["toggle_notify"], {})
  4758. conn = db()
  4759. check(conn.execute("select count(*) from task_notify_prefs where task_id = ?",
  4760. (pref_task,)).fetchone()[0] == 0,
  4761. "Don't notify me removes the pref row")
  4762. conn.close()
  4763. check(task_state(auth, pref_task).get("notify_me") is False,
  4764. "the task slot reflects the opt-out")
  4765. print("== task E: dispatch matrix — global blocks vs opted-in lifecycle ==")
  4766. # Two "browsers" for admin (/main, /gone) and one for another user
  4767. # (id 999, rows seeded directly — push targeting is per user).
  4768. endpoint_gone = push.url("/gone")
  4769. push.status_for["/gone"] = 410
  4770. act(auth, dash["push_subscribe"],
  4771. {"endpoint": endpoint_gone, **subscribe_fields})
  4772. other_browser = ec.generate_private_key(ec.SECP256R1())
  4773. other_public = other_browser.public_key().public_bytes(
  4774. Encoding.X962, PublicFormat.UncompressedPoint)
  4775. other_auth = os.urandom(16)
  4776. endpoint_other = push.url("/other")
  4777. conn = db()
  4778. conn.execute("insert into push_subscriptions (user_id, endpoint, p256dh, auth,"
  4779. " created_at) values (999, ?, ?, ?, strftime('%s','now'))",
  4780. (endpoint_other, b64url(other_public), b64url(other_auth)))
  4781. conn.commit()
  4782. conn.close()
  4783. # Task 1: admin opted in via the UI toggle; the other user is not.
  4784. # Baselines are captured BEFORE the enqueue: the first-start push
  4785. # fires at the allocation, the instant the dispatch lands.
  4786. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4787. {"project_id": "1", "title": "Push lifecycle task", "priority": "5"})
  4788. task1 = task_id_of("Push lifecycle task")
  4789. act(auth, task_state(auth, task1)["toggle_notify"], {})
  4790. main_before = len(push.hits("/main"))
  4791. other_before = len(push.hits("/other"))
  4792. gone_before = len(push.hits("/gone"))
  4793. enqueue_task(auth, task1)
  4794. check(wait_for(lambda: fake.running_task == task1 or False, timeout=30,
  4795. what="task 1 assignment") is not None,
  4796. "task 1 dispatches to the fake daemon")
  4797. task1_session = fake.session_id
  4798. check(wait_for(lambda: len(push.hits("/main")) > main_before, timeout=15,
  4799. what="first-start push to the opted-in admin") is not None,
  4800. "first start notifies the opted-in user's subscription")
  4801. check(wait_for(lambda: len(push.hits("/gone")) > gone_before, timeout=15,
  4802. what="first-start push to the gone endpoint") is not None,
  4803. "first start reaches every subscription of the opted-in user")
  4804. check(quiet_window(quiet_seconds(),
  4805. lambda: len(push.hits("/other")) == other_before,
  4806. "no first-start push to the not-opted-in user"),
  4807. "first start never reaches users without the notify pref")
  4808. check(wait_task_done(auth, task1, timeout=60) is not None,
  4809. "task 1 completes")
  4810. _, done_payload = decrypt_webpush(push.hits("/main")[-1], browser,
  4811. browser_public, rotated_auth)
  4812. check(done_payload["title"] == "Push lifecycle task — completed"
  4813. and done_payload["url"] == "/tasks/%d" % task1,
  4814. "completion notifies the opted-in user (decrypted payload)")
  4815. check(len(push.hits("/other")) == other_before,
  4816. "completion stays with the opted-in user only")
  4817. check(wait_for(lambda: subscription_count(endpoint_gone) == 0, timeout=15,
  4818. what="410 endpoint pruned") is not None,
  4819. "a 410 Gone endpoint is pruned from push_subscriptions")
  4820. # Block events go to EVERY push-subscribed user globally. The
  4821. # poll-era /update raise is gone: a live (non-terminal) host task
  4822. # with an open session on the fake carries the block through the
  4823. # results push — task1 is done and terminal pushes are consumed
  4824. # silently, so the host is its own fixture row.
  4825. conn = db()
  4826. conn.execute("insert into tasks (project_id, title, status, priority,"
  4827. " created_at) values (1, 'Push block host', 'working', 5,"
  4828. " strftime('%s','now'))")
  4829. push_host = conn.execute("select max(id) from tasks").fetchone()[0]
  4830. conn.execute("insert into sessions (task_id, saddle_id, started_at)"
  4831. " values (?, ?, strftime('%s','now'))", (push_host, fake_id))
  4832. push_host_session = conn.execute(
  4833. "select max(id) from sessions").fetchone()[0]
  4834. conn.commit()
  4835. conn.close()
  4836. def raise_global_block(question):
  4837. return saddle_api("POST", "/api/saddle/results", fake_token, {
  4838. "session_id": push_host_session, "state": "blocked",
  4839. "block": {"question": question, "type": "question"}})
  4840. main_before = len(push.hits("/main"))
  4841. other_before = len(push.hits("/other"))
  4842. raise_global_block("Global question for everyone?")
  4843. check(wait_for(lambda: len(push.hits("/main")) > main_before
  4844. and len(push.hits("/other")) > other_before, timeout=15,
  4845. what="global block push") is not None,
  4846. "a raised block notifies every push-subscribed user globally")
  4847. block_hit = push.hits("/other")[-1]
  4848. _, payload = decrypt_webpush(block_hit, other_browser, other_public, other_auth)
  4849. check(payload["title"] == "Push block host — question raised"
  4850. and payload["body"] == "Global question for everyone?"
  4851. and payload["url"] == "/tasks/%d" % push_host,
  4852. "the block payload carries task title + kind, question and click URL (%s)"
  4853. % payload)
  4854. ciphertext_len = len(block_hit["body"]) - (21 + 65)
  4855. envelope = block_hit["body"]
  4856. record_size = int.from_bytes(envelope[16:20], "big")
  4857. # rs = plaintext + delimiter (1) + tag (16) == ciphertext-with-tag len.
  4858. check(record_size == ciphertext_len,
  4859. "the RFC 8291 envelope record size covers payload + delimiter + tag")
  4860. claims = verify_vapid(block_hit, vapid["public_key"], vapid["private_key"])
  4861. check(claims.get("aud") == "http://127.0.0.1:%d" % push.port
  4862. and claims.get("sub", "").startswith("mailto:")
  4863. and claims.get("exp", 0) > time.time(),
  4864. "the VAPID JWT verifies: aud = the endpoint origin, mailto sub, future exp")
  4865. check(block_hit["headers"].get("ttl") == "60"
  4866. and block_hit["headers"].get("content-type") == "application/octet-stream",
  4867. "the push POST carries TTL and the encrypted content type")
  4868. # Task 2: only the OTHER user opted in — start + failure reach them
  4869. # alone. Baseline again before the enqueue (first start fires at
  4870. # the allocation).
  4871. fake.fail_next = True
  4872. act(auth, slot_public(auth, "/tasks", "tasks")["create"],
  4873. {"project_id": "1", "title": "Push failure task", "priority": "5"})
  4874. task2 = task_id_of("Push failure task")
  4875. conn = db()
  4876. conn.execute("insert into task_notify_prefs (task_id, user_id) values (?, 999)",
  4877. (task2,))
  4878. conn.commit()
  4879. conn.close()
  4880. main_before2 = len(push.hits("/main"))
  4881. other_before2 = len(push.hits("/other"))
  4882. enqueue_task(auth, task2)
  4883. check(wait_for(lambda: fake.running_task == task2 or False, timeout=30,
  4884. what="task 2 assignment") is not None,
  4885. "task 2 dispatches (scripted to fail)")
  4886. check(wait_for(lambda: task_state(auth, task2)["status"] == "failed"
  4887. or False, timeout=30, what="task 2 failed") is not None,
  4888. "task 2 fails")
  4889. check(wait_for(lambda: len(push.hits("/other")) >= other_before2 + 2,
  4890. timeout=15, what="opted-in user's started+failed pushes"),
  4891. "the opted-in user gets first start AND failure for the task")
  4892. started_hit = [hit for hit in push.hits("/other")[other_before2:]][0]
  4893. _, started_payload = decrypt_webpush(started_hit, other_browser,
  4894. other_public, other_auth)
  4895. check(started_payload["title"] == "Push failure task — started",
  4896. "the first-start payload names task + kind (%s)" % started_payload)
  4897. _, failure_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4898. other_public, other_auth)
  4899. check(failure_payload["title"] == "Push failure task — failed"
  4900. and failure_payload["url"] == "/tasks/%d" % task2,
  4901. "the failure payload names the task and links its page")
  4902. check(len(push.hits("/main")) == main_before2,
  4903. "an agent failure never reaches users without the pref")
  4904. print("== task E: retry next tick (best-effort delivery) ==")
  4905. endpoint_flaky = push.url("/flaky")
  4906. act(auth, dash["push_subscribe"],
  4907. {"endpoint": endpoint_flaky, **subscribe_fields})
  4908. push.fail_next["/flaky"] = 1
  4909. flaky_before = len(push.hits("/flaky"))
  4910. raise_global_block("Flaky delivery question?")
  4911. check(wait_for(lambda: len(push.hits("/flaky")) >= flaky_before + 2,
  4912. timeout=20, what="flaky endpoint retried") is not None,
  4913. "a failed send retries on the next dispatcher tick and lands")
  4914. print("== plan 12: goal notifications — blocks/success/failure always ==")
  4915. # Goal blocks, completion approval and failure push to EVERY
  4916. # subscribed user (the mirror on the goal-run task stays quiet).
  4917. def goal_state(goal_id):
  4918. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  4919. push_goal = None
  4920. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4921. "project_id": "1", "title": "Push goal", "brief": "Notifies everyone.",
  4922. "branch_name": "goal/push"})
  4923. conn = db()
  4924. row = conn.execute("select id from goals where title = 'Push goal'").fetchone()
  4925. conn.close()
  4926. push_goal = int(row[0])
  4927. fake.goal_script = [("plan", "# Push plan\n\n1. Ring the bells")]
  4928. main_before = len(push.hits("/main"))
  4929. other_before = len(push.hits("/other"))
  4930. act(auth, goal_state(push_goal)["start"], {})
  4931. check(wait_for(lambda: goal_state(push_goal)["status"] == "plan_review" or False,
  4932. timeout=60, what="push goal enters plan review") is not None,
  4933. "the push goal reaches plan review")
  4934. check(wait_for(lambda: len(push.hits("/main")) > main_before
  4935. and len(push.hits("/other")) > other_before, timeout=15,
  4936. what="goal plan-review push") is not None,
  4937. "a goal plan review notifies every subscribed user globally")
  4938. _, plan_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4939. other_public, other_auth)
  4940. check("Push goal" in plan_payload["title"] and "plan" in plan_payload["title"]
  4941. and plan_payload["url"] == "/goals/%d" % push_goal,
  4942. "the goal block payload carries the goal title + click URL (%s)"
  4943. % plan_payload)
  4944. main_before = len(push.hits("/main"))
  4945. fake.goal_script = [("suspend",)]
  4946. act(auth, goal_state(push_goal)["plan_pending_block"]["answer_action"],
  4947. {"answer": "Plan approved. Proceed with implementation."})
  4948. check(wait_for(lambda: goal_state(push_goal)["status"] == "active" or False,
  4949. timeout=30, what="push goal active") is not None,
  4950. "the push goal activates")
  4951. check(quiet_window(3, lambda: len(push.hits("/main")) == main_before,
  4952. "no push for an internal resume"),
  4953. "the goal agent's own park/resume does not notify (internal)")
  4954. # `saddle failure` in goal context fails the goal — global push.
  4955. fake.goal_script = [("fail", "the harness collapsed")]
  4956. other_before2 = len(push.hits("/other"))
  4957. main_before2 = len(push.hits("/main"))
  4958. conn = db()
  4959. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  4960. " priority, completed_at, created_at) values (1, ?, 'task',"
  4961. " 'Warm', 'done', 5,"
  4962. " strftime('%s','now'),"
  4963. " strftime('%s','now','-30 seconds'))", (push_goal,))
  4964. conn.commit()
  4965. conn.close()
  4966. check(wait_for(lambda: goal_state(push_goal)["status"] == "failed" or False,
  4967. timeout=60, what="goal failure lands") is not None,
  4968. "the goal agent's failure fails the goal")
  4969. check(wait_for(lambda: len(push.hits("/other")) > other_before2
  4970. and len(push.hits("/main")) > main_before2, timeout=15,
  4971. what="goal failure push") is not None,
  4972. "a goal failure notifies every subscribed user globally")
  4973. _, fail_payload = decrypt_webpush(push.hits("/other")[-1], other_browser,
  4974. other_public, other_auth)
  4975. check("Push goal" in fail_payload["title"] and "failed" in fail_payload["title"]
  4976. and fail_payload["url"] == "/goals/%d" % push_goal,
  4977. "the goal failure payload carries the goal title + click URL (%s)"
  4978. % fail_payload)
  4979. # Completion approval pushes "complete" globally (success always).
  4980. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  4981. "project_id": "1", "title": "Push done goal", "brief": "Completes.",
  4982. "branch_name": "goal/push-done"})
  4983. conn = db()
  4984. row = conn.execute("select id from goals where title = 'Push done goal'").fetchone()
  4985. conn.close()
  4986. done_goal = int(row[0])
  4987. fake.goal_script = [("plan", "# Done plan")]
  4988. act(auth, goal_state(done_goal)["start"], {})
  4989. check(wait_for(lambda: goal_state(done_goal)["status"] == "plan_review" or False,
  4990. timeout=60, what="done goal plan review") is not None,
  4991. "the done goal reaches plan review")
  4992. fake.goal_script = [("done", "# Completion\n\nShipped.")]
  4993. act(auth, goal_state(done_goal)["plan_pending_block"]["answer_action"],
  4994. {"answer": "Plan approved. Proceed with implementation."})
  4995. check(wait_for(lambda: goal_state(done_goal)["status"] == "completion_review"
  4996. or False, timeout=60, what="done goal completion review") is not None,
  4997. "the approved done goal reaches completion review")
  4998. main_before = len(push.hits("/main"))
  4999. act(auth, goal_state(done_goal)["completion_pending_block"]["answer_action"],
  5000. {"answer": "Review approved. Continue with the task."})
  5001. check(wait_for(lambda: goal_state(done_goal)["status"] == "complete" or False,
  5002. timeout=30, what="done goal completes") is not None,
  5003. "the done goal completes")
  5004. check(wait_for(lambda: len(push.hits("/main")) > main_before, timeout=15,
  5005. what="goal success push") is not None,
  5006. "a goal completion notifies every subscribed user globally")
  5007. _, done_goal_payload = decrypt_webpush(push.hits("/main")[-1], browser,
  5008. browser_public, rotated_auth)
  5009. check("Push done goal" in done_goal_payload["title"]
  5010. and "complete" in done_goal_payload["title"]
  5011. and done_goal_payload["url"] == "/goals/%d" % done_goal,
  5012. "the goal success payload carries the goal title + click URL (%s)"
  5013. % done_goal_payload)
  5014. print("== task E: unsubscribe removes the subscription ==")
  5015. dash = slot_public(auth, "/", "dashboard")
  5016. check(dash.get("push_subscribed") is True,
  5017. "the bell shows subscribed while endpoints exist")
  5018. act(auth, dash["push_unsubscribe"], {"endpoint": endpoint_main})
  5019. check(subscription_count(endpoint_main) == 0,
  5020. "unsubscribing removes the endpoint's row")
  5021. # =============================================================================
  5022. # Bundle: goals — the plan-12 goal lifecycle: creation with branch-name
  5023. # uniqueness, the start → planning → plan review → active flow with
  5024. # revisions, the goal agent's task fan-out through the task CLI
  5025. # callbacks (ownership + creator-only enqueue), the event-driven
  5026. # coalesced resume, pause/resume queueing, the completion review with
  5027. # branch push state, the cancel cascade, and the human tasks'
  5028. # auto-enqueue-after predecessor.
  5029. # =============================================================================
  5030. def bundle_goals(ctx):
  5031. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  5032. app = ctx.app
  5033. def goal_state(goal_id):
  5034. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  5035. def create_goal(fields):
  5036. act(auth, slot_public(auth, "/goals", "goals")["create"], fields)
  5037. rows = [g for g in slot_public(auth, "/goals", "goals")["goals"]
  5038. if g["title"] == fields["title"]]
  5039. return int(rows[0]["id"])
  5040. print("== plan 12: goal creation, validation, lifecycle actions ==")
  5041. goal1 = create_goal({"project_id": "1", "title": "Ship the flange",
  5042. "brief": "Make the flange module production-grade.",
  5043. "branch_name": "goal/flange", "priority": "3"})
  5044. state = goal_state(goal1)
  5045. check(state["status"] == "draft" and state["display"] == "draft"
  5046. and state["branch_name"] == "goal/flange"
  5047. and state["base_branch"] == "main",
  5048. "a goal lands in draft with its branch pair")
  5049. check(state.get("start") is not None and state.get("cancel") is not None
  5050. and state.get("pause") is None,
  5051. "draft offers start + cancel only")
  5052. check(state["run_task_id"] == 0 and state["comments"] == [],
  5053. "a draft goal has no thread yet (the run task owns it)")
  5054. draft_page = http_get_page(auth, "/goals/%d" % goal1)
  5055. check('stm-if="goal.run_task_id &gt; 0" stm-action="goal.comment"' in draft_page
  5056. and "comments open with its run" in draft_page,
  5057. "the draft goal page gates the composer on the run (muted note until then)")
  5058. # Branch-name uniqueness: same name, same involved project → refuse.
  5059. duplicate_directives = act(auth, slot_public(auth, "/goals", "goals")["create"], {
  5060. "project_id": "1", "title": "Clash", "brief": "b", "branch_name": "goal/flange"})
  5061. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  5062. and "goal/flange" in (d.get("message") or "")
  5063. for d in duplicate_directives),
  5064. "a live goal's branch name cannot be reused in an involved project (%s)"
  5065. % [d.get("message") for d in duplicate_directives if d.get("type") == "notify"])
  5066. conn = db()
  5067. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  5068. " values ('other-repo', 'https://example.com/other.git', 'main',"
  5069. " strftime('%s','now'))")
  5070. conn.commit()
  5071. conn.close()
  5072. goal_elsewhere = create_goal({"project_id": "2", "title": "Elsewhere",
  5073. "brief": "b", "branch_name": "goal/flange"})
  5074. check(goal_elsewhere > 0,
  5075. "the same branch name in a disjoint project is fine (one per repo)")
  5076. # Brief validation.
  5077. brief_directives = act(auth, slot_public(auth, "/goals", "goals")["create"], {
  5078. "project_id": "1", "title": "No brief", "brief": " ", "branch_name": "goal/x1"})
  5079. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  5080. and "brief" in (d.get("message") or "").lower()
  5081. for d in brief_directives),
  5082. "an empty brief rejects")
  5083. # Start: planning + the goal-run internal task.
  5084. act(auth, state["start"], {})
  5085. state = goal_state(goal1)
  5086. check(state["status"] == "planning" and state.get("start") is None,
  5087. "start moves the goal to planning")
  5088. conn = db()
  5089. run_row = conn.execute(
  5090. "select id, kind, mode, creator, goal_id, priority, status from tasks"
  5091. " where goal_id = ? and kind = 'goal_run'", (goal1,)).fetchone()
  5092. conn.close()
  5093. check(run_row is not None and run_row[1] == "goal_run"
  5094. and run_row[2] == "orchestrate" and run_row[3] == "goal"
  5095. and run_row[4] == goal1 and run_row[5] == 3
  5096. and run_row[6] in ("queued", "assigned", "working"),
  5097. "start creates the goal-run task (orchestrate, priority 3, creator goal,"
  5098. " queued)")
  5099. run_task = int(run_row[0])
  5100. check(goal_state(goal1)["run_task_id"] == run_task,
  5101. "the goal state carries the run task id")
  5102. check(any(e["kind"] == "started" for e in goal_state(goal1)["events"]),
  5103. "the narrative records the start")
  5104. print("== feedback: goal-agent runs are hidden from every task listing ==")
  5105. # The internal run task never lists anywhere tasks are browsed —
  5106. # only the goal page exposes it (worker tasks stay listed). The
  5107. # plan script is armed BEFORE the first dispatch so this section's
  5108. # waits never consume the round the plan-review flow below needs.
  5109. fake.goal_script = [("plan", "# Plan v1\n\n1. Add tests\n2. Ship")]
  5110. check(wait_for(lambda: task_state(auth, run_task)["status"]
  5111. in ("assigned", "working") or False,
  5112. timeout=60, what="run task dispatches") is not None,
  5113. "the run task reaches its saddle")
  5114. queue_rows = slot_public(auth, "/tasks", "tasks")["tasks"]
  5115. check(all(int(t["id"]) != run_task for t in queue_rows),
  5116. "the tasks queue never lists the goal-agent run task")
  5117. check(all(t["kind"] != "goal_run" for t in queue_rows),
  5118. "no goal_run rows leak into the queue at all")
  5119. project_state = slot_public(auth, "/projects/1", "project")
  5120. check(all(int(t["id"]) != run_task for t in project_state["tasks"]),
  5121. "the project page's task list excludes the run task")
  5122. dashboard = slot_public(auth, "/", "dashboard")
  5123. check(all(int(a["id"]) != run_task for a in dashboard["active_tasks"]),
  5124. "the dashboard's active tasks exclude the run task")
  5125. check(all(int(i["task_id"]) != run_task for i in dashboard["activity"]),
  5126. "the activity timeline never references the run task")
  5127. check(wait_for(lambda: int(next(
  5128. (s for s in slot_public(auth, "/", "dashboard")["saddles"]
  5129. if s["name"] == "fake-saddle"), {})
  5130. .get("current_goal_id") or 0) == goal1 or False,
  5131. timeout=30, what="saddle card links the goal") is not None,
  5132. "a saddle hosting the goal agent reads as supervising the goal")
  5133. fake_dash_card = next(s for s in slot_public(auth, "/", "dashboard")["saddles"]
  5134. if s["name"] == "fake-saddle")
  5135. check(fake_dash_card["current_goal_title"] == "Ship the flange",
  5136. "the supervision link carries the goal title")
  5137. print("== plan 12: the goal agent plans, plan review, revisions ==")
  5138. # (The plan script was armed before the run's first dispatch — see
  5139. # the listing-hiding section above — so the first round submits it.)
  5140. check(wait_for(lambda: goal_state(goal1)["status"] == "plan_review" or False,
  5141. timeout=120, what="goal agent submits its plan") is not None,
  5142. "the goal agent's plan push enters plan review")
  5143. state = goal_state(goal1)
  5144. check(task_state(auth, run_task)["status"] == "blocked",
  5145. "the goal-run task parks on the plan review")
  5146. # U3's plan-review counterpart: the run-task card never reads as a
  5147. # bare "blocked" while a review-shaped block parks it.
  5148. check(task_state(auth, run_task)["display"] == "awaiting your review",
  5149. "the run-task card reads 'awaiting your review' during the plan review (U3)")
  5150. pending = state.get("plan_pending_block")
  5151. check(pending and "# Plan v1" in (pending.get("body") or ""),
  5152. "the pending plan review carries the submitted markdown")
  5153. check(any(b["block_type"] == "plan" and b["is_plan_review"]
  5154. for b in state["blocks"]),
  5155. "the goal blocks list carries the pending plan block")
  5156. print("== feedback: goal visual identity ==")
  5157. # A goal never reads as a task at a glance: marked nav entry,
  5158. # iconed list page, and the dashboard pile's goal cards carry
  5159. # their own accent styling.
  5160. home_html = http_get_page(auth, "/")
  5161. check('class="nav-goal"' in home_html and "&#127919;" in home_html,
  5162. "the nav carries the marked 🎯 Goals entry beside Tasks")
  5163. check(any(p["item_type"] == "goal" for p in
  5164. slot_public(auth, "/", "dashboard")["pinned"]),
  5165. "the goal's pending block pins onto the dashboard pile")
  5166. check("'card goal-card'" in home_html and 'badge-kind-goal' in home_html,
  5167. "dashboard goal cards carry the distinct goal styling")
  5168. goals_html = http_get_page(auth, "/goals")
  5169. check("&#127919;" in goals_html and "goal-icon" in goals_html,
  5170. "the goals list page carries the goal icon")
  5171. goal_page_html = http_get_page(auth, "/goals/%d" % goal1)
  5172. check('class="card goal-head"' in goal_page_html and "goal-page" in goal_page_html,
  5173. "the goal page carries the goal-accented identity chrome")
  5174. # Reject with feedback: the agent revises.
  5175. fake.goal_script = [("plan", "# Plan v2\n\n1. Add tests\n2. Add docs\n3. Ship")]
  5176. reject_resume_index = len(fake.goal_assignments)
  5177. act(auth, pending["answer_action"], {"answer": "Add documentation please"})
  5178. check(wait_for(lambda: goal_state(goal1)["status"] == "plan_review" or False,
  5179. timeout=60, what="revised plan enters review") is not None,
  5180. "feedback sends the agent back to planning; the revision re-enters review")
  5181. # The rejection resume carried NO context_update (nothing in the
  5182. # instruction context had changed).
  5183. check(all("context_update" not in p
  5184. for p in fake.goal_assignments[reject_resume_index:]),
  5185. "a resume without context changes carries no context_update")
  5186. state = goal_state(goal1)
  5187. revisions = state["plan_revisions"]
  5188. check(len(revisions) == 2
  5189. and revisions[0]["answered"] and "Add documentation please" in revisions[0]["answer"]
  5190. and not revisions[1]["answered"],
  5191. "rejected revisions stay as answered history (historical-blocks data)")
  5192. # Plan 16 S1 pin: goals.plan is accept-gated — the pending revision
  5193. # lives only in its block; nothing lands on the goal before accept.
  5194. conn = db()
  5195. plan_column = conn.execute(
  5196. "select plan from goals where id = ?", (goal1,)).fetchone()[0]
  5197. conn.close()
  5198. check((plan_column is None or plan_column == "")
  5199. and (state["plan"] or "") == "",
  5200. "goals.plan stays empty while the revision is only pending (accept-gated, S1)")
  5201. # Approve: goal.plan = v2, status active, agent resumes and parks.
  5202. # Plan 16 S2: the accept posts the verdict MARKER — the server
  5203. # resolves the goal-plan kind and owns the constant.
  5204. fake.goal_script = [("suspend",)]
  5205. pending = state["plan_pending_block"]
  5206. act(auth, pending["answer_action"], {"verdict": "accept"})
  5207. check(wait_for(lambda: goal_state(goal1)["status"] == "active" or False,
  5208. timeout=60, what="approved plan activates the goal") is not None,
  5209. "approving the plan activates the goal")
  5210. state = goal_state(goal1)
  5211. check(state["plan"] == "# Plan v2\n\n1. Add tests\n2. Add docs\n3. Ship",
  5212. "the approved plan markdown is stored on the goal (the accept verdict's write)")
  5213. # The approval resume carries the plan delta as a context_update
  5214. # turn (the prompt-cache-friendly replacement for the daemon's
  5215. # old system-prompt refresh).
  5216. check(wait_for(lambda: len(fake.goal_assignments) > 0 and
  5217. "context_update" in fake.goal_assignments[-1] or False,
  5218. timeout=30, what="approval resume carries context_update") is not None,
  5219. "the plan-approval resume carries a context_update turn")
  5220. approval_update = fake.goal_assignments[-1]["context_update"]
  5221. check("Plan approved" in approval_update and "# Plan v2" in approval_update,
  5222. "the context_update summarises the approved plan markdown")
  5223. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5224. or False, timeout=60, what="goal agent parks after approval") is not None,
  5225. "the resumed goal agent parks (saddle suspend)")
  5226. print("== plan 12: task fan-out via the task CLI callbacks ==")
  5227. # The goal agent (parked, open session on its saddle) creates,
  5228. # enqueues and deletes its tasks through /api/saddle/task/*.
  5229. conn = db()
  5230. agent_session = conn.execute(
  5231. "select id from sessions where task_id = ? and ended_at is null",
  5232. (run_task,)).fetchone()[0]
  5233. conn.close()
  5234. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5235. "session_id": agent_session, "title": "Flange tests",
  5236. "mandate": "Write the test suite for the flange module.",
  5237. "mode": "test"})
  5238. check(status == 200 and body.get("ok") is True,
  5239. "task create under the goal succeeds (%s)" % body.get("error"))
  5240. fan_task = int(body["task_id"])
  5241. detail = task_state(auth, fan_task)
  5242. check(detail["status"] == "draft" and detail["mode"] == "test"
  5243. and detail["creator"] == "goal" and detail.get("goal_id") == goal1,
  5244. "the created task is a draft goal task with its mode and creator")
  5245. check(detail["task_branch"] == "task/%d-%d" % (goal1, fan_task)
  5246. and detail["branch_from"] == "goal/flange",
  5247. "goal worker tasks get ephemeral branches cut from the goal branch")
  5248. check(any(e["kind"] == "task-created" and int(e["task_id"]) == fan_task
  5249. for e in goal_state(goal1)["events"]),
  5250. "the narrative records the agent's task creation")
  5251. # Draft until the agent enqueues; humans may not (creator-only).
  5252. check(detail.get("enqueue") is None,
  5253. "the human Enqueue action is not offered for goal tasks (creator-only)")
  5254. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  5255. "session_id": agent_session, "task_id": fan_task})
  5256. check(status == 200 and task_state(auth, fan_task)["status"] == "queued",
  5257. "task enqueue by the goal agent queues the draft")
  5258. # Ownership + shape errors, verbatim for the CLI.
  5259. status, body = saddle_api("POST", "/api/saddle/task/enqueue", fake_token, {
  5260. "session_id": agent_session, "task_id": 999999})
  5261. check(status == 400 and "No task exists" in (body.get("error") or ""),
  5262. "enqueue of a missing task errors verbatim")
  5263. create_queued(auth, {"project_id": "1", "title": "Innocent bystander", "priority": "4"})
  5264. bystander = task_id_of("Innocent bystander")
  5265. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  5266. "session_id": agent_session, "task_id": bystander})
  5267. check(status == 400 and "does not belong to your goal" in (body.get("error") or ""),
  5268. "the goal agent cannot touch tasks outside its goal")
  5269. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5270. "session_id": agent_session, "title": "Bad mode", "mandate": "m", "mode": "party"})
  5271. check(status == 400 and "valid modes" in (body.get("error") or ""),
  5272. "an unknown mode rejects with the valid list")
  5273. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5274. "session_id": agent_session, "title": "Bad tag", "mandate": "m",
  5275. "capabilities": ["warp-drive"]})
  5276. check(status == 400 and "warp-drive" in (body.get("error") or "")
  5277. and "valid tags" in (body.get("error") or ""),
  5278. "an unknown capability tag rejects naming the valid set")
  5279. # A plain task's session is not a goal-agent identity.
  5280. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token,
  5281. {"session_id": 999999, "title": "x", "mandate": "m"})
  5282. check(status == 400 and "session" in (body.get("error") or ""),
  5283. "an unknown session_id errors verbatim")
  5284. # Delete: draft + owned.
  5285. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5286. "session_id": agent_session, "title": "Scratch task", "mandate": "m"})
  5287. scratch = int(body["task_id"])
  5288. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  5289. "session_id": agent_session, "task_id": scratch})
  5290. check(status == 200 and not any(
  5291. t["id"] == scratch for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5292. "task delete removes the owned draft")
  5293. status, body = saddle_api("POST", "/api/saddle/task/delete", fake_token, {
  5294. "session_id": agent_session, "task_id": fan_task})
  5295. check(status == 400 and "draft" in (body.get("error") or ""),
  5296. "deleting a queued task refuses (draft only)")
  5297. print("== plan 12: goal context in the worker assignment + coalesced resume ==")
  5298. # The queued fan-out task dispatches to the daemon with the goal
  5299. # reference + ephemeral branch; its completion schedules the parked
  5300. # goal agent's resume (>= SADDLE_GOAL_RESUME_S after the event).
  5301. check(wait_for(lambda: any(int(p.get("task", {}).get("id") or 0) == fan_task
  5302. for p in fake.start_payloads) or False,
  5303. timeout=60, what="fan-out task dispatches") is not None,
  5304. "the goal worker task dispatches")
  5305. fan_payload = [p for p in fake.start_payloads
  5306. if int(p.get("task", {}).get("id") or 0) == fan_task][-1]
  5307. goal_ctx = fan_payload.get("goal") or {}
  5308. check(goal_ctx.get("id") == goal1 and goal_ctx.get("branch") == "goal/flange"
  5309. and goal_ctx.get("base_branch") == "main"
  5310. and "flange module" in goal_ctx.get("brief", "")
  5311. and "# Plan v2" in goal_ctx.get("plan", ""),
  5312. "the worker assignment carries the goal context (read-only brief + plan)")
  5313. check(fan_payload.get("ephemeral_branch") == "task/%d-%d" % (goal1, fan_task)
  5314. and fan_payload.get("kind") == "task" and fan_payload.get("mode") == "test"
  5315. and fan_payload.get("creator") == "goal",
  5316. "the worker assignment carries the ephemeral branch + identity triplet")
  5317. check(wait_task_done(auth, fan_task, timeout=60) is not None,
  5318. "the goal worker task completes")
  5319. check(any(e["kind"] == "task-done" and int(e["task_id"]) == fan_task
  5320. for e in goal_state(goal1)["events"]),
  5321. "the narrative records the task's completion")
  5322. goal_runs_before = len(fake.goal_assignments)
  5323. check(wait_for(lambda: len(fake.goal_assignments) > goal_runs_before or False,
  5324. timeout=30, what="parked goal agent resumes") is not None,
  5325. "the task-terminal event resumes the parked goal agent")
  5326. resume_payload = fake.goal_assignments[-1]
  5327. notice = resume_payload.get("resume_notice") or ""
  5328. check("Task statuses" in notice and "Flange tests" in notice
  5329. and "done" in notice,
  5330. "the resume notice batches ALL plan task statuses")
  5331. check("New completion reports" in notice and "fake daemon finished" in notice,
  5332. "the resume notice carries the new completion report")
  5333. check("context_update" not in resume_payload,
  5334. "a later resume with no context changes omits context_update entirely")
  5335. check(resume_payload.get("kind") == "goal_run"
  5336. and resume_payload.get("mode") == "orchestrate",
  5337. "the resumed goal agent carries its identity triplet")
  5338. # The resumed agent parked again (script): two events at once must
  5339. # coalesce into ONE resume within the window.
  5340. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5341. or False, timeout=60, what="goal agent re-parks") is not None,
  5342. "the resumed goal agent parks again")
  5343. print("== plan 16 S3: delta resume notices — one-line statuses, bodies once ==")
  5344. # A MULTI-LINE completion lands while the agent is parked. The next
  5345. # notice lists every status ONE-LINE (first line of the summary
  5346. # only) and embeds each NEW completion's full body exactly once —
  5347. # no statuses-section/reports-section double embedding. (Timestamps
  5348. # are second-granular: each fixture waits out the park's second so
  5349. # completed_at is strictly newer than suspended_at.)
  5350. def run_park_second_passed():
  5351. conn = db()
  5352. try:
  5353. row = conn.execute("select suspended_at from tasks where id = ?",
  5354. (run_task,)).fetchone()
  5355. if not row or not row[0]:
  5356. return False
  5357. return time.time() > float(row[0]) + 1.05
  5358. finally:
  5359. conn.close()
  5360. check(wait_for(run_park_second_passed, timeout=30,
  5361. what="S3 park second passes") is not None,
  5362. "the park stamp is in a strictly older second")
  5363. conn = db()
  5364. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  5365. " priority, summary, completed_at, created_at) values (1, ?, 'task',"
  5366. " 'Multiline report', 'done', 5,"
  5367. " 'Headline: the flange calibrates\n\nBody: the full report with all"
  5368. " the detail lines.',"
  5369. " strftime('%s','now'),"
  5370. " strftime('%s','now','-30 seconds'))", (goal1,))
  5371. conn.commit()
  5372. conn.close()
  5373. s3_before = len(fake.goal_assignments)
  5374. check(wait_for(lambda: len(fake.goal_assignments) > s3_before or False,
  5375. timeout=60, what="S3 delta resume fires") is not None,
  5376. "the multiline completion resumes the parked agent")
  5377. s3_notice = fake.goal_assignments[-1].get("resume_notice") or ""
  5378. s3_statuses = s3_notice.split("## Task statuses", 1)[1] \
  5379. .split("## New completion reports", 1)[0]
  5380. check("Headline: the flange calibrates" in s3_statuses
  5381. and "the full report with all the detail lines" not in s3_statuses,
  5382. "the statuses section carries ONE LINE per task (the summary's first line)")
  5383. check(s3_notice.count("the full report with all the detail lines.") == 1
  5384. and "### #" in s3_notice,
  5385. "each new completion's full body embeds EXACTLY ONCE (no double embedding)")
  5386. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5387. or False, timeout=60, what="S3 agent re-parks") is not None,
  5388. "the S3 agent re-parks")
  5389. # Size constant per event, not cumulative: the NEXT resume (armed
  5390. # with a fresh single-line completion) reports only the NEW body —
  5391. # the consumed multiline report never re-embeds.
  5392. check(wait_for(run_park_second_passed, timeout=30,
  5393. what="S3 second park second passes") is not None,
  5394. "the second park stamp is in a strictly older second")
  5395. conn = db()
  5396. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  5397. " priority, summary, completed_at, created_at) values (1, ?, 'task',"
  5398. " 'Fresh completion', 'done', 5, 'fresh one-liner',"
  5399. " strftime('%s','now'),"
  5400. " strftime('%s','now','-30 seconds'))", (goal1,))
  5401. conn.commit()
  5402. conn.close()
  5403. s3_more = len(fake.goal_assignments)
  5404. check(wait_for(lambda: len(fake.goal_assignments) > s3_more or False,
  5405. timeout=60, what="S3 second delta resume") is not None,
  5406. "the fresh completion resumes the agent again")
  5407. s3_next = fake.goal_assignments[-1].get("resume_notice") or ""
  5408. check("the full report with all the detail lines." not in s3_next
  5409. and "### #" in s3_next and "fresh one-liner" in s3_next,
  5410. "the consumed completion's body never re-embeds (notice size constant per event)")
  5411. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5412. or False, timeout=60, what="S3 agent parks a third time") is not None,
  5413. "the S3 agent parks for the pause section")
  5414. print("== feedback: goal page parity — progress feed, current activity, runs ==")
  5415. # The goal agent's runs feed the page's live surfaces: progress
  5416. # lines (green latest-first feed), the open round's newest
  5417. # activity line and its hosting saddle. Parked runs keep their
  5418. # open session, so fixtures land as rows without disturbing the
  5419. # scripted daemon.
  5420. conn = db()
  5421. open_run_session = conn.execute(
  5422. "select id from sessions where task_id = ? and ended_at is null",
  5423. (run_task,)).fetchone()[0]
  5424. conn.execute(
  5425. "insert into task_progress (task_id, summary, created_at)"
  5426. " values (?, 'Overseeing the flange fan-out', strftime('%s','now'))",
  5427. (run_task,))
  5428. conn.execute(
  5429. "insert into session_commands (session_id, command_text, type, started_at)"
  5430. " values (?, 'git -C demo log --oneline -5', 'command',"
  5431. " strftime('%s','now'))", (open_run_session,))
  5432. conn.commit()
  5433. conn.close()
  5434. # A manual refresh records the daemon's health snapshot (the
  5435. # parked daemon answers /status with its suspended state).
  5436. act(auth, saddle_card(auth, "fake-saddle")["refresh"], {})
  5437. state = goal_state(goal1)
  5438. check(state["progress"] and state["progress"][0]["summary"]
  5439. == "Overseeing the flange fan-out",
  5440. "the goal page carries the agent's live progress feed")
  5441. check(state["current_command"] == "git -C demo log --oneline -5"
  5442. and state["current_command_running"] is True,
  5443. "the current activity shows the open round's running command")
  5444. check(state["agent_saddle"] == "fake-saddle"
  5445. and "fake-saddle" in state["saddle_health"],
  5446. "the assigned agent saddle and its health display")
  5447. check(state["runs"] and state["runs"][0]["saddle_name"] == "fake-saddle"
  5448. and "session_id=" in state["runs"][0]["terminal_url"],
  5449. "the run table carries host saddles and deep-linked terminals")
  5450. goal_page = http_get_page(auth, "/goals/%d" % goal1)
  5451. check('stm-markdown="goal.brief"' in goal_page
  5452. and 'stm-markdown="goal.plan"' in goal_page
  5453. and 'stm-markdown="comment.body"' in goal_page
  5454. and 'stm-markdown="event.text"' in goal_page
  5455. and 'stm-markdown="block.body"' in goal_page,
  5456. "every long-form goal body renders through stm-markdown")
  5457. check('stm-attribute.href="run.terminal_url" target="_blank" rel="noopener"' in goal_page,
  5458. "the run table's terminal links open in a new tab")
  5459. check("progress-latest" in goal_page and "Agent progress" in goal_page,
  5460. "the green progress feed renders on the goal page")
  5461. # Plan revision history keeps its verdicts (approved + rejected).
  5462. revisions = goal_state(goal1)["plan_revisions"]
  5463. check(revisions[0]["answered"] is True and revisions[0]["approved"] is False
  5464. and revisions[1]["approved"] is True,
  5465. "plan revision history badges approved and rejected verdicts")
  5466. print("== plan 12: pause freezes supervision; events coalesce on resume ==")
  5467. state = goal_state(goal1)
  5468. act(auth, state["pause"], {})
  5469. check(goal_state(goal1)["status"] == "paused"
  5470. and goal_state(goal1).get("resume") is not None,
  5471. "an active goal pauses and offers resume")
  5472. # Terminal events under a paused goal queue without waking anybody.
  5473. # (The real completion path — complete_task — records the goal's
  5474. # task-done narrative event; the resume machinery keys on exactly
  5475. # those terminal kinds, never on the agent's own enqueue narrative.)
  5476. conn = db()
  5477. conn.execute("insert into tasks (project_id, goal_id, kind, title, status, priority,"
  5478. " summary, completed_at, created_at) values (1, ?, 'task',"
  5479. " 'Quiet task', 'done', 5, 'finished while paused',"
  5480. " strftime('%s','now'), strftime('%s','now'))", (goal1,))
  5481. quiet_id = conn.execute("select max(id) from tasks").fetchone()[0]
  5482. conn.commit()
  5483. conn.close()
  5484. paused_runs = len(fake.goal_assignments)
  5485. check(quiet_window(quiet_seconds(),
  5486. lambda: len(fake.goal_assignments) == paused_runs,
  5487. "paused goal does not resume"),
  5488. "a paused goal's events queue without scheduling a resume")
  5489. state = goal_state(goal1)
  5490. act(auth, state["resume"], {})
  5491. check(goal_state(goal1)["status"] == "active",
  5492. "resume returns the goal to active")
  5493. check(wait_for(lambda: len(fake.goal_assignments) > paused_runs or False,
  5494. timeout=30, what="queued events flush on resume") is not None,
  5495. "the queued events coalesce into the post-resume wake")
  5496. check("finished while paused" in (fake.goal_assignments[-1].get("resume_notice") or ""),
  5497. "the flushed notice reports the task that finished while paused")
  5498. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  5499. or False, timeout=60, what="goal agent parks again") is not None,
  5500. "the goal agent parks again after the flush")
  5501. # The watermark consumed the flushed transition: with nothing new
  5502. # under the goal, no further resume fires (parked stays parked).
  5503. flushed_assignments = len(fake.goal_assignments)
  5504. check(quiet_window(quiet_seconds(),
  5505. lambda: len(fake.goal_assignments) == flushed_assignments,
  5506. "consumed watermark never re-fires"),
  5507. "the consumed watermark never re-fires a resume")
  5508. print("== plan 12: completion review, push state, accept ==")
  5509. # The daemon exposes goal-branch push state on /status; the web
  5510. # caches it on the goal when it probes the goal agent's saddle.
  5511. def status_extra():
  5512. return None
  5513. fake.status_extra = {"goal_branches": [
  5514. {"branch": "goal/flange", "pushed": True},
  5515. {"branch": "goal/other-repo", "pushed": False}]}
  5516. fake_card = saddle_card(auth, "fake-saddle")
  5517. act(auth, fake_card["refresh"], {})
  5518. check(wait_for(lambda: goal_state(goal1).get("push_branches") or False,
  5519. timeout=30, what="push state lands on the goal") is not None,
  5520. "the daemon's /status goal_branches exposure caches on the goal")
  5521. branches = goal_state(goal1)["push_branches"]
  5522. check({(b["branch"], b["pushed"]) for b in branches}
  5523. == {("goal/flange", True), ("goal/other-repo", False)},
  5524. "the push state renders per branch")
  5525. # the daemon's real shape carries repo too — multi-repo rows stay
  5526. # distinguishable as "repo: branch" labels
  5527. fake.status_extra = {"goal_branches": [
  5528. {"repo": "repoa", "branch": "goal/flange", "pushed": True},
  5529. {"repo": "repob", "branch": "goal/flange", "pushed": False}]}
  5530. act(auth, fake_card["refresh"], {})
  5531. check(wait_for(lambda: {b["branch"] for b in goal_state(goal1).get("push_branches") or []}
  5532. >= {"repoa: goal/flange"}, timeout=30,
  5533. what="repo-qualified push state lands") is not None,
  5534. "repo-qualified goal_branches rows render as 'repo: branch'")
  5535. fake.status_extra = None
  5536. # `saddle done` in goal context: the completion review.
  5537. fake.goal_script = [("done", "# Completion\n\nThe flange ships.")]
  5538. # Wake the parked agent: a terminal transition newer than the
  5539. # watermark (the pause-flush consumed everything up to it, so arm
  5540. # one directly with a fresh row).
  5541. conn = db()
  5542. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  5543. " priority, completed_at, created_at) values (1, ?, 'task',"
  5544. " 'Warmup', 'done', 5,"
  5545. " strftime('%s','now'),"
  5546. " strftime('%s','now','-30 seconds'))", (goal1,))
  5547. conn.commit()
  5548. conn.close()
  5549. check(wait_for(lambda: goal_state(goal1)["status"] == "completion_review" or False,
  5550. timeout=60, what="goal agent submits its completion") is not None,
  5551. "`saddle done` in goal context enters completion review")
  5552. state = goal_state(goal1)
  5553. # Plan 16 S1 (canonical-on-accept): while the review is PENDING the
  5554. # goal row carries NO report — the document lives only in its
  5555. # block; completion_report is written solely by the accept verdict.
  5556. conn = db()
  5557. pending_report_column = conn.execute(
  5558. "select completion_report from goals where id = ?", (goal1,)).fetchone()[0]
  5559. conn.close()
  5560. check((pending_report_column is None or pending_report_column == "")
  5561. and (state["completion_report"] or "") == ""
  5562. and "# Completion" in (state["completion_pending_block"].get("body") or "")
  5563. and state["completion_pending"] is True
  5564. and state["completion_pending_block"] is not None
  5565. and state["completion_pending_block"] is not False,
  5566. "the pending report lives ONLY in its block (goal row clean, S1)")
  5567. check(task_state(auth, run_task)["status"] == "blocked",
  5568. "the goal-run task parks on the completion review")
  5569. # Plan 16 S5 (U3): label reconciliation — the goal awaiting its
  5570. # completion review reads "awaiting your review" and the run-task
  5571. # status card agrees (never a bare "blocked" for a review park).
  5572. check(goal_state(goal1)["display"] == "awaiting your review"
  5573. and task_state(auth, run_task)["display"] == "awaiting your review",
  5574. "the goal and the run-task card agree: 'awaiting your review' (U3)")
  5575. check(state["compare_url"].endswith("/compare/main...goal/flange"),
  5576. "the completion review links the compare view")
  5577. # Reject first: feedback returns the goal to active. Plan 16 S2:
  5578. # the goal page's reject posts raw `feedback` — the SERVER wraps
  5579. # it with the completion-review prefix (byte-identical to the
  5580. # historical client-built answer).
  5581. fake.goal_script = [("suspend",)]
  5582. act(auth, state["completion_pending_block"]["answer_action"],
  5583. {"feedback": "Not done — the docs are missing"})
  5584. check(wait_for(lambda: goal_state(goal1)["status"] == "active" or False,
  5585. timeout=30, what="rejected completion reactivates") is not None,
  5586. "rejecting the completion returns the goal to active")
  5587. conn = db()
  5588. rejected_answer = conn.execute(
  5589. "select answer from task_blocks where task_id = ?"
  5590. " and type = 'completion' order by id desc", (run_task,)).fetchone()[0]
  5591. conn.close()
  5592. check(rejected_answer
  5593. == "Review feedback received:\n\nNot done — the docs are missing",
  5594. "the completion rejection wraps feedback with the stable prefix (%r)"
  5595. % rejected_answer)
  5596. conn = db()
  5597. rejected_report = conn.execute(
  5598. "select completion_report from goals where id = ?", (goal1,)).fetchone()[0]
  5599. conn.close()
  5600. check(rejected_report is None or rejected_report == "",
  5601. "reject/revise leaves the goal row clean (no report leaked, S1)")
  5602. # Round 2: submit again and accept.
  5603. fake.goal_script = [("done", "# Completion v2\n\nThe flange ships, with docs.")]
  5604. conn = db()
  5605. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  5606. " priority, completed_at, created_at) values (1, ?, 'task',"
  5607. " 'Warmup2', 'done', 5,"
  5608. " strftime('%s','now'),"
  5609. " strftime('%s','now','-30 seconds'))", (goal1,))
  5610. conn.commit()
  5611. conn.close()
  5612. check(wait_for(lambda: goal_state(goal1)["status"] == "completion_review" or False,
  5613. timeout=60, what="resubmitted completion") is not None,
  5614. "the agent resubmits its completion after feedback")
  5615. state = goal_state(goal1)
  5616. # Regression (plan-15 followup): the daemon's done-park ALSO pushes a
  5617. # review-kind block payload (question "Goal completion review", the
  5618. # real daemon's wording) after the done entry raised the completion
  5619. # row — the two paths must converge on ONE row, not twin reviews.
  5620. fake.push_results("blocked", block={
  5621. "question": "Goal completion review", "type": "review",
  5622. "body": "# Completion v2\n\nThe flange ships, with docs.",
  5623. "options": None})
  5624. conn = db()
  5625. rows = conn.execute(
  5626. "select count(*) from task_blocks where task_id = ?"
  5627. " and answer is null and type in ('completion','review')",
  5628. (run_task,)).fetchone()[0]
  5629. conn.close()
  5630. check(rows == 1,
  5631. "the daemon's review-kind completion push adopts the pending row (no twin)")
  5632. state = goal_state(goal1)
  5633. review_family_in_open = [b for b in state.get("open_blocks", [])
  5634. if b.get("is_completion_review")]
  5635. check(state["completion_pending"] is True and len(review_family_in_open) == 1,
  5636. "the pending completion review renders ONCE — as the rich attention block")
  5637. fake.pending_block = None
  5638. # Raise-side single-row invariant (the render guard and the
  5639. # twin-answer sweep are gone — fresh DBs cannot hold pre-dedupe
  5640. # twins, and 4884259's raise-side cross-dedupe keeps it that way):
  5641. # a REDELIVERED review-kind completion push adopts the same pending
  5642. # row instead of stacking a twin.
  5643. fake.push_results("blocked", block={
  5644. "question": "Goal completion review", "type": "review",
  5645. "body": "# Completion v2\n\nThe flange ships, with docs.",
  5646. "options": None})
  5647. fake.pending_block = None
  5648. conn = db()
  5649. rows = conn.execute(
  5650. "select count(*) from task_blocks where task_id = ?"
  5651. " and answer is null and type in ('completion','review')",
  5652. (run_task,)).fetchone()[0]
  5653. conn.close()
  5654. check(rows == 1,
  5655. "a redelivered review-kind push adopts the pending row (raise-side single-row invariant)")
  5656. # Plan 15 C4: the completion-accept hard gate — the live probe
  5657. # flags still report repob's branch unpushed, so the operator's
  5658. # accept REFUSES with origin behind.
  5659. refusal = action_notify(act(auth, state["completion_pending_block"]["answer_action"],
  5660. {"answer": "Review approved. Continue with the task."}))
  5661. check(goal_state(goal1)["status"] == "completion_review",
  5662. "the accept REFUSES while origin is behind (hard gate, live flags)")
  5663. # One parser, one label: the gate's refusal names the SAME repo-
  5664. # qualified unpushed row the chips render — both surfaces read
  5665. # GoalService.parse_goal_branches (the gate-vs-chips divergence is
  5666. # structurally gone).
  5667. branches = {(b["branch"], b["pushed"]) for b in goal_state(goal1)["push_branches"]}
  5668. check("repob: goal/flange" in (refusal or "")
  5669. and ("repob: goal/flange", False) in branches
  5670. and ("repoa: goal/flange", True) in branches,
  5671. "the refusal and the chips read ONE parser (same labels, same flags)")
  5672. # Push the branch daemon-side and probe again — the flags flip
  5673. # live (no goal-row write), and the accept goes through.
  5674. fake.status_extra = {"goal_branches": [
  5675. {"repo": "repoa", "branch": "goal/flange", "pushed": True},
  5676. {"repo": "repob", "branch": "goal/flange", "pushed": True}]}
  5677. act(auth, fake_card["refresh"], {})
  5678. check(wait_for(lambda: (goal_state(goal1).get("push_branches") or [])
  5679. and all(b["pushed"] for b in goal_state(goal1)["push_branches"])
  5680. or False, timeout=30, what="pushed flags land") is not None,
  5681. "the push chips derive from the LIVE probe flags")
  5682. conn = db()
  5683. no_push_column = conn.execute(
  5684. "select count(*) from pragma_table_info('goals')"
  5685. " where name = 'branch_push_state'").fetchone()[0] == 0
  5686. conn.close()
  5687. check(no_push_column,
  5688. "no stored push snapshot exists (F9: the goal row never records it)")
  5689. state = goal_state(goal1)
  5690. # The passing accept posts the verdict MARKER (the goal page's
  5691. # accept form shape, plan 16 S2) — the server resolves the
  5692. # completion kind and stores the stable approval wording.
  5693. act(auth, state["completion_pending_block"]["answer_action"],
  5694. {"verdict": "accept"})
  5695. check(wait_for(lambda: goal_state(goal1)["status"] == "complete" or False,
  5696. timeout=30, what="accepted completion completes") is not None,
  5697. "accepting the completion completes the goal once origin is current")
  5698. state = goal_state(goal1)
  5699. conn = db()
  5700. accepted_report = conn.execute(
  5701. "select completion_report from goals where id = ?", (goal1,)).fetchone()[0]
  5702. conn.close()
  5703. check(state["terminal"] is True and state.get("cancel") is None
  5704. and accepted_report == "# Completion v2\n\nThe flange ships, with docs."
  5705. and "# Completion v2" in state["completion_report"],
  5706. "a complete goal is terminal with the WINNING block's body as its report (S1)")
  5707. check(wait_for(lambda: task_state(auth, run_task)["status"] == "done" or False,
  5708. timeout=30, what="goal run task closes") is not None,
  5709. "approving the completion closes the goal-run task done")
  5710. conn = db()
  5711. twins_left = conn.execute(
  5712. "select count(*) from task_blocks where task_id = ?"
  5713. " and answer is null and type in ('completion','review')",
  5714. (run_task,)).fetchone()[0]
  5715. conn.close()
  5716. check(twins_left == 0,
  5717. "the verdict answered the pending completion-family row (single-row invariant)")
  5718. print("== plan 15 C3: the narrative derives from the recorded shape ==")
  5719. # Content equivalence with the old projection on this run's exact
  5720. # shape: every kind the goal_events projection produced, keyed the
  5721. # same way, plus the watermark and no-ingest guarantees.
  5722. narrative = goal_state(goal1)["events"]
  5723. kinds = [e["kind"] for e in narrative]
  5724. for expected in ("created", "started", "plan-submitted", "plan-rejected",
  5725. "plan-approved", "task-created", "task-done",
  5726. "completion-submitted", "completion-rejected", "goal-approved"):
  5727. check(expected in kinds,
  5728. "the derived narrative carries the %s row" % expected)
  5729. check(all(k != "task-enqueued" and k != "resumed" and k != "retry" for k in kinds),
  5730. "timestamp-less bookkeeping kinds never return")
  5731. stamps = [e["at_display"] for e in narrative if e.get("at_display")]
  5732. check(stamps == sorted(stamps, reverse=True),
  5733. "the narrative reads newest first")
  5734. conn = db()
  5735. no_event_table = conn.execute(
  5736. "select count(*) from sqlite_master where type = 'table'"
  5737. " and name = 'goal_events'").fetchone()[0] == 0
  5738. conn.close()
  5739. check(no_event_table,
  5740. "the goal_events table is gone (no narrative rows on ingest)")
  5741. print("== plan 12: cancel cascades to the goal's tasks ==")
  5742. goal2 = create_goal({"project_id": "1", "title": "Doomed goal",
  5743. "brief": "This goal will be cancelled.",
  5744. "branch_name": "goal/doomed"})
  5745. fake.goal_script = [("suspend",)]
  5746. act(auth, goal_state(goal2)["start"], {})
  5747. conn = db()
  5748. run2 = conn.execute("select id from tasks where goal_id = ? and kind = 'goal_run'",
  5749. (goal2,)).fetchone()[0]
  5750. conn.close()
  5751. check(wait_for(lambda: task_state(auth, run2)["status"] == "suspended" or False,
  5752. timeout=60, what="doomed goal agent parks") is not None,
  5753. "the doomed goal's agent parks")
  5754. conn = db()
  5755. agent_session2 = conn.execute(
  5756. "select id from sessions where task_id = ? and ended_at is null",
  5757. (run2,)).fetchone()[0]
  5758. conn.close()
  5759. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5760. "session_id": agent_session2, "title": "Doomed draft", "mandate": "m"})
  5761. doomed_draft = int(body["task_id"])
  5762. doomed_queued_task = None
  5763. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5764. "session_id": agent_session2, "title": "Doomed runner", "mandate": "m"})
  5765. doomed_runner = int(body["task_id"])
  5766. saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  5767. {"session_id": agent_session2, "task_id": doomed_runner})
  5768. act(auth, goal_state(goal2)["cancel"], {})
  5769. check(goal_state(goal2)["status"] == "cancelled",
  5770. "the goal cancels from active (parked-agent) state")
  5771. check(task_state(auth, run2)["status"] == "failed",
  5772. "the cascade cancels the goal agent's run task")
  5773. check(wait_for(lambda: task_state(auth, doomed_runner)["status"] == "failed"
  5774. or False, timeout=30, what="cascade cancels the queued task") is not None,
  5775. "the cascade cancels the goal's queued task")
  5776. check(not any(t["id"] == doomed_draft
  5777. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5778. "the cascade deletes the goal's draft tasks")
  5779. # A cancelled goal frees its branch name.
  5780. reuse = create_goal({"project_id": "1", "title": "Reused name",
  5781. "brief": "b", "branch_name": "goal/doomed"})
  5782. check(reuse > goal2, "a cancelled goal's branch name is reusable")
  5783. print("== plan 13 B3: goal failure cascades to non-terminal tasks ==")
  5784. # A goal holding a draft, a queued task and a working task: the
  5785. # agent's failure cascades like a cancellation — drafts deleted (no
  5786. # orphan stays dispatchable), queued/working cancelled — and the
  5787. # narrative records the cascade.
  5788. collapse = create_goal({"project_id": "1", "title": "Collapse goal",
  5789. "brief": "Fails with tasks in flight.",
  5790. "branch_name": "goal/collapse"})
  5791. fake.goal_script = [("suspend",)]
  5792. act(auth, goal_state(collapse)["start"], {})
  5793. conn = db()
  5794. run3 = conn.execute("select id from tasks where goal_id = ? and kind = 'goal_run'",
  5795. (collapse,)).fetchone()[0]
  5796. conn.close()
  5797. check(wait_for(lambda: task_state(auth, run3)["status"] == "suspended" or False,
  5798. timeout=60, what="collapse goal agent parks") is not None,
  5799. "the collapse goal's agent parks first")
  5800. conn = db()
  5801. run3_session = conn.execute(
  5802. "select id from sessions where task_id = ? and ended_at is null",
  5803. (run3,)).fetchone()[0]
  5804. conn.close()
  5805. def agent_task(title):
  5806. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5807. "session_id": run3_session, "title": title, "mandate": "m"})
  5808. task_id = int(body["task_id"])
  5809. saddle_api("POST", "/api/saddle/task/enqueue", fake_token,
  5810. {"session_id": run3_session, "task_id": task_id})
  5811. return task_id
  5812. status, body = saddle_api("POST", "/api/saddle/task/create", fake_token, {
  5813. "session_id": run3_session, "title": "Collapse draft", "mandate": "m"})
  5814. collapse_draft = int(body["task_id"]) # stays draft (never enqueued)
  5815. collapse_queued = agent_task("Collapse queued")
  5816. collapse_worker = agent_task("Collapse worker")
  5817. # Both queued tasks race for the one saddle; freeze the daemon the
  5818. # moment the first dispatches so one stays genuinely WORKING (and
  5819. # the other queued) when the goal fails.
  5820. fake.hold_state = True
  5821. def collapse_working():
  5822. for task_id in (collapse_queued, collapse_worker):
  5823. if task_state(auth, task_id)["status"] == "working":
  5824. return task_id
  5825. return False
  5826. running_one = wait_for(collapse_working, timeout=60, what="a collapse task works")
  5827. check(running_one is not None,
  5828. "a collapse task reaches working before the failure")
  5829. queued_one = collapse_worker if running_one == collapse_queued else collapse_queued
  5830. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  5831. {"session_id": run3_session, "state": "failed",
  5832. "summary": "the foundation crumbled"})
  5833. check(status == 200 and goal_state(collapse)["status"] == "failed",
  5834. "the agent's failure fails the goal")
  5835. check(task_state(auth, run3)["status"] == "failed",
  5836. "the failure fails the goal agent's run task")
  5837. check(wait_for(lambda: task_state(auth, queued_one)["status"] == "failed"
  5838. and task_state(auth, running_one)["status"] == "failed" or False,
  5839. timeout=30, what="failure cascade settles") is not None,
  5840. "the failure cascade cancels the queued and working tasks")
  5841. check(not any(t["id"] == collapse_draft
  5842. for t in slot_public(auth, "/tasks", "tasks")["tasks"]),
  5843. "the failure cascade deletes the goal's draft tasks")
  5844. state = goal_state(collapse)
  5845. check(any(e["kind"] == "cascade" for e in state["events"]),
  5846. "the narrative records the failure cascade")
  5847. check(state["draft_tasks"] == 0 and state["queued_tasks"] == 0,
  5848. "nothing under the failed goal stays dispatchable (no orphan drafts)")
  5849. check(len([e for e in state["events"] if e["kind"] == "goal-failed"]) == 1,
  5850. "the failing goal records exactly one goal-failed event")
  5851. # Plan 16 S1: the FAILURE report keeps its goal-side home (failure
  5852. # is terminal — no pending duplication exists, so unlike the
  5853. # completion report it is written at failure time).
  5854. conn = db()
  5855. failure_report = conn.execute(
  5856. "select completion_report from goals where id = ?", (collapse,)).fetchone()[0]
  5857. conn.close()
  5858. check(failure_report == "the foundation crumbled",
  5859. "fail_goal's failure report keeps its goal-side home (S1)")
  5860. # Plan 16 S4: the narrative renders the task-failed rows from the
  5861. # terminal summary's lead — the run thread carries NO duplicate
  5862. # agent comment of the goal failure text.
  5863. failed_rows = [e for e in state["events"] if e["kind"] == "task-failed"]
  5864. check(failed_rows
  5865. and all(": Cancelled by user" in e["text"] for e in failed_rows),
  5866. "task-failed narrative rows render the summary lead (S4: summary is the terminal cache)")
  5867. run_comments = [c for c in task_state(auth, run3)["comments"]
  5868. if c["author"] == "agent"]
  5869. check(not any("the foundation crumbled" in c["body"] for c in run_comments),
  5870. "the goal failure text never duplicates as an agent comment (S4)")
  5871. fake.hold_state = False
  5872. print("== plan 12: auto-enqueue-after for human tasks ==")
  5873. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5874. "project_id": "1", "title": "Predecessor task", "priority": "4"})
  5875. predecessor = task_id_of("Predecessor task")
  5876. enqueue_task(auth, predecessor)
  5877. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5878. "project_id": "1", "title": "Successor task", "priority": "4",
  5879. "enqueue_after_task_id": str(predecessor)})
  5880. successor = task_id_of("Successor task")
  5881. check(task_state(auth, successor)["status"] == "draft"
  5882. and task_state(auth, successor).get("enqueue_after_task_id") == predecessor,
  5883. "a human task can carry an auto-enqueue predecessor")
  5884. check(wait_task_done(auth, predecessor, timeout=60) is not None,
  5885. "the predecessor completes")
  5886. check(wait_for(lambda: task_state(auth, successor)["status"] in
  5887. ("queued", "assigned", "working") or False,
  5888. timeout=30, what="successor auto-enqueues") is not None,
  5889. "the done predecessor auto-enqueues its dependent")
  5890. # Cycle validation refuses a predecessor chain that loops.
  5891. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5892. "project_id": "1", "title": "Cycle A", "priority": "4"})
  5893. cycle_a = task_id_of("Cycle A")
  5894. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5895. "project_id": "1", "title": "Cycle B", "priority": "4",
  5896. "enqueue_after_task_id": str(cycle_a)})
  5897. cycle_b = task_id_of("Cycle B")
  5898. cycle_directives = act(auth, task_state(auth, cycle_a)["update"], {
  5899. "title": "Cycle A", "description": "x", "priority": "4",
  5900. "enqueue_after_task_id": str(cycle_b)})
  5901. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  5902. and "cycle" in (d.get("message") or "").lower()
  5903. for d in cycle_directives),
  5904. "a predecessor cycle rejects with a naming error")
  5905. # A failed predecessor leaves the dependent in draft.
  5906. fake.fail_next = True
  5907. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5908. "project_id": "1", "title": "Failing predecessor", "priority": "1"})
  5909. failing_pred = task_id_of("Failing predecessor")
  5910. enqueue_task(auth, failing_pred)
  5911. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  5912. "project_id": "1", "title": "Stranded successor", "priority": "4",
  5913. "enqueue_after_task_id": str(failing_pred)})
  5914. stranded = task_id_of("Stranded successor")
  5915. check(wait_for(lambda: task_state(auth, failing_pred)["status"] == "failed"
  5916. or False, timeout=60, what="failing predecessor fails") is not None,
  5917. "the scripted-failure predecessor fails")
  5918. check(quiet_window(quiet_seconds(),
  5919. lambda: task_state(auth, stranded)["status"] == "draft",
  5920. "failed predecessor leaves the draft"),
  5921. "a failed predecessor leaves its dependent in draft")
  5922. # Successor cleanup: let the queued successor finish so the
  5923. # shard's app shuts down with an empty queue.
  5924. check(wait_task_done(auth, successor, timeout=90) is not None,
  5925. "the auto-enqueued successor completes")
  5926. print("== feedback: context_update carries rule/note deltas on resume ==")
  5927. # A standalone task parks on a question; while it is parked a rule
  5928. # is attached to the project and a note lands; the resuming
  5929. # assignment carries both as the context_update markdown turn.
  5930. probe_id = create_queued(auth, {"project_id": "1", "title": "Context probe",
  5931. "priority": "4"})
  5932. check(wait_for(lambda: fake.running_task == probe_id
  5933. and task_state(auth, probe_id)["status"] == "working" or False,
  5934. timeout=60, what="probe task runs") is not None,
  5935. "the probe task dispatches")
  5936. fake.set_state("blocked")
  5937. fake.push_results("blocked", block={"type": "question",
  5938. "question": "Which database dialect?"})
  5939. check(wait_for(lambda: task_state(auth, probe_id)["status"] == "blocked" or False,
  5940. timeout=60, what="probe task blocks") is not None,
  5941. "the probe task parks on its question")
  5942. detail = task_state(auth, probe_id)
  5943. open_block = [b for b in detail["blocks"] if not b["answered"]][0]
  5944. # Backdate the parked round's start: stamps are second-resolution
  5945. # epochs, and the delta compares strictly-later — the park must
  5946. # span a real interval like an operator's would.
  5947. conn = db()
  5948. conn.execute("update sessions set started_at = strftime('%s','now') - 60"
  5949. " where id = (select min(id) from sessions where task_id = ?)",
  5950. (probe_id,))
  5951. conn.commit()
  5952. conn.close()
  5953. # While parked: a new rule attached to the project + a new note.
  5954. rules_state = slot_public(auth, "/rules", "rules")
  5955. act(auth, rules_state["create"], {
  5956. "name": "Nightly gate", "body": "Every PR must pass the nightly suite before merge."})
  5957. conn = db()
  5958. rule_id = conn.execute("select id from rules where name = 'Nightly gate'").fetchone()[0]
  5959. conn.close()
  5960. act(auth, slot_public(auth, "/projects/1", "project")["attach_rule"],
  5961. {"rule_id": str(rule_id)})
  5962. conn = db()
  5963. conn.execute("insert into project_notes (project_id, body, created_at)"
  5964. " values (1, 'The demo repo moved its CI to nightly builds.',"
  5965. " strftime('%s','now'))")
  5966. conn.commit()
  5967. check(conn.execute("select count(*) from rule_projects where rule_id = ?",
  5968. (rule_id,)).fetchone()[0] == 1,
  5969. "the rule attaches to the project while the task is parked")
  5970. conn.close()
  5971. probe_assignments = len([p for p in fake.start_payloads
  5972. if int(p.get("task", {}).get("id") or 0) == probe_id])
  5973. act(auth, open_block["answer_action"], {"answer": "postgres"})
  5974. check(wait_for(lambda: len([p for p in fake.start_payloads
  5975. if int(p.get("task", {}).get("id") or 0) == probe_id])
  5976. > probe_assignments or False, timeout=60,
  5977. what="probe task resumes") is not None,
  5978. "answering the block resumes the probe task")
  5979. probe_resume = [p for p in fake.start_payloads
  5980. if int(p.get("task", {}).get("id") or 0) == probe_id][-1]
  5981. delta = probe_resume.get("context_update") or ""
  5982. check("Rules changed" in delta and "Nightly gate" in delta
  5983. and "nightly suite" in delta,
  5984. "the resume's context_update summarises the newly attached rule")
  5985. check("New project notes" in delta and "nightly builds" in delta,
  5986. "the resume's context_update summarises the new project note")
  5987. check("Plan approved" not in delta,
  5988. "standalone resumes carry no plan section")
  5989. check(wait_task_done(auth, probe_id, timeout=60) is not None,
  5990. "the probe task completes after its resume")
  5991. # =============================================================================
  5992. # Bundle: replay — plan 13 B1/B2: the daemon-global entry dedup and the
  5993. # idempotent terminal/narrative projections. Replays the live-failure
  5994. # post-mortem shapes directly against the push channels: an outbox
  5995. # redelivery arriving under the WRONG session id after churn (and after
  5996. # a web restart), and repeated failure pushes that must still project
  5997. # exactly once. Includes this shard's one deliberate app restart (the
  5998. # dedup must survive it — it is database state, not memory).
  5999. # =============================================================================
  6000. def bundle_replay(ctx):
  6001. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  6002. app = ctx.app
  6003. def rows_for(session):
  6004. conn = db()
  6005. try:
  6006. return conn.execute(
  6007. "select count(*) from session_commands where session_id = ?",
  6008. (session,)).fetchone()[0]
  6009. finally:
  6010. conn.close()
  6011. def dedup_rows():
  6012. conn = db()
  6013. try:
  6014. return conn.execute("select count(*) from saddle_entry_dedup").fetchone()[0]
  6015. finally:
  6016. conn.close()
  6017. def open_session_on_fake(task_id):
  6018. """A fixture open session row on the shard's saddle (the churn
  6019. shape: a fresh web-side run row the daemon never really drove)."""
  6020. conn = db()
  6021. try:
  6022. conn.execute(
  6023. "insert into sessions (task_id, saddle_id, started_at)"
  6024. " values (?, ?, strftime('%s','now'))", (task_id, fake_id))
  6025. conn.commit()
  6026. return conn.execute(
  6027. "select max(id) from sessions where task_id = ?",
  6028. (task_id,)).fetchone()[0]
  6029. finally:
  6030. conn.close()
  6031. print("== plan 13 B1: entry dedup is daemon-global, not per-session ==")
  6032. # A first task runs to completion; its session is the replay source.
  6033. first = create_queued(auth, {"project_id": "1", "title": "Replay source task",
  6034. "priority": "2"})
  6035. check(wait_task_done(auth, first, timeout=60) is not None,
  6036. "the replay-source task completes")
  6037. conn = db()
  6038. src_session = conn.execute(
  6039. "select max(id) from sessions where task_id = ?", (first,)).fetchone()[0]
  6040. conn.close()
  6041. # The outbox batch: two command entries the daemon already
  6042. # delivered once (their ids landed with the source session).
  6043. burst = [
  6044. {"id": 5001, "command": "make test", "output": "ok", "exit_code": 0,
  6045. "type": "command", "timestamp": "2026-09-11T00:00:00Z"},
  6046. {"id": 5002, "command": "grep -r flange src/", "output": "src/flange.vala",
  6047. "exit_code": 0, "type": "command", "timestamp": "2026-09-11T00:00:01Z"},
  6048. ]
  6049. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6050. {"session_id": src_session, "state": "done",
  6051. "entries": burst})
  6052. check(status == 200 and rows_for(src_session) >= 2,
  6053. "the entries batch stores under its session")
  6054. stored_once = rows_for(src_session)
  6055. dedup_after_first = dedup_rows()
  6056. # Redelivery under the SAME session: consumed, nothing new.
  6057. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6058. {"session_id": src_session, "state": "done",
  6059. "entries": burst})
  6060. check(status == 200 and rows_for(src_session) == stored_once
  6061. and dedup_rows() == dedup_after_first,
  6062. "a same-session redelivery stores nothing new (consumed silently)")
  6063. # Session churn: a brand-new session id on the same saddle replays
  6064. # the SAME entry ids — the post-mortem's mis-keyed outbox send.
  6065. # The entries' ids already populated another session, so the push
  6066. # may not create rows here either.
  6067. conn = db()
  6068. conn.execute(
  6069. "insert into tasks (project_id, title, status, priority, created_at,"
  6070. " completed_at) values (1, 'Churn target task', 'done', 5,"
  6071. " strftime('%s','now'), strftime('%s','now'))")
  6072. conn.commit()
  6073. churn_task = conn.execute(
  6074. "select max(id) from tasks where title = 'Churn target task'").fetchone()[0]
  6075. conn.close()
  6076. churn_session = open_session_on_fake(churn_task)
  6077. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6078. {"session_id": churn_session, "state": "done",
  6079. "entries": burst})
  6080. check(status == 200 and rows_for(churn_session) == 0,
  6081. "replay-under-wrong-session stores nothing new (daemon-global dedup)")
  6082. check(dedup_rows() == dedup_after_first,
  6083. "the consumed redelivery claims no fresh dedup rows")
  6084. # A fresh entry id under the churned session DOES store — the dedup
  6085. # keys on the entry id, never on the session.
  6086. fresh = [{"id": 5003, "command": "git status", "output": "clean",
  6087. "exit_code": 0, "type": "command", "timestamp": "2026-09-11T00:00:02Z"}]
  6088. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6089. {"session_id": churn_session, "state": "done",
  6090. "entries": fresh})
  6091. check(status == 200 and rows_for(churn_session) == 1
  6092. and dedup_rows() == dedup_after_first + 1,
  6093. "a fresh entry id stores under any session of its saddle")
  6094. # Web restart: the dedup survives (database state, not memory).
  6095. app.terminate()
  6096. app.wait(timeout=10)
  6097. app = start_app()
  6098. auth = login("admin", "adminpass123")
  6099. ctx.app = app # teardown tracks the restarted process
  6100. ctx.auth = auth
  6101. # The restart wiped the in-memory ask bookkeeping; the daemon
  6102. # re-establishes sleeping with a fresh ask (the real daemon's
  6103. # idle-awake ask / 15-minute safety self-ask).
  6104. fake.ask_now()
  6105. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6106. {"session_id": churn_session, "state": "done",
  6107. "entries": burst + fresh})
  6108. check(status == 200 and rows_for(churn_session) == 1
  6109. and rows_for(src_session) == stored_once,
  6110. "a post-restart redelivery still stores nothing (dedup is persistent)")
  6111. print("== plan 13 B2: duplicate failed entries project once (task) ==")
  6112. # The post-mortem's honest burst: the same failure entry redelivered
  6113. # under a churned session AND a second, DISTINCT failure entry id
  6114. # in the same session — one transition, one comment, ever.
  6115. def agent_comments(task_id, body=None):
  6116. conn = db()
  6117. try:
  6118. if body is None:
  6119. return conn.execute(
  6120. "select count(*) from task_comments"
  6121. " where task_id = ? and author = 'agent'",
  6122. (task_id,)).fetchone()[0]
  6123. return conn.execute(
  6124. "select count(*) from task_comments"
  6125. " where task_id = ? and author = 'agent' and body = ?",
  6126. (task_id, body)).fetchone()[0]
  6127. finally:
  6128. conn.close()
  6129. conn = db()
  6130. conn.execute(
  6131. "insert into tasks (project_id, title, status, priority, created_at)"
  6132. " values (1, 'Burst failure task', 'working', 5, strftime('%s','now'))")
  6133. conn.commit()
  6134. burst_task = conn.execute(
  6135. "select max(id) from tasks where title = 'Burst failure task'").fetchone()[0]
  6136. conn.close()
  6137. burst_session = open_session_on_fake(burst_task)
  6138. first_fail = [{"id": 6001, "command": "saddle failure",
  6139. "output": "bash -n rejected the script", "exit_code": 1,
  6140. "type": "failed", "timestamp": "2026-09-11T00:01:00Z"}]
  6141. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6142. {"session_id": burst_session, "state": "failed",
  6143. "entries": first_fail,
  6144. "summary": "bash -n rejected the script"})
  6145. check(status == 200
  6146. and task_state(auth, burst_task)["status"] == "failed",
  6147. "the failure entry + state pair fails the task")
  6148. check(agent_comments(burst_task, "bash -n rejected the script") == 0
  6149. and "bash -n rejected the script"
  6150. in (task_state(auth, burst_task).get("summary") or ""),
  6151. "the failure explanation lives ONCE — in tasks.summary, the terminal cache (S4: no duplicate agent comment)")
  6152. # The burst: a DISTINCT failure entry id in the same session, plus
  6153. # both ids redelivered under a churned session — nothing re-runs.
  6154. second_fail = [{"id": 6002, "command": "saddle failure",
  6155. "output": "bash -n rejected the script", "exit_code": 1,
  6156. "type": "failed", "timestamp": "2026-09-11T00:01:01Z"}]
  6157. churned_burst = open_session_on_fake(burst_task)
  6158. for target in (burst_session, churned_burst):
  6159. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6160. {"session_id": target, "state": "failed",
  6161. "entries": first_fail + second_fail,
  6162. "summary": "bash -n rejected the script"})
  6163. check(status == 200,
  6164. "the burst push under %s is consumed, not rejected" % (
  6165. "its session" if target == burst_session else "a churned session"))
  6166. check(task_state(auth, burst_task)["status"] == "failed"
  6167. and agent_comments(burst_task) == 0
  6168. and "bash -n rejected the script"
  6169. in (task_state(auth, burst_task).get("summary") or ""),
  6170. "duplicate failed entries leave one transition, one summary, zero agent comments (S4)")
  6171. print("== plan 13 B2: goal failure projects once ==")
  6172. # Goal context: `saddle failure` fails the goal ONCE — the 115
  6173. # goal-failed events of the live failure are structurally gone.
  6174. def goal_state(goal_id):
  6175. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  6176. def goal_failed_events(goal_id):
  6177. # Plan 15 C3: the narrative derives at read time — the
  6178. # failed-goal row IS the goal-failed record (one row, ever).
  6179. return len([e for e in goal_state(goal_id)["events"]
  6180. if e["kind"] == "goal-failed"])
  6181. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  6182. "project_id": "1", "title": "Burst goal", "brief": "Fails honestly.",
  6183. "branch_name": "goal/burst"})
  6184. conn = db()
  6185. burst_goal = conn.execute(
  6186. "select id from goals where title = 'Burst goal'").fetchone()[0]
  6187. conn.close()
  6188. fake.goal_script = [("suspend",)]
  6189. act(auth, goal_state(burst_goal)["start"], {})
  6190. conn = db()
  6191. run_task = conn.execute(
  6192. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  6193. (burst_goal,)).fetchone()[0]
  6194. conn.close()
  6195. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6196. or False, timeout=60, what="burst goal agent parks") is not None,
  6197. "the burst goal's agent parks first")
  6198. conn = db()
  6199. run_session = conn.execute(
  6200. "select id from sessions where task_id = ? and ended_at is null",
  6201. (run_task,)).fetchone()[0]
  6202. conn.close()
  6203. goal_fail = [{"id": 7001, "command": "saddle failure",
  6204. "output": "the harness collapsed", "exit_code": 1,
  6205. "type": "failed", "timestamp": "2026-09-11T00:02:00Z"},
  6206. {"id": 7002, "command": "saddle failure",
  6207. "output": "the harness collapsed", "exit_code": 1,
  6208. "type": "failed", "timestamp": "2026-09-11T00:02:01Z"}]
  6209. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6210. {"session_id": run_session, "state": "failed",
  6211. "entries": goal_fail, "summary": "the harness collapsed"})
  6212. check(status == 200 and goal_state(burst_goal)["status"] == "failed",
  6213. "the goal agent's failure fails the goal")
  6214. check(goal_failed_events(burst_goal) == 1,
  6215. "a two-entry failure burst records exactly one goal-failed event")
  6216. # Redeliveries — same ids under the run's session AND under a
  6217. # churned session — plus the bare failed state again: still one.
  6218. churned_run = open_session_on_fake(run_task)
  6219. for target in (run_session, churned_run):
  6220. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6221. {"session_id": target, "state": "failed",
  6222. "entries": goal_fail,
  6223. "summary": "the harness collapsed"})
  6224. check(status == 200, "the goal-failure redelivery under %s is consumed"
  6225. % ("its session" if target == run_session else "a churned session"))
  6226. check(goal_state(burst_goal)["status"] == "failed"
  6227. and goal_failed_events(burst_goal) == 1,
  6228. "redelivered failures never re-run the goal failure (one event, ever)")
  6229. check(task_state(auth, run_task)["status"] == "failed",
  6230. "the goal-run task stays failed after the replays")
  6231. conn = db()
  6232. burst_blocks = conn.execute(
  6233. "select count(*) from task_blocks where task_id = ?", (run_task,)
  6234. ).fetchone()[0]
  6235. conn.close()
  6236. check(burst_blocks == 0,
  6237. "the goal-failed path raises ZERO blocks (nothing pins the pile)")
  6238. print("== plan 13 B4: the comment projection stores the body ==")
  6239. # The heredoc shape: the command is the pipe invocation, the OUTPUT
  6240. # is the body. The projections must carry the body — the command
  6241. # echo never becomes comment text, and the literal `saddle
  6242. # comment` string never renders outside the terminal.
  6243. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  6244. "project_id": "1", "title": "Comment goal", "brief": "Reports cleanly.",
  6245. "branch_name": "goal/comment"})
  6246. conn = db()
  6247. comment_goal = conn.execute(
  6248. "select id from goals where title = 'Comment goal'").fetchone()[0]
  6249. conn.close()
  6250. fake.goal_script = [("suspend",)]
  6251. act(auth, goal_state(comment_goal)["start"], {})
  6252. conn = db()
  6253. comment_run = conn.execute(
  6254. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  6255. (comment_goal,)).fetchone()[0]
  6256. conn.close()
  6257. check(wait_for(lambda: task_state(auth, comment_run)["status"] == "suspended"
  6258. or False, timeout=60, what="comment goal agent parks") is not None,
  6259. "the comment goal's agent parks")
  6260. conn = db()
  6261. comment_session = conn.execute(
  6262. "select id from sessions where task_id = ? and ended_at is null",
  6263. (comment_run,)).fetchone()[0]
  6264. conn.close()
  6265. comment_body = "The flange weld holds. First sentence carries the information."
  6266. comment_entry = [{"id": 8001, "command": "cat << 'EOF' | saddle comment",
  6267. "output": comment_body, "exit_code": 0, "type": "comment",
  6268. "timestamp": "2026-09-11T00:03:00Z"}]
  6269. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6270. {"session_id": comment_session, "state": "suspended",
  6271. "entries": comment_entry})
  6272. check(status == 200, "the comment entry push is accepted")
  6273. conn = db()
  6274. task_comment_bodies = [r[0] for r in conn.execute(
  6275. "select body from task_comments where task_id = ?", (comment_run,))]
  6276. tables = {r[0] for r in conn.execute(
  6277. "select name from sqlite_master where type = 'table'").fetchall()}
  6278. conn.close()
  6279. check(task_comment_bodies == [comment_body],
  6280. "the run task's comment stores the body, not the command echo")
  6281. check("goal_comments" not in tables,
  6282. "the goal_comments table is gone (the run task's rows are the thread)")
  6283. narrative_comments = [e["text"] for e in goal_state(comment_goal)["events"]
  6284. if e["kind"] == "comment"]
  6285. check(len(narrative_comments) == 1
  6286. and narrative_comments[0].startswith("The flange weld holds.")
  6287. and "saddle comment" not in narrative_comments[0]
  6288. and "EOF" not in narrative_comments[0],
  6289. "the derived narrative's comment rows carry the body text")
  6290. state = goal_state(comment_goal)
  6291. check(state["current_command"] == comment_body,
  6292. "the goal page's current-activity line shows the comment body")
  6293. check(state["comments"] and state["comments"][0]["body"] == comment_body
  6294. and any(e["kind"] == "comment"
  6295. and e["text"].startswith("The flange weld holds.")
  6296. for e in state["events"]),
  6297. "the goal slot carries the body in its comments and narrative")
  6298. page = http_get_page(auth, "/goals/%d" % comment_goal)
  6299. check("saddle comment" not in page,
  6300. "the rendered goal page never shows the command echo")
  6301. check("event.kind == 'comment' ? ' footnote'" in page,
  6302. "the narrative's comment events render with footnote styling")
  6303. check(page.index('stm-markdown="comment.body"')
  6304. < page.index('stm-text="comment.quote"'),
  6305. "the comment card shows the body before the quote")
  6306. # Drain: nothing queued remains for the shard's shutdown.
  6307. check(queued_count() == 0, "the replay shard drains its queue")
  6308. def bundle_goalui(ctx):
  6309. """Plan 14 workstream B + plan 15 C1: the goal supervision surface.
  6310. B1 — goal-run control parity (Retry supervision / Requeue-to-resume
  6311. on the status head, the /tasks/<goal-run-id> redirect, no
  6312. notify-me toggle), B2 — the plan-review remarks queue, B4 —
  6313. sessions.resume_notice + the terminal dropdown/resume panel, B5 —
  6314. page order, effective rules and per-task capability badges, B6 —
  6315. narrative footnote weights. C1 — the single-row block world: the
  6316. goal's blocks ARE the run task's rows (answered from every
  6317. surface through one path; no dual rows, no stragglers, at most
  6318. one review-kind block per verdict path). C4 — the goal page
  6319. batch: one muted head activity line, plan between attention and
  6320. tasks, answered blocks behind an expander, footnote comments.
  6321. C5 — the dashboard deep-link closure: goal pile cards link the
  6322. goal page, every surface settles the single row, and no
  6323. goal-side store exists to hold stragglers.
  6324. """
  6325. auth, fake, fake_id, fake_token = ctx.auth, ctx.fake, ctx.fake_id, ctx.fake_token
  6326. def goal_state(goal_id):
  6327. return slot_public(auth, "/goals/%d" % goal_id, "goal")
  6328. def run_task_of(goal_id):
  6329. conn = db()
  6330. try:
  6331. return int(conn.execute(
  6332. "select id from tasks where goal_id = ? and kind = 'goal_run'",
  6333. (goal_id,)).fetchone()[0])
  6334. finally:
  6335. conn.close()
  6336. def wait_run(status, timeout=60, what="run status"):
  6337. return wait_for(lambda: task_state(auth, run_task_of(goal))["status"] == status
  6338. or False, timeout=timeout, what=what)
  6339. def pile_questions():
  6340. return [b.get("question") for b in
  6341. slot_public(auth, "/", "dashboard")["pinned"]
  6342. if b.get("item_type") == "goal"]
  6343. def open_session(task_id):
  6344. conn = db()
  6345. try:
  6346. row = conn.execute(
  6347. "select id from sessions where task_id = ? and ended_at is null",
  6348. (task_id,)).fetchone()
  6349. return int(row[0]) if row else None
  6350. finally:
  6351. conn.close()
  6352. print("== B1: the goal-run task page redirects to the goal ==")
  6353. fake.goal_script = [("plan", "# Remarks plan\n\n## Steps\n\n1. First move")]
  6354. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  6355. "project_id": "1", "title": "Goalui goal",
  6356. "brief": "Drive the plan-14 goal surface end to end.",
  6357. "branch_name": "goal/goalui"})
  6358. conn = db()
  6359. goal = conn.execute("select id from goals where title = 'Goalui goal'"
  6360. ).fetchone()[0]
  6361. conn.close()
  6362. act(auth, goal_state(goal)["start"], {})
  6363. wait_run("blocked", what="goalui goal agent parks on its plan") # plan review parks blocked
  6364. run_task = run_task_of(goal)
  6365. frames = directives("/tasks/%d" % run_task, auth)
  6366. navigations = [d for d in frames if d.get("type") == "navigate"]
  6367. check(any(d.get("uri") == "/goals/%d" % goal for d in navigations),
  6368. "the goal-run task page redirects to /goals/<id> (navigate directive)")
  6369. check(slot_public(auth, "/tasks/%d" % run_task, "task")["id"] == run_task,
  6370. "the redirect still hydrates the task slot (sealed refresh + API readers)")
  6371. status, page = http("GET", "/tasks/%d" % run_task, headers={
  6372. "X-Statum-Slot": "key=%s; as_at=%s" % (auth["key"], auth["as_at"])}, timeout=15)
  6373. check(status == 200, "the compiled goal-run page serves")
  6374. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  6375. "project_id": "1", "title": "Goalui worker", "priority": "4",
  6376. "description": "A plain worker under no goal."})
  6377. conn = db()
  6378. worker = conn.execute("select id from tasks where title = 'Goalui worker'"
  6379. ).fetchone()[0]
  6380. conn.close()
  6381. check(not [d for d in directives("/tasks/%d" % worker, auth)
  6382. if d.get("type") == "navigate"],
  6383. "worker task pages render normally (no redirect)")
  6384. state = goal_state(goal)
  6385. check("toggle_notify" not in state and state.get("notify") is None,
  6386. "no notify-me toggle on the goal (goals notify unconditionally)")
  6387. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6388. check("Notify me" not in goal_page and "toggle-notify" not in goal_page,
  6389. "the goal page template ships no notify control")
  6390. check(state["branch_name"] == "goal/goalui" and state["base_branch"] == "main"
  6391. and isinstance(state["push_branches"], list)
  6392. and state["priority"] == 3
  6393. and len(state["started_display"]) > 0
  6394. and len(state["agent_saddle"]) > 0,
  6395. "the status head carries the full field set (branch pair, chips list,"
  6396. " priority, timestamps, agent saddle)")
  6397. check("Retry supervision" in goal_page and "Requeue to resume" in goal_page,
  6398. "the status head ships the run-control parity buttons")
  6399. check("status-corner" not in goal_page and "goal complete" not in goal_page
  6400. and goal_page.count("badge-yeehaw") == 1,
  6401. "yeehaw is rows-only (no goal-head corner badge; the row badge remains)")
  6402. check(goal_state(goal)["current_activity"] == "parked awaiting the plan review",
  6403. "the head line reads 'parked awaiting the plan review' while one is open")
  6404. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6405. check(goal_page.index("Goal agent blocks") < goal_page.index("<h3>Plan</h3>")
  6406. < goal_page.index("<h3>Tasks</h3>"),
  6407. "the plan section sits between attention and tasks")
  6408. check("data-plan-review" in goal_page and "Approved plan &amp; revisions" in goal_page,
  6409. "an open review renders expanded beside the collapsed approved-plan expander")
  6410. print("== B2: the plan-review remarks queue ==")
  6411. check(goal_state(goal)["status"] == "plan_review"
  6412. and goal_state(goal)["plan_pending_block"] is not None,
  6413. "the goal sits in plan review with a pending block")
  6414. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6415. review_at = goal_page.index("data-plan-review")
  6416. check(review_at > 0, "the plan review region is marked for the remarks queue")
  6417. check(goal_page.index('data-block-id="goal.plan_pending_block.id"') > 0,
  6418. "the queue keys on the pending goal block id")
  6419. body_at = goal_page.index('data-plan-body')
  6420. remarks_at = goal_page.index("data-plan-remarks")
  6421. check(body_at < remarks_at,
  6422. "the remarks queue renders at the bottom of the plan body")
  6423. for marker in ("data-plan-accept", "data-plan-toggle", "data-plan-submit",
  6424. "data-plan-remove", "plan-popover", "remarksByBlock"):
  6425. check(marker in goal_page, "the remarks queue ships %s" % marker)
  6426. check("(index + 1) + '. '" in goal_page,
  6427. "the rejection payload numbers every queued remark")
  6428. check("rejectOpenByBlock" in goal_page and "statum.afterEvaluate(syncPlanRemarks)" in goal_page,
  6429. "the queue survives pulse refreshes (maps outside statum re-renders)")
  6430. # The rejection payload exactly as the client composes it: the
  6431. # stable verdict wording, then each remark NUMBERED in queue order
  6432. # with its quote prefixed like a comment.
  6433. payload = ("Plan feedback received:\n\n"
  6434. "> ## Steps\n\n1. First move\n\n"
  6435. "1. Add a rollback step\n\n"
  6436. "2. Name the owner of the migration")
  6437. act(auth, goal_state(goal)["plan_pending_block"]["answer_action"],
  6438. {"answer": payload})
  6439. state = goal_state(goal)
  6440. check(state["status"] == "planning",
  6441. "the remarks rejection returns the agent to planning")
  6442. rejected = [r for r in state["plan_revisions"] if r.get("answered")]
  6443. check(any(r["answer"] == payload for r in rejected),
  6444. "the rejection carries the remarks verbatim, in order")
  6445. check(payload.index("1. Add a rollback step") < payload.index("2. Name the owner"),
  6446. "the numbering is queue-ordered")
  6447. print("== B4: resume_notice lands on the resumed session row ==")
  6448. fake.goal_script = [("question", "Which datastore?", ["SQLite", "Redis"])]
  6449. check(wait_for(lambda: goal_state(goal)["status"] == "planning" or False,
  6450. timeout=30, what="rejection observed") is not None,
  6451. "the agent revises")
  6452. # The parked plan agent resumes with the verdict; the next round
  6453. # raises the scripted question.
  6454. check(wait_for(lambda: any(b["question"] == "Which datastore?"
  6455. and not b.get("answered")
  6456. for b in goal_state(goal)["blocks"]) or False,
  6457. timeout=60, what="question raised") is not None,
  6458. "the resumed agent raises its question")
  6459. conn = db()
  6460. notices = dict(conn.execute(
  6461. "select id, resume_notice from sessions where task_id = ?", (run_task,)
  6462. ).fetchall())
  6463. conn.close()
  6464. resumed_ids = [i for i, text in notices.items() if text]
  6465. fresh_ids = [i for i, text in notices.items() if not text]
  6466. check(len(resumed_ids) >= 1 and any("Plan feedback received" in notices[i]
  6467. for i in resumed_ids),
  6468. "the resumed session stores the notice it was allocated")
  6469. check(min(notices) in fresh_ids,
  6470. "session 1 (the fresh opening round) carries no resume notice")
  6471. print("== C1: the single run-task row IS the goal's block ==")
  6472. check("Which datastore?" in pile_questions(),
  6473. "the open goal question pins onto the dashboard pile")
  6474. goal_rows = [b for b in goal_state(goal)["blocks"]
  6475. if b["question"] == "Which datastore?"]
  6476. run_rows = [b for b in task_state(auth, run_task)["blocks"]
  6477. if b["question"] == "Which datastore?"]
  6478. check(len(run_rows) == 1 and len(goal_rows) == 1
  6479. and int(run_rows[0]["id"]) == int(goal_rows[0]["id"]),
  6480. "the goal page and the run task read the SAME single row")
  6481. pile_card = [b for b in slot_public(auth, "/", "dashboard")["pinned"]
  6482. if b.get("question") == "Which datastore?"][0]
  6483. check(pile_card.get("item_type") == "goal"
  6484. and int(pile_card.get("goal_id") or 0) == goal
  6485. and int(pile_card.get("id") or 0) == int(run_rows[0]["id"])
  6486. and pile_card.get("goal_title") == "Goalui goal",
  6487. "the pile card is the run-task row styled as a goal item")
  6488. act(auth, [b for b in goal_state(goal)["blocks"]
  6489. if b["question"] == "Which datastore?" and not b.get("answered")]
  6490. [0]["answer_action"], {"option": "SQLite"})
  6491. conn = db()
  6492. unanswered = conn.execute(
  6493. "select count(*) from task_blocks where question = 'Which datastore?'"
  6494. " and answer is null").fetchone()[0]
  6495. conn.close()
  6496. check(unanswered == 0, "answering from the goal page closes the single row")
  6497. check("Which datastore?" not in pile_questions(),
  6498. "the answered row no longer pins the dashboard pile")
  6499. # The task-page deep link (the AnswerBlockAction API surface)
  6500. # answers the SAME row through the one goal path — there is no
  6501. # second row to sweep and no stale copy can survive.
  6502. conn = db()
  6503. conn.execute("insert into task_blocks (task_id, type, question, created_at)"
  6504. " values (?, 'question', 'Deep link probe?',"
  6505. " strftime('%s','now'))", (run_task,))
  6506. conn.commit()
  6507. conn.close()
  6508. check("Deep link probe?" in pile_questions(),
  6509. "the fixture row pins like any goal question")
  6510. deep_block = [b for b in task_state(auth, run_task)["blocks"]
  6511. if b["question"] == "Deep link probe?" and not b.get("answered")][0]
  6512. act(auth, deep_block["answer_action"], {"answer": "Answered via the deep link"})
  6513. conn = db()
  6514. answered_row = conn.execute(
  6515. "select answer from task_blocks where question = 'Deep link probe?'"
  6516. ).fetchone()[0]
  6517. tables = {r[0] for r in conn.execute(
  6518. "select name from sqlite_master where type = 'table'").fetchall()}
  6519. conn.close()
  6520. check(answered_row == "Answered via the deep link",
  6521. "the task-page deep link answers the same single row (the API path)")
  6522. check("Deep link probe?" not in pile_questions(),
  6523. "the deep-link answer closes the pile card too")
  6524. check("goal_blocks" not in tables,
  6525. "the goal_blocks table is gone (run-task blocks are canonical)")
  6526. print("== C5: deep-link closure on the single-row world ==")
  6527. # The pile card's goal item deep-links the goal page (the answer
  6528. # surface); answering from either surface settled THE row above.
  6529. home_markup = http_get_page(auth, "/")
  6530. check("'/goals/' + blockview.goal_id" in home_markup,
  6531. "the pile card deep-links the goal page for goal items")
  6532. conn = db()
  6533. dupes = conn.execute(
  6534. "select count(*) from (select question from task_blocks where task_id = ?"
  6535. " group by question having count(*) > 1)", (run_task,)).fetchone()[0]
  6536. stragglers = conn.execute(
  6537. "select count(*) from task_blocks where task_id = ? and answer is null",
  6538. (run_task,)).fetchone()[0]
  6539. goal_side_tables = [r[0] for r in conn.execute(
  6540. "select name from sqlite_master where type = 'table'"
  6541. " and name in ('goal_blocks','goal_comments','goal_events')").fetchall()]
  6542. conn.close()
  6543. check(dupes == 0 and stragglers == 0,
  6544. "one row per question on the run task, none left unanswered")
  6545. check(not goal_side_tables,
  6546. "no goal-side store exists — historical stragglers are impossible")
  6547. print("== B4: the terminal session dropdown + resume-info panel ==")
  6548. fake.goal_script = [("suspend",)]
  6549. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6550. or False, timeout=60, what="agent parks suspended") is not None,
  6551. "the agent parks suspended for the requeue scenario")
  6552. terminal = slot_public(auth, "/tasks/%d/terminal" % run_task, "terminal")
  6553. ids = [int(s["id"]) for s in terminal["sessions"]]
  6554. check(ids == sorted(ids, reverse=True),
  6555. "the session dropdown lists newest-first")
  6556. check(int(terminal["session_id"]) == ids[0],
  6557. "the terminal still defaults to the latest session")
  6558. labels = {int(s["id"]): s["label"] for s in terminal["sessions"]}
  6559. check(all(label.startswith("Session #") for label in labels.values()),
  6560. "dropdown labels read 'Session #N — started <time>'")
  6561. # Recompute at the check point: the C1 answers above each
  6562. # resumed the agent too, so the earlier snapshot would go stale.
  6563. conn = db()
  6564. resumed_ids = [int(i) for (i, text) in conn.execute(
  6565. "select id, resume_notice from sessions where task_id = ?",
  6566. (run_task,)).fetchall() if text]
  6567. conn.close()
  6568. resumed_markers = [i for i in ids if "[resumed]" in labels[i]]
  6569. check(set(resumed_markers) == set(resumed_ids),
  6570. "the [resumed] marker rides exactly the notice-carrying sessions")
  6571. notices_by_id = {int(s["id"]): s.get("notice") or "" for s in terminal["sessions"]}
  6572. check("Opening brief" in notices_by_id[min(ids)]
  6573. and "Drive the plan-14 goal surface" in notices_by_id[min(ids)],
  6574. "session 1's panel shows the opening-brief framing (from the goal brief)")
  6575. check(any("Plan feedback received" in (notices_by_id[i] or "") for i in resumed_ids),
  6576. "a resumed session's panel shows the stored resume notice")
  6577. terminal_page = http_get_page(auth, "/tasks/%d/terminal" % run_task)
  6578. check('id="session-select"' in terminal_page
  6579. and "window.terminalPickSession" in terminal_page,
  6580. "the session picker is an options dropdown")
  6581. check('stm-markdown="window.terminalSessionNotice(terminal)"' in terminal_page,
  6582. "the panel renders the selected session's notice as markdown")
  6583. check("No opening brief or resume notice recorded" in terminal_page,
  6584. "the panel ships its graceful empty state")
  6585. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6586. check("resume-notice-panel" in css and "max-height: 200px" in css,
  6587. "the panel is a 200px vertical-scroll strip (stylesheet)")
  6588. print("== B1: requeue-to-resume from the goal head ==")
  6589. conn = db()
  6590. conn.execute("update saddles set status = 'offline' where id = ?", (fake_id,))
  6591. conn.commit()
  6592. conn.close()
  6593. def requeue_offered():
  6594. # Act on the SAME state that satisfied the wait: a second read
  6595. # once raced the scripted daemon's ask reviving the saddle row,
  6596. # and the conditionally-authored action vanished between the
  6597. # two reads (KeyError on act).
  6598. offered = goal_state(goal)
  6599. return offered if offered.get("requeue_run") is not None else False
  6600. state = wait_for(requeue_offered, timeout=30, what="requeue offered")
  6601. check(state is not None,
  6602. "a parked run on a dead saddle offers Requeue-to-resume")
  6603. check(state.get("retry_run") is None,
  6604. "an active goal offers no Retry supervision")
  6605. open_before = open_session(run_task)
  6606. def parked_session_ended():
  6607. if open_before is None:
  6608. return True
  6609. conn = db()
  6610. try:
  6611. return conn.execute(
  6612. "select ended_at is not null from sessions where id = ?",
  6613. (open_before,)).fetchone()[0] == 1
  6614. finally:
  6615. conn.close()
  6616. act(auth, state["requeue_run"], {})
  6617. check(task_state(auth, run_task)["status"] == "queued",
  6618. "the requeue returns the run to the queue")
  6619. # The PARKED session itself must end (the restore-on-dispatch
  6620. # successor may open immediately — the check keys the old row,
  6621. # not the task's transient open-session window).
  6622. check(wait_for(parked_session_ended, timeout=60,
  6623. what="parked session closed") is not None,
  6624. "the requeue closed the parked session (restore-on-dispatch)")
  6625. conn = db()
  6626. conn.execute("update saddles set status = 'idle' where id = ?", (fake_id,))
  6627. conn.commit()
  6628. conn.close()
  6629. fake.goal_script = [("suspend",)]
  6630. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6631. or False, timeout=60, what="requeued run re-dispatches") is not None,
  6632. "the requeued run re-dispatches and re-parks")
  6633. fresh_session = open_session(run_task)
  6634. conn = db()
  6635. fresh_notice = conn.execute(
  6636. "select resume_notice from sessions where id = ?", (fresh_session,)
  6637. ).fetchone()[0]
  6638. conn.close()
  6639. check(fresh_notice is None,
  6640. "a requeue's fresh session carries no resume notice (empty panel state)")
  6641. print("== B1: Retry supervision revives a failed goal ==")
  6642. fake.push_results("failed", summary="the supervision collapsed (scripted)")
  6643. check(wait_for(lambda: goal_state(goal)["status"] == "failed" or False,
  6644. timeout=30, what="goal fails") is not None,
  6645. "the run's failure fails the goal")
  6646. check(wait_for(lambda: goal_state(goal).get("retry_run") is not None
  6647. or False, timeout=30, what="retry offered") is not None,
  6648. "a failed goal offers Retry supervision")
  6649. fake.goal_script = [("suspend",)]
  6650. act(auth, goal_state(goal)["retry_run"], {})
  6651. state = goal_state(goal)
  6652. check(state["status"] == "active",
  6653. "the retry revives supervision (goal back to active)")
  6654. check(task_state(auth, run_task)["status"] in ("queued", "assigned", "working",
  6655. "suspended", "blocked"),
  6656. "the retry re-offered the run task")
  6657. check(wait_for(lambda: task_state(auth, run_task)["status"] == "suspended"
  6658. or False, timeout=60, what="retried supervision parks") is not None,
  6659. "the retried supervision dispatches and parks again")
  6660. state = goal_state(goal)
  6661. check(any(e["kind"] == "system" and "Supervision retried" in e["text"]
  6662. for e in state["events"]),
  6663. "the narrative records the supervision retry (a system row)")
  6664. print("== B5 + C4: order, effective rules, capability badges ==")
  6665. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6666. markers = [
  6667. ('class="card goal-head"', "status head"),
  6668. ("Agent progress", "progress"),
  6669. ("Goal agent blocks", "attention blocks"),
  6670. ("<h3>Plan</h3>", "plan"),
  6671. ("<h3>Tasks</h3>", "tasks"),
  6672. ("Initial brief", "brief"),
  6673. ("Involved projects", "projects"),
  6674. ("<h3>Rules</h3>", "rules"),
  6675. ("Supervision narrative", "narrative"),
  6676. ("<h3>Comments</h3>", "comments"),
  6677. ("Goal agent runs", "runs"),
  6678. ]
  6679. positions = []
  6680. for marker, _ in markers:
  6681. check(marker in goal_page, "the goal page ships the %s section" % _)
  6682. positions.append(goal_page.index(marker))
  6683. check(positions == sorted(positions),
  6684. "the page reads status → progress → attention → plan → tasks → brief →"
  6685. " rules → narrative → comments → runs (in order)")
  6686. check("goal.current_activity" in goal_page and "Current activity" not in goal_page,
  6687. "the activity lives as ONE muted head line (the card is gone)")
  6688. check(".goal-page .card" in open(os.path.join(REPO, "src/pages/app.css")).read(),
  6689. "the stylesheet restores the goal page's card rhythm (padding regression)")
  6690. rules_state = slot_public(auth, "/rules", "rules")
  6691. act(auth, rules_state["create"], {"name": "goalui-primary", "body": "Primary rule"})
  6692. act(auth, rules_state["create"], {"name": "goalui-codev", "body": "Co-dev rule"})
  6693. act(auth, rules_state["create"], {"name": "goalui-ref", "body": "Reference rule"})
  6694. conn = db()
  6695. rule_ids = {name: int(conn.execute("select id from rules where name = ?",
  6696. (name,)).fetchone()[0])
  6697. for name in ("goalui-primary", "goalui-codev", "goalui-ref")}
  6698. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  6699. " values (?, 1, strftime('%s','now'))", (rule_ids["goalui-primary"],))
  6700. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  6701. " values ('goalui-codev-project', 'https://example.com/g.git',"
  6702. " 'main', strftime('%s','now'))")
  6703. codev_project = conn.execute(
  6704. "select id from projects where name = 'goalui-codev-project'").fetchone()[0]
  6705. conn.execute("insert into projects (name, git_url, default_branch, created_at)"
  6706. " values ('goalui-ref-project', 'https://example.com/r.git',"
  6707. " 'main', strftime('%s','now'))")
  6708. ref_project = conn.execute(
  6709. "select id from projects where name = 'goalui-ref-project'").fetchone()[0]
  6710. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  6711. " values (?, ?, strftime('%s','now'))",
  6712. (rule_ids["goalui-codev"], codev_project))
  6713. conn.execute("insert into rule_projects (rule_id, project_id, created_at)"
  6714. " values (?, ?, strftime('%s','now'))",
  6715. (rule_ids["goalui-ref"], ref_project))
  6716. conn.commit()
  6717. conn.close()
  6718. act(auth, goal_state(goal)["add_link"], {"linked_project_id": str(codev_project),
  6719. "relationship": "co-developed"})
  6720. act(auth, goal_state(goal)["add_link"], {"linked_project_id": str(ref_project),
  6721. "relationship": "reference"})
  6722. rule_names = [r["name"] for r in goal_state(goal)["rules"]]
  6723. check(rule_names == ["goalui-primary", "goalui-codev"],
  6724. "the Rules section lists the goal's effective set (primary then"
  6725. " co-developed; reference contributes nothing)")
  6726. act(auth, slot_public(auth, "/saddles", "saddles")["create_capability"],
  6727. {"name": "goalui-capability"})
  6728. conn = db()
  6729. capability = conn.execute(
  6730. "select id from capabilities where name = 'goalui-capability'"
  6731. ).fetchone()[0]
  6732. # The early redirect-fixture worker joins the goal (a fanned
  6733. # worker's shape) so its row carries the badge too.
  6734. conn.execute("update tasks set goal_id = ? where id = ?", (goal, worker))
  6735. conn.execute("insert into task_capabilities (task_id, capability_id)"
  6736. " values (?, ?)", (worker, capability))
  6737. conn.commit()
  6738. conn.close()
  6739. goal_worker = {"id": worker, "caps": None}
  6740. act(auth, slot_public(auth, "/tasks", "tasks")["create"], {
  6741. "project_id": "1", "title": "Goalui fanned worker", "priority": "4",
  6742. "description": "A worker the agent fanned out."})
  6743. conn = db()
  6744. fanned = conn.execute(
  6745. "select id from tasks where title = 'Goalui fanned worker'").fetchone()[0]
  6746. conn.execute("update tasks set goal_id = ? where id = ?", (goal, fanned))
  6747. conn.execute("insert into task_capabilities (task_id, capability_id)"
  6748. " values (?, ?)", (fanned, capability))
  6749. conn.commit()
  6750. conn.close()
  6751. rows = {int(t["id"]): t for t in goal_state(goal)["goal_tasks"]}
  6752. check(rows[fanned].get("capabilities") == ["goalui-capability"]
  6753. and rows[worker].get("capabilities") == ["goalui-capability"],
  6754. "task rows carry their required capability tags")
  6755. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6756. check('stm-for-capability-in="goal_task.capabilities"' in goal_page
  6757. and "badge-capability" in goal_page,
  6758. "the task rows render capability badges")
  6759. print("== B6: narrative weights — events full, comments footnote ==")
  6760. # An AGENT comment projects the narrative's comment event (human
  6761. # comments only thread) — pushed through the entries channel while
  6762. # parked, so the suspended state stays put.
  6763. fake.push_results("suspended", entries=[{
  6764. "id": 9001, "command": "saddle comment", "output": "An agent aside.",
  6765. "exit_code": 0, "type": "comment", "timestamp": "2026-09-12T00:00:00Z"}])
  6766. check(wait_for(lambda: any(e["kind"] == "comment"
  6767. for e in goal_state(goal)["events"]) or False,
  6768. timeout=15, what="comment event lands") is not None,
  6769. "an agent comment lands as a narrative event")
  6770. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6771. check("stm-attribute.class=\"'goal-event' + (event.kind == 'comment'"
  6772. " ? ' footnote' : '')\"" in goal_page.replace("\n", " ").replace(" ", " ")
  6773. or "'goal-event' + (event.kind == 'comment' ? ' footnote' : '')" in goal_page,
  6774. "the WHOLE comment event row carries .footnote (badge included)")
  6775. check("'badge badge-goal-' + event.kind" in goal_page,
  6776. "non-comment events keep their full-weight kind badges")
  6777. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6778. check(".goal-event.footnote" in css and ".footnote {" in css,
  6779. "the stylesheet ships the footnote row weight beside the utility")
  6780. print("== C2: system rows render distinctly on the ONE thread ==")
  6781. run_comments = task_state(auth, run_task)["comments"]
  6782. system_rows = [c for c in run_comments if c.get("is_system")]
  6783. check(system_rows and all(c["author"] == "system" for c in system_rows)
  6784. and not any(c.get("from_agent") for c in system_rows),
  6785. "the harness bookkeeping rows are authored 'system' (never agent)")
  6786. goal_thread = goal_state(goal)["comments"]
  6787. check(any(c.get("is_system") for c in goal_thread),
  6788. "the goal page reads the same thread (the system rows included)")
  6789. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6790. check(".comment.system" in css and ".system-label" in css,
  6791. "the stylesheet ships the distinct system-event styling")
  6792. page = http_get_page(auth, "/goals/%d" % goal)
  6793. check("comment.is_system" in page and "system-label" in page,
  6794. "the goal page renders system rows with the labelled muted style")
  6795. task_page = http_get_page(auth, "/tasks/%d" % worker)
  6796. check("comment.is_system" in task_page and "system-label" in task_page,
  6797. "the task page renders system rows with the same style")
  6798. print("== S5 U2: mechanical rows filtered from user-facing timelines ==")
  6799. # The daemon's mechanical system entries (the park notice, the
  6800. # restore footnote) ride the wire typed 'system': the raw terminal
  6801. # row STORES (session_commands), but no comment row, narrative
  6802. # event or dashboard timeline row is authored for them.
  6803. open_run = open_session(run_task)
  6804. mechanical = [
  6805. {"id": 9501, "command": "saddle suspend",
  6806. "output": "goal agent parked until an owned task completes or"
  6807. " fails; resume via /start resume_notice",
  6808. "exit_code": 0, "type": "system", "timestamp": "2026-09-12T00:00:00Z"},
  6809. {"id": 9502, "command": "harness resume",
  6810. "output": "[harness] session context restored — task resumed",
  6811. "exit_code": 0, "type": "system", "timestamp": "2026-09-12T00:00:01Z"},
  6812. ]
  6813. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6814. {"session_id": open_run, "state": "suspended",
  6815. "entries": mechanical})
  6816. check(status == 200, "the mechanical system entries push cleanly")
  6817. conn = db()
  6818. raw_rows = conn.execute(
  6819. "select count(*) from session_commands where session_id = ?"
  6820. " and type = 'system'", (open_run,)).fetchone()[0]
  6821. conn.close()
  6822. check(raw_rows >= 2,
  6823. "the raw terminal keeps the mechanical rows (typed entries store)")
  6824. check(all("parked until" not in c["body"]
  6825. and "session context restored" not in c["body"]
  6826. for c in task_state(auth, run_task)["comments"]),
  6827. "no mechanical comment row lands on the thread (U2)")
  6828. check(all("parked until" not in e["text"]
  6829. and "session context restored" not in e["text"]
  6830. for e in goal_state(goal)["events"]),
  6831. "no mechanical narrative event lands on the goal page (U2)")
  6832. dash_events = slot_public(auth, "/", "dashboard")["activity"]
  6833. check(all("parked until" not in e["text"]
  6834. and "session context restored" not in e["text"]
  6835. for e in dash_events),
  6836. "no mechanical row lands on the dashboard timeline (U2)")
  6837. print("== C4: head line, answered-blocks expander, footnote comments ==")
  6838. state = goal_state(goal)
  6839. check(state["current_activity"] == "parked awaiting its tasks' terminal transitions",
  6840. "a suspended run folds into the one muted head line")
  6841. check(len(state.get("answered_blocks") or []) >= 2
  6842. and len(state.get("open_blocks") or []) == 0,
  6843. "the historic answered blocks expose as their own vector (open ones empty)")
  6844. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6845. check("Answered blocks (" in goal_page and "comment-meta" in goal_page,
  6846. "the answered blocks and the footnote comment meta ship in the markup")
  6847. check("timeless note for a future reader" in goal_page,
  6848. "the composer hint states the timeless-comment rule")
  6849. css = open(os.path.join(REPO, "src/pages/app.css")).read()
  6850. check(".goal-page .card { margin-bottom" in css and ".comment-meta" in css,
  6851. "the stylesheet ships the card rhythm and the comment footnote meta")
  6852. print("== C1: one review block per verdict path (F6) ==")
  6853. # The daemon's honest round pushes the ENTRY and the STATE
  6854. # together — the done pair must raise exactly ONE completion
  6855. # block, and a redelivered pair nothing more.
  6856. fake.goal_script = [("done", "# Completion\n\nOne block only.")]
  6857. conn = db()
  6858. conn.execute("insert into tasks (project_id, goal_id, kind, title, status,"
  6859. " priority, completed_at, created_at) values (1, ?, 'task',"
  6860. " 'Warmup', 'done', 5,"
  6861. " strftime('%s','now'),"
  6862. " strftime('%s','now','-30 seconds'))", (goal,))
  6863. conn.commit()
  6864. conn.close()
  6865. check(wait_for(lambda: goal_state(goal)["status"] == "completion_review" or False,
  6866. timeout=60, what="goalui completion review opens") is not None,
  6867. "the scripted done round enters completion review")
  6868. def completion_block_count():
  6869. conn = db()
  6870. try:
  6871. return conn.execute(
  6872. "select count(*) from task_blocks where task_id = ?"
  6873. " and type = 'completion'", (run_task,)).fetchone()[0]
  6874. finally:
  6875. conn.close()
  6876. check(completion_block_count() == 1,
  6877. "the done state raises exactly ONE completion block")
  6878. # Plan 16 S5 (U1): the verdict-shaped block renders the rich review
  6879. # form — explicit accept/reject affordances with the free-text
  6880. # feedback path, never a free-text-only verdict.
  6881. goal_page = http_get_page(auth, "/goals/%d" % goal)
  6882. check("Accept goal" in goal_page and "Reject with feedback" in goal_page
  6883. and 'name="feedback"' in goal_page,
  6884. "the completion review presents explicit accept/reject + free-text feedback (U1)")
  6885. # The burst shape: the done ENTRY and the done STATE in one push
  6886. # (fresh entry ids), then the whole pair redelivered — the
  6887. # pending-report idempotency leaves the one row alone.
  6888. conn = db()
  6889. burst_session = conn.execute(
  6890. "select id from sessions where task_id = ? and ended_at is null",
  6891. (run_task,)).fetchone()[0]
  6892. conn.close()
  6893. done_pair = [{"id": 9401, "command": "saddle done",
  6894. "output": "# Completion\n\nOne block only.", "exit_code": 0,
  6895. "type": "done", "timestamp": "2026-09-12T00:00:00Z"}]
  6896. status, _ = saddle_api("POST", "/api/saddle/results", fake_token,
  6897. {"session_id": burst_session, "state": "done",
  6898. "entries": done_pair,
  6899. "summary": "# Completion\n\nOne block only."})
  6900. check(status == 200 and completion_block_count() == 1,
  6901. "the done entry + state pair raises nothing more (one block, ever)")
  6902. state = goal_state(goal)
  6903. act(auth, state["completion_pending_block"]["answer_action"],
  6904. {"verdict": "accept"})
  6905. check(wait_for(lambda: goal_state(goal)["status"] == "complete" or False,
  6906. timeout=30, what="goalui goal completes") is not None,
  6907. "accepting the completion completes the goal")
  6908. check(completion_block_count() == 1,
  6909. "the accept path leaves exactly one review-kind block behind")
  6910. conn = db()
  6911. stragglers = conn.execute(
  6912. "select count(*) from task_blocks where task_id = ? and answer is null",
  6913. (run_task,)).fetchone()[0]
  6914. conn.close()
  6915. check(stragglers == 0,
  6916. "no unanswered straggler rows survive the completion")
  6917. print("== S2: server-owned verdicts + the container-resolved reject ==")
  6918. # A fresh goal drives the verdict paths the goal page's forms now
  6919. # use: verdict markers for accept, raw `feedback` for reject, and
  6920. # the block resolution living in the review CONTAINER (not
  6921. # goal.plan_pending_block — the diagnosed completion-review bug).
  6922. fake.goal_script = [("plan", "# S2 plan\n\nOne step")]
  6923. act(auth, slot_public(auth, "/goals", "goals")["create"], {
  6924. "project_id": "1", "title": "S2 verdict goal",
  6925. "brief": "Covers the plan-16 S2 verdict paths.",
  6926. "branch_name": "goal/s2-verdicts"})
  6927. conn = db()
  6928. s2_goal = int(conn.execute(
  6929. "select id from goals where title = 'S2 verdict goal'").fetchone()[0])
  6930. conn.close()
  6931. act(auth, goal_state(s2_goal)["start"], {})
  6932. check(wait_for(lambda: goal_state(s2_goal)["status"] == "plan_review" or False,
  6933. timeout=90, what="S2 goal enters plan review") is not None,
  6934. "the S2 goal enters plan review")
  6935. s2_state = goal_state(s2_goal)
  6936. s2_pending = s2_state["plan_pending_block"]
  6937. # (1) A remark-less, text-less rejection is refused: the action
  6938. # errors and the block keeps waiting.
  6939. refusal = act(auth, s2_pending["answer_action"], {"feedback": " "})
  6940. check(any(d.get("type") == "notify" and d.get("kind") == "error"
  6941. and "answer is required" in (d.get("message") or "").lower()
  6942. for d in refusal),
  6943. "a remark-less, text-less rejection is refused with an error")
  6944. conn = db()
  6945. s2_still_open = conn.execute(
  6946. "select answer from task_blocks where id = ?",
  6947. (s2_pending["id"],)).fetchone()[0]
  6948. conn.close()
  6949. check(s2_still_open is None,
  6950. "the refused rejection leaves the block unanswered")
  6951. # (3) The goal page template ships no verdict constants and its
  6952. # script resolves the review block from ANY [data-plan-review]
  6953. # container via the open-blocks list (the completion-review fix).
  6954. # Fetched while the review is open so the accept form renders.
  6955. s2_page = http_get_page(auth, "/goals/%d" % s2_goal)
  6956. check("Plan approved. Proceed with implementation." not in s2_page
  6957. and "Review approved. Continue with the task." not in s2_page,
  6958. "the goal page ships no verdict constants (server-owned wording)")
  6959. check('name="verdict" value="accept"' in s2_page,
  6960. "the goal page's accept forms post the verdict marker")
  6961. check("resolveReviewBlock" in s2_page and "goal.open_blocks" in s2_page,
  6962. "the reject flow resolves its block from the open-blocks list (container-keyed)")
  6963. check("statum.act(block.answer_action, { feedback: feedback })" in s2_page,
  6964. "the reject flow posts raw feedback (the server wraps the prefix)")
  6965. check("extraText.length === 0" in s2_page,
  6966. "a remark-less rejection with textarea content is allowed (S2)")
  6967. # (2) The goal page's reject rides `feedback` (the client composes
  6968. # the numbered-remarks body) and the SERVER wraps it with the plan
  6969. # prefix — byte-identical to the historical client-built answer.
  6970. act(auth, s2_pending["answer_action"],
  6971. {"feedback": "> ## One step\n\n1. Tighten it\n\n2. Name the owner"})
  6972. conn = db()
  6973. s2_wrapped = conn.execute(
  6974. "select answer from task_blocks where id = ?",
  6975. (s2_pending["id"],)).fetchone()[0]
  6976. conn.close()
  6977. check(s2_wrapped
  6978. == "Plan feedback received:\n\n"
  6979. "> ## One step\n\n1. Tighten it\n\n2. Name the owner",
  6980. "the plan rejection wraps the client-shaped body with the stable prefix (%r)"
  6981. % s2_wrapped)
  6982. check(goal_state(s2_goal)["status"] == "planning",
  6983. "the feedback rejection returns the agent to planning")
  6984. BUNDLES_ORDER = ("pages", "dispatch", "subtasks", "lineage",
  6985. "allocation", "lifecycle", "answers", "push", "goals",
  6986. "replay", "goalui")
  6987. def run_bundle(name):
  6988. """Runs one shard to completion; returns a failure count."""
  6989. started = time.monotonic()
  6990. ctx = start_bundle(name)
  6991. runner = globals()["bundle_" + name]
  6992. try:
  6993. runner(ctx)
  6994. finally:
  6995. # Exit-code diagnostic: distinguishes a crashed app (negative
  6996. # returncode, e.g. -11 SIGSEGV) from a clean shutdown. When
  6997. # tearing down mid-exception, also capture the still-alive
  6998. # app's stacks before killing it (a wedged-but-alive server
  6999. # otherwise leaves no evidence).
  7000. print("(app returncode at teardown: %s)" % ctx.app.poll())
  7001. if ctx.app.poll() is None and sys.exc_info()[0] is not None:
  7002. dump_app_stacks(ctx.app.pid)
  7003. ctx.fake.kill()
  7004. try:
  7005. ctx.app.terminate()
  7006. try:
  7007. ctx.app.wait(timeout=5)
  7008. except subprocess.TimeoutExpired:
  7009. ctx.app.kill()
  7010. check(ctx.app.poll() in (0, -15),
  7011. "bundle %s app shut down cleanly (exit %s)"
  7012. % (name, ctx.app.poll()))
  7013. except OSError:
  7014. pass
  7015. print("%d passed, %d failed" % (passes, failures))
  7016. print("[bundle %s] %.1fs" % (name, time.monotonic() - started))
  7017. return failures
  7018. def run_all_parallel():
  7019. """The default meson entry: one subprocess per bundle (each with its
  7020. own app, daemons and database), verdicts aggregated into one exit
  7021. code and one combined check-count summary."""
  7022. base = os.environ.get("WEBSTACK_WORK", "/tmp/kilo/webstack-e2e")
  7023. log_dir = os.path.join(os.path.dirname(base) or "/tmp/kilo",
  7024. "webstack-shards")
  7025. os.makedirs(log_dir, exist_ok=True)
  7026. procs = {}
  7027. started = time.monotonic()
  7028. for name in BUNDLES_ORDER:
  7029. out_path = os.path.join(log_dir, "bundle-%s.log" % name)
  7030. handle = open(out_path, "w")
  7031. procs[name] = (subprocess.Popen(
  7032. [sys.executable, "-u", os.path.abspath(__file__), APP,
  7033. "--bundle", name],
  7034. stdout=handle, stderr=subprocess.STDOUT), handle, out_path)
  7035. total_pass = total_fail = 0
  7036. broken = []
  7037. for name, (proc, handle, out_path) in procs.items():
  7038. try:
  7039. proc.wait(timeout=SHARD_TIMEOUT_S)
  7040. except subprocess.TimeoutExpired:
  7041. proc.kill()
  7042. proc.wait()
  7043. handle.close()
  7044. text = open(out_path).read()
  7045. match = re.search(r"(\d+) passed, (\d+) failed", text)
  7046. took = re.search(r"\[bundle %s\] ([0-9.]+)s" % name, text)
  7047. bundle_pass = int(match.group(1)) if match else 0
  7048. bundle_fail = int(match.group(2)) if match else -1
  7049. total_pass += max(bundle_pass, 0)
  7050. total_fail += max(bundle_fail, 0)
  7051. status = "ok"
  7052. if proc.returncode != 0 or bundle_fail != 0 or match is None:
  7053. status = "BROKEN (exit %s)" % proc.returncode
  7054. broken.append(name)
  7055. print("[shard %-10s] %6ss %3d passed %3d failed %s"
  7056. % (name, took.group(1) if took else "?",
  7057. bundle_pass, bundle_fail, status))
  7058. if status != "ok":
  7059. tail = "\n".join(text.rstrip().split("\n")[-60:])
  7060. print("--- web-stack/%s tail (full log: %s) ---" % (name, out_path))
  7061. print(tail)
  7062. print("--- end web-stack/%s tail ---" % name)
  7063. print("shards wall: %.1fs (logs under %s)" % (time.monotonic() - started, log_dir))
  7064. print("ALL SHARDS: %d passed, %d failed%s"
  7065. % (total_pass, total_fail,
  7066. "" if not broken else " BROKEN: " + ", ".join(broken)))
  7067. return 1 if broken or total_fail else 0
  7068. def main():
  7069. if not os.path.exists(APP):
  7070. raise SystemExit("app binary not found at %s (build first)" % APP)
  7071. argv = sys.argv[2:]
  7072. if "--bundle" in argv:
  7073. sys.exit(1 if run_bundle(argv[argv.index("--bundle") + 1]) else 0)
  7074. if os.environ.get("WEBSTACK_SEQUENTIAL"):
  7075. # Debug path: every bundle in-process, one after another.
  7076. for name in BUNDLES_ORDER:
  7077. if run_bundle(name):
  7078. return 1
  7079. return 0
  7080. return run_all_parallel()
  7081. if __name__ == "__main__":
  7082. sys.exit(main())